Categorygithub.com/andygrunwald/go-jira
modulepackage
1.16.0
Repository: https://github.com/andygrunwald/go-jira.git
Documentation: pkg.go.dev

# README

go-jira

GoDoc Build Status Go Report Card

Go client library for Atlassian Jira.

Go client library for Atlassian Jira

Features

  • Authentication (HTTP Basic, OAuth, Session Cookie)
  • Create and retrieve issues
  • Create and retrieve issue transitions (status updates)
  • Call every API endpoint of the Jira, even if it is not directly implemented in this library

This package is not Jira API complete (yet), but you can call every API endpoint you want. See Call a not implemented API endpoint how to do this. For all possible API endpoints of Jira have a look at latest Jira REST API documentation.

Requirements

  • Go >= 1.14
  • Jira v6.3.4 & v7.1.2.

Note that we also run our tests against 1.13, though only the last two versions of Go are officially supported.

Installation

It is go gettable

go get github.com/andygrunwald/go-jira

For stable versions you can use one of our tags with gopkg.in. E.g.

package main

import (
	jira "gopkg.in/andygrunwald/go-jira.v1"
)
...

(optional) to run unit / example tests:

cd $GOPATH/src/github.com/andygrunwald/go-jira
go test -v ./...

API

Please have a look at the GoDoc documentation for a detailed API description.

The latest Jira REST API documentation was the base document for this package.

Examples

Further a few examples how the API can be used. A few more examples are available in the GoDoc examples section.

Get a single issue

Lets retrieve MESOS-3325 from the Apache Mesos project.

package main

import (
	"fmt"
	jira "github.com/andygrunwald/go-jira"
)

func main() {
	jiraClient, _ := jira.NewClient(nil, "https://issues.apache.org/jira/")
	issue, _, _ := jiraClient.Issue.Get("MESOS-3325", nil)

	fmt.Printf("%s: %+v\n", issue.Key, issue.Fields.Summary)
	fmt.Printf("Type: %s\n", issue.Fields.Type.Name)
	fmt.Printf("Priority: %s\n", issue.Fields.Priority.Name)

	// MESOS-3325: Running [email protected] in a container causes slave to be lost after a restart
	// Type: Bug
	// Priority: Critical
}

Authentication

The go-jira library does not handle most authentication directly. Instead, authentication should be handled within an http.Client. That client can then be passed into the NewClient function when creating a jira client.

For convenience, capability for basic and cookie-based authentication is included in the main library.

Token (Jira on Atlassian Cloud)

Token-based authentication uses the basic authentication scheme, with a user-generated API token in place of a user's password. You can generate a token for your user here. Additional information about Atlassian Cloud API tokens can be found here.

A more thorough, runnable example is provided in the examples directory.

func main() {
	tp := jira.BasicAuthTransport{
		Username: "username",
		Password: "token",
	}

	client, err := jira.NewClient(tp.Client(), "https://my.jira.com")

	u, _, err := client.User.Get("some_user")

	fmt.Printf("\nEmail: %v\nSuccess!\n", u.EmailAddress)
}

Basic (self-hosted Jira)

Password-based API authentication works for self-hosted Jira only, and has been deprecated for users of Atlassian Cloud.

The above token authentication example may be used, substituting a user's password for a generated token.

Authenticate with OAuth

If you want to connect via OAuth to your Jira Cloud instance checkout the example of using OAuth authentication with Jira in Go by @Lupus.

For more details have a look at the issue #56.

Create an issue

Example how to create an issue.

package main

import (
	"fmt"
	"github.com/andygrunwald/go-jira"
)

func main() {
	base := "https://my.jira.com"
	tp := jira.BasicAuthTransport{
		Username: "username",
		Password: "token",
	}

	jiraClient, err := jira.NewClient(tp.Client(), base)
	if err != nil {
		panic(err)
	}

	i := jira.Issue{
		Fields: &jira.IssueFields{
			Assignee: &jira.User{
				Name: "myuser",
			},
			Reporter: &jira.User{
				Name: "youruser",
			},
			Description: "Test Issue",
			Type: jira.IssueType{
				Name: "Bug",
			},
			Project: jira.Project{
				Key: "PROJ1",
			},
			Summary: "Just a demo issue",
		},
	}
	issue, _, err := jiraClient.Issue.Create(&i)
	if err != nil {
		panic(err)
	}

	fmt.Printf("%s: %+v\n", issue.Key, issue.Fields.Summary)
}

