File: add.go

package info (click to toggle)
gitbatch 0.6.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 644 kB
  • sloc: makefile: 5; sh: 1
file content (80 lines) | stat: -rw-r--r-- 1,647 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package command

import (
	"fmt"

	"github.com/isacikgoz/gitbatch/internal/git"
)

// AddOptions defines the rules for "git add" command
type AddOptions struct {
	// Update
	Update bool
	// Force
	Force bool
	// DryRun
	DryRun bool
	// Mode is the command mode
	CommandMode Mode
}

// Add is a wrapper function for "git add" command
func Add(r *git.Repository, f *git.File, o *AddOptions) error {
	mode := o.CommandMode
	if o.Update || o.Force || o.DryRun {
		mode = ModeLegacy
	}
	switch mode {
	case ModeLegacy:
		err := addWithGit(r, f, o)
		return err
	case ModeNative:
		err := addWithGoGit(r, f)
		return err
	}
	return fmt.Errorf("unhandled add operation")
}

// AddAll function is the wrapper of "git add ." command
func AddAll(r *git.Repository, o *AddOptions) error {
	args := make([]string, 0)
	args = append(args, "add")
	if o.DryRun {
		args = append(args, "--dry-run")
	}
	args = append(args, ".")
	_, err := Run(r.AbsPath, "git", args)
	if err != nil {
		return fmt.Errorf("could not run add function: %v", err)
	}
	return nil
}

func addWithGit(r *git.Repository, f *git.File, o *AddOptions) error {
	args := make([]string, 0)
	args = append(args, "add")
	args = append(args, f.Name)
	if o.Update {
		args = append(args, "--update")
	}
	if o.Force {
		args = append(args, "--force")
	}
	if o.DryRun {
		args = append(args, "--dry-run")
	}
	_, err := Run(r.AbsPath, "git", args)
	if err != nil {
		return fmt.Errorf("could not add %s: %v", f.AbsPath, err)
	}
	return nil
}

func addWithGoGit(r *git.Repository, f *git.File) error {
	w, err := r.Repo.Worktree()
	if err != nil {
		return err
	}
	_, err = w.Add(f.Name)
	return err
}