Debian Codegraph @

internal/command/commit.go

raw symbols SCIP
1 package command
2
3 import (
4 "fmt"
5 "time"
6
7 gogit "github.com/go-git/go-git/v5"
8 "github.com/go-git/go-git/v5/plumbing/object"
9 giterr "github.com/isacikgoz/gitbatch/internal/errors"
10 "github.com/isacikgoz/gitbatch/internal/git"
11 )
12
13 // CommitOptions defines the rules for commit operation
14 type CommitOptions struct {
15 // CommitMsg
16 CommitMsg string
17 // User
18 User string
19 // Email
20 Email string
21 // Mode is the command mode
22 CommandMode Mode
23 }
24
25 // Commit defines which commit command to use.
26 func Commit(r *git.Repository, o *CommitOptions) (err error) {
27 // here we configure commit operation
28
29 switch o.CommandMode {
30 case ModeLegacy:
31 return commitWithGit(r, o)
32 case ModeNative:
33 return commitWithGoGit(r, o)
34 }
35 return fmt.Errorf("unhandled commit operation")
36 }
37
38 // commitWithGit is simply a bare git commit -m <msg> command which is flexible
39 func commitWithGit(r *git.Repository, opt *CommitOptions) (err error) {
40 args := make([]string, 0)
41 args = append(args, "commit")
42 args = append(args, "-m")
43 // parse options to command line arguments
44 if len(opt.CommitMsg) > 0 {
45 args = append(args, opt.CommitMsg)
46 }
47 if out, err := Run(r.AbsPath, "git", args); err != nil {
48 _ = r.Refresh()
49 return giterr.ParseGitError(out, err)
50 }
51 // till this step everything should be ok
52 return r.Refresh()
53 }
54
55 // commitWithGoGit is the primary commit method
56 func commitWithGoGit(r *git.Repository, options *CommitOptions) (err error) {
57 opt := &gogit.CommitOptions{
58 Author: &object.Signature{
59 Name: options.User,
60 Email: options.Email,
61 When: time.Now(),
62 },
63 Committer: &object.Signature{
64 Name: options.User,
65 Email: options.Email,
66 When: time.Now(),
67 },
68 }
69
70 w, err := r.Repo.Worktree()
71 if err != nil {
72 return err
73 }
74
75 _, err = w.Commit(options.CommitMsg, opt)
76 if err != nil {
77 _ = r.Refresh()
78 return err
79 }
80 // till this step everything should be ok
81 return r.Refresh()
82 }