forked from JonathanWThom/jira-git
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
109 lines (90 loc) · 2.29 KB
/
main.go
File metadata and controls
109 lines (90 loc) · 2.29 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
package main
import (
"errors"
"fmt"
"log"
"net/url"
"os"
"os/exec"
"regexp"
"strings"
jira "github.com/andygrunwald/go-jira"
)
var (
apiToken = os.Getenv("ATLASSIAN_API_TOKEN")
baseURL = os.Getenv("ATLASSIAN_BASE_URL")
email = os.Getenv("ATLASSIAN_EMAIL")
)
func main() {
if err := Run(os.Args); err != nil {
log.Fatal(err)
}
}
func Run(args []string) error {
if len(args) != 2 {
return errors.New("Please pass Issue URL as argument")
}
for _, param := range []string{apiToken, baseURL, email} {
if param == "" {
return errors.New("Please set all environment variables")
}
}
issueID, err := getIssueID(os.Args[1])
if err != nil {
return err
}
jc, err := newJiraClient(email, apiToken)
if err != nil {
return err
}
summary, err := jc.GetIssueSummary(issueID)
if err != nil {
return err
}
return checkoutNewBranch(issueID, summary)
}
func getIssueID(uri string) (string, error) {
url, err := url.ParseRequestURI(uri)
if err != nil {
return "", err
}
paths := strings.Split(url.Path, "/")
// Probably want to handle invalid urls here
// Something that might return 0 paths....
// We'll get to testing soon
return paths[len(paths)-1], nil
}
var reg = regexp.MustCompile("[^a-zA-Z0-9 ]+")
func checkoutNewBranch(id, summary string) error {
sanitized := reg.ReplaceAllString(summary, "")
dashed := strings.ToLower(strings.ReplaceAll(sanitized, " ", "-"))
branchName := fmt.Sprintf("%s--%s", id, dashed)
fmt.Println(branchName)
// Could maybe stash here first?
cmd := exec.Command("git", "checkout", "-b", branchName) // This could probably be replaced with something like `git-go` to avoid shelling out
return cmd.Run()
}
type jiraClient struct {
client *jira.Client
}
// Tell me to tell you about functional parameters. It's a nice way to add mutliple configuration, and having nice defaults
func newJiraClient(email, apiToken string) (*jiraClient, error) {
tp := jira.BasicAuthTransport{
Username: email,
Password: apiToken,
}
client, err := jira.NewClient(tp.Client(), baseUrl)
if err != nil {
return nil, err
}
return &jiraClient{
client: client,
}, nil
}
func (c *jiraClient) GetIssueSummary(id string) (string, error) {
issue, _, err := c.client.Issue.Get(id, nil)
if err != nil {
return "", err
}
return issue.Fields.Summary, nil
}