Shared Atlassian clients: atlassian/jira and atlassian/confluence
New library module yetano.dev/yetano/yetano-clients (owner decision 2026-11-01) replacing the three own Jira clients in yareco, yabaratla and yamcp: - atlassian: Options, Auth (api_token, basic, bearer/pat, cookie), Deployment (Cloud/Data Center), TLS, APIError and sentinel errors. - atlassian/internal/transport: retry with backoff on 5xx/connection errors, shared adaptive 429 throttle honouring Retry-After (from yabaratla/yareco), CA file, proxy, cross-host redirect hardening, response cap (from yamcp), startAt pagination, file downloads. - atlassian/jira: typed reads (projects, versions, fields, issues, comments, changelog, editmeta, transitions), JQL search on Cloud (/search/jql) and Data Center, classic search pages, issue writes, ADF/plain-text bodies per deployment, custom-field helpers. - atlassian/confluence: small content API client (CQL search, pages, spaces, current user, create/update page with version check, comment, label), taken over from yamcp. Standard library only; tests against httptest servers. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
6a97dbd4c6
24 files changed
+3524
No files matched your search
@@ -0,0 +1,137 @@
|
||||
// Package jira is a Jira REST API client for Atlassian Cloud (REST API
|
||||
// v3, Atlassian Document Format bodies) and Server/Data Center (REST API
|
||||
// v2, plain-text/wiki-markup bodies).
|
||||
//
|
||||
// It offers typed calls for what the yetano programs use (projects,
|
||||
// versions, fields, JQL search, issues, comments, changelog, edit
|
||||
// metadata, transitions, issue writes) and the raw Get/Post/Put/Delete/
|
||||
// Paginate/DownloadFile underneath for everything else (the Agile API,
|
||||
// worklogs, attachments, ...). Every call takes a context; retries,
|
||||
// rate-limit handling and authentication are described on
|
||||
// atlassian.Options.
|
||||
package jira
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"yetano.dev/yetano/yetano-clients/atlassian"
|
||||
"yetano.dev/yetano/yetano-clients/atlassian/internal/transport"
|
||||
)
|
||||
|
||||
// Client is a Jira client. It is safe for concurrent use.
|
||||
type Client struct {
|
||||
t *transport.Client
|
||||
cloud bool
|
||||
}
|
||||
|
||||
// New builds a Client. It sends no request; a bad TLS CA file or proxy
|
||||
// URL is the only error.
|
||||
func New(o atlassian.Options) (*Client, error) {
|
||||
t, err := transport.New(o)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Client{t: t, cloud: o.Deployment.IsCloud()}, nil
|
||||
}
|
||||
|
||||
// BaseURL is the site root without trailing slash.
|
||||
func (c *Client) BaseURL() string { return c.t.BaseURL() }
|
||||
|
||||
// HasCredentials reports whether any credentials are configured.
|
||||
func (c *Client) HasCredentials() bool { return c.t.HasCredentials() }
|
||||
|
||||
// IsCloud reports whether the client talks to Atlassian Cloud.
|
||||
func (c *Client) IsCloud() bool { return c.cloud }
|
||||
|
||||
// APIPrefix is /rest/api/3 on Cloud and /rest/api/2 on Server/Data
|
||||
// Center.
|
||||
func (c *Client) APIPrefix() string {
|
||||
if c.cloud {
|
||||
return "/rest/api/3"
|
||||
}
|
||||
return "/rest/api/2"
|
||||
}
|
||||
|
||||
func (c *Client) api(suffix string) string { return c.APIPrefix() + suffix }
|
||||
|
||||
// IssueURL is the browser URL of an issue.
|
||||
func (c *Client) IssueURL(key string) string {
|
||||
return fmt.Sprintf("%s/browse/%s", c.BaseURL(), key)
|
||||
}
|
||||
|
||||
// Close releases idle connections.
|
||||
func (c *Client) Close() { c.t.Close() }
|
||||
|
||||
// SetSleep replaces every wait (backoff, Retry-After, throttle,
|
||||
// APIDelay) -- for tests that must not really wait.
|
||||
func (c *Client) SetSleep(f func(ctx context.Context, d time.Duration) error) { c.t.SetSleep(f) }
|
||||
|
||||
// Get issues a GET against BaseURL+path and returns the JSON body.
|
||||
func (c *Client) Get(ctx context.Context, path string, params url.Values) (json.RawMessage, error) {
|
||||
return c.t.Do(ctx, http.MethodGet, path, params, nil)
|
||||
}
|
||||
|
||||
// Post issues a POST with a JSON body.
|
||||
func (c *Client) Post(ctx context.Context, path string, body any) (json.RawMessage, error) {
|
||||
return c.t.Do(ctx, http.MethodPost, path, nil, body)
|
||||
}
|
||||
|
||||
// Put issues a PUT with a JSON body.
|
||||
func (c *Client) Put(ctx context.Context, path string, body any) (json.RawMessage, error) {
|
||||
return c.t.Do(ctx, http.MethodPut, path, nil, body)
|
||||
}
|
||||
|
||||
// Delete issues a DELETE.
|
||||
func (c *Client) Delete(ctx context.Context, path string, params url.Values) (json.RawMessage, error) {
|
||||
return c.t.Do(ctx, http.MethodDelete, path, params, nil)
|
||||
}
|
||||
|
||||
// Paginate walks a startAt/maxResults listing and returns every element
|
||||
// of the itemsKey array ("values" for most endpoints, "comments" for
|
||||
// issue comments) across all pages.
|
||||
func (c *Client) Paginate(ctx context.Context, path string, params url.Values, itemsKey string, pageSize int) ([]json.RawMessage, error) {
|
||||
return c.t.Paginate(ctx, path, params, itemsKey, pageSize)
|
||||
}
|
||||
|
||||
// DownloadFile streams fileURL (absolute, or a path starting with "/")
|
||||
// to dest, retrying and removing partial files; see
|
||||
// atlassian.Options.DownloadTimeout. Credentials are not sent along a
|
||||
// redirect to another host.
|
||||
func (c *Client) DownloadFile(ctx context.Context, fileURL, dest string) error {
|
||||
return c.t.DownloadFile(ctx, fileURL, dest)
|
||||
}
|
||||
|
||||
func decodeAll[T any](raw []json.RawMessage) ([]T, error) {
|
||||
out := make([]T, 0, len(raw))
|
||||
for _, r := range raw {
|
||||
var v T
|
||||
if err := json.Unmarshal(r, &v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, v)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *Client) getInto(ctx context.Context, path string, params url.Values, out any) error {
|
||||
raw, err := c.Get(ctx, path, params)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := json.Unmarshal(raw, out); err != nil {
|
||||
return fmt.Errorf("GET %s: decoding response: %w", path, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func requireKey(what, v string) error {
|
||||
if v == "" {
|
||||
return fmt.Errorf("%w: %s must not be empty", atlassian.ErrInvalidArgument, what)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package jira
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Names returns the names of a list of Named/Version values.
|
||||
func Names[T Named | Version](items []T) []string {
|
||||
out := make([]string, 0, len(items))
|
||||
for _, it := range items {
|
||||
switch v := any(it).(type) {
|
||||
case Named:
|
||||
out = append(out, v.Name)
|
||||
case Version:
|
||||
out = append(out, v.Name)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// OptionValues reads a select/multi-select/label-like field value as a
|
||||
// list of strings: null, a string, a list of strings, an option object
|
||||
// {"value": ...} (or {"name": ...}) or a list of those. A value of any
|
||||
// other shape is an error, never silently empty -- a field mapped to the
|
||||
// wrong field ID must be noticed.
|
||||
func OptionValues(raw json.RawMessage) ([]string, error) {
|
||||
s := strings.TrimSpace(string(raw))
|
||||
if len(raw) == 0 || s == "null" {
|
||||
return nil, nil
|
||||
}
|
||||
var str string
|
||||
if json.Unmarshal(raw, &str) == nil {
|
||||
return nonEmpty(str), nil
|
||||
}
|
||||
if strings.HasPrefix(s, "{") {
|
||||
var opt struct {
|
||||
Value *string `json:"value"`
|
||||
Name *string `json:"name"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &opt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch {
|
||||
case opt.Value != nil:
|
||||
return nonEmpty(*opt.Value), nil
|
||||
case opt.Name != nil:
|
||||
return nonEmpty(*opt.Name), nil
|
||||
}
|
||||
return nil, fmt.Errorf("unexpected field value %s", abbreviate(s))
|
||||
}
|
||||
var list []json.RawMessage
|
||||
if err := json.Unmarshal(raw, &list); err != nil {
|
||||
return nil, fmt.Errorf("unexpected field value %s", abbreviate(s))
|
||||
}
|
||||
var out []string
|
||||
for _, item := range list {
|
||||
vals, err := OptionValues(item)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, vals...)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Sprint is one entry of the Jira Software sprint field.
|
||||
type Sprint struct {
|
||||
Name string `json:"name"`
|
||||
State string `json:"state"` // active, future or closed
|
||||
}
|
||||
|
||||
var rxLegacySprint = regexp.MustCompile(`(?:^|[\[,])(state|name)=([^,\]]*)`)
|
||||
|
||||
// SprintValues reads the sprint field: null, a list of sprint objects
|
||||
// (Cloud) or a list of the legacy
|
||||
// "com.atlassian.greenhopper.service.sprint.Sprint@…[state=…,name=…]"
|
||||
// strings (older Data Center). States are lower-cased. Like
|
||||
// OptionValues, any other shape is an error, never silently "no sprint".
|
||||
func SprintValues(raw json.RawMessage) ([]Sprint, error) {
|
||||
s := strings.TrimSpace(string(raw))
|
||||
if len(raw) == 0 || s == "null" {
|
||||
return nil, nil
|
||||
}
|
||||
var list []json.RawMessage
|
||||
if err := json.Unmarshal(raw, &list); err != nil {
|
||||
return nil, fmt.Errorf("unexpected sprint value %s", abbreviate(s))
|
||||
}
|
||||
var out []Sprint
|
||||
for _, item := range list {
|
||||
var legacy string
|
||||
if json.Unmarshal(item, &legacy) == nil {
|
||||
var sp Sprint
|
||||
for _, m := range rxLegacySprint.FindAllStringSubmatch(legacy, -1) {
|
||||
if m[1] == "name" {
|
||||
sp.Name = m[2]
|
||||
} else {
|
||||
sp.State = strings.ToLower(m[2])
|
||||
}
|
||||
}
|
||||
if sp.Name == "" {
|
||||
return nil, fmt.Errorf("unexpected sprint value %s", abbreviate(legacy))
|
||||
}
|
||||
out = append(out, sp)
|
||||
continue
|
||||
}
|
||||
var sp Sprint
|
||||
if err := json.Unmarshal(item, &sp); err != nil || sp.Name == "" {
|
||||
return nil, fmt.Errorf("unexpected sprint value %s", abbreviate(string(item)))
|
||||
}
|
||||
sp.State = strings.ToLower(sp.State)
|
||||
out = append(out, sp)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func nonEmpty(s string) []string {
|
||||
if s = strings.TrimSpace(s); s == "" {
|
||||
return nil
|
||||
}
|
||||
return []string{s}
|
||||
}
|
||||
|
||||
func abbreviate(s string) string {
|
||||
if len(s) > 80 {
|
||||
return s[:80] + "…"
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
var rxCustomField = regexp.MustCompile(`^customfield_(\d+)$`)
|
||||
|
||||
// CustomFieldNumber returns "11411" for "customfield_11411" (the cf[N]
|
||||
// JQL form), ok=false for a system field.
|
||||
func CustomFieldNumber(id string) (string, bool) {
|
||||
m := rxCustomField.FindStringSubmatch(id)
|
||||
if m == nil {
|
||||
return "", false
|
||||
}
|
||||
return m[1], true
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
package jira
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"yetano.dev/yetano/yetano-clients/atlassian"
|
||||
)
|
||||
|
||||
func newTestClient(t *testing.T, h http.HandlerFunc, dep atlassian.Deployment) *Client {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(h)
|
||||
t.Cleanup(srv.Close)
|
||||
c, err := New(atlassian.Options{BaseURL: srv.URL + "/", Deployment: dep, MaxRetries: 1,
|
||||
Auth: atlassian.Auth{Type: atlassian.AuthAPIToken, Username: "e@example.com", Password: "t"},
|
||||
Logger: slog.New(slog.NewTextHandler(io.Discard, nil))})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c.SetSleep(func(ctx context.Context, _ time.Duration) error { return ctx.Err() })
|
||||
return c
|
||||
}
|
||||
|
||||
func TestAPIPrefixByDeployment(t *testing.T) {
|
||||
noop := func(http.ResponseWriter, *http.Request) {}
|
||||
if p := newTestClient(t, noop, "").APIPrefix(); p != "/rest/api/3" {
|
||||
t.Errorf("zero deployment prefix = %q, want Cloud's /rest/api/3", p)
|
||||
}
|
||||
if p := newTestClient(t, noop, atlassian.DataCenter).APIPrefix(); p != "/rest/api/2" {
|
||||
t.Errorf("datacenter prefix = %q", p)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSearchCloudFollowsNextPageToken(t *testing.T) {
|
||||
var bodies []map[string]any
|
||||
c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost || r.URL.Path != "/rest/api/3/search/jql" {
|
||||
t.Errorf("unexpected %s %s", r.Method, r.URL.Path)
|
||||
}
|
||||
var body map[string]any
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
bodies = append(bodies, body)
|
||||
if body["nextPageToken"] == nil {
|
||||
fmt.Fprint(w, `{"issues":[{"key":"DEV-1","fields":{"summary":"a","customfield_1":[{"value":"PI28.15"}]}}],"nextPageToken":"p2"}`)
|
||||
return
|
||||
}
|
||||
fmt.Fprint(w, `{"issues":[{"key":"DEV-2","fields":{"summary":"b"}}],"isLast":true}`)
|
||||
}, atlassian.Cloud)
|
||||
issues, err := c.SearchAll(context.Background(), SearchQuery{JQL: "project = DEV", Fields: []string{"summary", "customfield_1"}, PageSize: 1})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(issues) != 2 || issues[0].Key != "DEV-1" || issues[1].Key != "DEV-2" {
|
||||
t.Fatalf("issues = %+v", issues)
|
||||
}
|
||||
if bodies[1]["nextPageToken"] != "p2" || bodies[0]["maxResults"].(float64) != 1 {
|
||||
t.Errorf("request bodies = %v", bodies)
|
||||
}
|
||||
pis, err := OptionValues(issues[0].Fields.Raw["customfield_1"])
|
||||
if err != nil || len(pis) != 1 || pis[0] != "PI28.15" {
|
||||
t.Errorf("custom field = %v, %v", pis, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSearchDataCenterUsesOffsets(t *testing.T) {
|
||||
var starts []float64
|
||||
c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/rest/api/2/search" {
|
||||
t.Errorf("unexpected path %s", r.URL.Path)
|
||||
}
|
||||
var body map[string]any
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
start := body["startAt"].(float64)
|
||||
starts = append(starts, start)
|
||||
if exp, _ := body["expand"].([]any); len(exp) != 2 {
|
||||
t.Errorf("expand = %v, want a list of 2", body["expand"])
|
||||
}
|
||||
fmt.Fprintf(w, `{"startAt":%v,"total":3,"issues":[{"key":"OPS-%v"},{"key":"OPS-x"}]}`, start, start)
|
||||
}, atlassian.DataCenter)
|
||||
issues, err := c.SearchAll(context.Background(), SearchQuery{JQL: "project = OPS", PageSize: 2, Expand: "renderedFields, changelog"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(issues) != 4 || len(starts) != 2 || starts[1] != 2 {
|
||||
t.Errorf("issues = %d, starts = %v", len(issues), starts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSearchPageClassic(t *testing.T) {
|
||||
c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/rest/api/3/search" {
|
||||
t.Errorf("unexpected path %s", r.URL.Path)
|
||||
}
|
||||
var body PageQuery
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
if body.JQL != "project = OPS" || body.MaxResults != 25 || body.StartAt != 25 {
|
||||
t.Errorf("body = %+v", body)
|
||||
}
|
||||
fmt.Fprint(w, `{"startAt":25,"maxResults":25,"total":100,"issues":[{"key":"OPS-1","fields":{"summary":"first"}}]}`)
|
||||
}, atlassian.Cloud)
|
||||
res, err := c.SearchPage(context.Background(), PageQuery{JQL: "project = OPS", StartAt: 25, MaxResults: 25})
|
||||
if err != nil || res.Total != 100 || len(res.Issues) != 1 || res.Issues[0].Fields.Summary != "first" {
|
||||
t.Fatalf("res = %+v, %v", res, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmptyArgumentsSendNothing(t *testing.T) {
|
||||
c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
t.Errorf("request sent: %s %s", r.Method, r.URL.Path)
|
||||
}, atlassian.Cloud)
|
||||
ctx := context.Background()
|
||||
checks := map[string]error{}
|
||||
_, checks["Issue"] = c.Issue(ctx, "", nil)
|
||||
_, checks["Project"] = c.Project(ctx, "")
|
||||
_, checks["SearchPage"] = c.SearchPage(ctx, PageQuery{})
|
||||
checks["Search"] = c.Search(ctx, SearchQuery{JQL: " "}, func([]Issue) error { return nil })
|
||||
checks["EditIssue"] = c.EditIssue(ctx, "", IssueEdit{})
|
||||
for name, err := range checks {
|
||||
if !errors.Is(err, atlassian.ErrInvalidArgument) {
|
||||
t.Errorf("%s: err = %v, want ErrInvalidArgument", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestListProjectsPerDeployment(t *testing.T) {
|
||||
var paths []string
|
||||
cloud := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
paths = append(paths, r.URL.Path+"?"+r.URL.Query().Get("orderBy")+"@"+r.URL.Query().Get("startAt"))
|
||||
if r.URL.Query().Get("startAt") == "0" {
|
||||
fmt.Fprint(w, `{"isLast":false,"values":[{"id":"1","key":"DEV","name":"Development","projectTypeKey":"software"}]}`)
|
||||
return
|
||||
}
|
||||
fmt.Fprint(w, `{"isLast":true,"values":[{"id":"2","key":"OPS","projectTypeKey":"service_desk"}]}`)
|
||||
}, atlassian.Cloud)
|
||||
got, err := cloud.ListProjects(context.Background())
|
||||
if err != nil || len(got) != 2 || got[1].ProjectTypeKey != "service_desk" {
|
||||
t.Fatalf("cloud projects = %+v, %v", got, err)
|
||||
}
|
||||
if strings.Join(paths, ",") != "/rest/api/3/project/search?key@0,/rest/api/3/project/search?key@1" {
|
||||
t.Errorf("cloud requests = %v", paths)
|
||||
}
|
||||
|
||||
dc := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/rest/api/2/project" {
|
||||
t.Errorf("datacenter path = %s", r.URL.Path)
|
||||
}
|
||||
fmt.Fprint(w, `[{"key":"OPS"}]`)
|
||||
}, atlassian.DataCenter)
|
||||
if got, err := dc.ListProjects(context.Background()); err != nil || len(got) != 1 {
|
||||
t.Fatalf("dc projects = %+v, %v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCommentsFromOffset(t *testing.T) {
|
||||
c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
if q.Get("startAt") != "2" || q.Get("orderBy") != "created" {
|
||||
t.Errorf("query = %v", q)
|
||||
}
|
||||
fmt.Fprint(w, `{"total":3,"comments":[{"id":"3","created":"2026-05-01T10:00:00.000+0200"}]}`)
|
||||
}, atlassian.Cloud)
|
||||
cs, err := c.Comments(context.Background(), "DEV-1", 2)
|
||||
if err != nil || len(cs) != 1 || cs[0].ID != "3" {
|
||||
t.Fatalf("comments = %+v, %v", cs, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEditIssueSendsOnlyNonEmptyParts(t *testing.T) {
|
||||
var got []string
|
||||
c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
got = append(got, string(b))
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}, atlassian.Cloud)
|
||||
ctx := context.Background()
|
||||
if err := c.EditIssue(ctx, "DEV-1", IssueEdit{Update: map[string][]map[string]any{"labels": {{"add": "x"}}}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := c.UpdateIssue(ctx, "DEV-1", map[string]any{"summary": "s"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got[0] != `{"update":{"labels":[{"add":"x"}]}}` || got[1] != `{"fields":{"summary":"s"}}` {
|
||||
t.Errorf("bodies = %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWritesPerDeployment(t *testing.T) {
|
||||
for _, dep := range []atlassian.Deployment{atlassian.Cloud, atlassian.DataCenter} {
|
||||
var bodies = map[string]map[string]any{}
|
||||
c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
var body map[string]any
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
bodies[r.Method+" "+r.URL.Path] = body
|
||||
switch {
|
||||
case strings.HasSuffix(r.URL.Path, "/comment"):
|
||||
fmt.Fprint(w, `{"id":"77"}`)
|
||||
case strings.HasSuffix(r.URL.Path, "/issue"):
|
||||
fmt.Fprint(w, `{"id":"1","key":"OPS-9"}`)
|
||||
default:
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
}, dep)
|
||||
ctx := context.Background()
|
||||
key, err := c.CreateIssue(ctx, CreateIssueInput{ProjectKey: "OPS", IssueType: "Task", Summary: "s", Description: "d", ParentKey: "OPS-1"})
|
||||
if err != nil || key != "OPS-9" {
|
||||
t.Fatalf("%s: create = %q, %v", dep, key, err)
|
||||
}
|
||||
id, err := c.AddComment(ctx, "OPS-9", "hello")
|
||||
if err != nil || id != "77" {
|
||||
t.Fatalf("%s: comment = %q, %v", dep, id, err)
|
||||
}
|
||||
if err := c.AssignIssue(ctx, "OPS-9", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := c.DoTransition(ctx, "OPS-9", "31"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := c.LinkIssues(ctx, "Blocks", "OPS-1", "OPS-9"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
p := c.APIPrefix()
|
||||
fields := bodies["POST "+p+"/issue"]["fields"].(map[string]any)
|
||||
desc := fields["description"]
|
||||
comment := bodies["POST "+p+"/issue/OPS-9/comment"]["body"]
|
||||
assign := bodies["PUT "+p+"/issue/OPS-9/assignee"]
|
||||
if dep == atlassian.Cloud {
|
||||
if m, ok := desc.(map[string]any); !ok || m["type"] != "doc" {
|
||||
t.Errorf("cloud description = %v, want ADF", desc)
|
||||
}
|
||||
if _, ok := comment.(map[string]any); !ok {
|
||||
t.Errorf("cloud comment = %v, want ADF", comment)
|
||||
}
|
||||
if v, ok := assign["accountId"]; !ok || v != nil {
|
||||
t.Errorf("cloud unassign = %v, want accountId null", assign)
|
||||
}
|
||||
} else {
|
||||
if desc != "d" || comment != "hello" {
|
||||
t.Errorf("dc description/comment = %v / %v, want plain strings", desc, comment)
|
||||
}
|
||||
if v, ok := assign["name"]; !ok || v != nil {
|
||||
t.Errorf("dc unassign = %v, want name null", assign)
|
||||
}
|
||||
}
|
||||
if fields["parent"].(map[string]any)["key"] != "OPS-1" {
|
||||
t.Errorf("parent = %v", fields["parent"])
|
||||
}
|
||||
if tr := bodies["POST "+p+"/issue/OPS-9/transitions"]["transition"].(map[string]any); tr["id"] != "31" {
|
||||
t.Errorf("transition = %v", tr)
|
||||
}
|
||||
if l := bodies["POST "+p+"/issueLink"]; l["type"].(map[string]any)["name"] != "Blocks" {
|
||||
t.Errorf("link = %v", l)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEditMetaAndTransitions(t *testing.T) {
|
||||
c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/rest/api/3/issue/DEV-1/editmeta":
|
||||
fmt.Fprint(w, `{"fields":{"components":{"operations":["add","set","remove"]}}}`)
|
||||
case "/rest/api/3/issue/DEV-1/transitions":
|
||||
fmt.Fprint(w, `{"transitions":[{"id":"31","name":"Done","to":{"name":"Done"}}]}`)
|
||||
default:
|
||||
t.Errorf("unexpected %s", r.URL.Path)
|
||||
}
|
||||
}, atlassian.Cloud)
|
||||
meta, err := c.EditMeta(context.Background(), "DEV-1")
|
||||
if err != nil || len(meta["components"]) != 3 {
|
||||
t.Fatalf("editmeta = %v, %v", meta, err)
|
||||
}
|
||||
trs, err := c.Transitions(context.Background(), "DEV-1")
|
||||
if err != nil || len(trs) != 1 || trs[0].To.StatusName() != "Done" {
|
||||
t.Fatalf("transitions = %+v, %v", trs, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIssueRoundTripKeepsRawFields(t *testing.T) {
|
||||
in := `{"id":"1","key":"DEV-1","fields":{"summary":"s","customfield_9":{"value":"x"},"parent":{"key":"DEV-0"},"subtasks":[{"key":"DEV-2"}]}}`
|
||||
var is Issue
|
||||
if err := json.Unmarshal([]byte(in), &is); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if is.Fields.Parent.Key != "DEV-0" || len(is.Fields.Subtasks) != 1 || is.Fields.Raw["customfield_9"] == nil {
|
||||
t.Fatalf("issue = %+v", is)
|
||||
}
|
||||
out, _ := json.Marshal(is)
|
||||
if !strings.Contains(string(out), `"customfield_9":{"value":"x"}`) {
|
||||
t.Errorf("round trip lost a custom field: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOptionValuesShapes(t *testing.T) {
|
||||
cases := map[string][]string{
|
||||
`null`: nil,
|
||||
`"PI28.15"`: {"PI28.15"},
|
||||
`["PI28.15","PI28.22"]`: {"PI28.15", "PI28.22"},
|
||||
`{"value":"PI29.2"}`: {"PI29.2"},
|
||||
`{"name":"label"}`: {"label"},
|
||||
`[{"value":"PI29.2"},{"value":"PI29.3"}]`: {"PI29.2", "PI29.3"},
|
||||
}
|
||||
for in, want := range cases {
|
||||
got, err := OptionValues(json.RawMessage(in))
|
||||
if err != nil || strings.Join(got, "|") != strings.Join(want, "|") {
|
||||
t.Errorf("OptionValues(%s) = %v, %v; want %v", in, got, err, want)
|
||||
}
|
||||
}
|
||||
for _, bad := range []string{`{"foo":1}`, `42`} {
|
||||
if _, err := OptionValues(json.RawMessage(bad)); err == nil {
|
||||
t.Errorf("OptionValues(%s): unexpected shape must be an error", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSprintValuesShapes(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
`null`: "",
|
||||
`[]`: "",
|
||||
`[{"id":1,"name":"Sprint 41","state":"closed","boardId":3},{"id":2,"name":"Sprint 42","state":"ACTIVE"}]`: "Sprint 41/closed|Sprint 42/active",
|
||||
`["com.atlassian.greenhopper.service.sprint.Sprint@1a2b[id=7,rapidViewId=3,state=FUTURE,name=Sprint 43,startDate=<null>]"]`: "Sprint 43/future",
|
||||
}
|
||||
for in, want := range cases {
|
||||
got, err := SprintValues(json.RawMessage(in))
|
||||
var parts []string
|
||||
for _, sp := range got {
|
||||
parts = append(parts, sp.Name+"/"+sp.State)
|
||||
}
|
||||
if err != nil || strings.Join(parts, "|") != want {
|
||||
t.Errorf("SprintValues(%s) = %v, %v; want %s", in, got, err, want)
|
||||
}
|
||||
}
|
||||
for _, bad := range []string{`"Sprint 1"`, `{"name":"Sprint 1"}`, `[{"id":1}]`, `[42]`} {
|
||||
if _, err := SprintValues(json.RawMessage(bad)); err == nil {
|
||||
t.Errorf("SprintValues(%s): unexpected shape must be an error", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCustomFieldNumberAndNames(t *testing.T) {
|
||||
if n, ok := CustomFieldNumber("customfield_11411"); !ok || n != "11411" {
|
||||
t.Errorf("CustomFieldNumber = %q %v", n, ok)
|
||||
}
|
||||
if _, ok := CustomFieldNumber("summary"); ok {
|
||||
t.Error("system field reported as custom")
|
||||
}
|
||||
if got := Names([]Version{{Name: "a"}, {Name: "b"}}); strings.Join(got, ",") != "a,b" {
|
||||
t.Errorf("Names = %v", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package jira
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Myself returns the authenticated account -- the cheapest call that
|
||||
// proves URL and credentials work.
|
||||
func (c *Client) Myself(ctx context.Context) (User, error) {
|
||||
var u User
|
||||
return u, c.getInto(ctx, c.api("/myself"), nil, &u)
|
||||
}
|
||||
|
||||
// ServerInfo returns the instance's /serverInfo.
|
||||
func (c *Client) ServerInfo(ctx context.Context) (ServerInfo, error) {
|
||||
var si ServerInfo
|
||||
return si, c.getInto(ctx, c.api("/serverInfo"), nil, &si)
|
||||
}
|
||||
|
||||
// ListProjects returns every project the account can browse, ordered by
|
||||
// key. On Cloud it walks /project/search (archived and trashed projects
|
||||
// are not included); Server/Data Center returns all from /project.
|
||||
func (c *Client) ListProjects(ctx context.Context) ([]Project, error) {
|
||||
if !c.cloud {
|
||||
var out []Project
|
||||
return out, c.getInto(ctx, c.api("/project"), nil, &out)
|
||||
}
|
||||
raw, err := c.Paginate(ctx, c.api("/project/search"), url.Values{"orderBy": []string{"key"}}, "values", 50)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return decodeAll[Project](raw)
|
||||
}
|
||||
|
||||
// Project returns one project with description, lead and components.
|
||||
func (c *Client) Project(ctx context.Context, keyOrID string) (Project, error) {
|
||||
var p Project
|
||||
if err := requireKey("project key", keyOrID); err != nil {
|
||||
return p, err
|
||||
}
|
||||
return p, c.getInto(ctx, c.api("/project/"+url.PathEscape(keyOrID)), nil, &p)
|
||||
}
|
||||
|
||||
// ProjectVersions returns all versions of a project (unpaginated on this
|
||||
// endpoint).
|
||||
func (c *Client) ProjectVersions(ctx context.Context, keyOrID string) ([]Version, error) {
|
||||
var out []Version
|
||||
return out, c.getInto(ctx, c.api("/project/"+url.PathEscape(keyOrID)+"/versions"), nil, &out)
|
||||
}
|
||||
|
||||
// Version returns one version.
|
||||
func (c *Client) Version(ctx context.Context, id string) (Version, error) {
|
||||
var v Version
|
||||
return v, c.getInto(ctx, c.api("/version/"+url.PathEscape(id)), nil, &v)
|
||||
}
|
||||
|
||||
// Fields returns every system and custom field of the site.
|
||||
func (c *Client) Fields(ctx context.Context) ([]Field, error) {
|
||||
var out []Field
|
||||
return out, c.getInto(ctx, c.api("/field"), nil, &out)
|
||||
}
|
||||
|
||||
// Issue returns one issue. fields limits the returned fields (nil: Jira's
|
||||
// default, all navigable fields); expand is passed on as the expand
|
||||
// parameter (e.g. "renderedFields", "changelog").
|
||||
func (c *Client) Issue(ctx context.Context, keyOrID string, fields []string, expand ...string) (Issue, error) {
|
||||
var is Issue
|
||||
if err := requireKey("issue key", keyOrID); err != nil {
|
||||
return is, err
|
||||
}
|
||||
params := url.Values{}
|
||||
if len(fields) > 0 {
|
||||
params.Set("fields", strings.Join(fields, ","))
|
||||
}
|
||||
if len(expand) > 0 {
|
||||
params.Set("expand", strings.Join(expand, ","))
|
||||
}
|
||||
return is, c.getInto(ctx, c.api("/issue/"+url.PathEscape(keyOrID)), params, &is)
|
||||
}
|
||||
|
||||
// CommentPage returns one page of an issue's comments, oldest first.
|
||||
func (c *Client) CommentPage(ctx context.Context, keyOrID string, startAt, maxResults int) (CommentPage, error) {
|
||||
var page CommentPage
|
||||
q := url.Values{
|
||||
"orderBy": {"created"},
|
||||
"startAt": {strconv.Itoa(startAt)},
|
||||
"maxResults": {strconv.Itoa(maxResults)},
|
||||
}
|
||||
return page, c.getInto(ctx, c.api("/issue/"+url.PathEscape(keyOrID)+"/comment"), q, &page)
|
||||
}
|
||||
|
||||
// Comments returns an issue's comments from startAt on, oldest first. A
|
||||
// later start is useful because a search response already embeds the
|
||||
// first page.
|
||||
func (c *Client) Comments(ctx context.Context, keyOrID string, startAt int) ([]Comment, error) {
|
||||
var out []Comment
|
||||
for {
|
||||
page, err := c.CommentPage(ctx, keyOrID, startAt, 100)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
out = append(out, page.Comments...)
|
||||
startAt += len(page.Comments)
|
||||
if len(page.Comments) == 0 || startAt >= page.Total {
|
||||
return out, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Changelog returns an issue's complete change history. The endpoint
|
||||
// exists on Cloud only; Server/Data Center has the history in an issue
|
||||
// fetched with expand "changelog".
|
||||
func (c *Client) Changelog(ctx context.Context, keyOrID string) ([]ChangelogEntry, error) {
|
||||
raw, err := c.Paginate(ctx, c.api("/issue/"+url.PathEscape(keyOrID)+"/changelog"), nil, "values", 100)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return decodeAll[ChangelogEntry](raw)
|
||||
}
|
||||
|
||||
// EditMeta returns, by field ID, the edit operations ("add", "set",
|
||||
// "remove") the authenticated user may use on the issue. A missing field
|
||||
// cannot be edited by this user (screen or permission).
|
||||
func (c *Client) EditMeta(ctx context.Context, keyOrID string) (map[string][]string, error) {
|
||||
var meta struct {
|
||||
Fields map[string]struct {
|
||||
Operations []string `json:"operations"`
|
||||
} `json:"fields"`
|
||||
}
|
||||
if err := c.getInto(ctx, c.api("/issue/"+url.PathEscape(keyOrID)+"/editmeta"), nil, &meta); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make(map[string][]string, len(meta.Fields))
|
||||
for id, f := range meta.Fields {
|
||||
out[id] = f.Operations
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Transitions returns the workflow transitions currently available on an
|
||||
// issue.
|
||||
func (c *Client) Transitions(ctx context.Context, keyOrID string) ([]Transition, error) {
|
||||
var result struct {
|
||||
Transitions []Transition `json:"transitions"`
|
||||
}
|
||||
return result.Transitions, c.getInto(ctx, c.api("/issue/"+url.PathEscape(keyOrID)+"/transitions"), nil, &result)
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
package jira
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"yetano.dev/yetano/yetano-clients/atlassian"
|
||||
)
|
||||
|
||||
// SearchQuery is one JQL search walked to the end by Search/SearchAll.
|
||||
type SearchQuery struct {
|
||||
JQL string
|
||||
Fields []string
|
||||
Expand string // comma-separated, e.g. "renderedFields,changelog"
|
||||
PageSize int // default 100
|
||||
}
|
||||
|
||||
// Search runs a JQL query and calls fn once per page, so a caller never
|
||||
// has to hold more than it needs. On Cloud it uses the enhanced search
|
||||
// endpoint (/rest/api/3/search/jql, nextPageToken pagination); on
|
||||
// Server/Data Center POST /rest/api/2/search with startAt/total.
|
||||
func (c *Client) Search(ctx context.Context, q SearchQuery, fn func([]Issue) error) error {
|
||||
if strings.TrimSpace(q.JQL) == "" {
|
||||
return fmt.Errorf("%w: jql must not be empty", atlassian.ErrInvalidArgument)
|
||||
}
|
||||
if q.PageSize <= 0 {
|
||||
q.PageSize = 100
|
||||
}
|
||||
if !c.cloud {
|
||||
return c.searchOffset(ctx, q, fn)
|
||||
}
|
||||
next := ""
|
||||
for {
|
||||
body := map[string]any{"jql": q.JQL, "fields": q.Fields, "maxResults": q.PageSize}
|
||||
if q.Expand != "" {
|
||||
body["expand"] = q.Expand
|
||||
}
|
||||
if next != "" {
|
||||
body["nextPageToken"] = next
|
||||
}
|
||||
raw, err := c.Post(ctx, c.api("/search/jql"), body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var page struct {
|
||||
Issues []Issue `json:"issues"`
|
||||
NextPageToken string `json:"nextPageToken"`
|
||||
IsLast *bool `json:"isLast"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &page); err != nil {
|
||||
return fmt.Errorf("search: %w", err)
|
||||
}
|
||||
if len(page.Issues) > 0 {
|
||||
if err := fn(page.Issues); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
next = page.NextPageToken
|
||||
if next == "" || len(page.Issues) == 0 || (page.IsLast != nil && *page.IsLast) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) searchOffset(ctx context.Context, q SearchQuery, fn func([]Issue) error) error {
|
||||
start := 0
|
||||
for {
|
||||
page, err := c.SearchPage(ctx, PageQuery{JQL: q.JQL, StartAt: start, MaxResults: q.PageSize, Fields: q.Fields, Expand: splitList(q.Expand)})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(page.Issues) > 0 {
|
||||
if err := fn(page.Issues); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
start += len(page.Issues)
|
||||
if len(page.Issues) == 0 || start >= page.Total {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// SearchAll is Search collecting every issue.
|
||||
func (c *Client) SearchAll(ctx context.Context, q SearchQuery) ([]Issue, error) {
|
||||
var all []Issue
|
||||
err := c.Search(ctx, q, func(page []Issue) error {
|
||||
all = append(all, page...)
|
||||
return nil
|
||||
})
|
||||
return all, err
|
||||
}
|
||||
|
||||
// PageQuery is one page of a classic offset search.
|
||||
type PageQuery struct {
|
||||
JQL string
|
||||
StartAt int
|
||||
MaxResults int
|
||||
Fields []string
|
||||
Expand []string
|
||||
}
|
||||
|
||||
// SearchResult is one page of a classic offset search.
|
||||
type SearchResult struct {
|
||||
StartAt int `json:"startAt"`
|
||||
MaxResults int `json:"maxResults"`
|
||||
Total int `json:"total"`
|
||||
Issues []Issue `json:"issues"`
|
||||
}
|
||||
|
||||
// SearchPage fetches one page through the classic POST {prefix}/search
|
||||
// endpoint (startAt/maxResults/total). It is what Server/Data Center
|
||||
// offers; on Cloud Atlassian has deprecated it in favour of
|
||||
// /rest/api/3/search/jql (Search), so new Cloud code should use Search.
|
||||
func (c *Client) SearchPage(ctx context.Context, q PageQuery) (SearchResult, error) {
|
||||
var out SearchResult
|
||||
if strings.TrimSpace(q.JQL) == "" {
|
||||
return out, fmt.Errorf("%w: jql must not be empty", atlassian.ErrInvalidArgument)
|
||||
}
|
||||
body := struct {
|
||||
JQL string `json:"jql"`
|
||||
StartAt int `json:"startAt"`
|
||||
MaxResults int `json:"maxResults"`
|
||||
Fields []string `json:"fields,omitempty"`
|
||||
Expand []string `json:"expand,omitempty"`
|
||||
}{q.JQL, q.StartAt, q.MaxResults, q.Fields, q.Expand}
|
||||
raw, err := c.Post(ctx, c.api("/search"), body)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
if err := json.Unmarshal(raw, &out); err != nil {
|
||||
return out, fmt.Errorf("search: %w", err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func splitList(s string) []string {
|
||||
var out []string
|
||||
for _, p := range strings.Split(s, ",") {
|
||||
if p = strings.TrimSpace(p); p != "" {
|
||||
out = append(out, p)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
package jira
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
// Project is a Jira project. Description, Lead and Components are only
|
||||
// filled by Project (the single-project call), not by ListProjects.
|
||||
type Project struct {
|
||||
ID string `json:"id"`
|
||||
Key string `json:"key"`
|
||||
Name string `json:"name"`
|
||||
ProjectTypeKey string `json:"projectTypeKey"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Lead *User `json:"lead,omitempty"`
|
||||
Components []Named `json:"components,omitempty"`
|
||||
}
|
||||
|
||||
// User is a Jira account: AccountID on Cloud, Name/Key on Server/Data
|
||||
// Center.
|
||||
type User struct {
|
||||
AccountID string `json:"accountId"`
|
||||
Name string `json:"name,omitempty"`
|
||||
Key string `json:"key,omitempty"`
|
||||
DisplayName string `json:"displayName"`
|
||||
EmailAddress string `json:"emailAddress"`
|
||||
}
|
||||
|
||||
// Named is any Jira object identified by id/name (and sometimes key):
|
||||
// components, issue types, priorities, link types.
|
||||
type Named struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Key string `json:"key,omitempty"`
|
||||
}
|
||||
|
||||
// Version is a project version ("release").
|
||||
type Version struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Released bool `json:"released"`
|
||||
Archived bool `json:"archived"`
|
||||
ReleaseDate string `json:"releaseDate,omitempty"`
|
||||
StartDate string `json:"startDate,omitempty"`
|
||||
ProjectID int `json:"projectId,omitempty"`
|
||||
}
|
||||
|
||||
// Field is one entry of the field list.
|
||||
type Field struct {
|
||||
ID string `json:"id"`
|
||||
Key string `json:"key"`
|
||||
Name string `json:"name"`
|
||||
Custom bool `json:"custom"`
|
||||
Schema *FieldSchema `json:"schema"`
|
||||
}
|
||||
|
||||
// FieldSchema describes a field's value shape.
|
||||
type FieldSchema struct {
|
||||
Type string `json:"type"`
|
||||
Items string `json:"items,omitempty"`
|
||||
Custom string `json:"custom,omitempty"`
|
||||
}
|
||||
|
||||
// Issue is a Jira issue. The standard fields are decoded into Fields;
|
||||
// every field (standard and custom) also stays available raw in
|
||||
// Fields.Raw, because custom field IDs differ per site and are only known
|
||||
// at runtime.
|
||||
type Issue struct {
|
||||
ID string `json:"id"`
|
||||
Key string `json:"key"`
|
||||
Self string `json:"self,omitempty"`
|
||||
Fields IssueFields `json:"fields"`
|
||||
}
|
||||
|
||||
// IssueFields are the standard fields. Description is ADF (a JSON
|
||||
// object) on Cloud and a wiki-markup string on Server/Data Center.
|
||||
type IssueFields struct {
|
||||
Summary string `json:"summary"`
|
||||
Status *Status `json:"status"`
|
||||
IssueType *Named `json:"issuetype"`
|
||||
Resolutiondate string `json:"resolutiondate"`
|
||||
Created string `json:"created"`
|
||||
Updated string `json:"updated"`
|
||||
Reporter *User `json:"reporter"`
|
||||
Assignee *User `json:"assignee"`
|
||||
Priority *Named `json:"priority"`
|
||||
Components []Named `json:"components"`
|
||||
Versions []Version `json:"versions"` // affected versions
|
||||
FixVersions []Version `json:"fixVersions"` // fix versions
|
||||
Labels []string `json:"labels"`
|
||||
Comment *CommentPage `json:"comment"`
|
||||
Description json.RawMessage `json:"description"`
|
||||
IssueLinks []IssueLink `json:"issuelinks"`
|
||||
Parent *LinkedIssue `json:"parent"`
|
||||
Subtasks []LinkedIssue `json:"subtasks"`
|
||||
|
||||
Raw map[string]json.RawMessage `json:"-"`
|
||||
}
|
||||
|
||||
// UnmarshalJSON decodes the standard fields and keeps all of them raw.
|
||||
func (f *IssueFields) UnmarshalJSON(data []byte) error {
|
||||
type plain IssueFields
|
||||
var p plain
|
||||
if err := json.Unmarshal(data, &p); err != nil {
|
||||
return err
|
||||
}
|
||||
var raw map[string]json.RawMessage
|
||||
if err := json.Unmarshal(data, &raw); err != nil {
|
||||
return err
|
||||
}
|
||||
*f = IssueFields(p)
|
||||
f.Raw = raw
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalJSON writes the raw fields back, so an Issue round-trips.
|
||||
func (f IssueFields) MarshalJSON() ([]byte, error) {
|
||||
if f.Raw != nil {
|
||||
return json.Marshal(f.Raw)
|
||||
}
|
||||
type plain IssueFields
|
||||
return json.Marshal(plain(f))
|
||||
}
|
||||
|
||||
// Status is an issue status with its category (new, indeterminate, done).
|
||||
type Status struct {
|
||||
Name string `json:"name"`
|
||||
StatusCategory *struct {
|
||||
Key string `json:"key"`
|
||||
} `json:"statusCategory"`
|
||||
}
|
||||
|
||||
// CategoryKey is the status category key, "" if unknown.
|
||||
func (s *Status) CategoryKey() string {
|
||||
if s == nil || s.StatusCategory == nil {
|
||||
return ""
|
||||
}
|
||||
return s.StatusCategory.Key
|
||||
}
|
||||
|
||||
// StatusName is s.Name, "" for nil.
|
||||
func (s *Status) StatusName() string {
|
||||
if s == nil {
|
||||
return ""
|
||||
}
|
||||
return s.Name
|
||||
}
|
||||
|
||||
// CommentPage is one page of comments (also embedded in a search result
|
||||
// when the comment field is requested).
|
||||
type CommentPage struct {
|
||||
Comments []Comment `json:"comments"`
|
||||
Total int `json:"total"`
|
||||
MaxResults int `json:"maxResults"`
|
||||
StartAt int `json:"startAt"`
|
||||
}
|
||||
|
||||
// Comment is one issue comment. Body is ADF on Cloud, a string on
|
||||
// Server/Data Center.
|
||||
type Comment struct {
|
||||
ID string `json:"id"`
|
||||
Author *User `json:"author"`
|
||||
Body json.RawMessage `json:"body"`
|
||||
Created string `json:"created"`
|
||||
Updated string `json:"updated"`
|
||||
}
|
||||
|
||||
// IssueLinkType names a link type in both directions.
|
||||
type IssueLinkType struct {
|
||||
Name string `json:"name"`
|
||||
Inward string `json:"inward"`
|
||||
Outward string `json:"outward"`
|
||||
}
|
||||
|
||||
// IssueLink links two issues; exactly one of InwardIssue/OutwardIssue is
|
||||
// set, the other end is the issue the link belongs to.
|
||||
type IssueLink struct {
|
||||
Type *IssueLinkType `json:"type"`
|
||||
InwardIssue *LinkedIssue `json:"inwardIssue"`
|
||||
OutwardIssue *LinkedIssue `json:"outwardIssue"`
|
||||
}
|
||||
|
||||
// LinkedIssue is the short form of an issue inside a link, a parent or a
|
||||
// subtask list.
|
||||
type LinkedIssue struct {
|
||||
ID string `json:"id,omitempty"`
|
||||
Key string `json:"key"`
|
||||
Fields struct {
|
||||
Summary string `json:"summary"`
|
||||
Status *Status `json:"status"`
|
||||
} `json:"fields"`
|
||||
}
|
||||
|
||||
// ChangelogEntry is one change set of an issue's history.
|
||||
type ChangelogEntry struct {
|
||||
ID string `json:"id"`
|
||||
Author *User `json:"author"`
|
||||
Created string `json:"created"`
|
||||
Items []ChangelogItem `json:"items"`
|
||||
}
|
||||
|
||||
// ChangelogItem is one changed field inside a ChangelogEntry.
|
||||
type ChangelogItem struct {
|
||||
Field string `json:"field"`
|
||||
FieldID string `json:"fieldId"`
|
||||
From string `json:"from"`
|
||||
FromString string `json:"fromString"`
|
||||
To string `json:"to"`
|
||||
ToString string `json:"toString"`
|
||||
}
|
||||
|
||||
// Transition is a workflow transition currently available on an issue.
|
||||
type Transition struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
To *Status `json:"to"`
|
||||
}
|
||||
|
||||
// ServerInfo is /serverInfo.
|
||||
type ServerInfo struct {
|
||||
BaseURL string `json:"baseUrl"`
|
||||
Version string `json:"version"`
|
||||
DeploymentType string `json:"deploymentType"`
|
||||
ServerTitle string `json:"serverTitle"`
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
package jira
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
// TextBody encodes plain text as a description/comment body: a minimal
|
||||
// Atlassian Document Format document (one paragraph) on Cloud, the plain
|
||||
// string on Server/Data Center.
|
||||
func (c *Client) TextBody(text string) any {
|
||||
if !c.cloud {
|
||||
return text
|
||||
}
|
||||
return map[string]any{
|
||||
"type": "doc",
|
||||
"version": 1,
|
||||
"content": []any{
|
||||
map[string]any{
|
||||
"type": "paragraph",
|
||||
"content": []any{
|
||||
map[string]any{"type": "text", "text": text},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// IssueEdit is one PUT on an issue. Fields replaces whole field values
|
||||
// ({"summary": "x"}); Update applies operations to them
|
||||
// ({"labels": [{"add": "x"}], "components": [{"remove": {"id": "10"}}]}),
|
||||
// touching only the named values, so a value someone else added in the
|
||||
// meantime stays. An empty part is left out of the request.
|
||||
type IssueEdit struct {
|
||||
Fields map[string]any
|
||||
Update map[string][]map[string]any
|
||||
}
|
||||
|
||||
// EditIssue applies e to an issue.
|
||||
func (c *Client) EditIssue(ctx context.Context, keyOrID string, e IssueEdit) error {
|
||||
if err := requireKey("issue key", keyOrID); err != nil {
|
||||
return err
|
||||
}
|
||||
body := map[string]any{}
|
||||
if len(e.Fields) > 0 {
|
||||
body["fields"] = e.Fields
|
||||
}
|
||||
if len(e.Update) > 0 {
|
||||
body["update"] = e.Update
|
||||
}
|
||||
_, err := c.Put(ctx, c.api("/issue/"+url.PathEscape(keyOrID)), body)
|
||||
return err
|
||||
}
|
||||
|
||||
// UpdateIssue sets whole field values on an issue (EditIssue with
|
||||
// Fields only).
|
||||
func (c *Client) UpdateIssue(ctx context.Context, keyOrID string, fields map[string]any) error {
|
||||
return c.EditIssue(ctx, keyOrID, IssueEdit{Fields: fields})
|
||||
}
|
||||
|
||||
// UpdateVersion changes a version (e.g. {"released": true,
|
||||
// "releaseDate": "2026-11-01"}).
|
||||
func (c *Client) UpdateVersion(ctx context.Context, id string, body map[string]any) error {
|
||||
if err := requireKey("version id", id); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := c.Put(ctx, c.api("/version/"+url.PathEscape(id)), body)
|
||||
return err
|
||||
}
|
||||
|
||||
// CreateIssueInput describes a new issue; ParentKey makes it a subtask.
|
||||
type CreateIssueInput struct {
|
||||
ProjectKey string
|
||||
IssueType string // issue type name
|
||||
Summary string
|
||||
Description string // plain text, encoded with TextBody
|
||||
Labels []string
|
||||
ParentKey string
|
||||
}
|
||||
|
||||
// CreateIssue creates an issue and returns its key.
|
||||
func (c *Client) CreateIssue(ctx context.Context, in CreateIssueInput) (string, error) {
|
||||
fields := map[string]any{
|
||||
"project": map[string]string{"key": in.ProjectKey},
|
||||
"issuetype": map[string]string{"name": in.IssueType},
|
||||
"summary": in.Summary,
|
||||
}
|
||||
if in.Description != "" {
|
||||
fields["description"] = c.TextBody(in.Description)
|
||||
}
|
||||
if len(in.Labels) > 0 {
|
||||
fields["labels"] = in.Labels
|
||||
}
|
||||
if in.ParentKey != "" {
|
||||
fields["parent"] = map[string]string{"key": in.ParentKey}
|
||||
}
|
||||
raw, err := c.Post(ctx, c.api("/issue"), map[string]any{"fields": fields})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
var resp struct {
|
||||
Key string `json:"key"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &resp); err != nil {
|
||||
return "", fmt.Errorf("create issue: %w", err)
|
||||
}
|
||||
return resp.Key, nil
|
||||
}
|
||||
|
||||
// AddComment adds a plain-text comment (encoded with TextBody) and
|
||||
// returns its ID.
|
||||
func (c *Client) AddComment(ctx context.Context, keyOrID, text string) (string, error) {
|
||||
if err := requireKey("issue key", keyOrID); err != nil {
|
||||
return "", err
|
||||
}
|
||||
raw, err := c.Post(ctx, c.api("/issue/"+url.PathEscape(keyOrID)+"/comment"), map[string]any{"body": c.TextBody(text)})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
var resp struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &resp); err != nil {
|
||||
return "", fmt.Errorf("add comment: %w", err)
|
||||
}
|
||||
return resp.ID, nil
|
||||
}
|
||||
|
||||
// DoTransition moves an issue along the transition with the given ID
|
||||
// (see Transitions).
|
||||
func (c *Client) DoTransition(ctx context.Context, keyOrID, transitionID string) error {
|
||||
_, err := c.Post(ctx, c.api("/issue/"+url.PathEscape(keyOrID)+"/transitions"),
|
||||
map[string]any{"transition": map[string]string{"id": transitionID}})
|
||||
return err
|
||||
}
|
||||
|
||||
// AssignIssue assigns an issue to a Cloud accountId or a Server/Data
|
||||
// Center username; an empty assignee unassigns it.
|
||||
func (c *Client) AssignIssue(ctx context.Context, keyOrID, assignee string) error {
|
||||
body := map[string]any{}
|
||||
switch {
|
||||
case c.cloud:
|
||||
body["accountId"] = nilIfEmpty(assignee)
|
||||
default:
|
||||
body["name"] = nilIfEmpty(assignee)
|
||||
}
|
||||
_, err := c.Put(ctx, c.api("/issue/"+url.PathEscape(keyOrID)+"/assignee"), body)
|
||||
return err
|
||||
}
|
||||
|
||||
func nilIfEmpty(s string) any {
|
||||
if s == "" {
|
||||
return nil
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// LinkIssues links two issues with the named link type.
|
||||
func (c *Client) LinkIssues(ctx context.Context, linkType, inwardKey, outwardKey string) error {
|
||||
_, err := c.Post(ctx, c.api("/issueLink"), map[string]any{
|
||||
"type": map[string]string{"name": linkType},
|
||||
"inwardIssue": map[string]string{"key": inwardKey},
|
||||
"outwardIssue": map[string]string{"key": outwardKey},
|
||||
})
|
||||
return err
|
||||
}
|
||||
Reference in new issue
Block a user