Change an issue status

This is how one can change an issue status. In this example, we change the issue from "To Do" to "In Progress."

package main

import (
	"fmt"
	"github.com/andygrunwald/go-jira"
)

func main() {
	base := "https://my.jira.com"
	tp := jira.BasicAuthTransport{
		Username: "username",
		Password: "token",
	}

	jiraClient, err := jira.NewClient(tp.Client(), base)
	if err != nil {
		panic(err)
	}

	issue, _, _ := jiraClient.Issue.Get("FART-1", nil)
	currentStatus := issue.Fields.Status.Name
	fmt.Printf("Current status: %s\n", currentStatus)

	var transitionID string
	possibleTransitions, _, _ := jiraClient.Issue.GetTransitions("FART-1")
	for _, v := range possibleTransitions {
		if v.Name == "In Progress" {
			transitionID = v.ID
			break
		}
	}

	jiraClient.Issue.DoTransition("FART-1", transitionID)
	issue, _, _ = jiraClient.Issue.Get(testIssueID, nil)
	fmt.Printf("Status after transition: %+v\n", issue.Fields.Status.Name)
}

Get all the issues for JQL with Pagination

Jira API has limit on maxResults it can return. You may have a usecase where you need to get all issues for given JQL. This example shows reference implementation of GetAllIssues function which does pagination on Jira API to get all the issues for given JQL

please look at Pagination Example

Call a not implemented API endpoint

