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// MergeMethodValue represents a project merge type within GitLab.
217//
218// GitLab API docs: https://docs.gitlab.com/ce/api/projects.html#project-merge-method
219type MergeMethodValue string
220
221// List of available merge type
222//
223// GitLab API docs: https://docs.gitlab.com/ce/api/projects.html#project-merge-method
224const (
225	NoFastForwardMerge MergeMethodValue = "merge"
226	FastForwardMerge   MergeMethodValue = "ff"
227	RebaseMerge        MergeMethodValue = "rebase_merge"
228)
229
230// EventTypeValue represents actions type for contribution events
231type EventTypeValue string
232
233// List of available action type
234//
235// GitLab API docs: https://docs.gitlab.com/ce/api/events.html#action-types
236const (
237	CreatedEventType   EventTypeValue = "created"
238	UpdatedEventType   EventTypeValue = "updated"
239	ClosedEventType    EventTypeValue = "closed"
240	ReopenedEventType  EventTypeValue = "reopened"
241	PushedEventType    EventTypeValue = "pushed"
242	CommentedEventType EventTypeValue = "commented"
243	MergedEventType    EventTypeValue = "merged"
244	JoinedEventType    EventTypeValue = "joined"
245	LeftEventType      EventTypeValue = "left"
246	DestroyedEventType EventTypeValue = "destroyed"
247	ExpiredEventType   EventTypeValue = "expired"
248)
249
250// EventTargetTypeValue represents actions type value for contribution events
251type EventTargetTypeValue string
252
253// List of available action type
254//
255// GitLab API docs: https://docs.gitlab.com/ce/api/events.html#target-types
256const (
257	IssueEventTargetType        EventTargetTypeValue = "issue"
258	MilestoneEventTargetType    EventTargetTypeValue = "milestone"
259	MergeRequestEventTargetType EventTargetTypeValue = "merge_request"
260	NoteEventTargetType         EventTargetTypeValue = "note"
261	ProjectEventTargetType      EventTargetTypeValue = "project"
262	SnippetEventTargetType      EventTargetTypeValue = "snippet"
263	UserEventTargetType         EventTargetTypeValue = "user"
264)
265
266// A Client manages communication with the GitLab API.
267type Client struct {
268	// HTTP client used to communicate with the API.
269	client *http.Client
270
271	// Base URL for API requests. Defaults to the public GitLab API, but can be
272	// set to a domain endpoint to use with a self hosted GitLab server. baseURL
273	// should always be specified with a trailing slash.
274	baseURL *url.URL
275
276	// Token type used to make authenticated API calls.
277	authType authType
278
279	// Username and password used for basix authentication.
280	username, password string
281
282	// Token used to make authenticated API calls.
283	token string
284
285	// User agent used when communicating with the GitLab API.
286	UserAgent string
287
288	// Services used for talking to different parts of the GitLab API.
289	AccessRequests        *AccessRequestsService
290	AwardEmoji            *AwardEmojiService
291	Boards                *IssueBoardsService
292	Branches              *BranchesService
293	BroadcastMessage      *BroadcastMessagesService
294	BuildVariables        *BuildVariablesService
295	CIYMLTemplate         *CIYMLTemplatesService
296	Commits               *CommitsService
297	ContainerRegistry     *ContainerRegistryService
298	CustomAttribute       *CustomAttributesService
299	DeployKeys            *DeployKeysService
300	Deployments           *DeploymentsService
301	Discussions           *DiscussionsService
302	Environments          *EnvironmentsService
303	Epics                 *EpicsService
304	Events                *EventsService
305	Features              *FeaturesService
306	GitIgnoreTemplates    *GitIgnoreTemplatesService
307	GroupBadges           *GroupBadgesService
308	GroupIssueBoards      *GroupIssueBoardsService
309	GroupLabels           *GroupLabelsService
310	GroupMembers          *GroupMembersService
311	GroupMilestones       *GroupMilestonesService
312	GroupVariables        *GroupVariablesService
313	Groups                *GroupsService
314	IssueLinks            *IssueLinksService
315	Issues                *IssuesService
316	Jobs                  *JobsService
317	Keys                  *KeysService
318	Labels                *LabelsService
319	License               *LicenseService
320	LicenseTemplates      *LicenseTemplatesService
321	MergeRequestApprovals *MergeRequestApprovalsService
322	MergeRequests         *MergeRequestsService
323	Milestones            *MilestonesService
324	Namespaces            *NamespacesService
325	Notes                 *NotesService
326	NotificationSettings  *NotificationSettingsService
327	PagesDomains          *PagesDomainsService
328	PipelineSchedules     *PipelineSchedulesService
329	PipelineTriggers      *PipelineTriggersService
330	Pipelines             *PipelinesService
331	ProjectBadges         *ProjectBadgesService
332	ProjectCluster        *ProjectClustersService
333	ProjectImportExport   *ProjectImportExportService
334	ProjectMembers        *ProjectMembersService
335	ProjectSnippets       *ProjectSnippetsService
336	ProjectVariables      *ProjectVariablesService
337	Projects              *ProjectsService
338	ProtectedBranches     *ProtectedBranchesService
339	ProtectedTags         *ProtectedTagsService
340	ReleaseLinks          *ReleaseLinksService
341	Releases              *ReleasesService
342	Repositories          *RepositoriesService
343	RepositoryFiles       *RepositoryFilesService
344	ResourceLabelEvents   *ResourceLabelEventsService
345	Runners               *RunnersService
346	Search                *SearchService
347	Services              *ServicesService
348	Settings              *SettingsService
349	Sidekiq               *SidekiqService
350	Snippets              *SnippetsService
351	SystemHooks           *SystemHooksService
352	Tags                  *TagsService
353	Todos                 *TodosService
354	Users                 *UsersService
355	Validate              *ValidateService
356	Version               *VersionService
357	Wikis                 *WikisService
358}
359
360// ListOptions specifies the optional parameters to various List methods that
361// support pagination.
362type ListOptions struct {
363	// For paginated result sets, page of results to retrieve.
364	Page int `url:"page,omitempty" json:"page,omitempty"`
365
366	// For paginated result sets, the number of results to include per page.
367	PerPage int `url:"per_page,omitempty" json:"per_page,omitempty"`
368}
369
370// NewClient returns a new GitLab API client. If a nil httpClient is
371// provided, http.DefaultClient will be used. To use API methods which require
372// authentication, provide a valid private or personal token.
373func NewClient(httpClient *http.Client, token string) *Client {
374	client := newClient(httpClient)
375	client.authType = privateToken
376	client.token = token
377	return client
378}
379
380// NewBasicAuthClient returns a new GitLab API client. If a nil httpClient is
381// provided, http.DefaultClient will be used. To use API methods which require
382// authentication, provide a valid username and password.
383func NewBasicAuthClient(httpClient *http.Client, endpoint, username, password string) (*Client, error) {
384	client := newClient(httpClient)
385	client.authType = basicAuth
386	client.username = username
387	client.password = password
388	client.SetBaseURL(endpoint)
389
390	err := client.requestOAuthToken(context.TODO())
391	if err != nil {
392		return nil, err
393	}
394
395	return client, nil
396}
397
398func (c *Client) requestOAuthToken(ctx context.Context) error {
399	config := &oauth2.Config{
400		Endpoint: oauth2.Endpoint{
401			AuthURL:  fmt.Sprintf("%s://%s/oauth/authorize", c.BaseURL().Scheme, c.BaseURL().Host),
402			TokenURL: fmt.Sprintf("%s://%s/oauth/token", c.BaseURL().Scheme, c.BaseURL().Host),
403		},
404	}
405	ctx = context.WithValue(ctx, oauth2.HTTPClient, c.client)
406	t, err := config.PasswordCredentialsToken(ctx, c.username, c.password)
407	if err != nil {
408		return err
409	}
410	c.token = t.AccessToken
411	return nil
412}
413
414// NewOAuthClient returns a new GitLab API client. If a nil httpClient is
415// provided, http.DefaultClient will be used. To use API methods which require
416// authentication, provide a valid oauth token.
417func NewOAuthClient(httpClient *http.Client, token string) *Client {
418	client := newClient(httpClient)
419	client.authType = oAuthToken
420	client.token = token
421	return client
422}
423
424func newClient(httpClient *http.Client) *Client {
425	if httpClient == nil {
426		httpClient = http.DefaultClient
427	}
428
429	c := &Client{client: httpClient, UserAgent: userAgent}
430	if err := c.SetBaseURL(defaultBaseURL); err != nil {
431		// Should never happen since defaultBaseURL is our constant.
432		panic(err)
433	}
434
435	// Create the internal timeStats service.
436	timeStats := &timeStatsService{client: c}
437
438	// Create all the public services.
439	c.AccessRequests = &AccessRequestsService{client: c}
440	c.AwardEmoji = &AwardEmojiService{client: c}
441	c.Boards = &IssueBoardsService{client: c}
442	c.Branches = &BranchesService{client: c}
443	c.BroadcastMessage = &BroadcastMessagesService{client: c}
444	c.BuildVariables = &BuildVariablesService{client: c}
445	c.CIYMLTemplate = &CIYMLTemplatesService{client: c}
446	c.Commits = &CommitsService{client: c}
447	c.ContainerRegistry = &ContainerRegistryService{client: c}
448	c.CustomAttribute = &CustomAttributesService{client: c}
449	c.DeployKeys = &DeployKeysService{client: c}
450	c.Deployments = &DeploymentsService{client: c}
451	c.Discussions = &DiscussionsService{client: c}
452	c.Environments = &EnvironmentsService{client: c}
453	c.Epics = &EpicsService{client: c}
454	c.Events = &EventsService{client: c}
455	c.Features = &FeaturesService{client: c}
456	c.GitIgnoreTemplates = &GitIgnoreTemplatesService{client: c}
457	c.GroupBadges = &GroupBadgesService{client: c}
458	c.GroupIssueBoards = &GroupIssueBoardsService{client: c}
459	c.GroupLabels = &GroupLabelsService{client: c}
460	c.GroupMembers = &GroupMembersService{client: c}
461	c.GroupMilestones = &GroupMilestonesService{client: c}
462	c.GroupVariables = &GroupVariablesService{client: c}
463	c.Groups = &GroupsService{client: c}
464	c.IssueLinks = &IssueLinksService{client: c}
465	c.Issues = &IssuesService{client: c, timeStats: timeStats}
466	c.Jobs = &JobsService{client: c}
467	c.Keys = &KeysService{client: c}
468	c.Labels = &LabelsService{client: c}
469	c.License = &LicenseService{client: c}
470	c.LicenseTemplates = &LicenseTemplatesService{client: c}
471	c.MergeRequestApprovals = &MergeRequestApprovalsService{client: c}
472	c.MergeRequests = &MergeRequestsService{client: c, timeStats: timeStats}
473	c.Milestones = &MilestonesService{client: c}
474	c.Namespaces = &NamespacesService{client: c}
475	c.Notes = &NotesService{client: c}
476	c.NotificationSettings = &NotificationSettingsService{client: c}
477	c.PagesDomains = &PagesDomainsService{client: c}
478	c.PipelineSchedules = &PipelineSchedulesService{client: c}
479	c.PipelineTriggers = &PipelineTriggersService{client: c}
480	c.Pipelines = &PipelinesService{client: c}
481	c.ProjectBadges = &ProjectBadgesService{client: c}
482	c.ProjectCluster = &ProjectClustersService{client: c}
483	c.ProjectImportExport = &ProjectImportExportService{client: c}
484	c.ProjectMembers = &ProjectMembersService{client: c}
485	c.ProjectSnippets = &ProjectSnippetsService{client: c}
486	c.ProjectVariables = &ProjectVariablesService{client: c}
487	c.Projects = &ProjectsService{client: c}
488	c.ProtectedBranches = &ProtectedBranchesService{client: c}
489	c.ProtectedTags = &ProtectedTagsService{client: c}
490	c.ReleaseLinks = &ReleaseLinksService{client: c}
491	c.Releases = &ReleasesService{client: c}
492	c.Repositories = &RepositoriesService{client: c}
493	c.RepositoryFiles = &RepositoryFilesService{client: c}
494	c.ResourceLabelEvents = &ResourceLabelEventsService{client: c}
495	c.Runners = &RunnersService{client: c}
496	c.Search = &SearchService{client: c}
497	c.Services = &ServicesService{client: c}
498	c.Settings = &SettingsService{client: c}
499	c.Sidekiq = &SidekiqService{client: c}
500	c.Snippets = &SnippetsService{client: c}
501	c.SystemHooks = &SystemHooksService{client: c}
502	c.Tags = &TagsService{client: c}
503	c.Todos = &TodosService{client: c}
504	c.Users = &UsersService{client: c}
505	c.Validate = &ValidateService{client: c}
506	c.Version = &VersionService{client: c}
507	c.Wikis = &WikisService{client: c}
508
509	return c
510}
511
512// BaseURL return a copy of the baseURL.
513func (c *Client) BaseURL() *url.URL {
514	u := *c.baseURL
515	return &u
516}
517
518// SetBaseURL sets the base URL for API requests to a custom endpoint. urlStr
519// should always be specified with a trailing slash.
520func (c *Client) SetBaseURL(urlStr string) error {
521	// Make sure the given URL end with a slash
522	if !strings.HasSuffix(urlStr, "/") {
523		urlStr += "/"
524	}
525
526	baseURL, err := url.Parse(urlStr)
527	if err != nil {
528		return err
529	}
530
531	if !strings.HasSuffix(baseURL.Path, apiVersionPath) {
532		baseURL.Path += apiVersionPath
533	}
534
535	// Update the base URL of the client.
536	c.baseURL = baseURL
537
538	return nil
539}
540
541// NewRequest creates an API request. A relative URL path can be provided in
542// urlStr, in which case it is resolved relative to the base URL of the Client.
543// Relative URL paths should always be specified without a preceding slash. If
544// specified, the value pointed to by body is JSON encoded and included as the
545// request body.
546func (c *Client) NewRequest(method, path string, opt interface{}, options []OptionFunc) (*http.Request, error) {
547	u := *c.baseURL
548	unescaped, err := url.PathUnescape(path)
549	if err != nil {
550		return nil, err
551	}
552
553	// Set the encoded path data
554	u.RawPath = c.baseURL.Path + path
555	u.Path = c.baseURL.Path + unescaped
556
557	if opt != nil {
558		q, err := query.Values(opt)
559		if err != nil {
560			return nil, err
561		}
562		u.RawQuery = q.Encode()
563	}
564
565	req := &http.Request{
566		Method:     method,
567		URL:        &u,
568		Proto:      "HTTP/1.1",
569		ProtoMajor: 1,
570		ProtoMinor: 1,
571		Header:     make(http.Header),
572		Host:       u.Host,
573	}
574
575	for _, fn := range options {
576		if fn == nil {
577			continue
578		}
579
580		if err := fn(req); err != nil {
581			return nil, err
582		}
583	}
584
585	if method == "POST" || method == "PUT" {
586		bodyBytes, err := json.Marshal(opt)
587		if err != nil {
588			return nil, err
589		}
590		bodyReader := bytes.NewReader(bodyBytes)
591
592		u.RawQuery = ""
593		req.Body = ioutil.NopCloser(bodyReader)
594		req.GetBody = func() (io.ReadCloser, error) {
595			return ioutil.NopCloser(bodyReader), nil
596		}
597		req.ContentLength = int64(bodyReader.Len())
598		req.Header.Set("Content-Type", "application/json")
599	}
600
601	req.Header.Set("Accept", "application/json")
602
603	switch c.authType {
604	case basicAuth, oAuthToken:
605		req.Header.Set("Authorization", "Bearer "+c.token)
606	case privateToken:
607		req.Header.Set("PRIVATE-TOKEN", c.token)
608	}
609
610	if c.UserAgent != "" {
611		req.Header.Set("User-Agent", c.UserAgent)
612	}
613
614	return req, nil
615}
616
617// Response is a GitLab API response. This wraps the standard http.Response
618// returned from GitLab and provides convenient access to things like
619// pagination links.
620type Response struct {
621	*http.Response
622
623	// These fields provide the page values for paginating through a set of
624	// results. Any or all of these may be set to the zero value for
625	// responses that are not part of a paginated set, or for which there
626	// are no additional pages.
627	TotalItems   int
628	TotalPages   int
629	ItemsPerPage int
630	CurrentPage  int
631	NextPage     int
632	PreviousPage int
633}
634
635// newResponse creates a new Response for the provided http.Response.
636func newResponse(r *http.Response) *Response {
637	response := &Response{Response: r}
638	response.populatePageValues()
639	return response
640}
641
642const (
643	xTotal      = "X-Total"
644	xTotalPages = "X-Total-Pages"
645	xPerPage    = "X-Per-Page"
646	xPage       = "X-Page"
647	xNextPage   = "X-Next-Page"
648	xPrevPage   = "X-Prev-Page"
649)
650
651// populatePageValues parses the HTTP Link response headers and populates the
652// various pagination link values in the Response.
653func (r *Response) populatePageValues() {
654	if totalItems := r.Response.Header.Get(xTotal); totalItems != "" {
655		r.TotalItems, _ = strconv.Atoi(totalItems)
656	}
657	if totalPages := r.Response.Header.Get(xTotalPages); totalPages != "" {
658		r.TotalPages, _ = strconv.Atoi(totalPages)
659	}
660	if itemsPerPage := r.Response.Header.Get(xPerPage); itemsPerPage != "" {
661		r.ItemsPerPage, _ = strconv.Atoi(itemsPerPage)
662	}
663	if currentPage := r.Response.Header.Get(xPage); currentPage != "" {
664		r.CurrentPage, _ = strconv.Atoi(currentPage)
665	}
666	if nextPage := r.Response.Header.Get(xNextPage); nextPage != "" {
667		r.NextPage, _ = strconv.Atoi(nextPage)
668	}
669	if previousPage := r.Response.Header.Get(xPrevPage); previousPage != "" {
670		r.PreviousPage, _ = strconv.Atoi(previousPage)
671	}
672}
673
674// Do sends an API request and returns the API response. The API response is
675// JSON decoded and stored in the value pointed to by v, or returned as an
676// error if an API error has occurred. If v implements the io.Writer
677// interface, the raw response body will be written to v, without attempting to
678// first decode it.
679func (c *Client) Do(req *http.Request, v interface{}) (*Response, error) {
680	resp, err := c.client.Do(req)
681	if err != nil {
682		return nil, err
683	}
684	defer resp.Body.Close()
685
686	if resp.StatusCode == http.StatusUnauthorized && c.authType == basicAuth {
687		err = c.requestOAuthToken(req.Context())
688		if err != nil {
689			return nil, err
690		}
691		return c.Do(req, v)
692	}
693
694	response := newResponse(resp)
695
696	err = CheckResponse(resp)
697	if err != nil {
698		// even though there was an error, we still return the response
699		// in case the caller wants to inspect it further
700		return response, err
701	}
702
703	if v != nil {
704		if w, ok := v.(io.Writer); ok {
705			_, err = io.Copy(w, resp.Body)
706		} else {
707			err = json.NewDecoder(resp.Body).Decode(v)
708		}
709	}
710
711	return response, err
712}
713
714// Helper function to accept and format both the project ID or name as project
715// identifier for all API calls.
716func parseID(id interface{}) (string, error) {
717	switch v := id.(type) {
718	case int:
719		return strconv.Itoa(v), nil
720	case string:
721		return v, nil
722	default:
723		return "", fmt.Errorf("invalid ID type %#v, the ID must be an int or a string", id)
724	}
725}
726
727// Helper function to escape a project identifier.
728func pathEscape(s string) string {
729	return strings.Replace(url.PathEscape(s), ".", "%2E", -1)
730}
731
732// An ErrorResponse reports one or more errors caused by an API request.
733//
734// GitLab API docs:
735// https://docs.gitlab.com/ce/api/README.html#data-validation-and-error-reporting
736type ErrorResponse struct {
737	Body     []byte
738	Response *http.Response
739	Message  string
740}
741
742func (e *ErrorResponse) Error() string {
743	path, _ := url.QueryUnescape(e.Response.Request.URL.Path)
744	u := fmt.Sprintf("%s://%s%s", e.Response.Request.URL.Scheme, e.Response.Request.URL.Host, path)
745	return fmt.Sprintf("%s %s: %d %s", e.Response.Request.Method, u, e.Response.StatusCode, e.Message)
746}
747
748// CheckResponse checks the API response for errors, and returns them if present.
749func CheckResponse(r *http.Response) error {
750	switch r.StatusCode {
751	case 200, 201, 202, 204, 304:
752		return nil
753	}
754
755	errorResponse := &ErrorResponse{Response: r}
756	data, err := ioutil.ReadAll(r.Body)
757	if err == nil && data != nil {
758		errorResponse.Body = data
759
760		var raw interface{}
761		if err := json.Unmarshal(data, &raw); err != nil {
762			errorResponse.Message = "failed to parse unknown error format"
763		} else {
764			errorResponse.Message = parseError(raw)
765		}
766	}
767
768	return errorResponse
769}
770
771// Format:
772// {
773//     "message": {
774//         "<property-name>": [
775//             "<error-message>",
776//             "<error-message>",
777//             ...
778//         ],
779//         "<embed-entity>": {
780//             "<property-name>": [
781//                 "<error-message>",
782//                 "<error-message>",
783//                 ...
784//             ],
785//         }
786//     },
787//     "error": "<error-message>"
788// }
789func parseError(raw interface{}) string {
790	switch raw := raw.(type) {
791	case string:
792		return raw
793
794	case []interface{}:
795		var errs []string
796		for _, v := range raw {
797			errs = append(errs, parseError(v))
798		}
799		return fmt.Sprintf("[%s]", strings.Join(errs, ", "))
800
801	case map[string]interface{}:
802		var errs []string
803		for k, v := range raw {
804			errs = append(errs, fmt.Sprintf("{%s: %s}", k, parseError(v)))
805		}
806		sort.Strings(errs)
807		return strings.Join(errs, ", ")
808
809	default:
810		return fmt.Sprintf("failed to parse unexpected error type: %T", raw)
811	}
812}
813
814// OptionFunc can be passed to all API requests to make the API call as if you were
815// another user, provided your private token is from an administrator account.
816//
817// GitLab docs: https://docs.gitlab.com/ce/api/README.html#sudo
818type OptionFunc func(*http.Request) error
819
820// WithSudo takes either a username or user ID and sets the SUDO request header
821func WithSudo(uid interface{}) OptionFunc {
822	return func(req *http.Request) error {
823		user, err := parseID(uid)
824		if err != nil {
825			return err
826		}
827		req.Header.Set("SUDO", user)
828		return nil
829	}
830}
831
832// WithContext runs the request with the provided context
833func WithContext(ctx context.Context) OptionFunc {
834	return func(req *http.Request) error {
835		*req = *req.WithContext(ctx)
836		return nil
837	}
838}
839
840// Bool is a helper routine that allocates a new bool value
841// to store v and returns a pointer to it.
842func Bool(v bool) *bool {
843	p := new(bool)
844	*p = v
845	return p
846}
847
848// Int is a helper routine that allocates a new int32 value
849// to store v and returns a pointer to it, but unlike Int32
850// its argument value is an int.
851func Int(v int) *int {
852	p := new(int)
853	*p = v
854	return p
855}
856
857// String is a helper routine that allocates a new string value
858// to store v and returns a pointer to it.
859func String(v string) *string {
860	p := new(string)
861	*p = v
862	return p
863}
864
865// AccessLevel is a helper routine that allocates a new AccessLevelValue
866// to store v and returns a pointer to it.
867func AccessLevel(v AccessLevelValue) *AccessLevelValue {
868	p := new(AccessLevelValue)
869	*p = v
870	return p
871}
872
873// BuildState is a helper routine that allocates a new BuildStateValue
874// to store v and returns a pointer to it.
875func BuildState(v BuildStateValue) *BuildStateValue {
876	p := new(BuildStateValue)
877	*p = v
878	return p
879}
880
881// NotificationLevel is a helper routine that allocates a new NotificationLevelValue
882// to store v and returns a pointer to it.
883func NotificationLevel(v NotificationLevelValue) *NotificationLevelValue {
884	p := new(NotificationLevelValue)
885	*p = v
886	return p
887}
888
889// Visibility is a helper routine that allocates a new VisibilityValue
890// to store v and returns a pointer to it.
891func Visibility(v VisibilityValue) *VisibilityValue {
892	p := new(VisibilityValue)
893	*p = v
894	return p
895}
896
897// MergeMethod is a helper routine that allocates a new MergeMethod
898// to sotre v and returns a pointer to it.
899func MergeMethod(v MergeMethodValue) *MergeMethodValue {
900	p := new(MergeMethodValue)
901	*p = v
902	return p
903}
904
905// BoolValue is a boolean value with advanced json unmarshaling features.
906type BoolValue bool
907
908// UnmarshalJSON allows 1 and 0 to be considered as boolean values
909// Needed for https://gitlab.com/gitlab-org/gitlab-ce/issues/50122
910func (t *BoolValue) UnmarshalJSON(b []byte) error {
911	switch string(b) {
912	case `"1"`:
913		*t = true
914		return nil
915	case `"0"`:
916		*t = false
917		return nil
918	default:
919		var v bool
920		err := json.Unmarshal(b, &v)
921		*t = BoolValue(v)
922		return err
923	}
924}