-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathremove.go
More file actions
343 lines (313 loc) · 8.12 KB
/
Copy pathremove.go
File metadata and controls
343 lines (313 loc) · 8.12 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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
package main
import (
"bufio"
"flag"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"strings"
"sync"
"text/tabwriter"
"time"
)
var (
shortIDRe = regexp.MustCompile(`^[0-9A-Za-z]{8}$`)
urlShareRe = regexp.MustCompile(`^https?://[^/]+/s/([0-9A-Za-z]{8})/?$`)
)
type removeTargetKind int
const (
removeTargetFilename removeTargetKind = iota
removeTargetShortID
)
type removeTarget struct {
kind removeTargetKind
filename string
shortID string
}
type removeOptions struct {
all bool
pick string
yes bool
nonInteractive bool
}
type removeIO struct {
stdin io.Reader
stdout io.Writer
stderr io.Writer
isTTY bool
once sync.Once
br *bufio.Reader
}
func defaultRemoveIO() removeIO {
return removeIO{
stdin: os.Stdin,
stdout: os.Stdout,
stderr: os.Stderr,
isTTY: true,
}
}
func runRemove(args []string) error {
rio := defaultRemoveIO()
return runRemoveWith(args, &rio)
}
func runRemoveWith(args []string, rio *removeIO) error {
fs := flag.NewFlagSet("remove", flag.ContinueOnError)
all := fs.Bool("all", false, "remove every match (with a confirm prompt unless --yes)")
pick := fs.String("pick", "", "short_id to remove when the argument is ambiguous")
yes := fs.Bool("yes", false, "skip the per-share confirmation prompt")
nonInteractive := fs.Bool("non-interactive", false, "fail instead of prompting for input")
if err := fs.Parse(args); err != nil {
return err
}
rest := fs.Args()
if len(rest) != 1 {
return fmt.Errorf("usage: gander remove [--all|--pick <short_id>|--yes|--non-interactive] (<filename>|<short_id>|<url>)")
}
opts := removeOptions{
all: *all,
pick: *pick,
yes: *yes,
nonInteractive: *nonInteractive,
}
return doRemove(rest[0], opts, rio)
}
func parseRemoveArg(arg string) removeTarget {
if m := urlShareRe.FindStringSubmatch(arg); m != nil {
return removeTarget{kind: removeTargetShortID, shortID: m[1]}
}
if shortIDRe.MatchString(arg) {
return removeTarget{kind: removeTargetShortID, shortID: arg}
}
return removeTarget{kind: removeTargetFilename, filename: arg}
}
func doRemove(arg string, opts removeOptions, rio *removeIO) error {
cfg, err := requireAuth()
if err != nil {
return err
}
cli := newAPIClient(cfg.APIURL, cfg.APIToken)
target := parseRemoveArg(arg)
matches, err := resolveRemoveTargets(cli, &cfg, target)
if err != nil {
return err
}
if opts.all && opts.pick != "" {
return fmt.Errorf("--all and --pick are mutually exclusive")
}
switch len(matches) {
case 0:
return fmt.Errorf("no share found for %q", arg)
case 1:
return confirmAndDelete([]shareResp{matches[0]}, opts, cfg, rio)
default:
if opts.pick != "" {
chosen, ok := pickFromMatches(matches, opts.pick)
if !ok {
return fmt.Errorf("--pick %s did not match any of the %d candidates; pass one of the SHORT_IDs listed below\n\n%s",
opts.pick, len(matches), formatMatchesTable(matches))
}
return confirmAndDelete([]shareResp{chosen}, opts, cfg, rio)
}
if opts.all {
return confirmAndDelete(matches, opts, cfg, rio)
}
if opts.nonInteractive || !rio.isTTY {
return ambiguousError(arg, matches)
}
chosen, err := promptPick(matches, rio)
if err != nil {
return err
}
return confirmAndDelete([]shareResp{chosen}, opts, cfg, rio)
}
}
func resolveRemoveTargets(cli *apiClient, cfg *Config, target removeTarget) ([]shareResp, error) {
switch target.kind {
case removeTargetShortID:
all, err := cli.ListShares()
if err != nil {
return nil, fmt.Errorf("list: %w", err)
}
for i := range all {
if all[i].ShortID == target.shortID {
return []shareResp{all[i]}, nil
}
}
return nil, nil
case removeTargetFilename:
canonical, err := canonicalPath(target.filename)
if err != nil {
return nil, err
}
if sid, ok := cfg.Shares[canonical]; ok {
all, err := cli.ListShares()
if err != nil {
return nil, fmt.Errorf("list: %w", err)
}
for i := range all {
if all[i].ShortID == sid {
return []shareResp{all[i]}, nil
}
}
}
list, err := cli.ListSharesByFilename(filepath.Base(canonical))
if err != nil {
return nil, fmt.Errorf("lookup: %w", err)
}
return list, nil
}
return nil, fmt.Errorf("unhandled remove target")
}
func pickFromMatches(matches []shareResp, want string) (shareResp, bool) {
for _, m := range matches {
if m.ShortID == want {
return m, true
}
}
return shareResp{}, false
}
func ambiguousError(arg string, matches []shareResp) error {
var b strings.Builder
fmt.Fprintf(&b, "%q matched %d shares; pass --pick <short_id> or --all, or run interactively\n\n",
arg, len(matches))
b.WriteString(formatMatchesTable(matches))
return fmt.Errorf("%s", b.String())
}
func formatMatchesTable(matches []shareResp) string {
var b strings.Builder
tw := tabwriter.NewWriter(&b, 0, 0, 2, ' ', 0)
fmt.Fprintln(tw, "SHORT ID\tFILE\tCREATED\tSIZE")
for i := range matches {
created := formatTime(matches[i].CreatedAt)
fmt.Fprintf(tw, "%s\t%s\t%s\t%s\n",
matches[i].ShortID,
matches[i].Filename,
created,
humanSize(matches[i].SizeBytes),
)
}
_ = tw.Flush()
return b.String()
}
func formatTime(s string) string {
t, err := time.Parse(time.RFC3339, s)
if err != nil {
return s
}
return t.Local().Format("2006-01-02 15:04")
}
func humanSize(n int) string {
if n < 1024 {
return fmt.Sprintf("%d B", n)
}
div, exp := float64(1024), 0
for v := float64(n) / 1024; v >= 1024; v /= 1024 {
div *= 1024
exp++
}
return fmt.Sprintf("%.1f %cB", float64(n)/div, "KMGTPE"[exp])
}
func promptPick(matches []shareResp, rio *removeIO) (shareResp, error) {
fmt.Fprintln(rio.out(), formatMatchesTable(matches))
fmt.Fprintf(rio.out(), "Pick a share to remove (enter SHORT ID, or 'q' to quit): ")
ans, err := readLine(rio.lineReader())
if err != nil {
if err == io.EOF {
return shareResp{}, fmt.Errorf("no selection made")
}
return shareResp{}, err
}
ans = strings.TrimSpace(ans)
if strings.EqualFold(ans, "q") || ans == "" {
return shareResp{}, fmt.Errorf("aborted")
}
for _, m := range matches {
if m.ShortID == ans {
return m, nil
}
}
return shareResp{}, fmt.Errorf("%q did not match any SHORT ID listed above", ans)
}
func readLine(br *bufio.Reader) (string, error) {
line, err := br.ReadString('\n')
if err != nil && line != "" {
return line, err
}
return strings.TrimRight(line, "\r\n"), err
}
func confirmAndDelete(targets []shareResp, opts removeOptions, cfg Config, rio *removeIO) error {
if len(targets) == 0 {
return nil
}
if !opts.yes && rio.isTTY {
fmt.Fprintf(rio.out(), "About to remove %d share(s):\n", len(targets))
fmt.Fprintln(rio.out(), formatMatchesTable(targets))
ok, err := promptYesNo(rio)
if err != nil {
return err
}
if !ok {
return fmt.Errorf("aborted")
}
}
for i := range targets {
if err := newAPIClient(cfg.APIURL, cfg.APIToken).DeleteShare(targets[i].UUID); err != nil {
return fmt.Errorf("delete %s: %w", targets[i].ShortID, err)
}
fmt.Fprintf(rio.out(), "Removed %s (%s).\n", targets[i].Filename, targets[i].URL)
}
cleanupConfig(&cfg, targets)
if err := WriteConfig(cfg); err != nil {
return fmt.Errorf("save config: %w", err)
}
return nil
}
func promptYesNo(rio *removeIO) (bool, error) {
fmt.Fprintf(rio.out(), "Proceed? [y/N] ")
line, err := readLine(rio.lineReader())
if err != nil && line == "" {
if err == io.EOF {
return false, nil
}
return false, err
}
ans := strings.TrimSpace(strings.ToLower(line))
return ans == "y" || ans == "yes", nil
}
func cleanupConfig(cfg *Config, removed []shareResp) {
removedIDs := make(map[string]bool, len(removed))
for _, sh := range removed {
removedIDs[sh.ShortID] = true
}
for path, sid := range cfg.Shares {
if removedIDs[sid] {
delete(cfg.Shares, path)
}
}
}
func (rio *removeIO) out() io.Writer {
if rio.stdout == nil {
return io.Discard
}
return rio.stdout
}
func (rio *removeIO) errOut() io.Writer {
if rio.stderr == nil {
return io.Discard
}
return rio.stderr
}
func (rio *removeIO) lineReader() *bufio.Reader {
rio.once.Do(func() {
if br, ok := rio.stdin.(*bufio.Reader); ok {
rio.br = br
return
}
if rio.stdin != nil {
rio.br = bufio.NewReader(rio.stdin)
}
})
return rio.br
}