/
new.go
639 lines (559 loc) · 18.8 KB
/
new.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
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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
//nolint:gochecknoglobals // cobra uses globals for commands
package cmd
import (
"encoding/json"
"fmt"
"os"
"os/exec"
"regexp"
"sort"
"strings"
"time"
"github.com/alessio/shellescape"
"github.com/AlecAivazis/survey/v2"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/object"
"github.com/go-git/go-git/v5/plumbing/transport"
"github.com/magefile/mage/sh"
"github.com/go-git/go-git/v5"
"github.com/charmbracelet/bubbles/key"
"github.com/charmbracelet/huh"
"github.com/pterm/pterm"
"github.com/spf13/cobra"
)
// newCmd represents the new command
var newCmd = &cobra.Command{
Use: "new",
Short: "🚀 Create a new PR",
Long: `Use this command to create a new PR.
It will ask you a few questions and help you create a PR with an interactive prompt.
If you don't like confetti, you can disable it by setting the environment variable CONFETTI=1.
I'll probably add a flag to disable in the future, but till then yeah 🎊🎉`,
Run: func(cmd *cobra.Command, args []string) {
createPR()
},
}
// evaluateScopeMonths is how far back in git history to evaluate scopes to provide with autocompletion.
const evaluateScopeMonths int = 6
func init() {
rootCmd.AddCommand(newCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// newCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// newCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
func conventionalCommitTypeOptions() []huh.Option[string] {
return huh.NewOptions(
"ci",
"build",
"feat",
"fix",
"refactor",
"style",
"chore",
"test",
"docs",
"perf",
"revert",
"security",
)
}
// emojify returns a nice emoji for the given commit type.
// Emoji's make it easier to smile. :).
// Trailing space is to ensure it doesn't run into the scope message.
func emojify(commitTypeString string) string {
switch commitTypeString {
case "feat":
return "✨" + " "
case "fix":
return "🐛" + " "
case "chore":
return "🔨" + " "
case "refactor":
return "🛠️" + " "
case "test":
return "🧪" + " "
case "docs":
return "📘" + " "
case "style":
return "🎨" + " "
case "perf":
return "⚡" + " "
case "ci":
return "🚀" + " "
case "build":
return "👷" + " "
case "revert":
return "💩" + " "
default:
return "" + " "
}
}
var (
commit, scope string
title, description string
confirm bool
)
// customKeyMap uses the default keymap, but overrides certain keys so it doesn't have to all be redefined.
func customKeyMap() *huh.KeyMap {
df := huh.NewDefaultKeyMap()
// df.Confirm.Submit = key.NewBinding(key.WithKeys("ctrl+s"), key.WithHelp("💾 ctrl+s", "submit form"))
df.Quit = key.NewBinding(key.WithKeys("ctrl+c"), key.WithHelp("ctrl", "exit"))
df.Text.NewLine = key.NewBinding(key.WithKeys("enter", "ctrl+j"), key.WithHelp("enter / ctrl+j", "new line"))
df.Text.Next = key.NewBinding(key.WithKeys("tab"), key.WithHelp("tab", "next"))
df.Input.AcceptSuggestion = key.NewBinding(key.WithKeys("right"), key.WithHelp("→", "next"))
return df
}
func gatherInput() (title, description, workitems string, draft bool) {
if Debug {
pterm.EnableDebugMessages()
}
var err error
var commitType, scope string
var confirm bool
// var okWithEmptyDescription bool
// while this can return a collection, maxResults means return the most popular single scope in last evaluateScopeMonths period.
// placeholderForScope := "lowercase-hypen-separated"
// TODO: make this prettier in future :-p, cause I want to do something with the list of scopes
nf := huh.NewForm(
huh.NewGroup(
huh.NewSelect[string]().
Title("type").
Value(&commitType).
Description("press / to quickly filter by typing").
Options(conventionalCommitTypeOptions()...),
// WithHeight(5),
),
).WithKeyMap(customKeyMap()).
WithTheme(huh.ThemeDracula())
if err = nf.Run(); err != nil {
pterm.Warning.Printfln("issue gather input, either by user cancellation, or other issue. I goofed. not your fault. ## ShouldHaveDoneTDD: %v", err)
os.Exit(0)
}
var suggestedScope []ScopeCount
suggestedScope, err = GetScopesInLastMonths(evaluateScopeMonths, 6, commitType)
if err != nil {
pterm.Warning.Printfln("suggested scope logic errored, continuing: %v", err)
}
var scopesToSuggest []string
for _, s := range suggestedScope {
scopesToSuggest = append(scopesToSuggest, s.Scope)
}
// var suggestionsForScope []string{}
scopePlaceholder := DynamicScopeSuggestion(commitType)
// if len(scopeSuggestions) == 0 {
// pterm.Debug.Println("scope suggestions are just a single result, so using that value instead of scope array") // TODO: cleanup in future, it's redundant
// suggestionsForScope = []string{scopePlaceholder}
// }
nf = huh.NewForm(
huh.NewGroup(
// TODO: have the suggestions populate the string array list
huh.NewInput().Title("scope").Inline(true).Value(&scope).Suggestions(scopesToSuggest).Placeholder(scopePlaceholder).CharLimit(20),
huh.NewInput().Title("title").Inline(true).Value(&title).Placeholder("use lower case, present tense").CharLimit(72),
huh.NewText().
Title("PR description").
Placeholder("- Tell me more... ").
Value(&description),
// NOTE: it is confusing as it doesn't get inserted into current group, therefore disabling and letting user choose for now
// related context: https://github.com/charmbracelet/huh/issues/108
// Validate(func(t string) error {
// if t == "" {
// if err := huh.NewConfirm().
// Title("Is it ok to proceed with an empty description?").
// Value(&okWithEmptyDescription).Run(); err != nil {
// return fmt.Errorf("NewConfirm for NewText Validate failure: %v", err)
// }
// if okWithEmptyDescription {
// return nil
// }
// return fmt.Errorf("no input was provided, so try again")
// }
// return nil
// }).Value(&description),
huh.NewConfirm().Title("draft pr?").Inline(true).Value(&draft),
huh.NewInput().Title("workitems").Inline(true).Value(&workitems).Placeholder("(optional) space separated"),
huh.NewConfirm().Title("submit?").Inline(true).Value(&confirm),
),
).
WithKeyMap(customKeyMap()).
WithTheme(huh.ThemeDracula())
pterm.DefaultSection.Println("PR Creation")
if !confirm {
pterm.Warning.Println("confirm was set to false")
}
if err = nf.Run(); err != nil {
pterm.Warning.Printfln("issue gather input, either by user cancellation, or other issue. I goofed. not your fault. ## ShouldHaveDoneTDD: %v", err)
os.Exit(0)
}
if scope != "" {
scope = "(" + scope + "):"
} else {
scope = ":"
}
title = fmt.Sprintf("%s%s %s%s", commitType, scope, emojify(commitType), title)
pterm.Info.Println(title)
pterm.Info.Printfln("\n%s", description)
if !confirm {
pterm.Warning.Printfln("you selected to not submit, so exiting without further action")
os.Exit(0)
}
return title, description, workitems, draft
}
// getRemote reads the current remote url from git.
func getRemote() (remoteConfig *git.Remote, err error) {
r, err := git.PlainOpen(".")
if err != nil {
return nil, fmt.Errorf("unable to open git repo: %w", err)
}
remoteConfig, err = r.Remote("origin")
if err != nil {
return nil, fmt.Errorf("unable to get remote for origin: %w", err)
}
return remoteConfig, nil
}
// trunk-ignore(golangci-lint/funlen)
func getUpstreamBranch() (branchName string, err error) {
if Debug {
pterm.EnableDebugMessages()
}
r, err := git.PlainOpen(".")
if err != nil {
return "", fmt.Errorf("unable to open git repo: %w", err)
}
head, err := r.Head()
if err != nil {
return "", fmt.Errorf("unable to get head from git: %w", err)
}
pterm.Debug.Printfln("[Type: %+v]\n[Hash: %+v]\n[Name: %+v]\n[Target: %+v]\n[String: %+v]\n[Name.Short: %+v]",
head.Type(),
head.Hash(),
head.Name(),
head.Target(),
head.String(),
head.Name().Short())
bl, err := r.Branches()
if err != nil {
return "", fmt.Errorf("unable to get branches from git: %w", err)
}
var detectMaster bool
var detectMain bool
err = bl.ForEach(func(b *plumbing.Reference) error {
pterm.Debug.Printfln("\tBranch.ForEach: [Type: %+v][Hash: %+v][Name: %+v][Target: %+v][Name.Short: %+v]",
b.Type(),
b.Hash(),
b.Name(),
b.Target(),
b.Name().Short())
switch b.Name().Short() {
case "master":
detectMaster = true
case "main":
detectMain = true
default:
}
return nil
})
if detectMaster && detectMain {
pterm.Warning.Println("things seem to be confusing here. you have a main and a master branch")
if err := survey.AskOne(&survey.Input{
Message: "Which branch do you want to use as target for push?",
Default: "main",
Suggest: func(toComplete string) []string {
return []string{"main", "master"}
},
}, &branchName); err != nil {
return "", fmt.Errorf("failed to input branch name: %w", err)
}
} else {
if detectMaster {
branchName = "master"
} else if detectMain {
branchName = "main"
} else {
branchName = "" // just for clarity.. not really needed :-)
pterm.Warning.Println("unable to detect main or master branch")
}
pterm.Info.Printfln("autodetected target branch of: %s", branchName)
}
return branchName, err
}
func detectSSH() bool {
if Debug {
pterm.EnableDebugMessages()
}
// Open the repository
repo, err := git.PlainOpenWithOptions(".", &git.PlainOpenOptions{DetectDotGit: true})
if err != nil {
pterm.Error.Printfln("error opening repository: %v", err)
os.Exit(1)
}
// Get the URL of the remote
remote, err := repo.Remote("origin")
if err != nil {
pterm.Error.Printfln("error getting remote: %v", err)
os.Exit(1)
}
url := remote.Config().URLs[0]
// Check if the URL is an ssh URL
_, err = transport.NewEndpoint(url)
if err != nil {
pterm.Debug.Println("The remote was cloned via https")
return false
} else {
pterm.Debug.Println("The remote was cloned via ssh")
return true
}
}
type RemoteConfigData struct {
RemoteConfig *git.Remote
}
func (r *RemoteConfigData) GetURL() (url string) {
if len(r.RemoteConfig.Config().URLs) > 0 {
url = r.RemoteConfig.Config().URLs[0]
pterm.Debug.Printfln("(r *RemoteConfigData) GetURL(): %s", url)
return url
}
return ""
}
// ProjectName parses the project name out of ssh://git@ssh.dev.azure.com:v3/{org}/{project}/{repo}
func (r *RemoteConfigData) ProjectName() (project string) {
url := r.GetURL()
project = strings.Split(url, "/")[5]
pterm.Debug.Printfln("(r *RemoteConfigData) ProjectName(): %s", project)
return project
}
// RepoName parses the repo name out of git@ssh.dev.azure.com:v3/{org}/{project}/{repo}
func (r *RemoteConfigData) RepoName() (repo string) {
url := r.GetURL()
repo = strings.Split(url, "/")[6]
pterm.Debug.Printfln("(r *RemoteConfigData) RepoName(): %s", repo)
return repo
}
// OrgName parses the repo name out of git@ssh.dev.azure.com:v3/{org}/{project}/{repo}
func (r *RemoteConfigData) OrgName() (org string) {
url := r.GetURL()
org = strings.Split(url, "/")[4]
pterm.Debug.Printfln("(r *RemoteConfigData) OrgName(): %s", org)
return org
}
func createPR() { //nolint:funlen,cyclop // this is a cli tool, not a library, ok with longer workflow command
if Debug {
pterm.EnableDebugMessages()
}
var branchName string
var err error
isSSH := detectSSH()
remoteData := RemoteConfigData{}
// NOTE: can't use autodetect with ssh so have to be specific:
// Per error: DevOps SSH URLs are not supported for repo auto-detection yet. https://github.com/Microsoft/azure-devops-cli-extension/issues/142
// Attempt to calculate for user based on main/master pattern.
if isSSH {
pterm.Debug.Println("ssh based repo identified")
branchName, err = getUpstreamBranch()
if err != nil {
pterm.Warning.Printfln("isSSH check for getUpstreamBranch: %v", err)
}
rd, err := getRemote()
if err != nil {
pterm.Warning.Printfln("unable to process origin remote config data: %v", err)
}
remoteData.RemoteConfig = rd
// pterm.Debug.Printfln("remoteData: %v", remoteData.RemoteConfig)
pterm.Debug.Printfln("remoteURL: %s", remoteData.GetURL())
pterm.Debug.Printfln("projectName: %s", remoteData.ProjectName())
pterm.Debug.Printfln("repoName: %s", remoteData.RepoName())
pterm.Debug.Printfln("orgName: %s", remoteData.OrgName())
}
title, description, workitems, draft := gatherInput()
args := []string{
"repos", "pr", "create",
"--output", "json", // i had issues when passing at end, so make this the first arg
"--title", title,
"--draft", fmt.Sprintf("%t", draft),
"--auto-complete", "true",
"--delete-source-branch", "true",
"--squash",
"--transition-work-items", "true",
"--open",
"--merge-commit-message", title,
}
if isSSH && branchName != "" {
pterm.Debug.Printfln("isSSH && branchName is: %s", branchName)
args = append(args, "--target-branch")
args = append(args, branchName)
args = append(args, "--repository", remoteData.RepoName())
args = append(args, "--project", remoteData.ProjectName())
} else {
pterm.Debug.Println("target-branch is not set so default branch set in Azure Repos will be used")
args = append(args, "--detect")
}
args = append(args, "--description")
args = append(args, description)
// Repository contains the response URL for the PR
type Repository struct {
WebURL string `json:"webUrl"` //nolint:tagliatelle // this is output from azure-cli I don't control
}
// PullRequestResponse contains the response from the PR creation, captured the azure-cli.
type PullRequestResponse struct {
PullRequestID int `json:"pullRequestId"` //nolint:tagliatelle // this is output from azure-cli I don't control
Repository Repository `json:"repository"` //nolint:tagliatelle // this is output from azure-cli I don't control
}
cmd := exec.Command("az", args...)
pterm.Debug.Printfln("az %s", shellescape.QuoteCommand(args))
out, err := cmd.CombinedOutput()
if err != nil {
pterm.Error.Printf("failure running azure-cli via az-cli:\n%v\n\n", err)
pterm.Error.Printfln("out: %s", out)
pterm.Error.Printfln("err: %v", err)
pterm.Info.Println("try again by rerunning this generated command")
pterm.Info.Println("az " + shellescape.QuoteCommand(args))
os.Exit(1)
}
prResponse := PullRequestResponse{}
if err := json.Unmarshal(out, &prResponse); err != nil {
pterm.Error.Printf("unmarshal failure: %v\n", err)
pterm.Debug.Printf("out:\n%s\n", string(out))
os.Exit(1)
}
// to give better control when running in container, i want to output the url to the console to control click.
url := fmt.Sprintf(
"%s/pullrequest/%d",
prResponse.Repository.WebURL,
prResponse.PullRequestID,
)
pterm.Success.Printf("Pull Request Url: %s\n", url)
// Try to match against a pr item number, and if so then append.
// If not, bypass the entire process of trying to link to work-items.
reg := regexp.MustCompile(`\d{5,7}`)
if reg.MatchString(workitems) {
associateWorkItemIDargs := []string{
"repos", "pr", "work-item", "add",
"--id", fmt.Sprintf("%d", prResponse.PullRequestID),
"--work-items",
}
pterm.Success.Printf("Work Item IDs: %s\n", workitems)
// Argument escaping seems to have issues with spaces in string
// This as a workaround to turn the space delimited string into each being an individual argument to pass to command processor.
itemIDs := strings.Split(workitems, " ")
associateWorkItemIDargs = append(associateWorkItemIDargs, itemIDs...)
pterm.Info.Println("az " + shellescape.QuoteCommand(associateWorkItemIDargs))
if err := sh.Run("az", associateWorkItemIDargs...); err != nil {
pterm.Error.Printf("failure associating work-items via az-cli:\n%v\n\n", err)
os.Exit(0)
}
} else {
pterm.Info.Println("no work items to associate")
}
_ = pterm.DefaultBigText.WithLetters(pterm.NewLettersFromString("CELEBRATE")).Render()
if os.Getenv("NO_CONFETTI") == "1" {
pterm.Debug.Printfln("no fun, no confetty, exiting")
os.Exit(0)
}
time.Sleep(1 * time.Second)
}
type ScopeCount struct {
Scope string
Count int
}
type ByCount []ScopeCount
func (a ByCount) Len() int { return len(a) }
func (a ByCount) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByCount) Less(i, j int) bool { return a[i].Count > a[j].Count }
func GetScopesInLastMonths(months, maxResults int, commitType string) ([]ScopeCount, error) {
r, err := git.PlainOpenWithOptions(".", &git.PlainOpenOptions{DetectDotGit: true})
if err != nil {
pterm.Error.Printfln("error opening repository: %v", err)
return nil, err
}
ref, err := r.Head()
if err != nil {
return nil, err
}
cIter, err := r.Log(&git.LogOptions{From: ref.Hash()})
if err != nil {
return nil, err
}
// Bulk review
// var commitTypes []string
// for _, i := range conventionalCommitTypeOptions() {
// commitTypes = append(commitTypes, i.Value)
// }
// listOfCommitTypes := strings.Join(commitTypes, "|")
scopeCounts := make(map[string]int)
err = cIter.ForEach(func(c *object.Commit) error {
if c.Author.When.After(time.Now().AddDate(0, -months, 0)) {
re := regexp.MustCompile(fmt.Sprintf(`(?:%s)\((.*?)\):`, commitType))
submatchall := re.FindAllStringSubmatch(c.Message, -1)
for _, element := range submatchall {
scopeCounts[element[1]]++
}
}
return nil
})
if err != nil {
return nil, err
}
var scopes ByCount
for k, v := range scopeCounts {
scopes = append(scopes, ScopeCount{k, v})
}
sort.Sort(scopes)
if len(scopes) > maxResults {
scopes = scopes[:maxResults]
}
pterm.Debug.Printfln("total scope count: %d", len(scopes))
pterm.Debug.Printfln("scope counts: %v", scopes)
return scopes, nil
}
// DynamicScopeSuggestion calculates the best possible scope for the current commit type based on history.
func DynamicScopeSuggestion(commitType string) string {
if commitType == "" {
return ""
}
r, err := git.PlainOpenWithOptions(".", &git.PlainOpenOptions{DetectDotGit: true})
if err != nil {
pterm.Error.Printfln("error opening repository: %v", err)
return ""
}
ref, err := r.Head()
if err != nil {
return ""
}
cIter, err := r.Log(&git.LogOptions{From: ref.Hash()})
if err != nil {
return ""
}
scopeCounts := make(map[string]int)
err = cIter.ForEach(func(c *object.Commit) error {
if c.Author.When.After(time.Now().AddDate(0, -evaluateScopeMonths, 0)) {
re := regexp.MustCompile(fmt.Sprintf(`(?:%s)\((.*?)\):`, commitType))
submatchall := re.FindAllStringSubmatch(c.Message, -1)
for _, element := range submatchall {
scopeCounts[element[1]]++
}
}
return nil
})
if err != nil {
return ""
}
var scopes ByCount
for k, v := range scopeCounts {
scopes = append(scopes, ScopeCount{k, v})
}
sort.Sort(scopes)
if len(scopes) > 1 {
scopes = scopes[:1]
}
pterm.Debug.Printfln("total scope count: %d", len(scopes))
pterm.Debug.Printfln("scope counts: %v", scopes)
if len(scopes) > 0 {
scopeRecommendation := scopes[0].Scope
pterm.Debug.Printfln("best recommendation is: %s", scopeRecommendation)
return scopeRecommendation
}
return ""
}