-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
497 lines (450 loc) · 12.6 KB
/
main.go
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
// Package main does the thing
package main
import (
"fmt"
"io/fs"
"math"
"os"
"path/filepath"
"slices"
"time"
"git.burning.moe/celediel/gt/internal/filemode"
"git.burning.moe/celediel/gt/internal/files"
"git.burning.moe/celediel/gt/internal/filter"
"git.burning.moe/celediel/gt/internal/interactive"
"git.burning.moe/celediel/gt/internal/interactive/modes"
"golang.org/x/term"
"github.com/adrg/xdg"
"github.com/charmbracelet/log"
"github.com/urfave/cli/v2"
)
const (
appname string = "gt"
appsubtitle string = "xdg trash cli"
appversion string = "v0.0.3"
appdesc string = `A small command line program to interface with the
Freedesktop.org / XDG trash specification.
Run with no command or filename(s) to start interactive mode.
See gt(1) for more information.`
executePerm = fs.FileMode(0755)
)
var (
fltr *filter.Filter
loglvl string
onArg, beforeArg, afterArg string
globArg, patternArg string
unGlobArg, unPatternArg string
modeArg, minArg, maxArg string
filesOnlyArg, dirsOnlyArg bool
hiddenArg, noInterArg bool
askconfirm, all bool
workdir, ogdir cli.Path
recursive bool
isTerminal bool
beforeAll = func(_ *cli.Context) error {
if term.IsTerminal(int(os.Stdout.Fd())) && term.IsTerminal(int(os.Stdin.Fd())) {
isTerminal = true
}
// setup log
log.SetReportTimestamp(true)
log.SetTimeFormat(time.TimeOnly)
if level, err := log.ParseLevel(loglvl); err == nil {
log.SetLevel(level)
// Some extra info for debug level
if log.GetLevel() == log.DebugLevel {
log.SetReportCaller(true)
}
} else {
log.Errorf("unknown log level '%s' (possible values: debug, info, warn, error, fatal, default: warn)", loglvl)
}
if !isTerminal {
log.SetLevel(math.MaxInt32)
}
// ensure personal trash directories exist
homeTrash := filepath.Join(xdg.DataHome, "Trash")
if _, e := os.Lstat(filepath.Join(homeTrash, "info")); os.IsNotExist(e) {
if err := os.MkdirAll(filepath.Join(homeTrash, "info"), executePerm); err != nil {
return err
}
}
if _, e := os.Lstat(filepath.Join(homeTrash, "files")); os.IsNotExist(e) {
if err := os.MkdirAll(filepath.Join(homeTrash, "files"), executePerm); err != nil {
return err
}
}
return nil
}
// action launches interactive mode if run without args, or trashes files as args.
action = func(ctx *cli.Context) error {
var (
err error
)
if fltr == nil {
md, e := filemode.Parse(modeArg)
if e != nil {
return e
}
fltr, err = filter.New(onArg, beforeArg, afterArg, globArg, patternArg, unGlobArg, unPatternArg, filesOnlyArg, dirsOnlyArg, false, minArg, maxArg, md)
}
if err != nil {
return err
}
if len(ctx.Args().Slice()) == 0 {
// no ags, so do interactive mode
var (
infiles files.Files
selected files.Files
mode modes.Mode
err error
)
infiles = files.FindInAllTrashes(ogdir, fltr)
if len(infiles) <= 0 {
var msg string
if fltr.Blank() {
msg = "trash is empty"
} else {
msg = "no files to show"
}
fmt.Fprintln(os.Stdout, msg)
return nil
}
if !isTerminal {
fmt.Fprint(os.Stdout, infiles.String())
return nil
}
selected, mode, err = interactive.Select(infiles, false, false, workdir, modes.Interactive)
if err != nil {
return err
}
switch mode {
case modes.Cleaning:
for _, file := range selected {
log.Debugf("gonna clean %s", file.Name())
}
if err := files.ConfirmClean(askconfirm, selected); err != nil {
return err
}
case modes.Restoring:
for _, file := range selected {
log.Debugf("gonna restore %s", file.Name())
}
if err := files.ConfirmRestore(askconfirm, selected); err != nil {
return err
}
case modes.Interactive:
return nil
default:
return fmt.Errorf("got bad mode %s", mode)
}
return nil
}
// args, so try to trash files
var filesToTrash files.Files
for _, arg := range ctx.Args().Slice() {
file, e := files.NewDisk(arg)
if e != nil {
log.Errorf("cannot trash '%s': No such file or directory", arg)
continue
}
filesToTrash = append(filesToTrash, file)
}
return files.ConfirmTrash(askconfirm, filesToTrash)
}
beforeCommands = func(ctx *cli.Context) (err error) {
// setup filter
if fltr == nil {
md, e := filemode.Parse(modeArg)
if e != nil {
return e
}
fltr, err = filter.New(onArg, beforeArg, afterArg, globArg, patternArg, unGlobArg, unPatternArg, filesOnlyArg, dirsOnlyArg, false, minArg, maxArg, md, ctx.Args().Slice()...)
}
log.Debugf("filter: %s", fltr.String())
return
}
beforeTrash = func(_ *cli.Context) (err error) {
if fltr == nil {
md, e := filemode.Parse(modeArg)
if e != nil {
return e
}
fltr, err = filter.New(onArg, beforeArg, afterArg, globArg, patternArg, unGlobArg, unPatternArg, filesOnlyArg, dirsOnlyArg, !hiddenArg, minArg, maxArg, md)
}
log.Debugf("filter: %s", fltr.String())
return
}
after = func(_ *cli.Context) error {
files.WriteDirectorySizes()
return nil
}
doTrash = &cli.Command{
Name: "trash",
Aliases: []string{"tr"},
Usage: "Trash a file or files",
UsageText: "[command options] [filename(s)]",
Flags: slices.Concat(trashingFlags, filterFlags),
Before: beforeTrash,
Action: func(ctx *cli.Context) error {
var filesToTrash files.Files
for _, arg := range ctx.Args().Slice() {
file, e := files.NewDisk(arg)
if e != nil || workdir != "" {
log.Debugf("%s wasn't really a file", arg)
fltr.AddFileName(arg)
continue
}
filesToTrash = append(filesToTrash, file)
}
// if none of the args were files, then find files based on filter
if len(filesToTrash) == 0 {
fls := files.FindDisk(workdir, recursive, fltr)
if len(fls) == 0 {
fmt.Fprintln(os.Stdout, "no files to trash")
return nil
}
filesToTrash = append(filesToTrash, fls...)
}
selected, _, err := interactive.Select(filesToTrash, false, false, workdir, modes.Trashing)
if err != nil {
return err
}
if len(selected) <= 0 {
return nil
}
return files.ConfirmTrash(askconfirm, selected)
},
}
doList = &cli.Command{
Name: "list",
Aliases: []string{"ls"},
Usage: "List trashed files",
Flags: slices.Concat(listFlags, trashedFlags, filterFlags),
Before: beforeCommands,
Action: func(_ *cli.Context) error {
fls := files.FindInAllTrashes(ogdir, fltr)
var msg string
log.Debugf("filter '%s' is blank? %t in %s", fltr, fltr.Blank(), ogdir)
if fltr.Blank() && ogdir == "" {
msg = "trash is empty"
} else {
msg = "no files to show"
}
if len(fls) == 0 {
fmt.Fprintln(os.Stdout, msg)
return nil
}
if !isTerminal {
fmt.Fprint(os.Stdout, fls.String())
return nil
}
return interactive.Show(fls, noInterArg, workdir)
},
}
doRestore = &cli.Command{
Name: "restore",
Aliases: []string{"re"},
Usage: "Restore a trashed file or files",
UsageText: "[command options] [filename(s)]",
Flags: slices.Concat(cleanRestoreFlags, trashedFlags, filterFlags),
Before: beforeCommands,
Action: func(_ *cli.Context) error {
fls := files.FindInAllTrashes(ogdir, fltr)
if len(fls) == 0 {
fmt.Fprintln(os.Stdout, "no files to restore")
return nil
}
selected, _, err := interactive.Select(fls, all, all, workdir, modes.Restoring)
if err != nil {
return err
}
if len(selected) <= 0 {
return nil
}
return files.ConfirmRestore(askconfirm || all, selected)
},
}
doClean = &cli.Command{
Name: "clean",
Aliases: []string{"cl"},
Usage: "Clean files from trash",
UsageText: "[command options] [filename(s)]",
Flags: slices.Concat(cleanRestoreFlags, trashedFlags, filterFlags),
Before: beforeCommands,
Action: func(_ *cli.Context) error {
fls := files.FindInAllTrashes(ogdir, fltr)
if len(fls) == 0 {
fmt.Fprintln(os.Stdout, "no files to clean")
return nil
}
selected, _, err := interactive.Select(fls, all, all, workdir, modes.Cleaning)
if err != nil {
return err
}
if len(selected) <= 0 {
return nil
}
return files.ConfirmClean(askconfirm, selected)
},
}
globalFlags = []cli.Flag{
&cli.StringFlag{
Name: "log",
Usage: "set log level",
Value: "warn",
Aliases: []string{"l"},
Destination: &loglvl,
},
&cli.BoolFlag{
Name: "confirm",
Usage: "ask for confirmation before executing any action",
Value: false,
Aliases: []string{"c"},
DisableDefaultText: true,
Destination: &askconfirm,
},
}
filterFlags = []cli.Flag{
&cli.StringFlag{
Name: "match",
Usage: "operate on files matching regex `PATTERN`",
Aliases: []string{"m"},
Destination: &patternArg,
},
&cli.StringFlag{
Name: "glob",
Usage: "operate on files matching `GLOB`",
Aliases: []string{"g"},
Destination: &globArg,
},
&cli.StringFlag{
Name: "not-match",
Usage: "operate on files not matching regex `PATTERN`",
Aliases: []string{"M"},
Destination: &unPatternArg,
},
&cli.StringFlag{
Name: "not-glob",
Usage: "operate on files not matching `GLOB`",
Aliases: []string{"G"},
Destination: &unGlobArg,
},
&cli.StringFlag{
Name: "on",
Usage: "operate on files modified on `DATE`",
Aliases: []string{"O"},
Destination: &onArg,
},
&cli.StringFlag{
Name: "after",
Usage: "operate on files modified before `DATE`",
Aliases: []string{"A"},
Destination: &afterArg,
},
&cli.StringFlag{
Name: "before",
Usage: "operate on files modified after `DATE`",
Aliases: []string{"B"},
Destination: &beforeArg,
},
&cli.BoolFlag{
Name: "files-only",
Usage: "operate on files only",
Aliases: []string{"F"},
DisableDefaultText: true,
Destination: &filesOnlyArg,
},
&cli.BoolFlag{
Name: "dirs-only",
Usage: "operate on directories only",
Aliases: []string{"D"},
DisableDefaultText: true,
Destination: &dirsOnlyArg,
},
&cli.StringFlag{
Name: "min-size",
Usage: "operate on files larger than `SIZE`",
Aliases: []string{"N"},
Destination: &minArg,
},
&cli.StringFlag{
Name: "max-size",
Usage: "operate on files smaller than `SIZE`",
Aliases: []string{"X"},
Destination: &maxArg,
},
&cli.StringFlag{
Name: "mode",
Usage: "operate on files matching mode `MODE`",
Aliases: []string{"x"},
Destination: &modeArg,
},
}
trashingFlags = []cli.Flag{
&cli.BoolFlag{
Name: "recursive",
Usage: "operate on files recursively",
Aliases: []string{"r"},
Destination: &recursive,
Value: false,
DisableDefaultText: true,
},
&cli.PathFlag{
Name: "work-dir",
Usage: "operate on files in this `DIRECTORY`",
Aliases: []string{"w"},
Destination: &workdir,
},
&cli.BoolFlag{
Name: "hidden",
Usage: "operate on hidden files",
Aliases: []string{"H"},
DisableDefaultText: true,
Destination: &hiddenArg,
},
}
trashedFlags = []cli.Flag{
&cli.PathFlag{
Name: "original-path",
Usage: "operate on files trashed from this `DIRECTORY`",
Aliases: []string{"o"},
Destination: &ogdir,
},
}
listFlags = []cli.Flag{
&cli.BoolFlag{
Name: "non-interactive",
Usage: "list files and quit",
Aliases: []string{"n"},
Destination: &noInterArg,
DisableDefaultText: true,
},
}
cleanRestoreFlags = []cli.Flag{
&cli.BoolFlag{
Name: "all",
Usage: "operate on all files in trash",
Aliases: []string{"a"},
Destination: &all,
DisableDefaultText: true,
},
}
)
func main() {
app := &cli.App{
Name: appname,
Usage: appsubtitle,
Version: appversion,
Before: beforeAll,
After: after,
Action: action,
Commands: []*cli.Command{doTrash, doList, doRestore, doClean},
Flags: globalFlags,
UsageText: appname + " [global options] [command [command options] / filename(s)]",
Description: appdesc,
EnableBashCompletion: true,
UseShortOptionHandling: true,
}
if err := app.Run(os.Args); err != nil {
log.Fatal(err)
}
}