| 1 | package command |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | |
| 6 | "github.com/isacikgoz/gitbatch/internal/git" |
| 7 | ) |
| 8 | |
| 9 | // AddOptions defines the rules for "git add" command |
| 10 | type AddOptions struct { |
| 11 | // Update |
| 12 | Update bool |
| 13 | // Force |
| 14 | Force bool |
| 15 | // DryRun |
| 16 | DryRun bool |
| 17 | // Mode is the command mode |
| 18 | CommandMode Mode |
| 19 | } |
| 20 | |
| 21 | // Add is a wrapper function for "git add" command |
| 22 | func Add(r *git.Repository, f *git.File, o *AddOptions) error { |
| 23 | mode := o.CommandMode |
| 24 | if o.Update || o.Force || o.DryRun { |
| 25 | mode = ModeLegacy |
| 26 | } |
| 27 | switch mode { |
| 28 | case ModeLegacy: |
| 29 | err := addWithGit(r, f, o) |
| 30 | return err |
| 31 | case ModeNative: |
| 32 | err := addWithGoGit(r, f) |
| 33 | return err |
| 34 | } |
| 35 | return fmt.Errorf("unhandled add operation") |
| 36 | } |
| 37 | |
| 38 | // AddAll function is the wrapper of "git add ." command |
| 39 | func AddAll(r *git.Repository, o *AddOptions) error { |
| 40 | args := make([]string, 0) |
| 41 | args = append(args, "add") |
| 42 | if o.DryRun { |
| 43 | args = append(args, "--dry-run") |
| 44 | } |
| 45 | args = append(args, ".") |
| 46 | _, err := Run(r.AbsPath, "git", args) |
| 47 | if err != nil { |
| 48 | return fmt.Errorf("could not run add function: %v", err) |
| 49 | } |
| 50 | return nil |
| 51 | } |
| 52 | |
| 53 | func addWithGit(r *git.Repository, f *git.File, o *AddOptions) error { |
| 54 | args := make([]string, 0) |
| 55 | args = append(args, "add") |
| 56 | args = append(args, f.Name) |
| 57 | if o.Update { |
| 58 | args = append(args, "--update") |
| 59 | } |
| 60 | if o.Force { |
| 61 | args = append(args, "--force") |
| 62 | } |
| 63 | if o.DryRun { |
| 64 | args = append(args, "--dry-run") |
| 65 | } |
| 66 | _, err := Run(r.AbsPath, "git", args) |
| 67 | if err != nil { |
| 68 | return fmt.Errorf("could not add %s: %v", f.AbsPath, err) |
| 69 | } |
| 70 | return nil |
| 71 | } |
| 72 | |
| 73 | func addWithGoGit(r *git.Repository, f *git.File) error { |
| 74 | w, err := r.Repo.Worktree() |
| 75 | if err != nil { |
| 76 | return err |
| 77 | } |
| 78 | _, err = w.Add(f.Name) |
| 79 | return err |
| 80 | } |