Episode #14— Github & Jira CLI with Golang part 3: passing string to CL and iterating slice of string in Go
In this session we continued to work on Gong, our CLI tool for Jira & Github. Code is 100% open sourced and any comments or suggestions are welcomed.
I thought there were two interesting parts to discuss.
We wanted our CLI tool to be able to automatically create a git branch when we execute a certain command, for exmple
gong start <ticket_id>
would execute
git checkout -b <branch_name>
os/exec
is the right package to handle this job. We can pass in our commands as arguments to the function exec.Command
like so:
import (
"os/exec"
)...branchName := gong.GetBranchName(jiraClient, issueId, branchType)
cmd := "git"
args := []string{"checkout", "-b", branchName}
out, err := exec.Command(cmd, args...).Output()...
Upon execution this code would create a git branch on this current working directory.
Next step we wanted to have a function to automatically transition to a start
status. Our jiraClient
would already handle the API connection for us, but due to the way Jira API is designed, the status start
will be available for us only AFTER we transition to ready
status. So we have to execute the DoTransition
command twice.
The way we handled this is that we create a slice of strings of available status name and iterate that slice. It turns out it’s actually NOT super straight forward to do iterations in Go, we had to create a custom function indexOf
to check our string slice like so:
func indexOf(status string, data []string) int {
for k, v := range data {
if status == v {
return k
}
}
return -1
}
func StartIssue(jiraClient *jira.Client, issueId string) error {
allowed := []string{"Ready", "Start"}
transitions, _, _ := jiraClient.Issue.GetTransitions(issueId)
nextTransition := transitions[0]
if indexOf(nextTransition.Name, allowed) > -1 {
_, err := jiraClient.Issue.DoTransition(issueId, nextTransition.ID)
if err != nil {
return err
}
_ = StartIssue(jiraClient, issueId)
}
return nil
}
That’s it for today, hope you find it helpful. Tonight we’ll continue our little adventure of learning Go, join us!