-
Notifications
You must be signed in to change notification settings - Fork 524
Expand file tree
/
Copy pathrm.go
More file actions
322 lines (264 loc) · 7.75 KB
/
rm.go
File metadata and controls
322 lines (264 loc) · 7.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
package commands
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"regexp"
"slices"
"strings"
"github.com/89luca89/distrobox/internal/userenv"
"github.com/89luca89/distrobox/pkg/config"
"github.com/89luca89/distrobox/pkg/containermanager"
"github.com/89luca89/distrobox/pkg/ui"
)
type RmResult struct {
Containers []containermanager.Container
}
type RmCommand struct {
cfg *config.Values
containerManager containermanager.ContainerManager
listCmd *ListCommand
generateEntryCmd *GenerateEntryCommand
prompter *ui.Prompter
}
type RmOptions struct {
NoTTY bool
Force bool
All bool
RemoveHome bool
ContainerNames []string
}
func NewRmCommand(
cfg *config.Values,
cm containermanager.ContainerManager,
prompter *ui.Prompter,
) *RmCommand {
listCmd := NewListCommand(cfg, cm)
generateEntryCmd := NewGenerateEntryCommand(cfg, listCmd)
return &RmCommand{
cfg: cfg,
containerManager: cm,
listCmd: listCmd,
generateEntryCmd: generateEntryCmd,
prompter: prompter,
}
}
func removeValue(slice []string, valueToRemove string) []string {
for i, value := range slice {
if value == valueToRemove {
return slices.Delete(slice, i, i+1)
}
}
return slice
}
func (c *RmCommand) Execute(ctx context.Context, options RmOptions) (*RmResult, error) {
if !options.NoTTY && c.prompter == nil {
return nil, errors.New("prompter is required for interactive mode")
}
var validContainerName = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_.-]*$`) // podman regex
for _, containerName := range options.ContainerNames {
if !validContainerName.MatchString(containerName) {
return nil, fmt.Errorf("invalid container name '%s'", containerName)
}
}
listResult, err := c.listCmd.Execute(ctx)
if err != nil {
return nil, fmt.Errorf("failed while listing containers: %w", err)
}
explicitlyRequested := options.ContainerNames
distroboxesToRemove := getContainersToRemove(listResult.Containers, options.ContainerNames, options.All)
userEnv := userenv.LoadUserEnvironment(ctx)
userHome := userEnv.Home
var removedDistroboxes []containermanager.Container
for _, currentDistrobox := range distroboxesToRemove {
explicitlyRequested = removeValue(explicitlyRequested, currentDistrobox.Name)
err := c.removeContainer(ctx, currentDistrobox, options.Force, options.NoTTY, userHome)
if err != nil {
//nolint:forbidigo // waiting for the logger implementation
fmt.Printf("error deleting %s: %s", currentDistrobox.Name, err)
}
removedDistroboxes = append(removedDistroboxes, currentDistrobox)
}
// Clean up exported files of all remaining explicitly requested distroboxes,
// even if the container doesn't exist anymore
for _, containerName := range explicitlyRequested {
c.cleanup(ctx, userHome, containerName)
}
return &RmResult{Containers: removedDistroboxes}, nil
}
func (c *RmCommand) removeContainer(
ctx context.Context,
container containermanager.Container,
force bool,
noTTY bool,
userHome string,
) error {
forceRemove := force
if !forceRemove && !noTTY && strings.Contains(container.Status, "Up") {
if c.prompter.Prompt("Container is running, do you want to force delete it?", false) {
forceRemove = true
} else {
return nil
}
}
inspectOutput, err := c.containerManager.InspectContainer(ctx, container.Name)
if err != nil {
return fmt.Errorf("error inspecting the container: %w", err)
}
removeHome := false
if !noTTY && inspectOutput.ContainerHome != userHome {
question := fmt.Sprintf(
"Do you really want to remove custom home of container %s (%s)?",
container.Name,
inspectOutput.ContainerHome,
)
answer := c.prompter.Prompt(question, false)
removeHome = answer
}
cmOptions := containermanager.RmOptions{
Force: forceRemove,
RemoveHome: removeHome,
ContainerHome: inspectOutput.ContainerHome,
}
err = c.containerManager.Remove(ctx, container.Name, cmOptions)
if err != nil {
return fmt.Errorf("failed to remove container: %w", err)
}
c.cleanup(ctx, userHome, container.Name)
return nil
}
func (c *RmCommand) cleanup(ctx context.Context, userHome, containerName string) {
bins := findExportedBinaries(userHome, containerName)
desktopApps := findExportedDesktopApps(userHome, containerName)
toDelete := slices.Concat(bins, desktopApps)
for _, path := range toDelete {
if err := os.Remove(path); err != nil {
//nolint:forbidigo // FIXME: use logger instead of fmt.Printf when available
fmt.Printf("warning: failed to remove file '%s': %s\n", path, err)
}
}
err := c.generateEntryCmd.Execute(
ctx,
&GenerateEntryOptions{
ContainerName: containerName,
Delete: true,
// TODO: handle verbose
Verbose: false,
},
)
if err != nil {
//nolint:forbidigo // FIXME: use logger instead of fmt.Printf when available
fmt.Printf("warning: failed to remove desktop entry for container '%s': %s\n", containerName, err)
}
}
func getContainersToRemove(
containers []containermanager.Container,
names []string,
all bool,
) []containermanager.Container {
if all {
return containers
}
var filtered []containermanager.Container
for _, container := range containers {
if slices.ContainsFunc(names, func(name string) bool {
return container.Name == name
}) {
filtered = append(filtered, container)
}
}
return filtered
}
func findExportedBinaries(userHome, containerName string) []string {
binDir := filepath.Join(userHome, ".local", "bin")
entries, err := os.ReadDir(binDir)
if err != nil {
return nil
}
var files []string
for _, entry := range entries {
if entry.IsDir() {
continue
}
path := filepath.Join(binDir, entry.Name())
data, err := os.ReadFile(path)
if err != nil {
continue
}
content := string(data)
if strings.Contains(content, "# distrobox_binary") &&
strings.Contains(content, "# name: "+containerName+"\n") {
absPath, err := filepath.Abs(path)
if err != nil {
continue
}
files = append(files, absPath)
}
}
return files
}
func findExportedDesktopApps(userHome, containerName string) []string {
appsPattern := filepath.Join(userHome, ".local", "share", "applications", containerName+"*")
matches, err := filepath.Glob(appsPattern)
if err != nil {
//nolint:forbidigo // FIXME: use logger instead of fmt.Printf when available
fmt.Printf("warning: failed to glob desktop apps: %s\n", err)
return []string{}
}
var files []string
for _, desktopFile := range matches {
iconValue, ok := parseDesktopExport(desktopFile, containerName)
if !ok {
continue
}
absDesktop, err := filepath.Abs(desktopFile)
if err != nil {
continue
}
files = append(files, absDesktop)
if iconValue != "" {
files = append(files, findIconFiles(userHome, iconValue)...)
}
}
return files
}
func parseDesktopExport(desktopFile, containerName string) (string, bool) {
data, err := os.ReadFile(desktopFile)
if err != nil {
return "", false
}
hasExecMatch := false
var iconValue string
for _, line := range strings.Split(string(data), "\n") {
if strings.HasPrefix(line, "Exec=") && strings.Contains(line, containerName+" ") {
hasExecMatch = true
}
if strings.HasPrefix(line, "Icon=") {
iconValue = strings.TrimPrefix(line, "Icon=")
}
}
return iconValue, hasExecMatch
}
func findIconFiles(userHome, iconName string) []string {
iconsDir := filepath.Join(userHome, ".local", "share", "icons")
iconPrefix := iconName + "."
var files []string
_ = filepath.WalkDir(iconsDir, func(path string, d os.DirEntry, err error) error {
if err != nil {
return nil //nolint:nilerr // skip unreadable directories
}
if d.IsDir() {
return nil
}
if strings.HasPrefix(d.Name(), iconPrefix) {
absIcon, err := filepath.Abs(path)
if err == nil {
files = append(files, absIcon)
}
}
return nil
})
return files
}