-
-
Notifications
You must be signed in to change notification settings - Fork 70
Expand file tree
/
Copy pathlog.go
More file actions
540 lines (459 loc) · 14.7 KB
/
Copy pathlog.go
File metadata and controls
540 lines (459 loc) · 14.7 KB
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
package main
import (
"bufio"
"cmp"
"context"
"encoding"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"strings"
"github.com/alecthomas/kong"
"go.abhg.dev/gs/internal/forge"
"go.abhg.dev/gs/internal/git"
"go.abhg.dev/gs/internal/handler/list"
"go.abhg.dev/gs/internal/secret"
"go.abhg.dev/gs/internal/silog"
"go.abhg.dev/gs/internal/spice"
"go.abhg.dev/gs/internal/spice/state"
"go.abhg.dev/gs/internal/ui"
"go.abhg.dev/gs/internal/ui/branchtree"
"go.abhg.dev/gs/internal/ui/commit"
)
type logCmd struct {
Short logShortCmd `cmd:"" aliases:"s" help:"List branches"`
Long logLongCmd `cmd:"" aliases:"l" help:"List branches and commits"`
}
func (*logCmd) AfterApply(kctx *kong.Context) error {
return kctx.BindToProvider(func(
log *silog.Logger,
repo *git.Repository,
store *state.Store,
svc *spice.Service,
remoteResolver *remoteResolver,
stash secret.Stash,
) (ListHandler, error) {
return &list.Handler{
Log: log,
Repository: repo,
Store: store,
Service: svc,
ResolveRepository: func(ctx context.Context, remote string) (forge.Forge, forge.RepositoryID, error) {
f, repoID, err := remoteResolver.Resolve(ctx, remote)
var unsupported *unsupportedForgeError
if errors.As(err, &unsupported) {
return nil, nil, nil
}
return f, repoID, err
},
OpenRemoteRepository: func(ctx context.Context, f forge.Forge, repo forge.RepositoryID) (forge.Repository, error) {
return openForgeRepository(ctx, stash, f, repo)
},
}, nil
})
}
type ListHandler interface {
ListBranches(context.Context, *list.BranchesRequest) (*list.BranchesResponse, error)
}
// branchLogCmd is the shared implementation of logShortCmd and logLongCmd.
type branchLogCmd struct {
list.Options
ChangeFormat changeFormat `config:"log.crFormat" help:"Format for displaying change request information. One of 'id' or 'url'." hidden:"" default:"id"`
ChangeFormatShort *changeFormat `config:"logShort.crFormat" help:"Format for displaying change request information in short log. One of 'id' or 'url', defaults to crFormat." hidden:""`
ChangeFormatLong *changeFormat `config:"logLong.crFormat" help:"Format for displaying change request information in long log. One of 'id' or 'url', defaults to crFormat." hidden:""`
CRStatus bool `name:"cr-status" short:"S" config:"log.crStatus" help:"Request and include information about the Change Request" default:"false" negatable:""`
// TODO: When needed, add a crStatusFormat config to control presentation.
Comments bool `name:"cr-comments" short:"c" config:"log.crComments" help:"Include comment resolution counts for changes" default:"false" negatable:""`
PushStatusFormat pushStatusFormat `config:"log.pushStatusFormat" help:"Show indicator for branches that are out of sync with their remotes. One of 'true', 'false' and 'aheadbehind'." hidden:"" default:"true"`
JSON bool `name:"json" released:"v0.18.0" help:"Write to stdout as a stream of JSON objects in an unspecified order"`
}
type branchLogOptions struct {
Commits bool
}
func (cmd *branchLogCmd) run(
ctx context.Context,
kctx *kong.Context,
opts *branchLogOptions,
wt *git.Worktree,
listHandler ListHandler,
) (err error) {
opts = cmp.Or(opts, &branchLogOptions{})
currentBranch, err := wt.CurrentBranch(ctx)
if err != nil {
currentBranch = "" // may be detached
}
var presenter logPresenter
var wantPushStatus, wantChangeState, wantCommentCounts bool
if cmd.JSON {
// JSON always wants URLs and push status, but respects flags for change state/comments.
wantPushStatus = true
wantChangeState = cmd.CRStatus
wantCommentCounts = cmd.Comments
presenter = &jsonLogPresenter{
Stdout: kctx.Stdout,
CurrentWorktree: wt.RootDir(),
}
} else {
// Determine which ChangeFormat to use:
// prefer long/short-specific, then fallback to general.
changeFormat := cmd.ChangeFormat
if opts.Commits && cmd.ChangeFormatLong != nil {
changeFormat = *cmd.ChangeFormatLong
} else if !opts.Commits && cmd.ChangeFormatShort != nil {
changeFormat = *cmd.ChangeFormatShort
}
wantPushStatus = cmd.PushStatusFormat.Enabled()
wantChangeState = cmd.CRStatus
wantCommentCounts = cmd.Comments
stderrView := ui.NewFileView(kctx.Stderr)
presenter = &graphLogPresenter{
Stderr: stderrView,
Theme: stderrView.Theme(),
ChangeFormat: changeFormat,
ShowCRStatus: wantChangeState,
ShowCommentCounts: wantCommentCounts,
PushStatusFormat: cmd.PushStatusFormat,
CurrentWorktree: wt.RootDir(),
}
}
req := list.BranchesRequest{
Branch: currentBranch,
Options: &cmd.Options,
Include: list.IncludeChangeURL,
}
if wantChangeState {
req.Include |= list.IncludeChangeState
}
if opts.Commits {
req.Include |= list.IncludeCommits
}
if wantPushStatus {
req.Include |= list.IncludePushStatus
}
if wantCommentCounts {
req.Include |= list.IncludeCommentCounts
}
res, err := listHandler.ListBranches(ctx, &req)
if err != nil {
return fmt.Errorf("log branches: %w", err)
}
return presenter.Present(res, currentBranch)
}
type logPresenter interface {
Present(res *list.BranchesResponse, currentBranch string) error
}
type graphLogPresenter struct {
Stderr ui.View // required
Theme ui.Theme // required
ChangeFormat changeFormat // required
ShowCRStatus bool // required
ShowCommentCounts bool // required
PushStatusFormat pushStatusFormat // required
CurrentWorktree string // required
}
func (p *graphLogPresenter) Present(res *list.BranchesResponse, currentBranch string) error {
home, err := os.UserHomeDir()
if err != nil {
home = "" // if no home directory, we won't substitute paths
}
// Convert list.BranchItem to widget.BranchItem.
items := make([]*branchtree.Item, len(res.Branches))
for i, b := range res.Branches {
item := &branchtree.Item{
Branch: b.Name,
Worktree: b.Worktree,
NeedsRestack: b.NeedsRestack,
Aboves: b.Aboves,
Highlighted: b.Name == currentBranch,
}
// Format change ID based on requested format.
if b.ChangeID != nil {
switch p.ChangeFormat {
case changeFormatID:
item.ChangeID = b.ChangeID.String()
case changeFormatURL:
item.ChangeID = b.ChangeURL
}
item.ChangeURL = b.ChangeURL
// Include change state if requested.
if p.ShowCRStatus && b.ChangeState != 0 {
item.ChangeState = &b.ChangeState
}
// Include comment counts if requested and available.
if p.ShowCommentCounts && b.CommentCounts != nil {
item.CommentCounts = b.CommentCounts
}
}
if s := b.PushStatus; s != nil {
item.PushStatus = branchtree.PushStatus{
Ahead: s.Ahead,
Behind: s.Behind,
NeedsPush: s.NeedsPush,
}
}
if len(b.Commits) > 0 {
item.Commits = make([]commit.Summary, len(b.Commits))
for j, c := range b.Commits {
item.Commits[j] = commit.Summary{
ShortHash: c.ShortHash,
Subject: c.Subject,
AuthorDate: c.AuthorDate,
}
}
}
items[i] = item
}
// Convert push status format.
var pushFmt branchtree.PushStatusFormat
switch p.PushStatusFormat {
case pushStatusEnabled:
pushFmt = branchtree.PushStatusSimple
case pushStatusAheadBehind:
pushFmt = branchtree.PushStatusAheadBehind
default:
pushFmt = branchtree.PushStatusDisabled
}
g := branchtree.Graph{
Items: items,
Roots: []int{res.TrunkIdx},
}
opts := &branchtree.GraphOptions{
Theme: p.Theme,
PushStatusFormat: pushFmt,
CurrentWorktree: p.CurrentWorktree,
HomeDir: home,
}
if err := branchtree.Write(p.Stderr, g, opts); err != nil {
return fmt.Errorf("write tree: %w", err)
}
return nil
}
type jsonLogPresenter struct {
Stdout io.Writer // required
CurrentWorktree string // required
}
func (p *jsonLogPresenter) Present(res *list.BranchesResponse, currentBranch string) (retErr error) {
bufw := bufio.NewWriter(p.Stdout)
defer func() {
retErr = errors.Join(retErr, bufw.Flush())
}()
enc := json.NewEncoder(bufw)
for _, branch := range res.Branches {
logBranch := jsonLogBranch{
Name: branch.Name,
Current: branch.Name == currentBranch,
}
if branch.Base != "" {
logBranch.Down = &jsonLogDown{
Name: branch.Base,
NeedsRestack: branch.NeedsRestack,
}
}
if len(branch.Aboves) > 0 {
ups := make([]jsonLogUp, 0, len(branch.Aboves))
for _, aboveIdx := range branch.Aboves {
ups = append(ups, jsonLogUp{
Name: res.Branches[aboveIdx].Name,
})
}
logBranch.Ups = ups
}
if len(branch.Commits) > 0 {
commits := make([]jsonLogCommit, 0, len(branch.Commits))
for _, commit := range branch.Commits {
commits = append(commits, jsonLogCommit{
SHA: commit.Hash.String(),
Subject: commit.Subject,
})
}
logBranch.Commits = commits
}
if branch.ChangeID != nil {
jc := &jsonLogChange{
ID: branch.ChangeID.String(),
URL: branch.ChangeURL,
}
if branch.ChangeState != 0 {
switch branch.ChangeState {
case forge.ChangeOpen:
jc.Status = "open"
case forge.ChangeClosed:
jc.Status = "closed"
case forge.ChangeMerged:
jc.Status = "merged"
}
}
if cc := branch.CommentCounts; cc != nil {
jc.Comments = &jsonLogComments{
Total: cc.Total,
Resolved: cc.Resolved,
Unresolved: cc.Unresolved,
}
}
logBranch.Change = jc
}
if status := branch.PushStatus; status != nil {
logBranch.Push = &jsonLogPushStatus{
Ahead: status.Ahead,
Behind: status.Behind,
NeedsPush: status.NeedsPush,
}
}
if wt := branch.Worktree; wt != "" && wt != p.CurrentWorktree {
logBranch.Worktree = wt
}
if err := enc.Encode(logBranch); err != nil {
return fmt.Errorf("encode branch %q: %w", branch.Name, err)
}
}
return nil
}
type jsonLogBranch struct {
// Name of the branch.
Name string `json:"name"`
// Current is true if this branch is the current branch.
// This is false or omitted if this is not the current branch.
Current bool `json:"current,omitempty"`
// Down is the base branch onto which this branch is stacked.
// This is unset if this branch is trunk.
// 'git-spice down' from the current branch will check out this branch.
Down *jsonLogDown `json:"down,omitempty"`
// Ups is a list of branches that are stacked directly above this branch.
// 'git-spice up' from this branch will check out one of these branches.
Ups []jsonLogUp `json:"ups,omitempty"`
// Commits is a list of commits on this branch.
// These are not included unless invoked with 'git-spice log long'.
Commits []jsonLogCommit `json:"commits,omitempty"`
// Change is the associated change request, if any.
// This is unset if this branch has not been published.
Change *jsonLogChange `json:"change,omitempty"`
// Push indicates the push status of this branch,
// if the branch has been pushed to a remote.
// This is unset if the branch has not been pushed
// from git-spice's perspective.
Push *jsonLogPushStatus `json:"push,omitempty"`
// Worktree is the absolute path to the worktree
// where this branch is checked out,
// if it's not the current branch.
//
// This is unset if the branch is not checked out
// in any worktree,
// or if it's the current branch (current is true).
Worktree string `json:"worktree,omitempty"`
}
type jsonLogDown struct {
// Name of the base branch.
Name string `json:"name"`
// NeedsRestack is true if the branch needs to be restacked
// onto its base branch.
NeedsRestack bool `json:"needsRestack,omitempty"`
}
type jsonLogUp struct {
// Name of the branch stacked directly above this branch.
Name string `json:"name"`
}
type jsonLogCommit struct {
// SHA is the full commit hash.
SHA string `json:"sha"`
// Subject is the commit subject line.
Subject string `json:"subject"`
}
type jsonLogChange struct {
// ID is the change ID of the associated change.
// For GitHub, this is the PR number.
// For GitLab, this is the MR IID.
ID string `json:"id"`
// URL is the web URL of the associated change.
URL string `json:"url"`
// Status is the current state of the change (open|closed|merged).
Status string `json:"status,omitempty"`
// Comments contains comment resolution counts for the change.
Comments *jsonLogComments `json:"comments,omitempty"`
}
type jsonLogComments struct {
// Total is the total number of resolvable comments or threads.
Total int `json:"total"`
// Resolved is the number of resolved comments or threads.
Resolved int `json:"resolved"`
// Unresolved is the number of unresolved comments or threads.
Unresolved int `json:"unresolved"`
}
type jsonLogPushStatus struct {
// Ahead is the number of commits that this branch is ahead
// of its remote tracking branch.
Ahead int `json:"ahead"`
// Behind is the number of commits that this branch is behind
// its remote tracking branch.
Behind int `json:"behind"`
// NeedsPush is true if this branch is out of sync with its remote,
// and should be pushed.
//
// This will be false if Ahead and Behind are both zero.
NeedsPush bool `json:"needsPush,omitempty"`
}
// pushStatusFormat enumerates the possible values for the pushStatusFormat config.
type pushStatusFormat int
const (
pushStatusEnabled pushStatusFormat = iota // "(needs push)"
pushStatusDisabled // show nothing
pushStatusAheadBehind // show number of commits ahead/behind
)
var _ encoding.TextUnmarshaler = (*pushStatusFormat)(nil)
func (f *pushStatusFormat) UnmarshalText(bs []byte) error {
switch strings.ToLower(string(bs)) {
case "true", "1", "yes":
*f = pushStatusEnabled
case "false", "0", "no":
*f = pushStatusDisabled
case "aheadbehind":
*f = pushStatusAheadBehind
default:
return fmt.Errorf("invalid value %q: expected true, false, or aheadbehind", string(bs))
}
return nil
}
func (f pushStatusFormat) String() string {
switch f {
case pushStatusEnabled:
return "true"
case pushStatusDisabled:
return "false"
case pushStatusAheadBehind:
return "aheadBehind"
default:
return "unknown"
}
}
func (f pushStatusFormat) Enabled() bool {
return f == pushStatusEnabled || f == pushStatusAheadBehind
}
// changeFormat enumerates the possible values for the changeFormat config.
type changeFormat int
const (
changeFormatID changeFormat = iota // "id"
changeFormatURL // "url"
)
var _ encoding.TextUnmarshaler = (*changeFormat)(nil)
func (f *changeFormat) UnmarshalText(bs []byte) error {
switch strings.ToLower(string(bs)) {
case "id":
*f = changeFormatID
case "url":
*f = changeFormatURL
default:
return fmt.Errorf("invalid value %q: expected id or url", string(bs))
}
return nil
}
func (f changeFormat) String() string {
switch f {
case changeFormatID:
return "id"
case changeFormatURL:
return "url"
default:
return fmt.Sprintf("changeFormat(%d)", int(f))
}
}