jira

package
v0.47.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 11, 2026 License: Apache-2.0 Imports: 28 Imported by: 0

Documentation

Overview

Package jira implements an HTTP client for the Jira Cloud REST API v3.

Index

Constants

View Source
const MaxMarkdownBytes = maxMarkdownParseBytes

MaxMarkdownBytes is the exported form of maxMarkdownParseBytes, for callers that assemble a markdown body destined for CreateComment/ UpdateComment (or MarkdownToADF directly) and need to cap its size before hitting the limit at write time rather than after.

Variables

This section is empty.

Functions

func ADFToMarkdown added in v0.37.0

func ADFToMarkdown(body any) string

ADFToMarkdown converts a Jira issue or comment body to CommonMark Markdown, the reverse of MarkdownToADF. body is either a plain string or an ADF document (map[string]any), matching the two shapes Jira's REST API returns for description/body fields; any other type (including nil) yields "".

Unlike ADFToPlainText, this preserves formatting (bold/italic/code/ links, headings, lists, blockquotes, code blocks, tables) rather than discarding it: tracker.Body is documented as Markdown-formatted text, so a Jira-backed tracker.Client returning plain text there would silently drop content GitHub- and GitLab-backed implementations preserve.

func ADFToPlainText added in v0.37.0

func ADFToPlainText(body any) string

ADFToPlainText extracts plain text from a Jira issue or comment body. body is either a plain string or an ADF document (map[string]any), matching the two shapes Jira's REST API returns for description/body fields; any other type (including nil) yields "".

func MarkdownToADF added in v0.37.0

func MarkdownToADF(source string) (map[string]any, error)

