This repository has been archived by the owner on Jan 12, 2023. It is now read-only.
/
utility.go
95 lines (86 loc) · 2.46 KB
/
utility.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
package api
import (
"errors"
"os"
"path"
"path/filepath"
"strings"
)
// Append elm if it is not yet on dest
func AppendUniqueString(dest []string, elm string) []string {
for _, d := range dest {
if d == elm {
return dest
}
}
return append(dest, elm)
}
// Returns a handler whichasd will track seal/index files, and call the given handler aftrewards, writing the
// into the provided slice
func IndexTrackingResultHandlerAdapter(indices *[]string, handler func(r Result)) func(r Result) {
return func(r Result) {
handler(r)
if r == nil || r.FileInformation() == nil {
return
}
if r.FileInformation().Size < 0 {
*indices = append(*indices, r.FileInformation().Path)
}
}
}
// Parse all valid source items from the given list.
// May either be files or directories. The returned list may be shorter, as contained paths are
// skipped automatically. Paths will be normalized.
func ParseSources(items []string, allowFiles bool) (res []string, err error) {
var invalidTrees, noTrees, noRegularFiles []string
res = make([]string, len(items))
copy(res, items)
for i, tree := range res {
if stat, err := os.Stat(tree); err != nil {
invalidTrees = append(invalidTrees, tree)
continue
} else if !stat.IsDir() {
if !allowFiles {
noTrees = append(noTrees, tree)
continue
} else if !stat.Mode().IsRegular() {
noRegularFiles = append(noRegularFiles, tree)
}
// otherwise it's a regular file
}
tree = path.Clean(tree)
if !filepath.IsAbs(tree) {
tree, err = filepath.Abs(tree)
if err != nil {
return nil, err
}
}
res[i] = tree
}
if len(invalidTrees) > 0 {
return nil, errors.New("None of the following items exists: " + strings.Join(invalidTrees, ", "))
}
if len(noTrees) > 0 {
return nil, errors.New("The following items are no directory: " + strings.Join(noTrees, ", "))
}
if len(noRegularFiles) > 0 {
return nil, errors.New("The following items are no regular files: " + strings.Join(noRegularFiles, ", "))
}
// drop trees which are a sub-tree of another, or which are equal !
if len(res) > 1 {
validTrees := make([]string, 0, len(res))
for i, ltree := range res {
for x, rtree := range res {
if i == x || strings.HasPrefix(ltree, rtree+string(os.PathSeparator)) {
continue
}
validTrees = AppendUniqueString(validTrees, ltree)
}
}
if len(validTrees) == 0 {
panic("Didn't find a single valid tree after pruning - shouldn't happen")
}
res = validTrees
}
return res, nil
}