forked from odeke-em/drive
/
list.go
551 lines (450 loc) · 11.4 KB
/
list.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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package drive
import (
"fmt"
"strings"
"github.com/odeke-em/log"
)
type attribute struct {
minimal bool
mask int
parent string
diskUsageOnly bool
}
type traversalSt struct {
file *File
headPath string
depth int
mask int
inTrash bool
explicitNoPrompt bool
sorters []string
matchQuery *matchQuery
}
func sorters(opts *Options) []string {
if opts == nil || opts.Meta == nil {
return nil
}
meta := *(opts.Meta)
retr, ok := meta[SortKey]
if !ok {
return nil
}
// Keys sent it via meta need to be comma split
// first, space trimmed then added.
// See Issue https://github.com/odeke-em/drive/issues/714.
var sortKeys []string
for _, attr := range retr {
splits := strings.Split(attr, ",")
for _, split := range splits {
trimmedAttr := strings.TrimSpace(split)
sortKeys = append(sortKeys, trimmedAttr)
}
}
return sortKeys
}
func (g *Commands) ListMatches() error {
inTrash := trashed(g.opts.TypeMask)
mq := g.createMatchQuery(false)
mq.titleSearches = append(mq.titleSearches, fuzzyStringsValuePair{
fuzzyLevel: Like, values: g.opts.Sources, inTrash: inTrash, joiner: Or,
})
pagePair := g.rem.FindMatches(mq)
spin := g.playabler()
spin.play()
defer spin.stop()
traversalCount := 0
matches := pagePair.filesChan
errsChan := pagePair.errsChan
working := true
for working {
select {
case err := <-errsChan:
if err != nil {
return err
}
case match, stillHasContent := <-matches:
if !stillHasContent {
working = false
break
}
if match == nil {
continue
}
travSt := traversalSt{
depth: g.opts.Depth,
file: match,
headPath: g.opts.Path,
inTrash: g.opts.InTrash,
mask: g.opts.TypeMask,
sorters: sorters(g.opts),
}
traversalCount += 1
if !g.breadthFirst(travSt, spin) {
break
}
}
}
if traversalCount < 1 {
g.log.LogErrln("no matches found!")
}
return nil
}
func (g *Commands) createMatchQuery(exactMatch bool) *matchQuery {
mimeQuerySearches := []fuzzyStringsValuePair{}
titleSearches := []fuzzyStringsValuePair{}
ownerSearches := []fuzzyStringsValuePair{}
if g.opts.Meta != nil {
meta := *(g.opts.Meta)
skipMimes, sOk := meta[SkipMimeKeyKey]
if sOk {
mimeQuerySearches = append(mimeQuerySearches, fuzzyStringsValuePair{
fuzzyLevel: Not, values: skipMimes, inTrash: g.opts.InTrash, joiner: And,
})
}
matchMimes, mOk := meta[MatchMimeKeyKey]
if mOk {
mimeQuerySearches = append(mimeQuerySearches, fuzzyStringsValuePair{
fuzzyLevel: Is, values: matchMimes, inTrash: g.opts.InTrash, joiner: Or,
})
}
exactTitles, etOk := meta[ExactTitleKey]
if etOk {
titleSearches = append(titleSearches, fuzzyStringsValuePair{
fuzzyLevel: Is, values: exactTitles, inTrash: g.opts.InTrash, joiner: Or,
})
}
exactOwners, eoOk := meta[ExactOwnerKey]
if eoOk {
ownerSearches = append(ownerSearches, fuzzyStringsValuePair{
fuzzyLevel: Is, values: exactOwners, joiner: Or,
})
}
matchOwners, moOk := meta[MatchOwnerKey]
if moOk {
ownerSearches = append(ownerSearches, fuzzyStringsValuePair{
fuzzyLevel: Like, values: matchOwners, joiner: Or,
})
}
notOwner, soOk := meta[NotOwnerKey]
if soOk {
ownerSearches = append(ownerSearches, fuzzyStringsValuePair{
fuzzyLevel: NotIn, values: notOwner, joiner: And,
})
}
}
mq := matchQuery{
dirPath: g.opts.Path,
inTrash: g.opts.InTrash,
mimeQuerySearches: mimeQuerySearches,
titleSearches: titleSearches,
ownerSearches: ownerSearches,
}
return &mq
}
func (g *Commands) List(byId bool) error {
var kvList []*keyValue
resolver := g.rem.FindByPath
if byId {
resolver = g.rem.FindById
}
mq := g.createMatchQuery(true)
for i, relPath := range g.opts.Sources {
r, rErr := resolver(relPath)
g.DebugPrintf("[Commands.List] #%d %q\n", i, relPath)
if rErr != nil && rErr != ErrPathNotExists {
return illogicalStateErr(fmt.Errorf("%v: '%s'", rErr, relPath))
}
if r == nil {
g.log.LogErrf("%s cannot be found remotely\n", customQuote(relPath))
continue
}
parentPath := ""
if !byId {
parentPath = g.parentPather(relPath)
} else {
parentPath = r.Id
}
if remoteRootLike(parentPath) {
parentPath = ""
}
if remoteRootLike(r.Name) {
r.Name = ""
}
if rootLike(parentPath) {
parentPath = ""
}
kvList = append(kvList, &keyValue{key: parentPath, value: r})
}
spin := g.playabler()
spin.play()
for _, kv := range kvList {
if kv == nil || kv.value == nil {
continue
}
travSt := traversalSt{
depth: g.opts.Depth,
file: kv.value.(*File),
headPath: kv.key,
inTrash: g.opts.InTrash,
mask: g.opts.TypeMask,
sorters: sorters(g.opts),
matchQuery: mq,
}
if !g.breadthFirst(travSt, spin) {
break
}
}
spin.stop()
return nil
}
func (g *Commands) listSharedPerPath(relToRootPath string) ([]*keyValue, error) {
pagePair := g.rem.FindByPathShared(relToRootPath)
errsChan := pagePair.errsChan
sharedRemotes := pagePair.filesChan
var kvList []*keyValue
working := true
for working {
select {
case err := <-errsChan:
if err != nil {
g.log.LogErrf("%v: '%s'\n", err, relToRootPath)
return kvList, err
}
case s, stillHasContent := <-sharedRemotes:
if !stillHasContent {
working = false
break
}
parentPath := g.parentPather(relToRootPath)
if remoteRootLike(parentPath) {
parentPath = ""
}
if rootLike(parentPath) {
parentPath = ""
}
if s == nil {
continue
}
if remoteRootLike(s.Name) {
s.Name = ""
}
kvList = append(kvList, &keyValue{key: parentPath, value: s})
}
}
return kvList, nil
}
func (g *Commands) ListShared() (err error) {
spin := g.playabler()
spin.play()
defer spin.stop()
var kvList []*keyValue
for _, relPath := range g.opts.Sources {
childKvList, err := g.listSharedPerPath(relPath)
if err != nil {
return err
}
kvList = append(kvList, childKvList...)
}
for _, kv := range kvList {
if kv == nil || kv.value == nil {
continue
}
travSt := traversalSt{
depth: g.opts.Depth,
file: kv.value.(*File),
headPath: kv.key,
inTrash: g.opts.InTrash,
mask: g.opts.TypeMask,
}
if !g.breadthFirst(travSt, spin) {
break
}
}
spin.stop()
return
}
func (f *File) pretty(logy *log.Logger, opt attribute) {
fmtdPath := sepJoin("/", opt.parent, f.Name)
if opt.diskUsageOnly {
logy.Logf("%-12v %s\n", f.Size, fmtdPath)
return
}
if opt.minimal {
logy.Logf("%s", fmtdPath)
} else {
if f.IsDir {
logy.Logf("d")
} else {
logy.Logf("-")
}
if f.Shared {
logy.Logf("s")
} else {
logy.Logf("-")
}
if f.UserPermission != nil {
logy.Logf(" %-10s ", f.UserPermission.Role)
}
}
if owners(opt.mask) && len(f.OwnerNames) >= 1 {
logy.Logf(" %s ", strings.Join(f.OwnerNames, " & "))
}
if version(opt.mask) {
logy.Logf(" v%d", f.Version)
}
if !opt.minimal {
logy.Logf(" %-10s\t%-10s\t\t%-20s\t%-s\n", prettyBytes(f.Size), f.Id, f.ModTime, fmtdPath)
} else {
logy.Logln()
}
}
func (g *Commands) breadthFirst(travSt traversalSt, spin *playable) bool {
opt := attribute{
minimal: isMinimal(g.opts.TypeMask),
diskUsageOnly: diskUsageOnly(g.opts.TypeMask),
mask: travSt.mask,
}
opt.parent = ""
if travSt.headPath != "/" {
opt.parent = travSt.headPath
}
f := travSt.file
if !f.IsDir {
f.pretty(g.log, opt)
return true
}
// New head path
if !(rootLike(opt.parent) && rootLike(f.Name)) {
opt.parent = sepJoin("/", opt.parent, f.Name)
}
// A depth of < 0 means traverse as deep as you can
if travSt.depth == 0 {
// At the end of the line, this was successful.
return true
} else if travSt.depth > 0 {
travSt.depth -= 1
}
expr := buildExpression(f.Id, travSt.mask, travSt.inTrash)
if travSt.matchQuery != nil {
exprExtra := travSt.matchQuery.Stringer()
expr = sepJoinNonEmpty(" and ", fmt.Sprintf("(%s)", expr), exprExtra)
}
req := g.rem.service.Files.List()
req.Q(expr)
req.MaxResults(g.opts.PageSize)
spin.pause()
canPrompt := !travSt.explicitNoPrompt
if canPrompt {
canPrompt = g.opts.canPrompt()
}
spin.play()
onlyFiles := nonFolderExplicitly(g.opts.TypeMask)
iterCount := uint64(0)
var collector []*File
// We shouldn't prompt in between the same page otherwise we get
// spurious prompts. See Issue https://github.com/odeke-em/drive/issues/724.
// We'll only make the prompts in between children.
pagePair := reqDoPage(req, g.opts.Hidden, false)
errsChan := pagePair.errsChan
filesChan := pagePair.filesChan
working := true
for working {
select {
case err := <-errsChan:
if err != nil {
g.log.LogErrf("%v", err)
return false
}
case file, stillHasContent := <-filesChan:
if !stillHasContent {
working = false
break
}
if file == nil {
return false
}
if !isHidden(file.Name, g.opts.Hidden) {
collector = append(collector, file)
}
}
}
if len(travSt.sorters) >= 1 {
collector = g.sort(collector, travSt.sorters...)
}
var children []*File
for _, file := range collector {
if file.IsDir {
children = append(children, file)
}
// The case in which only directories wanted is covered by the buildExpression clause
// reason being that only folder are allowed to be roots, including the only files clause
// would result in incorrect traversal since non-folders don't have children.
// Just don't print it, however, the folder will still be explored.
if onlyFiles && file.IsDir {
continue
}
file.pretty(g.log, opt)
iterCount += 1
}
if !travSt.inTrash && !g.opts.InTrash {
// We'll only prompt when traversing children to avoid
// spurious prompts that result from asynchronous paging
// before children have been retrieved, sorted and printed.
// See Issue https://github.com/odeke-em/drive/issues/724.
canPage := travSt.depth != 0 && len(children) > 0
if canPage && canPrompt && !nextPage() {
return false
}
for _, file := range children {
childSt := traversalSt{
depth: travSt.depth,
file: file,
headPath: opt.parent,
inTrash: travSt.inTrash,
mask: g.opts.TypeMask,
explicitNoPrompt: travSt.explicitNoPrompt,
sorters: travSt.sorters,
matchQuery: travSt.matchQuery,
}
if !g.breadthFirst(childSt, spin) {
return false
}
}
return true
}
return iterCount >= 1
}
func diskUsageOnly(mask int) bool {
return (mask & DiskUsageOnly) != 0
}
func isMinimal(mask int) bool {
return (mask & Minimal) != 0
}
func owners(mask int) bool {
return (mask & Owners) != 0
}
func version(mask int) bool {
return (mask & CurrentVersion) != 0
}
func shared(mask int) bool {
return (mask & Shared) != 0
}
func trashed(mask int) bool {
return (mask & InTrash) != 0
}
func starred(mask int) bool {
return (mask & Starred) != 0
}