-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.go
129 lines (95 loc) · 2.04 KB
/
app.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
package cli
import (
"context"
"flag"
"fmt"
"io"
"io/fs"
"os"
"sync"
"github.com/markbates/bostongo"
"github.com/markbates/iox"
)
// App is the main application struct for the walker command.
type App struct {
// IO to be used by the app
iox.IO
// Cab is the file system to walk. Defaults to os.DirFS(pwd).
Cab fs.FS
mu sync.RWMutex
}
// snippet: main
// Main is the main entry point for the walker command.
func (a *App) Main(ctx context.Context, pwd string, args []string) error {
if a == nil {
return fmt.Errorf("nil app")
}
if ctx == nil {
ctx = context.Background()
}
wk := bostongo.Walker{}
flags := a.flags(&wk)
err := flags.Parse(args)
if err != nil {
return err
}
a.mu.RLock()
cab := a.Cab
oi := a.IO
a.mu.RUnlock()
args = flags.Args()
if len(args) > 0 {
pwd = args[0]
}
if cab == nil {
cab = os.DirFS(pwd)
}
sctx, cause := context.WithCancelCause(ctx)
defer cause(nil)
// launch as a goroutine so if it takes too
// long we can cancel the command.
go func() {
err := wk.Walk(cab, oi.Stdout())
cause(err)
}()
<-sctx.Done()
err = context.Cause(sctx)
if err != nil && err != context.Canceled {
return err
}
return nil
}
// snippet: main
// SetIO sets the IO to be used by the app.
func (a *App) SetIO(oi iox.IO) {
if a == nil {
return
}
a.mu.Lock()
defer a.mu.Unlock()
a.IO = oi
}
// Print prints the usage for the walker command.
func (a *App) Print(w io.Writer) error {
if a == nil {
return fmt.Errorf("nil app")
}
if w == nil {
w = a.Stdout()
}
flags := a.flags(&bostongo.Walker{})
flags.SetOutput(w)
flags.Usage()
return nil
}
// Describe returns a description of the walker command.
func (a *App) Describe() string {
return "walks a path and prints the files and directories"
}
func (a *App) flags(wk *bostongo.Walker) *flag.FlagSet {
flags := flag.NewFlagSet("walker", flag.ContinueOnError)
flags.SetOutput(a.Stderr())
flags.BoolVar(&wk.PrintDirs, "dirs", false, "print directories")
flags.BoolVar(&wk.SkipFiles, "skip-files", false, "skip files")
return flags
}