|
| 1 | +package git |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "os/exec" |
| 6 | +) |
| 7 | + |
| 8 | +func executeGitCommand(args []string) error { |
| 9 | + cmd := exec.Command("git", args...) |
| 10 | + |
| 11 | + out, err := cmd.CombinedOutput() |
| 12 | + |
| 13 | + if err != nil { |
| 14 | + return fmt.Errorf("[Error] Failed to run Skip Worktree: %s", out) |
| 15 | + } |
| 16 | + |
| 17 | + return nil |
| 18 | +} |
| 19 | + |
| 20 | +func SkipWorkTree(files []string) error { |
| 21 | + |
| 22 | + filesToSkip := sanitizeToTrackedFiles(files) |
| 23 | + if len(filesToSkip) == 0 { |
| 24 | + return fmt.Errorf("[Error] No files listed in config are being tracked by git") |
| 25 | + } |
| 26 | + skipWorktreeArgs := append( |
| 27 | + []string{ |
| 28 | + "update-index", |
| 29 | + "--skip-worktree", |
| 30 | + }, |
| 31 | + filesToSkip..., |
| 32 | + ) |
| 33 | + return executeGitCommand(skipWorktreeArgs) |
| 34 | +} |
| 35 | + |
| 36 | +func NoSkipWorkTree(files []string) error { |
| 37 | + |
| 38 | + filesToRevert := sanitizeToTrackedFiles(files) |
| 39 | + if len(filesToRevert) == 0 { |
| 40 | + return fmt.Errorf("[Error] No files listed in config are being tracked by git") |
| 41 | + } |
| 42 | + skipWorktreeArgs := append( |
| 43 | + []string{ |
| 44 | + "update-index", |
| 45 | + "--no-skip-worktree", |
| 46 | + }, |
| 47 | + filesToRevert..., |
| 48 | + ) |
| 49 | + return executeGitCommand(skipWorktreeArgs) |
| 50 | +} |
| 51 | + |
| 52 | +func isFileTracked(file string) bool { |
| 53 | + trackCheckArgs := []string{ |
| 54 | + "ls-files", |
| 55 | + "--error-unmatch", |
| 56 | + file, |
| 57 | + } |
| 58 | + |
| 59 | + err := executeGitCommand(trackCheckArgs) |
| 60 | + |
| 61 | + return err == nil |
| 62 | +} |
| 63 | + |
| 64 | +func sanitizeToTrackedFiles(files []string) []string { |
| 65 | + |
| 66 | + filesTracked := []string{} |
| 67 | + |
| 68 | + for _, file := range files { |
| 69 | + if isFileTracked(file) { |
| 70 | + filesTracked = append(filesTracked, file) |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + return filesTracked |
| 75 | + |
| 76 | +} |
0 commit comments