summaryrefslogtreecommitdiff
path: root/core/command/cmd-add.go
blob: 2addb23e21114c26abc7021c4e7763749626d5c6 (about) (plain)
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
81
82
83
84
85
86
87
88
89
package command

import (
	"errors"

	"github.com/isacikgoz/gitbatch/core/git"
	log "github.com/sirupsen/logrus"
)

var (
	addCmdMode string

	addCommand       = "add"
	addCmdModeLegacy = "git"
	addCmdModeNative = "go-git"
)

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

// Add is a wrapper function for "git add" command
func Add(e *git.RepoEntity, file *File, option AddOptions) error {
	addCmdMode = addCmdModeNative
	if option.Update || option.Force || option.DryRun {
		addCmdMode = addCmdModeLegacy
	}
	switch addCmdMode {
	case addCmdModeLegacy:
		err := addWithGit(e, file, option)
		return err
	case addCmdModeNative:
		err := addWithGoGit(e, file)
		return err
	}
	return errors.New("Unhandled add operation")
}

// AddAll function is the wrapper of "git add ." command
func AddAll(e *git.RepoEntity, option AddOptions) error {
	args := make([]string, 0)
	args = append(args, addCommand)
	if option.DryRun {
		args = append(args, "--dry-run")
	}
	args = append(args, ".")
	out, err := GenericGitCommandWithOutput(e.AbsPath, args)
	if err != nil {
		log.Warn("Error while add command")
		return errors.New(out + "\n" + err.Error())
	}
	return nil
}

func addWithGit(e *git.RepoEntity, file *File, option AddOptions) error {
	args := make([]string, 0)
	args = append(args, addCommand)
	args = append(args, file.Name)
	if option.Update {
		args = append(args, "--update")
	}
	if option.Force {
		args = append(args, "--force")
	}
	if option.DryRun {
		args = append(args, "--dry-run")
	}
	out, err := GenericGitCommandWithOutput(e.AbsPath, args)
	if err != nil {
		log.Warn("Error while add command")
		return errors.New(out + "\n" + err.Error())
	}
	return nil
}

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