gitlab.go

  1//
  2// Copyright 2017, Sander van Harmelen
  3//
  4// Licensed under the Apache License, Version 2.0 (the "License");
  5// you may not use this file except in compliance with the License.
  6// You may obtain a copy of the License at
  7//
  8//     http://www.apache.org/licenses/LICENSE-2.0
  9//
 10// Unless required by applicable law or agreed to in writing, software
 11// distributed under the License is distributed on an "AS IS" BASIS,
 12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13// See the License for the specific language governing permissions and
 14// limitations under the License.
 15//
 16
 17package gitlab
 18
 19import (
 20	"bytes"
 21	"context"
 22	"encoding/json"
 23	"errors"
 24	"fmt"
 25	"io"
 26	"io/ioutil"
 27	"net/http"
 28	"net/url"
 29	"sort"
 30	"strconv"
 31	"strings"
 32	"time"
 33
 34	"github.com/google/go-querystring/query"
 35	"golang.org/x/oauth2"
 36)
 37
 38const (
 39	defaultBaseURL = "https://gitlab.com/"
 40	apiVersionPath = "api/v4/"
 41	userAgent      = "go-gitlab"
 42)
 43
 44// authType represents an authentication type within GitLab.
 45//
 46// GitLab API docs: https://docs.gitlab.com/ce/api/
 47type authType int
 48
 49// List of available authentication types.
 50//
 51// GitLab API docs: https://docs.gitlab.com/ce/api/
 52const (
 53	basicAuth authType = iota
 54	oAuthToken
 55	privateToken
 56)
 57
 58// AccessLevelValue represents a permission level within GitLab.
 59//
 60// GitLab API docs: https://docs.gitlab.com/ce/permissions/permissions.html
 61type AccessLevelValue int
 62
 63// List of available access levels
 64//
 65// GitLab API docs: https://docs.gitlab.com/ce/permissions/permissions.html
 66const (
 67	NoPermissions         AccessLevelValue = 0
 68	GuestPermissions      AccessLevelValue = 10
 69	ReporterPermissions   AccessLevelValue = 20
 70	DeveloperPermissions  AccessLevelValue = 30
 71	MaintainerPermissions AccessLevelValue = 40
 72	OwnerPermissions      AccessLevelValue = 50
 73
 74	// These are deprecated and should be removed in a future version
 75	MasterPermissions AccessLevelValue = 40
 76	OwnerPermission   AccessLevelValue = 50
 77)
 78
 79// BuildStateValue represents a GitLab build state.
 80type BuildStateValue string
 81
 82// These constants represent all valid build states.
 83const (
 84	Pending  BuildStateValue = "pending"
 85	Running  BuildStateValue = "running"
 86	Success  BuildStateValue = "success"
 87	Failed   BuildStateValue = "failed"
 88	Canceled BuildStateValue = "canceled"
 89	Skipped  BuildStateValue = "skipped"
 90)
 91
 92// ISOTime represents an ISO 8601 formatted date
 93type ISOTime time.Time
 94
 95// ISO 8601 date format
 96const iso8601 = "2006-01-02"
 97
 98// MarshalJSON implements the json.Marshaler interface
 99func (t ISOTime) MarshalJSON() ([]byte, error) {
100	if y := time.Time(t).Year(); y < 0 || y >= 10000 {
101		// ISO 8901 uses 4 digits for the years
102		return nil, errors.New("ISOTime.MarshalJSON: year outside of range [0,9999]")
103	}
104
105	b := make([]byte, 0, len(iso8601)+2)
106	b = append(b, '"')
107	b = time.Time(t).AppendFormat(b, iso8601)
108	b = append(b, '"')
109
110	return b, nil
111}
112
113// UnmarshalJSON implements the json.Unmarshaler interface
114func (t *ISOTime) UnmarshalJSON(data []byte) error {
115	// Ignore null, like in the main JSON package
116	if string(data) == "null" {
117		return nil
118	}
119
120	isotime, err := time.Parse(`"`+iso8601+`"`, string(data))
121	*t = ISOTime(isotime)
122
123	return err
124}
125
126// EncodeValues implements the query.Encoder interface
127func (t *ISOTime) EncodeValues(key string, v *url.Values) error {
128	if t == nil || (time.Time(*t)).IsZero() {
129		return nil
130	}
131	v.Add(key, t.String())
132	return nil
133}
134
135// String implements the Stringer interface
136func (t ISOTime) String() string {
137	return time.Time(t).Format(iso8601)
138}
139
140// NotificationLevelValue represents a notification level.
141type NotificationLevelValue int
142
143// String implements the fmt.Stringer interface.
144func (l NotificationLevelValue) String() string {
145	return notificationLevelNames[l]
146}
147
148// MarshalJSON implements the json.Marshaler interface.
149func (l NotificationLevelValue) MarshalJSON() ([]byte, error) {
150	return json.Marshal(l.String())
151}
152
153// UnmarshalJSON implements the json.Unmarshaler interface.
154func (l *NotificationLevelValue) UnmarshalJSON(data []byte) error {
155	var raw interface{}
156	if err := json.Unmarshal(data, &raw); err != nil {
157		return err
158	}
159
160	switch raw := raw.(type) {
161	case float64:
162		*l = NotificationLevelValue(raw)
163	case string:
164		*l = notificationLevelTypes[raw]
165	case nil:
166		// No action needed.
167	default:
168		return fmt.Errorf("json: cannot unmarshal %T into Go value of type %T", raw, *l)
169	}
170
171	return nil
172}
173
174// List of valid notification levels.
175const (
176	DisabledNotificationLevel NotificationLevelValue = iota
177	ParticipatingNotificationLevel
178	WatchNotificationLevel
179	GlobalNotificationLevel
180	MentionNotificationLevel
181	CustomNotificationLevel
182)
183
184var notificationLevelNames = [...]string{
185	"disabled",
186	"participating",
187	"watch",
188	"global",
189	"mention",
190	"custom",
191}
192
193var notificationLevelTypes = map[string]NotificationLevelValue{
194	"disabled":      DisabledNotificationLevel,
195	"participating": ParticipatingNotificationLevel,
196	"watch":         WatchNotificationLevel,
197	"global":        GlobalNotificationLevel,
198	"mention":       MentionNotificationLevel,
199	"custom":        CustomNotificationLevel,
200}
201
202// VisibilityValue represents a visibility level within GitLab.
203//
204// GitLab API docs: https://docs.gitlab.com/ce/api/
205type VisibilityValue string
206
207// List of available visibility levels.
208//
209// GitLab API docs: https://docs.gitlab.com/ce/api/
210const (
211	PrivateVisibility  VisibilityValue = "private"
212	InternalVisibility VisibilityValue = "internal"
213	PublicVisibility   VisibilityValue = "public"
214)
215
216// VariableTypeValue represents a variable type within GitLab.
217//
218// GitLab API docs: https://docs.gitlab.com/ce/api/
219type VariableTypeValue string
220
221// List of available variable types.
222//
223// GitLab API docs: https://docs.gitlab.com/ce/api/
224const (
225	EnvVariableType  VariableTypeValue = "env_var"
226	FileVariableType VariableTypeValue = "file"
227)
228
229// MergeMethodValue represents a project merge type within GitLab.
230//
231// GitLab API docs: https://docs.gitlab.com/ce/api/projects.html#project-merge-method
232type MergeMethodValue string
233
234// List of available merge type
235//
236// GitLab API docs: https://docs.gitlab.com/ce/api/projects.html#project-merge-method
237const (
238	NoFastForwardMerge MergeMethodValue = "merge"
239	FastForwardMerge   MergeMethodValue = "ff"
240	RebaseMerge        MergeMethodValue = "rebase_merge"
241)
242
243// EventTypeValue represents actions type for contribution events
244type EventTypeValue string
245
246// List of available action type
247//
248// GitLab API docs: https://docs.gitlab.com/ce/api/events.html#action-types
249const (
250	CreatedEventType   EventTypeValue = "created"
251	UpdatedEventType   EventTypeValue = "updated"
252	ClosedEventType    EventTypeValue = "closed"
253	ReopenedEventType  EventTypeValue = "reopened"
254	PushedEventType    EventTypeValue = "pushed"
255	CommentedEventType EventTypeValue = "commented"
256	MergedEventType    EventTypeValue = "merged"
257	JoinedEventType    EventTypeValue = "joined"
258	LeftEventType      EventTypeValue = "left"
259	DestroyedEventType EventTypeValue = "destroyed"
260	ExpiredEventType   EventTypeValue = "expired"
261)
262
263// EventTargetTypeValue represents actions type value for contribution events
264type EventTargetTypeValue string
265
266// List of available action type
267//
268// GitLab API docs: https://docs.gitlab.com/ce/api/events.html#target-types
269const (
270	IssueEventTargetType        EventTargetTypeValue = "issue"
271	MilestoneEventTargetType    EventTargetTypeValue = "milestone"
272	MergeRequestEventTargetType EventTargetTypeValue = "merge_request"
273	NoteEventTargetType         EventTargetTypeValue = "note"
274	ProjectEventTargetType      EventTargetTypeValue = "project"
275	SnippetEventTargetType      EventTargetTypeValue = "snippet"
276	UserEventTargetType         EventTargetTypeValue = "user"
277)
278
279// A Client manages communication with the GitLab API.
280type Client struct {
281	// HTTP client used to communicate with the API.
282	client *http.Client
283
284	// Base URL for API requests. Defaults to the public GitLab API, but can be
285	// set to a domain endpoint to use with a self hosted GitLab server. baseURL
286	// should always be specified with a trailing slash.
287	baseURL *url.URL
288
289	// Token type used to make authenticated API calls.
290	authType authType
291
292	// Username and password used for basix authentication.
293	username, password string
294
295	// Token used to make authenticated API calls.
296	token string
297
298	// User agent used when communicating with the GitLab API.
299	UserAgent string
300
301	// Services used for talking to different parts of the GitLab API.
302	AccessRequests        *AccessRequestsService
303	AwardEmoji            *AwardEmojiService
304	Boards                *IssueBoardsService
305	Branches              *BranchesService
306	BroadcastMessage      *BroadcastMessagesService
307	CIYMLTemplate         *CIYMLTemplatesService
308	Commits               *CommitsService
309	ContainerRegistry     *ContainerRegistryService
310	CustomAttribute       *CustomAttributesService
311	DeployKeys            *DeployKeysService
312	Deployments           *DeploymentsService
313	Discussions           *DiscussionsService
314	Environments          *EnvironmentsService
315	Epics                 *EpicsService
316	Events                *EventsService
317	Features              *FeaturesService
318	GitIgnoreTemplates    *GitIgnoreTemplatesService
319	GroupBadges           *GroupBadgesService
320	GroupIssueBoards      *GroupIssueBoardsService
321	GroupLabels           *GroupLabelsService
322	GroupMembers          *GroupMembersService
323	GroupMilestones       *GroupMilestonesService
324	GroupVariables        *GroupVariablesService
325	Groups                *GroupsService
326	IssueLinks            *IssueLinksService
327	Issues                *IssuesService
328	Jobs                  *JobsService
329	Keys                  *KeysService
330	Labels                *LabelsService
331	License               *LicenseService
332	LicenseTemplates      *LicenseTemplatesService
333	MergeRequestApprovals *MergeRequestApprovalsService
334	MergeRequests         *MergeRequestsService
335	Milestones            *MilestonesService
336	Namespaces            *NamespacesService
337	Notes                 *NotesService
338	NotificationSettings  *NotificationSettingsService
339	PagesDomains          *PagesDomainsService
340	PipelineSchedules     *PipelineSchedulesService
341	PipelineTriggers      *PipelineTriggersService
342	Pipelines             *PipelinesService
343	ProjectBadges         *ProjectBadgesService
344	ProjectCluster        *ProjectClustersService
345	ProjectImportExport   *ProjectImportExportService
346	ProjectMembers        *ProjectMembersService
347	ProjectSnippets       *ProjectSnippetsService
348	ProjectVariables      *ProjectVariablesService
349	Projects              *ProjectsService
350	ProtectedBranches     *ProtectedBranchesService
351	ProtectedTags         *ProtectedTagsService
352	ReleaseLinks          *ReleaseLinksService
353	Releases              *ReleasesService
354	Repositories          *RepositoriesService
355	RepositoryFiles       *RepositoryFilesService
356	ResourceLabelEvents   *ResourceLabelEventsService
357	Runners               *RunnersService
358	Search                *SearchService
359	Services              *ServicesService
360	Settings              *SettingsService
361	Sidekiq               *SidekiqService
362	Snippets              *SnippetsService
363	SystemHooks           *SystemHooksService
364	Tags                  *TagsService
365	Todos                 *TodosService
366	Users                 *UsersService
367	Validate              *ValidateService
368	Version               *VersionService
369	Wikis                 *WikisService
370}
371
372// ListOptions specifies the optional parameters to various List methods that
373// support pagination.
374type ListOptions struct {
375	// For paginated result sets, page of results to retrieve.
376	Page int `url:"page,omitempty" json:"page,omitempty"`
377
378	// For paginated result sets, the number of results to include per page.
379	PerPage int `url:"per_page,omitempty" json:"per_page,omitempty"`
380}
381
382// NewClient returns a new GitLab API client. If a nil httpClient is
383// provided, http.DefaultClient will be used. To use API methods which require
384// authentication, provide a valid private or personal token.
385func NewClient(httpClient *http.Client, token string) *Client {
386	client := newClient(httpClient)
387	client.authType = privateToken
388	client.token = token
389	return client
390}
391
392// NewBasicAuthClient returns a new GitLab API client. If a nil httpClient is
393// provided, http.DefaultClient will be used. To use API methods which require
394// authentication, provide a valid username and password.
395func NewBasicAuthClient(httpClient *http.Client, endpoint, username, password string) (*Client, error) {
396	client := newClient(httpClient)
397	client.authType = basicAuth
398	client.username = username
399	client.password = password
400	client.SetBaseURL(endpoint)
401
402	err := client.requestOAuthToken(context.TODO())
403	if err != nil {
404		return nil, err
405	}
406
407	return client, nil
408}
409
410func (c *Client) requestOAuthToken(ctx context.Context) error {
411	config := &oauth2.Config{
412		Endpoint: oauth2.Endpoint{
413			AuthURL:  fmt.Sprintf("%s://%s/oauth/authorize", c.BaseURL().Scheme, c.BaseURL().Host),
414			TokenURL: fmt.Sprintf("%s://%s/oauth/token", c.BaseURL().Scheme, c.BaseURL().Host),
415		},
416	}
417	ctx = context.WithValue(ctx, oauth2.HTTPClient, c.client)
418	t, err := config.PasswordCredentialsToken(ctx, c.username, c.password)
419	if err != nil {
420		return err
421	}
422	c.token = t.AccessToken
423	return nil
424}
425
426// NewOAuthClient returns a new GitLab API client. If a nil httpClient is
427// provided, http.DefaultClient will be used. To use API methods which require
428// authentication, provide a valid oauth token.
429func NewOAuthClient(httpClient *http.Client, token string) *Client {
430	client := newClient(httpClient)
431	client.authType = oAuthToken
432	client.token = token
433	return client
434}
435
436func newClient(httpClient *http.Client) *Client {
437	if httpClient == nil {
438		httpClient = http.DefaultClient
439	}
440
441	c := &Client{client: httpClient, UserAgent: userAgent}
442	if err := c.SetBaseURL(defaultBaseURL); err != nil {
443		// Should never happen since defaultBaseURL is our constant.
444		panic(err)
445	}
446
447	// Create the internal timeStats service.
448	timeStats := &timeStatsService{client: c}
449
450	// Create all the public services.
451	c.AccessRequests = &AccessRequestsService{client: c}
452	c.AwardEmoji = &AwardEmojiService{client: c}
453	c.Boards = &IssueBoardsService{client: c}
454	c.Branches = &BranchesService{client: c}
455	c.BroadcastMessage = &BroadcastMessagesService{client: c}
456	c.CIYMLTemplate = &CIYMLTemplatesService{client: c}
457	c.Commits = &CommitsService{client: c}
458	c.ContainerRegistry = &ContainerRegistryService{client: c}
459	c.CustomAttribute = &CustomAttributesService{client: c}
460	c.DeployKeys = &DeployKeysService{client: c}
461	c.Deployments = &DeploymentsService{client: c}
462	c.Discussions = &DiscussionsService{client: c}
463	c.Environments = &EnvironmentsService{client: c}
464	c.Epics = &EpicsService{client: c}
465	c.Events = &EventsService{client: c}
466	c.Features = &FeaturesService{client: c}
467	c.GitIgnoreTemplates = &GitIgnoreTemplatesService{client: c}
468	c.GroupBadges = &GroupBadgesService{client: c}
469	c.GroupIssueBoards = &GroupIssueBoardsService{client: c}
470	c.GroupLabels = &GroupLabelsService{client: c}
471	c.GroupMembers = &GroupMembersService{client: c}
472	c.GroupMilestones = &GroupMilestonesService{client: c}
473	c.GroupVariables = &GroupVariablesService{client: c}
474	c.Groups = &GroupsService{client: c}
475	c.IssueLinks = &IssueLinksService{client: c}
476	c.Issues = &IssuesService{client: c, timeStats: timeStats}
477	c.Jobs = &JobsService{client: c}
478	c.Keys = &KeysService{client: c}
479	c.Labels = &LabelsService{client: c}
480	c.License = &LicenseService{client: c}
481	c.LicenseTemplates = &LicenseTemplatesService{client: c}
482	c.MergeRequestApprovals = &MergeRequestApprovalsService{client: c}
483	c.MergeRequests = &MergeRequestsService{client: c, timeStats: timeStats}
484	c.Milestones = &MilestonesService{client: c}
485	c.Namespaces = &NamespacesService{client: c}
486	c.Notes = &NotesService{client: c}
487	c.NotificationSettings = &NotificationSettingsService{client: c}
488	c.PagesDomains = &PagesDomainsService{client: c}
489	c.PipelineSchedules = &PipelineSchedulesService{client: c}
490	c.PipelineTriggers = &PipelineTriggersService{client: c}
491	c.Pipelines = &PipelinesService{client: c}
492	c.ProjectBadges = &ProjectBadgesService{client: c}
493	c.ProjectCluster = &ProjectClustersService{client: c}
494	c.ProjectImportExport = &ProjectImportExportService{client: c}
495	c.ProjectMembers = &ProjectMembersService{client: c}
496	c.ProjectSnippets = &ProjectSnippetsService{client: c}
497	c.ProjectVariables = &ProjectVariablesService{client: c}
498	c.Projects = &ProjectsService{client: c}
499	c.ProtectedBranches = &ProtectedBranchesService{client: c}
500	c.ProtectedTags = &ProtectedTagsService{client: c}
501	c.ReleaseLinks = &ReleaseLinksService{client: c}
502	c.Releases = &ReleasesService{client: c}
503	c.Repositories = &RepositoriesService{client: c}
504	c.RepositoryFiles = &RepositoryFilesService{client: c}
505	c.ResourceLabelEvents = &ResourceLabelEventsService{client: c}
506	c.Runners = &RunnersService{client: c}
507	c.Search = &SearchService{client: c}
508	c.Services = &ServicesService{client: c}
509	c.Settings = &SettingsService{client: c}
510	c.Sidekiq = &SidekiqService{client: c}
511	c.Snippets = &SnippetsService{client: c}
512	c.SystemHooks = &SystemHooksService{client: c}
513	c.Tags = &TagsService{client: c}
514	c.Todos = &TodosService{client: c}
515	c.Users = &UsersService{client: c}
516	c.Validate = &ValidateService{client: c}
517	c.Version = &VersionService{client: c}
518	c.Wikis = &WikisService{client: c}
519
520	return c
521}
522
523// BaseURL return a copy of the baseURL.
524func (c *Client) BaseURL() *url.URL {
525	u := *c.baseURL
526	return &u
527}
528
529// SetBaseURL sets the base URL for API requests to a custom endpoint. urlStr
530// should always be specified with a trailing slash.
531func (c *Client) SetBaseURL(urlStr string) error {
532	// Make sure the given URL end with a slash
533	if !strings.HasSuffix(urlStr, "/") {
534		urlStr += "/"
535	}
536
537	baseURL, err := url.Parse(urlStr)
538	if err != nil {
539		return err
540	}
541
542	if !strings.HasSuffix(baseURL.Path, apiVersionPath) {
543		baseURL.Path += apiVersionPath
544	}
545
546	// Update the base URL of the client.
547	c.baseURL = baseURL
548
549	return nil
550}
551
552// NewRequest creates an API request. A relative URL path can be provided in
553// urlStr, in which case it is resolved relative to the base URL of the Client.
554// Relative URL paths should always be specified without a preceding slash. If
555// specified, the value pointed to by body is JSON encoded and included as the
556// request body.
557func (c *Client) NewRequest(method, path string, opt interface{}, options []OptionFunc) (*http.Request, error) {
558	u := *c.baseURL
559	unescaped, err := url.PathUnescape(path)
560	if err != nil {
561		return nil, err
562	}
563
564	// Set the encoded path data
565	u.RawPath = c.baseURL.Path + path
566	u.Path = c.baseURL.Path + unescaped
567
568	if opt != nil {
569		q, err := query.Values(opt)
570		if err != nil {
571			return nil, err
572		}
573		u.RawQuery = q.Encode()
574	}
575
576	req := &http.Request{
577		Method:     method,
578		URL:        &u,
579		Proto:      "HTTP/1.1",
580		ProtoMajor: 1,
581		ProtoMinor: 1,
582		Header:     make(http.Header),
583		Host:       u.Host,
584	}
585
586	for _, fn := range options {
587		if fn == nil {
588			continue
589		}
590
591		if err := fn(req); err != nil {
592			return nil, err
593		}
594	}
595
596	if method == "POST" || method == "PUT" {
597		bodyBytes, err := json.Marshal(opt)
598		if err != nil {
599			return nil, err
600		}
601		bodyReader := bytes.NewReader(bodyBytes)
602
603		u.RawQuery = ""
604		req.Body = ioutil.NopCloser(bodyReader)
605		req.GetBody = func() (io.ReadCloser, error) {
606			return ioutil.NopCloser(bodyReader), nil
607		}
608		req.ContentLength = int64(bodyReader.Len())
609		req.Header.Set("Content-Type", "application/json")
610	}
611
612	req.Header.Set("Accept", "application/json")
613
614	switch c.authType {
615	case basicAuth, oAuthToken:
616		req.Header.Set("Authorization", "Bearer "+c.token)
617	case privateToken:
618		req.Header.Set("PRIVATE-TOKEN", c.token)
619	}
620
621	if c.UserAgent != "" {
622		req.Header.Set("User-Agent", c.UserAgent)
623	}
624
625	return req, nil
626}
627
628// Response is a GitLab API response. This wraps the standard http.Response
629// returned from GitLab and provides convenient access to things like
630// pagination links.
631type Response struct {
632	*http.Response
633
634	// These fields provide the page values for paginating through a set of
635	// results. Any or all of these may be set to the zero value for
636	// responses that are not part of a paginated set, or for which there
637	// are no additional pages.
638	TotalItems   int
639	TotalPages   int
640	ItemsPerPage int
641	CurrentPage  int
642	NextPage     int
643	PreviousPage int
644}
645
646// newResponse creates a new Response for the provided http.Response.
647func newResponse(r *http.Response) *Response {
648	response := &Response{Response: r}
649	response.populatePageValues()
650	return response
651}
652
653const (
654	xTotal      = "X-Total"
655	xTotalPages = "X-Total-Pages"
656	xPerPage    = "X-Per-Page"
657	xPage       = "X-Page"
658	xNextPage   = "X-Next-Page"
659	xPrevPage   = "X-Prev-Page"
660)
661
662// populatePageValues parses the HTTP Link response headers and populates the
663// various pagination link values in the Response.
664func (r *Response) populatePageValues() {
665	if totalItems := r.Response.Header.Get(xTotal); totalItems != "" {
666		r.TotalItems, _ = strconv.Atoi(totalItems)
667	}
668	if totalPages := r.Response.Header.Get(xTotalPages); totalPages != "" {
669		r.TotalPages, _ = strconv.Atoi(totalPages)
670	}
671	if itemsPerPage := r.Response.Header.Get(xPerPage); itemsPerPage != "" {
672		r.ItemsPerPage, _ = strconv.Atoi(itemsPerPage)
673	}
674	if currentPage := r.Response.Header.Get(xPage); currentPage != "" {
675		r.CurrentPage, _ = strconv.Atoi(currentPage)
676	}
677	if nextPage := r.Response.Header.Get(xNextPage); nextPage != "" {
678		r.NextPage, _ = strconv.Atoi(nextPage)
679	}
680	if previousPage := r.Response.Header.Get(xPrevPage); previousPage != "" {
681		r.PreviousPage, _ = strconv.Atoi(previousPage)
682	}
683}
684
685// Do sends an API request and returns the API response. The API response is
686// JSON decoded and stored in the value pointed to by v, or returned as an
687// error if an API error has occurred. If v implements the io.Writer
688// interface, the raw response body will be written to v, without attempting to
689// first decode it.
690func (c *Client) Do(req *http.Request, v interface{}) (*Response, error) {
691	resp, err := c.client.Do(req)
692	if err != nil {
693		return nil, err
694	}
695	defer resp.Body.Close()
696
697	if resp.StatusCode == http.StatusUnauthorized && c.authType == basicAuth {
698		err = c.requestOAuthToken(req.Context())
699		if err != nil {
700			return nil, err
701		}
702		return c.Do(req, v)
703	}
704
705	response := newResponse(resp)
706
707	err = CheckResponse(resp)
708	if err != nil {
709		// even though there was an error, we still return the response
710		// in case the caller wants to inspect it further
711		return response, err
712	}
713
714	if v != nil {
715		if w, ok := v.(io.Writer); ok {
716			_, err = io.Copy(w, resp.Body)
717		} else {
718			err = json.NewDecoder(resp.Body).Decode(v)
719		}
720	}
721
722	return response, err
723}
724
725// Helper function to accept and format both the project ID or name as project
726// identifier for all API calls.
727func parseID(id interface{}) (string, error) {
728	switch v := id.(type) {
729	case int:
730		return strconv.Itoa(v), nil
731	case string:
732		return v, nil
733	default:
734		return "", fmt.Errorf("invalid ID type %#v, the ID must be an int or a string", id)
735	}
736}
737
738// Helper function to escape a project identifier.
739func pathEscape(s string) string {
740	return strings.Replace(url.PathEscape(s), ".", "%2E", -1)
741}
742
743// An ErrorResponse reports one or more errors caused by an API request.
744//
745// GitLab API docs:
746// https://docs.gitlab.com/ce/api/README.html#data-validation-and-error-reporting
747type ErrorResponse struct {
748	Body     []byte
749	Response *http.Response
750	Message  string
751}
752
753func (e *ErrorResponse) Error() string {
754	path, _ := url.QueryUnescape(e.Response.Request.URL.Path)
755	u := fmt.Sprintf("%s://%s%s", e.Response.Request.URL.Scheme, e.Response.Request.URL.Host, path)
756	return fmt.Sprintf("%s %s: %d %s", e.Response.Request.Method, u, e.Response.StatusCode, e.Message)
757}
758
759// CheckResponse checks the API response for errors, and returns them if present.
760func CheckResponse(r *http.Response) error {
761	switch r.StatusCode {
762	case 200, 201, 202, 204, 304:
763		return nil
764	}
765
766	errorResponse := &ErrorResponse{Response: r}
767	data, err := ioutil.ReadAll(r.Body)
768	if err == nil && data != nil {
769		errorResponse.Body = data
770
771		var raw interface{}
772		if err := json.Unmarshal(data, &raw); err != nil {
773			errorResponse.Message = "failed to parse unknown error format"
774		} else {
775			errorResponse.Message = parseError(raw)
776		}
777	}
778
779	return errorResponse
780}
781
782// Format:
783// {
784//     "message": {
785//         "<property-name>": [
786//             "<error-message>",
787//             "<error-message>",
788//             ...
789//         ],
790//         "<embed-entity>": {
791//             "<property-name>": [
792//                 "<error-message>",
793//                 "<error-message>",
794//                 ...
795//             ],
796//         }
797//     },
798//     "error": "<error-message>"
799// }
800func parseError(raw interface{}) string {
801	switch raw := raw.(type) {
802	case string:
803		return raw
804
805	case []interface{}:
806		var errs []string
807		for _, v := range raw {
808			errs = append(errs, parseError(v))
809		}
810		return fmt.Sprintf("[%s]", strings.Join(errs, ", "))
811
812	case map[string]interface{}:
813		var errs []string
814		for k, v := range raw {
815			errs = append(errs, fmt.Sprintf("{%s: %s}", k, parseError(v)))
816		}
817		sort.Strings(errs)
818		return strings.Join(errs, ", ")
819
820	default:
821		return fmt.Sprintf("failed to parse unexpected error type: %T", raw)
822	}
823}
824
825// OptionFunc can be passed to all API requests to make the API call as if you were
826// another user, provided your private token is from an administrator account.
827//
828// GitLab docs: https://docs.gitlab.com/ce/api/README.html#sudo
829type OptionFunc func(*http.Request) error
830
831// WithSudo takes either a username or user ID and sets the SUDO request header
832func WithSudo(uid interface{}) OptionFunc {
833	return func(req *http.Request) error {
834		user, err := parseID(uid)
835		if err != nil {
836			return err
837		}
838		req.Header.Set("SUDO", user)
839		return nil
840	}
841}
842
843// WithContext runs the request with the provided context
844func WithContext(ctx context.Context) OptionFunc {
845	return func(req *http.Request) error {
846		*req = *req.WithContext(ctx)
847		return nil
848	}
849}
850
851// Bool is a helper routine that allocates a new bool value
852// to store v and returns a pointer to it.
853func Bool(v bool) *bool {
854	p := new(bool)
855	*p = v
856	return p
857}
858
859// Int is a helper routine that allocates a new int32 value
860// to store v and returns a pointer to it, but unlike Int32
861// its argument value is an int.
862func Int(v int) *int {
863	p := new(int)
864	*p = v
865	return p
866}
867
868// String is a helper routine that allocates a new string value
869// to store v and returns a pointer to it.
870func String(v string) *string {
871	p := new(string)
872	*p = v
873	return p
874}
875
876// AccessLevel is a helper routine that allocates a new AccessLevelValue
877// to store v and returns a pointer to it.
878func AccessLevel(v AccessLevelValue) *AccessLevelValue {
879	p := new(AccessLevelValue)
880	*p = v
881	return p
882}
883
884// BuildState is a helper routine that allocates a new BuildStateValue
885// to store v and returns a pointer to it.
886func BuildState(v BuildStateValue) *BuildStateValue {
887	p := new(BuildStateValue)
888	*p = v
889	return p
890}
891
892// NotificationLevel is a helper routine that allocates a new NotificationLevelValue
893// to store v and returns a pointer to it.
894func NotificationLevel(v NotificationLevelValue) *NotificationLevelValue {
895	p := new(NotificationLevelValue)
896	*p = v
897	return p
898}
899
900// Visibility is a helper routine that allocates a new VisibilityValue
901// to store v and returns a pointer to it.
902func Visibility(v VisibilityValue) *VisibilityValue {
903	p := new(VisibilityValue)
904	*p = v
905	return p
906}
907
908// MergeMethod is a helper routine that allocates a new MergeMethod
909// to sotre v and returns a pointer to it.
910func MergeMethod(v MergeMethodValue) *MergeMethodValue {
911	p := new(MergeMethodValue)
912	*p = v
913	return p
914}
915
916// BoolValue is a boolean value with advanced json unmarshaling features.
917type BoolValue bool
918
919// UnmarshalJSON allows 1 and 0 to be considered as boolean values
920// Needed for https://gitlab.com/gitlab-org/gitlab-ce/issues/50122
921func (t *BoolValue) UnmarshalJSON(b []byte) error {
922	switch string(b) {
923	case `"1"`:
924		*t = true
925		return nil
926	case `"0"`:
927		*t = false
928		return nil
929	default:
930		var v bool
931		err := json.Unmarshal(b, &v)
932		*t = BoolValue(v)
933		return err
934	}
935}