MarkdownToADF parses source as CommonMark (plus GFM tables) and returns an Atlassian Document Format (ADF) "doc" node, since Jira's comment/description fields don't accept markdown directly. It supports the block/inline vocabulary ADFToPlainText (and the read-side walker it mirrors in internal/jirapoll) already recognizes: paragraphs, headings, bullet/ordered lists, blockquotes, fenced/indented code blocks, thematic breaks, GFM tables, and the strong/em/code/link/hardBreak inline marks. Block-level constructs outside that vocabulary (raw HTML) fall back to a plain-text paragraph of their raw source rather than vanishing outright — ADF has no equivalent node for most of them, but dropping the content entirely would silently lose whatever a caller wrote (e.g. this repo's own <details> convention for collapsing output).

Returns an error, rather than a partial or empty result, if source is over maxMarkdownParseBytes or if it converts to no ADF content at all (e.g. markdown that's nothing but a chain of nested blockquotes deeper than maxADFWriteDepth): callers write the result straight to Jira, and silently posting a truncated or visibly empty comment is worse than failing the write.

func RolePriority added in v0.36.0

func RolePriority(roleName string) int

RolePriority returns the priority of a Jira project role name. Higher values take precedence when a user appears in multiple roles.

KNOWN LIMITATION (intentional for the MVP): matches by role name, not by the project's permission scheme. See mapJiraRole in internal/jirapoll and docs/guides/user/jira-integration.md#actor-role-resolution.

func ValidateBaseURL added in v0.37.0

func ValidateBaseURL(rawURL string) error

ValidateBaseURL checks that the base URL uses https, unless it points to a loopback address (for httptest servers), and rejects embedded credentials. Exported so other Jira-backed clients (e.g. tracker.JiraClient) can apply the same policy to base URLs they accept.

Types

type APIError

type APIError struct {
	StatusCode int
	Message    string
}

APIError represents an error response from the Jira API.

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) IsTransient added in v0.37.0

func (e *APIError) IsTransient() bool

IsTransient reports whether the API error represents a transient failure that may succeed on retry: server errors (500–504) and rate limits (429). This method satisfies the transientReporter interface used by forge.IsTransient.

func (*APIError) Unwrap

func (e *APIError) Unwrap() error

type ChangeItem

type ChangeItem struct {
	Field      string `json:"field"`
	From       string `json:"from"` // Stable ID of the previous value (e.g. status ID); survives renames
	To         string `json:"to"`   // Stable ID of the new value
	FromString string `json:"fromString"`
	ToString   string `json:"toString"`
}

ChangeItem describes a single field change within a changelog entry.

type ChangelogEntry

type ChangelogEntry struct {
	ID      string       `json:"id"`
	Author  User         `json:"author"`
	Created string       `json:"created"`
	Items   []ChangeItem `json:"items"`
}

ChangelogEntry represents a single changelog entry on a Jira issue.

type Comment

type Comment struct {
	ID   string `json:"id"`
	Body any    `json:"body"` // ADF object or string
	// Author is the account that originally created the comment;
	// UpdateAuthor is the account that last modified it (set by Jira on
	// edit). They differ when someone with Edit-All-Comments edits another
	// user's comment — the poller must attribute an edit-detected event to
	// the editor, not the author, to avoid running attacker-authored text
	// under the original author's role.
	Author       User   `json:"author"`
	UpdateAuthor User   `json:"updateAuthor"`
	Created      string `json:"created"`
	Updated      string `json:"updated"`
	// Properties holds entity properties when the comment was fetched
	// with ?expand=properties. Each property has a key and an arbitrary
	// JSON value. Properties are invisible to users in the Jira UI, so
	// they are used for sticky-comment marker storage instead of
	// embedding markers in visible ADF body text.
	Properties []CommentProperty `json:"properties,omitempty"`
}

Comment represents a single comment on a Jira issue.

type CommentPage

type CommentPage struct {
	Comments   []Comment `json:"comments"`
	Total      int       `json:"total"`
	MaxResults int       `json:"maxResults"`
	StartAt    int       `json:"startAt"`
}

CommentPage is a paginated list of comments.

type CommentProperty added in v0.40.0

type CommentProperty struct {
	Key   string          `json:"key"`
	Value json.RawMessage `json:"value"`
}

CommentProperty represents an entity property on a Jira comment. Properties are opaque key/value pairs stored alongside a comment that do not appear in the Jira UI.

type EntityPropertyValue

type EntityPropertyValue struct {
	Key   string          `json:"key"`
	Value json.RawMessage `json:"value"`
}

EntityPropertyValue wraps a JSON value stored as a Jira entity property.

type Issue

type Issue struct {
	ID     string      `json:"id"`
	Key    string      `json:"key"`
	Self   string      `json:"self"`
	Fields IssueFields `json:"fields"`
}

Issue represents a Jira issue.

type IssueFields

type IssueFields struct {
	Summary     string       `json:"summary"`
	Description any          `json:"description"` // ADF object or string
	Status      Status       `json:"status"`
	Labels      []string     `json:"labels"`
	Reporter    User         `json:"reporter"`
	Created     string       `json:"created"`
	Updated     string       `json:"updated"`
	Comment     *CommentPage `json:"comment,omitempty"`
	IssueType   *IssueType   `json:"issuetype,omitempty"`

	// CustomFields holds the raw JSON value of every "customfield_*" key
	// in the fields object, keyed by field ID (e.g. "customfield_10875").
	// Custom field IDs and value shapes vary per Jira instance, so values
	// are kept verbatim rather than decoded into a fixed type. Populated
	// only by unmarshalling; it is not serialized back out.
	CustomFields map[string]json.RawMessage `json:"-"`
}

IssueFields contains the standard fields of a Jira issue.

func (*IssueFields) UnmarshalJSON added in v0.46.0

func (f *IssueFields) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the standard fields and additionally collects every "customfield_*" key into CustomFields.

type IssueType added in v0.46.0

type IssueType struct {
	ID      string `json:"id"`
	Name    string `json:"name"`
	Subtask bool   `json:"subtask"`
}

IssueType represents the type of a Jira issue (e.g. Bug, Story, Task).

type LiveClient

type LiveClient struct {
	// contains filtered or unexported fields
}

LiveClient is an HTTP client for the Jira Cloud REST API v3.

func New

func New(token string, opts ...Option) (*LiveClient, error)

New creates a new Jira client with the given API token.

func (*LiveClient) CreateComment added in v0.37.0

func (c *LiveClient) CreateComment(ctx context.Context, issueIDOrKey, body string) (*Comment, error)

CreateComment adds a new comment to an issue. body is markdown; it's converted to ADF before being sent, since Jira Cloud doesn't accept markdown directly.

func (*LiveClient) CreateCommentWithProperties added in v0.40.0

func (c *LiveClient) CreateCommentWithProperties(ctx context.Context, issueIDOrKey, body string, properties []CommentProperty) (*Comment, error)

CreateCommentWithProperties adds a new comment to an issue with optional entity properties. body is markdown; it's converted to ADF before being sent, since Jira Cloud doesn't accept markdown directly. Properties are stored alongside the comment and are invisible in the Jira UI; they are used for sticky-comment marker storage.

func (*LiveClient) DeleteComment added in v0.40.0

func (c *LiveClient) DeleteComment(ctx context.Context, issueIDOrKey, commentID string) error

DeleteComment removes a comment by ID from the given issue.

func (*LiveClient) DeleteEntityProperty

func (c *LiveClient) DeleteEntityProperty(ctx context.Context, issueIDOrKey, propertyKey string) error

DeleteEntityProperty removes an entity property from an issue.

func (*LiveClient) GetCommentProperty added in v0.40.0

func (c *LiveClient) GetCommentProperty(ctx context.Context, issueIDOrKey, commentID, propertyKey string) (json.RawMessage, error)

GetCommentProperty retrieves the value of an entity property on a comment. Returns forge.ErrNotFound (wrapped) if the property does not exist.

func (*LiveClient) GetEntityProperty

func (c *LiveClient) GetEntityProperty(ctx context.Context, issueIDOrKey, propertyKey string) (json.RawMessage, error)

GetEntityProperty retrieves the value of an entity property on an issue. Returns forge.ErrNotFound (wrapped) if the property does not exist.

func (*LiveClient) GetIssue

func (c *LiveClient) GetIssue(ctx context.Context, issueIDOrKey string) (*Issue, error)

GetIssue fetches a single issue by ID or key.

func (*LiveClient) GetMyself

func (c *LiveClient) GetMyself(ctx context.Context) (*User, error)

GetMyself returns the currently authenticated user.

func (*LiveClient) GetProjectRoleActors added in v0.36.0

func (c *LiveClient) GetProjectRoleActors(ctx context.Context, projectKey string) (map[string]ProjectRoleActors, error)

GetProjectRoleActors returns the direct users and group assignments for each project role without enumerating group members. This avoids the 100-page pagination cap on the group/member endpoint that used to truncate large groups. Callers combine the returned structure with GetUserGroups for per-actor resolution.

func (*LiveClient) GetStatus

func (c *LiveClient) GetStatus(ctx context.Context, idOrName string) (*Status, error)

GetStatus fetches a single status by ID or name, including its statusCategory. Used to classify changelog status transitions by category rather than by matching locale/workflow-specific status name substrings.

func (*LiveClient) GetUserGroups added in v0.36.0

func (c *LiveClient) GetUserGroups(ctx context.Context, accountID string) ([]UserGroupInfo, error)

GetUserGroups returns the groups that the specified user belongs to, for per-actor role resolution that is not subject to the group/member pagination cap (see GetProjectRoleActors).

func (*LiveClient) LinkIssues added in v0.46.0

func (c *LiveClient) LinkIssues(ctx context.Context, inwardIssueKey, outwardIssueKey, linkTypeName string) error

LinkIssues creates a typed link between two issues via POST /rest/api/3/issueLink. linkTypeName is the instance-specific link type name (e.g. "Blocks", "Relates", "Cloners") and is passed through verbatim. Jira records the link in the link type's outward direction from inwardIssueKey to outwardIssueKey: for "Blocks", inwardIssueKey blocks outwardIssueKey.

func (*LiveClient) ListChangelog

func (c *LiveClient) ListChangelog(ctx context.Context, issueIDOrKey string) ([]ChangelogEntry, error)

ListChangelog fetches all changelog entries for an issue, exhausting pagination up to maxListPages pages.

func (*LiveClient) ListComments

func (c *LiveClient) ListComments(ctx context.Context, issueIDOrKey string) ([]Comment, error)

ListComments fetches all comments on an issue, exhausting pagination up to maxListPages pages. Comments include entity properties via ?expand=properties so callers can match sticky markers stored as comment properties instead of scanning body text.

func (*LiveClient) SearchIssues

func (c *LiveClient) SearchIssues(ctx context.Context, jql string, limit int) ([]Issue, error)

SearchIssues executes a JQL search and returns up to limit matching issues, using the POST /rest/api/3/search/jql endpoint with cursor-based pagination (nextPageToken + isLast). Pagination stops as soon as limit issues have been collected, so a limit smaller than the full match set bounds API cost rather than fetching everything and truncating afterward. A limit <= 0 fetches all matching issues, capped at maxSearchPages pages (10,000 issues at 50 per page) to prevent unbounded memory growth.

This endpoint is eventually consistent: Atlassian documents that recent updates might not be immediately visible in results. For the poller that only means an issue can appear (or re-sort under ORDER BY updated) a cycle late — per-issue checkpoints come from the strongly-consistent direct comment/changelog GETs, never from search results, so no events are lost. Do not "fix" ordering assumptions by trusting search freshness.

func (*LiveClient) SetCommentProperty added in v0.40.0

func (c *LiveClient) SetCommentProperty(ctx context.Context, issueIDOrKey, commentID, propertyKey string, value any) error

SetCommentProperty sets (creates or updates) an entity property on a comment. Used to store sticky-comment markers in a location invisible to Jira users.

func (*LiveClient) SetEntityProperty

func (c *LiveClient) SetEntityProperty(ctx context.Context, issueIDOrKey, propertyKey string, value any) error

SetEntityProperty sets (creates or updates) an entity property on an issue.

func (*LiveClient) UpdateComment added in v0.37.0

func (c *LiveClient) UpdateComment(ctx context.Context, issueIDOrKey, commentID, body string) error

UpdateComment replaces the body of an existing comment. body is markdown; it's converted to ADF before being sent, for the same reason as CreateComment.

type Option

type Option func(*LiveClient)

Option configures the Jira client.

func WithBaseURL

func WithBaseURL(rawURL string) Option

WithBaseURL sets a custom base URL for the Jira instance.

func WithEmail

func WithEmail(email string) Option

WithEmail sets the email address for Basic auth (Jira Cloud). When set, the client uses Authorization: Basic base64(email:token). When empty, the client uses Authorization: Bearer token (Cloud PAT). Note: despite the Bearer-auth option, this client's REST endpoints are Cloud-only (see apiURL) — Data Center is not currently supported.

func WithHTTPClient

func WithHTTPClient(client *http.Client) Option

WithHTTPClient sets a custom HTTP client for API calls.

type ProjectRoleActors added in v0.36.0

type ProjectRoleActors struct {
	DirectUsers map[string]bool // accountIDs directly assigned to this role
	GroupIDs    []string        // group IDs assigned to this role
}

ProjectRoleActors describes the direct users and group assignments for a project role without enumerating group members, so it is not subject to the group/member pagination cap.

type ProjectRoleDetail

type ProjectRoleDetail struct {
	Name   string      `json:"name"`
	Actors []RoleActor `json:"actors"`
}

ProjectRoleDetail is the response from GET /rest/api/3/project/{key}/role/{id}.

type ProjectRoleList

type ProjectRoleList map[string]string

ProjectRoleList is the response from GET /rest/api/3/project/{key}/role. It maps role names to their URLs. Example: {"Administrators": "https://.../role/10002", "Developers": "https://.../role/10001"}

type RoleActor

type RoleActor struct {
	ID          int             `json:"id"`
	DisplayName string          `json:"displayName"`
	Type        string          `json:"type"` // "atlassian-user-role-actor", "atlassian-group-role-actor"
	ActorUser   *RoleActorUser  `json:"actorUser,omitempty"`
	ActorGroup  *RoleActorGroup `json:"actorGroup,omitempty"`
}

RoleActor represents a member of a project role.

type RoleActorGroup

type RoleActorGroup struct {
	GroupID string `json:"groupId"`
	Name    string `json:"name"`
}

RoleActorGroup identifies a group granted a project role directly (as opposed to an individual user).

type RoleActorUser

type RoleActorUser struct {
	AccountID string `json:"accountId"`
}

RoleActorUser contains the account ID of a role actor.

type SearchResult

type SearchResult struct {
	Issues        []Issue `json:"issues"`
	NextPageToken string  `json:"nextPageToken,omitempty"`
	IsLast        bool    `json:"isLast"`
}

SearchResult is the response from the POST /rest/api/3/search/jql endpoint. Uses cursor-based pagination (nextPageToken + isLast).

type Status

type Status struct {
	Name           string         `json:"name"`
	StatusCategory StatusCategory `json:"statusCategory"`
}

Status represents the status of a Jira issue.

type StatusCategory

type StatusCategory struct {
	Key string `json:"key"`
}

StatusCategory groups statuses into broad categories. Key is one of "new", "indeterminate", or "done".

type User

type User struct {
	AccountID   string `json:"accountId"`
	Name        string `json:"name"` // Data Center/Server username; unset on Cloud. Unused today since this client only targets Cloud (see apiURL); kept for future Data Center support.
	DisplayName string `json:"displayName"`
	AccountType string `json:"accountType"` // "atlassian", "app", "customer"
	Active      bool   `json:"active"`
}

User represents a Jira user account.

type UserGroupInfo added in v0.36.0

type UserGroupInfo struct {
	Name    string `json:"name"`
	GroupID string `json:"groupId"`
	Self    string `json:"self"`
}

UserGroupInfo represents a group returned by GET /rest/api/3/user/groups. Used for per-actor role resolution that checks the actor's group memberships instead of enumerating all members of a role-assigned group.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL