Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add jira client cli tool #1561

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions tools/jira_client/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
module github.com/smartcontractkit/chainlink-testing-framework/tools/jiraclient

go 1.23.3

require (
github.com/andygrunwald/go-jira v1.16.0 // indirect
github.com/fatih/structs v1.1.0 // indirect
github.com/golang-jwt/jwt/v4 v4.4.2 // indirect
github.com/google/go-querystring v1.1.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/spf13/cobra v1.8.1 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/trivago/tgo v1.0.7 // indirect
)
28 changes: 28 additions & 0 deletions tools/jira_client/go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
github.com/andygrunwald/go-jira v1.16.0 h1:PU7C7Fkk5L96JvPc6vDVIrd99vdPnYudHu4ju2c2ikQ=
github.com/andygrunwald/go-jira v1.16.0/go.mod h1:UQH4IBVxIYWbgagc0LF/k9FRs9xjIiQ8hIcC6HfLwFU=
github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/fatih/structs v1.1.0 h1:Q7juDM0QtcnhCpeyLGQKyg4TOIghuNXrkL32pHAUMxo=
github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M=
github.com/golang-jwt/jwt/v4 v4.4.2 h1:rcc4lwaZgFMCZ5jxF9ABolDcIHdBytAFgqFPbSJQAYs=
github.com/golang-jwt/jwt/v4 v4.4.2/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8=
github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM=
github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/trivago/tgo v1.0.7 h1:uaWH/XIy9aWYWpjm2CU3RpcqZXmX2ysQ9/Go+d9gyrM=
github.com/trivago/tgo v1.0.7/go.mod h1:w4dpD+3tzNIIiIfkWWa85w5/B77tlvdZckQ+6PkFnhc=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20220330033206-e17cdc41300f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
311 changes: 311 additions & 0 deletions tools/jira_client/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,311 @@
package main

import (
"context"
"fmt"
"log"
"os"
"strings"

"github.com/andygrunwald/go-jira"
"github.com/spf13/cobra"
)

// Flags for subcommands
var (
projectKey string
issueKey string
summary string
description string
issueType string
commentBody string
transitionName string
resolutionName string
)

// rootCmd is the base command
var rootCmd = &cobra.Command{
Use: "jira-cli",
Short: "A CLI tool to interact with Jira",
Long: `jira-cli is a command line interface tool that uses the go-jira library
to list, create, and update Jira tickets. Jira domain, email, and API key
must be provided as environment variables:

JIRA_DOMAIN, JIRA_EMAIL, JIRA_API_KEY
`,
}

// listCmd lists the tickets in a project
var listCmd = &cobra.Command{
Use: "list",
Short: "List tickets in a project",
Run: func(cmd *cobra.Command, args []string) {
client, err := getJiraClient()
if err != nil {
log.Fatalf("Error creating Jira client: %v", err)
}

if projectKey == "" {
log.Fatal("Project key is required (use --projectKey)")
}

jql := fmt.Sprintf("project = %s ORDER BY created DESC", projectKey)
issues, _, err := client.Issue.SearchWithContext(context.Background(), jql, nil)
if err != nil {
log.Fatalf("Error fetching tickets: %v", err)
}

fmt.Printf("Tickets in project %s:\n", projectKey)
if len(issues) == 0 {
fmt.Println("No tickets found.")
return
}

for _, issue := range issues {
fmt.Printf("- %s: %s\n", issue.Key, issue.Fields.Summary)
}
},
}

// createCmd creates a new ticket in a project
var createCmd = &cobra.Command{
Use: "create",
Short: "Create a new ticket in a project",
Run: func(cmd *cobra.Command, args []string) {
client, err := getJiraClient()
if err != nil {
log.Fatalf("Error creating Jira client: %v", err)
}

if projectKey == "" {
log.Fatal("Project key is required (use --projectKey)")
}
if summary == "" {
log.Fatal("Summary is required (use --summary)")
}
if issueType == "" {
issueType = "Task" // default to "Task" if not provided
}

issue := &jira.Issue{
Fields: &jira.IssueFields{
Project: jira.Project{Key: projectKey},
Summary: summary,
Description: description,
Type: jira.IssueType{
Name: issueType,
},
},
}

newIssue, resp, err := client.Issue.Create(issue)
if err != nil {
log.Fatalf("Error creating ticket: %v\nResponse: %v", err, resp)
}

fmt.Printf("Ticket created! %v\n", newIssue)
},
}

// updateCmd updates an existing ticket
var updateCmd = &cobra.Command{
Use: "update",
Short: "Update an existing ticket",
Run: func(cmd *cobra.Command, args []string) {
client, err := getJiraClient()
if err != nil {
log.Fatalf("Error creating Jira client: %v", err)
}

if issueKey == "" {
log.Fatal("Issue key is required (use --issueKey)")
}

// Fetch the existing issue
issue, resp, err := client.Issue.Get(issueKey, nil)
if err != nil {
log.Fatalf("Error fetching issue %s: %v\nResponse: %v", issueKey, err, resp)
}

// Update only if flags were provided
if summary != "" {
issue.Fields.Summary = summary
}
if description != "" {
issue.Fields.Description = description
}

updatedIssue, resp, err := client.Issue.Update(issue)
if err != nil {
log.Fatalf("Error updating issue %s: %v\nResponse: %v", issueKey, err, resp)
}

fmt.Printf("Ticket updated! Key: %s Summary: %s\n", updatedIssue.Key, updatedIssue.Fields.Summary)
},
}

// commentCmd adds a comment to an existing ticket
var commentCmd = &cobra.Command{
Use: "comment",
Short: "Add a comment to an existing ticket",
Run: func(cmd *cobra.Command, args []string) {
client, err := getJiraClient()
if err != nil {
log.Fatalf("Error creating Jira client: %v", err)
}

if issueKey == "" {
log.Fatal("Issue key is required (use --issueKey)")
}
if commentBody == "" {
log.Fatal("Comment body is required (use --body)")
}

comment := &jira.Comment{
Body: commentBody,
}

newComment, resp, err := client.Issue.AddComment(issueKey, comment)
if err != nil {
log.Fatalf("Error adding comment to issue %s: %v\nResponse: %v", issueKey, err, resp)
}

fmt.Printf("Comment added to %s: %s\n", issueKey, newComment.Body)
},
}

// closeCmd transitions an issue to "Done", "Closed", or any target transitionName
var closeCmd = &cobra.Command{
Use: "close",
Short: "Close (transition) an existing ticket to a given state (e.g. Done)",
Long: `Attempt to transition the specified issue to a given state by name.
By default, tries to move the ticket to "Done" unless --transitionName is set.`,
Run: func(cmd *cobra.Command, args []string) {
client, err := getJiraClient()
if err != nil {
log.Fatalf("Error creating Jira client: %v", err)
}

if issueKey == "" {
log.Fatal("Issue key is required (use --issueKey)")
}
if transitionName == "" {
transitionName = "Done" // default transition name
}
if resolutionName == "" {
resolutionName = "Done" // default resolution if none provided
}

// 1. Get available transitions
transitions, resp, err := client.Issue.GetTransitions(issueKey)
if err != nil {
log.Fatalf("Error getting transitions for %s: %v\nResponse: %v", issueKey, err, resp)
}

// 2. Find the desired transition
var desiredID string
for _, t := range transitions {
if strings.EqualFold(t.Name, transitionName) {
desiredID = t.ID
break
}
}

if desiredID == "" {
log.Fatalf("Transition '%s' not found for issue %s. Available transitions: %v",
transitionName, issueKey, getTransitionNames(transitions))
}

// 3. Build transition payload with resolution
transitionPayload := jira.CreateTransitionPayload{
Transition: jira.TransitionPayload{
ID: desiredID,
},
Fields: jira.TransitionPayloadFields{
Resolution: &jira.Resolution{
Name: resolutionName,
},
},
}

// 4. Execute the transition with the payload
if _, err := client.Issue.DoTransitionWithPayload(issueKey, transitionPayload); err != nil {
log.Fatalf("Error transitioning issue %s to '%s' with resolution '%s': %v",
issueKey, transitionName, resolutionName, err)
}

fmt.Printf("Issue %s transitioned to '%s' (resolution: %s)\n", issueKey, transitionName, resolutionName)
},
}

func init() {
// Add subcommands to the root command
rootCmd.AddCommand(listCmd)
rootCmd.AddCommand(createCmd)
rootCmd.AddCommand(updateCmd)
rootCmd.AddCommand(commentCmd)
rootCmd.AddCommand(closeCmd)

// Flags for listing tickets
listCmd.Flags().StringVar(&projectKey, "projectKey", "", "Project key (e.g. TEST)")

// Flags for creating tickets
createCmd.Flags().StringVar(&projectKey, "projectKey", "", "Project key (e.g. TEST)")
createCmd.Flags().StringVar(&summary, "summary", "", "Issue summary")
createCmd.Flags().StringVar(&description, "description", "", "Issue description")
createCmd.Flags().StringVar(&issueType, "issueType", "Task", "Issue type (e.g. Task, Bug, Story)")

// Flags for updating tickets
updateCmd.Flags().StringVar(&issueKey, "issueKey", "", "Issue key to update (e.g. TEST-123)")
updateCmd.Flags().StringVar(&summary, "summary", "", "New summary for the issue")
updateCmd.Flags().StringVar(&description, "description", "", "New description for the issue")

// Flags for commenting
commentCmd.Flags().StringVar(&issueKey, "issueKey", "", "Issue key to comment on (e.g. TEST-123)")
commentCmd.Flags().StringVar(&commentBody, "body", "", "Comment body")

// Flags for closing tickets
closeCmd.Flags().StringVar(&issueKey, "issueKey", "", "Issue key to close (e.g. TEST-123)")
closeCmd.Flags().StringVar(&transitionName, "transitionName", "", "Name of the desired transition (default: Done)")
}

// main executes the root command
func main() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}

// getJiraClient constructs the Jira client using environment variables
func getJiraClient() (*jira.Client, error) {
domain := os.Getenv("JIRA_DOMAIN")
if domain == "" {
return nil, fmt.Errorf("JIRA_DOMAIN environment variable is not set")
}

email := os.Getenv("JIRA_EMAIL")
if email == "" {
return nil, fmt.Errorf("JIRA_EMAIL environment variable is not set")
}

apiKey := os.Getenv("JIRA_API_KEY")
if apiKey == "" {
return nil, fmt.Errorf("JIRA_API_KEY environment variable is not set")
}

tp := jira.BasicAuthTransport{
Username: email,
Password: apiKey,
}
return jira.NewClient(tp.Client(), fmt.Sprintf("https://%s", domain))
}

// getTransitionNames is a helper to format transition names for error messages
func getTransitionNames(transitions []jira.Transition) []string {
var names []string
for _, t := range transitions {
names = append(names, t.Name)
}
return names
}
Loading