/
log.go
337 lines (306 loc) · 8.2 KB
/
log.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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
// Copyright 2018 The gg Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package git
import (
"bufio"
"bytes"
"context"
"errors"
"fmt"
"io"
"strings"
"time"
)
// CommitInfo stores information about a single commit.
type CommitInfo struct {
Hash Hash
Parents []Hash
Author User
Committer User
AuthorTime time.Time
CommitTime time.Time
Message string
}
// Summary returns the first line of the message.
func (c *CommitInfo) Summary() string {
i := strings.IndexByte(c.Message, '\n')
if i == -1 {
return c.Message
}
return c.Message[:i]
}
// User identifies an author or committer.
type User struct {
// Name is the user's full name.
Name string
// Email is the user's email address.
Email string
}
// String returns the user information as a string in the
// form "User Name <foo@example.com>".
func (u User) String() string {
return fmt.Sprintf("%s <%s>", u.Name, u.Email)
}
// CommitInfo obtains information about a single commit.
func (g *Git) CommitInfo(ctx context.Context, rev string) (*CommitInfo, error) {
errPrefix := fmt.Sprintf("git log %q", rev)
if err := validateRev(rev); err != nil {
return nil, fmt.Errorf("%s: %w", errPrefix, err)
}
if strings.HasPrefix(rev, "^") {
return nil, fmt.Errorf("%s: revision cannot be an exclusion", errPrefix)
}
if strings.Contains(rev, "..") {
return nil, fmt.Errorf("%s: revision cannot be a range", errPrefix)
}
if strings.HasSuffix(rev, "^@") {
return nil, fmt.Errorf("%s: revision cannot use parent shorthand", errPrefix)
}
out, err := g.output(ctx, errPrefix, []string{
"log",
"--max-count=1",
"-z",
"--pretty=" + commitInfoPrettyFormat,
rev,
"--",
})
if err != nil {
return nil, err
}
info, err := parseCommitInfo(out)
if err != nil {
return nil, fmt.Errorf("%s: %w", errPrefix, err)
}
return info, nil
}
const (
commitInfoPrettyFormat = "tformat:%H%x00%P%x00%an%x00%ae%x00%aI%x00%cn%x00%ce%x00%cI%x00%B"
commitInfoFieldCount = 9
)
func parseCommitInfo(out string) (*CommitInfo, error) {
if !strings.HasSuffix(out, "\x00") {
return nil, errors.New("parse commit: invalid format")
}
fields := strings.Split(out[:len(out)-1], "\x00")
if len(fields) != commitInfoFieldCount {
return nil, errors.New("parse commit: invalid format")
}
hash, err := ParseHash(fields[0])
if err != nil {
return nil, fmt.Errorf("parse commit: hash: %w", err)
}
var parents []Hash
if parentStrings := strings.Fields(fields[1]); len(parentStrings) > 0 {
parents = make([]Hash, 0, len(parentStrings))
for _, s := range parentStrings {
p, err := ParseHash(s)
if err != nil {
return nil, fmt.Errorf("parse commit: parents: %w", err)
}
parents = append(parents, p)
}
}
authorTime, err := time.Parse(time.RFC3339, fields[4])
if err != nil {
return nil, fmt.Errorf("parse commit: author time: %w", err)
}
commitTime, err := time.Parse(time.RFC3339, fields[7])
if err != nil {
return nil, fmt.Errorf("parse commit: commit time: %w", err)
}
return &CommitInfo{
Hash: hash,
Parents: parents,
Author: User{
Name: fields[2],
Email: fields[3],
},
Committer: User{
Name: fields[5],
Email: fields[6],
},
AuthorTime: authorTime,
CommitTime: commitTime,
Message: fields[8],
}, nil
}
// LogOptions specifies filters and ordering on a log listing.
type LogOptions struct {
// Revs specifies the set of commits to list. When empty, it defaults
// to all commits reachable from HEAD.
Revs []string
// MaxParents sets an inclusive upper limit on the number of parents
// on revisions to return from Log. If MaxParents is zero, then it is
// treated as no limit unless AllowZeroMaxParents is true.
MaxParents int
AllowZeroMaxParents bool
// If FirstParent is true, then follow only the first parent commit
// upon seeing a merge commit.
FirstParent bool
// Limit specifies the upper bound on the number of revisions to return from Log.
// Zero means no limit.
Limit int
// If Reverse is true, then commits will be returned in reverse order.
Reverse bool
// If NoWalk is true, then ancestor commits are not traversed. Does not have
// an effect if Revs contains a range.
NoWalk bool
}
// Log starts fetching information about a set of commits. The context's
// deadline and cancelation will apply to the entire read from the Log.
func (g *Git) Log(ctx context.Context, opts LogOptions) (*Log, error) {
// TODO(someday): Add an example for this method.
const errPrefix = "git log"
for _, rev := range opts.Revs {
if err := validateRev(rev); err != nil {
return nil, fmt.Errorf("%s: %w", errPrefix, err)
}
}
args := []string{"log", "-z", "--pretty=" + commitInfoPrettyFormat}
if opts.MaxParents > 0 || opts.AllowZeroMaxParents {
args = append(args, fmt.Sprintf("--max-parents=%d", opts.MaxParents))
}
if opts.FirstParent {
args = append(args, "--first-parent")
}
if opts.Limit > 0 {
args = append(args, fmt.Sprintf("--max-count=%d", opts.Limit))
}
if opts.Reverse {
args = append(args, "--reverse")
}
if opts.NoWalk {
args = append(args, "--no-walk=sorted")
}
args = append(args, opts.Revs...)
args = append(args, "--")
ctx, cancel := context.WithCancel(ctx)
stderr := new(bytes.Buffer)
pipe, err := StartPipe(ctx, g.runner, &Invocation{
Args: args,
Dir: g.dir,
Stderr: &limitWriter{w: stderr, n: 4096},
})
if err != nil {
cancel()
return nil, fmt.Errorf("%s: %w", errPrefix, err)
}
r := bufio.NewReaderSize(pipe, 1<<20 /* 1 MiB */)
if _, err := r.Peek(1); err != nil && !errors.Is(err, io.EOF) {
cancel()
waitErr := pipe.Close()
return nil, commandError(errPrefix, waitErr, stderr.Bytes())
}
return &Log{
r: r,
cancel: cancel,
close: pipe,
}, nil
}
// Log is an open handle to a `git log` subprocess. Closing the Log
// stops the subprocess.
type Log struct {
r *bufio.Reader
cancel context.CancelFunc
close io.Closer
scanErr error
scanDone bool
info *CommitInfo
}
// Next attempts to scan the next log entry and returns whether there is a new entry.
func (l *Log) Next() bool {
if l.scanDone {
return false
}
// Continue growing buffer until we've fit a log entry.
end := -1
for n := l.r.Buffered(); n < l.r.Size(); {
data, err := l.r.Peek(n)
end = findCommitInfoEnd(data)
if end != -1 {
break
}
if err != nil {
switch {
case err == io.EOF && l.r.Buffered() == 0:
l.abort(nil)
case err == io.EOF && l.r.Buffered() > 0:
l.abort(io.ErrUnexpectedEOF)
default:
l.abort(err)
}
return false
}
if l.r.Buffered() > n {
n = l.r.Buffered()
} else {
n++
}
}
if end == -1 {
l.abort(bufio.ErrBufferFull)
return false
}
// Parse entry.
data, err := l.r.Peek(end)
if err != nil {
// Should already be buffered.
panic(err)
}
info, err := parseCommitInfo(string(data))
if err != nil {
l.abort(err)
return false
}
if _, err := l.r.Discard(end); err != nil {
// Should already be buffered.
panic(err)
}
l.info = info
return true
}
func (l *Log) abort(e error) {
l.r = nil
l.scanErr = e
l.scanDone = true
l.info = nil
l.cancel()
}
func findCommitInfoEnd(b []byte) int {
nuls := 0
for i := range b {
if b[i] != 0 {
continue
}
nuls++
if nuls == commitInfoFieldCount {
return i + 1
}
}
return -1
}
// CommitInfo returns the most recently scanned log entry.
// Next must be called at least once before calling CommitInfo.
func (l *Log) CommitInfo() *CommitInfo {
return l.info
}
// Close ends the log subprocess and waits for it to finish.
// Close returns an error if Next returned false due to a parse failure.
func (l *Log) Close() error {
// Not safe to call multiple times, but interface for Close doesn't
// require this to be supported.
l.cancel()
l.close.Close() // Ignore error, since it's probably from interrupting.
return l.scanErr
}