-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
230 lines (198 loc) · 5.45 KB
/
main.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
package main
import (
"encoding/json"
"flag"
"fmt"
"log/slog"
"os"
"strconv"
"strings"
tea "github.com/charmbracelet/bubbletea"
"github.com/cli/go-gh/v2"
"github.com/cli/go-gh/v2/pkg/repository"
"github.com/fatih/color"
"github.com/sourcegraph/conc/pool"
)
var (
bold = color.New(color.Bold).SprintFunc()
hiBlack = color.New(color.FgHiBlack).SprintFunc()
green = color.New(color.FgGreen).SprintFunc()
yellow = color.New(color.FgYellow).SprintFunc()
red = color.New(color.FgRed).SprintFunc()
blue = color.New(color.FgHiBlue).SprintFunc()
)
func main() {
flag.Usage = func() {
fmt.Fprintf(color.Output, "%s\n\n", "Chainlink - link chained pull requests and issues.")
fmt.Fprintf(color.Output, "%s\n", bold("USAGE"))
fmt.Fprintf(color.Output, " %s\n\n", "gh chainlink <issue ref>")
fmt.Fprintf(color.Output, "%s", bold("ISSUE REF"))
fmt.Fprintf(color.Output, "%s\n", `
autodetect: Leave empty to use the pull request for the current branch.
number: Enter the issue or pull request number for the current repo e.g. 123.
url: Enter the issue or pull request url e.g. https://github.com/RoryQ/gh-chainlink/issues/1
`)
flag.PrintDefaults()
}
flag.Parse()
args := flag.Args()
// Detect repo and issue for current branch
client := must(NewGhClient())
// Use provided issue ref if provided
targetIssue := getTargetIssue(args)
if targetIssue.Number == 0 {
flag.Usage()
os.Exit(0)
}
// get chain from ref issue
issue := must(client.GetIssue(targetIssue))
chain := must(Parse(targetIssue, issue.Body))
_, err := tea.NewProgram(model{
gh: client,
sub: make(chan responseMsg),
responses: make(map[int]responseMsg),
chain: *chain,
}).Run()
if err != nil {
slog.Error("Error running program", "error", err)
os.Exit(1)
}
}
func updateIssue(client *GhClient, chain Chain, item ChainItem) (string, error) {
item.IsPullRequest = client.IsPull(item.ChainIssue)
// update the CurrentLocationIndicator to the current issue
issueChainString := chain.ResetCurrent(item.ChainIssue).RenderMarkdown()
itemIssue, err := client.GetIssue(item.ChainIssue)
if err != nil {
return "error", fmt.Errorf("error retrieving item %d: %w", item.Number, err)
}
updatedBody := ReplaceChain(itemIssue.Body, issueChainString)
if updatedBody == itemIssue.Body {
return "skipped", nil
}
if err := client.UpdateIssueBody(item.ChainIssue, updatedBody); err != nil {
return "error", fmt.Errorf("error updating item %d: %w", item.Number, err)
}
return "updated", nil
}
func getTargetIssue(args []string) ChainIssue {
currentRepo, _ := repository.Current()
// use first argument
if len(args) >= 1 {
issueRef := args[0]
// current repo reference if number only
if _, err := strconv.Atoi(issueRef); err == nil {
issueRef = "#" + issueRef
}
issue := issueFromString(issueRef)
// Argument was a URL
if issue.Number != 0 && issue.Repo.Host != "" {
return issue
}
// Argument was a number
issue.Repo = currentRepo
if issue.Number != 0 && issue.Repo.Host != "" {
return issue
}
// bad argument
return ChainIssue{}
}
// detect from branch
stdOut, stdErr, err := gh.Exec("pr", "status", "--json", "number,baseRefName,url")
if err != nil {
panic(err)
}
println(stdErr.String())
jsonResp := struct {
CurrentBranch struct {
BaseRefName string `json:"baseRefName"`
Number int `json:"number"`
Url string `json:"url"`
}
}{}
must0(json.Unmarshal(stdOut.Bytes(), &jsonResp))
return issueFromMessage(currentRepo, jsonResp.CurrentBranch.Url)
}
func must[T any](v T, err error) T {
if err != nil {
panic(err)
}
return v
}
func must0(err error) {
if err != nil {
panic(err)
}
}
type responseMsg struct {
index int
result string
err error
}
func (m model) updatePRs() tea.Cmd {
return func() tea.Msg {
p := pool.New().WithMaxGoroutines(5)
for i, item := range m.chain.Items {
i, item := i, item
p.Go(func() {
resp, err := updateIssue(m.gh, m.chain, item)
m.sub <- responseMsg{index: i, result: resp, err: err}
})
}
p.Wait()
return nil
}
}
// A command that waits for the activity on a channel.
func waitForActivity(sub chan responseMsg) tea.Cmd {
return func() tea.Msg {
return <-sub
}
}
type model struct {
gh *GhClient
sub chan responseMsg
responses map[int]responseMsg
chain Chain
}
func (m model) Init() tea.Cmd {
return tea.Batch(
m.updatePRs(), // generate activity
waitForActivity(m.sub), // wait for activity
)
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch v := msg.(type) {
case tea.KeyMsg:
return m, tea.Quit
case responseMsg:
m.responses[v.index] = v
if len(m.responses) == len(m.chain.Items) {
return m, tea.Quit
}
return m, waitForActivity(m.sub) // wait for next event
default:
return m, nil
}
}
func (m model) View() string {
sb := new(strings.Builder)
if m.chain.Header != "" {
_, _ = fmt.Fprintln(sb, blue(m.chain.Header))
}
for i, item := range m.chain.Items {
if response, ok := m.responses[i]; ok {
switch response.result {
case "updated":
_, _ = fmt.Fprintln(sb, green("✓"), item.renderListPoint(i), item.Message)
case "skipped":
_, _ = fmt.Fprintln(sb, yellow("∅"), item.renderListPoint(i), item.Message)
case "error":
_, _ = fmt.Fprintln(sb, red("✗"), item.renderListPoint(i), item.Message, red(response.err))
}
} else {
_, _ = fmt.Fprintln(sb, hiBlack("_"), item.renderListPoint(i), item.Message)
}
}
return sb.String()
}