Skip to content

Commit

Permalink
Merge pull request #18 from macanton/set-project-label-on-branch-crea…
Browse files Browse the repository at this point in the history
…tion

Set project label on branch creation
  • Loading branch information
macanton authored Jan 26, 2022
2 parents 26ac439 + caf46fd commit 9616fd7
Show file tree
Hide file tree
Showing 5 changed files with 149 additions and 1 deletion.
58 changes: 58 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import (
"got/pkg/config"
"got/pkg/git"
"got/pkg/jira"
"strings"
"sync"
)

func main() {
Expand All @@ -27,6 +29,8 @@ func main() {
linkJiraIssueToCurrentBranch()
case config.UnlinkJiraIssueFromCurrentBranch:
unlinkJiraIssueFromCurrentBranch()
case config.AddLabels:
addLabels()
}
}

Expand Down Expand Up @@ -54,6 +58,10 @@ func checkoutJiraBranch() {
return
}

var waitGroup sync.WaitGroup
waitGroup.Add(1)
go addRepoLabelToJiraIssue(&waitGroup, config.GetIssueKey())

branchName, err = git.GenerateBranchName([]string{issue.Key}, issue.Fields.Summary)
if err != nil {
printErrorToConsole(err)
Expand All @@ -66,6 +74,7 @@ func checkoutJiraBranch() {
return
}

waitGroup.Wait()
printInfoToConsole(string(output))
printJiraIssueData(issue)
}
Expand All @@ -77,6 +86,10 @@ func createJiraTicketAndCheckBranch() {
return
}

var waitGroup sync.WaitGroup
waitGroup.Add(1)
go addRepoLabelToJiraIssue(&waitGroup, issueKey)

branchName, err := git.GenerateBranchName([]string{issueKey}, config.Options.Summary)
if err != nil {
printErrorToConsole(err)
Expand All @@ -89,9 +102,35 @@ func createJiraTicketAndCheckBranch() {
return
}

waitGroup.Wait()
printInfoToConsole(string(output))
}

func addLabels() {
currentBranchName, err := git.GetCurrentBranchName()
if err != nil {
printErrorToConsole(err)
return
}

issueKeys := git.GetIssueKeysFromBranchName(currentBranchName)
if len(issueKeys) == 0 {
printErrorToConsole(fmt.Errorf(
"Branch name '%s' does not contain issue keys with prefix '%s'", currentBranchName, config.GetIssueKeyPrefix(),
))
return
}

issueKey := issueKeys[0]
newLabels, err := jira.AddIssueLabels(issueKey, config.Options.Labels)
if err != nil {
printErrorToConsole(err)
return
}

printInfoToConsole(fmt.Sprintf("Jira issue labels updated to '%s'", strings.Join(newLabels, ", ")))
}

