1// Copyright 2013 The go-github AUTHORS. All rights reserved.
2//
3// Use of this source code is governed by a BSD-style
4// license that can be found in the LICENSE file.
5
6package github
7
8import (
9	"context"
10	"fmt"
11	"strings"
12	"time"
13)
14
15// IssuesService handles communication with the issue related
16// methods of the GitHub API.
17//
18// GitHub API docs: https://developer.github.com/v3/issues/
19type IssuesService service
20
21// Issue represents a GitHub issue on a repository.
22//
23// Note: As far as the GitHub API is concerned, every pull request is an issue,
24// but not every issue is a pull request. Some endpoints, events, and webhooks
25// may also return pull requests via this struct. If PullRequestLinks is nil,
26// this is an issue, and if PullRequestLinks is not nil, this is a pull request.
27// The IsPullRequest helper method can be used to check that.
28type Issue struct {
29	ID               *int64            `json:"id,omitempty"`
30	Number           *int              `json:"number,omitempty"`
31	State            *string           `json:"state,omitempty"`
32	Locked           *bool             `json:"locked,omitempty"`
33	Title            *string           `json:"title,omitempty"`
34	Body             *string           `json:"body,omitempty"`
35	User             *User             `json:"user,omitempty"`
36	Labels           []Label           `json:"labels,omitempty"`
37	Assignee         *User             `json:"assignee,omitempty"`
38	Comments         *int              `json:"comments,omitempty"`
39	ClosedAt         *time.Time        `json:"closed_at,omitempty"`
40	CreatedAt        *time.Time        `json:"created_at,omitempty"`
41	UpdatedAt        *time.Time        `json:"updated_at,omitempty"`
42	ClosedBy         *User             `json:"closed_by,omitempty"`
43	URL              *string           `json:"url,omitempty"`
44	HTMLURL          *string           `json:"html_url,omitempty"`
45	CommentsURL      *string           `json:"comments_url,omitempty"`
46	EventsURL        *string           `json:"events_url,omitempty"`
47	LabelsURL        *string           `json:"labels_url,omitempty"`
48	RepositoryURL    *string           `json:"repository_url,omitempty"`
49	Milestone        *Milestone        `json:"milestone,omitempty"`
50	PullRequestLinks *PullRequestLinks `json:"pull_request,omitempty"`
51	Repository       *Repository       `json:"repository,omitempty"`
52	Reactions        *Reactions        `json:"reactions,omitempty"`
53	Assignees        []*User           `json:"assignees,omitempty"`
54	NodeID           *string           `json:"node_id,omitempty"`
55
56	// TextMatches is only populated from search results that request text matches
57	// See: search.go and https://developer.github.com/v3/search/#text-match-metadata
58	TextMatches []TextMatch `json:"text_matches,omitempty"`
59
60	// ActiveLockReason is populated only when LockReason is provided while locking the issue.
61	// Possible values are: "off-topic", "too heated", "resolved", and "spam".
62	ActiveLockReason *string `json:"active_lock_reason,omitempty"`
63}
64
65func (i Issue) String() string {
66	return Stringify(i)
67}
68
69// IsPullRequest reports whether the issue is also a pull request. It uses the
70// method recommended by GitHub's API documentation, which is to check whether
71// PullRequestLinks is non-nil.
72func (i Issue) IsPullRequest() bool {
73	return i.PullRequestLinks != nil
74}
75
76// IssueRequest represents a request to create/edit an issue.
77// It is separate from Issue above because otherwise Labels
78// and Assignee fail to serialize to the correct JSON.
79type IssueRequest struct {
80	Title     *string   `json:"title,omitempty"`
81	Body      *string   `json:"body,omitempty"`
82	Labels    *[]string `json:"labels,omitempty"`
83	Assignee  *string   `json:"assignee,omitempty"`
84	State     *string   `json:"state,omitempty"`
85	Milestone *int      `json:"milestone,omitempty"`
86	Assignees *[]string `json:"assignees,omitempty"`
87}
88
89// IssueListOptions specifies the optional parameters to the IssuesService.List
90// and IssuesService.ListByOrg methods.
91type IssueListOptions struct {
92	// Filter specifies which issues to list. Possible values are: assigned,
93	// created, mentioned, subscribed, all. Default is "assigned".
94	Filter string `url:"filter,omitempty"`
95
96	// State filters issues based on their state. Possible values are: open,
97	// closed, all. Default is "open".
98	State string `url:"state,omitempty"`
99
100	// Labels filters issues based on their label.
101	Labels []string `url:"labels,comma,omitempty"`
102
103	// Sort specifies how to sort issues. Possible values are: created, updated,
104	// and comments. Default value is "created".
105	Sort string `url:"sort,omitempty"`
106
107	// Direction in which to sort issues. Possible values are: asc, desc.
108	// Default is "desc".
109	Direction string `url:"direction,omitempty"`
110
111	// Since filters issues by time.
112	Since time.Time `url:"since,omitempty"`
113
114	ListOptions
115}
116
117// PullRequestLinks object is added to the Issue object when it's an issue included
118// in the IssueCommentEvent webhook payload, if the webhook is fired by a comment on a PR.
119type PullRequestLinks struct {
120	URL      *string `json:"url,omitempty"`
121	HTMLURL  *string `json:"html_url,omitempty"`
122	DiffURL  *string `json:"diff_url,omitempty"`
123	PatchURL *string `json:"patch_url,omitempty"`
124}
125
126// List the issues for the authenticated user. If all is true, list issues
127// across all the user's visible repositories including owned, member, and
128// organization repositories; if false, list only owned and member
129// repositories.
130//
131// GitHub API docs: https://developer.github.com/v3/issues/#list-issues
132func (s *IssuesService) List(ctx context.Context, all bool, opt *IssueListOptions) ([]*Issue, *Response, error) {
133	var u string
134	if all {
135		u = "issues"
136	} else {
137		u = "user/issues"
138	}
139	return s.listIssues(ctx, u, opt)
140}
141
142// ListByOrg fetches the issues in the specified organization for the
143// authenticated user.
144//
145// GitHub API docs: https://developer.github.com/v3/issues/#list-issues
146func (s *IssuesService) ListByOrg(ctx context.Context, org string, opt *IssueListOptions) ([]*Issue, *Response, error) {
147	u := fmt.Sprintf("orgs/%v/issues", org)
148	return s.listIssues(ctx, u, opt)
149}
150
151func (s *IssuesService) listIssues(ctx context.Context, u string, opt *IssueListOptions) ([]*Issue, *Response, error) {
152	u, err := addOptions(u, opt)
153	if err != nil {
154		return nil, nil, err
155	}
156
157	req, err := s.client.NewRequest("GET", u, nil)
158	if err != nil {
159		return nil, nil, err
160	}
161
162	// TODO: remove custom Accept headers when APIs fully launch.
163	acceptHeaders := []string{mediaTypeReactionsPreview, mediaTypeLabelDescriptionSearchPreview, mediaTypeLockReasonPreview}
164	req.Header.Set("Accept", strings.Join(acceptHeaders, ", "))
165
166	var issues []*Issue
167	resp, err := s.client.Do(ctx, req, &issues)
168	if err != nil {
169		return nil, resp, err
170	}
171
172	return issues, resp, nil
173}
174
175// IssueListByRepoOptions specifies the optional parameters to the
176// IssuesService.ListByRepo method.
177type IssueListByRepoOptions struct {
178	// Milestone limits issues for the specified milestone. Possible values are
179	// a milestone number, "none" for issues with no milestone, "*" for issues
180	// with any milestone.
181	Milestone string `url:"milestone,omitempty"`
182
183	// State filters issues based on their state. Possible values are: open,
184	// closed, all. Default is "open".
185	State string `url:"state,omitempty"`
186
187	// Assignee filters issues based on their assignee. Possible values are a
188	// user name, "none" for issues that are not assigned, "*" for issues with
189	// any assigned user.
190	Assignee string `url:"assignee,omitempty"`
191
192	// Creator filters issues based on their creator.
193	Creator string `url:"creator,omitempty"`
194
195	// Mentioned filters issues to those mentioned a specific user.
196	Mentioned string `url:"mentioned,omitempty"`
197
198	// Labels filters issues based on their label.
199	Labels []string `url:"labels,omitempty,comma"`
200
201	// Sort specifies how to sort issues. Possible values are: created, updated,
202	// and comments. Default value is "created".
203	Sort string `url:"sort,omitempty"`
204
205	// Direction in which to sort issues. Possible values are: asc, desc.
206	// Default is "desc".
207	Direction string `url:"direction,omitempty"`
208
209	// Since filters issues by time.
210	Since time.Time `url:"since,omitempty"`
211
212	ListOptions
213}
214
215// ListByRepo lists the issues for the specified repository.
216//
217// GitHub API docs: https://developer.github.com/v3/issues/#list-issues-for-a-repository
218func (s *IssuesService) ListByRepo(ctx context.Context, owner string, repo string, opt *IssueListByRepoOptions) ([]*Issue, *Response, error) {
219	u := fmt.Sprintf("repos/%v/%v/issues", owner, repo)
220	u, err := addOptions(u, opt)
221	if err != nil {
222		return nil, nil, err
223	}
224
225	req, err := s.client.NewRequest("GET", u, nil)
226	if err != nil {
227		return nil, nil, err
228	}
229
230	// TODO: remove custom Accept headers when APIs fully launch.
231	acceptHeaders := []string{mediaTypeReactionsPreview, mediaTypeLabelDescriptionSearchPreview, mediaTypeIntegrationPreview}
232	req.Header.Set("Accept", strings.Join(acceptHeaders, ", "))
233
234	var issues []*Issue
235	resp, err := s.client.Do(ctx, req, &issues)
236	if err != nil {
237		return nil, resp, err
238	}
239
240	return issues, resp, nil
241}
242
243// Get a single issue.
244//
245// GitHub API docs: https://developer.github.com/v3/issues/#get-a-single-issue
246func (s *IssuesService) Get(ctx context.Context, owner string, repo string, number int) (*Issue, *Response, error) {
247	u := fmt.Sprintf("repos/%v/%v/issues/%d", owner, repo, number)
248	req, err := s.client.NewRequest("GET", u, nil)
249	if err != nil {
250		return nil, nil, err
251	}
252
253	// TODO: remove custom Accept headers when APIs fully launch.
254	acceptHeaders := []string{mediaTypeReactionsPreview, mediaTypeLabelDescriptionSearchPreview, mediaTypeLockReasonPreview}
255	req.Header.Set("Accept", strings.Join(acceptHeaders, ", "))
256
257	issue := new(Issue)
258	resp, err := s.client.Do(ctx, req, issue)
259	if err != nil {
260		return nil, resp, err
261	}
262
263	return issue, resp, nil
264}
265
266// Create a new issue on the specified repository.
267//
268// GitHub API docs: https://developer.github.com/v3/issues/#create-an-issue
269func (s *IssuesService) Create(ctx context.Context, owner string, repo string, issue *IssueRequest) (*Issue, *Response, error) {
270	u := fmt.Sprintf("repos/%v/%v/issues", owner, repo)
271	req, err := s.client.NewRequest("POST", u, issue)
272	if err != nil {
273		return nil, nil, err
274	}
275
276	// TODO: remove custom Accept header when this API fully launches.
277	req.Header.Set("Accept", mediaTypeLabelDescriptionSearchPreview)
278
279	i := new(Issue)
280	resp, err := s.client.Do(ctx, req, i)
281	if err != nil {
282		return nil, resp, err
283	}
284
285	return i, resp, nil
286}
287
288// Edit an issue.
289//
290// GitHub API docs: https://developer.github.com/v3/issues/#edit-an-issue
291func (s *IssuesService) Edit(ctx context.Context, owner string, repo string, number int, issue *IssueRequest) (*Issue, *Response, error) {
292	u := fmt.Sprintf("repos/%v/%v/issues/%d", owner, repo, number)
293	req, err := s.client.NewRequest("PATCH", u, issue)
294	if err != nil {
295		return nil, nil, err
296	}
297
298	// TODO: remove custom Accept header when this API fully launches.
299	req.Header.Set("Accept", mediaTypeLabelDescriptionSearchPreview)
300
301	i := new(Issue)
302	resp, err := s.client.Do(ctx, req, i)
303	if err != nil {
304		return nil, resp, err
305	}
306
307	return i, resp, nil
308}
309
310// LockIssueOptions specifies the optional parameters to the
311// IssuesService.Lock method.
312type LockIssueOptions struct {
313	// LockReason specifies the reason to lock this issue.
314	// Providing a lock reason can help make it clearer to contributors why an issue
315	// was locked. Possible values are: "off-topic", "too heated", "resolved", and "spam".
316	LockReason string `json:"lock_reason,omitempty"`
317}
318
319// Lock an issue's conversation.
320//
321// GitHub API docs: https://developer.github.com/v3/issues/#lock-an-issue
322func (s *IssuesService) Lock(ctx context.Context, owner string, repo string, number int, opt *LockIssueOptions) (*Response, error) {
323	u := fmt.Sprintf("repos/%v/%v/issues/%d/lock", owner, repo, number)
324	req, err := s.client.NewRequest("PUT", u, opt)
325	if err != nil {
326		return nil, err
327	}
328
329	if opt != nil {
330		req.Header.Set("Accept", mediaTypeLockReasonPreview)
331	}
332
333	return s.client.Do(ctx, req, nil)
334}
335
336// Unlock an issue's conversation.
337//
338// GitHub API docs: https://developer.github.com/v3/issues/#unlock-an-issue
339func (s *IssuesService) Unlock(ctx context.Context, owner string, repo string, number int) (*Response, error) {
340	u := fmt.Sprintf("repos/%v/%v/issues/%d/lock", owner, repo, number)
341	req, err := s.client.NewRequest("DELETE", u, nil)
342	if err != nil {
343		return nil, err
344	}
345
346	return s.client.Do(ctx, req, nil)
347}
348