File: attribs.go

package info (click to toggle)
git-lfs 3.6.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 4,808 kB
  • sloc: sh: 21,256; makefile: 507; ruby: 417
file content (230 lines) | stat: -rw-r--r-- 6,482 bytes parent folder | download
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
226
227
228
229
230
package git

import (
	"errors"
	"io"
	"os"
	"path"
	"path/filepath"
	"sort"
	"strings"

	"github.com/git-lfs/git-lfs/v3/filepathfilter"
	"github.com/git-lfs/git-lfs/v3/git/gitattr"
	"github.com/git-lfs/git-lfs/v3/tools"
	"github.com/git-lfs/git-lfs/v3/tr"
	"github.com/rubyist/tracerx"
)

const (
	LockableAttrib = "lockable"
	FilterAttrib   = "filter"
)

// 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
	// Path is handled by Git LFS (i.e., filter=lfs)
	Tracked bool
}

type AttributeSource struct {
	Path       string
	LineEnding string
}

type attrFile struct {
	path       string
	readMacros bool
}

func (s *AttributeSource) String() string {
	return s.Path
}

// GetRootAttributePaths beahves as GetRootAttributePaths, and loads information
// only from the global gitattributes file.
func GetRootAttributePaths(mp *gitattr.MacroProcessor, cfg Env) []AttributePath {
	af, _ := cfg.Get("core.attributesfile")
	af, err := tools.ExpandConfigPath(af, "git/attributes")
	if err != nil {
		return nil
	}

	if _, err := os.Stat(af); os.IsNotExist(err) {
		return nil
	}

	// The working directory for the root gitattributes file is blank.
	return attrPathsFromFile(mp, af, "", true)
}

// GetSystemAttributePaths behaves as GetAttributePaths, and loads information
// only from the system gitattributes file, respecting the $PREFIX environment
// variable.
func GetSystemAttributePaths(mp *gitattr.MacroProcessor, env Env) ([]AttributePath, error) {
	var path string
	if IsGitVersionAtLeast("2.42.0") {
		cmd, err := gitNoLFS("var", "GIT_ATTR_SYSTEM")
		if err != nil {
			return nil, errors.New(tr.Tr.Get("failed to find `git var GIT_ATTR_SYSTEM`: %v", err))
		}
		out, err := cmd.Output()
		if err != nil {
			return nil, errors.New(tr.Tr.Get("failed to call `git var GIT_ATTR_SYSTEM`: %v", err))
		}
		paths := strings.Split(string(out), "\n")
		if len(paths) == 0 {
			return nil, nil
		}
		path = paths[0]
	} else {
		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, nil
	}

	return attrPathsFromFile(mp, path, "", true), nil
}

// 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(mp *gitattr.MacroProcessor, workingDir, gitDir string) []AttributePath {
	paths := make([]AttributePath, 0)

	for _, file := range findAttributeFiles(workingDir, gitDir) {
		paths = append(paths, attrPathsFromFile(mp, file.path, workingDir, file.readMacros)...)
	}

	return paths
}

func attrPathsFromFile(mp *gitattr.MacroProcessor, path, workingDir string, readMacros bool) []AttributePath {
	attributes, err := os.Open(path)
	if err != nil {
		return nil
	}
	defer attributes.Close()
	return AttrPathsFromReader(mp, path, workingDir, attributes, readMacros)
}

func AttrPathsFromReader(mp *gitattr.MacroProcessor, fpath, workingDir string, rdr io.Reader, readMacros bool) []AttributePath {
	var paths []AttributePath

	relfile, _ := filepath.Rel(workingDir, fpath)
	// Go 1.20 now always returns ".\foo" instead of "foo" in filepath.Rel,
	// but only on Windows.  Strip the extra dot here so our paths are
	// always fully relative with no "." or ".." components.
	reldir := filepath.ToSlash(tools.TrimCurrentPrefix(filepath.Dir(relfile)))
	if reldir == "." {
		reldir = ""
	}
	source := &AttributeSource{Path: relfile}

	lines, eol, err := gitattr.ParseLines(rdr)
	if err != nil {
		return nil
	}

	patternLines := mp.ProcessLines(lines, readMacros)

	for _, line := range patternLines {
		lockable := false
		tracked := false
		hasFilter := false

		for _, attr := range line.Attrs() {
			if attr.K == FilterAttrib {
				hasFilter = true
				tracked = attr.V == "lfs"
			} else if attr.K == LockableAttrib && attr.V == "true" {
				lockable = true
			}
		}

		if !hasFilter && !lockable {
			continue
		}

		pattern := line.Pattern().String()
		if len(reldir) > 0 {
			pattern = path.Join(reldir, pattern)
		}

		paths = append(paths, AttributePath{
			Path:     pattern,
			Source:   source,
			Lockable: lockable,
			Tracked:  tracked,
		})
	}

	source.LineEnding = eol

	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(gitattr.NewMacroProcessor(), 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), filepathfilter.GitAttributes))
	}

	return filepathfilter.NewFromPatterns(patterns, nil)
}

func findAttributeFiles(workingDir, gitDir string) []attrFile {
	var paths []attrFile

	repoAttributes := filepath.Join(gitDir, "info", "attributes")
	if info, err := os.Stat(repoAttributes); err == nil && !info.IsDir() {
		paths = append(paths, attrFile{path: repoAttributes, readMacros: true})
	}

	lsFiles, err := NewLsFiles(workingDir, true, true)
	if err != nil {
		tracerx.Printf("Error finding .gitattributes: %v", err)
		return paths
	}

	if gitattributesFiles, present := lsFiles.FilesByName[".gitattributes"]; present {
		for _, f := range gitattributesFiles {
			tracerx.Printf("findAttributeFiles: located %s", f.FullPath)
			paths = append(paths, attrFile{
				path:       filepath.Join(workingDir, f.FullPath),
				readMacros: f.FullPath == ".gitattributes", // Read macros from the top-level attributes
			})
		}
	}

	// reverse the order of the files so more specific entries are found first
	// when iterating from the front (respects precedence)
	sort.Slice(paths[:], func(i, j int) bool {
		return len(paths[i].path) > len(paths[j].path)
	})

	return paths
}