| 1 | package commands |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "os" |
| 6 | "strings" |
| 7 | |
| 8 | "github.com/git-lfs/git-lfs/v3/tools" |
| 9 | "github.com/git-lfs/git-lfs/v3/tr" |
| 10 | "github.com/spf13/cobra" |
| 11 | ) |
| 12 | |
| 13 | // untrackCommand takes a list of paths as an argument, and removes each path from the |
| 14 | // default attributes file (.gitattributes), if it exists. |
| 15 | func untrackCommand(cmd *cobra.Command, args []string) { |
| 16 | setupWorkingCopy() |
| 17 | |
| 18 | installHooks(false) |
| 19 | |
| 20 | if len(args) < 1 { |
| 21 | Print("git lfs untrack <path> [path]*") |
| 22 | return |
| 23 | } |
| 24 | |
| 25 | data, err := os.ReadFile(".gitattributes") |
| 26 | if err != nil { |
| 27 | return |
| 28 | } |
| 29 | |
| 30 | attributes := strings.NewReader(string(data)) |
| 31 | |
| 32 | attributesFile, err := os.Create(".gitattributes") |
| 33 | if err != nil { |
| 34 | Print(tr.Tr.Get("Error opening '.gitattributes' for writing")) |
| 35 | return |
| 36 | } |
| 37 | defer attributesFile.Close() |
| 38 | |
| 39 | scanner := bufio.NewScanner(attributes) |
| 40 | |
| 41 | // Iterate through each line of the attributes file and rewrite it, |
| 42 | // if the path was meant to be untracked, omit it, and print a message instead. |
| 43 | for scanner.Scan() { |
| 44 | line := scanner.Text() |
| 45 | if !strings.Contains(line, "filter=lfs") { |
| 46 | attributesFile.WriteString(line + "\n") |
| 47 | continue |
| 48 | } |
| 49 | |
| 50 | path := strings.Fields(line)[0] |
| 51 | if removePath(path, args) { |
| 52 | Print(tr.Tr.Get("Untracking %q", unescapeAttrPattern(path))) |
| 53 | } else { |
| 54 | attributesFile.WriteString(line + "\n") |
| 55 | } |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | func removePath(path string, args []string) bool { |
| 60 | withoutCurrentDir := tools.TrimCurrentPrefix(path) |
| 61 | for _, t := range args { |
| 62 | if withoutCurrentDir == escapeAttrPattern(tools.TrimCurrentPrefix(t)) { |
| 63 | return true |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | return false |
| 68 | } |
| 69 | |
| 70 | func init() { |
| 71 | RegisterCommand("untrack", untrackCommand, nil) |
| 72 | } |