| 1 | package gitattr |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "io" |
| 6 | "os" |
| 7 | "path" |
| 8 | "path/filepath" |
| 9 | "sort" |
| 10 | "strings" |
| 11 | |
| 12 | "github.com/git-lfs/git-lfs/v3/filepathfilter" |
| 13 | "github.com/git-lfs/git-lfs/v3/git" |
| 14 | "github.com/git-lfs/git-lfs/v3/tools" |
| 15 | "github.com/git-lfs/git-lfs/v3/tr" |
| 16 | "github.com/rubyist/tracerx" |
| 17 | ) |
| 18 | |
| 19 | const ( |
| 20 | LockableAttrib = "lockable" |
| 21 | FilterAttrib = "filter" |
| 22 | ) |
| 23 | |
| 24 | // AttributePath is a path entry in a gitattributes file which has the LFS filter |
| 25 | type AttributePath struct { |
| 26 | // Path entry in the attribute file |
| 27 | Path string |
| 28 | // The attribute file which was the source of this entry |
| 29 | Source *AttributeSource |
| 30 | // Path also has the 'lockable' attribute |
| 31 | Lockable bool |
| 32 | // Path is handled by Git LFS (i.e., filter=lfs) |
| 33 | Tracked bool |
| 34 | } |
| 35 | |
| 36 | type AttributeSource struct { |
| 37 | Path string |
| 38 | LineEnding string |
| 39 | } |
| 40 | |
| 41 | type attrFile struct { |
| 42 | path string |
| 43 | readMacros bool |
| 44 | } |
| 45 | |
| 46 | func (s *AttributeSource) String() string { |
| 47 | return s.Path |
| 48 | } |
| 49 | |
| 50 | // GetUserAttributePaths behaves as GetAttributePaths, and loads information |
| 51 | // only from the user's global attributes file. |
| 52 | func GetUserAttributePaths(mp *MacroProcessor, gitEnv Environment) ([]AttributePath, error) { |
| 53 | path, err := GetUserAttributeFilePath(gitEnv) |
| 54 | if err != nil || len(path) == 0 { |
| 55 | return nil, err |
| 56 | } |
| 57 | |
| 58 | reader, err := os.Open(path) |
| 59 | if err != nil { |
| 60 | return nil, err |
| 61 | } |
| 62 | defer reader.Close() |
| 63 | // The working directory for the user gitattributes file is blank. |
| 64 | return AttrPathsFromReader(mp, path, "", reader, true), nil |
| 65 | } |
| 66 | |
| 67 | func GetUserAttributeFilePath(gitEnv Environment) (string, error) { |
| 68 | path, _ := gitEnv.Get("core.attributesfile") |
| 69 | path, err := tools.ExpandConfigPath(path, "git/attributes") |
| 70 | if err != nil { |
| 71 | return "", err |
| 72 | } |
| 73 | if _, err := os.Stat(path); os.IsNotExist(err) { |
| 74 | return "", nil |
| 75 | } |
| 76 | return path, nil |
| 77 | } |
| 78 | |
| 79 | func GetRepoAttributeFilePath(gitDir string) (string, error) { |
| 80 | path := filepath.Join(gitDir, "info", "attributes") |
| 81 | |
| 82 | if _, err := os.Stat(path); os.IsNotExist(err) { |
| 83 | return "", nil |
| 84 | } |
| 85 | return path, nil |
| 86 | } |
| 87 | |
| 88 | // GetSystemAttributePaths behaves as GetAttributePaths, and loads information |
| 89 | // only from the system gitattributes file, respecting the $PREFIX environment |
| 90 | // variable. |
| 91 | func GetSystemAttributePaths(mp *MacroProcessor, env Environment) ([]AttributePath, error) { |
| 92 | path, err := GetSystemAttributeFilePath(env) |
| 93 | if err != nil || len(path) == 0 { |
| 94 | return nil, err |
| 95 | } |
| 96 | |
| 97 | reader, err := os.Open(path) |
| 98 | if err != nil { |
| 99 | return nil, err |
| 100 | } |
| 101 | defer reader.Close() |
| 102 | // The working directory for the system gitattributes file is blank. |
| 103 | return AttrPathsFromReader(mp, path, "", reader, true), nil |
| 104 | } |
| 105 | |
| 106 | func GetSystemAttributeFilePath(osEnv Environment) (string, error) { |
| 107 | var path string |
| 108 | if git.IsGitVersionAtLeast("2.42.0") { |
| 109 | cmd, err := git.Var("GIT_ATTR_SYSTEM") |
| 110 | if err != nil { |
| 111 | return "", errors.New(tr.Tr.Get("failed to find `git var GIT_ATTR_SYSTEM`: %v", err)) |
| 112 | } |
| 113 | out, err := cmd.Output() |
| 114 | if err != nil { |
| 115 | return "", errors.New(tr.Tr.Get("failed to call `git var GIT_ATTR_SYSTEM`: %v", err)) |
| 116 | } |
| 117 | paths := strings.Split(string(out), "\n") |
| 118 | if len(paths) == 0 { |
| 119 | return "", nil |
| 120 | } |
| 121 | path = paths[0] |
| 122 | } else { |
| 123 | prefix, _ := osEnv.Get("PREFIX") |
| 124 | if len(prefix) == 0 { |
| 125 | prefix = string(filepath.Separator) |
| 126 | } |
| 127 | |
| 128 | path = filepath.Join(prefix, "etc", "gitattributes") |
| 129 | } |
| 130 | |
| 131 | if _, err := os.Stat(path); os.IsNotExist(err) { |
| 132 | return "", nil |
| 133 | } |
| 134 | |
| 135 | return path, nil |
| 136 | } |
| 137 | |
| 138 | // GetAttributePaths returns a list of entries in .gitattributes which are |
| 139 | // configured with the filter=lfs attribute |
| 140 | // workingDir is the root of the working copy |
| 141 | // gitDir is the root of the git repo |
| 142 | func GetAttributePaths(mp *MacroProcessor, workingDir, gitDir string) []AttributePath { |
| 143 | paths := make([]AttributePath, 0) |
| 144 | |
| 145 | for _, file := range findAttributeFiles(workingDir, gitDir) { |
| 146 | paths = append(paths, attrPathsFromFile(mp, file.path, workingDir, file.readMacros)...) |
| 147 | } |
| 148 | |
| 149 | return paths |
| 150 | } |
| 151 | |
| 152 | func attrPathsFromFile(mp *MacroProcessor, path, workingDir string, readMacros bool) []AttributePath { |
| 153 | attributes, err := os.Open(path) |
| 154 | if err != nil { |
| 155 | return nil |
| 156 | } |
| 157 | defer attributes.Close() |
| 158 | return AttrPathsFromReader(mp, path, workingDir, attributes, readMacros) |
| 159 | } |
| 160 | |
| 161 | func AttrPathsFromReader(mp *MacroProcessor, fpath, workingDir string, rdr io.Reader, readMacros bool) []AttributePath { |
| 162 | var paths []AttributePath |
| 163 | |
| 164 | relfile, _ := filepath.Rel(workingDir, fpath) |
| 165 | // Go 1.20 now always returns ".\foo" instead of "foo" in filepath.Rel, |
| 166 | // but only on Windows. Strip the extra dot here so our paths are |
| 167 | // always fully relative with no "." or ".." components. |
| 168 | reldir := filepath.ToSlash(tools.TrimCurrentPrefix(filepath.Dir(relfile))) |
| 169 | if reldir == "." { |
| 170 | reldir = "" |
| 171 | } |
| 172 | source := &AttributeSource{Path: relfile} |
| 173 | |
| 174 | lines, eol, err := ParseLines(rdr) |
| 175 | if err != nil { |
| 176 | tracerx.Printf("Error parsing attributes from %s: %v", fpath, err) |
| 177 | return nil |
| 178 | } |
| 179 | |
| 180 | patternLines := mp.ProcessLines(lines, readMacros) |
| 181 | |
| 182 | for _, line := range patternLines { |
| 183 | lockable := false |
| 184 | tracked := false |
| 185 | hasFilter := false |
| 186 | |
| 187 | for _, attr := range line.Attrs() { |
| 188 | if attr.K == FilterAttrib { |
| 189 | hasFilter = true |
| 190 | tracked = attr.V == "lfs" |
| 191 | } else if attr.K == LockableAttrib && attr.V == "true" { |
| 192 | lockable = true |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | if !hasFilter && !lockable { |
| 197 | continue |
| 198 | } |
| 199 | |
| 200 | pattern := line.Pattern().String() |
| 201 | if len(reldir) > 0 { |
| 202 | pattern = path.Join(reldir, pattern) |
| 203 | } |
| 204 | |
| 205 | paths = append(paths, AttributePath{ |
| 206 | Path: pattern, |
| 207 | Source: source, |
| 208 | Lockable: lockable, |
| 209 | Tracked: tracked, |
| 210 | }) |
| 211 | } |
| 212 | |
| 213 | source.LineEnding = eol |
| 214 | |
| 215 | return paths |
| 216 | } |
| 217 | |
| 218 | // GetAttributeFilter returns a list of entries in .gitattributes which are |
| 219 | // configured with the filter=lfs attribute as a file path filter which |
| 220 | // file paths can be matched against |
| 221 | // workingDir is the root of the working copy |
| 222 | // gitDir is the root of the git repo |
| 223 | func GetAttributeFilter(gitEnv filepathfilter.Environment, workingDir, gitDir string) *filepathfilter.Filter { |
| 224 | paths := GetAttributePaths(NewMacroProcessor(), workingDir, gitDir) |
| 225 | patterns := make([]filepathfilter.Pattern, 0, len(paths)) |
| 226 | |
| 227 | for _, path := range paths { |
| 228 | // Convert all separators to `/` before creating a pattern to |
| 229 | // avoid characters being escaped in situations like `subtree\*.md` |
| 230 | patterns = append(patterns, filepathfilter.NewPattern(filepath.ToSlash(path.Path), filepathfilter.GitAttributes, gitEnv)) |
| 231 | } |
| 232 | |
| 233 | return filepathfilter.NewFromPatterns(patterns, nil) |
| 234 | } |
| 235 | |
| 236 | // findAttributeFiles finds all attributes files in the repository, starting with the repository-wide attributes |
| 237 | // file, and then any .gitattributes files in the working tree |
| 238 | func findAttributeFiles(workingDir, gitDir string) []attrFile { |
| 239 | var paths []attrFile |
| 240 | |
| 241 | repoAttributes := filepath.Join(gitDir, "info", "attributes") |
| 242 | if info, err := os.Stat(repoAttributes); err == nil && !info.IsDir() { |
| 243 | paths = append(paths, attrFile{path: repoAttributes, readMacros: true}) |
| 244 | } |
| 245 | |
| 246 | lsFiles, err := git.NewLsFiles(workingDir, true, true) |
| 247 | if err != nil { |
| 248 | tracerx.Printf("Error finding .gitattributes: %v", err) |
| 249 | return paths |
| 250 | } |
| 251 | |
| 252 | if gitattributesFiles, present := lsFiles.FilesByName[".gitattributes"]; present { |
| 253 | for _, f := range gitattributesFiles { |
| 254 | tracerx.Printf("findAttributeFiles: located %s", f.FullPath) |
| 255 | paths = append(paths, attrFile{ |
| 256 | path: filepath.Join(workingDir, f.FullPath), |
| 257 | readMacros: f.FullPath == ".gitattributes", // Read macros from the top-level attributes |
| 258 | }) |
| 259 | } |
| 260 | } |
| 261 | |
| 262 | // reverse the order of the files so more specific entries are found first |
| 263 | // when iterating from the front (respects precedence) |
| 264 | sort.Slice(paths[:], func(i, j int) bool { |
| 265 | return len(paths[i].path) > len(paths[j].path) |
| 266 | }) |
| 267 | |
| 268 | return paths |
| 269 | } |