| 1 | package commands |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "bytes" |
| 6 | "encoding/json" |
| 7 | "fmt" |
| 8 | "os" |
| 9 | "path" |
| 10 | "path/filepath" |
| 11 | "runtime" |
| 12 | "strings" |
| 13 | "time" |
| 14 | |
| 15 | "github.com/git-lfs/git-lfs/v3/git" |
| 16 | "github.com/git-lfs/git-lfs/v3/git/gitattr" |
| 17 | "github.com/git-lfs/git-lfs/v3/tools" |
| 18 | "github.com/git-lfs/git-lfs/v3/tr" |
| 19 | "github.com/spf13/cobra" |
| 20 | ) |
| 21 | |
| 22 | var ( |
| 23 | prefixBlocklist = []string{ |
| 24 | ".git", ".lfs", |
| 25 | } |
| 26 | |
| 27 | trackLockableFlag bool |
| 28 | trackNotLockableFlag bool |
| 29 | trackVerboseLoggingFlag bool |
| 30 | trackDryRunFlag bool |
| 31 | trackNoModifyAttrsFlag bool |
| 32 | trackNoExcludedFlag bool |
| 33 | trackFilenameFlag bool |
| 34 | trackJSONFlag bool |
| 35 | ) |
| 36 | |
| 37 | func trackCommand(cmd *cobra.Command, args []string) { |
| 38 | requireGitVersion() |
| 39 | setupWorkingCopy() |
| 40 | |
| 41 | if trackDryRunFlag { |
| 42 | trackNoModifyAttrsFlag = true |
| 43 | } |
| 44 | |
| 45 | if !cfg.Os.Bool("GIT_LFS_TRACK_NO_INSTALL_HOOKS", false) { |
| 46 | installHooks(false) |
| 47 | } |
| 48 | |
| 49 | if len(args) == 0 { |
| 50 | listPatterns() |
| 51 | return |
| 52 | } |
| 53 | |
| 54 | if trackJSONFlag { |
| 55 | Exit(tr.Tr.Get("--json option can't be combined with arguments")) |
| 56 | } |
| 57 | |
| 58 | mp := gitattr.NewMacroProcessor() |
| 59 | |
| 60 | // Intentionally do _not_ consider global- and system-level |
| 61 | // .gitattributes here. Parse them still to expand any macros. |
| 62 | gitattr.GetSystemAttributePaths(mp, cfg.Os) |
| 63 | gitattr.GetUserAttributePaths(mp, cfg.Git) |
| 64 | knownPatterns := gitattr.GetAttributePaths(mp, cfg.LocalWorkingDir(), cfg.LocalGitDir()) |
| 65 | lineEnd := getAttributeLineEnding(knownPatterns) |
| 66 | if len(lineEnd) == 0 { |
| 67 | lineEnd = gitLineEnding(cfg.Git) |
| 68 | } |
| 69 | |
| 70 | wd, _ := tools.Getwd() |
| 71 | wd = tools.ResolveSymlinks(wd) |
| 72 | relpath, err := filepath.Rel(cfg.LocalWorkingDir(), wd) |
| 73 | if err != nil { |
| 74 | Exit(tr.Tr.Get("Current directory %q outside of Git working directory %q.", wd, cfg.LocalWorkingDir())) |
| 75 | } |
| 76 | |
| 77 | changedAttribLines := make(map[string]string) |
| 78 | var readOnlyPatterns []string |
| 79 | var writeablePatterns []string |
| 80 | ArgsLoop: |
| 81 | for _, unsanitizedPattern := range args { |
| 82 | pattern := tools.TrimCurrentPrefix(cleanRootPath(unsanitizedPattern)) |
| 83 | |
| 84 | // Generate the new / changed attrib line for merging |
| 85 | var encodedArg string |
| 86 | if trackFilenameFlag { |
| 87 | encodedArg = escapeGlobCharacters(pattern) |
| 88 | pattern = escapeGlobCharacters(pattern) |
| 89 | } else { |
| 90 | encodedArg = escapeAttrPattern(pattern) |
| 91 | } |
| 92 | |
| 93 | if !trackNoModifyAttrsFlag { |
| 94 | for _, known := range knownPatterns { |
| 95 | if unescapeAttrPattern(known.Path) == path.Join(relpath, pattern) && |
| 96 | ((trackLockableFlag && known.Lockable) || // enabling lockable & already lockable (no change) |
| 97 | (trackNotLockableFlag && !known.Lockable) || // disabling lockable & not lockable (no change) |
| 98 | (!trackLockableFlag && !trackNotLockableFlag)) { // leave lockable as-is in all cases |
| 99 | Print(tr.Tr.Get("%q already supported", pattern)) |
| 100 | continue ArgsLoop |
| 101 | } |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | lockableArg := "" |
| 106 | if trackLockableFlag { // no need to test trackNotLockableFlag, if we got here we're disabling |
| 107 | lockableArg = " " + gitattr.LockableAttrib |
| 108 | } |
| 109 | |
| 110 | changedAttribLines[pattern] = fmt.Sprintf("%s filter=lfs diff=lfs merge=lfs -text%v%s", encodedArg, lockableArg, lineEnd) |
| 111 | |
| 112 | if trackLockableFlag { |
| 113 | readOnlyPatterns = append(readOnlyPatterns, pattern) |
| 114 | } else { |
| 115 | writeablePatterns = append(writeablePatterns, pattern) |
| 116 | } |
| 117 | |
| 118 | Print(tr.Tr.Get("Tracking %q", unescapeAttrPattern(encodedArg))) |
| 119 | } |
| 120 | |
| 121 | // Now read the whole local attributes file and iterate over the contents, |
| 122 | // replacing any lines where the values have changed, and appending new lines |
| 123 | // change this: |
| 124 | |
| 125 | var ( |
| 126 | attribContents []byte |
| 127 | attributesFile *os.File |
| 128 | ) |
| 129 | if !trackNoModifyAttrsFlag { |
| 130 | attribContents, err = os.ReadFile(".gitattributes") |
| 131 | // it's fine for file to not exist |
| 132 | if err != nil && !os.IsNotExist(err) { |
| 133 | Print(tr.Tr.Get("Error reading '.gitattributes' file")) |
| 134 | return |
| 135 | } |
| 136 | // Re-generate the file with merge of old contents and new (to deal with changes) |
| 137 | attributesFile, err = os.OpenFile(".gitattributes", os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0660) |
| 138 | if err != nil { |
| 139 | Print(tr.Tr.Get("Error opening '.gitattributes' file")) |
| 140 | return |
| 141 | } |
| 142 | defer attributesFile.Close() |
| 143 | |
| 144 | if len(attribContents) > 0 { |
| 145 | scanner := bufio.NewScanner(bytes.NewReader(attribContents)) |
| 146 | for scanner.Scan() { |
| 147 | line := scanner.Text() |
| 148 | fields := strings.Fields(line) |
| 149 | if len(fields) < 1 { |
| 150 | continue |
| 151 | } |
| 152 | |
| 153 | pattern := unescapeAttrPattern(fields[0]) |
| 154 | if newline, ok := changedAttribLines[pattern]; ok { |
| 155 | // Replace this line (newline already embedded) |
| 156 | attributesFile.WriteString(newline) |
| 157 | // Remove from map so we know we don't have to add it to the end |
| 158 | delete(changedAttribLines, pattern) |
| 159 | } else { |
| 160 | // Write line unchanged (replace newline) |
| 161 | attributesFile.WriteString(line + lineEnd) |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | // Our method of writing also made sure there's always a newline at end |
| 166 | } |
| 167 | } |
| 168 | |
| 169 | modified := false |
| 170 | sawError := false |
| 171 | // Any items left in the map, write new lines at the end of the file |
| 172 | // Note this is only new patterns, not ones which changed locking flags |
| 173 | for pattern, newline := range changedAttribLines { |
| 174 | // Also, for any new patterns we've added, make sure any existing git |
| 175 | // tracked files have their timestamp updated so they will now show as |
| 176 | // modified note this is relative to current dir which is how we write |
| 177 | // .gitattributes deliberately not done in parallel as a chan because |
| 178 | // we'll be marking modified |
| 179 | // |
| 180 | // NOTE: `git ls-files` does not do well with leading slashes. |
| 181 | // Since all `git-lfs track` calls are relative to the root of |
| 182 | // the repository, the leading slash is simply removed for its |
| 183 | // implicit counterpart. |
| 184 | if trackVerboseLoggingFlag { |
| 185 | Print(tr.Tr.Get("Searching for files matching pattern: %s", pattern)) |
| 186 | } |
| 187 | |
| 188 | gittracked, err := git.GetTrackedFiles(pattern) |
| 189 | if err != nil { |
| 190 | Exit(tr.Tr.Get("Error getting tracked files for %q: %s", pattern, err)) |
| 191 | } |
| 192 | |
| 193 | if trackVerboseLoggingFlag { |
| 194 | Print(tr.Tr.Get("Found %d files previously added to Git matching pattern: %s", len(gittracked), pattern)) |
| 195 | } |
| 196 | |
| 197 | var matchedBlocklist bool |
| 198 | for _, f := range gittracked { |
| 199 | if forbidden := blocklistItem(f); forbidden != "" { |
| 200 | Print(tr.Tr.Get("Pattern '%s' matches forbidden file '%s'. If you would like to track %s, modify '.gitattributes' manually.", pattern, f, f)) |
| 201 | matchedBlocklist = true |
| 202 | } |
| 203 | } |
| 204 | if matchedBlocklist { |
| 205 | continue |
| 206 | } |
| 207 | |
| 208 | if !trackNoModifyAttrsFlag { |
| 209 | // Newline already embedded |
| 210 | attributesFile.WriteString(newline) |
| 211 | } |
| 212 | modified = true |
| 213 | |
| 214 | for _, f := range gittracked { |
| 215 | if trackVerboseLoggingFlag || trackDryRunFlag { |
| 216 | Print(tr.Tr.Get("Touching %q", f)) |
| 217 | } |
| 218 | |
| 219 | if !trackDryRunFlag { |
| 220 | now := time.Now() |
| 221 | err := os.Chtimes(f, now, now) |
| 222 | if err != nil { |
| 223 | LoggedError(err, tr.Tr.Get("Error marking %q modified: %s", f, err)) |
| 224 | sawError = true |
| 225 | continue |
| 226 | } |
| 227 | } |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | // now flip read-only mode based on lockable / not lockable changes |
| 232 | lockClient := newLockClient() |
| 233 | err = lockClient.FixFileWriteFlagsInDir(relpath, readOnlyPatterns, writeablePatterns) |
| 234 | if err != nil { |
| 235 | LoggedError(err, tr.Tr.Get("Error changing lockable file permissions: %s", err)) |
| 236 | sawError = true |
| 237 | } |
| 238 | |
| 239 | if sawError { |
| 240 | ExitWithCode(2) |
| 241 | } |
| 242 | // If we didn't modify things, but that's because the patterns |
| 243 | // were already supported, don't return an error, since what the |
| 244 | // user wanted has already been done. |
| 245 | // Otherwise, if we didn't modify things but only because the |
| 246 | // patterns were disallowed, return an error. |
| 247 | if !modified && len(changedAttribLines) > 0 { |
| 248 | ExitWithCode(1) |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | type PatternData struct { |
| 253 | Pattern string `json:"pattern"` |
| 254 | Source string `json:"source"` |
| 255 | Lockable bool `json:"lockable"` |
| 256 | Tracked bool `json:"tracked"` |
| 257 | } |
| 258 | |
| 259 | func listPatterns() { |
| 260 | knownPatterns, err := getAllKnownPatterns() |
| 261 | if err != nil { |
| 262 | Exit("unable to list patterns: %s", err) |
| 263 | } |
| 264 | if trackJSONFlag { |
| 265 | patterns := struct { |
| 266 | Patterns []PatternData `json:"patterns"` |
| 267 | }{Patterns: make([]PatternData, 0, len(knownPatterns))} |
| 268 | for _, p := range knownPatterns { |
| 269 | patterns.Patterns = append(patterns.Patterns, PatternData{ |
| 270 | Pattern: p.Path, |
| 271 | Source: p.Source.String(), |
| 272 | Tracked: p.Tracked, |
| 273 | Lockable: p.Lockable, |
| 274 | }) |
| 275 | } |
| 276 | encoder := json.NewEncoder(os.Stdout) |
| 277 | encoder.SetIndent("", " ") |
| 278 | err := encoder.Encode(patterns) |
| 279 | if err != nil { |
| 280 | ExitWithError(err) |
| 281 | } |
| 282 | return |
| 283 | } |
| 284 | |
| 285 | if len(knownPatterns) < 1 { |
| 286 | return |
| 287 | } |
| 288 | |
| 289 | Print(tr.Tr.Get("Listing tracked patterns")) |
| 290 | for _, t := range knownPatterns { |
| 291 | if t.Lockable { |
| 292 | // TRANSLATORS: Leading spaces here should be preserved. |
| 293 | Print(tr.Tr.Get(" %s [lockable] (%s)", t.Path, t.Source)) |
| 294 | } else if t.Tracked { |
| 295 | Print(" %s (%s)", t.Path, t.Source) |
| 296 | } |
| 297 | } |
| 298 | |
| 299 | if trackNoExcludedFlag { |
| 300 | return |
| 301 | } |
| 302 | |
| 303 | Print(tr.Tr.Get("Listing excluded patterns")) |
| 304 | for _, t := range knownPatterns { |
| 305 | if !t.Tracked && !t.Lockable { |
| 306 | Print(" %s (%s)", t.Path, t.Source) |
| 307 | } |
| 308 | } |
| 309 | } |
| 310 | |
| 311 | func getAllKnownPatterns() ([]gitattr.AttributePath, error) { |
| 312 | mp := gitattr.NewMacroProcessor() |
| 313 | |
| 314 | // Parse these in this order so that macros in one file are properly |
| 315 | // expanded when referred to in a later file, then order them in the |
| 316 | // order we want. |
| 317 | systemPatterns, err := gitattr.GetSystemAttributePaths(mp, cfg.Os) |
| 318 | if err != nil { |
| 319 | return nil, err |
| 320 | } |
| 321 | userPatterns, err := gitattr.GetUserAttributePaths(mp, cfg.Git) |
| 322 | if err != nil { |
| 323 | return nil, err |
| 324 | } |
| 325 | knownPatterns := gitattr.GetAttributePaths(mp, cfg.LocalWorkingDir(), cfg.LocalGitDir()) |
| 326 | knownPatterns = append(knownPatterns, userPatterns...) |
| 327 | knownPatterns = append(knownPatterns, systemPatterns...) |
| 328 | |
| 329 | return knownPatterns, nil |
| 330 | } |
| 331 | |
| 332 | func getAttributeLineEnding(attribs []gitattr.AttributePath) string { |
| 333 | for _, a := range attribs { |
| 334 | if a.Source.Path == ".gitattributes" { |
| 335 | return a.Source.LineEnding |
| 336 | } |
| 337 | } |
| 338 | return "" |
| 339 | } |
| 340 | |
| 341 | // blocklistItem returns the name of the blocklist item preventing the given |
| 342 | // file-name from being tracked, or an empty string, if there is none. |
| 343 | func blocklistItem(name string) string { |
| 344 | base := filepath.Base(name) |
| 345 | |
| 346 | for _, p := range prefixBlocklist { |
| 347 | if strings.HasPrefix(base, p) { |
| 348 | return p |
| 349 | } |
| 350 | } |
| 351 | |
| 352 | return "" |
| 353 | } |
| 354 | |
| 355 | var ( |
| 356 | trackEscapePatterns = map[string]string{ |
| 357 | " ": "[[:space:]]", |
| 358 | "#": "\\#", |
| 359 | } |
| 360 | trackEscapeStrings = []string{"*", "[", "]", "?"} |
| 361 | ) |
| 362 | |
| 363 | func escapeGlobCharacters(s string) string { |
| 364 | var escaped string |
| 365 | if runtime.GOOS == "windows" { |
| 366 | escaped = strings.Replace(s, `\`, "/", -1) |
| 367 | } else { |
| 368 | escaped = strings.Replace(s, `\`, `\\`, -1) |
| 369 | } |
| 370 | |
| 371 | for _, ch := range trackEscapeStrings { |
| 372 | escaped = strings.Replace(escaped, ch, fmt.Sprintf("\\%s", ch), -1) |
| 373 | } |
| 374 | |
| 375 | for from, to := range trackEscapePatterns { |
| 376 | escaped = strings.Replace(escaped, from, to, -1) |
| 377 | } |
| 378 | return escaped |
| 379 | } |
| 380 | |
| 381 | func escapeAttrPattern(s string) string { |
| 382 | var escaped string |
| 383 | if runtime.GOOS == "windows" { |
| 384 | escaped = strings.Replace(s, `\`, "/", -1) |
| 385 | } else { |
| 386 | escaped = strings.Replace(s, `\`, `\\`, -1) |
| 387 | } |
| 388 | |
| 389 | for from, to := range trackEscapePatterns { |
| 390 | escaped = strings.Replace(escaped, from, to, -1) |
| 391 | } |
| 392 | |
| 393 | return escaped |
| 394 | } |
| 395 | |
| 396 | func unescapeAttrPattern(escaped string) string { |
| 397 | var unescaped string = escaped |
| 398 | |
| 399 | for to, from := range trackEscapePatterns { |
| 400 | unescaped = strings.Replace(unescaped, from, to, -1) |
| 401 | } |
| 402 | |
| 403 | if runtime.GOOS != "windows" { |
| 404 | unescaped = strings.Replace(unescaped, `\\`, `\`, -1) |
| 405 | } |
| 406 | |
| 407 | return unescaped |
| 408 | } |
| 409 | |
| 410 | func init() { |
| 411 | RegisterCommand("track", trackCommand, func(cmd *cobra.Command) { |
| 412 | cmd.Flags().BoolVarP(&trackLockableFlag, "lockable", "l", false, "make pattern lockable, i.e. read-only unless locked") |
| 413 | cmd.Flags().BoolVarP(&trackNotLockableFlag, "not-lockable", "", false, "remove lockable attribute from pattern") |
| 414 | cmd.Flags().BoolVarP(&trackVerboseLoggingFlag, "verbose", "v", false, "log which files are being tracked and modified") |
| 415 | cmd.Flags().BoolVarP(&trackDryRunFlag, "dry-run", "d", false, "preview results of running `git lfs track`") |
| 416 | cmd.Flags().BoolVarP(&trackNoModifyAttrsFlag, "no-modify-attrs", "", false, "skip modifying .gitattributes file") |
| 417 | cmd.Flags().BoolVarP(&trackNoExcludedFlag, "no-excluded", "", false, "skip listing excluded paths") |
| 418 | cmd.Flags().BoolVarP(&trackFilenameFlag, "filename", "", false, "treat this pattern as a literal filename") |
| 419 | cmd.Flags().BoolVarP(&trackJSONFlag, "json", "j", false, "print output in JSON") |
| 420 | }) |
| 421 | } |