func (t *BoolValue) UnmarshalJSON(b []byte) error {
	switch string(b) {
	case `"1"`:
		*t = true
		return nil
	case `"0"`:
		*t = false
		return nil
	default:
		var v bool
		err := json.Unmarshal(b, &v)
		*t = BoolValue(v)
		return err
	}
}
UnmarshalJSON allows 1 and 0 to be considered as boolean values
Needed for https://gitlab.com/gitlab-org/gitlab-ce/issues/50122
package gitlab
import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"sort"
	"strconv"
	"strings"
	"time"
	"github.com/google/go-querystring/query"
	"golang.org/x/oauth2"
)
const (
	defaultBaseURL = "https://gitlab.com/"
	apiVersionPath = "api/v4/"
	userAgent      = "go-gitlab"
)
type authType int
const (
	basicAuth authType = iota
	oAuthToken
	privateToken
)
type AccessLevelValue int
const (
	NoPermissions         AccessLevelValue = 0
	GuestPermissions      AccessLevelValue = 10
	ReporterPermissions   AccessLevelValue = 20
	DeveloperPermissions  AccessLevelValue = 30
	MaintainerPermissions AccessLevelValue = 40
	OwnerPermissions      AccessLevelValue = 50
	MasterPermissions AccessLevelValue = 40
	OwnerPermission   AccessLevelValue = 50
)
type BuildStateValue string
const (
	Pending  BuildStateValue = "pending"
	Running  BuildStateValue = "running"
	Success  BuildStateValue = "success"
	Failed   BuildStateValue = "failed"
	Canceled BuildStateValue = "canceled"
	Skipped  BuildStateValue = "skipped"
)
type ISOTime time.Time
const iso8601 = "2006-01-02"
func (t ISOTime) MarshalJSON() ([]byte, error) {
	if y := time.Time(t).Year(); y < 0 || y >= 10000 {
		return nil, errors.New("ISOTime.MarshalJSON: year outside of range [0,9999]")
	}
	b := make([]byte, 0, len(iso8601)+2)
	b = append(b, '"')
	b = time.Time(t).AppendFormat(b, iso8601)
	b = append(b, '"')
	return b, nil
}
func (t *ISOTime) UnmarshalJSON(data []byte) error {
	if string(data) == "null" {
		return nil
	}
	isotime, err := time.Parse(`"`+iso8601+`"`, string(data))
	*t = ISOTime(isotime)
	return err
}
func (t *ISOTime) EncodeValues(key string, v *url.Values) error {
	if t == nil || (time.Time(*t)).IsZero() {
		return nil
	}
	v.Add(key, t.String())
	return nil
}
func (t ISOTime) String() string {
	return time.Time(t).Format(iso8601)
}
type NotificationLevelValue int
func (l NotificationLevelValue) String() string {
	return notificationLevelNames[l]
}
func (l NotificationLevelValue) MarshalJSON() ([]byte, error) {
	return json.Marshal(l.String())
}
func (l *NotificationLevelValue) UnmarshalJSON(data []byte) error {
	var raw interface{}
	if err := json.Unmarshal(data, &raw); err != nil {
		return err
	}
	switch raw := raw.(type) {
	case float64:
		*l = NotificationLevelValue(raw)
	case string:
		*l = notificationLevelTypes[raw]
	case nil:
	default:
		return fmt.Errorf("json: cannot unmarshal %T into Go value of type %T", raw, *l)
	}
	return nil
}
const (
	DisabledNotificationLevel NotificationLevelValue = iota
	ParticipatingNotificationLevel
	WatchNotificationLevel
	GlobalNotificationLevel
	MentionNotificationLevel
	CustomNotificationLevel
)
var notificationLevelNames = [...]string{
	"disabled",
	"participating",
	"watch",
	"global",
	"mention",
	"custom",
}
var notificationLevelTypes = map[string]NotificationLevelValue{
	"disabled":      DisabledNotificationLevel,
	"participating": ParticipatingNotificationLevel,
	"watch":         WatchNotificationLevel,
	"global":        GlobalNotificationLevel,
	"mention":       MentionNotificationLevel,
	"custom":        CustomNotificationLevel,
}
type VisibilityValue string
const (
	PrivateVisibility  VisibilityValue = "private"
	InternalVisibility VisibilityValue = "internal"
	PublicVisibility   VisibilityValue = "public"
)
type MergeMethodValue string
const (
	NoFastForwardMerge MergeMethodValue = "merge"
	FastForwardMerge   MergeMethodValue = "ff"
	RebaseMerge        MergeMethodValue = "rebase_merge"
)
type EventTypeValue string
const (
	CreatedEventType   EventTypeValue = "created"
	UpdatedEventType   EventTypeValue = "updated"
	ClosedEventType    EventTypeValue = "closed"
	ReopenedEventType  EventTypeValue = "reopened"
	PushedEventType    EventTypeValue = "pushed"
	CommentedEventType EventTypeValue = "commented"
	MergedEventType    EventTypeValue = "merged"
	JoinedEventType    EventTypeValue = "joined"
	LeftEventType      EventTypeValue = "left"
	DestroyedEventType EventTypeValue = "destroyed"
	ExpiredEventType   EventTypeValue = "expired"
)
type EventTargetTypeValue string
const (
	IssueEventTargetType        EventTargetTypeValue = "issue"
	MilestoneEventTargetType    EventTargetTypeValue = "milestone"
	MergeRequestEventTargetType EventTargetTypeValue = "merge_request"
	NoteEventTargetType         EventTargetTypeValue = "note"
	ProjectEventTargetType      EventTargetTypeValue = "project"
	SnippetEventTargetType      EventTargetTypeValue = "snippet"
	UserEventTargetType         EventTargetTypeValue = "user"
)
type Client struct {
	client *http.Client
	baseURL *url.URL
	authType authType
	username, password string
	token string
	UserAgent string
	AccessRequests        *AccessRequestsService
	AwardEmoji            *AwardEmojiService
	Boards                *IssueBoardsService
	Branches              *BranchesService
	BroadcastMessage      *BroadcastMessagesService
	BuildVariables        *BuildVariablesService
	CIYMLTemplate         *CIYMLTemplatesService
	Commits               *CommitsService
	ContainerRegistry     *ContainerRegistryService
	CustomAttribute       *CustomAttributesService
	DeployKeys            *DeployKeysService
	Deployments           *DeploymentsService
	Discussions           *DiscussionsService
	Environments          *EnvironmentsService
	Epics                 *EpicsService
	Events                *EventsService
	Features              *FeaturesService
	GitIgnoreTemplates    *GitIgnoreTemplatesService
	GroupBadges           *GroupBadgesService
	GroupIssueBoards      *GroupIssueBoardsService
	GroupLabels           *GroupLabelsService
	GroupMembers          *GroupMembersService
	GroupMilestones       *GroupMilestonesService
	GroupVariables        *GroupVariablesService
	Groups                *GroupsService
	IssueLinks            *IssueLinksService
	Issues                *IssuesService
	Jobs                  *JobsService
	Keys                  *KeysService
	Labels                *LabelsService
	License               *LicenseService
	LicenseTemplates      *LicenseTemplatesService
	MergeRequestApprovals *MergeRequestApprovalsService
	MergeRequests         *MergeRequestsService
	Milestones            *MilestonesService
	Namespaces            *NamespacesService
	Notes                 *NotesService
	NotificationSettings  *NotificationSettingsService
	PagesDomains          *PagesDomainsService
	PipelineSchedules     *PipelineSchedulesService
	PipelineTriggers      *PipelineTriggersService
	Pipelines             *PipelinesService
	ProjectBadges         *ProjectBadgesService
	ProjectCluster        *ProjectClustersService
	ProjectImportExport   *ProjectImportExportService
	ProjectMembers        *ProjectMembersService
	ProjectSnippets       *ProjectSnippetsService
	ProjectVariables      *ProjectVariablesService
	Projects              *ProjectsService
	ProtectedBranches     *ProtectedBranchesService
	ProtectedTags         *ProtectedTagsService
	ReleaseLinks          *ReleaseLinksService
	Releases              *ReleasesService
	Repositories          *RepositoriesService
	RepositoryFiles       *RepositoryFilesService
	Runners               *RunnersService
	Search                *SearchService
	Services              *ServicesService
	Settings              *SettingsService
	Sidekiq               *SidekiqService
	Snippets              *SnippetsService
	SystemHooks           *SystemHooksService
	Tags                  *TagsService
	Todos                 *TodosService
	Users                 *UsersService
	Validate              *ValidateService
	Version               *VersionService
	Wikis                 *WikisService
}
type ListOptions struct {
	Page int `url:"page,omitempty" json:"page,omitempty"`
	PerPage int `url:"per_page,omitempty" json:"per_page,omitempty"`
}
func NewClient(httpClient *http.Client, token string) *Client {
	client := newClient(httpClient)
	client.authType = privateToken
	client.token = token
	return client
}
func NewBasicAuthClient(httpClient *http.Client, endpoint, username, password string) (*Client, error) {
	client := newClient(httpClient)
	client.authType = basicAuth
	client.username = username
	client.password = password
	client.SetBaseURL(endpoint)
	err := client.requestOAuthToken(context.TODO())
	if err != nil {
		return nil, err
	}
	return client, nil
}
func (c *Client) requestOAuthToken(ctx context.Context) error {
	config := &oauth2.Config{
		Endpoint: oauth2.Endpoint{
			AuthURL:  fmt.Sprintf("%s://%s/oauth/authorize", c.BaseURL().Scheme, c.BaseURL().Host),
			TokenURL: fmt.Sprintf("%s://%s/oauth/token", c.BaseURL().Scheme, c.BaseURL().Host),
		},
	}
	ctx = context.WithValue(ctx, oauth2.HTTPClient, c.client)
	t, err := config.PasswordCredentialsToken(ctx, c.username, c.password)
	if err != nil {
		return err
	}
	c.token = t.AccessToken
	return nil
}
func NewOAuthClient(httpClient *http.Client, token string) *Client {
	client := newClient(httpClient)
	client.authType = oAuthToken
	client.token = token
	return client
}
func newClient(httpClient *http.Client) *Client {
	if httpClient == nil {
		httpClient = http.DefaultClient
	}
	c := &Client{client: httpClient, UserAgent: userAgent}
	if err := c.SetBaseURL(defaultBaseURL); err != nil {
		panic(err)
	}
	timeStats := &timeStatsService{client: c}
	c.AccessRequests = &AccessRequestsService{client: c}
	c.AwardEmoji = &AwardEmojiService{client: c}
	c.Boards = &IssueBoardsService{client: c}
	c.Branches = &BranchesService{client: c}
	c.BroadcastMessage = &BroadcastMessagesService{client: c}
	c.BuildVariables = &BuildVariablesService{client: c}
	c.CIYMLTemplate = &CIYMLTemplatesService{client: c}
	c.Commits = &CommitsService{client: c}
	c.ContainerRegistry = &ContainerRegistryService{client: c}
	c.CustomAttribute = &CustomAttributesService{client: c}
	c.DeployKeys = &DeployKeysService{client: c}
	c.Deployments = &DeploymentsService{client: c}
	c.Discussions = &DiscussionsService{client: c}
	c.Environments = &EnvironmentsService{client: c}
	c.Epics = &EpicsService{client: c}
	c.Events = &EventsService{client: c}
	c.Features = &FeaturesService{client: c}
	c.GitIgnoreTemplates = &GitIgnoreTemplatesService{client: c}
	c.GroupBadges = &GroupBadgesService{client: c}
	c.GroupIssueBoards = &GroupIssueBoardsService{client: c}
	c.GroupLabels = &GroupLabelsService{client: c}
	c.GroupMembers = &GroupMembersService{client: c}
	c.GroupMilestones = &GroupMilestonesService{client: c}
	c.GroupVariables = &GroupVariablesService{client: c}
	c.Groups = &GroupsService{client: c}
	c.IssueLinks = &IssueLinksService{client: c}
	c.Issues = &IssuesService{client: c, timeStats: timeStats}
	c.Jobs = &JobsService{client: c}
	c.Keys = &KeysService{client: c}
	c.Labels = &LabelsService{client: c}
	c.License = &LicenseService{client: c}
	c.LicenseTemplates = &LicenseTemplatesService{client: c}
	c.MergeRequestApprovals = &MergeRequestApprovalsService{client: c}
	c.MergeRequests = &MergeRequestsService{client: c, timeStats: timeStats}
	c.Milestones = &MilestonesService{client: c}
	c.Namespaces = &NamespacesService{client: c}
	c.Notes = &NotesService{client: c}
	c.NotificationSettings = &NotificationSettingsService{client: c}
	c.PagesDomains = &PagesDomainsService{client: c}
	c.PipelineSchedules = &PipelineSchedulesService{client: c}
	c.PipelineTriggers = &PipelineTriggersService{client: c}
	c.Pipelines = &PipelinesService{client: c}
	c.ProjectBadges = &ProjectBadgesService{client: c}
	c.ProjectCluster = &ProjectClustersService{client: c}
	c.ProjectImportExport = &ProjectImportExportService{client: c}
	c.ProjectMembers = &ProjectMembersService{client: c}
	c.ProjectSnippets = &ProjectSnippetsService{client: c}
	c.ProjectVariables = &ProjectVariablesService{client: c}
	c.Projects = &ProjectsService{client: c}
	c.ProtectedBranches = &ProtectedBranchesService{client: c}
	c.ProtectedTags = &ProtectedTagsService{client: c}
	c.ReleaseLinks = &ReleaseLinksService{client: c}
	c.Releases = &ReleasesService{client: c}
	c.Repositories = &RepositoriesService{client: c}
	c.RepositoryFiles = &RepositoryFilesService{client: c}
	c.Runners = &RunnersService{client: c}
	c.Search = &SearchService{client: c}
	c.Services = &ServicesService{client: c}
	c.Settings = &SettingsService{client: c}
	c.Sidekiq = &SidekiqService{client: c}
	c.Snippets = &SnippetsService{client: c}
	c.SystemHooks = &SystemHooksService{client: c}
	c.Tags = &TagsService{client: c}
	c.Todos = &TodosService{client: c}
	c.Users = &UsersService{client: c}
	c.Validate = &ValidateService{client: c}
	c.Version = &VersionService{client: c}
	c.Wikis = &WikisService{client: c}
	return c
}
func (c *Client) BaseURL() *url.URL {
	u := *c.baseURL
	return &u
}
func (c *Client) SetBaseURL(urlStr string) error {
	if !strings.HasSuffix(urlStr, "/") {
		urlStr += "/"
	}
	baseURL, err := url.Parse(urlStr)
	if err != nil {
		return err
	}
	if !strings.HasSuffix(baseURL.Path, apiVersionPath) {
		baseURL.Path += apiVersionPath
	}
	c.baseURL = baseURL
	return nil
}
func (c *Client) NewRequest(method, path string, opt interface{}, options []OptionFunc) (*http.Request, error) {
	u := *c.baseURL
	unescaped, err := url.PathUnescape(path)
	if err != nil {
		return nil, err
	}
	u.RawPath = c.baseURL.Path + path
	u.Path = c.baseURL.Path + unescaped
	if opt != nil {
		q, err := query.Values(opt)
		if err != nil {
			return nil, err
		}
		u.RawQuery = q.Encode()
	}
	req := &http.Request{
		Method:     method,
		URL:        &u,
		Proto:      "HTTP/1.1",
		ProtoMajor: 1,
		ProtoMinor: 1,
		Header:     make(http.Header),
		Host:       u.Host,
	}
	for _, fn := range options {
		if fn == nil {
			continue
		}
		if err := fn(req); err != nil {
			return nil, err
		}
	}
	if method == "POST" || method == "PUT" {
		bodyBytes, err := json.Marshal(opt)
		if err != nil {
			return nil, err
		}
		bodyReader := bytes.NewReader(bodyBytes)
		u.RawQuery = ""
		req.Body = ioutil.NopCloser(bodyReader)
		req.GetBody = func() (io.ReadCloser, error) {
			return ioutil.NopCloser(bodyReader), nil
		}
		req.ContentLength = int64(bodyReader.Len())
		req.Header.Set("Content-Type", "application/json")
	}
	req.Header.Set("Accept", "application/json")
	switch c.authType {
	case basicAuth, oAuthToken:
		req.Header.Set("Authorization", "Bearer "+c.token)
	case privateToken:
		req.Header.Set("PRIVATE-TOKEN", c.token)
	}
	if c.UserAgent != "" {
		req.Header.Set("User-Agent", c.UserAgent)
	}
	return req, nil
}
type Response struct {
	*http.Response
	TotalItems   int
	TotalPages   int
	ItemsPerPage int
	CurrentPage  int
	NextPage     int
	PreviousPage int
}
func newResponse(r *http.Response) *Response {
	response := &Response{Response: r}
	response.populatePageValues()
	return response
}
const (
	xTotal      = "X-Total"
	xTotalPages = "X-Total-Pages"
	xPerPage    = "X-Per-Page"
	xPage       = "X-Page"
	xNextPage   = "X-Next-Page"
	xPrevPage   = "X-Prev-Page"
)
func (r *Response) populatePageValues() {
	if totalItems := r.Response.Header.Get(xTotal); totalItems != "" {
		r.TotalItems, _ = strconv.Atoi(totalItems)
	}
	if totalPages := r.Response.Header.Get(xTotalPages); totalPages != "" {
		r.TotalPages, _ = strconv.Atoi(totalPages)
	}
	if itemsPerPage := r.Response.Header.Get(xPerPage); itemsPerPage != "" {
		r.ItemsPerPage, _ = strconv.Atoi(itemsPerPage)
	}
	if currentPage := r.Response.Header.Get(xPage); currentPage != "" {
		r.CurrentPage, _ = strconv.Atoi(currentPage)
	}
	if nextPage := r.Response.Header.Get(xNextPage); nextPage != "" {
		r.NextPage, _ = strconv.Atoi(nextPage)
	}
	if previousPage := r.Response.Header.Get(xPrevPage); previousPage != "" {
		r.PreviousPage, _ = strconv.Atoi(previousPage)
	}
}
func (c *Client) Do(req *http.Request, v interface{}) (*Response, error) {
	resp, err := c.client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	if resp.StatusCode == http.StatusUnauthorized && c.authType == basicAuth {
		err = c.requestOAuthToken(req.Context())
		if err != nil {
			return nil, err
		}
		return c.Do(req, v)
	}
	response := newResponse(resp)
	err = CheckResponse(resp)
	if err != nil {
		return response, err
	}
	if v != nil {
		if w, ok := v.(io.Writer); ok {
			_, err = io.Copy(w, resp.Body)
		} else {
			err = json.NewDecoder(resp.Body).Decode(v)
		}
	}
	return response, err
}
func parseID(id interface{}) (string, error) {
	switch v := id.(type) {
	case int:
		return strconv.Itoa(v), nil
	case string:
		return v, nil
	default:
		return "", fmt.Errorf("invalid ID type %#v, the ID must be an int or a string", id)
	}
}
func pathEscape(s string) string {
	return strings.Replace(url.PathEscape(s), ".", "%2E", -1)
}
type ErrorResponse struct {
	Body     []byte
	Response *http.Response
	Message  string
}
func (e *ErrorResponse) Error() string {
	path, _ := url.QueryUnescape(e.Response.Request.URL.Path)
	u := fmt.Sprintf("%s://%s%s", e.Response.Request.URL.Scheme, e.Response.Request.URL.Host, path)
	return fmt.Sprintf("%s %s: %d %s", e.Response.Request.Method, u, e.Response.StatusCode, e.Message)
}
func CheckResponse(r *http.Response) error {
	switch r.StatusCode {
	case 200, 201, 202, 204, 304:
		return nil
	}
	errorResponse := &ErrorResponse{Response: r}
	data, err := ioutil.ReadAll(r.Body)
	if err == nil && data != nil {
		errorResponse.Body = data
		var raw interface{}
		if err := json.Unmarshal(data, &raw); err != nil {
			errorResponse.Message = "failed to parse unknown error format"
		} else {
			errorResponse.Message = parseError(raw)
		}
	}
	return errorResponse
}
func parseError(raw interface{}) string {
	switch raw := raw.(type) {
	case string:
		return raw
	case []interface{}:
		var errs []string
		for _, v := range raw {
			errs = append(errs, parseError(v))
		}
		return fmt.Sprintf("[%s]", strings.Join(errs, ", "))
	case map[string]interface{}:
		var errs []string
		for k, v := range raw {
			errs = append(errs, fmt.Sprintf("{%s: %s}", k, parseError(v)))
		}
		sort.Strings(errs)
		return strings.Join(errs, ", ")
	default:
		return fmt.Sprintf("failed to parse unexpected error type: %T", raw)
	}
}
type OptionFunc func(*http.Request) error
func WithSudo(uid interface{}) OptionFunc {
	return func(req *http.Request) error {
		user, err := parseID(uid)
		if err != nil {
			return err
		}
		req.Header.Set("SUDO", user)
		return nil
	}
}
func WithContext(ctx context.Context) OptionFunc {
	return func(req *http.Request) error {
		*req = *req.WithContext(ctx)
		return nil
	}
}
func Bool(v bool) *bool {
	p := new(bool)
	*p = v
	return p
}
func Int(v int) *int {
	p := new(int)
	*p = v
	return p
}
func String(v string) *string {
	p := new(string)
	*p = v
	return p
}
func AccessLevel(v AccessLevelValue) *AccessLevelValue {
	p := new(AccessLevelValue)
	*p = v
	return p
}
func BuildState(v BuildStateValue) *BuildStateValue {
	p := new(BuildStateValue)
	*p = v
	return p
}
func NotificationLevel(v NotificationLevelValue) *NotificationLevelValue {
	p := new(NotificationLevelValue)
	*p = v
	return p
}
func Visibility(v VisibilityValue) *VisibilityValue {
	p := new(VisibilityValue)
	*p = v
	return p
}
func MergeMethod(v MergeMethodValue) *MergeMethodValue {
	p := new(MergeMethodValue)
	*p = v
	return p
}
type BoolValue bool