-
Notifications
You must be signed in to change notification settings - Fork 1
/
commit.go
210 lines (189 loc) · 4.41 KB
/
commit.go
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
// Copyright 2020 Fazlul Shahriar. All rights reserved.
// Use of this source code is governed by the
// license that can be found in the LICENSE file.
package cli
import (
"bufio"
"bytes"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing/object"
"github.com/spf13/cobra"
)
func init() {
var cc commitCmd
cmd := &cobra.Command{
Use: "commit",
Aliases: []string{"ci"},
Short: "Record changes to the repository",
Long: `If the commit message (-m flag) is empty, a text editor will be opened to
edit the commit message. The text editor is configured by the either the
$GIT_EDITOR, $VISUAL, or $EDITOR environment variable, in that order,
falling back to a default editor if all three environment variables
are empty.
`,
RunE: cc.run,
}
cmd.Flags().StringVarP(&cc.message, "message", "m", "", "Commit message")
cmd.Flags().BoolVarP(&cc.all, "all", "a", false, "Stage modified/deleted files before commit")
rootCmd.AddCommand(cmd)
}
type commitCmd struct {
message string
all bool
}
func (cc *commitCmd) run(_ *cobra.Command, args []string) error {
root, r, err := openRepo()
if err != nil {
return err
}
w, err := r.Worktree()
if err != nil {
return err
}
status, err := w.Status()
if err != nil {
return err
}
if nothingInStaging(status) {
if !cc.all {
return fmt.Errorf(`nothing to commit (use "gig add")`)
}
if nothingInWorktree(status) {
return fmt.Errorf(`nothing to commit, working tree clean`)
}
}
name := os.Getenv("GIT_AUTHOR_NAME")
email := os.Getenv("GIT_AUTHOR_EMAIL")
if name == "" || email == "" {
cfg, err := loadRepoConfig(r)
if err != nil {
return err
}
if name == "" {
name = cfg.User.Name
}
if email == "" {
email = cfg.User.Email
}
}
if name == "" || email == "" {
fmt.Fprintf(os.Stderr, "%v\n", unknownUserMsg)
return fmt.Errorf("user's name and/or email are empty")
}
if cc.message == "" {
mfile := filepath.Join(root, ".git", "COMMIT_EDITMSG")
err := ioutil.WriteFile(mfile, []byte(emptyCommit), 0644)
if err != nil {
return err
}
err = editFile(mfile)
if err != nil {
return fmt.Errorf("editor failed: %v", err)
}
msg, err := readCommit(mfile)
if err != nil {
return err
}
if msg == "" {
return fmt.Errorf("aborting commit due to empty commit message")
}
cc.message = msg
}
_, err = w.Commit(cc.message, &git.CommitOptions{
All: cc.all,
Author: &object.Signature{
Name: name,
Email: email,
When: time.Now(),
},
})
return err
}
func nothingInStaging(s git.Status) bool {
for _, status := range s {
switch status.Staging {
case git.Unmodified, git.Untracked:
default:
return false
}
}
return true
}
func nothingInWorktree(s git.Status) bool {
for _, status := range s {
switch status.Worktree {
case git.Unmodified, git.Untracked:
default:
return false
}
}
return true
}
func editFile(filename string) error {
args := strings.Fields(preferredEditor())
if len(args) == 0 {
panic("internal error: empty editor")
}
args = append(args, filename)
cmd := exec.Command(args[0], args[1:]...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
func readCommit(filename string) (string, error) {
f, err := os.Open(filename)
if err != nil {
return "", err
}
defer f.Close()
scanner := bufio.NewScanner(f)
var msg []byte
for scanner.Scan() {
b := append(scanner.Bytes(), '\n')
if b[0] != '#' {
msg = append(msg, b...)
}
}
if err := scanner.Err(); err != nil {
return "", err
}
msg = bytes.TrimFunc(msg, func(r rune) bool { return r == '\n' })
if len(msg) > 0 {
msg = append(msg, '\n')
}
return string(msg), nil
}
func preferredEditor() string {
for _, name := range []string{
"GIT_EDITOR",
"VISUAL",
"EDITOR",
} {
if e := os.Getenv(name); e != "" {
return e
}
}
return defaultEditor()
}
var unknownUserMsg = `Author identity unknown
*** Please tell me who you are.
To set your account's default identity, write a configuration file like
the following to .git/config file or the global <HOME>/.gitconfig file:
[user]
email = gitster@example.com
name = Junio C Hamano
Alternatively, set the GIT_AUTHOR_NAME and GIT_AUTHOR_EMAIL environment
variables instead.
`
var emptyCommit = `
# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
`