commands: files ls: sort output
Imitate Unix `ls` command, sort by default; disable with `-U` flag. License: MIT Signed-off-by: Lucas Molas <schomatis@gmail.com>
Lucas Molas committed
Jul 12, 2018 at 19:42 UTC
dfb81abf8013eeed325f39699c573e6a3e6c2745
2 files changed
+23
-4
core/commands/files.go
+10
-1
@@ -8,6 +8,7 @@ import (
8
"io"
9
"os"
10
gopath "path"
11
+ "sort"
12
"strings"
13
14
bservice "github.com/ipfs/go-ipfs/blockservice"
@@ -405,6 +406,7 @@ Examples:
406
},
407
Options: []cmdkit.Option{
408
cmdkit.BoolOption("l", "Use long listing format."),
409
+ cmdkit.BoolOption("U", "Do not sort; list entries in directory order."),
410
},
411
Run: func(req oldcmds.Request, res oldcmds.Response) {
412
var arg string
@@ -482,8 +484,15 @@ Examples:
484
}
485
486
buf := new(bytes.Buffer)
485
- long, _, _ := res.Request().Option("l").Bool()
487
488
+ noSort, _, _ := res.Request().Option("U").Bool()
489
+ if !noSort {
490
+ sort.Slice(out.Entries, func(i, j int) bool {
491
+ return strings.Compare(out.Entries[i].Name, out.Entries[j].Name) < 0
492
+ })
493
+ }
494
+
495
+ long, _, _ := res.Request().Option("l").Bool()
496
for _, o := range out.Entries {
497
if long {
498
fmt.Fprintf(buf, "%s\t%s\t%d\n", o.Name, o.Hash, o.Size)
test/sharness/t0250-files-api.sh
+13
-3
@@ -56,19 +56,29 @@ test_sharding() {
56
57
test_expect_success "can make 100 files in a directory $EXTRA" '
58
printf "" > list_exp_raw
59
- for i in `seq 100`
59
+ for i in `seq 100 -1 1`
60
do
61
echo $i | ipfs files write --create /foo/file$i || return 1
62
echo file$i >> list_exp_raw
63
done
64
'
65
+ # Create the files in reverse (unsorted) order (`seq 100 -1 1`)
66
+ # to check the sort in the `ipfs files ls` command. `ProtoNode`
67
+ # links are always sorted at the DAG layer so the sorting feature
68
+ # is tested with sharded directories.
69
66
- test_expect_success "listing works $EXTRA" '
67
- ipfs files ls /foo |sort > list_out &&
70
+ test_expect_success "sorted listing works $EXTRA" '
71
+ ipfs files ls /foo > list_out &&
72
sort list_exp_raw > list_exp &&
73
test_cmp list_exp list_out
74
'
75
76
+ test_expect_success "unsorted listing works $EXTRA" '
77
+ ipfs files ls -U /foo > list_out &&
78
+ sort list_exp_raw > sort_list_not_exp &&
79
+ ! test_cmp sort_list_not_exp list_out
80
+ '
81
+
82
test_expect_success "can read a file from sharded directory $EXTRA" '
83
ipfs files read /foo/file65 > file_out &&
84
echo "65" > file_exp &&