Not all API endpoints of the Jira API are implemented into go-jira. But you can call them anyway: Lets get all public projects of Atlassian`s Jira instance.

package main

import (
	"fmt"
	"github.com/andygrunwald/go-jira"
)

func main() {
	base := "https://my.jira.com"
	tp := jira.BasicAuthTransport{
		Username: "username",
		Password: "token",
	}

	jiraClient, err := jira.NewClient(tp.Client(), base)
	req, _ := jiraClient.NewRequest("GET", "rest/api/2/project", nil)

	projects := new([]jira.Project)
	_, err = jiraClient.Do(req, projects)
	if err != nil {
		panic(err)
	}

	for _, project := range *projects {
		fmt.Printf("%s: %s\n", project.Key, project.Name)
	}

	// ...
	// BAM: Bamboo
	// BAMJ: Bamboo Jira Plugin
	// CLOV: Clover
	// CONF: Confluence
	// ...
}

Implementations

Code structure

The code structure of this package was inspired by google/go-github.

There is one main part (the client). Based on this main client the other endpoints, like Issues or Authentication are extracted in services. E.g. IssueService or AuthenticationService. These services own a responsibility of the single endpoints / usecases of Jira.

Contribution

We ❤️ PR's

Contribution, in any kind of way, is highly welcome! It doesn't matter if you are not able to write code. Creating issues or holding talks and help other people to use go-jira is contribution, too! A few examples:

  • Correct typos in the README / documentation
  • Reporting bugs
  • Implement a new feature or endpoint
  • Sharing the love of go-jira and help people to get use to it

If you are new to pull requests, checkout Collaborating on projects using issues and pull requests / Creating a pull request.

Dependency management

go-jira uses go modules for dependency management. After cloning the repo, it's easy to make sure you have the correct dependencies by running go mod tidy.

For adding new dependencies, updating dependencies, and other operations, the Daily workflow is a good place to start.

Sandbox environment for testing

Jira offers sandbox test environments at http://go.atlassian.com/cloud-dev.

You can read more about them at https://developer.atlassian.com/blog/2016/04/cloud-ecosystem-dev-env/.

Releasing

Install standard-version

npm i -g standard-version
standard-version
git push --tags

Manually copy/paste text from changelog (for this new version) into the release on Github.com. E.g.

https://github.com/andygrunwald/go-jira/releases/edit/v1.11.0

License

This project is released under the terms of the MIT license.

# Packages

# Functions

Bool is a helper routine that allocates a new bool value to store v and returns a pointer to it.
CheckResponse checks the API response for errors, and returns them if present.
InitIssueWithMetaAndFields returns Issue with with values from fieldsConfig properly set.
NewClient returns a new Jira API client.
NewJiraError creates a new jira Error.
WithAccountId sets the account id to search.
WithActive sets the active users lookup.
WithInactive sets the inactive users lookup.
WithMaxResults sets the max results to return.
WithProperty sets the property (Property keys are specified by path) to search.
Applies query options to http request.
WithStartAt set the start pager.
WithUsername sets the username to search.

# Constants

AssigneeAutomatic represents the value of the "Assignee: Automatic" of Jira.
These constants are the keys of the default Jira status categories.
These constants are the keys of the default Jira status categories.
These constants are the keys of the default Jira status categories.
These constants are the keys of the default Jira status categories.

# Structs

Actor represents a Jira actor.
ActorUser contains the account id of the actor/user.
Attachment represents a Jira attachment.
AuthenticationService handles authentication for the Jira instance / API.
AvatarUrls represents different dimensions of avatars / images.
BasicAuthTransport is an http.RoundTripper that authenticates all requests using HTTP Basic Authentication with the provided username and password.
BearerAuthTransport is a http.RoundTripper that authenticates all requests using Jira's bearer (oauth 2.0 (3lo)) based authentication.
Board represents a Jira agile board.
BoardConfiguration represents a boardConfiguration of a jira board.
BoardConfigurationColumn lists the name of the board with the statuses that maps to a particular column.
BoardConfigurationColumnConfig lists the columns for a given board in the order defined in the column configuration with constrainttype (none, issueCount, issueCountExclSubs).
BoardConfigurationColumnStatus represents a status in the column configuration.
BoardConfigurationFilter reference to the filter used by the given board.
BoardConfigurationLocation reference to the container that the board is located in.
BoardConfigurationSubQuery (Kanban only) - JQL subquery used by the given board.
BoardListOptions specifies the optional parameters to the BoardService.GetList.
BoardService handles Agile Boards for the Jira instance / API.
BoardsList reflects a list of agile boards.
Changelog reflects the change log of an issue.
ChangelogHistory reflects one single changelog history entry.
ChangelogItems reflects one single changelog item of a history item.
A Client manages communication with the Jira API.
Comment represents a comment by a person to an issue in Jira.
Comments represents a list of Comment.
CommentVisibility represents he visibility of a comment.
Component represents a "component" of a Jira issue.
ComponentService handles components for the Jira instance / API.// Jira API docs: https://docs.atlassian.com/software/jira/docs/api/REST/7.10.1/#api/2/component.
CookieAuthTransport is an http.RoundTripper that authenticates all requests using Jira's cookie-based authentication.
CreateComponentOptions are passed to the ComponentService.Create function to create a new Jira component.
CreateMetaInfo contains information about fields and their attributed to create a ticket.
CreateTransitionPayload is used for creating new issue transitions.
Customer represents a ServiceDesk customer.
CustomerList is a page of customers.
CustomerListOptions is the query options for listing customers.
CustomerService handles ServiceDesk customers for the Jira instance / API.
EditMetaInfo contains information about fields and their attributed to edit a ticket.
Epic represents the epic to which an issue is associated Not that this struct does not process the returned "color" value.
Error message from Jira See https://docs.atlassian.com/jira/REST/cloud/#error-responses.
Field represents a field of a Jira issue.
FieldSchema represents a schema of a Jira field.
FieldService handles fields for the Jira instance / API.
Filter represents a Filter in Jira.
FilterSearchOptions specifies the optional parameters for the Search method https://developer.atlassian.com/cloud/jira/platform/rest/v3/#api-rest-api-3-filter-search-get.
FilterService handles fields for the Jira instance / API.
FiltersList reflects a list of filters.
FiltersListItem represents a Filter of FiltersList in Jira.
FixVersion represents a software release in which an issue is fixed.
GetAllSprintsOptions specifies the optional parameters to the BoardService.GetList.
GetMyFiltersQueryOptions specifies the optional parameters for the Get My Filters method.
GetQueryOptions specifies the optional parameters for the Get Issue methods.
GetWorklogsQueryOptions specifies the optional parameters for the Get Worklogs method.
Group represents a Jira group.
GroupMember reflects a single member of a group.
GroupSearchOptions specifies the optional parameters for the Get Group methods.
GroupService handles Groups for the Jira instance / API.
Issue represents a Jira issue.
IssueFields represents single fields of a Jira issue.
IssueLink represents a link between two issues in Jira.
IssueLinkType represents a type of a link between to issues in Jira.
IssueLinkTypeService handles issue link types for the Jira instance / API.
IssueRenderedFields represents rendered fields of a Jira issue.
IssueService handles Issues for the Jira instance / API.
IssuesInSprintResult represents a wrapper struct for search result.
IssuesWrapper represents a wrapper struct for moving issues to sprint.
IssueType represents a type of a Jira issue.
JWTAuthTransport is an http.RoundTripper that authenticates all requests using Jira's JWT based authentication.
MetaIssueType represents the different issue types a project has.
MetaProject is the meta information about a project returned from createmeta api.
Option represents an option value in a SelectList or MultiSelect custom issue field.
Organization contains Organization data.
OrganizationCreationDTO is DTO for creat organization API.
OrganizationService handles Organizations for the Jira instance / API.
OrganizationUsersDTO contains organization user ids.
PagedDTO is response of a paged list.
Parent represents the parent of a Jira issue, to be used with subtask issue types.
PATAuthTransport is an http.RoundTripper that authenticates all requests using the Personal Access Token specified.
PermissionScheme represents the permission scheme for the project.
PermissionSchemeService handles permissionschemes for the Jira instance / API.
Priority represents a priority of a Jira issue.
PriorityService handles priorities for the Jira instance / API.
Progress represents the progress of a Jira issue.
Project represents a Jira Project.
ProjectCategory represents a single project category.
ProjectComponent represents a single component of a project.
ProjectService handles projects for the Jira instance / API.
PropertyKey contains Property key details.
PropertyKeys contains an array of PropertyKey.
RemoteLink represents remote links which linked to issues.
RemoteLinkApplication represents remote links application.
RemoteLinkIcon represents icon displayed next to link.
RemoteLinkObject represents remote link object itself.
RemoteLinkStatus if the link is a resolvable object (issue, epic) - the structure represent its status.
Request represents a ServiceDesk customer request.
RequestComment is a comment for a request.
RequestDate is the date format used in requests.
RequestFieldValue is a request field.
RequestService handles ServiceDesk customer requests for the Jira instance / API.
RequestStatus is the status for a request.
Resolution represents a resolution of a Jira issue.
ResolutionService handles resolutions for the Jira instance / API.
Response represents Jira API response.
Role represents a Jira product role.
RoleService handles roles for the Jira instance / API.
SearchOptions specifies the optional parameters to various List methods that support pagination.
SelfLink Stores REST API URL to the organization.
ServiceDeskOrganizationDTO is a DTO for ServiceDesk organizations.
ServiceDeskService handles ServiceDesk for the Jira instance / API.
Session represents a Session JSON response by the Jira API.
Sprint represents a sprint on Jira agile board.
SprintService handles sprints in Jira Agile API.
SprintsList reflects a list of agile sprints.
Status represents the current status of a Jira issue.
StatusCategory represents the category a status belongs to.
StatusCategoryService handles status categories for the Jira instance / API.
StatusService handles staties for the Jira instance / API.
Subtasks represents all issues of a parent issue.
TimeTracking represents the timetracking fields of a Jira issue.
Transition represents an issue transition in Jira.
TransitionField represents the value of one Transition.
TransitionPayload represents the request payload of Transition calls like DoTransition.
TransitionPayloadComment represents comment in Transition payload.
TransitionPayloadCommentBody represents body of comment in payload.
TransitionPayloadFields represents the fields that can be set when executing a transition.
TransitionPayloadUpdate represents the updates of Transition calls like DoTransition.
UpdateQueryOptions specifies the optional parameters to the Edit issue.
User represents a Jira user.
UserGroup represents the group list.
UserService handles users for the Jira instance / API.
Version represents a single release version of a project.
VersionService handles Versions for the Jira instance / API.
Watcher represents a simplified user that "observes" the issue.
Watches represents a type of how many and which user are "observing" a Jira issue to track the status / updates.
Worklog represents the work log of a Jira issue.
WorklogRecord represents one entry of a Worklog.

# Type aliases

AffectsVersion represents a software release which is affected by an issue.
CustomFields represents custom fields of Jira This can heavily differ between Jira instances.
Date represents the Date definition of Jira as a time.Time of go.
ProjectList represent a list of Projects.
Time represents the Time definition of Jira as a time.Time of go.