/
attribs.go
225 lines (187 loc) · 5.69 KB
/
attribs.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
package git
import (
"bufio"
"bytes"
"os"
"path/filepath"
"strings"
"github.com/git-lfs/git-lfs/filepathfilter"
"github.com/git-lfs/git-lfs/tools"
"github.com/rubyist/tracerx"
)
const (
LockableAttrib = "lockable"
)
// AttributePath is a path entry in a gitattributes file which has the LFS filter
type AttributePath struct {
// Path entry in the attribute file
Path string
// The attribute file which was the source of this entry
Source *AttributeSource
// Path also has the 'lockable' attribute
Lockable bool
}
type AttributeSource struct {
Path string
LineEnding string
}
func (s *AttributeSource) String() string {
return s.Path
}
// GetRootAttributePaths beahves as GetRootAttributePaths, and loads information
// only from the global gitattributes file.
func GetRootAttributePaths(cfg Env) []AttributePath {
af, ok := cfg.Get("core.attributesfile")
if !ok {
return nil
}
// The working directory for the root gitattributes file is blank.
return attrPaths(af, "")
}
// GetSystemAttributePaths behaves as GetAttributePaths, and loads information
// only from the system gitattributes file, respecting the $PREFIX environment
// variable.
func GetSystemAttributePaths(env Env) []AttributePath {
prefix, _ := env.Get("PREFIX")
if len(prefix) == 0 {
prefix = string(filepath.Separator)
}
path := filepath.Join(prefix, "etc", "gitattributes")
if _, err := os.Stat(path); os.IsNotExist(err) {
return nil
}
return attrPaths(path, "")
}
// GetAttributePaths returns a list of entries in .gitattributes which are
// configured with the filter=lfs attribute
// workingDir is the root of the working copy
// gitDir is the root of the git repo
func GetAttributePaths(workingDir, gitDir string) []AttributePath {
paths := make([]AttributePath, 0)
for _, path := range findAttributeFiles(workingDir, gitDir) {
paths = append(paths, attrPaths(path, workingDir)...)
}
return paths
}
func attrPaths(path, workingDir string) []AttributePath {
attributes, err := os.Open(path)
if err != nil {
return nil
}
var paths []AttributePath
relfile, _ := filepath.Rel(workingDir, path)
reldir := filepath.Dir(relfile)
source := &AttributeSource{Path: relfile}
le := &lineEndingSplitter{}
scanner := bufio.NewScanner(attributes)
scanner.Split(le.ScanLines)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if strings.HasPrefix(line, "#") {
continue
}
// Check for filter=lfs (signifying that LFS is tracking
// this file) or "lockable", which indicates that the
// file is lockable (and may or may not be tracked by
// Git LFS).
if strings.Contains(line, "filter=lfs") ||
strings.HasSuffix(line, "lockable") {
fields := strings.Fields(line)
pattern := fields[0]
if len(reldir) > 0 {
pattern = filepath.Join(reldir, pattern)
}
// Find lockable flag in any position after pattern to avoid
// edge case of matching "lockable" to a file pattern
lockable := false
for _, f := range fields[1:] {
if f == LockableAttrib {
lockable = true
break
}
}
paths = append(paths, AttributePath{
Path: pattern,
Source: source,
Lockable: lockable,
})
}
}
source.LineEnding = le.LineEnding()
return paths
}
// GetAttributeFilter returns a list of entries in .gitattributes which are
// configured with the filter=lfs attribute as a file path filter which
// file paths can be matched against
// workingDir is the root of the working copy
// gitDir is the root of the git repo
func GetAttributeFilter(workingDir, gitDir string) *filepathfilter.Filter {
paths := GetAttributePaths(workingDir, gitDir)
patterns := make([]filepathfilter.Pattern, 0, len(paths))
for _, path := range paths {
// Convert all separators to `/` before creating a pattern to
// avoid characters being escaped in situations like `subtree\*.md`
patterns = append(patterns, filepathfilter.NewPattern(filepath.ToSlash(path.Path)))
}
return filepathfilter.NewFromPatterns(patterns, nil)
}
// copies bufio.ScanLines(), counting LF vs CRLF in a file
type lineEndingSplitter struct {
LFCount int
CRLFCount int
}
func (s *lineEndingSplitter) LineEnding() string {
if s.CRLFCount > s.LFCount {
return "\r\n"
} else if s.LFCount == 0 {
return ""
}
return "\n"
}
func (s *lineEndingSplitter) ScanLines(data []byte, atEOF bool) (advance int, token []byte, err error) {
if atEOF && len(data) == 0 {
return 0, nil, nil
}
if i := bytes.IndexByte(data, '\n'); i >= 0 {
// We have a full newline-terminated line.
return i + 1, s.dropCR(data[0:i]), nil
}
// If we're at EOF, we have a final, non-terminated line. Return it.
if atEOF {
return len(data), data, nil
}
// Request more data.
return 0, nil, nil
}
// dropCR drops a terminal \r from the data.
func (s *lineEndingSplitter) dropCR(data []byte) []byte {
if len(data) > 0 && data[len(data)-1] == '\r' {
s.CRLFCount++
return data[0 : len(data)-1]
}
s.LFCount++
return data
}
func findAttributeFiles(workingDir, gitDir string) []string {
var paths []string
repoAttributes := filepath.Join(gitDir, "info", "attributes")
if info, err := os.Stat(repoAttributes); err == nil && !info.IsDir() {
paths = append(paths, repoAttributes)
}
tools.FastWalkGitRepo(workingDir, func(parentDir string, info os.FileInfo, err error) {
if err != nil {
tracerx.Printf("Error finding .gitattributes: %v", err)
return
}
if info.IsDir() || info.Name() != ".gitattributes" {
return
}
paths = append(paths, filepath.Join(parentDir, info.Name()))
})
// reverse the order of the files so more specific entries are found first
// when iterating from the front (respects precedence)
for i, j := 0, len(paths)-1; i < j; i, j = i+1, j-1 {
paths[i], paths[j] = paths[j], paths[i]
}
return paths
}