forked from blacknon/lssh
/
cmd.go
116 lines (98 loc) · 2.45 KB
/
cmd.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
// Copyright (c) 2019 Blacknon. All rights reserved.
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.
// This file describes the code of the built-in command used by lsftp.
package sftp
import (
"os"
"sort"
"github.com/urfave/cli"
)
// FileInfos is []os.FileInfo.
type FileInfos []os.FileInfo
// ByName is sort by name.
type ByName struct{ FileInfos }
func (fi ByName) Len() int {
return len(fi.FileInfos)
}
func (fi ByName) Swap(i, j int) {
fi.FileInfos[i], fi.FileInfos[j] = fi.FileInfos[j], fi.FileInfos[i]
}
func (fi ByName) Less(i, j int) bool {
return fi.FileInfos[j].Name() > fi.FileInfos[i].Name()
}
// BySize is sort by size.
type BySize struct{ FileInfos }
func (fi BySize) Len() int {
return len(fi.FileInfos)
}
func (fi BySize) Swap(i, j int) {
fi.FileInfos[i], fi.FileInfos[j] = fi.FileInfos[j], fi.FileInfos[i]
}
func (fi BySize) Less(i, j int) bool {
return fi.FileInfos[j].Size() > fi.FileInfos[i].Size()
}
// ByTime is sort by time.
type ByTime struct{ FileInfos }
func (fi ByTime) Len() int {
return len(fi.FileInfos)
}
func (fi ByTime) Swap(i, j int) {
fi.FileInfos[i], fi.FileInfos[j] = fi.FileInfos[j], fi.FileInfos[i]
}
func (fi ByTime) Less(i, j int) bool {
return fi.FileInfos[j].ModTime().Unix() > fi.FileInfos[i].ModTime().Unix()
}
const (
helptext = `{{.Name}} - {{.Usage}}
{{.HelpName}} {{if .VisibleFlags}}[options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{end}}
{{range .VisibleFlags}} {{.}}
{{end}}
`
)
// sftpLsData struct by sftp ls command list data.
type sftpLsData struct {
Mode string
User string
Group string
Size string
Time string
Path string
}
// SortLsData sorts ...
func (r *RunSftp) SortLsData(c *cli.Context, files []os.FileInfo) {
// sort
switch {
case c.Bool("f"): // do not sort
// If the l flag is enabled, sort by name
if c.Bool("l") {
// check reverse
if c.Bool("r") {
sort.Sort(sort.Reverse(ByName{files}))
} else {
sort.Sort(ByName{files})
}
}
case c.Bool("S"): // sort by file size
// check reverse
if c.Bool("r") {
sort.Sort(sort.Reverse(BySize{files}))
} else {
sort.Sort(BySize{files})
}
case c.Bool("t"): // sort by mod time
// check reverse
if c.Bool("r") {
sort.Sort(sort.Reverse(ByTime{files}))
} else {
sort.Sort(ByTime{files})
}
default: // sort by name (default).
// check reverse
if c.Bool("r") {
sort.Sort(sort.Reverse(ByName{files}))
} else {
sort.Sort(ByName{files})
}
}
}