/
sourcerelpath.go
97 lines (84 loc) · 2.51 KB
/
sourcerelpath.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
package chezmoi
import (
"path"
"strings"
)
var emptySourceRelPath SourceRelPath
// A SourceRelPath is a relative path to an entry in the source state.
type SourceRelPath struct {
relPath RelPath
isDir bool
}
// NewSourceRelDirPath returns a new SourceRelPath for a directory.
func NewSourceRelDirPath(relPath string) SourceRelPath {
return SourceRelPath{
relPath: NewRelPath(relPath),
isDir: true,
}
}
// NewSourceRelPath returns a new SourceRelPath.
func NewSourceRelPath(relPath string) SourceRelPath {
return SourceRelPath{
relPath: NewRelPath(relPath),
}
}
// Dir returns p's directory.
func (p SourceRelPath) Dir() SourceRelPath {
return SourceRelPath{
relPath: p.relPath.Dir(),
isDir: true,
}
}
// Empty returns true if p is empty.
func (p SourceRelPath) Empty() bool {
return p == SourceRelPath{}
}
// Join appends sourceRelPaths to p.
func (p SourceRelPath) Join(sourceRelPaths ...SourceRelPath) SourceRelPath {
if len(sourceRelPaths) == 0 {
return p
}
relPaths := make([]RelPath, 0, len(sourceRelPaths))
for _, sourceRelPath := range sourceRelPaths {
relPaths = append(relPaths, sourceRelPath.relPath)
}
return SourceRelPath{
relPath: p.relPath.Join(relPaths...),
isDir: sourceRelPaths[len(sourceRelPaths)-1].isDir,
}
}
// Less returns true if p is less than other.
func (p SourceRelPath) Less(other SourceRelPath) bool {
return p.relPath.Less(other.relPath)
}
// RelPath returns p as a relative path.
func (p SourceRelPath) RelPath() RelPath {
return p.relPath
}
// Split returns the p's file and directory.
func (p SourceRelPath) Split() (SourceRelPath, SourceRelPath) {
dir, file := p.relPath.Split()
return NewSourceRelDirPath(dir.String()), NewSourceRelPath(file.String())
}
func (p SourceRelPath) String() string {
return p.relPath.String()
}
// TargetRelPath returns the relative path of p's target.
func (p SourceRelPath) TargetRelPath(encryptedSuffix string) RelPath {
sourceNames := strings.Split(p.relPath.String(), "/")
relPathStrs := make([]string, 0, len(sourceNames))
if p.isDir {
for _, sourceName := range sourceNames {
dirAttr := parseDirAttr(sourceName)
relPathStrs = append(relPathStrs, dirAttr.TargetName)
}
} else {
for _, sourceName := range sourceNames[:len(sourceNames)-1] {
dirAttr := parseDirAttr(sourceName)
relPathStrs = append(relPathStrs, dirAttr.TargetName)
}
fileAttr := parseFileAttr(sourceNames[len(sourceNames)-1], encryptedSuffix)
relPathStrs = append(relPathStrs, fileAttr.TargetName)
}
return NewRelPath(path.Join(relPathStrs...))
}