func modifyBranch() {
currentBranchName, err := git.GetCurrentBranchName()
if err != nil {
Expand Down Expand Up @@ -205,6 +244,25 @@ func printInfo() {
}
}

func addRepoLabelToJiraIssue(waitGroup *sync.WaitGroup, issueKey string) {
defer waitGroup.Done()

repoName, err := git.GetRepositoryName()
if err != nil {
printErrorToConsole(err)
return
}

repoNameLabel := fmt.Sprintf("repo-%s", repoName)
newLabels, err := jira.AddIssueLabels(issueKey, []string{repoNameLabel})
if err != nil {
printErrorToConsole(err)
return
}

printInfoToConsole(fmt.Sprintf("Added labels to the Jira issue: '%s'", strings.Join(newLabels, ", ")))
}

func printInfoToConsole(data string) {
if len(data) > 0 {
fmt.Println(data)
Expand Down
28 changes: 28 additions & 0 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,14 @@ const (
PrintInfo OperationType = "PrintInfo"
LinkJiraIssueToCurrentBranch OperationType = "LinkJiraIssueToCurrentBranch"
UnlinkJiraIssueFromCurrentBranch OperationType = "UnlinkJiraIssueFromCurrentBranch"
AddLabels OperationType = "AddLabels"
)

// OptionsType is a type for stored app configuration
type OptionsType struct {
IssueCode int
Summary string
Labels []string
Operation OperationType
IssueBranchSeparator string
Jira struct {
Expand All @@ -50,6 +52,7 @@ func InitAndRequestAdditionalData() error {

ticketID := flag.Int("b", 0, "Jira ticket number key for new branch")
modifyBranch := flag.Bool("m", false, "Update branch name with Jira issue summary")
addLabels := flag.Bool("al", false, "Add labels to jira issue")
createIssue := flag.Bool("cj", false, "Create a new Jira issue and switch to the new branch")
printIssuesInfo := flag.Bool("info", false, "Print current branch Jira issues information")
issueCodeForLinking := flag.Int("lj", 0, "Links Jira Issue to current branch")
Expand Down Expand Up @@ -90,6 +93,12 @@ func InitAndRequestAdditionalData() error {
return err
}

if *addLabels {
Options.Operation = AddLabels
err := readLabels()
return err
}

if *printIssuesInfo {
Options.Operation = PrintInfo
return nil
Expand All @@ -108,6 +117,25 @@ func GetIssueKeyPrefix() string {
return fmt.Sprintf("%s-", Options.Jira.ProjectCode)
}

func readLabels() error {
fmt.Print("Enter Jira issue labels to add separated by space: ")

reader := bufio.NewReader(os.Stdin)
labels, err := reader.ReadString('\n')
if err != nil {
return fmt.Errorf("Failed to read string from buffer reader: %s", err.Error())
}

labels = strings.TrimSpace(labels)
if len(labels) == 0 {
return errors.New("Labels list cannot be an empty string")
}

Options.Labels = strings.Split(labels, " ")

return nil
}

func readJiraIssueSummary() error {
fmt.Print("Enter Jira issue summary: ")

Expand Down
16 changes: 16 additions & 0 deletions pkg/git/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,22 @@ import (
"strings"
)

// Returns name of repo from branch origin url
func GetRepositoryName() (string, error) {
cmd := exec.Command("git", "config", "--get", "remote.origin.url")
output, err := cmd.Output()
if err != nil {
return string(output), fmt.Errorf(
fmt.Sprintf("Failed get current git orgin url with error: '%s'", err.Error()),
)
}

repoName := strings.Split(string(output), ".git")[0]
tempRepoName := strings.Split(repoName, "/")

return tempRepoName[len(tempRepoName)-1], nil
}

// FindBranchBySubstring finds branch
func FindBranchBySubstring(substring string) (string, error) {
listAllBranchesCmd := exec.Command("git", "branch", "-a")
Expand Down
41 changes: 41 additions & 0 deletions pkg/jira/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,47 @@ func CreateIssue(summary string) (string, error) {
return response.Key, nil
}

// AddIssueLabels updates Jira issue summary
func AddIssueLabels(issueKey string, labels []string) ([]string, error) {
client := &http.Client{}

requestURL, err := getRequestURL(jiraOperationUpdateIssue, issueKey)
if err != nil {
return labels, err
}

var updateIssueLabels []UpdateIssueLabels
for _, label := range labels {
updateIssueLabels = append(updateIssueLabels, UpdateIssueLabels{Add: label}) // note the = instead of :=
}
formValues := UpdateIssueData{
Update: UpdateIssueDataFields{
Labels: updateIssueLabels,
},
}
formValuesByte, err := json.Marshal(formValues)
if err != nil {
return labels, err
}

req, err := http.NewRequest("PUT", requestURL, bytes.NewReader(formValuesByte))
if err != nil {
return labels, fmt.Errorf("Failed to convert form values to json. Error: '%s'", err)
}

setJiraRequestHeaders(req)
resp, err := client.Do(req)
if err != nil {
return labels, err
}

if resp.StatusCode != 204 {
return labels, fmt.Errorf("Failed to update Jira ticket. Status code: %d", resp.StatusCode)
}

return labels, nil
}

// UpdateIssueSummary updates Jira issue summary
func UpdateIssueSummary(issueKey string, summary string) (string, error) {
client := &http.Client{}
Expand Down
7 changes: 6 additions & 1 deletion pkg/jira/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,12 @@ type UpdateIssueData struct {

// UpdateIssueDataFields is a type for issue update data fields
type UpdateIssueDataFields struct {
Summary []UpdateIssueSummaryFieldOperationData `json:"summary"`
Summary []UpdateIssueSummaryFieldOperationData `json:"summary,omitempty"`
Labels []UpdateIssueLabels `json:"labels,omitempty"`
}

type UpdateIssueLabels struct {
Add string `json:"add"`
}

// UpdateIssueSummaryFieldOperationData is a type for issue summary set operation
Expand Down

0 comments on commit 9616fd7

Please sign in to comment.