From 61b295fab27956205111dfa9b4300333d1071e12 Mon Sep 17 00:00:00 2001 From: ayesha arshad Date: Mon, 8 Apr 2024 15:48:40 +0200 Subject: [PATCH 01/16] added support for azure devops --- go.mod | 1 + pkg/adapter/adapter.go | 7 + pkg/params/info/events.go | 4 + pkg/provider/azuredevops/acl.go | 22 ++ pkg/provider/azuredevops/azuredevops.go | 396 ++++++++++++++++++++++ pkg/provider/azuredevops/detect.go | 43 +++ pkg/provider/azuredevops/parse_payload.go | 117 +++++++ pkg/provider/azuredevops/types/change.go | 16 + pkg/provider/azuredevops/types/types.go | 115 +++++++ 9 files changed, 721 insertions(+) create mode 100644 pkg/provider/azuredevops/acl.go create mode 100644 pkg/provider/azuredevops/azuredevops.go create mode 100644 pkg/provider/azuredevops/detect.go create mode 100644 pkg/provider/azuredevops/parse_payload.go create mode 100644 pkg/provider/azuredevops/types/change.go create mode 100644 pkg/provider/azuredevops/types/types.go diff --git a/go.mod b/go.mod index 88e488bcd..64c08b218 100644 --- a/go.mod +++ b/go.mod @@ -113,6 +113,7 @@ require ( github.com/kelseyhightower/envconfig v1.4.0 // indirect github.com/lunixbochs/vtclean v1.0.0 // indirect github.com/mailru/easyjson v0.7.7 // indirect + github.com/microsoft/azure-devops-go-api/azuredevops/v7 v7.1.0 github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect diff --git a/pkg/adapter/adapter.go b/pkg/adapter/adapter.go index 3efdba85f..554190847 100644 --- a/pkg/adapter/adapter.go +++ b/pkg/adapter/adapter.go @@ -17,6 +17,7 @@ import ( "github.com/openshift-pipelines/pipelines-as-code/pkg/params/info" "github.com/openshift-pipelines/pipelines-as-code/pkg/params/version" "github.com/openshift-pipelines/pipelines-as-code/pkg/provider" + "github.com/openshift-pipelines/pipelines-as-code/pkg/provider/azuredevops" "github.com/openshift-pipelines/pipelines-as-code/pkg/provider/bitbucketcloud" "github.com/openshift-pipelines/pipelines-as-code/pkg/provider/bitbucketserver" "github.com/openshift-pipelines/pipelines-as-code/pkg/provider/gitea" @@ -249,6 +250,12 @@ func (l listener) detectProvider(req *http.Request, reqBody string) (provider.In return l.processRes(processReq, bitCloud, logger, reason, err) } + ado := &azuredevops.Provider{} + isAdo, processReq, logger, reason, err := ado.Detect(req, reqBody, &log) + if isAdo { + return l.processRes(processReq, ado, logger, reason, err) + } + return l.processRes(false, nil, logger, "", fmt.Errorf("no supported Git provider has been detected")) } diff --git a/pkg/params/info/events.go b/pkg/params/info/events.go index ade45f046..85f3e274b 100644 --- a/pkg/params/info/events.go +++ b/pkg/params/info/events.go @@ -62,6 +62,10 @@ type Event struct { // Gitlab SourceProjectID int TargetProjectID int + + //AzureDevops + RepositoryId string + ProjectId string } type State struct { diff --git a/pkg/provider/azuredevops/acl.go b/pkg/provider/azuredevops/acl.go new file mode 100644 index 000000000..beb11db88 --- /dev/null +++ b/pkg/provider/azuredevops/acl.go @@ -0,0 +1,22 @@ +package azuredevops + +import ( + "context" + + "github.com/openshift-pipelines/pipelines-as-code/pkg/params/info" +) + +// CheckPolicyAllowing implements provider.Interface. +func (v *Provider) CheckPolicyAllowing(context.Context, *info.Event, []string) (bool, string) { + panic("unimplemented") +} + +// IsAllowed implements provider.Interface. +func (v *Provider) IsAllowed(context.Context, *info.Event) (bool, error) { + panic("unimplemented") +} + +// IsAllowedOwnersFile implements provider.Interface. +func (v *Provider) IsAllowedOwnersFile(context.Context, *info.Event) (bool, error) { + panic("unimplemented") +} diff --git a/pkg/provider/azuredevops/azuredevops.go b/pkg/provider/azuredevops/azuredevops.go new file mode 100644 index 000000000..b751bbf68 --- /dev/null +++ b/pkg/provider/azuredevops/azuredevops.go @@ -0,0 +1,396 @@ +package azuredevops + +import ( + "context" + "encoding/json" + "fmt" + "io" + "log" + "os" + "strings" + + "github.com/microsoft/azure-devops-go-api/azuredevops/v7" + "github.com/microsoft/azure-devops-go-api/azuredevops/v7/git" + "github.com/openshift-pipelines/pipelines-as-code/pkg/apis/pipelinesascode/v1alpha1" + "github.com/openshift-pipelines/pipelines-as-code/pkg/changedfiles" + "github.com/openshift-pipelines/pipelines-as-code/pkg/events" + "github.com/openshift-pipelines/pipelines-as-code/pkg/params" + "github.com/openshift-pipelines/pipelines-as-code/pkg/params/info" + "github.com/openshift-pipelines/pipelines-as-code/pkg/provider" + types "github.com/openshift-pipelines/pipelines-as-code/pkg/provider/azuredevops/types" + "go.uber.org/zap" +) + +const ( + taskStatusTemplate = ` + + + +{{- range $taskrun := .TaskRunList }} + + + +{{- end }} +
StatusDurationName
{{ formatCondition $taskrun.PipelineRunTaskRunStatus.Status.Conditions }}{{ formatDuration $taskrun.PipelineRunTaskRunStatus.Status.StartTime $taskrun.Status.CompletionTime }} + +{{ $taskrun.ConsoleLogURL }} + +
` +) + +var _ provider.Interface = (*Provider)(nil) + +type Provider struct { + Client git.Client + ctx context.Context + Logger *zap.SugaredLogger + Token *string + run *params.Run +} + +// CreateStatus implements provider.Interface. +func (v *Provider) CreateStatus(ctx context.Context, event *info.Event, statusOpts provider.StatusOpts) error { + if v.Client == nil { + return fmt.Errorf("cannot set status on azuredevops no token or url set") + } + + logger := log.New(os.Stdout, "INFO: ", log.Ldate|log.Ltime|log.Lshortfile) + + var gitStatusState git.GitStatusState + + logger.Println("statusOpts.Conclusion ", statusOpts.Conclusion) + logger.Println("statusOpts.Status ", statusOpts.Status) + + switch statusOpts.Conclusion { + case "succeeded": + statusOpts.Title = "Success" + statusOpts.Summary = "has successfully validated your commit." + gitStatusState = git.GitStatusStateValues.Succeeded + case "failed": + statusOpts.Title = "failure" + statusOpts.Summary = "has failed." + gitStatusState = git.GitStatusStateValues.Failed + case "pending": + statusOpts.Title = "Pending" + statusOpts.Summary = "is waiting to start." + gitStatusState = git.GitStatusStateValues.Pending + case "error": + statusOpts.Title = "Error" + statusOpts.Summary = "encountered an error during processing." + gitStatusState = git.GitStatusStateValues.Error + case "notApplicable": + statusOpts.Title = "Not Applicable" + statusOpts.Summary = "is not applicable for this commit." + gitStatusState = git.GitStatusStateValues.NotApplicable + default: + statusOpts.Title = "Unknown" + statusOpts.Summary = "doesn't know what happened with this commit." + gitStatusState = git.GitStatusStateValues.NotSet + } + + if statusOpts.Status == "in_progress" { + gitStatusState = git.GitStatusStateValues.Pending + } + + onPr := "" + if statusOpts.PipelineRunName != "" { + onPr = fmt.Sprintf("/%s", statusOpts.PipelineRunName) + } + statusOpts.Summary = fmt.Sprintf("%s%s %s", v.run.Info.Pac.ApplicationName, onPr, statusOpts.Summary) + + logger.Println("statusOpts.Summary ", statusOpts.Summary) + + // Preparing the GitStatus object with the updated status + gitStatus := git.GitStatus{ + State: &gitStatusState, + TargetUrl: &event.HeadURL, + Description: &statusOpts.Summary, + Context: &git.GitStatusContext{ + Name: &statusOpts.Title, + }, + } + // Posting the status to Azure DevOps + if _, err := v.Client.CreateCommitStatus(ctx, git.CreateCommitStatusArgs{ + Project: &event.Organization, + RepositoryId: &event.Repository, + CommitId: &event.SHA, + GitCommitStatusToCreate: &gitStatus, + }); err != nil { + return fmt.Errorf("failed to create commit status: %v", err) + } + return nil +} + +// CreateToken implements provider.Interface. +func (v *Provider) CreateToken(context.Context, []string, *info.Event) (string, error) { + panic("unimplemented") +} + +func (v *Provider) GetCommitInfo(ctx context.Context, event *info.Event) error { + if v.Client == nil { + return fmt.Errorf("no Azure DevOps client has been initialized, " + + "exiting... (hint: did you forget setting a secret on your repo?)") + } + + repository := event.Repository + projectId := event.ProjectId + sha := event.SHA + + // If SHA is not provided, try to fetch it from the branch or pull request + if sha == "" { + if event.HeadBranch != "" { + + refName := fmt.Sprintf("refs/heads/%s", event.HeadBranch) + refs, err := v.Client.GetRefs(ctx, git.GetRefsArgs{ + RepositoryId: &repository, + Filter: &refName, + Project: &projectId, + }) + if err != nil { + return fmt.Errorf("failed to get branch info: %v", err) + } + // Assuming refs is a pointer to a slice, we check its length like this: + if len(refs.Value) > 0 { + sha = *refs.Value[0].ObjectId + } + } else if event.PullRequestNumber != 0 { + pr, err := v.Client.GetPullRequest(ctx, git.GetPullRequestArgs{ + RepositoryId: &repository, + PullRequestId: &event.PullRequestNumber, + Project: &projectId, + }) + if err != nil { + return fmt.Errorf("failed to get pull request: %v", err) + } + sha = *pr.LastMergeSourceCommit.CommitId + event.HeadBranch = *pr.SourceRefName + event.BaseBranch = *pr.TargetRefName + } + } + if sha != "" { + commit, err := v.Client.GetCommit(ctx, git.GetCommitArgs{ + CommitId: &sha, + RepositoryId: &repository, + Project: &projectId, + }) + if err != nil { + return fmt.Errorf("failed to get commit: %v", err) + } + event.SHAURL = *commit.RemoteUrl + event.SHATitle = strings.Split(*commit.Comment, "\n\n")[0] + event.SHA = *commit.CommitId + + } else { + return fmt.Errorf("unable to determine commit SHA") + } + + return nil +} + +func (v *Provider) GetConfig() *info.ProviderConfig { + return &info.ProviderConfig{ + TaskStatusTMPL: taskStatusTemplate, + Name: "azuredevops", + } +} + +// GetFileInsideRepo implements provider.Interface. +func (v *Provider) GetFileInsideRepo(ctx context.Context, runevent *info.Event, path, target string) (string, error) { + panic("unimplemented") +} + +// GetFiles implements provider.Interface. +func (v *Provider) GetFiles(ctx context.Context, event *info.Event) (changedfiles.ChangedFiles, error) { + + filesChanged, err := v.Client.GetChanges(ctx, git.GetChangesArgs{ + RepositoryId: &event.RepositoryId, + CommitId: &event.SHA, + }) + + if err != nil { + v.Logger.Errorf("Failed to get changes for commit %s: %v", &event.SHA, err) + } + + changesJson, err := json.Marshal(filesChanged.Changes) + if err != nil { + v.Logger.Errorf("Failed to marshal changes: %v", err) + return changedfiles.ChangedFiles{}, err + } + + var changes []types.Change + if err := json.Unmarshal(changesJson, &changes); err != nil { + log.Fatalf("JSON Unmarshal error: %v", err) + } + + changedFiles := &changedfiles.ChangedFiles{} + + for _, c := range changes { + + switch c.ChangeType { + case "edit": + changedFiles.All = append(changedFiles.Added, c.Item.Path) + changedFiles.Modified = append(changedFiles.Added, c.Item.Path) + case "add": + changedFiles.All = append(changedFiles.Added, c.Item.Path) + changedFiles.Added = append(changedFiles.Added, c.Item.Path) + case "delete": + changedFiles.All = append(changedFiles.Added, c.Item.Path) + changedFiles.Deleted = append(changedFiles.Added, c.Item.Path) + case "rename": + changedFiles.All = append(changedFiles.Added, c.Item.Path) + changedFiles.Renamed = append(changedFiles.Added, c.Item.Path) + } + } + + return *changedFiles, nil +} + +// GetTaskURI TODO: Implement ME. +func (v *Provider) GetTaskURI(ctx context.Context, event *info.Event, uri string) (bool, string, error) { + return false, "", nil +} + +// GetTektonDir implements provider.Interface. +func (v *Provider) GetTektonDir(ctx context.Context, runevent *info.Event, path, provenance string) (string, error) { + + repositoryID := runevent.RepositoryId + ProjectId := runevent.ProjectId + var version string + + if provenance == "default_branch" { + version = runevent.DefaultBranch + v.Logger.Infof("Using Tekton definition from default branch: %s", version) + } else { + version = runevent.SHA + v.Logger.Infof("Using Tekton definition from commit ID: %s", version) + } + // Check if the path exists and is a directory + item, err := v.Client.GetItem(ctx, git.GetItemArgs{ + RepositoryId: &repositoryID, + Project: &ProjectId, + Path: &path, + }) + + if err != nil { + return "", fmt.Errorf("failed to fetch the item: %v", err) + } + + if item == nil { + return "", fmt.Errorf("no item found under the specified path '%s' in the repository at the given branch or commit '%s'", path, version) + } + + // Get the SHA of the directory and fetch the tree + tree, err := v.Client.GetTree(ctx, git.GetTreeArgs{ + RepositoryId: &repositoryID, + Project: &ProjectId, + Sha1: item.ObjectId, + Recursive: toBoolPtr(true), + }) + + if err != nil { + return "", fmt.Errorf("failed to fetch the tree: %v", err) + } + + // Concatenate all YAML files found within the tree entries + result, err := v.concatAllYamlFiles(ctx, tree.TreeEntries, repositoryID, ProjectId) + if err != nil { + return "", err + } + return result, nil + +} + +func toBoolPtr(b bool) *bool { + return &b +} + +func (v *Provider) concatAllYamlFiles(ctx context.Context, entries *[]git.GitTreeEntryRef, repositoryID string, projectId string) (string, error) { + var allTemplates string + + for _, entry := range *entries { + if *entry.GitObjectType == git.GitObjectTypeValues.Blob && (strings.HasSuffix(*entry.RelativePath, ".yaml") || strings.HasSuffix(*entry.RelativePath, ".yml")) { + + // Use the object ID (SHA) of the blob to fetch its content + data, err := v.getObject(ctx, repositoryID, projectId, *entry.ObjectId) + + if err != nil { + return "", err + } + // TODO: Validate YAML; + // var i any + // if err := yaml.Unmarshal(data, &i); err != nil { + // return "", fmt.Errorf("error unmarshalling YAML file %s: %w", *entry.RelativePath, err) + // } + // Ensure each YAML document is separated by '---' + if allTemplates != "" && !strings.HasPrefix(string(data), "---") { + allTemplates += "\n---\n" + } + allTemplates += string(data) + "\n" + } + } + return allTemplates, nil +} + +// getObject fetches the content of a file from an Azure DevOps repository. +func (v *Provider) getObject(ctx context.Context, repositoryID string, projectId string, sha string) ([]byte, error) { + reader, err := v.Client.GetBlobContent(ctx, git.GetBlobContentArgs{ + RepositoryId: &repositoryID, + Project: &projectId, + Sha1: &sha, + }) + if err != nil { + return nil, err + } + defer reader.Close() + + // Read the content from the reader returned by GetBlobContent + content, err := io.ReadAll(reader) + if err != nil { + return nil, err + } + + return content, nil +} + +// SetClient implements provider.Interface. +func (v *Provider) SetClient(_ context.Context, run *params.Run, event *info.Event, _ *v1alpha1.Repository, _ *events.EventEmitter) error { + var err error + + if event.Provider.Token == "" { + return fmt.Errorf("no git_provider.secret has been set in the repo crd") + } + + // if event.Provider.URL == "" { + // return fmt.Errorf("no provider.url has been set in the repo crd") + // } + + //TODO get organizationUrl from provider.url + organizationUrl := "https://dev.azure.com/ayeshaarshad" + + // Create a connection to your organization + connection := azuredevops.NewPatConnection(organizationUrl, event.Provider.Token) + + ctx := context.Background() + + v.Client, err = git.NewClient(ctx, connection) + + if err != nil { + return err + } + + v.Token = &event.Provider.Token + v.run = run + v.ctx = ctx + + return nil +} + +// SetLogger implements provider.Interface. +func (v *Provider) SetLogger(logger *zap.SugaredLogger) { + v.Logger = logger +} + +// Validate implements provider.Interface. +func (v *Provider) Validate(ctx context.Context, params *params.Run, event *info.Event) error { + return nil +} diff --git a/pkg/provider/azuredevops/detect.go b/pkg/provider/azuredevops/detect.go new file mode 100644 index 000000000..a2fd2cf82 --- /dev/null +++ b/pkg/provider/azuredevops/detect.go @@ -0,0 +1,43 @@ +package azuredevops + +import ( + "encoding/json" + "fmt" + "net/http" + + "github.com/microsoft/azure-devops-go-api/azuredevops/v7/servicehooks" + "go.uber.org/zap" +) + +func (v *Provider) Detect(req *http.Request, payload string, logger *zap.SugaredLogger) (bool, bool, *zap.SugaredLogger, string, error) { + isADO := false + eventType := req.Header.Get("X-Azure-DevOps-EventType") + if eventType == "" { + return false, false, logger, "no azure devops event", nil + } + + // it is an Azure DevOps event + isADO = true + + setLoggerAndProceed := func(processEvent bool, reason string, err error) (bool, bool, *zap.SugaredLogger, + string, error, + ) { + logger = logger.With("provider", "azure-devops", "event-id", req.Header.Get("X-Request-Id")) + return isADO, processEvent, logger, reason, err + } + + var event servicehooks.Event + err := json.Unmarshal([]byte(payload), &event) + if err != nil { + return isADO, false, logger, "", err + } + logger = logger.With("provider", "azuredevops", "event-type", event.EventType) + + // Simplified switch, expand as needed based on the Azure DevOps events you handle + switch eventType { + case "git.push", "git.pullrequest.created": + return setLoggerAndProceed(true, "", nil) + default: + return setLoggerAndProceed(false, fmt.Sprintf("Unsupported event type: %s", eventType), nil) + } +} diff --git a/pkg/provider/azuredevops/parse_payload.go b/pkg/provider/azuredevops/parse_payload.go new file mode 100644 index 000000000..9681799e9 --- /dev/null +++ b/pkg/provider/azuredevops/parse_payload.go @@ -0,0 +1,117 @@ +package azuredevops + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "strings" + + "github.com/microsoft/azure-devops-go-api/azuredevops/v7/servicehooks" + "github.com/openshift-pipelines/pipelines-as-code/pkg/params" + "github.com/openshift-pipelines/pipelines-as-code/pkg/params/info" + "github.com/openshift-pipelines/pipelines-as-code/pkg/params/triggertype" + types "github.com/openshift-pipelines/pipelines-as-code/pkg/provider/azuredevops/types" +) + +func (v *Provider) ParsePayload(_ context.Context, _ *params.Run, request *http.Request, + payload string, +) (*info.Event, error) { + + var genericEvent servicehooks.Event + err := json.Unmarshal([]byte(payload), &genericEvent) + if err != nil { + return nil, fmt.Errorf("error unmarshalling payload into Event: %v", err) + } + + if genericEvent.EventType == nil { + return nil, fmt.Errorf("event type is nil") + } + + processedEvent := info.NewEvent() + processedEvent.EventType = *genericEvent.EventType + + resourceBytes, err := json.Marshal(genericEvent.Resource) + if err != nil { + return nil, fmt.Errorf("error marshalling resource: %v", err) + } + + switch *genericEvent.EventType { + case "git.push": + + var pushEvent types.PushEventResource + if err := json.Unmarshal(resourceBytes, &pushEvent); err != nil { + return nil, fmt.Errorf("error unmarshalling push event resource: %v", err) + } + if len(pushEvent.Commits) > 0 { + processedEvent.SHA = pushEvent.Commits[0].CommitId + processedEvent.SHAURL = pushEvent.Commits[0].Url + processedEvent.SHATitle = pushEvent.Commits[0].Comment + } + + processedEvent.EventType = *genericEvent.EventType + processedEvent.Sender = pushEvent.PushedBy.DisplayName + processedEvent.Repository = pushEvent.Repository.Name + processedEvent.RepositoryId = pushEvent.Repository.Id + processedEvent.ProjectId = pushEvent.Repository.Project.Id + processedEvent.Organization = pushEvent.Repository.Project.Name + processedEvent.URL = pushEvent.Repository.RemoteUrl + processedEvent.DefaultBranch = pushEvent.Repository.DefaultBranch + processedEvent.TriggerTarget = triggertype.Push + // Assuming the repository URL can serve as both BaseURL and HeadURL for viewing purposes + processedEvent.BaseURL = pushEvent.Repository.Url // or it could be remoteUrl or it could be other; need to verify + processedEvent.HeadURL = pushEvent.Repository.Url // or it could be remoteUrl or it could be othe; need to verify + if len(pushEvent.RefUpdates) > 0 { + branchName := pushEvent.RefUpdates[0].Name + processedEvent.BaseBranch = branchName + processedEvent.HeadBranch = branchName + } + + case "git.pullrequest.created": + var prEvent types.PullRequestEventResource + if err := json.Unmarshal(resourceBytes, &prEvent); err != nil { + return nil, fmt.Errorf("error unmarshalling pull request event resource: %v", err) + } + + processedEvent.EventType = *genericEvent.EventType + processedEvent.PullRequestNumber = prEvent.PullRequestId + processedEvent.PullRequestTitle = prEvent.Title + processedEvent.SHA = prEvent.LastMergeSourceCommit.CommitId + processedEvent.SHAURL = prEvent.LastMergeSourceCommit.Url + processedEvent.SHATitle = prEvent.LastMergeSourceCommit.Comment + + // Extract branch names from the ref names + // Azure DevOps ref names are full references (refs/heads/branchName), so we'll extract the branch name + processedEvent.BaseBranch = prEvent.TargetRefName + processedEvent.HeadBranch = prEvent.SourceRefName + processedEvent.DefaultBranch = prEvent.Repository.DefaultBranch + + // Constructing URLs + remoteUrl := prEvent.Repository.RemoteUrl + baseBranch := ExtractBranchName(prEvent.TargetRefName) + headBranch := ExtractBranchName(prEvent.SourceRefName) + processedEvent.BaseURL = fmt.Sprintf("%s?version=GB%s", remoteUrl, baseBranch) + processedEvent.HeadURL = fmt.Sprintf("%s?version=GB%s", remoteUrl, headBranch) + + processedEvent.TriggerTarget = triggertype.PullRequest + processedEvent.Repository = prEvent.Repository.Name + processedEvent.RepositoryId = prEvent.Repository.Id + processedEvent.ProjectId = prEvent.Repository.Project.Id + processedEvent.URL = prEvent.Repository.RemoteUrl + processedEvent.Sender = prEvent.CreatedBy.DisplayName + default: + return nil, fmt.Errorf("event type %s is not supported", *genericEvent.EventType) + } + + return processedEvent, nil +} + +// ExtractBranchName extracts the branch name from a full ref name. +// E.g., "refs/heads/master" -> "master" +func ExtractBranchName(refName string) string { + parts := strings.Split(refName, "/") + if len(parts) > 2 { + return parts[len(parts)-1] // Get the last part which should be the branch name + } + return refName // Return as-is if the format is unexpected +} diff --git a/pkg/provider/azuredevops/types/change.go b/pkg/provider/azuredevops/types/change.go new file mode 100644 index 000000000..73dcccd15 --- /dev/null +++ b/pkg/provider/azuredevops/types/change.go @@ -0,0 +1,16 @@ +package azuredevops + +type Item struct { + CommitId string `json:"commitId"` + GitObjectType string `json:"gitObjectType"` + IsFolder bool `json:"isFolder"` + ObjectId string `json:"objectId"` + OriginalObjectId string `json:"originalObjectId"` + Path string `json:"path"` + URL string `json:"url"` +} + +type Change struct { + ChangeType string `json:"changeType"` + Item Item `json:"item"` +} diff --git a/pkg/provider/azuredevops/types/types.go b/pkg/provider/azuredevops/types/types.go new file mode 100644 index 000000000..800873a44 --- /dev/null +++ b/pkg/provider/azuredevops/types/types.go @@ -0,0 +1,115 @@ +package azuredevops + +import ( + "time" +) + +type PullRequestEventResource struct { + Repository Repository `json:"repository"` + PullRequestId int `json:"pullRequestId"` + Status string `json:"status"` + CreatedBy User `json:"createdBy"` + CreationDate CustomTime `json:"creationDate"` + Title string `json:"title"` + Description string `json:"description"` + SourceRefName string `json:"sourceRefName"` + TargetRefName string `json:"targetRefName"` + MergeStatus string `json:"mergeStatus"` + MergeId string `json:"mergeId"` + LastMergeSourceCommit Commit `json:"lastMergeSourceCommit"` + LastMergeTargetCommit Commit `json:"lastMergeTargetCommit"` + LastMergeCommit Commit `json:"lastMergeCommit"` + Reviewers []User `json:"reviewers"` + Url string `json:"url"` + Links Links `json:"_links"` +} + +type PushEventResource struct { + Commits []Commit `json:"commits"` + RefUpdates []RefUpdate `json:"refUpdates"` + Repository Repository `json:"repository"` + PushedBy User `json:"pushedBy"` + PushId int `json:"pushId"` + Date CustomTime `json:"date"` + Url string `json:"url"` +} + +type Commit struct { + CommitId string `json:"commitId"` + Author User `json:"author"` + Committer User `json:"committer"` + Comment string `json:"comment"` + Url string `json:"url"` +} + +type RefUpdate struct { + Name string `json:"name"` + OldObjectId string `json:"oldObjectId"` + NewObjectId string `json:"newObjectId"` +} + +type Repository struct { + Id string `json:"id"` + Name string `json:"name"` + Url string `json:"url"` + Project Project `json:"project"` + DefaultBranch string `json:"defaultBranch"` + RemoteUrl string `json:"remoteUrl"` +} + +type Project struct { + Id string `json:"id"` + Name string `json:"name"` + Url string `json:"url"` + State string `json:"state"` + Visibility string `json:"visibility"` + LastUpdateTime CustomTime `json:"lastUpdateTime"` +} + +type User struct { + Name string `json:"name"` + Email string `json:"email"` + Date CustomTime `json:"date"` + DisplayName string `json:"displayName,omitempty"` // Optional fields use "omitempty" + Id string `json:"id,omitempty"` + UniqueName string `json:"uniqueName,omitempty"` + ImageUrl string `json:"imageUrl,omitempty"` // Added to represent user's image URL +} + +type ResourceContainers struct { + Collection Container `json:"collection"` + Account Container `json:"account"` + Project Container `json:"project"` +} + +type Container struct { + Id string `json:"id"` +} + +type Links struct { + Web Href `json:"web"` + Statuses Href `json:"statuses"` +} + +type Href struct { + Href string `json:"href"` +} + +type CustomTime struct { + time.Time +} + +func (ct *CustomTime) UnmarshalJSON(b []byte) error { + s := string(b) + s = s[1 : len(s)-1] // Remove quotes + if s == "0001-01-01T00:00:00" || s == "" { + ct.Time = time.Time{} + return nil + } + t, err := time.Parse(time.RFC3339, s) + if err != nil { + return err + } + ct.Time = t + return nil +} From 7bbcd50cdcb79230035267f10b8a07195da10b56 Mon Sep 17 00:00:00 2001 From: ayesha arshad Date: Mon, 8 Apr 2024 15:54:39 +0200 Subject: [PATCH 02/16] updated vendor/modules.txt --- vendor/modules.txt | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/vendor/modules.txt b/vendor/modules.txt index 4fe83fe82..fbee9cd3c 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -283,6 +283,14 @@ github.com/mattn/go-isatty # github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d ## explicit github.com/mgutz/ansi +# github.com/microsoft/azure-devops-go-api/azuredevops v1.0.0-b5 +## explicit; go 1.12 +# github.com/microsoft/azure-devops-go-api/azuredevops/v7 v7.1.0 +## explicit; go 1.12 +github.com/microsoft/azure-devops-go-api/azuredevops/v7 +github.com/microsoft/azure-devops-go-api/azuredevops/v7/core +github.com/microsoft/azure-devops-go-api/azuredevops/v7/git +github.com/microsoft/azure-devops-go-api/azuredevops/v7/servicehooks # github.com/mitchellh/mapstructure v1.5.0 ## explicit; go 1.14 github.com/mitchellh/mapstructure From 3fb47c01366e9c1704ba56dd12b00d556de668df Mon Sep 17 00:00:00 2001 From: ayesha arshad Date: Mon, 8 Apr 2024 16:14:51 +0200 Subject: [PATCH 03/16] added vendor --- .../azuredevops/v7/LICENSE | 21 + .../azuredevops/v7/client.go | 450 ++ .../azuredevops/v7/client_options.go | 15 + .../azuredevops/v7/connection.go | 157 + .../azuredevops/v7/core/client.go | 917 +++ .../azuredevops/v7/core/models.go | 490 ++ .../v7/delegatedauthorization/models.go | 368 ++ .../azuredevops/v7/errors.go | 17 + .../azuredevops/v7/forminput/models.go | 194 + .../azuredevops/v7/git/client.go | 5852 +++++++++++++++++ .../azuredevops/v7/git/models.go | 3392 ++++++++++ .../azuredevops/v7/identity/client.go | 1097 +++ .../azuredevops/v7/identity/models.go | 253 + .../azuredevops/v7/models.go | 149 + .../azuredevops/v7/notification/client.go | 549 ++ .../azuredevops/v7/notification/models.go | 1353 ++++ .../azuredevops/v7/operations/client.go | 64 + .../azuredevops/v7/operations/models.go | 77 + .../azuredevops/v7/policy/client.go | 484 ++ .../azuredevops/v7/policy/models.go | 136 + .../azuredevops/v7/servicehooks/client.go | 720 ++ .../azuredevops/v7/servicehooks/models.go | 468 ++ .../azuredevops/v7/system/models.go | 97 + .../azuredevops/v7/version.go | 58 + .../azuredevops/v7/versionnegotiation.go | 72 + .../azuredevops/v7/webapi/models.go | 339 + vendor/modules.txt | 10 +- 27 files changed, 17797 insertions(+), 2 deletions(-) create mode 100644 vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/LICENSE create mode 100644 vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/client.go create mode 100644 vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/client_options.go create mode 100644 vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/connection.go create mode 100644 vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/core/client.go create mode 100644 vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/core/models.go create mode 100644 vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/delegatedauthorization/models.go create mode 100644 vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/errors.go create mode 100644 vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/forminput/models.go create mode 100644 vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/git/client.go create mode 100644 vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/git/models.go create mode 100644 vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/identity/client.go create mode 100644 vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/identity/models.go create mode 100644 vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/models.go create mode 100644 vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/notification/client.go create mode 100644 vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/notification/models.go create mode 100644 vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/operations/client.go create mode 100644 vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/operations/models.go create mode 100644 vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/policy/client.go create mode 100644 vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/policy/models.go create mode 100644 vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/servicehooks/client.go create mode 100644 vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/servicehooks/models.go create mode 100644 vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/system/models.go create mode 100644 vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/version.go create mode 100644 vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/versionnegotiation.go create mode 100644 vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/webapi/models.go diff --git a/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/LICENSE b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/LICENSE new file mode 100644 index 000000000..4b1ad51b2 --- /dev/null +++ b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/client.go b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/client.go new file mode 100644 index 000000000..e0d0d4ce8 --- /dev/null +++ b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/client.go @@ -0,0 +1,450 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azuredevops + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "io/ioutil" + "net/http" + "net/url" + "reflect" + "regexp" + "runtime" + "strings" + "sync" + + "github.com/google/uuid" +) + +const ( + // header keys + headerKeyAccept = "Accept" + headerKeyAuthorization = "Authorization" + headerKeyContentType = "Content-Type" + HeaderKeyContinuationToken = "X-MS-ContinuationToken" + headerKeyFedAuthRedirect = "X-TFS-FedAuthRedirect" + headerKeyForceMsaPassThrough = "X-VSS-ForceMsaPassThrough" + headerKeySession = "X-TFS-Session" + headerUserAgent = "User-Agent" + + // media types + MediaTypeTextPlain = "text/plain" + MediaTypeApplicationJson = "application/json" +) + +// Unique session id to be used by all requests of this session. +var SessionId = uuid.New().String() + +// ApiResourceLocation Cache by Url +var apiResourceLocationCache = make(map[string]*map[uuid.UUID]ApiResourceLocation) +var apiResourceLocationCacheLock = sync.RWMutex{} + +var version = "7.1.220.1" // todo: remove hardcoded version +var versionSuffix = " (dev)" + +// Base user agent string. The UserAgent set on the connection will be appended to this. +var baseUserAgent = "go/" + runtime.Version() + " (" + runtime.GOOS + " " + runtime.GOARCH + ") azure-devops-go-api/" + version + versionSuffix + +// NewClient provides an Azure DevOps client +// and copies the TLS config and timeout from the supplied connection +func NewClient(connection *Connection, baseUrl string) *Client { + httpClient := &http.Client{} + if connection.TlsConfig != nil { + httpClient.Transport = &http.Transport{TLSClientConfig: connection.TlsConfig} + } + if connection.Timeout != nil { + httpClient.Timeout = *connection.Timeout + } + + return NewClientWithOptions(connection, baseUrl, WithHTTPClient(httpClient)) +} + +// NewClientWithOptions returns an Azure DevOps client modified by the options +func NewClientWithOptions(connection *Connection, baseUrl string, options ...ClientOptionFunc) *Client { + httpClient := &http.Client{} + client := &Client{ + baseUrl: baseUrl, + client: httpClient, + authorization: connection.AuthorizationString, + suppressFedAuthRedirect: connection.SuppressFedAuthRedirect, + forceMsaPassThrough: connection.ForceMsaPassThrough, + userAgent: connection.UserAgent, + } + for _, fn := range options { + fn(client) + } + return client +} + +type Client struct { + baseUrl string + client *http.Client + authorization string + suppressFedAuthRedirect bool + forceMsaPassThrough bool + userAgent string +} + +func (client *Client) SendRequest(request *http.Request) (response *http.Response, err error) { + resp, err := client.client.Do(request) // todo: add retry logic + if resp != nil && (resp.StatusCode < 200 || resp.StatusCode >= 300) { + err = client.UnwrapError(resp) + } + return resp, err +} + +func (client *Client) Send(ctx context.Context, + httpMethod string, + locationId uuid.UUID, + apiVersion string, + routeValues map[string]string, + queryParameters url.Values, + body io.Reader, + mediaType string, + acceptMediaType string, + additionalHeaders map[string]string) (response *http.Response, err error) { + location, err := client.getResourceLocation(ctx, locationId) + if err != nil { + return nil, err + } + generatedUrl := client.GenerateUrl(location, routeValues, queryParameters) + fullUrl := combineUrl(client.baseUrl, generatedUrl) + negotiatedVersion, err := negotiateRequestVersion(location, apiVersion) + if err != nil { + return nil, err + } + + req, err := client.CreateRequestMessage(ctx, httpMethod, fullUrl, negotiatedVersion, body, mediaType, acceptMediaType, additionalHeaders) + if err != nil { + return nil, err + } + + resp, err := client.SendRequest(req) + if err != nil { + return nil, err + } + + // Set session if one was supplied in the response. + session, ok := resp.Header[headerKeySession] + if ok && len(session) > 0 { + SessionId = session[0] + } + + return resp, err +} + +func (client *Client) GenerateUrl(apiResourceLocation *ApiResourceLocation, routeValues map[string]string, queryParameters url.Values) (request string) { + builtUrl := *apiResourceLocation.RouteTemplate + if routeValues == nil { + routeValues = make(map[string]string) + } + routeValues["area"] = *apiResourceLocation.Area + routeValues["resource"] = *apiResourceLocation.ResourceName + builtUrl = transformRouteTemplate(builtUrl, routeValues) + if queryParameters != nil && len(queryParameters) > 0 { + builtUrl += "?" + queryParameters.Encode() + } + return builtUrl +} + +func (client *Client) CreateRequestMessage(ctx context.Context, + httpMethod string, + url string, + apiVersion string, + body io.Reader, + mediaType string, + acceptMediaType string, + additionalHeaders map[string]string) (request *http.Request, err error) { + req, err := http.NewRequest(httpMethod, url, body) + if err != nil { + return nil, err + } + + if ctx != nil { + req = req.WithContext(ctx) + } + + if client.authorization != "" { + req.Header.Add(headerKeyAuthorization, client.authorization) + } + accept := acceptMediaType + if apiVersion != "" { + accept += ";api-version=" + apiVersion + } + req.Header.Add(headerKeyAccept, accept) + if mediaType != "" { + req.Header.Add(headerKeyContentType, mediaType+";charset=utf-8") + } + if client.suppressFedAuthRedirect { + req.Header.Add(headerKeyFedAuthRedirect, "Suppress") + } + if client.forceMsaPassThrough { + req.Header.Add(headerKeyForceMsaPassThrough, "true") + } + + // set session if it has not already been set + _, ok := req.Header[headerKeySession] + if !ok { + req.Header.Add(headerKeySession, SessionId) + } + + userAgent := baseUserAgent + if client.userAgent != "" { + userAgent += " " + client.userAgent + } + req.Header.Add(headerUserAgent, userAgent) + + for key, value := range additionalHeaders { + req.Header.Add(key, value) + } + + return req, err +} + +func (client *Client) getResourceLocation(ctx context.Context, locationId uuid.UUID) (*ApiResourceLocation, error) { + locationsMap, ok := getApiResourceLocationCache(client.baseUrl) + if !ok { + locations, err := client.getResourceLocationsFromServer(ctx) + if err != nil { + return nil, err + } + newMap := make(map[uuid.UUID]ApiResourceLocation) + locationsMap = &newMap + for _, locationEntry := range locations { + (*locationsMap)[*locationEntry.Id] = locationEntry + } + + setApiResourceLocationCache(client.baseUrl, locationsMap) + } + + location, ok := (*locationsMap)[locationId] + if ok { + return &location, nil + } + + return nil, &LocationIdNotRegisteredError{locationId, client.baseUrl} +} + +func getApiResourceLocationCache(url string) (*map[uuid.UUID]ApiResourceLocation, bool) { + apiResourceLocationCacheLock.RLock() + defer apiResourceLocationCacheLock.RUnlock() + locationsMap, ok := apiResourceLocationCache[url] + return locationsMap, ok +} + +func setApiResourceLocationCache(url string, locationsMap *map[uuid.UUID]ApiResourceLocation) { + apiResourceLocationCacheLock.Lock() + defer apiResourceLocationCacheLock.Unlock() + apiResourceLocationCache[url] = locationsMap +} + +func (client *Client) getResourceLocationsFromServer(ctx context.Context) ([]ApiResourceLocation, error) { + optionsUri := combineUrl(client.baseUrl, "_apis") + request, err := client.CreateRequestMessage(ctx, http.MethodOptions, optionsUri, "", nil, "", MediaTypeApplicationJson, nil) + if err != nil { + return nil, err + } + + resp, err := client.SendRequest(request) + if err != nil { + return nil, err + } + + // Set session if one was supplied in the response. + session, ok := resp.Header[headerKeySession] + if ok && len(session) > 0 { + SessionId = session[0] + } + + if resp != nil && (resp.StatusCode < 200 || resp.StatusCode >= 300) { + return nil, client.UnwrapError(resp) + } + + var locations []ApiResourceLocation + err = client.UnmarshalCollectionBody(resp, &locations) + + return locations, err +} + +// Examples of api-version: 5.1, 5.1-preview, 5.1-preview.1 +var apiVersionRegEx = regexp.MustCompile(`(\d+(\.\d)?)(-preview(.(\d+))?)?`) + +func combineUrl(part1 string, part2 string) string { + return strings.TrimRight(part1, "/") + "/" + strings.TrimLeft(part2, "/") +} + +func transformRouteTemplate(routeTemplate string, routeValues map[string]string) string { + newTemplate := "" + routeTemplate = strings.Replace(routeTemplate, "{*", "{", -1) + segments := strings.Split(routeTemplate, "/") + for _, segment := range segments { + length := len(segment) + if length <= 2 || segment[0] != '{' || segment[length-1] != '}' { + newTemplate += "/" + segment + } else { + value, ok := routeValues[segment[1:length-1]] + if ok { + newTemplate += "/" + url.PathEscape(value) + } + // else this is an optional parameter that has not been supplied, so don't add it back + } + } + // following covers oddball templates with segments that include the token and additional constants + for key, value := range routeValues { + newTemplate = strings.Replace(newTemplate, "{"+key+"}", value, -1) + } + return newTemplate +} + +func (client *Client) UnmarshalBody(response *http.Response, v interface{}) (err error) { + if response != nil && response.Body != nil { + var err error + defer func() { + if closeError := response.Body.Close(); closeError != nil { + err = closeError + } + }() + body, err := ioutil.ReadAll(response.Body) + if err != nil { + return err + } + body = trimByteOrderMark(body) + return json.Unmarshal(body, &v) + } + return nil +} + +func (client *Client) UnmarshalCollectionBody(response *http.Response, v interface{}) (err error) { + if response != nil && response.Body != nil { + var err error + defer func() { + if closeError := response.Body.Close(); closeError != nil { + err = closeError + } + }() + body, err := ioutil.ReadAll(response.Body) + if err != nil { + return err + } + + body = trimByteOrderMark(body) + err = client.UnmarshalCollectionJson(body, v) + if err != nil { + return err + } + } + return nil +} + +func (client *Client) UnmarshalCollectionJson(jsonValue []byte, v interface{}) (err error) { + t := reflect.TypeOf(v) + if t.Kind() == reflect.Ptr { + t = t.Elem() + } else { + return errors.New("value type must be a pointer") + } + sType := reflect.StructOf([]reflect.StructField{ + {Name: "Count", Type: reflect.TypeOf(0)}, + {Name: "Value", Type: t}, + }) + sv := reflect.New(sType) + err = json.Unmarshal(jsonValue, sv.Interface()) + if err != nil { + return err + } + + rv := reflect.ValueOf(v) + rv.Elem().Set(sv.Elem().FieldByName("Value")) + return nil +} + +// Returns slice of body without utf-8 byte order mark. +// If BOM does not exist body is returned unchanged. +func trimByteOrderMark(body []byte) []byte { + return bytes.TrimPrefix(body, []byte("\xef\xbb\xbf")) +} + +func (client *Client) UnwrapError(response *http.Response) (err error) { + if response.ContentLength == 0 { + message := "Request returned status: " + response.Status + return &WrappedError{ + Message: &message, + StatusCode: &response.StatusCode, + } + } + + defer func() { + if closeError := response.Body.Close(); closeError != nil { + err = closeError + } + }() + + body, err := ioutil.ReadAll(response.Body) + if err != nil { + return err + } + + body = trimByteOrderMark(body) + + contentType, ok := response.Header[headerKeyContentType] + if ok && len(contentType) > 0 && strings.Index(contentType[0], MediaTypeTextPlain) >= 0 { + message := string(body) + statusCode := response.StatusCode + return WrappedError{Message: &message, StatusCode: &statusCode} + } + + var wrappedError WrappedError + err = json.Unmarshal(body, &wrappedError) + wrappedError.StatusCode = &response.StatusCode + if err != nil { + return err + } + + if wrappedError.Message == nil { + var wrappedImproperError WrappedImproperError + err = json.Unmarshal(body, &wrappedImproperError) + if err == nil && wrappedImproperError.Value != nil && wrappedImproperError.Value.Message != nil { + return &WrappedError{ + Message: wrappedImproperError.Value.Message, + StatusCode: &response.StatusCode, + } + } + } + + return wrappedError +} + +func (client *Client) GetResourceAreas(ctx context.Context) (*[]ResourceAreaInfo, error) { + queryParams := url.Values{} + locationId, _ := uuid.Parse("e81700f7-3be2-46de-8624-2eb35882fcaa") + resp, err := client.Send(ctx, http.MethodGet, locationId, "5.1-preview.1", nil, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []ResourceAreaInfo + err = client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +type LocationIdNotRegisteredError struct { + LocationId uuid.UUID + Url string +} + +func (e LocationIdNotRegisteredError) Error() string { + return "API resource location " + e.LocationId.String() + " is not registered on " + e.Url + "." +} + +type InvalidApiVersion struct { + ApiVersion string +} + +func (e InvalidApiVersion) Error() string { + return "The requested api-version is not in a valid format: " + e.ApiVersion +} diff --git a/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/client_options.go b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/client_options.go new file mode 100644 index 000000000..315288f6e --- /dev/null +++ b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/client_options.go @@ -0,0 +1,15 @@ +package azuredevops + +import ( + "net/http" +) + +// ClientOptionFunc can be used customize a new AzureDevops API client. +type ClientOptionFunc func(*Client) + +// WithHTTPClient can be used to configure a custom HTTP client. +func WithHTTPClient(httpClient *http.Client) ClientOptionFunc { + return func(c *Client) { + c.client = httpClient + } +} diff --git a/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/connection.go b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/connection.go new file mode 100644 index 000000000..eb76f53c7 --- /dev/null +++ b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/connection.go @@ -0,0 +1,157 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azuredevops + +import ( + "context" + "crypto/tls" + "encoding/base64" + "strings" + "sync" + "time" + + "github.com/google/uuid" +) + +// Creates a new Azure DevOps connection instance using a personal access token. +func NewPatConnection(organizationUrl string, personalAccessToken string) *Connection { + authorizationString := CreateBasicAuthHeaderValue("", personalAccessToken) + organizationUrl = normalizeUrl(organizationUrl) + return &Connection{ + AuthorizationString: authorizationString, + BaseUrl: organizationUrl, + SuppressFedAuthRedirect: true, + } +} + +func NewAnonymousConnection(organizationUrl string) *Connection { + organizationUrl = normalizeUrl(organizationUrl) + return &Connection{ + BaseUrl: organizationUrl, + SuppressFedAuthRedirect: true, + } +} + +type Connection struct { + AuthorizationString string + BaseUrl string + UserAgent string + SuppressFedAuthRedirect bool + ForceMsaPassThrough bool + Timeout *time.Duration + TlsConfig *tls.Config + clientCache map[string]Client + clientCacheLock sync.RWMutex + resourceAreaCache map[uuid.UUID]ResourceAreaInfo + resourceAreaCacheLock sync.RWMutex +} + +func CreateBasicAuthHeaderValue(username, password string) string { + auth := username + ":" + password + return "Basic " + base64.StdEncoding.EncodeToString([]byte(auth)) +} + +func normalizeUrl(url string) string { + return strings.ToLower(strings.TrimRight(url, "/")) +} + +func (connection *Connection) GetClientByResourceAreaId(ctx context.Context, resourceAreaID uuid.UUID) (*Client, error) { + resourceAreaInfo, err := connection.getResourceAreaInfo(ctx, resourceAreaID) + if err != nil { + return nil, err + } + var client *Client + if resourceAreaInfo != nil { + client = connection.GetClientByUrl(*resourceAreaInfo.LocationUrl) + } else { + // resourceAreaInfo will be nil for on prem servers + client = connection.GetClientByUrl(connection.BaseUrl) + } + return client, nil +} + +func (connection *Connection) GetClientByUrl(baseUrl string) *Client { + normalizedUrl := normalizeUrl(baseUrl) + azureDevOpsClient, ok := connection.getClientCacheEntry(normalizedUrl) + if !ok { + azureDevOpsClient = NewClient(connection, normalizedUrl) + connection.setClientCacheEntry(normalizedUrl, azureDevOpsClient) + } + return azureDevOpsClient +} + +func (connection *Connection) getResourceAreaInfo(ctx context.Context, resourceAreaId uuid.UUID) (*ResourceAreaInfo, error) { + resourceAreaInfo, ok := connection.getResourceAreaCacheEntry(resourceAreaId) + if !ok { + client := connection.GetClientByUrl(connection.BaseUrl) + resourceAreaInfos, err := client.GetResourceAreas(ctx) + if err != nil { + return nil, err + } + + if len(*resourceAreaInfos) > 0 { + for _, resourceEntry := range *resourceAreaInfos { + connection.setResourceAreaCacheEntry(*resourceEntry.Id, &resourceEntry) + } + resourceAreaInfo, ok = connection.getResourceAreaCacheEntry(resourceAreaId) + } else { + // on prem servers return an empty list + return nil, nil + } + } + + if ok { + return resourceAreaInfo, nil + } + + return nil, &ResourceAreaIdNotRegisteredError{resourceAreaId, connection.BaseUrl} +} + +// Client Cache by Url +func (connection *Connection) getClientCacheEntry(url string) (*Client, bool) { + if connection.clientCache == nil { + return nil, false + } + connection.clientCacheLock.RLock() + defer connection.clientCacheLock.RUnlock() + client, ok := connection.clientCache[url] + return &client, ok +} + +func (connection *Connection) setClientCacheEntry(url string, client *Client) { + connection.clientCacheLock.Lock() + defer connection.clientCacheLock.Unlock() + if connection.clientCache == nil { + connection.clientCache = make(map[string]Client) + } + connection.clientCache[url] = *client +} + +func (connection *Connection) getResourceAreaCacheEntry(resourceAreaId uuid.UUID) (*ResourceAreaInfo, bool) { + if connection.resourceAreaCache == nil { + return nil, false + } + connection.resourceAreaCacheLock.RLock() + defer connection.resourceAreaCacheLock.RUnlock() + resourceAreaInfo, ok := connection.resourceAreaCache[resourceAreaId] + return &resourceAreaInfo, ok +} + +func (connection *Connection) setResourceAreaCacheEntry(resourceAreaId uuid.UUID, resourceAreaInfo *ResourceAreaInfo) { + connection.resourceAreaCacheLock.Lock() + defer connection.resourceAreaCacheLock.Unlock() + if connection.resourceAreaCache == nil { + connection.resourceAreaCache = make(map[uuid.UUID]ResourceAreaInfo) + } + connection.resourceAreaCache[resourceAreaId] = *resourceAreaInfo +} + +type ResourceAreaIdNotRegisteredError struct { + ResourceAreaId uuid.UUID + Url string +} + +func (e ResourceAreaIdNotRegisteredError) Error() string { + return "API resource area Id " + e.ResourceAreaId.String() + " is not registered on " + e.Url + "." +} diff --git a/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/core/client.go b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/core/client.go new file mode 100644 index 000000000..9a5c85687 --- /dev/null +++ b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/core/client.go @@ -0,0 +1,917 @@ +// -------------------------------------------------------------------------------------------- +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// -------------------------------------------------------------------------------------------- +// Generated file, DO NOT EDIT +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// -------------------------------------------------------------------------------------------- + +package core + +import ( + "bytes" + "context" + "encoding/json" + "github.com/google/uuid" + "github.com/microsoft/azure-devops-go-api/azuredevops/v7" + "github.com/microsoft/azure-devops-go-api/azuredevops/v7/operations" + "github.com/microsoft/azure-devops-go-api/azuredevops/v7/webapi" + "net/http" + "net/url" + "strconv" + "strings" +) + +var ResourceAreaId, _ = uuid.Parse("79134c72-4a58-4b42-976c-04e7115f32bf") + +type Client interface { + // [Preview API] + CreateConnectedService(context.Context, CreateConnectedServiceArgs) (*WebApiConnectedService, error) + // [Preview API] + CreateOrUpdateProxy(context.Context, CreateOrUpdateProxyArgs) (*Proxy, error) + // [Preview API] Create a team in a team project. + CreateTeam(context.Context, CreateTeamArgs) (*WebApiTeam, error) + // [Preview API] + DeleteProxy(context.Context, DeleteProxyArgs) error + // [Preview API] Delete a team. + DeleteTeam(context.Context, DeleteTeamArgs) error + // [Preview API] Get a list of all teams. + GetAllTeams(context.Context, GetAllTeamsArgs) (*[]WebApiTeam, error) + // [Preview API] + GetConnectedServiceDetails(context.Context, GetConnectedServiceDetailsArgs) (*WebApiConnectedServiceDetails, error) + // [Preview API] + GetConnectedServices(context.Context, GetConnectedServicesArgs) (*[]WebApiConnectedService, error) + // [Preview API] Get a process by ID. + GetProcessById(context.Context, GetProcessByIdArgs) (*Process, error) + // [Preview API] Get a list of processes. + GetProcesses(context.Context, GetProcessesArgs) (*[]Process, error) + // [Preview API] Get project with the specified id or name, optionally including capabilities. + GetProject(context.Context, GetProjectArgs) (*TeamProject, error) + // [Preview API] Get project collection with the specified id or name. + GetProjectCollection(context.Context, GetProjectCollectionArgs) (*TeamProjectCollection, error) + // [Preview API] Get project collection references for this application. + GetProjectCollections(context.Context, GetProjectCollectionsArgs) (*[]TeamProjectCollectionReference, error) + // [Preview API] Get a collection of team project properties. + GetProjectProperties(context.Context, GetProjectPropertiesArgs) (*[]ProjectProperty, error) + // [Preview API] Get all projects in the organization that the authenticated user has access to. + GetProjects(context.Context, GetProjectsArgs) (*GetProjectsResponseValue, error) + // [Preview API] + GetProxies(context.Context, GetProxiesArgs) (*[]Proxy, error) + // [Preview API] Get a specific team. + GetTeam(context.Context, GetTeamArgs) (*WebApiTeam, error) + // [Preview API] Get a list of members for a specific team. + GetTeamMembersWithExtendedProperties(context.Context, GetTeamMembersWithExtendedPropertiesArgs) (*[]webapi.TeamMember, error) + // [Preview API] Get a list of teams. + GetTeams(context.Context, GetTeamsArgs) (*[]WebApiTeam, error) + // [Preview API] Queues a project to be created. Use the [GetOperation](../../operations/operations/get) to periodically check for create project status. + QueueCreateProject(context.Context, QueueCreateProjectArgs) (*operations.OperationReference, error) + // [Preview API] Queues a project to be deleted. Use the [GetOperation](../../operations/operations/get) to periodically check for delete project status. + QueueDeleteProject(context.Context, QueueDeleteProjectArgs) (*operations.OperationReference, error) + // [Preview API] Removes the avatar for the project. + RemoveProjectAvatar(context.Context, RemoveProjectAvatarArgs) error + // [Preview API] Sets the avatar for the project. + SetProjectAvatar(context.Context, SetProjectAvatarArgs) error + // [Preview API] Create, update, and delete team project properties. + SetProjectProperties(context.Context, SetProjectPropertiesArgs) error + // [Preview API] Update an existing project's name, abbreviation, description, or restore a project. + UpdateProject(context.Context, UpdateProjectArgs) (*operations.OperationReference, error) + // [Preview API] Update a team's name and/or description. + UpdateTeam(context.Context, UpdateTeamArgs) (*WebApiTeam, error) +} + +type ClientImpl struct { + Client azuredevops.Client +} + +func NewClient(ctx context.Context, connection *azuredevops.Connection) (Client, error) { + client, err := connection.GetClientByResourceAreaId(ctx, ResourceAreaId) + if err != nil { + return nil, err + } + return &ClientImpl{ + Client: *client, + }, nil +} + +// [Preview API] +func (client *ClientImpl) CreateConnectedService(ctx context.Context, args CreateConnectedServiceArgs) (*WebApiConnectedService, error) { + if args.ConnectedServiceCreationData == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.ConnectedServiceCreationData"} + } + routeValues := make(map[string]string) + if args.ProjectId == nil || *args.ProjectId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.ProjectId"} + } + routeValues["projectId"] = *args.ProjectId + + body, marshalErr := json.Marshal(*args.ConnectedServiceCreationData) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("b4f70219-e18b-42c5-abe3-98b07d35525e") + resp, err := client.Client.Send(ctx, http.MethodPost, locationId, "7.1-preview.1", routeValues, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue WebApiConnectedService + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the CreateConnectedService function +type CreateConnectedServiceArgs struct { + // (required) + ConnectedServiceCreationData *WebApiConnectedServiceDetails + // (required) + ProjectId *string +} + +// [Preview API] +func (client *ClientImpl) CreateOrUpdateProxy(ctx context.Context, args CreateOrUpdateProxyArgs) (*Proxy, error) { + if args.Proxy == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.Proxy"} + } + body, marshalErr := json.Marshal(*args.Proxy) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("ec1f4311-f2b4-4c15-b2b8-8990b80d2908") + resp, err := client.Client.Send(ctx, http.MethodPut, locationId, "7.1-preview.2", nil, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue Proxy + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the CreateOrUpdateProxy function +type CreateOrUpdateProxyArgs struct { + // (required) + Proxy *Proxy +} + +// [Preview API] Create a team in a team project. +func (client *ClientImpl) CreateTeam(ctx context.Context, args CreateTeamArgs) (*WebApiTeam, error) { + if args.Team == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.Team"} + } + routeValues := make(map[string]string) + if args.ProjectId == nil || *args.ProjectId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.ProjectId"} + } + routeValues["projectId"] = *args.ProjectId + + body, marshalErr := json.Marshal(*args.Team) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("d30a3dd1-f8ba-442a-b86a-bd0c0c383e59") + resp, err := client.Client.Send(ctx, http.MethodPost, locationId, "7.1-preview.3", routeValues, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue WebApiTeam + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the CreateTeam function +type CreateTeamArgs struct { + // (required) The team data used to create the team. + Team *WebApiTeam + // (required) The name or ID (GUID) of the team project in which to create the team. + ProjectId *string +} + +// [Preview API] +func (client *ClientImpl) DeleteProxy(ctx context.Context, args DeleteProxyArgs) error { + queryParams := url.Values{} + if args.ProxyUrl == nil { + return &azuredevops.ArgumentNilError{ArgumentName: "proxyUrl"} + } + queryParams.Add("proxyUrl", *args.ProxyUrl) + if args.Site != nil { + queryParams.Add("site", *args.Site) + } + locationId, _ := uuid.Parse("ec1f4311-f2b4-4c15-b2b8-8990b80d2908") + _, err := client.Client.Send(ctx, http.MethodDelete, locationId, "7.1-preview.2", nil, queryParams, nil, "", "application/json", nil) + if err != nil { + return err + } + + return nil +} + +// Arguments for the DeleteProxy function +type DeleteProxyArgs struct { + // (required) + ProxyUrl *string + // (optional) + Site *string +} + +// [Preview API] Delete a team. +func (client *ClientImpl) DeleteTeam(ctx context.Context, args DeleteTeamArgs) error { + routeValues := make(map[string]string) + if args.ProjectId == nil || *args.ProjectId == "" { + return &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.ProjectId"} + } + routeValues["projectId"] = *args.ProjectId + if args.TeamId == nil || *args.TeamId == "" { + return &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.TeamId"} + } + routeValues["teamId"] = *args.TeamId + + locationId, _ := uuid.Parse("d30a3dd1-f8ba-442a-b86a-bd0c0c383e59") + _, err := client.Client.Send(ctx, http.MethodDelete, locationId, "7.1-preview.3", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return err + } + + return nil +} + +// Arguments for the DeleteTeam function +type DeleteTeamArgs struct { + // (required) The name or ID (GUID) of the team project containing the team to delete. + ProjectId *string + // (required) The name or ID of the team to delete. + TeamId *string +} + +// [Preview API] Get a list of all teams. +func (client *ClientImpl) GetAllTeams(ctx context.Context, args GetAllTeamsArgs) (*[]WebApiTeam, error) { + queryParams := url.Values{} + if args.Mine != nil { + queryParams.Add("$mine", strconv.FormatBool(*args.Mine)) + } + if args.Top != nil { + queryParams.Add("$top", strconv.Itoa(*args.Top)) + } + if args.Skip != nil { + queryParams.Add("$skip", strconv.Itoa(*args.Skip)) + } + if args.ExpandIdentity != nil { + queryParams.Add("$expandIdentity", strconv.FormatBool(*args.ExpandIdentity)) + } + locationId, _ := uuid.Parse("7a4d9ee9-3433-4347-b47a-7a80f1cf307e") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.3", nil, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []WebApiTeam + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetAllTeams function +type GetAllTeamsArgs struct { + // (optional) If true, then return all teams requesting user is member. Otherwise return all teams user has read access. + Mine *bool + // (optional) Maximum number of teams to return. + Top *int + // (optional) Number of teams to skip. + Skip *int + // (optional) A value indicating whether or not to expand Identity information in the result WebApiTeam object. + ExpandIdentity *bool +} + +// [Preview API] +func (client *ClientImpl) GetConnectedServiceDetails(ctx context.Context, args GetConnectedServiceDetailsArgs) (*WebApiConnectedServiceDetails, error) { + routeValues := make(map[string]string) + if args.ProjectId == nil || *args.ProjectId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.ProjectId"} + } + routeValues["projectId"] = *args.ProjectId + if args.Name == nil || *args.Name == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.Name"} + } + routeValues["name"] = *args.Name + + locationId, _ := uuid.Parse("b4f70219-e18b-42c5-abe3-98b07d35525e") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue WebApiConnectedServiceDetails + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetConnectedServiceDetails function +type GetConnectedServiceDetailsArgs struct { + // (required) + ProjectId *string + // (required) + Name *string +} + +// [Preview API] +func (client *ClientImpl) GetConnectedServices(ctx context.Context, args GetConnectedServicesArgs) (*[]WebApiConnectedService, error) { + routeValues := make(map[string]string) + if args.ProjectId == nil || *args.ProjectId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.ProjectId"} + } + routeValues["projectId"] = *args.ProjectId + + queryParams := url.Values{} + if args.Kind != nil { + queryParams.Add("kind", string(*args.Kind)) + } + locationId, _ := uuid.Parse("b4f70219-e18b-42c5-abe3-98b07d35525e") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []WebApiConnectedService + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetConnectedServices function +type GetConnectedServicesArgs struct { + // (required) + ProjectId *string + // (optional) + Kind *ConnectedServiceKind +} + +// [Preview API] Get a process by ID. +func (client *ClientImpl) GetProcessById(ctx context.Context, args GetProcessByIdArgs) (*Process, error) { + routeValues := make(map[string]string) + if args.ProcessId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.ProcessId"} + } + routeValues["processId"] = (*args.ProcessId).String() + + locationId, _ := uuid.Parse("93878975-88c5-4e6a-8abb-7ddd77a8a7d8") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue Process + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetProcessById function +type GetProcessByIdArgs struct { + // (required) ID for a process. + ProcessId *uuid.UUID +} + +// [Preview API] Get a list of processes. +func (client *ClientImpl) GetProcesses(ctx context.Context, args GetProcessesArgs) (*[]Process, error) { + locationId, _ := uuid.Parse("93878975-88c5-4e6a-8abb-7ddd77a8a7d8") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", nil, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []Process + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetProcesses function +type GetProcessesArgs struct { +} + +// [Preview API] Get project with the specified id or name, optionally including capabilities. +func (client *ClientImpl) GetProject(ctx context.Context, args GetProjectArgs) (*TeamProject, error) { + routeValues := make(map[string]string) + if args.ProjectId == nil || *args.ProjectId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.ProjectId"} + } + routeValues["projectId"] = *args.ProjectId + + queryParams := url.Values{} + if args.IncludeCapabilities != nil { + queryParams.Add("includeCapabilities", strconv.FormatBool(*args.IncludeCapabilities)) + } + if args.IncludeHistory != nil { + queryParams.Add("includeHistory", strconv.FormatBool(*args.IncludeHistory)) + } + locationId, _ := uuid.Parse("603fe2ac-9723-48b9-88ad-09305aa6c6e1") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.4", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue TeamProject + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetProject function +type GetProjectArgs struct { + // (required) + ProjectId *string + // (optional) Include capabilities (such as source control) in the team project result (default: false). + IncludeCapabilities *bool + // (optional) Search within renamed projects (that had such name in the past). + IncludeHistory *bool +} + +// [Preview API] Get project collection with the specified id or name. +func (client *ClientImpl) GetProjectCollection(ctx context.Context, args GetProjectCollectionArgs) (*TeamProjectCollection, error) { + routeValues := make(map[string]string) + if args.CollectionId == nil || *args.CollectionId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.CollectionId"} + } + routeValues["collectionId"] = *args.CollectionId + + locationId, _ := uuid.Parse("8031090f-ef1d-4af6-85fc-698cd75d42bf") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.2", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue TeamProjectCollection + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetProjectCollection function +type GetProjectCollectionArgs struct { + // (required) + CollectionId *string +} + +// [Preview API] Get project collection references for this application. +func (client *ClientImpl) GetProjectCollections(ctx context.Context, args GetProjectCollectionsArgs) (*[]TeamProjectCollectionReference, error) { + queryParams := url.Values{} + if args.Top != nil { + queryParams.Add("$top", strconv.Itoa(*args.Top)) + } + if args.Skip != nil { + queryParams.Add("$skip", strconv.Itoa(*args.Skip)) + } + locationId, _ := uuid.Parse("8031090f-ef1d-4af6-85fc-698cd75d42bf") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.2", nil, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []TeamProjectCollectionReference + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetProjectCollections function +type GetProjectCollectionsArgs struct { + // (optional) + Top *int + // (optional) + Skip *int +} + +// [Preview API] Get a collection of team project properties. +func (client *ClientImpl) GetProjectProperties(ctx context.Context, args GetProjectPropertiesArgs) (*[]ProjectProperty, error) { + routeValues := make(map[string]string) + if args.ProjectId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.ProjectId"} + } + routeValues["projectId"] = (*args.ProjectId).String() + + queryParams := url.Values{} + if args.Keys != nil { + listAsString := strings.Join((*args.Keys)[:], ",") + queryParams.Add("keys", listAsString) + } + locationId, _ := uuid.Parse("4976a71a-4487-49aa-8aab-a1eda469037a") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []ProjectProperty + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetProjectProperties function +type GetProjectPropertiesArgs struct { + // (required) The team project ID. + ProjectId *uuid.UUID + // (optional) A comma-delimited string of team project property names. Wildcard characters ("?" and "*") are supported. If no key is specified, all properties will be returned. + Keys *[]string +} + +// [Preview API] Get all projects in the organization that the authenticated user has access to. +func (client *ClientImpl) GetProjects(ctx context.Context, args GetProjectsArgs) (*GetProjectsResponseValue, error) { + queryParams := url.Values{} + if args.StateFilter != nil { + queryParams.Add("stateFilter", string(*args.StateFilter)) + } + if args.Top != nil { + queryParams.Add("$top", strconv.Itoa(*args.Top)) + } + if args.Skip != nil { + queryParams.Add("$skip", strconv.Itoa(*args.Skip)) + } + if args.ContinuationToken != nil { + queryParams.Add("continuationToken", strconv.Itoa(*args.ContinuationToken)) + } + if args.GetDefaultTeamImageUrl != nil { + queryParams.Add("getDefaultTeamImageUrl", strconv.FormatBool(*args.GetDefaultTeamImageUrl)) + } + locationId, _ := uuid.Parse("603fe2ac-9723-48b9-88ad-09305aa6c6e1") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.4", nil, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GetProjectsResponseValue + responseValue.ContinuationToken = resp.Header.Get(azuredevops.HeaderKeyContinuationToken) + err = client.Client.UnmarshalCollectionBody(resp, &responseValue.Value) + return &responseValue, err +} + +// Arguments for the GetProjects function +type GetProjectsArgs struct { + // (optional) Filter on team projects in a specific team project state (default: WellFormed). + StateFilter *ProjectState + // (optional) + Top *int + // (optional) + Skip *int + // (optional) Pointer that shows how many projects already been fetched. + ContinuationToken *int + // (optional) + GetDefaultTeamImageUrl *bool +} + +// Return type for the GetProjects function +type GetProjectsResponseValue struct { + Value []TeamProjectReference + ContinuationToken string +} + +// [Preview API] +func (client *ClientImpl) GetProxies(ctx context.Context, args GetProxiesArgs) (*[]Proxy, error) { + queryParams := url.Values{} + if args.ProxyUrl != nil { + queryParams.Add("proxyUrl", *args.ProxyUrl) + } + locationId, _ := uuid.Parse("ec1f4311-f2b4-4c15-b2b8-8990b80d2908") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.2", nil, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []Proxy + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetProxies function +type GetProxiesArgs struct { + // (optional) + ProxyUrl *string +} + +// [Preview API] Get a specific team. +func (client *ClientImpl) GetTeam(ctx context.Context, args GetTeamArgs) (*WebApiTeam, error) { + routeValues := make(map[string]string) + if args.ProjectId == nil || *args.ProjectId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.ProjectId"} + } + routeValues["projectId"] = *args.ProjectId + if args.TeamId == nil || *args.TeamId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.TeamId"} + } + routeValues["teamId"] = *args.TeamId + + queryParams := url.Values{} + if args.ExpandIdentity != nil { + queryParams.Add("$expandIdentity", strconv.FormatBool(*args.ExpandIdentity)) + } + locationId, _ := uuid.Parse("d30a3dd1-f8ba-442a-b86a-bd0c0c383e59") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.3", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue WebApiTeam + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetTeam function +type GetTeamArgs struct { + // (required) The name or ID (GUID) of the team project containing the team. + ProjectId *string + // (required) The name or ID (GUID) of the team. + TeamId *string + // (optional) A value indicating whether or not to expand Identity information in the result WebApiTeam object. + ExpandIdentity *bool +} + +// [Preview API] Get a list of members for a specific team. +func (client *ClientImpl) GetTeamMembersWithExtendedProperties(ctx context.Context, args GetTeamMembersWithExtendedPropertiesArgs) (*[]webapi.TeamMember, error) { + routeValues := make(map[string]string) + if args.ProjectId == nil || *args.ProjectId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.ProjectId"} + } + routeValues["projectId"] = *args.ProjectId + if args.TeamId == nil || *args.TeamId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.TeamId"} + } + routeValues["teamId"] = *args.TeamId + + queryParams := url.Values{} + if args.Top != nil { + queryParams.Add("$top", strconv.Itoa(*args.Top)) + } + if args.Skip != nil { + queryParams.Add("$skip", strconv.Itoa(*args.Skip)) + } + locationId, _ := uuid.Parse("294c494c-2600-4d7e-b76c-3dd50c3c95be") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.2", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []webapi.TeamMember + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetTeamMembersWithExtendedProperties function +type GetTeamMembersWithExtendedPropertiesArgs struct { + // (required) The name or ID (GUID) of the team project the team belongs to. + ProjectId *string + // (required) The name or ID (GUID) of the team . + TeamId *string + // (optional) + Top *int + // (optional) + Skip *int +} + +// [Preview API] Get a list of teams. +func (client *ClientImpl) GetTeams(ctx context.Context, args GetTeamsArgs) (*[]WebApiTeam, error) { + routeValues := make(map[string]string) + if args.ProjectId == nil || *args.ProjectId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.ProjectId"} + } + routeValues["projectId"] = *args.ProjectId + + queryParams := url.Values{} + if args.Mine != nil { + queryParams.Add("$mine", strconv.FormatBool(*args.Mine)) + } + if args.Top != nil { + queryParams.Add("$top", strconv.Itoa(*args.Top)) + } + if args.Skip != nil { + queryParams.Add("$skip", strconv.Itoa(*args.Skip)) + } + if args.ExpandIdentity != nil { + queryParams.Add("$expandIdentity", strconv.FormatBool(*args.ExpandIdentity)) + } + locationId, _ := uuid.Parse("d30a3dd1-f8ba-442a-b86a-bd0c0c383e59") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.3", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []WebApiTeam + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetTeams function +type GetTeamsArgs struct { + // (required) + ProjectId *string + // (optional) If true return all the teams requesting user is member, otherwise return all the teams user has read access. + Mine *bool + // (optional) Maximum number of teams to return. + Top *int + // (optional) Number of teams to skip. + Skip *int + // (optional) A value indicating whether or not to expand Identity information in the result WebApiTeam object. + ExpandIdentity *bool +} + +// [Preview API] Queues a project to be created. Use the [GetOperation](../../operations/operations/get) to periodically check for create project status. +func (client *ClientImpl) QueueCreateProject(ctx context.Context, args QueueCreateProjectArgs) (*operations.OperationReference, error) { + if args.ProjectToCreate == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.ProjectToCreate"} + } + body, marshalErr := json.Marshal(*args.ProjectToCreate) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("603fe2ac-9723-48b9-88ad-09305aa6c6e1") + resp, err := client.Client.Send(ctx, http.MethodPost, locationId, "7.1-preview.4", nil, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue operations.OperationReference + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the QueueCreateProject function +type QueueCreateProjectArgs struct { + // (required) The project to create. + ProjectToCreate *TeamProject +} + +// [Preview API] Queues a project to be deleted. Use the [GetOperation](../../operations/operations/get) to periodically check for delete project status. +func (client *ClientImpl) QueueDeleteProject(ctx context.Context, args QueueDeleteProjectArgs) (*operations.OperationReference, error) { + routeValues := make(map[string]string) + if args.ProjectId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.ProjectId"} + } + routeValues["projectId"] = (*args.ProjectId).String() + + locationId, _ := uuid.Parse("603fe2ac-9723-48b9-88ad-09305aa6c6e1") + resp, err := client.Client.Send(ctx, http.MethodDelete, locationId, "7.1-preview.4", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue operations.OperationReference + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the QueueDeleteProject function +type QueueDeleteProjectArgs struct { + // (required) The project id of the project to delete. + ProjectId *uuid.UUID +} + +// [Preview API] Removes the avatar for the project. +func (client *ClientImpl) RemoveProjectAvatar(ctx context.Context, args RemoveProjectAvatarArgs) error { + routeValues := make(map[string]string) + if args.ProjectId == nil || *args.ProjectId == "" { + return &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.ProjectId"} + } + routeValues["projectId"] = *args.ProjectId + + locationId, _ := uuid.Parse("54b2a2a0-859b-4d05-827c-ec4c862f641a") + _, err := client.Client.Send(ctx, http.MethodDelete, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return err + } + + return nil +} + +// Arguments for the RemoveProjectAvatar function +type RemoveProjectAvatarArgs struct { + // (required) The ID or name of the project. + ProjectId *string +} + +// [Preview API] Sets the avatar for the project. +func (client *ClientImpl) SetProjectAvatar(ctx context.Context, args SetProjectAvatarArgs) error { + if args.AvatarBlob == nil { + return &azuredevops.ArgumentNilError{ArgumentName: "args.AvatarBlob"} + } + routeValues := make(map[string]string) + if args.ProjectId == nil || *args.ProjectId == "" { + return &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.ProjectId"} + } + routeValues["projectId"] = *args.ProjectId + + body, marshalErr := json.Marshal(*args.AvatarBlob) + if marshalErr != nil { + return marshalErr + } + locationId, _ := uuid.Parse("54b2a2a0-859b-4d05-827c-ec4c862f641a") + _, err := client.Client.Send(ctx, http.MethodPut, locationId, "7.1-preview.1", routeValues, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return err + } + + return nil +} + +// Arguments for the SetProjectAvatar function +type SetProjectAvatarArgs struct { + // (required) The avatar blob data object to upload. + AvatarBlob *ProjectAvatar + // (required) The ID or name of the project. + ProjectId *string +} + +// [Preview API] Create, update, and delete team project properties. +func (client *ClientImpl) SetProjectProperties(ctx context.Context, args SetProjectPropertiesArgs) error { + if args.PatchDocument == nil { + return &azuredevops.ArgumentNilError{ArgumentName: "args.PatchDocument"} + } + routeValues := make(map[string]string) + if args.ProjectId == nil { + return &azuredevops.ArgumentNilError{ArgumentName: "args.ProjectId"} + } + routeValues["projectId"] = (*args.ProjectId).String() + + body, marshalErr := json.Marshal(*args.PatchDocument) + if marshalErr != nil { + return marshalErr + } + locationId, _ := uuid.Parse("4976a71a-4487-49aa-8aab-a1eda469037a") + _, err := client.Client.Send(ctx, http.MethodPatch, locationId, "7.1-preview.1", routeValues, nil, bytes.NewReader(body), "application/json-patch+json", "application/json", nil) + if err != nil { + return err + } + + return nil +} + +// Arguments for the SetProjectProperties function +type SetProjectPropertiesArgs struct { + // (required) The team project ID. + ProjectId *uuid.UUID + // (required) A JSON Patch document that represents an array of property operations. See RFC 6902 for more details on JSON Patch. The accepted operation verbs are Add and Remove, where Add is used for both creating and updating properties. The path consists of a forward slash and a property name. + PatchDocument *[]webapi.JsonPatchOperation +} + +// [Preview API] Update an existing project's name, abbreviation, description, or restore a project. +func (client *ClientImpl) UpdateProject(ctx context.Context, args UpdateProjectArgs) (*operations.OperationReference, error) { + if args.ProjectUpdate == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.ProjectUpdate"} + } + routeValues := make(map[string]string) + if args.ProjectId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.ProjectId"} + } + routeValues["projectId"] = (*args.ProjectId).String() + + body, marshalErr := json.Marshal(*args.ProjectUpdate) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("603fe2ac-9723-48b9-88ad-09305aa6c6e1") + resp, err := client.Client.Send(ctx, http.MethodPatch, locationId, "7.1-preview.4", routeValues, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue operations.OperationReference + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the UpdateProject function +type UpdateProjectArgs struct { + // (required) The updates for the project. The state must be set to wellFormed to restore the project. + ProjectUpdate *TeamProject + // (required) The project id of the project to update. + ProjectId *uuid.UUID +} + +// [Preview API] Update a team's name and/or description. +func (client *ClientImpl) UpdateTeam(ctx context.Context, args UpdateTeamArgs) (*WebApiTeam, error) { + if args.TeamData == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.TeamData"} + } + routeValues := make(map[string]string) + if args.ProjectId == nil || *args.ProjectId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.ProjectId"} + } + routeValues["projectId"] = *args.ProjectId + if args.TeamId == nil || *args.TeamId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.TeamId"} + } + routeValues["teamId"] = *args.TeamId + + body, marshalErr := json.Marshal(*args.TeamData) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("d30a3dd1-f8ba-442a-b86a-bd0c0c383e59") + resp, err := client.Client.Send(ctx, http.MethodPatch, locationId, "7.1-preview.3", routeValues, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue WebApiTeam + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the UpdateTeam function +type UpdateTeamArgs struct { + // (required) + TeamData *WebApiTeam + // (required) The name or ID (GUID) of the team project containing the team to update. + ProjectId *string + // (required) The name of ID of the team to update. + TeamId *string +} diff --git a/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/core/models.go b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/core/models.go new file mode 100644 index 000000000..7977022d7 --- /dev/null +++ b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/core/models.go @@ -0,0 +1,490 @@ +// -------------------------------------------------------------------------------------------- +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// -------------------------------------------------------------------------------------------- +// Generated file, DO NOT EDIT +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// -------------------------------------------------------------------------------------------- + +package core + +import ( + "github.com/google/uuid" + "github.com/microsoft/azure-devops-go-api/azuredevops/v7" + "github.com/microsoft/azure-devops-go-api/azuredevops/v7/identity" + "github.com/microsoft/azure-devops-go-api/azuredevops/v7/webapi" +) + +type ConnectedServiceKind string + +type connectedServiceKindValuesType struct { + Custom ConnectedServiceKind + AzureSubscription ConnectedServiceKind + Chef ConnectedServiceKind + Generic ConnectedServiceKind +} + +var ConnectedServiceKindValues = connectedServiceKindValuesType{ + // Custom or unknown service + Custom: "custom", + // Azure Subscription + AzureSubscription: "azureSubscription", + // Chef Connection + Chef: "chef", + // Generic Connection + Generic: "generic", +} + +type IdentityData struct { + IdentityIds *[]uuid.UUID `json:"identityIds,omitempty"` +} + +type Process struct { + Name *string `json:"name,omitempty"` + Url *string `json:"url,omitempty"` + Links interface{} `json:"_links,omitempty"` + Description *string `json:"description,omitempty"` + Id *uuid.UUID `json:"id,omitempty"` + IsDefault *bool `json:"isDefault,omitempty"` + Type *ProcessType `json:"type,omitempty"` +} + +// Type of process customization on a collection. +type ProcessCustomizationType string + +type processCustomizationTypeValuesType struct { + Unknown ProcessCustomizationType + Xml ProcessCustomizationType + Inherited ProcessCustomizationType +} + +var ProcessCustomizationTypeValues = processCustomizationTypeValuesType{ + // Process customization can't be computed. + Unknown: "unknown", + // Customization based on project-scoped xml customization + Xml: "xml", + // Customization based on process inheritance + Inherited: "inherited", +} + +type ProcessReference struct { + Name *string `json:"name,omitempty"` + Url *string `json:"url,omitempty"` +} + +type ProcessType string + +type processTypeValuesType struct { + System ProcessType + Custom ProcessType + Inherited ProcessType +} + +var ProcessTypeValues = processTypeValuesType{ + System: "system", + Custom: "custom", + Inherited: "inherited", +} + +// Contains the image data for project avatar. +type ProjectAvatar struct { + // The avatar image represented as a byte array. + Image *[]byte `json:"image,omitempty"` +} + +type ProjectChangeType string + +type projectChangeTypeValuesType struct { + Modified ProjectChangeType + Deleted ProjectChangeType + Added ProjectChangeType +} + +var ProjectChangeTypeValues = projectChangeTypeValuesType{ + Modified: "modified", + Deleted: "deleted", + Added: "added", +} + +// Contains information describing a project. +type ProjectInfo struct { + // The abbreviated name of the project. + Abbreviation *string `json:"abbreviation,omitempty"` + // The description of the project. + Description *string `json:"description,omitempty"` + // The id of the project. + Id *uuid.UUID `json:"id,omitempty"` + // The time that this project was last updated. + LastUpdateTime *azuredevops.Time `json:"lastUpdateTime,omitempty"` + // The name of the project. + Name *string `json:"name,omitempty"` + // A set of name-value pairs storing additional property data related to the project. + Properties *[]ProjectProperty `json:"properties,omitempty"` + // The current revision of the project. + Revision *uint64 `json:"revision,omitempty"` + // The current state of the project. + State *ProjectState `json:"state,omitempty"` + // A Uri that can be used to refer to this project. + Uri *string `json:"uri,omitempty"` + // The version number of the project. + Version *uint64 `json:"version,omitempty"` + // Indicates whom the project is visible to. + Visibility *ProjectVisibility `json:"visibility,omitempty"` +} + +type ProjectMessage struct { + Project *ProjectInfo `json:"project,omitempty"` + ProjectChangeType *ProjectChangeType `json:"projectChangeType,omitempty"` + ShouldInvalidateSystemStore *bool `json:"shouldInvalidateSystemStore,omitempty"` +} + +type ProjectProperties struct { + // The team project Id + ProjectId *uuid.UUID `json:"projectId,omitempty"` + // The collection of team project properties + Properties *[]ProjectProperty `json:"properties,omitempty"` +} + +// A named value associated with a project. +type ProjectProperty struct { + // The name of the property. + Name *string `json:"name,omitempty"` + // The value of the property. + Value interface{} `json:"value,omitempty"` +} + +type ProjectState string + +type projectStateValuesType struct { + Deleting ProjectState + New ProjectState + WellFormed ProjectState + CreatePending ProjectState + All ProjectState + Unchanged ProjectState + Deleted ProjectState +} + +var ProjectStateValues = projectStateValuesType{ + // Project is in the process of being deleted. + Deleting: "deleting", + // Project is in the process of being created. + New: "new", + // Project is completely created and ready to use. + WellFormed: "wellFormed", + // Project has been queued for creation, but the process has not yet started. + CreatePending: "createPending", + // All projects regardless of state except Deleted. + All: "all", + // Project has not been changed. + Unchanged: "unchanged", + // Project has been deleted. + Deleted: "deleted", +} + +type ProjectVisibility string + +type projectVisibilityValuesType struct { + Private ProjectVisibility + Public ProjectVisibility +} + +var ProjectVisibilityValues = projectVisibilityValuesType{ + // The project is only visible to users with explicit access. + Private: "private", + // The project is visible to all. + Public: "public", +} + +type Proxy struct { + Authorization *ProxyAuthorization `json:"authorization,omitempty"` + // This is a description string + Description *string `json:"description,omitempty"` + // The friendly name of the server + FriendlyName *string `json:"friendlyName,omitempty"` + GlobalDefault *bool `json:"globalDefault,omitempty"` + // This is a string representation of the site that the proxy server is located in (e.g. "NA-WA-RED") + Site *string `json:"site,omitempty"` + SiteDefault *bool `json:"siteDefault,omitempty"` + // The URL of the proxy server + Url *string `json:"url,omitempty"` +} + +type ProxyAuthorization struct { + // Gets or sets the endpoint used to obtain access tokens from the configured token service. + AuthorizationUrl *string `json:"authorizationUrl,omitempty"` + // Gets or sets the client identifier for this proxy. + ClientId *uuid.UUID `json:"clientId,omitempty"` + // Gets or sets the user identity to authorize for on-prem. + Identity *string `json:"identity,omitempty"` + // Gets or sets the public key used to verify the identity of this proxy. Only specify on hosted. + PublicKey *webapi.PublicKey `json:"publicKey,omitempty"` +} + +type SourceControlTypes string + +type sourceControlTypesValuesType struct { + Tfvc SourceControlTypes + Git SourceControlTypes +} + +var SourceControlTypesValues = sourceControlTypesValuesType{ + Tfvc: "tfvc", + Git: "git", +} + +// The Team Context for an operation. +type TeamContext struct { + // The team project Id or name. Ignored if ProjectId is set. + Project *string `json:"project,omitempty"` + // The Team Project ID. Required if Project is not set. + ProjectId *uuid.UUID `json:"projectId,omitempty"` + // The Team Id or name. Ignored if TeamId is set. + Team *string `json:"team,omitempty"` + // The Team Id + TeamId *uuid.UUID `json:"teamId,omitempty"` +} + +// Represents a Team Project object. +type TeamProject struct { + // Project abbreviation. + Abbreviation *string `json:"abbreviation,omitempty"` + // Url to default team identity image. + DefaultTeamImageUrl *string `json:"defaultTeamImageUrl,omitempty"` + // The project's description (if any). + Description *string `json:"description,omitempty"` + // Project identifier. + Id *uuid.UUID `json:"id,omitempty"` + // Project last update time. + LastUpdateTime *azuredevops.Time `json:"lastUpdateTime,omitempty"` + // Project name. + Name *string `json:"name,omitempty"` + // Project revision. + Revision *uint64 `json:"revision,omitempty"` + // Project state. + State *ProjectState `json:"state,omitempty"` + // Url to the full version of the object. + Url *string `json:"url,omitempty"` + // Project visibility. + Visibility *ProjectVisibility `json:"visibility,omitempty"` + // The links to other objects related to this object. + Links interface{} `json:"_links,omitempty"` + // Set of capabilities this project has (such as process template & version control). + Capabilities *map[string]map[string]string `json:"capabilities,omitempty"` + // The shallow ref to the default team. + DefaultTeam *WebApiTeamRef `json:"defaultTeam,omitempty"` +} + +// Data contract for a TeamProjectCollection. +type TeamProjectCollection struct { + // Collection avatar Url. + AvatarUrl *string `json:"avatarUrl,omitempty"` + // Collection Id. + Id *uuid.UUID `json:"id,omitempty"` + // Collection Name. + Name *string `json:"name,omitempty"` + // Collection REST Url. + Url *string `json:"url,omitempty"` + // The links to other objects related to this object. + Links interface{} `json:"_links,omitempty"` + // Project collection description. + Description *string `json:"description,omitempty"` + // Process customization type on this collection. It can be Xml or Inherited. + ProcessCustomizationType *ProcessCustomizationType `json:"processCustomizationType,omitempty"` + // Project collection state. + State *string `json:"state,omitempty"` +} + +// Reference object for a TeamProjectCollection. +type TeamProjectCollectionReference struct { + // Collection avatar Url. + AvatarUrl *string `json:"avatarUrl,omitempty"` + // Collection Id. + Id *uuid.UUID `json:"id,omitempty"` + // Collection Name. + Name *string `json:"name,omitempty"` + // Collection REST Url. + Url *string `json:"url,omitempty"` +} + +// Represents a shallow reference to a TeamProject. +type TeamProjectReference struct { + // Project abbreviation. + Abbreviation *string `json:"abbreviation,omitempty"` + // Url to default team identity image. + DefaultTeamImageUrl *string `json:"defaultTeamImageUrl,omitempty"` + // The project's description (if any). + Description *string `json:"description,omitempty"` + // Project identifier. + Id *uuid.UUID `json:"id,omitempty"` + // Project last update time. + LastUpdateTime *azuredevops.Time `json:"lastUpdateTime,omitempty"` + // Project name. + Name *string `json:"name,omitempty"` + // Project revision. + Revision *uint64 `json:"revision,omitempty"` + // Project state. + State *ProjectState `json:"state,omitempty"` + // Url to the full version of the object. + Url *string `json:"url,omitempty"` + // Project visibility. + Visibility *ProjectVisibility `json:"visibility,omitempty"` +} + +// A data transfer object that stores the metadata associated with the creation of temporary data. +type TemporaryDataCreatedDTO struct { + ExpirationSeconds *int `json:"expirationSeconds,omitempty"` + Origin *string `json:"origin,omitempty"` + Value interface{} `json:"value,omitempty"` + ExpirationDate *azuredevops.Time `json:"expirationDate,omitempty"` + Id *uuid.UUID `json:"id,omitempty"` + Url *string `json:"url,omitempty"` +} + +// A data transfer object that stores the metadata associated with the temporary data. +type TemporaryDataDTO struct { + ExpirationSeconds *int `json:"expirationSeconds,omitempty"` + Origin *string `json:"origin,omitempty"` + Value interface{} `json:"value,omitempty"` +} + +// Updateable properties for a WebApiTeam. +type UpdateTeam struct { + // New description for the team. + Description *string `json:"description,omitempty"` + // New name for the team. + Name *string `json:"name,omitempty"` +} + +type WebApiConnectedService struct { + Url *string `json:"url,omitempty"` + // The user who did the OAuth authentication to created this service + AuthenticatedBy *webapi.IdentityRef `json:"authenticatedBy,omitempty"` + // Extra description on the service. + Description *string `json:"description,omitempty"` + // Friendly Name of service connection + FriendlyName *string `json:"friendlyName,omitempty"` + // Id/Name of the connection service. For Ex: Subscription Id for Azure Connection + Id *string `json:"id,omitempty"` + // The kind of service. + Kind *string `json:"kind,omitempty"` + // The project associated with this service + Project *TeamProjectReference `json:"project,omitempty"` + // Optional uri to connect directly to the service such as https://windows.azure.com + ServiceUri *string `json:"serviceUri,omitempty"` +} + +type WebApiConnectedServiceDetails struct { + Id *string `json:"id,omitempty"` + Url *string `json:"url,omitempty"` + // Meta data for service connection + ConnectedServiceMetaData *WebApiConnectedService `json:"connectedServiceMetaData,omitempty"` + // Credential info + CredentialsXml *string `json:"credentialsXml,omitempty"` + // Optional uri to connect directly to the service such as https://windows.azure.com + EndPoint *string `json:"endPoint,omitempty"` +} + +type WebApiConnectedServiceRef struct { + Id *string `json:"id,omitempty"` + Url *string `json:"url,omitempty"` +} + +// The representation of data needed to create a tag definition which is sent across the wire. +type WebApiCreateTagRequestData struct { + // Name of the tag definition that will be created. + Name *string `json:"name,omitempty"` +} + +type WebApiProject struct { + // Project abbreviation. + Abbreviation *string `json:"abbreviation,omitempty"` + // Url to default team identity image. + DefaultTeamImageUrl *string `json:"defaultTeamImageUrl,omitempty"` + // The project's description (if any). + Description *string `json:"description,omitempty"` + // Project identifier. + Id *uuid.UUID `json:"id,omitempty"` + // Project last update time. + LastUpdateTime *azuredevops.Time `json:"lastUpdateTime,omitempty"` + // Project name. + Name *string `json:"name,omitempty"` + // Project revision. + Revision *uint64 `json:"revision,omitempty"` + // Project state. + State *ProjectState `json:"state,omitempty"` + // Url to the full version of the object. + Url *string `json:"url,omitempty"` + // Project visibility. + Visibility *ProjectVisibility `json:"visibility,omitempty"` + // Set of capabilities this project has + Capabilities *map[string]map[string]string `json:"capabilities,omitempty"` + // Reference to collection which contains this project + Collection *WebApiProjectCollectionRef `json:"collection,omitempty"` + // Default team for this project + DefaultTeam *WebApiTeamRef `json:"defaultTeam,omitempty"` +} + +type WebApiProjectCollection struct { + // Collection Tfs Url (Host Url) + CollectionUrl *string `json:"collectionUrl,omitempty"` + // Collection Guid + Id *uuid.UUID `json:"id,omitempty"` + // Collection Name + Name *string `json:"name,omitempty"` + // Collection REST Url + Url *string `json:"url,omitempty"` + // Project collection description + Description *string `json:"description,omitempty"` + // Project collection state + State *string `json:"state,omitempty"` +} + +type WebApiProjectCollectionRef struct { + // Collection Tfs Url (Host Url) + CollectionUrl *string `json:"collectionUrl,omitempty"` + // Collection Guid + Id *uuid.UUID `json:"id,omitempty"` + // Collection Name + Name *string `json:"name,omitempty"` + // Collection REST Url + Url *string `json:"url,omitempty"` +} + +// The representation of a tag definition which is sent across the wire. +type WebApiTagDefinition struct { + // Whether or not the tag definition is active. + Active *bool `json:"active,omitempty"` + // ID of the tag definition. + Id *uuid.UUID `json:"id,omitempty"` + // The name of the tag definition. + Name *string `json:"name,omitempty"` + // Resource URL for the Tag Definition. + Url *string `json:"url,omitempty"` +} + +type WebApiTeam struct { + // Team (Identity) Guid. A Team Foundation ID. + Id *uuid.UUID `json:"id,omitempty"` + // Team name + Name *string `json:"name,omitempty"` + // Team REST API Url + Url *string `json:"url,omitempty"` + // Team description + Description *string `json:"description,omitempty"` + // Team identity. + Identity *identity.Identity `json:"identity,omitempty"` + // Identity REST API Url to this team + IdentityUrl *string `json:"identityUrl,omitempty"` + ProjectId *uuid.UUID `json:"projectId,omitempty"` + ProjectName *string `json:"projectName,omitempty"` +} + +type WebApiTeamRef struct { + // Team (Identity) Guid. A Team Foundation ID. + Id *uuid.UUID `json:"id,omitempty"` + // Team name + Name *string `json:"name,omitempty"` + // Team REST API Url + Url *string `json:"url,omitempty"` +} diff --git a/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/delegatedauthorization/models.go b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/delegatedauthorization/models.go new file mode 100644 index 000000000..5bee22b9f --- /dev/null +++ b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/delegatedauthorization/models.go @@ -0,0 +1,368 @@ +// -------------------------------------------------------------------------------------------- +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// -------------------------------------------------------------------------------------------- +// Generated file, DO NOT EDIT +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// -------------------------------------------------------------------------------------------- + +package delegatedauthorization + +import ( + "github.com/google/uuid" + "github.com/microsoft/azure-devops-go-api/azuredevops/v7" + "github.com/microsoft/azure-devops-go-api/azuredevops/v7/webapi" +) + +type AccessTokenResult struct { + AccessToken *webapi.JsonWebToken `json:"accessToken,omitempty"` + AccessTokenError *TokenError `json:"accessTokenError,omitempty"` + AuthorizationId *uuid.UUID `json:"authorizationId,omitempty"` + ErrorDescription *string `json:"errorDescription,omitempty"` + HasError *bool `json:"hasError,omitempty"` + IsFirstPartyClient *bool `json:"isFirstPartyClient,omitempty"` + RefreshToken *RefreshTokenGrant `json:"refreshToken,omitempty"` + Scope *string `json:"scope,omitempty"` + TokenType *string `json:"tokenType,omitempty"` + ValidTo *azuredevops.Time `json:"validTo,omitempty"` +} + +type Authorization struct { + AccessIssued *azuredevops.Time `json:"accessIssued,omitempty"` + Audience *string `json:"audience,omitempty"` + AuthorizationId *uuid.UUID `json:"authorizationId,omitempty"` + IdentityId *uuid.UUID `json:"identityId,omitempty"` + IsAccessUsed *bool `json:"isAccessUsed,omitempty"` + IsValid *bool `json:"isValid,omitempty"` + RedirectUri *string `json:"redirectUri,omitempty"` + RegistrationId *uuid.UUID `json:"registrationId,omitempty"` + Scopes *string `json:"scopes,omitempty"` + Source *string `json:"source,omitempty"` + ValidFrom *azuredevops.Time `json:"validFrom,omitempty"` + ValidTo *azuredevops.Time `json:"validTo,omitempty"` +} + +type AuthorizationDecision struct { + Authorization *Authorization `json:"authorization,omitempty"` + AuthorizationError *AuthorizationError `json:"authorizationError,omitempty"` + AuthorizationGrant *AuthorizationGrant `json:"authorizationGrant,omitempty"` + HasError *bool `json:"hasError,omitempty"` + IsAuthorized *bool `json:"isAuthorized,omitempty"` +} + +type AuthorizationDescription struct { + ClientRegistration *Registration `json:"clientRegistration,omitempty"` + HasError *bool `json:"hasError,omitempty"` + InitiationError *InitiationError `json:"initiationError,omitempty"` + ScopeDescriptions *[]AuthorizationScopeDescription `json:"scopeDescriptions,omitempty"` +} + +type AuthorizationDetails struct { + Authorization *Authorization `json:"authorization,omitempty"` + ClientRegistration *Registration `json:"clientRegistration,omitempty"` + ScopeDescriptions *[]AuthorizationScopeDescription `json:"scopeDescriptions,omitempty"` +} + +type AuthorizationError string + +type authorizationErrorValuesType struct { + None AuthorizationError + ClientIdRequired AuthorizationError + InvalidClientId AuthorizationError + ResponseTypeRequired AuthorizationError + ResponseTypeNotSupported AuthorizationError + ScopeRequired AuthorizationError + InvalidScope AuthorizationError + RedirectUriRequired AuthorizationError + InsecureRedirectUri AuthorizationError + InvalidRedirectUri AuthorizationError + InvalidUserId AuthorizationError + InvalidUserType AuthorizationError + AccessDenied AuthorizationError +} + +var AuthorizationErrorValues = authorizationErrorValuesType{ + None: "none", + ClientIdRequired: "clientIdRequired", + InvalidClientId: "invalidClientId", + ResponseTypeRequired: "responseTypeRequired", + ResponseTypeNotSupported: "responseTypeNotSupported", + ScopeRequired: "scopeRequired", + InvalidScope: "invalidScope", + RedirectUriRequired: "redirectUriRequired", + InsecureRedirectUri: "insecureRedirectUri", + InvalidRedirectUri: "invalidRedirectUri", + InvalidUserId: "invalidUserId", + InvalidUserType: "invalidUserType", + AccessDenied: "accessDenied", +} + +type AuthorizationGrant struct { + GrantType *GrantType `json:"grantType,omitempty"` +} + +type AuthorizationScopeDescription struct { + Description *string `json:"description,omitempty"` + Market *string `json:"market,omitempty"` + Title *string `json:"title,omitempty"` +} + +type ClientType string + +type clientTypeValuesType struct { + Confidential ClientType + Public ClientType + MediumTrust ClientType + HighTrust ClientType + FullTrust ClientType + Application ClientType +} + +var ClientTypeValues = clientTypeValuesType{ + Confidential: "confidential", + Public: "public", + MediumTrust: "mediumTrust", + HighTrust: "highTrust", + FullTrust: "fullTrust", + Application: "application", +} + +type GrantType string + +type grantTypeValuesType struct { + None GrantType + JwtBearer GrantType + RefreshToken GrantType + Implicit GrantType + ClientCredentials GrantType +} + +var GrantTypeValues = grantTypeValuesType{ + None: "none", + JwtBearer: "jwtBearer", + RefreshToken: "refreshToken", + Implicit: "implicit", + ClientCredentials: "clientCredentials", +} + +type HostAuthorization struct { + HostId *uuid.UUID `json:"hostId,omitempty"` + Id *uuid.UUID `json:"id,omitempty"` + IsValid *bool `json:"isValid,omitempty"` + RegistrationId *uuid.UUID `json:"registrationId,omitempty"` +} + +type HostAuthorizationDecision struct { + ClientType *ClientType `json:"clientType,omitempty"` + HasError *bool `json:"hasError,omitempty"` + HostAuthorizationError *HostAuthorizationError `json:"hostAuthorizationError,omitempty"` + HostAuthorizationId *uuid.UUID `json:"hostAuthorizationId,omitempty"` + RegistrationId *uuid.UUID `json:"registrationId,omitempty"` + RegistrationName *string `json:"registrationName,omitempty"` + SetupUri *string `json:"setupUri,omitempty"` +} + +type HostAuthorizationError string + +type hostAuthorizationErrorValuesType struct { + None HostAuthorizationError + ClientIdRequired HostAuthorizationError + AccessDenied HostAuthorizationError + FailedToAuthorizeHost HostAuthorizationError + ClientIdNotFound HostAuthorizationError + InvalidClientId HostAuthorizationError +} + +var HostAuthorizationErrorValues = hostAuthorizationErrorValuesType{ + None: "none", + ClientIdRequired: "clientIdRequired", + AccessDenied: "accessDenied", + FailedToAuthorizeHost: "failedToAuthorizeHost", + ClientIdNotFound: "clientIdNotFound", + InvalidClientId: "invalidClientId", +} + +type InitiationError string + +type initiationErrorValuesType struct { + None InitiationError + ClientIdRequired InitiationError + InvalidClientId InitiationError + ResponseTypeRequired InitiationError + ResponseTypeNotSupported InitiationError + ScopeRequired InitiationError + InvalidScope InitiationError + RedirectUriRequired InitiationError + InsecureRedirectUri InitiationError + InvalidRedirectUri InitiationError +} + +var InitiationErrorValues = initiationErrorValuesType{ + None: "none", + ClientIdRequired: "clientIdRequired", + InvalidClientId: "invalidClientId", + ResponseTypeRequired: "responseTypeRequired", + ResponseTypeNotSupported: "responseTypeNotSupported", + ScopeRequired: "scopeRequired", + InvalidScope: "invalidScope", + RedirectUriRequired: "redirectUriRequired", + InsecureRedirectUri: "insecureRedirectUri", + InvalidRedirectUri: "invalidRedirectUri", +} + +type RefreshTokenGrant struct { + GrantType *GrantType `json:"grantType,omitempty"` + Jwt *webapi.JsonWebToken `json:"jwt,omitempty"` +} + +type Registration struct { + AccessHash *string `json:"accessHash,omitempty"` + ClientType *ClientType `json:"clientType,omitempty"` + IdentityId *uuid.UUID `json:"identityId,omitempty"` + Issuer *string `json:"issuer,omitempty"` + IsValid *bool `json:"isValid,omitempty"` + IsWellKnown *bool `json:"isWellKnown,omitempty"` + OrganizationLocation *string `json:"organizationLocation,omitempty"` + OrganizationName *string `json:"organizationName,omitempty"` + // Raw cert data string from public key. This will be used for authenticating medium trust clients. + PublicKey *string `json:"publicKey,omitempty"` + RedirectUris *[]string `json:"redirectUris,omitempty"` + RegistrationDescription *string `json:"registrationDescription,omitempty"` + RegistrationId *uuid.UUID `json:"registrationId,omitempty"` + RegistrationLocation *string `json:"registrationLocation,omitempty"` + RegistrationLogoSecureLocation *string `json:"registrationLogoSecureLocation,omitempty"` + RegistrationName *string `json:"registrationName,omitempty"` + RegistrationPrivacyStatementLocation *string `json:"registrationPrivacyStatementLocation,omitempty"` + RegistrationTermsOfServiceLocation *string `json:"registrationTermsOfServiceLocation,omitempty"` + ResponseTypes *string `json:"responseTypes,omitempty"` + Scopes *string `json:"scopes,omitempty"` + Secret *string `json:"secret,omitempty"` + SecretValidTo *azuredevops.Time `json:"secretValidTo,omitempty"` + SecretVersionId *uuid.UUID `json:"secretVersionId,omitempty"` + SetupUri *string `json:"setupUri,omitempty"` + TenantIds *[]uuid.UUID `json:"tenantIds,omitempty"` + ValidFrom *azuredevops.Time `json:"validFrom,omitempty"` +} + +type ResponseType string + +type responseTypeValuesType struct { + None ResponseType + Assertion ResponseType + IdToken ResponseType + TenantPicker ResponseType + SignoutToken ResponseType + AppToken ResponseType + Code ResponseType +} + +var ResponseTypeValues = responseTypeValuesType{ + None: "none", + Assertion: "assertion", + IdToken: "idToken", + TenantPicker: "tenantPicker", + SignoutToken: "signoutToken", + AppToken: "appToken", + Code: "code", +} + +// Represents a session token used to access Azure DevOps resources +type SessionToken struct { + AccessId *uuid.UUID `json:"accessId,omitempty"` + // This is populated when user requests a compact token. The alternate token value is self describing token. + AlternateToken *string `json:"alternateToken,omitempty"` + AuthorizationId *uuid.UUID `json:"authorizationId,omitempty"` + Claims *map[string]string `json:"claims,omitempty"` + ClientId *uuid.UUID `json:"clientId,omitempty"` + DisplayName *string `json:"displayName,omitempty"` + HostAuthorizationId *uuid.UUID `json:"hostAuthorizationId,omitempty"` + IsPublic *bool `json:"isPublic,omitempty"` + IsValid *bool `json:"isValid,omitempty"` + PublicData *string `json:"publicData,omitempty"` + Scope *string `json:"scope,omitempty"` + Source *string `json:"source,omitempty"` + TargetAccounts *[]uuid.UUID `json:"targetAccounts,omitempty"` + // This is computed and not returned in Get queries + Token *string `json:"token,omitempty"` + UserId *uuid.UUID `json:"userId,omitempty"` + ValidFrom *azuredevops.Time `json:"validFrom,omitempty"` + ValidTo *azuredevops.Time `json:"validTo,omitempty"` +} + +type TokenError string + +type tokenErrorValuesType struct { + None TokenError + GrantTypeRequired TokenError + AuthorizationGrantRequired TokenError + ClientSecretRequired TokenError + RedirectUriRequired TokenError + InvalidAuthorizationGrant TokenError + InvalidAuthorizationScopes TokenError + InvalidRefreshToken TokenError + AuthorizationNotFound TokenError + AuthorizationGrantExpired TokenError + AccessAlreadyIssued TokenError + InvalidRedirectUri TokenError + AccessTokenNotFound TokenError + InvalidAccessToken TokenError + AccessTokenAlreadyRefreshed TokenError + InvalidClientSecret TokenError + ClientSecretExpired TokenError + ServerError TokenError + AccessDenied TokenError + AccessTokenKeyRequired TokenError + InvalidAccessTokenKey TokenError + FailedToGetAccessToken TokenError + InvalidClientId TokenError + InvalidClient TokenError + InvalidValidTo TokenError + InvalidUserId TokenError + FailedToIssueAccessToken TokenError + AuthorizationGrantScopeMissing TokenError + InvalidPublicAccessTokenKey TokenError + InvalidPublicAccessToken TokenError + PublicFeatureFlagNotEnabled TokenError + SshPolicyDisabled TokenError + HostAuthorizationNotFound TokenError + HostAuthorizationIsNotValid TokenError + InvalidScope TokenError +} + +var TokenErrorValues = tokenErrorValuesType{ + None: "none", + GrantTypeRequired: "grantTypeRequired", + AuthorizationGrantRequired: "authorizationGrantRequired", + ClientSecretRequired: "clientSecretRequired", + RedirectUriRequired: "redirectUriRequired", + InvalidAuthorizationGrant: "invalidAuthorizationGrant", + InvalidAuthorizationScopes: "invalidAuthorizationScopes", + InvalidRefreshToken: "invalidRefreshToken", + AuthorizationNotFound: "authorizationNotFound", + AuthorizationGrantExpired: "authorizationGrantExpired", + AccessAlreadyIssued: "accessAlreadyIssued", + InvalidRedirectUri: "invalidRedirectUri", + AccessTokenNotFound: "accessTokenNotFound", + InvalidAccessToken: "invalidAccessToken", + AccessTokenAlreadyRefreshed: "accessTokenAlreadyRefreshed", + InvalidClientSecret: "invalidClientSecret", + ClientSecretExpired: "clientSecretExpired", + ServerError: "serverError", + AccessDenied: "accessDenied", + AccessTokenKeyRequired: "accessTokenKeyRequired", + InvalidAccessTokenKey: "invalidAccessTokenKey", + FailedToGetAccessToken: "failedToGetAccessToken", + InvalidClientId: "invalidClientId", + InvalidClient: "invalidClient", + InvalidValidTo: "invalidValidTo", + InvalidUserId: "invalidUserId", + FailedToIssueAccessToken: "failedToIssueAccessToken", + AuthorizationGrantScopeMissing: "authorizationGrantScopeMissing", + InvalidPublicAccessTokenKey: "invalidPublicAccessTokenKey", + InvalidPublicAccessToken: "invalidPublicAccessToken", + PublicFeatureFlagNotEnabled: "publicFeatureFlagNotEnabled", + SshPolicyDisabled: "sshPolicyDisabled", + HostAuthorizationNotFound: "hostAuthorizationNotFound", + HostAuthorizationIsNotValid: "hostAuthorizationIsNotValid", + InvalidScope: "invalidScope", +} diff --git a/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/errors.go b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/errors.go new file mode 100644 index 000000000..e7cf6a377 --- /dev/null +++ b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/errors.go @@ -0,0 +1,17 @@ +package azuredevops + +type ArgumentNilError struct { + ArgumentName string +} + +func (e ArgumentNilError) Error() string { + return "Argument " + e.ArgumentName + " can not be nil" +} + +type ArgumentNilOrEmptyError struct { + ArgumentName string +} + +func (e ArgumentNilOrEmptyError) Error() string { + return "Argument " + e.ArgumentName + " can not be nil or empty" +} diff --git a/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/forminput/models.go b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/forminput/models.go new file mode 100644 index 000000000..ca53bf4e2 --- /dev/null +++ b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/forminput/models.go @@ -0,0 +1,194 @@ +// -------------------------------------------------------------------------------------------- +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// -------------------------------------------------------------------------------------------- +// Generated file, DO NOT EDIT +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// -------------------------------------------------------------------------------------------- + +package forminput + +import ( + "math/big" +) + +// Enumerates data types that are supported as subscription input values. +type InputDataType string + +type inputDataTypeValuesType struct { + None InputDataType + String InputDataType + Number InputDataType + Boolean InputDataType + Guid InputDataType + Uri InputDataType +} + +var InputDataTypeValues = inputDataTypeValuesType{ + // No data type is specified. + None: "none", + // Represents a textual value. + String: "string", + // Represents a numeric value. + Number: "number", + // Represents a value of true or false. + Boolean: "boolean", + // Represents a Guid. + Guid: "guid", + // Represents a URI. + Uri: "uri", +} + +// Describes an input for subscriptions. +type InputDescriptor struct { + // The ids of all inputs that the value of this input is dependent on. + DependencyInputIds *[]string `json:"dependencyInputIds,omitempty"` + // Description of what this input is used for + Description *string `json:"description,omitempty"` + // The group localized name to which this input belongs and can be shown as a header for the container that will include all the inputs in the group. + GroupName *string `json:"groupName,omitempty"` + // If true, the value information for this input is dynamic and should be fetched when the value of dependency inputs change. + HasDynamicValueInformation *bool `json:"hasDynamicValueInformation,omitempty"` + // Identifier for the subscription input + Id *string `json:"id,omitempty"` + // Mode in which the value of this input should be entered + InputMode *InputMode `json:"inputMode,omitempty"` + // Gets whether this input is confidential, such as for a password or application key + IsConfidential *bool `json:"isConfidential,omitempty"` + // Localized name which can be shown as a label for the subscription input + Name *string `json:"name,omitempty"` + // Custom properties for the input which can be used by the service provider + Properties *map[string]interface{} `json:"properties,omitempty"` + // Underlying data type for the input value. When this value is specified, InputMode, Validation and Values are optional. + Type *string `json:"type,omitempty"` + // Gets whether this input is included in the default generated action description. + UseInDefaultDescription *bool `json:"useInDefaultDescription,omitempty"` + // Information to use to validate this input's value + Validation *InputValidation `json:"validation,omitempty"` + // A hint for input value. It can be used in the UI as the input placeholder. + ValueHint *string `json:"valueHint,omitempty"` + // Information about possible values for this input + Values *InputValues `json:"values,omitempty"` +} + +// Defines a filter for subscription inputs. The filter matches a set of inputs if any (one or more) of the groups evaluates to true. +type InputFilter struct { + // Groups of input filter expressions. This filter matches a set of inputs if any (one or more) of the groups evaluates to true. + Conditions *[]InputFilterCondition `json:"conditions,omitempty"` +} + +// An expression which can be applied to filter a list of subscription inputs +type InputFilterCondition struct { + // Whether or not to do a case sensitive match + CaseSensitive *bool `json:"caseSensitive,omitempty"` + // The Id of the input to filter on + InputId *string `json:"inputId,omitempty"` + // The "expected" input value to compare with the actual input value + InputValue *string `json:"inputValue,omitempty"` + // The operator applied between the expected and actual input value + Operator *InputFilterOperator `json:"operator,omitempty"` +} + +type InputFilterOperator string + +type inputFilterOperatorValuesType struct { + Equals InputFilterOperator + NotEquals InputFilterOperator +} + +var InputFilterOperatorValues = inputFilterOperatorValuesType{ + Equals: "equals", + NotEquals: "notEquals", +} + +// Mode in which a subscription input should be entered (in a UI) +type InputMode string + +type inputModeValuesType struct { + None InputMode + TextBox InputMode + PasswordBox InputMode + Combo InputMode + RadioButtons InputMode + CheckBox InputMode + TextArea InputMode +} + +var InputModeValues = inputModeValuesType{ + // This input should not be shown in the UI + None: "none", + // An input text box should be shown + TextBox: "textBox", + // An password input box should be shown + PasswordBox: "passwordBox", + // A select/combo control should be shown + Combo: "combo", + // Radio buttons should be shown + RadioButtons: "radioButtons", + // Checkbox should be shown(for true/false values) + CheckBox: "checkBox", + // A multi-line text area should be shown + TextArea: "textArea", +} + +// Describes what values are valid for a subscription input +type InputValidation struct { + // Gets or sets the data type to validate. + DataType *InputDataType `json:"dataType,omitempty"` + // Gets or sets if this is a required field. + IsRequired *bool `json:"isRequired,omitempty"` + // Gets or sets the maximum length of this descriptor. + MaxLength *int `json:"maxLength,omitempty"` + // Gets or sets the minimum value for this descriptor. + MaxValue *big.Float `json:"maxValue,omitempty"` + // Gets or sets the minimum length of this descriptor. + MinLength *int `json:"minLength,omitempty"` + // Gets or sets the minimum value for this descriptor. + MinValue *big.Float `json:"minValue,omitempty"` + // Gets or sets the pattern to validate. + Pattern *string `json:"pattern,omitempty"` + // Gets or sets the error on pattern mismatch. + PatternMismatchErrorMessage *string `json:"patternMismatchErrorMessage,omitempty"` +} + +// Information about a single value for an input +type InputValue struct { + // Any other data about this input + Data *map[string]interface{} `json:"data,omitempty"` + // The text to show for the display of this value + DisplayValue *string `json:"displayValue,omitempty"` + // The value to store for this input + Value *string `json:"value,omitempty"` +} + +// Information about the possible/allowed values for a given subscription input +type InputValues struct { + // The default value to use for this input + DefaultValue *string `json:"defaultValue,omitempty"` + // Errors encountered while computing dynamic values. + Error *InputValuesError `json:"error,omitempty"` + // The id of the input + InputId *string `json:"inputId,omitempty"` + // Should this input be disabled + IsDisabled *bool `json:"isDisabled,omitempty"` + // Should the value be restricted to one of the values in the PossibleValues (True) or are the values in PossibleValues just a suggestion (False) + IsLimitedToPossibleValues *bool `json:"isLimitedToPossibleValues,omitempty"` + // Should this input be made read-only + IsReadOnly *bool `json:"isReadOnly,omitempty"` + // Possible values that this input can take + PossibleValues *[]InputValue `json:"possibleValues,omitempty"` +} + +// Error information related to a subscription input value. +type InputValuesError struct { + // The error message. + Message *string `json:"message,omitempty"` +} + +type InputValuesQuery struct { + CurrentValues *map[string]string `json:"currentValues,omitempty"` + // The input values to return on input, and the result from the consumer on output. + InputValues *[]InputValues `json:"inputValues,omitempty"` + // Subscription containing information about the publisher/consumer and the current input values + Resource interface{} `json:"resource,omitempty"` +} diff --git a/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/git/client.go b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/git/client.go new file mode 100644 index 000000000..aaca55418 --- /dev/null +++ b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/git/client.go @@ -0,0 +1,5852 @@ +// -------------------------------------------------------------------------------------------- +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// -------------------------------------------------------------------------------------------- +// Generated file, DO NOT EDIT +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// -------------------------------------------------------------------------------------------- + +package git + +import ( + "bytes" + "context" + "encoding/json" + "github.com/google/uuid" + "github.com/microsoft/azure-devops-go-api/azuredevops/v7" + "github.com/microsoft/azure-devops-go-api/azuredevops/v7/core" + "github.com/microsoft/azure-devops-go-api/azuredevops/v7/policy" + "github.com/microsoft/azure-devops-go-api/azuredevops/v7/webapi" + "io" + "net/http" + "net/url" + "strconv" +) + +var ResourceAreaId, _ = uuid.Parse("4e080c62-fa21-4fbc-8fef-2a10a2b38049") + +type Client interface { + // [Preview API] Create an annotated tag. + CreateAnnotatedTag(context.Context, CreateAnnotatedTagArgs) (*GitAnnotatedTag, error) + // [Preview API] Attach a new file to a pull request. + CreateAttachment(context.Context, CreateAttachmentArgs) (*Attachment, error) + // [Preview API] Create a comment on a specific thread in a pull request (up to 500 comments can be created per thread). + CreateComment(context.Context, CreateCommentArgs) (*Comment, error) + // [Preview API] Create Git commit status. + CreateCommitStatus(context.Context, CreateCommitStatusArgs) (*GitStatus, error) + // [Preview API] Creates a ref favorite + CreateFavorite(context.Context, CreateFavoriteArgs) (*GitRefFavorite, error) + // [Preview API] Request that another repository's refs be fetched into this one. It syncs two existing forks. To create a fork, please see the repositories endpoint + CreateForkSyncRequest(context.Context, CreateForkSyncRequestArgs) (*GitForkSyncRequest, error) + // [Preview API] Cherry pick a specific commit or commits that are associated to a pull request into a new branch. + CreateCherryPick(context.Context, CreateCherryPickArgs) (*GitCherryPick, error) + // [Preview API] Create an import request. + CreateImportRequest(context.Context, CreateImportRequestArgs) (*GitImportRequest, error) + // [Preview API] Add a like on a comment. + CreateLike(context.Context, CreateLikeArgs) error + // [Preview API] Request a git merge operation. Currently we support merging only 2 commits. + CreateMergeRequest(context.Context, CreateMergeRequestArgs) (*GitMerge, error) + // [Preview API] Create a pull request. + CreatePullRequest(context.Context, CreatePullRequestArgs) (*GitPullRequest, error) + // [Preview API] Create a pull request status on the iteration. This operation will have the same result as Create status on pull request with specified iteration ID in the request body. + CreatePullRequestIterationStatus(context.Context, CreatePullRequestIterationStatusArgs) (*GitPullRequestStatus, error) + // [Preview API] Create a label for a specified pull request. The only required field is the name of the new label. + CreatePullRequestLabel(context.Context, CreatePullRequestLabelArgs) (*core.WebApiTagDefinition, error) + // [Preview API] Add a reviewer to a pull request or cast a vote. + CreatePullRequestReviewer(context.Context, CreatePullRequestReviewerArgs) (*IdentityRefWithVote, error) + // [Preview API] Add reviewers to a pull request. + CreatePullRequestReviewers(context.Context, CreatePullRequestReviewersArgs) (*[]IdentityRefWithVote, error) + // [Preview API] Create a pull request status. + CreatePullRequestStatus(context.Context, CreatePullRequestStatusArgs) (*GitPullRequestStatus, error) + // [Preview API] Push changes to the repository. + CreatePush(context.Context, CreatePushArgs) (*GitPush, error) + // [Preview API] Create a git repository in a team project. + CreateRepository(context.Context, CreateRepositoryArgs) (*GitRepository, error) + // [Preview API] Starts the operation to create a new branch which reverts changes introduced by either a specific commit or commits that are associated to a pull request. + CreateRevert(context.Context, CreateRevertArgs) (*GitRevert, error) + // [Preview API] Create a thread in a pull request. + CreateThread(context.Context, CreateThreadArgs) (*GitPullRequestCommentThread, error) + // [Preview API] Add an unmaterialized identity to the reviewers of a pull request. + CreateUnmaterializedPullRequestReviewer(context.Context, CreateUnmaterializedPullRequestReviewerArgs) (*IdentityRefWithVote, error) + // [Preview API] Delete a pull request attachment. + DeleteAttachment(context.Context, DeleteAttachmentArgs) error + // [Preview API] Delete a comment associated with a specific thread in a pull request. + DeleteComment(context.Context, DeleteCommentArgs) error + // [Preview API] Delete a like on a comment. + DeleteLike(context.Context, DeleteLikeArgs) error + // [Preview API] Delete pull request iteration status. + DeletePullRequestIterationStatus(context.Context, DeletePullRequestIterationStatusArgs) error + // [Preview API] Removes a label from the set of those assigned to the pull request. + DeletePullRequestLabels(context.Context, DeletePullRequestLabelsArgs) error + // [Preview API] Remove a reviewer from a pull request. + DeletePullRequestReviewer(context.Context, DeletePullRequestReviewerArgs) error + // [Preview API] Delete pull request status. + DeletePullRequestStatus(context.Context, DeletePullRequestStatusArgs) error + // [Preview API] Deletes the refs favorite specified + DeleteRefFavorite(context.Context, DeleteRefFavoriteArgs) error + // [Preview API] Delete a git repository + DeleteRepository(context.Context, DeleteRepositoryArgs) error + // [Preview API] Destroy (hard delete) a soft-deleted Git repository. + DeleteRepositoryFromRecycleBin(context.Context, DeleteRepositoryFromRecycleBinArgs) error + // [Preview API] Get an annotated tag. + GetAnnotatedTag(context.Context, GetAnnotatedTagArgs) (*GitAnnotatedTag, error) + // [Preview API] Get the file content of a pull request attachment. + GetAttachmentContent(context.Context, GetAttachmentContentArgs) (io.ReadCloser, error) + // [Preview API] Get a list of files attached to a given pull request. + GetAttachments(context.Context, GetAttachmentsArgs) (*[]Attachment, error) + // [Preview API] Get the file content of a pull request attachment. + GetAttachmentZip(context.Context, GetAttachmentZipArgs) (io.ReadCloser, error) + // [Preview API] Get a single blob. + GetBlob(context.Context, GetBlobArgs) (*GitBlobRef, error) + // [Preview API] Get a single blob. + GetBlobContent(context.Context, GetBlobContentArgs) (io.ReadCloser, error) + // [Preview API] Gets one or more blobs in a zip file download. + GetBlobsZip(context.Context, GetBlobsZipArgs) (io.ReadCloser, error) + // [Preview API] Get a single blob. + GetBlobZip(context.Context, GetBlobZipArgs) (io.ReadCloser, error) + // [Preview API] Retrieve statistics about a single branch. + GetBranch(context.Context, GetBranchArgs) (*GitBranchStats, error) + // [Preview API] Retrieve statistics about all branches within a repository. + GetBranches(context.Context, GetBranchesArgs) (*[]GitBranchStats, error) + // [Preview API] Retrieve a comment associated with a specific thread in a pull request. + GetComment(context.Context, GetCommentArgs) (*Comment, error) + // [Preview API] Retrieve all comments associated with a specific thread in a pull request. + GetComments(context.Context, GetCommentsArgs) (*[]Comment, error) + // [Preview API] Retrieve a particular commit. + GetCommit(context.Context, GetCommitArgs) (*GitCommit, error) + // [Preview API] Find the closest common commit (the merge base) between base and target commits, and get the diff between either the base and target commits or common and target commits. + GetCommitDiffs(context.Context, GetCommitDiffsArgs) (*GitCommitDiffs, error) + // [Preview API] Retrieve git commits for a project + GetCommits(context.Context, GetCommitsArgs) (*[]GitCommitRef, error) + // [Preview API] Retrieve git commits for a project matching the search criteria + GetCommitsBatch(context.Context, GetCommitsBatchArgs) (*[]GitCommitRef, error) + // [Preview API] Retrieve deleted git repositories. + GetDeletedRepositories(context.Context, GetDeletedRepositoriesArgs) (*[]GitDeletedRepository, error) + // [Preview API] Retrieve all forks of a repository in the collection. + GetForks(context.Context, GetForksArgs) (*[]GitRepositoryRef, error) + // [Preview API] Get a specific fork sync operation's details. + GetForkSyncRequest(context.Context, GetForkSyncRequestArgs) (*GitForkSyncRequest, error) + // [Preview API] Retrieve all requested fork sync operations on this repository. + GetForkSyncRequests(context.Context, GetForkSyncRequestsArgs) (*[]GitForkSyncRequest, error) + // [Preview API] Retrieve changes for a particular commit. + GetChanges(context.Context, GetChangesArgs) (*GitCommitChanges, error) + // [Preview API] Retrieve information about a cherry pick operation by cherry pick Id. + GetCherryPick(context.Context, GetCherryPickArgs) (*GitCherryPick, error) + // [Preview API] Retrieve information about a cherry pick operation for a specific branch. This operation is expensive due to the underlying object structure, so this API only looks at the 1000 most recent cherry pick operations. + GetCherryPickForRefName(context.Context, GetCherryPickForRefNameArgs) (*GitCherryPick, error) + // [Preview API] Retrieve a particular import request. + GetImportRequest(context.Context, GetImportRequestArgs) (*GitImportRequest, error) + // [Preview API] Get Item Metadata and/or Content for a single item. The download parameter is to indicate whether the content should be available as a download or just sent as a stream in the response. Doesn't apply to zipped content, which is always returned as a download. + GetItem(context.Context, GetItemArgs) (*GitItem, error) + // [Preview API] Get Item Metadata and/or Content for a single item. The download parameter is to indicate whether the content should be available as a download or just sent as a stream in the response. Doesn't apply to zipped content, which is always returned as a download. + GetItemContent(context.Context, GetItemContentArgs) (io.ReadCloser, error) + // [Preview API] Get Item Metadata and/or Content for a collection of items. The download parameter is to indicate whether the content should be available as a download or just sent as a stream in the response. Doesn't apply to zipped content which is always returned as a download. + GetItems(context.Context, GetItemsArgs) (*[]GitItem, error) + // [Preview API] Post for retrieving a creating a batch out of a set of items in a repo / project given a list of paths or a long path + GetItemsBatch(context.Context, GetItemsBatchArgs) (*[][]GitItem, error) + // [Preview API] Get Item Metadata and/or Content for a single item. The download parameter is to indicate whether the content should be available as a download or just sent as a stream in the response. Doesn't apply to zipped content, which is always returned as a download. + GetItemText(context.Context, GetItemTextArgs) (io.ReadCloser, error) + // [Preview API] Get Item Metadata and/or Content for a single item. The download parameter is to indicate whether the content should be available as a download or just sent as a stream in the response. Doesn't apply to zipped content, which is always returned as a download. + GetItemZip(context.Context, GetItemZipArgs) (io.ReadCloser, error) + // [Preview API] Get likes for a comment. + GetLikes(context.Context, GetLikesArgs) (*[]webapi.IdentityRef, error) + // [Preview API] Find the merge bases of two commits, optionally across forks. If otherRepositoryId is not specified, the merge bases will only be calculated within the context of the local repositoryNameOrId. + GetMergeBases(context.Context, GetMergeBasesArgs) (*[]GitCommitRef, error) + // [Preview API] Get a specific merge operation's details. + GetMergeRequest(context.Context, GetMergeRequestArgs) (*GitMerge, error) + // [Preview API] GET Advanced Security Permission status. + GetPermission(context.Context, GetPermissionArgs) (*bool, error) + // [Preview API] Retrieve a list of policy configurations by a given set of scope/filtering criteria. + GetPolicyConfigurations(context.Context, GetPolicyConfigurationsArgs) (*GitPolicyConfigurationResponse, error) + // [Preview API] Retrieve a pull request. + GetPullRequest(context.Context, GetPullRequestArgs) (*GitPullRequest, error) + // [Preview API] Retrieve a pull request. + GetPullRequestById(context.Context, GetPullRequestByIdArgs) (*GitPullRequest, error) + // [Preview API] Get the commits for the specified pull request. + GetPullRequestCommits(context.Context, GetPullRequestCommitsArgs) (*GetPullRequestCommitsResponseValue, error) + // [Preview API] Get the specified iteration for a pull request. + GetPullRequestIteration(context.Context, GetPullRequestIterationArgs) (*GitPullRequestIteration, error) + // [Preview API] Get the commits for the specified iteration of a pull request. + GetPullRequestIterationCommits(context.Context, GetPullRequestIterationCommitsArgs) (*[]GitCommitRef, error) + // [Preview API] Retrieve the changes made in a pull request between two iterations. + GetPullRequestIterationChanges(context.Context, GetPullRequestIterationChangesArgs) (*GitPullRequestIterationChanges, error) + // [Preview API] Get the list of iterations for the specified pull request. + GetPullRequestIterations(context.Context, GetPullRequestIterationsArgs) (*[]GitPullRequestIteration, error) + // [Preview API] Get the specific pull request iteration status by ID. The status ID is unique within the pull request across all iterations. + GetPullRequestIterationStatus(context.Context, GetPullRequestIterationStatusArgs) (*GitPullRequestStatus, error) + // [Preview API] Get all the statuses associated with a pull request iteration. + GetPullRequestIterationStatuses(context.Context, GetPullRequestIterationStatusesArgs) (*[]GitPullRequestStatus, error) + // [Preview API] Retrieves a single label that has been assigned to a pull request. + GetPullRequestLabel(context.Context, GetPullRequestLabelArgs) (*core.WebApiTagDefinition, error) + // [Preview API] Get all the labels assigned to a pull request. + GetPullRequestLabels(context.Context, GetPullRequestLabelsArgs) (*[]core.WebApiTagDefinition, error) + // [Preview API] Get external properties of the pull request. + GetPullRequestProperties(context.Context, GetPullRequestPropertiesArgs) (interface{}, error) + // [Preview API] This API is used to find what pull requests are related to a given commit. It can be used to either find the pull request that created a particular merge commit or it can be used to find all pull requests that have ever merged a particular commit. The input is a list of queries which each contain a list of commits. For each commit that you search against, you will get back a dictionary of commit -> pull requests. + GetPullRequestQuery(context.Context, GetPullRequestQueryArgs) (*GitPullRequestQuery, error) + // [Preview API] Retrieve information about a particular reviewer on a pull request + GetPullRequestReviewer(context.Context, GetPullRequestReviewerArgs) (*IdentityRefWithVote, error) + // [Preview API] Retrieve the reviewers for a pull request + GetPullRequestReviewers(context.Context, GetPullRequestReviewersArgs) (*[]IdentityRefWithVote, error) + // [Preview API] Retrieve all pull requests matching a specified criteria. + GetPullRequests(context.Context, GetPullRequestsArgs) (*[]GitPullRequest, error) + // [Preview API] Retrieve all pull requests matching a specified criteria. + GetPullRequestsByProject(context.Context, GetPullRequestsByProjectArgs) (*[]GitPullRequest, error) + // [Preview API] Get the specific pull request status by ID. The status ID is unique within the pull request across all iterations. + GetPullRequestStatus(context.Context, GetPullRequestStatusArgs) (*GitPullRequestStatus, error) + // [Preview API] Get all the statuses associated with a pull request. + GetPullRequestStatuses(context.Context, GetPullRequestStatusesArgs) (*[]GitPullRequestStatus, error) + // [Preview API] Retrieve a thread in a pull request. + GetPullRequestThread(context.Context, GetPullRequestThreadArgs) (*GitPullRequestCommentThread, error) + // [Preview API] Retrieve a list of work items associated with a pull request. + GetPullRequestWorkItemRefs(context.Context, GetPullRequestWorkItemRefsArgs) (*[]webapi.ResourceRef, error) + // [Preview API] Retrieves a particular push. + GetPush(context.Context, GetPushArgs) (*GitPush, error) + // [Preview API] Retrieve a list of commits associated with a particular push. + GetPushCommits(context.Context, GetPushCommitsArgs) (*[]GitCommitRef, error) + // [Preview API] Retrieves pushes associated with the specified repository. + GetPushes(context.Context, GetPushesArgs) (*[]GitPush, error) + // [Preview API] Retrieve soft-deleted git repositories from the recycle bin. + GetRecycleBinRepositories(context.Context, GetRecycleBinRepositoriesArgs) (*[]GitDeletedRepository, error) + // [Preview API] Gets the refs favorite for a favorite Id. + GetRefFavorite(context.Context, GetRefFavoriteArgs) (*GitRefFavorite, error) + // [Preview API] Gets the refs favorites for a repo and an identity. + GetRefFavorites(context.Context, GetRefFavoritesArgs) (*[]GitRefFavorite, error) + // [Preview API] Queries the provided repository for its refs and returns them. + GetRefs(context.Context, GetRefsArgs) (*GetRefsResponseValue, error) + // [Preview API] Retrieve git repositories. + GetRepositories(context.Context, GetRepositoriesArgs) (*[]GitRepository, error) + // [Preview API] Retrieve a git repository. + GetRepository(context.Context, GetRepositoryArgs) (*GitRepository, error) + // [Preview API] Retrieve a git repository. + GetRepositoryWithParent(context.Context, GetRepositoryWithParentArgs) (*GitRepository, error) + // [Preview API] Retrieve information about a revert operation by revert Id. + GetRevert(context.Context, GetRevertArgs) (*GitRevert, error) + // [Preview API] Retrieve information about a revert operation for a specific branch. + GetRevertForRefName(context.Context, GetRevertForRefNameArgs) (*GitRevert, error) + // [Preview API] Get statuses associated with the Git commit. + GetStatuses(context.Context, GetStatusesArgs) (*[]GitStatus, error) + // [Preview API] Retrieve a pull request suggestion for a particular repository or team project. + GetSuggestions(context.Context, GetSuggestionsArgs) (*[]GitSuggestion, error) + // [Preview API] Retrieve all threads in a pull request. + GetThreads(context.Context, GetThreadsArgs) (*[]GitPullRequestCommentThread, error) + // [Preview API] The Tree endpoint returns the collection of objects underneath the specified tree. Trees are folders in a Git repository. + GetTree(context.Context, GetTreeArgs) (*GitTreeRef, error) + // [Preview API] The Tree endpoint returns the collection of objects underneath the specified tree. Trees are folders in a Git repository. + GetTreeZip(context.Context, GetTreeZipArgs) (io.ReadCloser, error) + // [Preview API] Retrieve import requests for a repository. + QueryImportRequests(context.Context, QueryImportRequestsArgs) (*[]GitImportRequest, error) + // [Preview API] Recover a soft-deleted Git repository. Recently deleted repositories go into a soft-delete state for a period of time before they are hard deleted and become unrecoverable. + RestoreRepositoryFromRecycleBin(context.Context, RestoreRepositoryFromRecycleBinArgs) (*GitRepository, error) + // [Preview API] Sends an e-mail notification about a specific pull request to a set of recipients + SharePullRequest(context.Context, SharePullRequestArgs) error + // [Preview API] Update a comment associated with a specific thread in a pull request. + UpdateComment(context.Context, UpdateCommentArgs) (*Comment, error) + // [Preview API] Retry or abandon a failed import request. + UpdateImportRequest(context.Context, UpdateImportRequestArgs) (*GitImportRequest, error) + // [Preview API] Update a pull request + UpdatePullRequest(context.Context, UpdatePullRequestArgs) (*GitPullRequest, error) + // [Preview API] Update pull request iteration statuses collection. The only supported operation type is `remove`. + UpdatePullRequestIterationStatuses(context.Context, UpdatePullRequestIterationStatusesArgs) error + // [Preview API] Create or update pull request external properties. The patch operation can be `add`, `replace` or `remove`. For `add` operation, the path can be empty. If the path is empty, the value must be a list of key value pairs. For `replace` operation, the path cannot be empty. If the path does not exist, the property will be added to the collection. For `remove` operation, the path cannot be empty. If the path does not exist, no action will be performed. + UpdatePullRequestProperties(context.Context, UpdatePullRequestPropertiesArgs) (interface{}, error) + // [Preview API] Edit a reviewer entry. These fields are patchable: isFlagged, hasDeclined + UpdatePullRequestReviewer(context.Context, UpdatePullRequestReviewerArgs) (*IdentityRefWithVote, error) + // [Preview API] Reset the votes of multiple reviewers on a pull request. NOTE: This endpoint only supports updating votes, but does not support updating required reviewers (use policy) or display names. + UpdatePullRequestReviewers(context.Context, UpdatePullRequestReviewersArgs) error + // [Preview API] Update pull request statuses collection. The only supported operation type is `remove`. + UpdatePullRequestStatuses(context.Context, UpdatePullRequestStatusesArgs) error + // [Preview API] Lock or Unlock a branch. + UpdateRef(context.Context, UpdateRefArgs) (*GitRef, error) + // [Preview API] Creating, updating, or deleting refs(branches). + UpdateRefs(context.Context, UpdateRefsArgs) (*[]GitRefUpdateResult, error) + // [Preview API] Updates the Git repository with either a new repo name or a new default branch. + UpdateRepository(context.Context, UpdateRepositoryArgs) (*GitRepository, error) + // [Preview API] Update a thread in a pull request. + UpdateThread(context.Context, UpdateThreadArgs) (*GitPullRequestCommentThread, error) +} + +type ClientImpl struct { + Client azuredevops.Client +} + +func NewClient(ctx context.Context, connection *azuredevops.Connection) (Client, error) { + client, err := connection.GetClientByResourceAreaId(ctx, ResourceAreaId) + if err != nil { + return nil, err + } + return &ClientImpl{ + Client: *client, + }, nil +} + +// [Preview API] Create an annotated tag. +func (client *ClientImpl) CreateAnnotatedTag(ctx context.Context, args CreateAnnotatedTagArgs) (*GitAnnotatedTag, error) { + if args.TagObject == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.TagObject"} + } + routeValues := make(map[string]string) + if args.Project == nil || *args.Project == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.Project"} + } + routeValues["project"] = *args.Project + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + + body, marshalErr := json.Marshal(*args.TagObject) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("5e8a8081-3851-4626-b677-9891cc04102e") + resp, err := client.Client.Send(ctx, http.MethodPost, locationId, "7.1-preview.1", routeValues, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitAnnotatedTag + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the CreateAnnotatedTag function +type CreateAnnotatedTagArgs struct { + // (required) Object containing details of tag to be created. + TagObject *GitAnnotatedTag + // (required) Project ID or project name + Project *string + // (required) ID or name of the repository. + RepositoryId *string +} + +// [Preview API] Attach a new file to a pull request. +func (client *ClientImpl) CreateAttachment(ctx context.Context, args CreateAttachmentArgs) (*Attachment, error) { + if args.UploadStream == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.UploadStream"} + } + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.FileName == nil || *args.FileName == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.FileName"} + } + routeValues["fileName"] = *args.FileName + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + + locationId, _ := uuid.Parse("965d9361-878b-413b-a494-45d5b5fd8ab7") + resp, err := client.Client.Send(ctx, http.MethodPost, locationId, "7.1-preview.1", routeValues, nil, args.UploadStream, "application/octet-stream", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue Attachment + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the CreateAttachment function +type CreateAttachmentArgs struct { + // (required) Stream to upload + UploadStream io.Reader + // (required) The name of the file. + FileName *string + // (required) The repository ID of the pull request’s target branch. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Create a comment on a specific thread in a pull request (up to 500 comments can be created per thread). +func (client *ClientImpl) CreateComment(ctx context.Context, args CreateCommentArgs) (*Comment, error) { + if args.Comment == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.Comment"} + } + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + if args.ThreadId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.ThreadId"} + } + routeValues["threadId"] = strconv.Itoa(*args.ThreadId) + + body, marshalErr := json.Marshal(*args.Comment) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("965a3ec7-5ed8-455a-bdcb-835a5ea7fe7b") + resp, err := client.Client.Send(ctx, http.MethodPost, locationId, "7.1-preview.1", routeValues, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue Comment + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the CreateComment function +type CreateCommentArgs struct { + // (required) The comment to create. Comments can be up to 150,000 characters. + Comment *Comment + // (required) The repository ID of the pull request's target branch. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (required) ID of the thread that the desired comment is in. + ThreadId *int + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Create Git commit status. +func (client *ClientImpl) CreateCommitStatus(ctx context.Context, args CreateCommitStatusArgs) (*GitStatus, error) { + if args.GitCommitStatusToCreate == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.GitCommitStatusToCreate"} + } + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.CommitId == nil || *args.CommitId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.CommitId"} + } + routeValues["commitId"] = *args.CommitId + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + + body, marshalErr := json.Marshal(*args.GitCommitStatusToCreate) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("428dd4fb-fda5-4722-af02-9313b80305da") + resp, err := client.Client.Send(ctx, http.MethodPost, locationId, "7.1-preview.1", routeValues, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitStatus + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the CreateCommitStatus function +type CreateCommitStatusArgs struct { + // (required) Git commit status object to create. + GitCommitStatusToCreate *GitStatus + // (required) ID of the Git commit. + CommitId *string + // (required) ID of the repository. + RepositoryId *string + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Creates a ref favorite +func (client *ClientImpl) CreateFavorite(ctx context.Context, args CreateFavoriteArgs) (*GitRefFavorite, error) { + if args.Favorite == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.Favorite"} + } + routeValues := make(map[string]string) + if args.Project == nil || *args.Project == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.Project"} + } + routeValues["project"] = *args.Project + + body, marshalErr := json.Marshal(*args.Favorite) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("876f70af-5792-485a-a1c7-d0a7b2f42bbb") + resp, err := client.Client.Send(ctx, http.MethodPost, locationId, "7.1-preview.1", routeValues, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitRefFavorite + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the CreateFavorite function +type CreateFavoriteArgs struct { + // (required) The ref favorite to create. + Favorite *GitRefFavorite + // (required) Project ID or project name + Project *string +} + +// [Preview API] Request that another repository's refs be fetched into this one. It syncs two existing forks. To create a fork, please see the repositories endpoint +func (client *ClientImpl) CreateForkSyncRequest(ctx context.Context, args CreateForkSyncRequestArgs) (*GitForkSyncRequest, error) { + if args.SyncParams == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.SyncParams"} + } + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryNameOrId == nil || *args.RepositoryNameOrId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryNameOrId"} + } + routeValues["repositoryNameOrId"] = *args.RepositoryNameOrId + + queryParams := url.Values{} + if args.IncludeLinks != nil { + queryParams.Add("includeLinks", strconv.FormatBool(*args.IncludeLinks)) + } + body, marshalErr := json.Marshal(*args.SyncParams) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("1703f858-b9d1-46af-ab62-483e9e1055b5") + resp, err := client.Client.Send(ctx, http.MethodPost, locationId, "7.1-preview.1", routeValues, queryParams, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitForkSyncRequest + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the CreateForkSyncRequest function +type CreateForkSyncRequestArgs struct { + // (required) Source repository and ref mapping. + SyncParams *GitForkSyncRequestParameters + // (required) The name or ID of the repository. + RepositoryNameOrId *string + // (optional) Project ID or project name + Project *string + // (optional) True to include links + IncludeLinks *bool +} + +// [Preview API] Cherry pick a specific commit or commits that are associated to a pull request into a new branch. +func (client *ClientImpl) CreateCherryPick(ctx context.Context, args CreateCherryPickArgs) (*GitCherryPick, error) { + if args.CherryPickToCreate == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.CherryPickToCreate"} + } + routeValues := make(map[string]string) + if args.Project == nil || *args.Project == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.Project"} + } + routeValues["project"] = *args.Project + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + + body, marshalErr := json.Marshal(*args.CherryPickToCreate) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("033bad68-9a14-43d1-90e0-59cb8856fef6") + resp, err := client.Client.Send(ctx, http.MethodPost, locationId, "7.1-preview.1", routeValues, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitCherryPick + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the CreateCherryPick function +type CreateCherryPickArgs struct { + // (required) + CherryPickToCreate *GitAsyncRefOperationParameters + // (required) Project ID or project name + Project *string + // (required) ID of the repository. + RepositoryId *string +} + +// [Preview API] Create an import request. +func (client *ClientImpl) CreateImportRequest(ctx context.Context, args CreateImportRequestArgs) (*GitImportRequest, error) { + if args.ImportRequest == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.ImportRequest"} + } + routeValues := make(map[string]string) + if args.Project == nil || *args.Project == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.Project"} + } + routeValues["project"] = *args.Project + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + + body, marshalErr := json.Marshal(*args.ImportRequest) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("01828ddc-3600-4a41-8633-99b3a73a0eb3") + resp, err := client.Client.Send(ctx, http.MethodPost, locationId, "7.1-preview.1", routeValues, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitImportRequest + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the CreateImportRequest function +type CreateImportRequestArgs struct { + // (required) The import request to create. + ImportRequest *GitImportRequest + // (required) Project ID or project name + Project *string + // (required) The name or ID of the repository. + RepositoryId *string +} + +// [Preview API] Add a like on a comment. +func (client *ClientImpl) CreateLike(ctx context.Context, args CreateLikeArgs) error { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + if args.ThreadId == nil { + return &azuredevops.ArgumentNilError{ArgumentName: "args.ThreadId"} + } + routeValues["threadId"] = strconv.Itoa(*args.ThreadId) + if args.CommentId == nil { + return &azuredevops.ArgumentNilError{ArgumentName: "args.CommentId"} + } + routeValues["commentId"] = strconv.Itoa(*args.CommentId) + + locationId, _ := uuid.Parse("5f2e2851-1389-425b-a00b-fb2adb3ef31b") + _, err := client.Client.Send(ctx, http.MethodPost, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return err + } + + return nil +} + +// Arguments for the CreateLike function +type CreateLikeArgs struct { + // (required) The repository ID of the pull request's target branch. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (required) The ID of the thread that contains the comment. + ThreadId *int + // (required) The ID of the comment. + CommentId *int + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Request a git merge operation. Currently we support merging only 2 commits. +func (client *ClientImpl) CreateMergeRequest(ctx context.Context, args CreateMergeRequestArgs) (*GitMerge, error) { + if args.MergeParameters == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.MergeParameters"} + } + routeValues := make(map[string]string) + if args.Project == nil || *args.Project == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.Project"} + } + routeValues["project"] = *args.Project + if args.RepositoryNameOrId == nil || *args.RepositoryNameOrId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryNameOrId"} + } + routeValues["repositoryNameOrId"] = *args.RepositoryNameOrId + + queryParams := url.Values{} + if args.IncludeLinks != nil { + queryParams.Add("includeLinks", strconv.FormatBool(*args.IncludeLinks)) + } + body, marshalErr := json.Marshal(*args.MergeParameters) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("985f7ae9-844f-4906-9897-7ef41516c0e2") + resp, err := client.Client.Send(ctx, http.MethodPost, locationId, "7.1-preview.1", routeValues, queryParams, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitMerge + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the CreateMergeRequest function +type CreateMergeRequestArgs struct { + // (required) Parents commitIds and merge commit messsage. + MergeParameters *GitMergeParameters + // (required) Project ID or project name + Project *string + // (required) The name or ID of the repository. + RepositoryNameOrId *string + // (optional) True to include links + IncludeLinks *bool +} + +// [Preview API] Create a pull request. +func (client *ClientImpl) CreatePullRequest(ctx context.Context, args CreatePullRequestArgs) (*GitPullRequest, error) { + if args.GitPullRequestToCreate == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.GitPullRequestToCreate"} + } + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + + queryParams := url.Values{} + if args.SupportsIterations != nil { + queryParams.Add("supportsIterations", strconv.FormatBool(*args.SupportsIterations)) + } + body, marshalErr := json.Marshal(*args.GitPullRequestToCreate) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("9946fd70-0d40-406e-b686-b4744cbbcc37") + resp, err := client.Client.Send(ctx, http.MethodPost, locationId, "7.1-preview.1", routeValues, queryParams, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitPullRequest + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the CreatePullRequest function +type CreatePullRequestArgs struct { + // (required) The pull request to create. + GitPullRequestToCreate *GitPullRequest + // (required) The repository ID of the pull request's target branch. + RepositoryId *string + // (optional) Project ID or project name + Project *string + // (optional) If true, subsequent pushes to the pull request will be individually reviewable. Set this to false for large pull requests for performance reasons if this functionality is not needed. + SupportsIterations *bool +} + +// [Preview API] Create a pull request status on the iteration. This operation will have the same result as Create status on pull request with specified iteration ID in the request body. +func (client *ClientImpl) CreatePullRequestIterationStatus(ctx context.Context, args CreatePullRequestIterationStatusArgs) (*GitPullRequestStatus, error) { + if args.Status == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.Status"} + } + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + if args.IterationId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.IterationId"} + } + routeValues["iterationId"] = strconv.Itoa(*args.IterationId) + + body, marshalErr := json.Marshal(*args.Status) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("75cf11c5-979f-4038-a76e-058a06adf2bf") + resp, err := client.Client.Send(ctx, http.MethodPost, locationId, "7.1-preview.1", routeValues, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitPullRequestStatus + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the CreatePullRequestIterationStatus function +type CreatePullRequestIterationStatusArgs struct { + // (required) Pull request status to create. + Status *GitPullRequestStatus + // (required) The repository ID of the pull request’s target branch. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (required) ID of the pull request iteration. + IterationId *int + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Create a label for a specified pull request. The only required field is the name of the new label. +func (client *ClientImpl) CreatePullRequestLabel(ctx context.Context, args CreatePullRequestLabelArgs) (*core.WebApiTagDefinition, error) { + if args.Label == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.Label"} + } + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + + queryParams := url.Values{} + if args.ProjectId != nil { + queryParams.Add("projectId", *args.ProjectId) + } + body, marshalErr := json.Marshal(*args.Label) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("f22387e3-984e-4c52-9c6d-fbb8f14c812d") + resp, err := client.Client.Send(ctx, http.MethodPost, locationId, "7.1-preview.1", routeValues, queryParams, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue core.WebApiTagDefinition + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the CreatePullRequestLabel function +type CreatePullRequestLabelArgs struct { + // (required) Label to assign to the pull request. + Label *core.WebApiCreateTagRequestData + // (required) The repository ID of the pull request’s target branch. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (optional) Project ID or project name + Project *string + // (optional) Project ID or project name. + ProjectId *string +} + +// [Preview API] Add a reviewer to a pull request or cast a vote. +func (client *ClientImpl) CreatePullRequestReviewer(ctx context.Context, args CreatePullRequestReviewerArgs) (*IdentityRefWithVote, error) { + if args.Reviewer == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.Reviewer"} + } + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + if args.ReviewerId == nil || *args.ReviewerId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.ReviewerId"} + } + routeValues["reviewerId"] = *args.ReviewerId + + body, marshalErr := json.Marshal(*args.Reviewer) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("4b6702c7-aa35-4b89-9c96-b9abf6d3e540") + resp, err := client.Client.Send(ctx, http.MethodPut, locationId, "7.1-preview.1", routeValues, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue IdentityRefWithVote + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the CreatePullRequestReviewer function +type CreatePullRequestReviewerArgs struct { + // (required) Reviewer's vote.
If the reviewer's ID is included here, it must match the reviewerID parameter.
Reviewers can set their own vote with this method. When adding other reviewers, vote must be set to zero. + Reviewer *IdentityRefWithVote + // (required) The repository ID of the pull request's target branch. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (required) ID of the reviewer. + ReviewerId *string + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Add reviewers to a pull request. +func (client *ClientImpl) CreatePullRequestReviewers(ctx context.Context, args CreatePullRequestReviewersArgs) (*[]IdentityRefWithVote, error) { + if args.Reviewers == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.Reviewers"} + } + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + + body, marshalErr := json.Marshal(*args.Reviewers) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("4b6702c7-aa35-4b89-9c96-b9abf6d3e540") + resp, err := client.Client.Send(ctx, http.MethodPost, locationId, "7.1-preview.1", routeValues, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []IdentityRefWithVote + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the CreatePullRequestReviewers function +type CreatePullRequestReviewersArgs struct { + // (required) Reviewers to add to the pull request. + Reviewers *[]webapi.IdentityRef + // (required) The repository ID of the pull request's target branch. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Create a pull request status. +func (client *ClientImpl) CreatePullRequestStatus(ctx context.Context, args CreatePullRequestStatusArgs) (*GitPullRequestStatus, error) { + if args.Status == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.Status"} + } + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + + body, marshalErr := json.Marshal(*args.Status) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("b5f6bb4f-8d1e-4d79-8d11-4c9172c99c35") + resp, err := client.Client.Send(ctx, http.MethodPost, locationId, "7.1-preview.1", routeValues, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitPullRequestStatus + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the CreatePullRequestStatus function +type CreatePullRequestStatusArgs struct { + // (required) Pull request status to create. + Status *GitPullRequestStatus + // (required) The repository ID of the pull request’s target branch. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Push changes to the repository. +func (client *ClientImpl) CreatePush(ctx context.Context, args CreatePushArgs) (*GitPush, error) { + if args.Push == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.Push"} + } + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + + body, marshalErr := json.Marshal(*args.Push) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("ea98d07b-3c87-4971-8ede-a613694ffb55") + resp, err := client.Client.Send(ctx, http.MethodPost, locationId, "7.1-preview.2", routeValues, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitPush + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the CreatePush function +type CreatePushArgs struct { + // (required) + Push *GitPush + // (required) The name or ID of the repository. + RepositoryId *string + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Create a git repository in a team project. +func (client *ClientImpl) CreateRepository(ctx context.Context, args CreateRepositoryArgs) (*GitRepository, error) { + if args.GitRepositoryToCreate == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.GitRepositoryToCreate"} + } + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + + queryParams := url.Values{} + if args.SourceRef != nil { + queryParams.Add("sourceRef", *args.SourceRef) + } + body, marshalErr := json.Marshal(*args.GitRepositoryToCreate) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("225f7195-f9c7-4d14-ab28-a83f7ff77e1f") + resp, err := client.Client.Send(ctx, http.MethodPost, locationId, "7.1-preview.1", routeValues, queryParams, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitRepository + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the CreateRepository function +type CreateRepositoryArgs struct { + // (required) Specify the repo name, team project and/or parent repository. Team project information can be omitted from gitRepositoryToCreate if the request is project-scoped (i.e., includes project Id). + GitRepositoryToCreate *GitRepositoryCreateOptions + // (optional) Project ID or project name + Project *string + // (optional) [optional] Specify the source refs to use while creating a fork repo + SourceRef *string +} + +// [Preview API] Starts the operation to create a new branch which reverts changes introduced by either a specific commit or commits that are associated to a pull request. +func (client *ClientImpl) CreateRevert(ctx context.Context, args CreateRevertArgs) (*GitRevert, error) { + if args.RevertToCreate == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.RevertToCreate"} + } + routeValues := make(map[string]string) + if args.Project == nil || *args.Project == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.Project"} + } + routeValues["project"] = *args.Project + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + + body, marshalErr := json.Marshal(*args.RevertToCreate) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("bc866058-5449-4715-9cf1-a510b6ff193c") + resp, err := client.Client.Send(ctx, http.MethodPost, locationId, "7.1-preview.1", routeValues, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitRevert + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the CreateRevert function +type CreateRevertArgs struct { + // (required) + RevertToCreate *GitAsyncRefOperationParameters + // (required) Project ID or project name + Project *string + // (required) ID of the repository. + RepositoryId *string +} + +// [Preview API] Create a thread in a pull request. +func (client *ClientImpl) CreateThread(ctx context.Context, args CreateThreadArgs) (*GitPullRequestCommentThread, error) { + if args.CommentThread == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.CommentThread"} + } + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + + body, marshalErr := json.Marshal(*args.CommentThread) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("ab6e2e5d-a0b7-4153-b64a-a4efe0d49449") + resp, err := client.Client.Send(ctx, http.MethodPost, locationId, "7.1-preview.1", routeValues, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitPullRequestCommentThread + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the CreateThread function +type CreateThreadArgs struct { + // (required) The thread to create. Thread must contain at least one comment. + CommentThread *GitPullRequestCommentThread + // (required) Repository ID of the pull request's target branch. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Add an unmaterialized identity to the reviewers of a pull request. +func (client *ClientImpl) CreateUnmaterializedPullRequestReviewer(ctx context.Context, args CreateUnmaterializedPullRequestReviewerArgs) (*IdentityRefWithVote, error) { + if args.Reviewer == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.Reviewer"} + } + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + + body, marshalErr := json.Marshal(*args.Reviewer) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("4b6702c7-aa35-4b89-9c96-b9abf6d3e540") + resp, err := client.Client.Send(ctx, http.MethodPut, locationId, "7.1-preview.1", routeValues, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue IdentityRefWithVote + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the CreateUnmaterializedPullRequestReviewer function +type CreateUnmaterializedPullRequestReviewerArgs struct { + // (required) Reviewer to add to the pull request. + Reviewer *IdentityRefWithVote + // (required) The repository ID of the pull request's target branch. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Delete a pull request attachment. +func (client *ClientImpl) DeleteAttachment(ctx context.Context, args DeleteAttachmentArgs) error { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.FileName == nil || *args.FileName == "" { + return &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.FileName"} + } + routeValues["fileName"] = *args.FileName + if args.RepositoryId == nil || *args.RepositoryId == "" { + return &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + + locationId, _ := uuid.Parse("965d9361-878b-413b-a494-45d5b5fd8ab7") + _, err := client.Client.Send(ctx, http.MethodDelete, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return err + } + + return nil +} + +// Arguments for the DeleteAttachment function +type DeleteAttachmentArgs struct { + // (required) The name of the attachment to delete. + FileName *string + // (required) The repository ID of the pull request’s target branch. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Delete a comment associated with a specific thread in a pull request. +func (client *ClientImpl) DeleteComment(ctx context.Context, args DeleteCommentArgs) error { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + if args.ThreadId == nil { + return &azuredevops.ArgumentNilError{ArgumentName: "args.ThreadId"} + } + routeValues["threadId"] = strconv.Itoa(*args.ThreadId) + if args.CommentId == nil { + return &azuredevops.ArgumentNilError{ArgumentName: "args.CommentId"} + } + routeValues["commentId"] = strconv.Itoa(*args.CommentId) + + locationId, _ := uuid.Parse("965a3ec7-5ed8-455a-bdcb-835a5ea7fe7b") + _, err := client.Client.Send(ctx, http.MethodDelete, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return err + } + + return nil +} + +// Arguments for the DeleteComment function +type DeleteCommentArgs struct { + // (required) The repository ID of the pull request's target branch. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (required) ID of the thread that the desired comment is in. + ThreadId *int + // (required) ID of the comment. + CommentId *int + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Delete a like on a comment. +func (client *ClientImpl) DeleteLike(ctx context.Context, args DeleteLikeArgs) error { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + if args.ThreadId == nil { + return &azuredevops.ArgumentNilError{ArgumentName: "args.ThreadId"} + } + routeValues["threadId"] = strconv.Itoa(*args.ThreadId) + if args.CommentId == nil { + return &azuredevops.ArgumentNilError{ArgumentName: "args.CommentId"} + } + routeValues["commentId"] = strconv.Itoa(*args.CommentId) + + locationId, _ := uuid.Parse("5f2e2851-1389-425b-a00b-fb2adb3ef31b") + _, err := client.Client.Send(ctx, http.MethodDelete, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return err + } + + return nil +} + +// Arguments for the DeleteLike function +type DeleteLikeArgs struct { + // (required) The repository ID of the pull request's target branch. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (required) The ID of the thread that contains the comment. + ThreadId *int + // (required) The ID of the comment. + CommentId *int + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Delete pull request iteration status. +func (client *ClientImpl) DeletePullRequestIterationStatus(ctx context.Context, args DeletePullRequestIterationStatusArgs) error { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + if args.IterationId == nil { + return &azuredevops.ArgumentNilError{ArgumentName: "args.IterationId"} + } + routeValues["iterationId"] = strconv.Itoa(*args.IterationId) + if args.StatusId == nil { + return &azuredevops.ArgumentNilError{ArgumentName: "args.StatusId"} + } + routeValues["statusId"] = strconv.Itoa(*args.StatusId) + + locationId, _ := uuid.Parse("75cf11c5-979f-4038-a76e-058a06adf2bf") + _, err := client.Client.Send(ctx, http.MethodDelete, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return err + } + + return nil +} + +// Arguments for the DeletePullRequestIterationStatus function +type DeletePullRequestIterationStatusArgs struct { + // (required) The repository ID of the pull request’s target branch. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (required) ID of the pull request iteration. + IterationId *int + // (required) ID of the pull request status. + StatusId *int + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Removes a label from the set of those assigned to the pull request. +func (client *ClientImpl) DeletePullRequestLabels(ctx context.Context, args DeletePullRequestLabelsArgs) error { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + if args.LabelIdOrName == nil || *args.LabelIdOrName == "" { + return &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.LabelIdOrName"} + } + routeValues["labelIdOrName"] = *args.LabelIdOrName + + queryParams := url.Values{} + if args.ProjectId != nil { + queryParams.Add("projectId", *args.ProjectId) + } + locationId, _ := uuid.Parse("f22387e3-984e-4c52-9c6d-fbb8f14c812d") + _, err := client.Client.Send(ctx, http.MethodDelete, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return err + } + + return nil +} + +// Arguments for the DeletePullRequestLabels function +type DeletePullRequestLabelsArgs struct { + // (required) The repository ID of the pull request’s target branch. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (required) The name or ID of the label requested. + LabelIdOrName *string + // (optional) Project ID or project name + Project *string + // (optional) Project ID or project name. + ProjectId *string +} + +// [Preview API] Remove a reviewer from a pull request. +func (client *ClientImpl) DeletePullRequestReviewer(ctx context.Context, args DeletePullRequestReviewerArgs) error { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + if args.ReviewerId == nil || *args.ReviewerId == "" { + return &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.ReviewerId"} + } + routeValues["reviewerId"] = *args.ReviewerId + + locationId, _ := uuid.Parse("4b6702c7-aa35-4b89-9c96-b9abf6d3e540") + _, err := client.Client.Send(ctx, http.MethodDelete, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return err + } + + return nil +} + +// Arguments for the DeletePullRequestReviewer function +type DeletePullRequestReviewerArgs struct { + // (required) The repository ID of the pull request's target branch. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (required) ID of the reviewer to remove. + ReviewerId *string + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Delete pull request status. +func (client *ClientImpl) DeletePullRequestStatus(ctx context.Context, args DeletePullRequestStatusArgs) error { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + if args.StatusId == nil { + return &azuredevops.ArgumentNilError{ArgumentName: "args.StatusId"} + } + routeValues["statusId"] = strconv.Itoa(*args.StatusId) + + locationId, _ := uuid.Parse("b5f6bb4f-8d1e-4d79-8d11-4c9172c99c35") + _, err := client.Client.Send(ctx, http.MethodDelete, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return err + } + + return nil +} + +// Arguments for the DeletePullRequestStatus function +type DeletePullRequestStatusArgs struct { + // (required) The repository ID of the pull request’s target branch. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (required) ID of the pull request status. + StatusId *int + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Deletes the refs favorite specified +func (client *ClientImpl) DeleteRefFavorite(ctx context.Context, args DeleteRefFavoriteArgs) error { + routeValues := make(map[string]string) + if args.Project == nil || *args.Project == "" { + return &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.Project"} + } + routeValues["project"] = *args.Project + if args.FavoriteId == nil { + return &azuredevops.ArgumentNilError{ArgumentName: "args.FavoriteId"} + } + routeValues["favoriteId"] = strconv.Itoa(*args.FavoriteId) + + locationId, _ := uuid.Parse("876f70af-5792-485a-a1c7-d0a7b2f42bbb") + _, err := client.Client.Send(ctx, http.MethodDelete, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return err + } + + return nil +} + +// Arguments for the DeleteRefFavorite function +type DeleteRefFavoriteArgs struct { + // (required) Project ID or project name + Project *string + // (required) The Id of the ref favorite to delete. + FavoriteId *int +} + +// [Preview API] Delete a git repository +func (client *ClientImpl) DeleteRepository(ctx context.Context, args DeleteRepositoryArgs) error { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil { + return &azuredevops.ArgumentNilError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = (*args.RepositoryId).String() + + locationId, _ := uuid.Parse("225f7195-f9c7-4d14-ab28-a83f7ff77e1f") + _, err := client.Client.Send(ctx, http.MethodDelete, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return err + } + + return nil +} + +// Arguments for the DeleteRepository function +type DeleteRepositoryArgs struct { + // (required) The ID of the repository. + RepositoryId *uuid.UUID + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Destroy (hard delete) a soft-deleted Git repository. +func (client *ClientImpl) DeleteRepositoryFromRecycleBin(ctx context.Context, args DeleteRepositoryFromRecycleBinArgs) error { + routeValues := make(map[string]string) + if args.Project == nil || *args.Project == "" { + return &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.Project"} + } + routeValues["project"] = *args.Project + if args.RepositoryId == nil { + return &azuredevops.ArgumentNilError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = (*args.RepositoryId).String() + + locationId, _ := uuid.Parse("a663da97-81db-4eb3-8b83-287670f63073") + _, err := client.Client.Send(ctx, http.MethodDelete, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return err + } + + return nil +} + +// Arguments for the DeleteRepositoryFromRecycleBin function +type DeleteRepositoryFromRecycleBinArgs struct { + // (required) Project ID or project name + Project *string + // (required) The ID of the repository. + RepositoryId *uuid.UUID +} + +// [Preview API] Get an annotated tag. +func (client *ClientImpl) GetAnnotatedTag(ctx context.Context, args GetAnnotatedTagArgs) (*GitAnnotatedTag, error) { + routeValues := make(map[string]string) + if args.Project == nil || *args.Project == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.Project"} + } + routeValues["project"] = *args.Project + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.ObjectId == nil || *args.ObjectId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.ObjectId"} + } + routeValues["objectId"] = *args.ObjectId + + locationId, _ := uuid.Parse("5e8a8081-3851-4626-b677-9891cc04102e") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitAnnotatedTag + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetAnnotatedTag function +type GetAnnotatedTagArgs struct { + // (required) Project ID or project name + Project *string + // (required) ID or name of the repository. + RepositoryId *string + // (required) ObjectId (Sha1Id) of tag to get. + ObjectId *string +} + +// [Preview API] Get the file content of a pull request attachment. +func (client *ClientImpl) GetAttachmentContent(ctx context.Context, args GetAttachmentContentArgs) (io.ReadCloser, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.FileName == nil || *args.FileName == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.FileName"} + } + routeValues["fileName"] = *args.FileName + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + + locationId, _ := uuid.Parse("965d9361-878b-413b-a494-45d5b5fd8ab7") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/octet-stream", nil) + if err != nil { + return nil, err + } + + return resp.Body, err +} + +// Arguments for the GetAttachmentContent function +type GetAttachmentContentArgs struct { + // (required) The name of the attachment. + FileName *string + // (required) The repository ID of the pull request’s target branch. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Get a list of files attached to a given pull request. +func (client *ClientImpl) GetAttachments(ctx context.Context, args GetAttachmentsArgs) (*[]Attachment, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + + locationId, _ := uuid.Parse("965d9361-878b-413b-a494-45d5b5fd8ab7") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []Attachment + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetAttachments function +type GetAttachmentsArgs struct { + // (required) The repository ID of the pull request’s target branch. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Get the file content of a pull request attachment. +func (client *ClientImpl) GetAttachmentZip(ctx context.Context, args GetAttachmentZipArgs) (io.ReadCloser, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.FileName == nil || *args.FileName == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.FileName"} + } + routeValues["fileName"] = *args.FileName + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + + locationId, _ := uuid.Parse("965d9361-878b-413b-a494-45d5b5fd8ab7") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/zip", nil) + if err != nil { + return nil, err + } + + return resp.Body, err +} + +// Arguments for the GetAttachmentZip function +type GetAttachmentZipArgs struct { + // (required) The name of the attachment. + FileName *string + // (required) The repository ID of the pull request’s target branch. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Get a single blob. +func (client *ClientImpl) GetBlob(ctx context.Context, args GetBlobArgs) (*GitBlobRef, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.Sha1 == nil || *args.Sha1 == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.Sha1"} + } + routeValues["sha1"] = *args.Sha1 + + queryParams := url.Values{} + if args.Download != nil { + queryParams.Add("download", strconv.FormatBool(*args.Download)) + } + if args.FileName != nil { + queryParams.Add("fileName", *args.FileName) + } + if args.ResolveLfs != nil { + queryParams.Add("resolveLfs", strconv.FormatBool(*args.ResolveLfs)) + } + locationId, _ := uuid.Parse("7b28e929-2c99-405d-9c5c-6167a06e6816") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitBlobRef + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetBlob function +type GetBlobArgs struct { + // (required) The name or ID of the repository. + RepositoryId *string + // (required) SHA1 hash of the file. You can get the SHA1 of a file using the "Git/Items/Get Item" endpoint. + Sha1 *string + // (optional) Project ID or project name + Project *string + // (optional) If true, prompt for a download rather than rendering in a browser. Note: this value defaults to true if $format is zip + Download *bool + // (optional) Provide a fileName to use for a download. + FileName *string + // (optional) If true, try to resolve a blob to its LFS contents, if it's an LFS pointer file. Only compatible with octet-stream Accept headers or $format types + ResolveLfs *bool +} + +// [Preview API] Get a single blob. +func (client *ClientImpl) GetBlobContent(ctx context.Context, args GetBlobContentArgs) (io.ReadCloser, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.Sha1 == nil || *args.Sha1 == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.Sha1"} + } + routeValues["sha1"] = *args.Sha1 + + queryParams := url.Values{} + if args.Download != nil { + queryParams.Add("download", strconv.FormatBool(*args.Download)) + } + if args.FileName != nil { + queryParams.Add("fileName", *args.FileName) + } + if args.ResolveLfs != nil { + queryParams.Add("resolveLfs", strconv.FormatBool(*args.ResolveLfs)) + } + locationId, _ := uuid.Parse("7b28e929-2c99-405d-9c5c-6167a06e6816") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/octet-stream", nil) + if err != nil { + return nil, err + } + + return resp.Body, err +} + +// Arguments for the GetBlobContent function +type GetBlobContentArgs struct { + // (required) The name or ID of the repository. + RepositoryId *string + // (required) SHA1 hash of the file. You can get the SHA1 of a file using the "Git/Items/Get Item" endpoint. + Sha1 *string + // (optional) Project ID or project name + Project *string + // (optional) If true, prompt for a download rather than rendering in a browser. Note: this value defaults to true if $format is zip + Download *bool + // (optional) Provide a fileName to use for a download. + FileName *string + // (optional) If true, try to resolve a blob to its LFS contents, if it's an LFS pointer file. Only compatible with octet-stream Accept headers or $format types + ResolveLfs *bool +} + +// [Preview API] Gets one or more blobs in a zip file download. +func (client *ClientImpl) GetBlobsZip(ctx context.Context, args GetBlobsZipArgs) (io.ReadCloser, error) { + if args.BlobIds == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.BlobIds"} + } + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + + queryParams := url.Values{} + if args.Filename != nil { + queryParams.Add("filename", *args.Filename) + } + body, marshalErr := json.Marshal(*args.BlobIds) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("7b28e929-2c99-405d-9c5c-6167a06e6816") + resp, err := client.Client.Send(ctx, http.MethodPost, locationId, "7.1-preview.1", routeValues, queryParams, bytes.NewReader(body), "application/json", "application/zip", nil) + if err != nil { + return nil, err + } + + return resp.Body, err +} + +// Arguments for the GetBlobsZip function +type GetBlobsZipArgs struct { + // (required) Blob IDs (SHA1 hashes) to be returned in the zip file. + BlobIds *[]string + // (required) The name or ID of the repository. + RepositoryId *string + // (optional) Project ID or project name + Project *string + // (optional) + Filename *string +} + +// [Preview API] Get a single blob. +func (client *ClientImpl) GetBlobZip(ctx context.Context, args GetBlobZipArgs) (io.ReadCloser, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.Sha1 == nil || *args.Sha1 == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.Sha1"} + } + routeValues["sha1"] = *args.Sha1 + + queryParams := url.Values{} + if args.Download != nil { + queryParams.Add("download", strconv.FormatBool(*args.Download)) + } + if args.FileName != nil { + queryParams.Add("fileName", *args.FileName) + } + if args.ResolveLfs != nil { + queryParams.Add("resolveLfs", strconv.FormatBool(*args.ResolveLfs)) + } + locationId, _ := uuid.Parse("7b28e929-2c99-405d-9c5c-6167a06e6816") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/zip", nil) + if err != nil { + return nil, err + } + + return resp.Body, err +} + +// Arguments for the GetBlobZip function +type GetBlobZipArgs struct { + // (required) The name or ID of the repository. + RepositoryId *string + // (required) SHA1 hash of the file. You can get the SHA1 of a file using the "Git/Items/Get Item" endpoint. + Sha1 *string + // (optional) Project ID or project name + Project *string + // (optional) If true, prompt for a download rather than rendering in a browser. Note: this value defaults to true if $format is zip + Download *bool + // (optional) Provide a fileName to use for a download. + FileName *string + // (optional) If true, try to resolve a blob to its LFS contents, if it's an LFS pointer file. Only compatible with octet-stream Accept headers or $format types + ResolveLfs *bool +} + +// [Preview API] Retrieve statistics about a single branch. +func (client *ClientImpl) GetBranch(ctx context.Context, args GetBranchArgs) (*GitBranchStats, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + + queryParams := url.Values{} + if args.Name == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "name"} + } + queryParams.Add("name", *args.Name) + if args.BaseVersionDescriptor != nil { + if args.BaseVersionDescriptor.VersionType != nil { + queryParams.Add("baseVersionDescriptor.versionType", string(*args.BaseVersionDescriptor.VersionType)) + } + if args.BaseVersionDescriptor.Version != nil { + queryParams.Add("baseVersionDescriptor.version", *args.BaseVersionDescriptor.Version) + } + if args.BaseVersionDescriptor.VersionOptions != nil { + queryParams.Add("baseVersionDescriptor.versionOptions", string(*args.BaseVersionDescriptor.VersionOptions)) + } + } + locationId, _ := uuid.Parse("d5b216de-d8d5-4d32-ae76-51df755b16d3") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitBranchStats + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetBranch function +type GetBranchArgs struct { + // (required) The name or ID of the repository. + RepositoryId *string + // (required) Name of the branch. + Name *string + // (optional) Project ID or project name + Project *string + // (optional) Identifies the commit or branch to use as the base. + BaseVersionDescriptor *GitVersionDescriptor +} + +// [Preview API] Retrieve statistics about all branches within a repository. +func (client *ClientImpl) GetBranches(ctx context.Context, args GetBranchesArgs) (*[]GitBranchStats, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + + queryParams := url.Values{} + if args.BaseVersionDescriptor != nil { + if args.BaseVersionDescriptor.VersionType != nil { + queryParams.Add("baseVersionDescriptor.versionType", string(*args.BaseVersionDescriptor.VersionType)) + } + if args.BaseVersionDescriptor.Version != nil { + queryParams.Add("baseVersionDescriptor.version", *args.BaseVersionDescriptor.Version) + } + if args.BaseVersionDescriptor.VersionOptions != nil { + queryParams.Add("baseVersionDescriptor.versionOptions", string(*args.BaseVersionDescriptor.VersionOptions)) + } + } + locationId, _ := uuid.Parse("d5b216de-d8d5-4d32-ae76-51df755b16d3") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []GitBranchStats + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetBranches function +type GetBranchesArgs struct { + // (required) The name or ID of the repository. + RepositoryId *string + // (optional) Project ID or project name + Project *string + // (optional) Identifies the commit or branch to use as the base. + BaseVersionDescriptor *GitVersionDescriptor +} + +// [Preview API] Retrieve a comment associated with a specific thread in a pull request. +func (client *ClientImpl) GetComment(ctx context.Context, args GetCommentArgs) (*Comment, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + if args.ThreadId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.ThreadId"} + } + routeValues["threadId"] = strconv.Itoa(*args.ThreadId) + if args.CommentId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.CommentId"} + } + routeValues["commentId"] = strconv.Itoa(*args.CommentId) + + locationId, _ := uuid.Parse("965a3ec7-5ed8-455a-bdcb-835a5ea7fe7b") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue Comment + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetComment function +type GetCommentArgs struct { + // (required) The repository ID of the pull request's target branch. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (required) ID of the thread that the desired comment is in. + ThreadId *int + // (required) ID of the comment. + CommentId *int + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Retrieve all comments associated with a specific thread in a pull request. +func (client *ClientImpl) GetComments(ctx context.Context, args GetCommentsArgs) (*[]Comment, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + if args.ThreadId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.ThreadId"} + } + routeValues["threadId"] = strconv.Itoa(*args.ThreadId) + + locationId, _ := uuid.Parse("965a3ec7-5ed8-455a-bdcb-835a5ea7fe7b") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []Comment + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetComments function +type GetCommentsArgs struct { + // (required) The repository ID of the pull request's target branch. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (required) ID of the thread. + ThreadId *int + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Retrieve a particular commit. +func (client *ClientImpl) GetCommit(ctx context.Context, args GetCommitArgs) (*GitCommit, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.CommitId == nil || *args.CommitId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.CommitId"} + } + routeValues["commitId"] = *args.CommitId + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + + queryParams := url.Values{} + if args.ChangeCount != nil { + queryParams.Add("changeCount", strconv.Itoa(*args.ChangeCount)) + } + locationId, _ := uuid.Parse("c2570c3b-5b3f-41b8-98bf-5407bfde8d58") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitCommit + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetCommit function +type GetCommitArgs struct { + // (required) The id of the commit. + CommitId *string + // (required) The id or friendly name of the repository. To use the friendly name, projectId must also be specified. + RepositoryId *string + // (optional) Project ID or project name + Project *string + // (optional) The number of changes to include in the result. + ChangeCount *int +} + +// [Preview API] Find the closest common commit (the merge base) between base and target commits, and get the diff between either the base and target commits or common and target commits. +func (client *ClientImpl) GetCommitDiffs(ctx context.Context, args GetCommitDiffsArgs) (*GitCommitDiffs, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + + queryParams := url.Values{} + if args.DiffCommonCommit != nil { + queryParams.Add("diffCommonCommit", strconv.FormatBool(*args.DiffCommonCommit)) + } + if args.Top != nil { + queryParams.Add("$top", strconv.Itoa(*args.Top)) + } + if args.Skip != nil { + queryParams.Add("$skip", strconv.Itoa(*args.Skip)) + } + if args.BaseVersionDescriptor != nil { + if args.BaseVersionDescriptor.BaseVersionType != nil { + queryParams.Add("baseVersionType", string(*args.BaseVersionDescriptor.BaseVersionType)) + } + if args.BaseVersionDescriptor.BaseVersion != nil { + queryParams.Add("baseVersion", *args.BaseVersionDescriptor.BaseVersion) + } + if args.BaseVersionDescriptor.BaseVersionOptions != nil { + queryParams.Add("baseVersionOptions", string(*args.BaseVersionDescriptor.BaseVersionOptions)) + } + } + if args.TargetVersionDescriptor != nil { + if args.TargetVersionDescriptor.TargetVersionType != nil { + queryParams.Add("targetVersionType", string(*args.TargetVersionDescriptor.TargetVersionType)) + } + if args.TargetVersionDescriptor.TargetVersion != nil { + queryParams.Add("targetVersion", *args.TargetVersionDescriptor.TargetVersion) + } + if args.TargetVersionDescriptor.TargetVersionOptions != nil { + queryParams.Add("targetVersionOptions", string(*args.TargetVersionDescriptor.TargetVersionOptions)) + } + } + locationId, _ := uuid.Parse("615588d5-c0c7-4b88-88f8-e625306446e8") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitCommitDiffs + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetCommitDiffs function +type GetCommitDiffsArgs struct { + // (required) The name or ID of the repository. + RepositoryId *string + // (optional) Project ID or project name + Project *string + // (optional) If true, diff between common and target commits. If false, diff between base and target commits. + DiffCommonCommit *bool + // (optional) Maximum number of changes to return. Defaults to 100. + Top *int + // (optional) Number of changes to skip + Skip *int + // (optional) Descriptor for base commit. + BaseVersionDescriptor *GitBaseVersionDescriptor + // (optional) Descriptor for target commit. + TargetVersionDescriptor *GitTargetVersionDescriptor +} + +// [Preview API] Retrieve git commits for a project +func (client *ClientImpl) GetCommits(ctx context.Context, args GetCommitsArgs) (*[]GitCommitRef, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + + queryParams := url.Values{} + if args.SearchCriteria == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "searchCriteria"} + } + if args.SearchCriteria.Ids != nil { + for index, item := range *args.SearchCriteria.Ids { + queryParams.Add("searchCriteria.ids["+strconv.Itoa(index)+"]", item) + } + } + if args.SearchCriteria.FromDate != nil { + queryParams.Add("searchCriteria.fromDate", *args.SearchCriteria.FromDate) + } + if args.SearchCriteria.ToDate != nil { + queryParams.Add("searchCriteria.toDate", *args.SearchCriteria.ToDate) + } + if args.SearchCriteria.ItemVersion != nil { + if args.SearchCriteria.ItemVersion.VersionType != nil { + queryParams.Add("searchCriteria.itemVersion.versionType", string(*args.SearchCriteria.ItemVersion.VersionType)) + } + if args.SearchCriteria.ItemVersion.Version != nil { + queryParams.Add("searchCriteria.itemVersion.version", *args.SearchCriteria.ItemVersion.Version) + } + if args.SearchCriteria.ItemVersion.VersionOptions != nil { + queryParams.Add("searchCriteria.itemVersion.versionOptions", string(*args.SearchCriteria.ItemVersion.VersionOptions)) + } + } + if args.SearchCriteria.CompareVersion != nil { + if args.SearchCriteria.CompareVersion.VersionType != nil { + queryParams.Add("searchCriteria.compareVersion.versionType", string(*args.SearchCriteria.CompareVersion.VersionType)) + } + if args.SearchCriteria.CompareVersion.Version != nil { + queryParams.Add("searchCriteria.compareVersion.version", *args.SearchCriteria.CompareVersion.Version) + } + if args.SearchCriteria.CompareVersion.VersionOptions != nil { + queryParams.Add("searchCriteria.compareVersion.versionOptions", string(*args.SearchCriteria.CompareVersion.VersionOptions)) + } + } + if args.SearchCriteria.FromCommitId != nil { + queryParams.Add("searchCriteria.fromCommitId", *args.SearchCriteria.FromCommitId) + } + if args.SearchCriteria.ToCommitId != nil { + queryParams.Add("searchCriteria.toCommitId", *args.SearchCriteria.ToCommitId) + } + if args.SearchCriteria.User != nil { + queryParams.Add("searchCriteria.user", *args.SearchCriteria.User) + } + if args.SearchCriteria.Author != nil { + queryParams.Add("searchCriteria.author", *args.SearchCriteria.Author) + } + if args.SearchCriteria.ItemPath != nil { + queryParams.Add("searchCriteria.itemPath", *args.SearchCriteria.ItemPath) + } + if args.SearchCriteria.ExcludeDeletes != nil { + queryParams.Add("searchCriteria.excludeDeletes", strconv.FormatBool(*args.SearchCriteria.ExcludeDeletes)) + } + if args.SearchCriteria.Skip != nil { + queryParams.Add("searchCriteria.$skip", strconv.Itoa(*args.SearchCriteria.Skip)) + } + if args.SearchCriteria.Top != nil { + queryParams.Add("searchCriteria.$top", strconv.Itoa(*args.SearchCriteria.Top)) + } + if args.SearchCriteria.IncludeLinks != nil { + queryParams.Add("searchCriteria.includeLinks", strconv.FormatBool(*args.SearchCriteria.IncludeLinks)) + } + if args.SearchCriteria.IncludeWorkItems != nil { + queryParams.Add("searchCriteria.includeWorkItems", strconv.FormatBool(*args.SearchCriteria.IncludeWorkItems)) + } + if args.SearchCriteria.IncludeUserImageUrl != nil { + queryParams.Add("searchCriteria.includeUserImageUrl", strconv.FormatBool(*args.SearchCriteria.IncludeUserImageUrl)) + } + if args.SearchCriteria.IncludePushData != nil { + queryParams.Add("searchCriteria.includePushData", strconv.FormatBool(*args.SearchCriteria.IncludePushData)) + } + if args.SearchCriteria.HistoryMode != nil { + queryParams.Add("searchCriteria.historyMode", string(*args.SearchCriteria.HistoryMode)) + } + if args.SearchCriteria.ShowOldestCommitsFirst != nil { + queryParams.Add("searchCriteria.showOldestCommitsFirst", strconv.FormatBool(*args.SearchCriteria.ShowOldestCommitsFirst)) + } + if args.Skip != nil { + queryParams.Add("$skip", strconv.Itoa(*args.Skip)) + } + if args.Top != nil { + queryParams.Add("$top", strconv.Itoa(*args.Top)) + } + locationId, _ := uuid.Parse("c2570c3b-5b3f-41b8-98bf-5407bfde8d58") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []GitCommitRef + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetCommits function +type GetCommitsArgs struct { + // (required) The id or friendly name of the repository. To use the friendly name, projectId must also be specified. + RepositoryId *string + // (required) + SearchCriteria *GitQueryCommitsCriteria + // (optional) Project ID or project name + Project *string + // (optional) + Skip *int + // (optional) + Top *int +} + +// [Preview API] Retrieve git commits for a project matching the search criteria +func (client *ClientImpl) GetCommitsBatch(ctx context.Context, args GetCommitsBatchArgs) (*[]GitCommitRef, error) { + if args.SearchCriteria == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.SearchCriteria"} + } + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + + queryParams := url.Values{} + if args.Skip != nil { + queryParams.Add("$skip", strconv.Itoa(*args.Skip)) + } + if args.Top != nil { + queryParams.Add("$top", strconv.Itoa(*args.Top)) + } + if args.IncludeStatuses != nil { + queryParams.Add("includeStatuses", strconv.FormatBool(*args.IncludeStatuses)) + } + body, marshalErr := json.Marshal(*args.SearchCriteria) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("6400dfb2-0bcb-462b-b992-5a57f8f1416c") + resp, err := client.Client.Send(ctx, http.MethodPost, locationId, "7.1-preview.1", routeValues, queryParams, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []GitCommitRef + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetCommitsBatch function +type GetCommitsBatchArgs struct { + // (required) Search options + SearchCriteria *GitQueryCommitsCriteria + // (required) The name or ID of the repository. + RepositoryId *string + // (optional) Project ID or project name + Project *string + // (optional) Number of commits to skip. + Skip *int + // (optional) Maximum number of commits to return. + Top *int + // (optional) True to include additional commit status information. + IncludeStatuses *bool +} + +// [Preview API] Retrieve deleted git repositories. +func (client *ClientImpl) GetDeletedRepositories(ctx context.Context, args GetDeletedRepositoriesArgs) (*[]GitDeletedRepository, error) { + routeValues := make(map[string]string) + if args.Project == nil || *args.Project == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.Project"} + } + routeValues["project"] = *args.Project + + locationId, _ := uuid.Parse("2b6869c4-cb25-42b5-b7a3-0d3e6be0a11a") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []GitDeletedRepository + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetDeletedRepositories function +type GetDeletedRepositoriesArgs struct { + // (required) Project ID or project name + Project *string +} + +// [Preview API] Retrieve all forks of a repository in the collection. +func (client *ClientImpl) GetForks(ctx context.Context, args GetForksArgs) (*[]GitRepositoryRef, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryNameOrId == nil || *args.RepositoryNameOrId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryNameOrId"} + } + routeValues["repositoryNameOrId"] = *args.RepositoryNameOrId + if args.CollectionId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.CollectionId"} + } + routeValues["collectionId"] = (*args.CollectionId).String() + + queryParams := url.Values{} + if args.IncludeLinks != nil { + queryParams.Add("includeLinks", strconv.FormatBool(*args.IncludeLinks)) + } + locationId, _ := uuid.Parse("158c0340-bf6f-489c-9625-d572a1480d57") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []GitRepositoryRef + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetForks function +type GetForksArgs struct { + // (required) The name or ID of the repository. + RepositoryNameOrId *string + // (required) Team project collection ID. + CollectionId *uuid.UUID + // (optional) Project ID or project name + Project *string + // (optional) True to include links. + IncludeLinks *bool +} + +// [Preview API] Get a specific fork sync operation's details. +func (client *ClientImpl) GetForkSyncRequest(ctx context.Context, args GetForkSyncRequestArgs) (*GitForkSyncRequest, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryNameOrId == nil || *args.RepositoryNameOrId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryNameOrId"} + } + routeValues["repositoryNameOrId"] = *args.RepositoryNameOrId + if args.ForkSyncOperationId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.ForkSyncOperationId"} + } + routeValues["forkSyncOperationId"] = strconv.Itoa(*args.ForkSyncOperationId) + + queryParams := url.Values{} + if args.IncludeLinks != nil { + queryParams.Add("includeLinks", strconv.FormatBool(*args.IncludeLinks)) + } + locationId, _ := uuid.Parse("1703f858-b9d1-46af-ab62-483e9e1055b5") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitForkSyncRequest + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetForkSyncRequest function +type GetForkSyncRequestArgs struct { + // (required) The name or ID of the repository. + RepositoryNameOrId *string + // (required) OperationId of the sync request. + ForkSyncOperationId *int + // (optional) Project ID or project name + Project *string + // (optional) True to include links. + IncludeLinks *bool +} + +// [Preview API] Retrieve all requested fork sync operations on this repository. +func (client *ClientImpl) GetForkSyncRequests(ctx context.Context, args GetForkSyncRequestsArgs) (*[]GitForkSyncRequest, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryNameOrId == nil || *args.RepositoryNameOrId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryNameOrId"} + } + routeValues["repositoryNameOrId"] = *args.RepositoryNameOrId + + queryParams := url.Values{} + if args.IncludeAbandoned != nil { + queryParams.Add("includeAbandoned", strconv.FormatBool(*args.IncludeAbandoned)) + } + if args.IncludeLinks != nil { + queryParams.Add("includeLinks", strconv.FormatBool(*args.IncludeLinks)) + } + locationId, _ := uuid.Parse("1703f858-b9d1-46af-ab62-483e9e1055b5") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []GitForkSyncRequest + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetForkSyncRequests function +type GetForkSyncRequestsArgs struct { + // (required) The name or ID of the repository. + RepositoryNameOrId *string + // (optional) Project ID or project name + Project *string + // (optional) True to include abandoned requests. + IncludeAbandoned *bool + // (optional) True to include links. + IncludeLinks *bool +} + +// [Preview API] Retrieve changes for a particular commit. +func (client *ClientImpl) GetChanges(ctx context.Context, args GetChangesArgs) (*GitCommitChanges, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.CommitId == nil || *args.CommitId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.CommitId"} + } + routeValues["commitId"] = *args.CommitId + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + + queryParams := url.Values{} + if args.Top != nil { + queryParams.Add("top", strconv.Itoa(*args.Top)) + } + if args.Skip != nil { + queryParams.Add("skip", strconv.Itoa(*args.Skip)) + } + locationId, _ := uuid.Parse("5bf884f5-3e07-42e9-afb8-1b872267bf16") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitCommitChanges + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetChanges function +type GetChangesArgs struct { + // (required) The id of the commit. + CommitId *string + // (required) The id or friendly name of the repository. To use the friendly name, projectId must also be specified. + RepositoryId *string + // (optional) Project ID or project name + Project *string + // (optional) The maximum number of changes to return. + Top *int + // (optional) The number of changes to skip. + Skip *int +} + +// [Preview API] Retrieve information about a cherry pick operation by cherry pick Id. +func (client *ClientImpl) GetCherryPick(ctx context.Context, args GetCherryPickArgs) (*GitCherryPick, error) { + routeValues := make(map[string]string) + if args.Project == nil || *args.Project == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.Project"} + } + routeValues["project"] = *args.Project + if args.CherryPickId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.CherryPickId"} + } + routeValues["cherryPickId"] = strconv.Itoa(*args.CherryPickId) + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + + locationId, _ := uuid.Parse("033bad68-9a14-43d1-90e0-59cb8856fef6") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitCherryPick + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetCherryPick function +type GetCherryPickArgs struct { + // (required) Project ID or project name + Project *string + // (required) ID of the cherry pick. + CherryPickId *int + // (required) ID of the repository. + RepositoryId *string +} + +// [Preview API] Retrieve information about a cherry pick operation for a specific branch. This operation is expensive due to the underlying object structure, so this API only looks at the 1000 most recent cherry pick operations. +func (client *ClientImpl) GetCherryPickForRefName(ctx context.Context, args GetCherryPickForRefNameArgs) (*GitCherryPick, error) { + routeValues := make(map[string]string) + if args.Project == nil || *args.Project == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.Project"} + } + routeValues["project"] = *args.Project + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + + queryParams := url.Values{} + if args.RefName == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "refName"} + } + queryParams.Add("refName", *args.RefName) + locationId, _ := uuid.Parse("033bad68-9a14-43d1-90e0-59cb8856fef6") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitCherryPick + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetCherryPickForRefName function +type GetCherryPickForRefNameArgs struct { + // (required) Project ID or project name + Project *string + // (required) ID of the repository. + RepositoryId *string + // (required) The GitAsyncRefOperationParameters generatedRefName used for the cherry pick operation. + RefName *string +} + +// [Preview API] Retrieve a particular import request. +func (client *ClientImpl) GetImportRequest(ctx context.Context, args GetImportRequestArgs) (*GitImportRequest, error) { + routeValues := make(map[string]string) + if args.Project == nil || *args.Project == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.Project"} + } + routeValues["project"] = *args.Project + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.ImportRequestId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.ImportRequestId"} + } + routeValues["importRequestId"] = strconv.Itoa(*args.ImportRequestId) + + locationId, _ := uuid.Parse("01828ddc-3600-4a41-8633-99b3a73a0eb3") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitImportRequest + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetImportRequest function +type GetImportRequestArgs struct { + // (required) Project ID or project name + Project *string + // (required) The name or ID of the repository. + RepositoryId *string + // (required) The unique identifier for the import request. + ImportRequestId *int +} + +// [Preview API] Get Item Metadata and/or Content for a single item. The download parameter is to indicate whether the content should be available as a download or just sent as a stream in the response. Doesn't apply to zipped content, which is always returned as a download. +func (client *ClientImpl) GetItem(ctx context.Context, args GetItemArgs) (*GitItem, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + + queryParams := url.Values{} + if args.Path == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "path"} + } + queryParams.Add("path", *args.Path) + if args.ScopePath != nil { + queryParams.Add("scopePath", *args.ScopePath) + } + if args.RecursionLevel != nil { + queryParams.Add("recursionLevel", string(*args.RecursionLevel)) + } + if args.IncludeContentMetadata != nil { + queryParams.Add("includeContentMetadata", strconv.FormatBool(*args.IncludeContentMetadata)) + } + if args.LatestProcessedChange != nil { + queryParams.Add("latestProcessedChange", strconv.FormatBool(*args.LatestProcessedChange)) + } + if args.Download != nil { + queryParams.Add("download", strconv.FormatBool(*args.Download)) + } + if args.VersionDescriptor != nil { + if args.VersionDescriptor.VersionType != nil { + queryParams.Add("versionDescriptor.versionType", string(*args.VersionDescriptor.VersionType)) + } + if args.VersionDescriptor.Version != nil { + queryParams.Add("versionDescriptor.version", *args.VersionDescriptor.Version) + } + if args.VersionDescriptor.VersionOptions != nil { + queryParams.Add("versionDescriptor.versionOptions", string(*args.VersionDescriptor.VersionOptions)) + } + } + if args.IncludeContent != nil { + queryParams.Add("includeContent", strconv.FormatBool(*args.IncludeContent)) + } + if args.ResolveLfs != nil { + queryParams.Add("resolveLfs", strconv.FormatBool(*args.ResolveLfs)) + } + if args.Sanitize != nil { + queryParams.Add("sanitize", strconv.FormatBool(*args.Sanitize)) + } + locationId, _ := uuid.Parse("fb93c0db-47ed-4a31-8c20-47552878fb44") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitItem + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetItem function +type GetItemArgs struct { + // (required) The name or ID of the repository. + RepositoryId *string + // (required) The item path. + Path *string + // (optional) Project ID or project name + Project *string + // (optional) The path scope. The default is null. + ScopePath *string + // (optional) The recursion level of this request. The default is 'none', no recursion. + RecursionLevel *VersionControlRecursionType + // (optional) Set to true to include content metadata. Default is false. + IncludeContentMetadata *bool + // (optional) Set to true to include the latest changes. Default is false. + LatestProcessedChange *bool + // (optional) Set to true to download the response as a file. Default is false. + Download *bool + // (optional) Version descriptor. Default is the default branch for the repository. + VersionDescriptor *GitVersionDescriptor + // (optional) Set to true to include item content when requesting json. Default is false. + IncludeContent *bool + // (optional) Set to true to resolve Git LFS pointer files to return actual content from Git LFS. Default is false. + ResolveLfs *bool + // (optional) Set to true to sanitize an svg file and return it as image. Useful only if requested for svg file. Default is false. + Sanitize *bool +} + +// [Preview API] Get Item Metadata and/or Content for a single item. The download parameter is to indicate whether the content should be available as a download or just sent as a stream in the response. Doesn't apply to zipped content, which is always returned as a download. +func (client *ClientImpl) GetItemContent(ctx context.Context, args GetItemContentArgs) (io.ReadCloser, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + + queryParams := url.Values{} + if args.Path == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "path"} + } + queryParams.Add("path", *args.Path) + if args.ScopePath != nil { + queryParams.Add("scopePath", *args.ScopePath) + } + if args.RecursionLevel != nil { + queryParams.Add("recursionLevel", string(*args.RecursionLevel)) + } + if args.IncludeContentMetadata != nil { + queryParams.Add("includeContentMetadata", strconv.FormatBool(*args.IncludeContentMetadata)) + } + if args.LatestProcessedChange != nil { + queryParams.Add("latestProcessedChange", strconv.FormatBool(*args.LatestProcessedChange)) + } + if args.Download != nil { + queryParams.Add("download", strconv.FormatBool(*args.Download)) + } + if args.VersionDescriptor != nil { + if args.VersionDescriptor.VersionType != nil { + queryParams.Add("versionDescriptor.versionType", string(*args.VersionDescriptor.VersionType)) + } + if args.VersionDescriptor.Version != nil { + queryParams.Add("versionDescriptor.version", *args.VersionDescriptor.Version) + } + if args.VersionDescriptor.VersionOptions != nil { + queryParams.Add("versionDescriptor.versionOptions", string(*args.VersionDescriptor.VersionOptions)) + } + } + if args.IncludeContent != nil { + queryParams.Add("includeContent", strconv.FormatBool(*args.IncludeContent)) + } + if args.ResolveLfs != nil { + queryParams.Add("resolveLfs", strconv.FormatBool(*args.ResolveLfs)) + } + if args.Sanitize != nil { + queryParams.Add("sanitize", strconv.FormatBool(*args.Sanitize)) + } + locationId, _ := uuid.Parse("fb93c0db-47ed-4a31-8c20-47552878fb44") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/octet-stream", nil) + if err != nil { + return nil, err + } + + return resp.Body, err +} + +// Arguments for the GetItemContent function +type GetItemContentArgs struct { + // (required) The name or ID of the repository. + RepositoryId *string + // (required) The item path. + Path *string + // (optional) Project ID or project name + Project *string + // (optional) The path scope. The default is null. + ScopePath *string + // (optional) The recursion level of this request. The default is 'none', no recursion. + RecursionLevel *VersionControlRecursionType + // (optional) Set to true to include content metadata. Default is false. + IncludeContentMetadata *bool + // (optional) Set to true to include the latest changes. Default is false. + LatestProcessedChange *bool + // (optional) Set to true to download the response as a file. Default is false. + Download *bool + // (optional) Version descriptor. Default is the default branch for the repository. + VersionDescriptor *GitVersionDescriptor + // (optional) Set to true to include item content when requesting json. Default is false. + IncludeContent *bool + // (optional) Set to true to resolve Git LFS pointer files to return actual content from Git LFS. Default is false. + ResolveLfs *bool + // (optional) Set to true to sanitize an svg file and return it as image. Useful only if requested for svg file. Default is false. + Sanitize *bool +} + +// [Preview API] Get Item Metadata and/or Content for a collection of items. The download parameter is to indicate whether the content should be available as a download or just sent as a stream in the response. Doesn't apply to zipped content which is always returned as a download. +func (client *ClientImpl) GetItems(ctx context.Context, args GetItemsArgs) (*[]GitItem, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + + queryParams := url.Values{} + if args.ScopePath != nil { + queryParams.Add("scopePath", *args.ScopePath) + } + if args.RecursionLevel != nil { + queryParams.Add("recursionLevel", string(*args.RecursionLevel)) + } + if args.IncludeContentMetadata != nil { + queryParams.Add("includeContentMetadata", strconv.FormatBool(*args.IncludeContentMetadata)) + } + if args.LatestProcessedChange != nil { + queryParams.Add("latestProcessedChange", strconv.FormatBool(*args.LatestProcessedChange)) + } + if args.Download != nil { + queryParams.Add("download", strconv.FormatBool(*args.Download)) + } + if args.IncludeLinks != nil { + queryParams.Add("includeLinks", strconv.FormatBool(*args.IncludeLinks)) + } + if args.VersionDescriptor != nil { + if args.VersionDescriptor.VersionType != nil { + queryParams.Add("versionDescriptor.versionType", string(*args.VersionDescriptor.VersionType)) + } + if args.VersionDescriptor.Version != nil { + queryParams.Add("versionDescriptor.version", *args.VersionDescriptor.Version) + } + if args.VersionDescriptor.VersionOptions != nil { + queryParams.Add("versionDescriptor.versionOptions", string(*args.VersionDescriptor.VersionOptions)) + } + } + if args.ZipForUnix != nil { + queryParams.Add("zipForUnix", strconv.FormatBool(*args.ZipForUnix)) + } + locationId, _ := uuid.Parse("fb93c0db-47ed-4a31-8c20-47552878fb44") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []GitItem + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetItems function +type GetItemsArgs struct { + // (required) The name or ID of the repository. + RepositoryId *string + // (optional) Project ID or project name + Project *string + // (optional) The path scope. The default is null. + ScopePath *string + // (optional) The recursion level of this request. The default is 'none', no recursion. + RecursionLevel *VersionControlRecursionType + // (optional) Set to true to include content metadata. Default is false. + IncludeContentMetadata *bool + // (optional) Set to true to include the latest changes. Default is false. + LatestProcessedChange *bool + // (optional) Set to true to download the response as a file. Default is false. + Download *bool + // (optional) Set to true to include links to items. Default is false. + IncludeLinks *bool + // (optional) Version descriptor. Default is the default branch for the repository. + VersionDescriptor *GitVersionDescriptor + // (optional) Set to true to keep the file permissions for unix (and POSIX) systems like executables and symlinks + ZipForUnix *bool +} + +// [Preview API] Post for retrieving a creating a batch out of a set of items in a repo / project given a list of paths or a long path +func (client *ClientImpl) GetItemsBatch(ctx context.Context, args GetItemsBatchArgs) (*[][]GitItem, error) { + if args.RequestData == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.RequestData"} + } + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + + body, marshalErr := json.Marshal(*args.RequestData) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("630fd2e4-fb88-4f85-ad21-13f3fd1fbca9") + resp, err := client.Client.Send(ctx, http.MethodPost, locationId, "7.1-preview.1", routeValues, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue [][]GitItem + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetItemsBatch function +type GetItemsBatchArgs struct { + // (required) Request data attributes: ItemDescriptors, IncludeContentMetadata, LatestProcessedChange, IncludeLinks. ItemDescriptors: Collection of items to fetch, including path, version, and recursion level. IncludeContentMetadata: Whether to include metadata for all items LatestProcessedChange: Whether to include shallow ref to commit that last changed each item. IncludeLinks: Whether to include the _links field on the shallow references. + RequestData *GitItemRequestData + // (required) The name or ID of the repository + RepositoryId *string + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Get Item Metadata and/or Content for a single item. The download parameter is to indicate whether the content should be available as a download or just sent as a stream in the response. Doesn't apply to zipped content, which is always returned as a download. +func (client *ClientImpl) GetItemText(ctx context.Context, args GetItemTextArgs) (io.ReadCloser, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + + queryParams := url.Values{} + if args.Path == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "path"} + } + queryParams.Add("path", *args.Path) + if args.ScopePath != nil { + queryParams.Add("scopePath", *args.ScopePath) + } + if args.RecursionLevel != nil { + queryParams.Add("recursionLevel", string(*args.RecursionLevel)) + } + if args.IncludeContentMetadata != nil { + queryParams.Add("includeContentMetadata", strconv.FormatBool(*args.IncludeContentMetadata)) + } + if args.LatestProcessedChange != nil { + queryParams.Add("latestProcessedChange", strconv.FormatBool(*args.LatestProcessedChange)) + } + if args.Download != nil { + queryParams.Add("download", strconv.FormatBool(*args.Download)) + } + if args.VersionDescriptor != nil { + if args.VersionDescriptor.VersionType != nil { + queryParams.Add("versionDescriptor.versionType", string(*args.VersionDescriptor.VersionType)) + } + if args.VersionDescriptor.Version != nil { + queryParams.Add("versionDescriptor.version", *args.VersionDescriptor.Version) + } + if args.VersionDescriptor.VersionOptions != nil { + queryParams.Add("versionDescriptor.versionOptions", string(*args.VersionDescriptor.VersionOptions)) + } + } + if args.IncludeContent != nil { + queryParams.Add("includeContent", strconv.FormatBool(*args.IncludeContent)) + } + if args.ResolveLfs != nil { + queryParams.Add("resolveLfs", strconv.FormatBool(*args.ResolveLfs)) + } + if args.Sanitize != nil { + queryParams.Add("sanitize", strconv.FormatBool(*args.Sanitize)) + } + locationId, _ := uuid.Parse("fb93c0db-47ed-4a31-8c20-47552878fb44") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "text/plain", nil) + if err != nil { + return nil, err + } + + return resp.Body, err +} + +// Arguments for the GetItemText function +type GetItemTextArgs struct { + // (required) The name or ID of the repository. + RepositoryId *string + // (required) The item path. + Path *string + // (optional) Project ID or project name + Project *string + // (optional) The path scope. The default is null. + ScopePath *string + // (optional) The recursion level of this request. The default is 'none', no recursion. + RecursionLevel *VersionControlRecursionType + // (optional) Set to true to include content metadata. Default is false. + IncludeContentMetadata *bool + // (optional) Set to true to include the latest changes. Default is false. + LatestProcessedChange *bool + // (optional) Set to true to download the response as a file. Default is false. + Download *bool + // (optional) Version descriptor. Default is the default branch for the repository. + VersionDescriptor *GitVersionDescriptor + // (optional) Set to true to include item content when requesting json. Default is false. + IncludeContent *bool + // (optional) Set to true to resolve Git LFS pointer files to return actual content from Git LFS. Default is false. + ResolveLfs *bool + // (optional) Set to true to sanitize an svg file and return it as image. Useful only if requested for svg file. Default is false. + Sanitize *bool +} + +// [Preview API] Get Item Metadata and/or Content for a single item. The download parameter is to indicate whether the content should be available as a download or just sent as a stream in the response. Doesn't apply to zipped content, which is always returned as a download. +func (client *ClientImpl) GetItemZip(ctx context.Context, args GetItemZipArgs) (io.ReadCloser, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + + queryParams := url.Values{} + if args.Path == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "path"} + } + queryParams.Add("path", *args.Path) + if args.ScopePath != nil { + queryParams.Add("scopePath", *args.ScopePath) + } + if args.RecursionLevel != nil { + queryParams.Add("recursionLevel", string(*args.RecursionLevel)) + } + if args.IncludeContentMetadata != nil { + queryParams.Add("includeContentMetadata", strconv.FormatBool(*args.IncludeContentMetadata)) + } + if args.LatestProcessedChange != nil { + queryParams.Add("latestProcessedChange", strconv.FormatBool(*args.LatestProcessedChange)) + } + if args.Download != nil { + queryParams.Add("download", strconv.FormatBool(*args.Download)) + } + if args.VersionDescriptor != nil { + if args.VersionDescriptor.VersionType != nil { + queryParams.Add("versionDescriptor.versionType", string(*args.VersionDescriptor.VersionType)) + } + if args.VersionDescriptor.Version != nil { + queryParams.Add("versionDescriptor.version", *args.VersionDescriptor.Version) + } + if args.VersionDescriptor.VersionOptions != nil { + queryParams.Add("versionDescriptor.versionOptions", string(*args.VersionDescriptor.VersionOptions)) + } + } + if args.IncludeContent != nil { + queryParams.Add("includeContent", strconv.FormatBool(*args.IncludeContent)) + } + if args.ResolveLfs != nil { + queryParams.Add("resolveLfs", strconv.FormatBool(*args.ResolveLfs)) + } + if args.Sanitize != nil { + queryParams.Add("sanitize", strconv.FormatBool(*args.Sanitize)) + } + locationId, _ := uuid.Parse("fb93c0db-47ed-4a31-8c20-47552878fb44") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/zip", nil) + if err != nil { + return nil, err + } + + return resp.Body, err +} + +// Arguments for the GetItemZip function +type GetItemZipArgs struct { + // (required) The name or ID of the repository. + RepositoryId *string + // (required) The item path. + Path *string + // (optional) Project ID or project name + Project *string + // (optional) The path scope. The default is null. + ScopePath *string + // (optional) The recursion level of this request. The default is 'none', no recursion. + RecursionLevel *VersionControlRecursionType + // (optional) Set to true to include content metadata. Default is false. + IncludeContentMetadata *bool + // (optional) Set to true to include the latest changes. Default is false. + LatestProcessedChange *bool + // (optional) Set to true to download the response as a file. Default is false. + Download *bool + // (optional) Version descriptor. Default is the default branch for the repository. + VersionDescriptor *GitVersionDescriptor + // (optional) Set to true to include item content when requesting json. Default is false. + IncludeContent *bool + // (optional) Set to true to resolve Git LFS pointer files to return actual content from Git LFS. Default is false. + ResolveLfs *bool + // (optional) Set to true to sanitize an svg file and return it as image. Useful only if requested for svg file. Default is false. + Sanitize *bool +} + +// [Preview API] Get likes for a comment. +func (client *ClientImpl) GetLikes(ctx context.Context, args GetLikesArgs) (*[]webapi.IdentityRef, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + if args.ThreadId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.ThreadId"} + } + routeValues["threadId"] = strconv.Itoa(*args.ThreadId) + if args.CommentId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.CommentId"} + } + routeValues["commentId"] = strconv.Itoa(*args.CommentId) + + locationId, _ := uuid.Parse("5f2e2851-1389-425b-a00b-fb2adb3ef31b") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []webapi.IdentityRef + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetLikes function +type GetLikesArgs struct { + // (required) The repository ID of the pull request's target branch. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (required) The ID of the thread that contains the comment. + ThreadId *int + // (required) The ID of the comment. + CommentId *int + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Find the merge bases of two commits, optionally across forks. If otherRepositoryId is not specified, the merge bases will only be calculated within the context of the local repositoryNameOrId. +func (client *ClientImpl) GetMergeBases(ctx context.Context, args GetMergeBasesArgs) (*[]GitCommitRef, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryNameOrId == nil || *args.RepositoryNameOrId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryNameOrId"} + } + routeValues["repositoryNameOrId"] = *args.RepositoryNameOrId + if args.CommitId == nil || *args.CommitId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.CommitId"} + } + routeValues["commitId"] = *args.CommitId + + queryParams := url.Values{} + if args.OtherCommitId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "otherCommitId"} + } + queryParams.Add("otherCommitId", *args.OtherCommitId) + if args.OtherCollectionId != nil { + queryParams.Add("otherCollectionId", (*args.OtherCollectionId).String()) + } + if args.OtherRepositoryId != nil { + queryParams.Add("otherRepositoryId", (*args.OtherRepositoryId).String()) + } + locationId, _ := uuid.Parse("7cf2abb6-c964-4f7e-9872-f78c66e72e9c") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []GitCommitRef + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetMergeBases function +type GetMergeBasesArgs struct { + // (required) ID or name of the local repository. + RepositoryNameOrId *string + // (required) First commit, usually the tip of the target branch of the potential merge. + CommitId *string + // (required) Other commit, usually the tip of the source branch of the potential merge. + OtherCommitId *string + // (optional) Project ID or project name + Project *string + // (optional) The collection ID where otherCommitId lives. + OtherCollectionId *uuid.UUID + // (optional) The repository ID where otherCommitId lives. + OtherRepositoryId *uuid.UUID +} + +// [Preview API] Get a specific merge operation's details. +func (client *ClientImpl) GetMergeRequest(ctx context.Context, args GetMergeRequestArgs) (*GitMerge, error) { + routeValues := make(map[string]string) + if args.Project == nil || *args.Project == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.Project"} + } + routeValues["project"] = *args.Project + if args.RepositoryNameOrId == nil || *args.RepositoryNameOrId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryNameOrId"} + } + routeValues["repositoryNameOrId"] = *args.RepositoryNameOrId + if args.MergeOperationId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.MergeOperationId"} + } + routeValues["mergeOperationId"] = strconv.Itoa(*args.MergeOperationId) + + queryParams := url.Values{} + if args.IncludeLinks != nil { + queryParams.Add("includeLinks", strconv.FormatBool(*args.IncludeLinks)) + } + locationId, _ := uuid.Parse("985f7ae9-844f-4906-9897-7ef41516c0e2") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitMerge + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetMergeRequest function +type GetMergeRequestArgs struct { + // (required) Project ID or project name + Project *string + // (required) The name or ID of the repository. + RepositoryNameOrId *string + // (required) OperationId of the merge request. + MergeOperationId *int + // (optional) True to include links + IncludeLinks *bool +} + +// [Preview API] GET Advanced Security Permission status. +func (client *ClientImpl) GetPermission(ctx context.Context, args GetPermissionArgs) (*bool, error) { + queryParams := url.Values{} + if args.ProjectName != nil { + queryParams.Add("$projectName", *args.ProjectName) + } + if args.RepositoryId != nil { + queryParams.Add("$repositoryId", *args.RepositoryId) + } + if args.Permission != nil { + queryParams.Add("$permission", *args.Permission) + } + locationId, _ := uuid.Parse("61b21a05-a60f-4910-a733-ba5347c2142d") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", nil, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue bool + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetPermission function +type GetPermissionArgs struct { + // (optional) + ProjectName *string + // (optional) Repository user is trying to access + RepositoryId *string + // (optional) Permission being requestd, must be "viewAlert" "dismissAlert" or "manage" + Permission *string +} + +// [Preview API] Retrieve a list of policy configurations by a given set of scope/filtering criteria. +func (client *ClientImpl) GetPolicyConfigurations(ctx context.Context, args GetPolicyConfigurationsArgs) (*GitPolicyConfigurationResponse, error) { + routeValues := make(map[string]string) + if args.Project == nil || *args.Project == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.Project"} + } + routeValues["project"] = *args.Project + + queryParams := url.Values{} + if args.RepositoryId != nil { + queryParams.Add("repositoryId", (*args.RepositoryId).String()) + } + if args.RefName != nil { + queryParams.Add("refName", *args.RefName) + } + if args.PolicyType != nil { + queryParams.Add("policyType", (*args.PolicyType).String()) + } + if args.Top != nil { + queryParams.Add("$top", strconv.Itoa(*args.Top)) + } + if args.ContinuationToken != nil { + queryParams.Add("continuationToken", *args.ContinuationToken) + } + locationId, _ := uuid.Parse("2c420070-a0a2-49cc-9639-c9f271c5ff07") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseBodyValue []policy.PolicyConfiguration + err = client.Client.UnmarshalCollectionBody(resp, &responseBodyValue) + + var responseValue *GitPolicyConfigurationResponse + xmsContinuationTokenHeader := resp.Header.Get("x-ms-continuationtoken") + if err == nil { + responseValue = &GitPolicyConfigurationResponse{ + PolicyConfigurations: &responseBodyValue, + ContinuationToken: &xmsContinuationTokenHeader, + } + } + + return responseValue, err +} + +// Arguments for the GetPolicyConfigurations function +type GetPolicyConfigurationsArgs struct { + // (required) Project ID or project name + Project *string + // (optional) The repository id. + RepositoryId *uuid.UUID + // (optional) The fully-qualified Git ref name (e.g. refs/heads/master). + RefName *string + // (optional) The policy type filter. + PolicyType *uuid.UUID + // (optional) Maximum number of policies to return. + Top *int + // (optional) Pass a policy configuration ID to fetch the next page of results, up to top number of results, for this endpoint. + ContinuationToken *string +} + +// [Preview API] Retrieve a pull request. +func (client *ClientImpl) GetPullRequest(ctx context.Context, args GetPullRequestArgs) (*GitPullRequest, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + + queryParams := url.Values{} + if args.MaxCommentLength != nil { + queryParams.Add("maxCommentLength", strconv.Itoa(*args.MaxCommentLength)) + } + if args.Skip != nil { + queryParams.Add("$skip", strconv.Itoa(*args.Skip)) + } + if args.Top != nil { + queryParams.Add("$top", strconv.Itoa(*args.Top)) + } + if args.IncludeCommits != nil { + queryParams.Add("includeCommits", strconv.FormatBool(*args.IncludeCommits)) + } + if args.IncludeWorkItemRefs != nil { + queryParams.Add("includeWorkItemRefs", strconv.FormatBool(*args.IncludeWorkItemRefs)) + } + locationId, _ := uuid.Parse("9946fd70-0d40-406e-b686-b4744cbbcc37") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitPullRequest + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetPullRequest function +type GetPullRequestArgs struct { + // (required) The repository ID of the pull request's target branch. + RepositoryId *string + // (required) The ID of the pull request to retrieve. + PullRequestId *int + // (optional) Project ID or project name + Project *string + // (optional) Not used. + MaxCommentLength *int + // (optional) Not used. + Skip *int + // (optional) Not used. + Top *int + // (optional) If true, the pull request will be returned with the associated commits. + IncludeCommits *bool + // (optional) If true, the pull request will be returned with the associated work item references. + IncludeWorkItemRefs *bool +} + +// [Preview API] Retrieve a pull request. +func (client *ClientImpl) GetPullRequestById(ctx context.Context, args GetPullRequestByIdArgs) (*GitPullRequest, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.PullRequestId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + + locationId, _ := uuid.Parse("01a46dea-7d46-4d40-bc84-319e7c260d99") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitPullRequest + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetPullRequestById function +type GetPullRequestByIdArgs struct { + // (required) The ID of the pull request to retrieve. + PullRequestId *int + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Get the commits for the specified pull request. +func (client *ClientImpl) GetPullRequestCommits(ctx context.Context, args GetPullRequestCommitsArgs) (*GetPullRequestCommitsResponseValue, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + + locationId, _ := uuid.Parse("52823034-34a8-4576-922c-8d8b77e9e4c4") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GetPullRequestCommitsResponseValue + responseValue.ContinuationToken = resp.Header.Get(azuredevops.HeaderKeyContinuationToken) + err = client.Client.UnmarshalCollectionBody(resp, &responseValue.Value) + return &responseValue, err +} + +// Arguments for the GetPullRequestCommits function +type GetPullRequestCommitsArgs struct { + // (required) ID or name of the repository. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (optional) Project ID or project name + Project *string +} + +// Return type for the GetPullRequestCommits function +type GetPullRequestCommitsResponseValue struct { + Value []GitCommitRef + ContinuationToken string +} + +// [Preview API] Get the specified iteration for a pull request. +func (client *ClientImpl) GetPullRequestIteration(ctx context.Context, args GetPullRequestIterationArgs) (*GitPullRequestIteration, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + if args.IterationId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.IterationId"} + } + routeValues["iterationId"] = strconv.Itoa(*args.IterationId) + + locationId, _ := uuid.Parse("d43911ee-6958-46b0-a42b-8445b8a0d004") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.2", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitPullRequestIteration + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetPullRequestIteration function +type GetPullRequestIterationArgs struct { + // (required) ID or name of the repository. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (required) ID of the pull request iteration to return. + IterationId *int + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Get the commits for the specified iteration of a pull request. +func (client *ClientImpl) GetPullRequestIterationCommits(ctx context.Context, args GetPullRequestIterationCommitsArgs) (*[]GitCommitRef, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + if args.IterationId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.IterationId"} + } + routeValues["iterationId"] = strconv.Itoa(*args.IterationId) + + queryParams := url.Values{} + if args.Top != nil { + queryParams.Add("top", strconv.Itoa(*args.Top)) + } + if args.Skip != nil { + queryParams.Add("skip", strconv.Itoa(*args.Skip)) + } + locationId, _ := uuid.Parse("e7ea0883-095f-4926-b5fb-f24691c26fb9") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []GitCommitRef + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetPullRequestIterationCommits function +type GetPullRequestIterationCommitsArgs struct { + // (required) ID or name of the repository. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (required) ID of the iteration from which to get the commits. + IterationId *int + // (optional) Project ID or project name + Project *string + // (optional) Maximum number of commits to return. The maximum number of commits that can be returned per batch is 500. + Top *int + // (optional) Number of commits to skip. + Skip *int +} + +// [Preview API] Retrieve the changes made in a pull request between two iterations. +func (client *ClientImpl) GetPullRequestIterationChanges(ctx context.Context, args GetPullRequestIterationChangesArgs) (*GitPullRequestIterationChanges, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + if args.IterationId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.IterationId"} + } + routeValues["iterationId"] = strconv.Itoa(*args.IterationId) + + queryParams := url.Values{} + if args.Top != nil { + queryParams.Add("$top", strconv.Itoa(*args.Top)) + } + if args.Skip != nil { + queryParams.Add("$skip", strconv.Itoa(*args.Skip)) + } + if args.CompareTo != nil { + queryParams.Add("$compareTo", strconv.Itoa(*args.CompareTo)) + } + locationId, _ := uuid.Parse("4216bdcf-b6b1-4d59-8b82-c34cc183fc8b") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitPullRequestIterationChanges + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetPullRequestIterationChanges function +type GetPullRequestIterationChangesArgs struct { + // (required) The repository ID of the pull request's target branch. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (required) ID of the pull request iteration.
Iteration one is the head of the source branch at the time the pull request is created and subsequent iterations are created when there are pushes to the source branch. Allowed values are between 1 and the maximum iteration on this pull request. + IterationId *int + // (optional) Project ID or project name + Project *string + // (optional) Optional. The number of changes to retrieve. The default value is 100 and the maximum value is 2000. + Top *int + // (optional) Optional. The number of changes to ignore. For example, to retrieve changes 101-150, set top 50 and skip to 100. + Skip *int + // (optional) ID of the pull request iteration to compare against. The default value is zero which indicates the comparison is made against the common commit between the source and target branches + CompareTo *int +} + +// [Preview API] Get the list of iterations for the specified pull request. +func (client *ClientImpl) GetPullRequestIterations(ctx context.Context, args GetPullRequestIterationsArgs) (*[]GitPullRequestIteration, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + + queryParams := url.Values{} + if args.IncludeCommits != nil { + queryParams.Add("includeCommits", strconv.FormatBool(*args.IncludeCommits)) + } + locationId, _ := uuid.Parse("d43911ee-6958-46b0-a42b-8445b8a0d004") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.2", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []GitPullRequestIteration + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetPullRequestIterations function +type GetPullRequestIterationsArgs struct { + // (required) ID or name of the repository. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (optional) Project ID or project name + Project *string + // (optional) If true, include the commits associated with each iteration in the response. + IncludeCommits *bool +} + +// [Preview API] Get the specific pull request iteration status by ID. The status ID is unique within the pull request across all iterations. +func (client *ClientImpl) GetPullRequestIterationStatus(ctx context.Context, args GetPullRequestIterationStatusArgs) (*GitPullRequestStatus, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + if args.IterationId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.IterationId"} + } + routeValues["iterationId"] = strconv.Itoa(*args.IterationId) + if args.StatusId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.StatusId"} + } + routeValues["statusId"] = strconv.Itoa(*args.StatusId) + + locationId, _ := uuid.Parse("75cf11c5-979f-4038-a76e-058a06adf2bf") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitPullRequestStatus + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetPullRequestIterationStatus function +type GetPullRequestIterationStatusArgs struct { + // (required) The repository ID of the pull request’s target branch. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (required) ID of the pull request iteration. + IterationId *int + // (required) ID of the pull request status. + StatusId *int + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Get all the statuses associated with a pull request iteration. +func (client *ClientImpl) GetPullRequestIterationStatuses(ctx context.Context, args GetPullRequestIterationStatusesArgs) (*[]GitPullRequestStatus, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + if args.IterationId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.IterationId"} + } + routeValues["iterationId"] = strconv.Itoa(*args.IterationId) + + locationId, _ := uuid.Parse("75cf11c5-979f-4038-a76e-058a06adf2bf") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []GitPullRequestStatus + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetPullRequestIterationStatuses function +type GetPullRequestIterationStatusesArgs struct { + // (required) The repository ID of the pull request’s target branch. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (required) ID of the pull request iteration. + IterationId *int + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Retrieves a single label that has been assigned to a pull request. +func (client *ClientImpl) GetPullRequestLabel(ctx context.Context, args GetPullRequestLabelArgs) (*core.WebApiTagDefinition, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + if args.LabelIdOrName == nil || *args.LabelIdOrName == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.LabelIdOrName"} + } + routeValues["labelIdOrName"] = *args.LabelIdOrName + + queryParams := url.Values{} + if args.ProjectId != nil { + queryParams.Add("projectId", *args.ProjectId) + } + locationId, _ := uuid.Parse("f22387e3-984e-4c52-9c6d-fbb8f14c812d") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue core.WebApiTagDefinition + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetPullRequestLabel function +type GetPullRequestLabelArgs struct { + // (required) The repository ID of the pull request’s target branch. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (required) The name or ID of the label requested. + LabelIdOrName *string + // (optional) Project ID or project name + Project *string + // (optional) Project ID or project name. + ProjectId *string +} + +// [Preview API] Get all the labels assigned to a pull request. +func (client *ClientImpl) GetPullRequestLabels(ctx context.Context, args GetPullRequestLabelsArgs) (*[]core.WebApiTagDefinition, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + + queryParams := url.Values{} + if args.ProjectId != nil { + queryParams.Add("projectId", *args.ProjectId) + } + locationId, _ := uuid.Parse("f22387e3-984e-4c52-9c6d-fbb8f14c812d") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []core.WebApiTagDefinition + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetPullRequestLabels function +type GetPullRequestLabelsArgs struct { + // (required) The repository ID of the pull request’s target branch. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (optional) Project ID or project name + Project *string + // (optional) Project ID or project name. + ProjectId *string +} + +// [Preview API] Get external properties of the pull request. +func (client *ClientImpl) GetPullRequestProperties(ctx context.Context, args GetPullRequestPropertiesArgs) (interface{}, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + + locationId, _ := uuid.Parse("48a52185-5b9e-4736-9dc1-bb1e2feac80b") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue interface{} + err = client.Client.UnmarshalBody(resp, responseValue) + return responseValue, err +} + +// Arguments for the GetPullRequestProperties function +type GetPullRequestPropertiesArgs struct { + // (required) The repository ID of the pull request’s target branch. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (optional) Project ID or project name + Project *string +} + +// [Preview API] This API is used to find what pull requests are related to a given commit. It can be used to either find the pull request that created a particular merge commit or it can be used to find all pull requests that have ever merged a particular commit. The input is a list of queries which each contain a list of commits. For each commit that you search against, you will get back a dictionary of commit -> pull requests. +func (client *ClientImpl) GetPullRequestQuery(ctx context.Context, args GetPullRequestQueryArgs) (*GitPullRequestQuery, error) { + if args.Queries == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.Queries"} + } + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + + body, marshalErr := json.Marshal(*args.Queries) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("b3a6eebe-9cf0-49ea-b6cb-1a4c5f5007b0") + resp, err := client.Client.Send(ctx, http.MethodPost, locationId, "7.1-preview.1", routeValues, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitPullRequestQuery + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetPullRequestQuery function +type GetPullRequestQueryArgs struct { + // (required) The list of queries to perform. + Queries *GitPullRequestQuery + // (required) ID of the repository. + RepositoryId *string + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Retrieve information about a particular reviewer on a pull request +func (client *ClientImpl) GetPullRequestReviewer(ctx context.Context, args GetPullRequestReviewerArgs) (*IdentityRefWithVote, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + if args.ReviewerId == nil || *args.ReviewerId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.ReviewerId"} + } + routeValues["reviewerId"] = *args.ReviewerId + + locationId, _ := uuid.Parse("4b6702c7-aa35-4b89-9c96-b9abf6d3e540") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue IdentityRefWithVote + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetPullRequestReviewer function +type GetPullRequestReviewerArgs struct { + // (required) The repository ID of the pull request's target branch. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (required) ID of the reviewer. + ReviewerId *string + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Retrieve the reviewers for a pull request +func (client *ClientImpl) GetPullRequestReviewers(ctx context.Context, args GetPullRequestReviewersArgs) (*[]IdentityRefWithVote, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + + locationId, _ := uuid.Parse("4b6702c7-aa35-4b89-9c96-b9abf6d3e540") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []IdentityRefWithVote + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetPullRequestReviewers function +type GetPullRequestReviewersArgs struct { + // (required) The repository ID of the pull request's target branch. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Retrieve all pull requests matching a specified criteria. +func (client *ClientImpl) GetPullRequests(ctx context.Context, args GetPullRequestsArgs) (*[]GitPullRequest, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + + queryParams := url.Values{} + if args.SearchCriteria == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "searchCriteria"} + } + if args.SearchCriteria.RepositoryId != nil { + queryParams.Add("searchCriteria.repositoryId", (*args.SearchCriteria.RepositoryId).String()) + } + if args.SearchCriteria.CreatorId != nil { + queryParams.Add("searchCriteria.creatorId", (*args.SearchCriteria.CreatorId).String()) + } + if args.SearchCriteria.ReviewerId != nil { + queryParams.Add("searchCriteria.reviewerId", (*args.SearchCriteria.ReviewerId).String()) + } + if args.SearchCriteria.Status != nil { + queryParams.Add("searchCriteria.status", string(*args.SearchCriteria.Status)) + } + if args.SearchCriteria.TargetRefName != nil { + queryParams.Add("searchCriteria.targetRefName", *args.SearchCriteria.TargetRefName) + } + if args.SearchCriteria.SourceRepositoryId != nil { + queryParams.Add("searchCriteria.sourceRepositoryId", (*args.SearchCriteria.SourceRepositoryId).String()) + } + if args.SearchCriteria.SourceRefName != nil { + queryParams.Add("searchCriteria.sourceRefName", *args.SearchCriteria.SourceRefName) + } + if args.SearchCriteria.IncludeLinks != nil { + queryParams.Add("searchCriteria.includeLinks", strconv.FormatBool(*args.SearchCriteria.IncludeLinks)) + } + if args.MaxCommentLength != nil { + queryParams.Add("maxCommentLength", strconv.Itoa(*args.MaxCommentLength)) + } + if args.Skip != nil { + queryParams.Add("$skip", strconv.Itoa(*args.Skip)) + } + if args.Top != nil { + queryParams.Add("$top", strconv.Itoa(*args.Top)) + } + locationId, _ := uuid.Parse("9946fd70-0d40-406e-b686-b4744cbbcc37") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []GitPullRequest + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetPullRequests function +type GetPullRequestsArgs struct { + // (required) The repository ID of the pull request's target branch. + RepositoryId *string + // (required) Pull requests will be returned that match this search criteria. + SearchCriteria *GitPullRequestSearchCriteria + // (optional) Project ID or project name + Project *string + // (optional) Not used. + MaxCommentLength *int + // (optional) The number of pull requests to ignore. For example, to retrieve results 101-150, set top to 50 and skip to 100. + Skip *int + // (optional) The number of pull requests to retrieve. + Top *int +} + +// [Preview API] Retrieve all pull requests matching a specified criteria. +func (client *ClientImpl) GetPullRequestsByProject(ctx context.Context, args GetPullRequestsByProjectArgs) (*[]GitPullRequest, error) { + routeValues := make(map[string]string) + if args.Project == nil || *args.Project == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.Project"} + } + routeValues["project"] = *args.Project + + queryParams := url.Values{} + if args.SearchCriteria == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "searchCriteria"} + } + if args.SearchCriteria.RepositoryId != nil { + queryParams.Add("searchCriteria.repositoryId", (*args.SearchCriteria.RepositoryId).String()) + } + if args.SearchCriteria.CreatorId != nil { + queryParams.Add("searchCriteria.creatorId", (*args.SearchCriteria.CreatorId).String()) + } + if args.SearchCriteria.ReviewerId != nil { + queryParams.Add("searchCriteria.reviewerId", (*args.SearchCriteria.ReviewerId).String()) + } + if args.SearchCriteria.Status != nil { + queryParams.Add("searchCriteria.status", string(*args.SearchCriteria.Status)) + } + if args.SearchCriteria.TargetRefName != nil { + queryParams.Add("searchCriteria.targetRefName", *args.SearchCriteria.TargetRefName) + } + if args.SearchCriteria.SourceRepositoryId != nil { + queryParams.Add("searchCriteria.sourceRepositoryId", (*args.SearchCriteria.SourceRepositoryId).String()) + } + if args.SearchCriteria.SourceRefName != nil { + queryParams.Add("searchCriteria.sourceRefName", *args.SearchCriteria.SourceRefName) + } + if args.SearchCriteria.IncludeLinks != nil { + queryParams.Add("searchCriteria.includeLinks", strconv.FormatBool(*args.SearchCriteria.IncludeLinks)) + } + if args.MaxCommentLength != nil { + queryParams.Add("maxCommentLength", strconv.Itoa(*args.MaxCommentLength)) + } + if args.Skip != nil { + queryParams.Add("$skip", strconv.Itoa(*args.Skip)) + } + if args.Top != nil { + queryParams.Add("$top", strconv.Itoa(*args.Top)) + } + locationId, _ := uuid.Parse("a5d28130-9cd2-40fa-9f08-902e7daa9efb") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []GitPullRequest + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetPullRequestsByProject function +type GetPullRequestsByProjectArgs struct { + // (required) Project ID or project name + Project *string + // (required) Pull requests will be returned that match this search criteria. + SearchCriteria *GitPullRequestSearchCriteria + // (optional) Not used. + MaxCommentLength *int + // (optional) The number of pull requests to ignore. For example, to retrieve results 101-150, set top to 50 and skip to 100. + Skip *int + // (optional) The number of pull requests to retrieve. + Top *int +} + +// [Preview API] Get the specific pull request status by ID. The status ID is unique within the pull request across all iterations. +func (client *ClientImpl) GetPullRequestStatus(ctx context.Context, args GetPullRequestStatusArgs) (*GitPullRequestStatus, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + if args.StatusId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.StatusId"} + } + routeValues["statusId"] = strconv.Itoa(*args.StatusId) + + locationId, _ := uuid.Parse("b5f6bb4f-8d1e-4d79-8d11-4c9172c99c35") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitPullRequestStatus + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetPullRequestStatus function +type GetPullRequestStatusArgs struct { + // (required) The repository ID of the pull request’s target branch. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (required) ID of the pull request status. + StatusId *int + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Get all the statuses associated with a pull request. +func (client *ClientImpl) GetPullRequestStatuses(ctx context.Context, args GetPullRequestStatusesArgs) (*[]GitPullRequestStatus, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + + locationId, _ := uuid.Parse("b5f6bb4f-8d1e-4d79-8d11-4c9172c99c35") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []GitPullRequestStatus + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetPullRequestStatuses function +type GetPullRequestStatusesArgs struct { + // (required) The repository ID of the pull request’s target branch. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Retrieve a thread in a pull request. +func (client *ClientImpl) GetPullRequestThread(ctx context.Context, args GetPullRequestThreadArgs) (*GitPullRequestCommentThread, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + if args.ThreadId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.ThreadId"} + } + routeValues["threadId"] = strconv.Itoa(*args.ThreadId) + + queryParams := url.Values{} + if args.Iteration != nil { + queryParams.Add("$iteration", strconv.Itoa(*args.Iteration)) + } + if args.BaseIteration != nil { + queryParams.Add("$baseIteration", strconv.Itoa(*args.BaseIteration)) + } + locationId, _ := uuid.Parse("ab6e2e5d-a0b7-4153-b64a-a4efe0d49449") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitPullRequestCommentThread + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetPullRequestThread function +type GetPullRequestThreadArgs struct { + // (required) The repository ID of the pull request's target branch. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (required) ID of the thread. + ThreadId *int + // (optional) Project ID or project name + Project *string + // (optional) If specified, thread position will be tracked using this iteration as the right side of the diff. + Iteration *int + // (optional) If specified, thread position will be tracked using this iteration as the left side of the diff. + BaseIteration *int +} + +// [Preview API] Retrieve a list of work items associated with a pull request. +func (client *ClientImpl) GetPullRequestWorkItemRefs(ctx context.Context, args GetPullRequestWorkItemRefsArgs) (*[]webapi.ResourceRef, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + + locationId, _ := uuid.Parse("0a637fcc-5370-4ce8-b0e8-98091f5f9482") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []webapi.ResourceRef + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetPullRequestWorkItemRefs function +type GetPullRequestWorkItemRefsArgs struct { + // (required) ID or name of the repository. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Retrieves a particular push. +func (client *ClientImpl) GetPush(ctx context.Context, args GetPushArgs) (*GitPush, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PushId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.PushId"} + } + routeValues["pushId"] = strconv.Itoa(*args.PushId) + + queryParams := url.Values{} + if args.IncludeCommits != nil { + queryParams.Add("includeCommits", strconv.Itoa(*args.IncludeCommits)) + } + if args.IncludeRefUpdates != nil { + queryParams.Add("includeRefUpdates", strconv.FormatBool(*args.IncludeRefUpdates)) + } + locationId, _ := uuid.Parse("ea98d07b-3c87-4971-8ede-a613694ffb55") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.2", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitPush + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetPush function +type GetPushArgs struct { + // (required) The name or ID of the repository. + RepositoryId *string + // (required) ID of the push. + PushId *int + // (optional) Project ID or project name + Project *string + // (optional) The number of commits to include in the result. + IncludeCommits *int + // (optional) If true, include the list of refs that were updated by the push. + IncludeRefUpdates *bool +} + +// [Preview API] Retrieve a list of commits associated with a particular push. +func (client *ClientImpl) GetPushCommits(ctx context.Context, args GetPushCommitsArgs) (*[]GitCommitRef, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + + queryParams := url.Values{} + if args.PushId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "pushId"} + } + queryParams.Add("pushId", strconv.Itoa(*args.PushId)) + if args.Top != nil { + queryParams.Add("top", strconv.Itoa(*args.Top)) + } + if args.Skip != nil { + queryParams.Add("skip", strconv.Itoa(*args.Skip)) + } + if args.IncludeLinks != nil { + queryParams.Add("includeLinks", strconv.FormatBool(*args.IncludeLinks)) + } + locationId, _ := uuid.Parse("c2570c3b-5b3f-41b8-98bf-5407bfde8d58") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []GitCommitRef + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetPushCommits function +type GetPushCommitsArgs struct { + // (required) The id or friendly name of the repository. To use the friendly name, projectId must also be specified. + RepositoryId *string + // (required) The id of the push. + PushId *int + // (optional) Project ID or project name + Project *string + // (optional) The maximum number of commits to return ("get the top x commits"). + Top *int + // (optional) The number of commits to skip. + Skip *int + // (optional) Set to false to avoid including REST Url links for resources. Defaults to true. + IncludeLinks *bool +} + +// [Preview API] Retrieves pushes associated with the specified repository. +func (client *ClientImpl) GetPushes(ctx context.Context, args GetPushesArgs) (*[]GitPush, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + + queryParams := url.Values{} + if args.Skip != nil { + queryParams.Add("$skip", strconv.Itoa(*args.Skip)) + } + if args.Top != nil { + queryParams.Add("$top", strconv.Itoa(*args.Top)) + } + if args.SearchCriteria != nil { + if args.SearchCriteria.FromDate != nil { + queryParams.Add("searchCriteria.fromDate", (*args.SearchCriteria.FromDate).AsQueryParameter()) + } + if args.SearchCriteria.ToDate != nil { + queryParams.Add("searchCriteria.toDate", (*args.SearchCriteria.ToDate).AsQueryParameter()) + } + if args.SearchCriteria.PusherId != nil { + queryParams.Add("searchCriteria.pusherId", (*args.SearchCriteria.PusherId).String()) + } + if args.SearchCriteria.RefName != nil { + queryParams.Add("searchCriteria.refName", *args.SearchCriteria.RefName) + } + if args.SearchCriteria.IncludeRefUpdates != nil { + queryParams.Add("searchCriteria.includeRefUpdates", strconv.FormatBool(*args.SearchCriteria.IncludeRefUpdates)) + } + if args.SearchCriteria.IncludeLinks != nil { + queryParams.Add("searchCriteria.includeLinks", strconv.FormatBool(*args.SearchCriteria.IncludeLinks)) + } + } + locationId, _ := uuid.Parse("ea98d07b-3c87-4971-8ede-a613694ffb55") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.2", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []GitPush + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetPushes function +type GetPushesArgs struct { + // (required) The name or ID of the repository. + RepositoryId *string + // (optional) Project ID or project name + Project *string + // (optional) Number of pushes to skip. + Skip *int + // (optional) Number of pushes to return. + Top *int + // (optional) Search criteria attributes: fromDate, toDate, pusherId, refName, includeRefUpdates or includeLinks. fromDate: Start date to search from. toDate: End date to search to. pusherId: Identity of the person who submitted the push. refName: Branch name to consider. includeRefUpdates: If true, include the list of refs that were updated by the push. includeLinks: Whether to include the _links field on the shallow references. + SearchCriteria *GitPushSearchCriteria +} + +// [Preview API] Retrieve soft-deleted git repositories from the recycle bin. +func (client *ClientImpl) GetRecycleBinRepositories(ctx context.Context, args GetRecycleBinRepositoriesArgs) (*[]GitDeletedRepository, error) { + routeValues := make(map[string]string) + if args.Project == nil || *args.Project == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.Project"} + } + routeValues["project"] = *args.Project + + locationId, _ := uuid.Parse("a663da97-81db-4eb3-8b83-287670f63073") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []GitDeletedRepository + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetRecycleBinRepositories function +type GetRecycleBinRepositoriesArgs struct { + // (required) Project ID or project name + Project *string +} + +// [Preview API] Gets the refs favorite for a favorite Id. +func (client *ClientImpl) GetRefFavorite(ctx context.Context, args GetRefFavoriteArgs) (*GitRefFavorite, error) { + routeValues := make(map[string]string) + if args.Project == nil || *args.Project == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.Project"} + } + routeValues["project"] = *args.Project + if args.FavoriteId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.FavoriteId"} + } + routeValues["favoriteId"] = strconv.Itoa(*args.FavoriteId) + + locationId, _ := uuid.Parse("876f70af-5792-485a-a1c7-d0a7b2f42bbb") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitRefFavorite + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetRefFavorite function +type GetRefFavoriteArgs struct { + // (required) Project ID or project name + Project *string + // (required) The Id of the requested ref favorite. + FavoriteId *int +} + +// [Preview API] Gets the refs favorites for a repo and an identity. +func (client *ClientImpl) GetRefFavorites(ctx context.Context, args GetRefFavoritesArgs) (*[]GitRefFavorite, error) { + routeValues := make(map[string]string) + if args.Project == nil || *args.Project == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.Project"} + } + routeValues["project"] = *args.Project + + queryParams := url.Values{} + if args.RepositoryId != nil { + queryParams.Add("repositoryId", *args.RepositoryId) + } + if args.IdentityId != nil { + queryParams.Add("identityId", *args.IdentityId) + } + locationId, _ := uuid.Parse("876f70af-5792-485a-a1c7-d0a7b2f42bbb") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []GitRefFavorite + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetRefFavorites function +type GetRefFavoritesArgs struct { + // (required) Project ID or project name + Project *string + // (optional) The id of the repository. + RepositoryId *string + // (optional) The id of the identity whose favorites are to be retrieved. If null, the requesting identity is used. + IdentityId *string +} + +// [Preview API] Queries the provided repository for its refs and returns them. +func (client *ClientImpl) GetRefs(ctx context.Context, args GetRefsArgs) (*GetRefsResponseValue, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + + queryParams := url.Values{} + if args.Filter != nil { + queryParams.Add("filter", *args.Filter) + } + if args.IncludeLinks != nil { + queryParams.Add("includeLinks", strconv.FormatBool(*args.IncludeLinks)) + } + if args.IncludeStatuses != nil { + queryParams.Add("includeStatuses", strconv.FormatBool(*args.IncludeStatuses)) + } + if args.IncludeMyBranches != nil { + queryParams.Add("includeMyBranches", strconv.FormatBool(*args.IncludeMyBranches)) + } + if args.LatestStatusesOnly != nil { + queryParams.Add("latestStatusesOnly", strconv.FormatBool(*args.LatestStatusesOnly)) + } + if args.PeelTags != nil { + queryParams.Add("peelTags", strconv.FormatBool(*args.PeelTags)) + } + if args.FilterContains != nil { + queryParams.Add("filterContains", *args.FilterContains) + } + if args.Top != nil { + queryParams.Add("$top", strconv.Itoa(*args.Top)) + } + if args.ContinuationToken != nil { + queryParams.Add("continuationToken", *args.ContinuationToken) + } + locationId, _ := uuid.Parse("2d874a60-a811-4f62-9c9f-963a6ea0a55b") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GetRefsResponseValue + responseValue.ContinuationToken = resp.Header.Get(azuredevops.HeaderKeyContinuationToken) + err = client.Client.UnmarshalCollectionBody(resp, &responseValue.Value) + return &responseValue, err +} + +// Arguments for the GetRefs function +type GetRefsArgs struct { + // (required) The name or ID of the repository. + RepositoryId *string + // (optional) Project ID or project name + Project *string + // (optional) [optional] A filter to apply to the refs (starts with). + Filter *string + // (optional) [optional] Specifies if referenceLinks should be included in the result. default is false. + IncludeLinks *bool + // (optional) [optional] Includes up to the first 1000 commit statuses for each ref. The default value is false. + IncludeStatuses *bool + // (optional) [optional] Includes only branches that the user owns, the branches the user favorites, and the default branch. The default value is false. Cannot be combined with the filter parameter. + IncludeMyBranches *bool + // (optional) [optional] True to include only the tip commit status for each ref. This option requires `includeStatuses` to be true. The default value is false. + LatestStatusesOnly *bool + // (optional) [optional] Annotated tags will populate the PeeledObjectId property. default is false. + PeelTags *bool + // (optional) [optional] A filter to apply to the refs (contains). + FilterContains *string + // (optional) [optional] Maximum number of refs to return. It cannot be bigger than 1000. If it is not provided but continuationToken is, top will default to 100. + Top *int + // (optional) The continuation token used for pagination. + ContinuationToken *string +} + +// Return type for the GetRefs function +type GetRefsResponseValue struct { + Value []GitRef + ContinuationToken string +} + +// [Preview API] Retrieve git repositories. +func (client *ClientImpl) GetRepositories(ctx context.Context, args GetRepositoriesArgs) (*[]GitRepository, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + + queryParams := url.Values{} + if args.IncludeLinks != nil { + queryParams.Add("includeLinks", strconv.FormatBool(*args.IncludeLinks)) + } + if args.IncludeAllUrls != nil { + queryParams.Add("includeAllUrls", strconv.FormatBool(*args.IncludeAllUrls)) + } + if args.IncludeHidden != nil { + queryParams.Add("includeHidden", strconv.FormatBool(*args.IncludeHidden)) + } + locationId, _ := uuid.Parse("225f7195-f9c7-4d14-ab28-a83f7ff77e1f") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []GitRepository + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetRepositories function +type GetRepositoriesArgs struct { + // (optional) Project ID or project name + Project *string + // (optional) [optional] True to include reference links. The default value is false. + IncludeLinks *bool + // (optional) [optional] True to include all remote URLs. The default value is false. + IncludeAllUrls *bool + // (optional) [optional] True to include hidden repositories. The default value is false. + IncludeHidden *bool +} + +// [Preview API] Retrieve a git repository. +func (client *ClientImpl) GetRepository(ctx context.Context, args GetRepositoryArgs) (*GitRepository, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + + locationId, _ := uuid.Parse("225f7195-f9c7-4d14-ab28-a83f7ff77e1f") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitRepository + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetRepository function +type GetRepositoryArgs struct { + // (required) The name or ID of the repository. + RepositoryId *string + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Retrieve a git repository. +func (client *ClientImpl) GetRepositoryWithParent(ctx context.Context, args GetRepositoryWithParentArgs) (*GitRepository, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + + queryParams := url.Values{} + if args.IncludeParent == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "includeParent"} + } + queryParams.Add("includeParent", strconv.FormatBool(*args.IncludeParent)) + locationId, _ := uuid.Parse("225f7195-f9c7-4d14-ab28-a83f7ff77e1f") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitRepository + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetRepositoryWithParent function +type GetRepositoryWithParentArgs struct { + // (required) The name or ID of the repository. + RepositoryId *string + // (required) True to include parent repository. Only available in authenticated calls. + IncludeParent *bool + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Retrieve information about a revert operation by revert Id. +func (client *ClientImpl) GetRevert(ctx context.Context, args GetRevertArgs) (*GitRevert, error) { + routeValues := make(map[string]string) + if args.Project == nil || *args.Project == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.Project"} + } + routeValues["project"] = *args.Project + if args.RevertId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.RevertId"} + } + routeValues["revertId"] = strconv.Itoa(*args.RevertId) + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + + locationId, _ := uuid.Parse("bc866058-5449-4715-9cf1-a510b6ff193c") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitRevert + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetRevert function +type GetRevertArgs struct { + // (required) Project ID or project name + Project *string + // (required) ID of the revert operation. + RevertId *int + // (required) ID of the repository. + RepositoryId *string +} + +// [Preview API] Retrieve information about a revert operation for a specific branch. +func (client *ClientImpl) GetRevertForRefName(ctx context.Context, args GetRevertForRefNameArgs) (*GitRevert, error) { + routeValues := make(map[string]string) + if args.Project == nil || *args.Project == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.Project"} + } + routeValues["project"] = *args.Project + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + + queryParams := url.Values{} + if args.RefName == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "refName"} + } + queryParams.Add("refName", *args.RefName) + locationId, _ := uuid.Parse("bc866058-5449-4715-9cf1-a510b6ff193c") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitRevert + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetRevertForRefName function +type GetRevertForRefNameArgs struct { + // (required) Project ID or project name + Project *string + // (required) ID of the repository. + RepositoryId *string + // (required) The GitAsyncRefOperationParameters generatedRefName used for the revert operation. + RefName *string +} + +// [Preview API] Get statuses associated with the Git commit. +func (client *ClientImpl) GetStatuses(ctx context.Context, args GetStatusesArgs) (*[]GitStatus, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.CommitId == nil || *args.CommitId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.CommitId"} + } + routeValues["commitId"] = *args.CommitId + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + + queryParams := url.Values{} + if args.Top != nil { + queryParams.Add("top", strconv.Itoa(*args.Top)) + } + if args.Skip != nil { + queryParams.Add("skip", strconv.Itoa(*args.Skip)) + } + if args.LatestOnly != nil { + queryParams.Add("latestOnly", strconv.FormatBool(*args.LatestOnly)) + } + locationId, _ := uuid.Parse("428dd4fb-fda5-4722-af02-9313b80305da") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []GitStatus + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetStatuses function +type GetStatusesArgs struct { + // (required) ID of the Git commit. + CommitId *string + // (required) ID of the repository. + RepositoryId *string + // (optional) Project ID or project name + Project *string + // (optional) Optional. The number of statuses to retrieve. Default is 1000. + Top *int + // (optional) Optional. The number of statuses to ignore. Default is 0. For example, to retrieve results 101-150, set top to 50 and skip to 100. + Skip *int + // (optional) The flag indicates whether to get only latest statuses grouped by `Context.Name` and `Context.Genre`. + LatestOnly *bool +} + +// [Preview API] Retrieve a pull request suggestion for a particular repository or team project. +func (client *ClientImpl) GetSuggestions(ctx context.Context, args GetSuggestionsArgs) (*[]GitSuggestion, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + + locationId, _ := uuid.Parse("9393b4fb-4445-4919-972b-9ad16f442d83") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []GitSuggestion + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetSuggestions function +type GetSuggestionsArgs struct { + // (required) ID of the git repository. + RepositoryId *string + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Retrieve all threads in a pull request. +func (client *ClientImpl) GetThreads(ctx context.Context, args GetThreadsArgs) (*[]GitPullRequestCommentThread, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + + queryParams := url.Values{} + if args.Iteration != nil { + queryParams.Add("$iteration", strconv.Itoa(*args.Iteration)) + } + if args.BaseIteration != nil { + queryParams.Add("$baseIteration", strconv.Itoa(*args.BaseIteration)) + } + locationId, _ := uuid.Parse("ab6e2e5d-a0b7-4153-b64a-a4efe0d49449") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []GitPullRequestCommentThread + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetThreads function +type GetThreadsArgs struct { + // (required) The repository ID of the pull request's target branch. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (optional) Project ID or project name + Project *string + // (optional) If specified, thread positions will be tracked using this iteration as the right side of the diff. + Iteration *int + // (optional) If specified, thread positions will be tracked using this iteration as the left side of the diff. + BaseIteration *int +} + +// [Preview API] The Tree endpoint returns the collection of objects underneath the specified tree. Trees are folders in a Git repository. +func (client *ClientImpl) GetTree(ctx context.Context, args GetTreeArgs) (*GitTreeRef, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.Sha1 == nil || *args.Sha1 == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.Sha1"} + } + routeValues["sha1"] = *args.Sha1 + + queryParams := url.Values{} + if args.ProjectId != nil { + queryParams.Add("projectId", *args.ProjectId) + } + if args.Recursive != nil { + queryParams.Add("recursive", strconv.FormatBool(*args.Recursive)) + } + if args.FileName != nil { + queryParams.Add("fileName", *args.FileName) + } + locationId, _ := uuid.Parse("729f6437-6f92-44ec-8bee-273a7111063c") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitTreeRef + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetTree function +type GetTreeArgs struct { + // (required) Repository Id. + RepositoryId *string + // (required) SHA1 hash of the tree object. + Sha1 *string + // (optional) Project ID or project name + Project *string + // (optional) Project Id. + ProjectId *string + // (optional) Search recursively. Include trees underneath this tree. Default is false. + Recursive *bool + // (optional) Name to use if a .zip file is returned. Default is the object ID. + FileName *string +} + +// [Preview API] The Tree endpoint returns the collection of objects underneath the specified tree. Trees are folders in a Git repository. +func (client *ClientImpl) GetTreeZip(ctx context.Context, args GetTreeZipArgs) (io.ReadCloser, error) { + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.Sha1 == nil || *args.Sha1 == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.Sha1"} + } + routeValues["sha1"] = *args.Sha1 + + queryParams := url.Values{} + if args.ProjectId != nil { + queryParams.Add("projectId", *args.ProjectId) + } + if args.Recursive != nil { + queryParams.Add("recursive", strconv.FormatBool(*args.Recursive)) + } + if args.FileName != nil { + queryParams.Add("fileName", *args.FileName) + } + locationId, _ := uuid.Parse("729f6437-6f92-44ec-8bee-273a7111063c") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/zip", nil) + if err != nil { + return nil, err + } + + return resp.Body, err +} + +// Arguments for the GetTreeZip function +type GetTreeZipArgs struct { + // (required) Repository Id. + RepositoryId *string + // (required) SHA1 hash of the tree object. + Sha1 *string + // (optional) Project ID or project name + Project *string + // (optional) Project Id. + ProjectId *string + // (optional) Search recursively. Include trees underneath this tree. Default is false. + Recursive *bool + // (optional) Name to use if a .zip file is returned. Default is the object ID. + FileName *string +} + +// [Preview API] Retrieve import requests for a repository. +func (client *ClientImpl) QueryImportRequests(ctx context.Context, args QueryImportRequestsArgs) (*[]GitImportRequest, error) { + routeValues := make(map[string]string) + if args.Project == nil || *args.Project == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.Project"} + } + routeValues["project"] = *args.Project + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + + queryParams := url.Values{} + if args.IncludeAbandoned != nil { + queryParams.Add("includeAbandoned", strconv.FormatBool(*args.IncludeAbandoned)) + } + locationId, _ := uuid.Parse("01828ddc-3600-4a41-8633-99b3a73a0eb3") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []GitImportRequest + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the QueryImportRequests function +type QueryImportRequestsArgs struct { + // (required) Project ID or project name + Project *string + // (required) The name or ID of the repository. + RepositoryId *string + // (optional) True to include abandoned import requests in the results. + IncludeAbandoned *bool +} + +// [Preview API] Recover a soft-deleted Git repository. Recently deleted repositories go into a soft-delete state for a period of time before they are hard deleted and become unrecoverable. +func (client *ClientImpl) RestoreRepositoryFromRecycleBin(ctx context.Context, args RestoreRepositoryFromRecycleBinArgs) (*GitRepository, error) { + if args.RepositoryDetails == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.RepositoryDetails"} + } + routeValues := make(map[string]string) + if args.Project == nil || *args.Project == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.Project"} + } + routeValues["project"] = *args.Project + if args.RepositoryId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = (*args.RepositoryId).String() + + body, marshalErr := json.Marshal(*args.RepositoryDetails) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("a663da97-81db-4eb3-8b83-287670f63073") + resp, err := client.Client.Send(ctx, http.MethodPatch, locationId, "7.1-preview.1", routeValues, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitRepository + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the RestoreRepositoryFromRecycleBin function +type RestoreRepositoryFromRecycleBinArgs struct { + // (required) + RepositoryDetails *GitRecycleBinRepositoryDetails + // (required) Project ID or project name + Project *string + // (required) The ID of the repository. + RepositoryId *uuid.UUID +} + +// [Preview API] Sends an e-mail notification about a specific pull request to a set of recipients +func (client *ClientImpl) SharePullRequest(ctx context.Context, args SharePullRequestArgs) error { + if args.UserMessage == nil { + return &azuredevops.ArgumentNilError{ArgumentName: "args.UserMessage"} + } + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + + body, marshalErr := json.Marshal(*args.UserMessage) + if marshalErr != nil { + return marshalErr + } + locationId, _ := uuid.Parse("696f3a82-47c9-487f-9117-b9d00972ca84") + _, err := client.Client.Send(ctx, http.MethodPost, locationId, "7.1-preview.1", routeValues, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return err + } + + return nil +} + +// Arguments for the SharePullRequest function +type SharePullRequestArgs struct { + // (required) + UserMessage *ShareNotificationContext + // (required) ID of the git repository. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Update a comment associated with a specific thread in a pull request. +func (client *ClientImpl) UpdateComment(ctx context.Context, args UpdateCommentArgs) (*Comment, error) { + if args.Comment == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.Comment"} + } + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + if args.ThreadId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.ThreadId"} + } + routeValues["threadId"] = strconv.Itoa(*args.ThreadId) + if args.CommentId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.CommentId"} + } + routeValues["commentId"] = strconv.Itoa(*args.CommentId) + + body, marshalErr := json.Marshal(*args.Comment) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("965a3ec7-5ed8-455a-bdcb-835a5ea7fe7b") + resp, err := client.Client.Send(ctx, http.MethodPatch, locationId, "7.1-preview.1", routeValues, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue Comment + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the UpdateComment function +type UpdateCommentArgs struct { + // (required) The comment content that should be updated. Comments can be up to 150,000 characters. + Comment *Comment + // (required) The repository ID of the pull request's target branch. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (required) ID of the thread that the desired comment is in. + ThreadId *int + // (required) ID of the comment to update. + CommentId *int + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Retry or abandon a failed import request. +func (client *ClientImpl) UpdateImportRequest(ctx context.Context, args UpdateImportRequestArgs) (*GitImportRequest, error) { + if args.ImportRequestToUpdate == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.ImportRequestToUpdate"} + } + routeValues := make(map[string]string) + if args.Project == nil || *args.Project == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.Project"} + } + routeValues["project"] = *args.Project + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.ImportRequestId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.ImportRequestId"} + } + routeValues["importRequestId"] = strconv.Itoa(*args.ImportRequestId) + + body, marshalErr := json.Marshal(*args.ImportRequestToUpdate) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("01828ddc-3600-4a41-8633-99b3a73a0eb3") + resp, err := client.Client.Send(ctx, http.MethodPatch, locationId, "7.1-preview.1", routeValues, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitImportRequest + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the UpdateImportRequest function +type UpdateImportRequestArgs struct { + // (required) The updated version of the import request. Currently, the only change allowed is setting the Status to Queued or Abandoned. + ImportRequestToUpdate *GitImportRequest + // (required) Project ID or project name + Project *string + // (required) The name or ID of the repository. + RepositoryId *string + // (required) The unique identifier for the import request to update. + ImportRequestId *int +} + +// [Preview API] Update a pull request +func (client *ClientImpl) UpdatePullRequest(ctx context.Context, args UpdatePullRequestArgs) (*GitPullRequest, error) { + if args.GitPullRequestToUpdate == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.GitPullRequestToUpdate"} + } + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + + body, marshalErr := json.Marshal(*args.GitPullRequestToUpdate) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("9946fd70-0d40-406e-b686-b4744cbbcc37") + resp, err := client.Client.Send(ctx, http.MethodPatch, locationId, "7.1-preview.1", routeValues, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitPullRequest + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the UpdatePullRequest function +type UpdatePullRequestArgs struct { + // (required) The pull request content that should be updated. + GitPullRequestToUpdate *GitPullRequest + // (required) The repository ID of the pull request's target branch. + RepositoryId *string + // (required) ID of the pull request to update. + PullRequestId *int + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Update pull request iteration statuses collection. The only supported operation type is `remove`. +func (client *ClientImpl) UpdatePullRequestIterationStatuses(ctx context.Context, args UpdatePullRequestIterationStatusesArgs) error { + if args.PatchDocument == nil { + return &azuredevops.ArgumentNilError{ArgumentName: "args.PatchDocument"} + } + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + if args.IterationId == nil { + return &azuredevops.ArgumentNilError{ArgumentName: "args.IterationId"} + } + routeValues["iterationId"] = strconv.Itoa(*args.IterationId) + + body, marshalErr := json.Marshal(*args.PatchDocument) + if marshalErr != nil { + return marshalErr + } + locationId, _ := uuid.Parse("75cf11c5-979f-4038-a76e-058a06adf2bf") + _, err := client.Client.Send(ctx, http.MethodPatch, locationId, "7.1-preview.1", routeValues, nil, bytes.NewReader(body), "application/json-patch+json", "application/json", nil) + if err != nil { + return err + } + + return nil +} + +// Arguments for the UpdatePullRequestIterationStatuses function +type UpdatePullRequestIterationStatusesArgs struct { + // (required) Operations to apply to the pull request statuses in JSON Patch format. + PatchDocument *[]webapi.JsonPatchOperation + // (required) The repository ID of the pull request’s target branch. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (required) ID of the pull request iteration. + IterationId *int + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Create or update pull request external properties. The patch operation can be `add`, `replace` or `remove`. For `add` operation, the path can be empty. If the path is empty, the value must be a list of key value pairs. For `replace` operation, the path cannot be empty. If the path does not exist, the property will be added to the collection. For `remove` operation, the path cannot be empty. If the path does not exist, no action will be performed. +func (client *ClientImpl) UpdatePullRequestProperties(ctx context.Context, args UpdatePullRequestPropertiesArgs) (interface{}, error) { + if args.PatchDocument == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.PatchDocument"} + } + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + + body, marshalErr := json.Marshal(*args.PatchDocument) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("48a52185-5b9e-4736-9dc1-bb1e2feac80b") + resp, err := client.Client.Send(ctx, http.MethodPatch, locationId, "7.1-preview.1", routeValues, nil, bytes.NewReader(body), "application/json-patch+json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue interface{} + err = client.Client.UnmarshalBody(resp, responseValue) + return responseValue, err +} + +// Arguments for the UpdatePullRequestProperties function +type UpdatePullRequestPropertiesArgs struct { + // (required) Properties to add, replace or remove in JSON Patch format. + PatchDocument *[]webapi.JsonPatchOperation + // (required) The repository ID of the pull request’s target branch. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Edit a reviewer entry. These fields are patchable: isFlagged, hasDeclined +func (client *ClientImpl) UpdatePullRequestReviewer(ctx context.Context, args UpdatePullRequestReviewerArgs) (*IdentityRefWithVote, error) { + if args.Reviewer == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.Reviewer"} + } + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + if args.ReviewerId == nil || *args.ReviewerId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.ReviewerId"} + } + routeValues["reviewerId"] = *args.ReviewerId + + body, marshalErr := json.Marshal(*args.Reviewer) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("4b6702c7-aa35-4b89-9c96-b9abf6d3e540") + resp, err := client.Client.Send(ctx, http.MethodPatch, locationId, "7.1-preview.1", routeValues, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue IdentityRefWithVote + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the UpdatePullRequestReviewer function +type UpdatePullRequestReviewerArgs struct { + // (required) Reviewer data.
If the reviewer's ID is included here, it must match the reviewerID parameter. + Reviewer *IdentityRefWithVote + // (required) The repository ID of the pull request's target branch. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (required) ID of the reviewer. + ReviewerId *string + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Reset the votes of multiple reviewers on a pull request. NOTE: This endpoint only supports updating votes, but does not support updating required reviewers (use policy) or display names. +func (client *ClientImpl) UpdatePullRequestReviewers(ctx context.Context, args UpdatePullRequestReviewersArgs) error { + if args.PatchVotes == nil { + return &azuredevops.ArgumentNilError{ArgumentName: "args.PatchVotes"} + } + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + + body, marshalErr := json.Marshal(*args.PatchVotes) + if marshalErr != nil { + return marshalErr + } + locationId, _ := uuid.Parse("4b6702c7-aa35-4b89-9c96-b9abf6d3e540") + _, err := client.Client.Send(ctx, http.MethodPatch, locationId, "7.1-preview.1", routeValues, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return err + } + + return nil +} + +// Arguments for the UpdatePullRequestReviewers function +type UpdatePullRequestReviewersArgs struct { + // (required) IDs of the reviewers whose votes will be reset to zero + PatchVotes *[]IdentityRefWithVote + // (required) The repository ID of the pull request's target branch. + RepositoryId *string + // (required) ID of the pull request + PullRequestId *int + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Update pull request statuses collection. The only supported operation type is `remove`. +func (client *ClientImpl) UpdatePullRequestStatuses(ctx context.Context, args UpdatePullRequestStatusesArgs) error { + if args.PatchDocument == nil { + return &azuredevops.ArgumentNilError{ArgumentName: "args.PatchDocument"} + } + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + + body, marshalErr := json.Marshal(*args.PatchDocument) + if marshalErr != nil { + return marshalErr + } + locationId, _ := uuid.Parse("b5f6bb4f-8d1e-4d79-8d11-4c9172c99c35") + _, err := client.Client.Send(ctx, http.MethodPatch, locationId, "7.1-preview.1", routeValues, nil, bytes.NewReader(body), "application/json-patch+json", "application/json", nil) + if err != nil { + return err + } + + return nil +} + +// Arguments for the UpdatePullRequestStatuses function +type UpdatePullRequestStatusesArgs struct { + // (required) Operations to apply to the pull request statuses in JSON Patch format. + PatchDocument *[]webapi.JsonPatchOperation + // (required) The repository ID of the pull request’s target branch. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Lock or Unlock a branch. +func (client *ClientImpl) UpdateRef(ctx context.Context, args UpdateRefArgs) (*GitRef, error) { + if args.NewRefInfo == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.NewRefInfo"} + } + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + + queryParams := url.Values{} + if args.Filter == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "filter"} + } + queryParams.Add("filter", *args.Filter) + if args.ProjectId != nil { + queryParams.Add("projectId", *args.ProjectId) + } + body, marshalErr := json.Marshal(*args.NewRefInfo) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("2d874a60-a811-4f62-9c9f-963a6ea0a55b") + resp, err := client.Client.Send(ctx, http.MethodPatch, locationId, "7.1-preview.1", routeValues, queryParams, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitRef + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the UpdateRef function +type UpdateRefArgs struct { + // (required) The ref update action (lock/unlock) to perform + NewRefInfo *GitRefUpdate + // (required) The name or ID of the repository. + RepositoryId *string + // (required) The name of the branch to lock/unlock + Filter *string + // (optional) Project ID or project name + Project *string + // (optional) ID or name of the team project. Optional if specifying an ID for repository. + ProjectId *string +} + +// [Preview API] Creating, updating, or deleting refs(branches). +func (client *ClientImpl) UpdateRefs(ctx context.Context, args UpdateRefsArgs) (*[]GitRefUpdateResult, error) { + if args.RefUpdates == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.RefUpdates"} + } + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + + queryParams := url.Values{} + if args.ProjectId != nil { + queryParams.Add("projectId", *args.ProjectId) + } + body, marshalErr := json.Marshal(*args.RefUpdates) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("2d874a60-a811-4f62-9c9f-963a6ea0a55b") + resp, err := client.Client.Send(ctx, http.MethodPost, locationId, "7.1-preview.1", routeValues, queryParams, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []GitRefUpdateResult + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the UpdateRefs function +type UpdateRefsArgs struct { + // (required) List of ref updates to attempt to perform + RefUpdates *[]GitRefUpdate + // (required) The name or ID of the repository. + RepositoryId *string + // (optional) Project ID or project name + Project *string + // (optional) ID or name of the team project. Optional if specifying an ID for repository. + ProjectId *string +} + +// [Preview API] Updates the Git repository with either a new repo name or a new default branch. +func (client *ClientImpl) UpdateRepository(ctx context.Context, args UpdateRepositoryArgs) (*GitRepository, error) { + if args.NewRepositoryInfo == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.NewRepositoryInfo"} + } + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = (*args.RepositoryId).String() + + body, marshalErr := json.Marshal(*args.NewRepositoryInfo) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("225f7195-f9c7-4d14-ab28-a83f7ff77e1f") + resp, err := client.Client.Send(ctx, http.MethodPatch, locationId, "7.1-preview.1", routeValues, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitRepository + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the UpdateRepository function +type UpdateRepositoryArgs struct { + // (required) Specify a new repo name or a new default branch of the repository + NewRepositoryInfo *GitRepository + // (required) The ID of the repository. + RepositoryId *uuid.UUID + // (optional) Project ID or project name + Project *string +} + +// [Preview API] Update a thread in a pull request. +func (client *ClientImpl) UpdateThread(ctx context.Context, args UpdateThreadArgs) (*GitPullRequestCommentThread, error) { + if args.CommentThread == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.CommentThread"} + } + routeValues := make(map[string]string) + if args.Project != nil && *args.Project != "" { + routeValues["project"] = *args.Project + } + if args.RepositoryId == nil || *args.RepositoryId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.RepositoryId"} + } + routeValues["repositoryId"] = *args.RepositoryId + if args.PullRequestId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.PullRequestId"} + } + routeValues["pullRequestId"] = strconv.Itoa(*args.PullRequestId) + if args.ThreadId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.ThreadId"} + } + routeValues["threadId"] = strconv.Itoa(*args.ThreadId) + + body, marshalErr := json.Marshal(*args.CommentThread) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("ab6e2e5d-a0b7-4153-b64a-a4efe0d49449") + resp, err := client.Client.Send(ctx, http.MethodPatch, locationId, "7.1-preview.1", routeValues, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GitPullRequestCommentThread + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the UpdateThread function +type UpdateThreadArgs struct { + // (required) The thread content that should be updated. + CommentThread *GitPullRequestCommentThread + // (required) The repository ID of the pull request's target branch. + RepositoryId *string + // (required) ID of the pull request. + PullRequestId *int + // (required) ID of the thread to update. + ThreadId *int + // (optional) Project ID or project name + Project *string +} diff --git a/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/git/models.go b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/git/models.go new file mode 100644 index 000000000..ebc04d8b1 --- /dev/null +++ b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/git/models.go @@ -0,0 +1,3392 @@ +// -------------------------------------------------------------------------------------------- +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// -------------------------------------------------------------------------------------------- +// Generated file, DO NOT EDIT +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// -------------------------------------------------------------------------------------------- + +package git + +import ( + "github.com/google/uuid" + "github.com/microsoft/azure-devops-go-api/azuredevops/v7" + "github.com/microsoft/azure-devops-go-api/azuredevops/v7/core" + "github.com/microsoft/azure-devops-go-api/azuredevops/v7/policy" + "github.com/microsoft/azure-devops-go-api/azuredevops/v7/webapi" +) + +type AdvSecEnablementStatus struct { + // Enabled status 0 disabled, 1 enabled, Null never explicitly set, always whatever project is, ya this should probably be an enum somewhere + Enabled *bool `json:"enabled,omitempty"` + // Enabled changed on datetime To Be Removed M223 + + EnabledChangedOnDate *azuredevops.Time `json:"enabledChangedOnDate,omitempty"` + // Enabled by VSID + ChangedById *uuid.UUID `json:"changedById,omitempty"` + // Enabled changed on datetime + ChangedOnDate *azuredevops.Time `json:"changedOnDate,omitempty"` + // ProjectId + ProjectId *uuid.UUID `json:"projectId,omitempty"` + // RepositoryId + RepositoryId *uuid.UUID `json:"repositoryId,omitempty"` +} + +type AdvSecEnablementUpdate struct { + // New status + NewStatus *bool `json:"newStatus,omitempty"` + // ProjectId + ProjectId *uuid.UUID `json:"projectId,omitempty"` + // RepositoryId Actual RepositoryId to Modify or Magic Repository Id "FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF" for ALL Repositories for that project + RepositoryId *uuid.UUID `json:"repositoryId,omitempty"` +} + +type AssociatedWorkItem struct { + AssignedTo *string `json:"assignedTo,omitempty"` + // Id of associated the work item. + Id *int `json:"id,omitempty"` + State *string `json:"state,omitempty"` + Title *string `json:"title,omitempty"` + // REST Url of the work item. + Url *string `json:"url,omitempty"` + WebUrl *string `json:"webUrl,omitempty"` + WorkItemType *string `json:"workItemType,omitempty"` +} + +type AsyncGitOperationNotification struct { + OperationId *int `json:"operationId,omitempty"` +} + +type AsyncRefOperationCommitLevelEventNotification struct { + OperationId *int `json:"operationId,omitempty"` + CommitId *string `json:"commitId,omitempty"` +} + +type AsyncRefOperationCompletedNotification struct { + OperationId *int `json:"operationId,omitempty"` + NewRefName *string `json:"newRefName,omitempty"` +} + +type AsyncRefOperationConflictNotification struct { + OperationId *int `json:"operationId,omitempty"` + CommitId *string `json:"commitId,omitempty"` +} + +type AsyncRefOperationGeneralFailureNotification struct { + OperationId *int `json:"operationId,omitempty"` +} + +type AsyncRefOperationProgressNotification struct { + OperationId *int `json:"operationId,omitempty"` + CommitId *string `json:"commitId,omitempty"` + Progress *float64 `json:"progress,omitempty"` +} + +type AsyncRefOperationTimeoutNotification struct { + OperationId *int `json:"operationId,omitempty"` +} + +// Meta data for a file attached to an artifact. +type Attachment struct { + // Links to other related objects. + Links interface{} `json:"_links,omitempty"` + // The person that uploaded this attachment. + Author *webapi.IdentityRef `json:"author,omitempty"` + // Content hash of on-disk representation of file content. Its calculated by the server by using SHA1 hash function. + ContentHash *string `json:"contentHash,omitempty"` + // The time the attachment was uploaded. + CreatedDate *azuredevops.Time `json:"createdDate,omitempty"` + // The description of the attachment. + Description *string `json:"description,omitempty"` + // The display name of the attachment. Can't be null or empty. + DisplayName *string `json:"displayName,omitempty"` + // Id of the attachment. + Id *int `json:"id,omitempty"` + // Extended properties. + Properties interface{} `json:"properties,omitempty"` + // The url to download the content of the attachment. + Url *string `json:"url,omitempty"` +} + +// Real time event (SignalR) for an auto-complete update on a pull request +type AutoCompleteUpdatedEvent struct { + // The id of this event. Can be used to track send/receive state between client and server. + EventId *uuid.UUID `json:"eventId,omitempty"` + // The id of the pull request this event was generated for. + PullRequestId *int `json:"pullRequestId,omitempty"` +} + +// Used by AdvSec to return billable committers. +type BillableCommitter struct { + // RepositoryId commit was pushed to. + RepoId *uuid.UUID `json:"repoId,omitempty"` + // Visual Studio ID /Team Foundation ID + Vsid *uuid.UUID `json:"vsid,omitempty"` +} + +type BillableCommitterDetail struct { + // RepositoryId commit was pushed to. + RepoId *uuid.UUID `json:"repoId,omitempty"` + // Visual Studio ID /Team Foundation ID + Vsid *uuid.UUID `json:"vsid,omitempty"` + // ID (SHA-1) of the commit. + CommitId *string `json:"commitId,omitempty"` + // Committer email address after parsing. + CommitterEmail *string `json:"committerEmail,omitempty"` + // Time reported by the commit. + CommitTime *azuredevops.Time `json:"commitTime,omitempty"` + // Project Id commit was pushed to. + ProjectId *uuid.UUID `json:"projectId,omitempty"` + // Project name commit was pushed to. + ProjectName *string `json:"projectName,omitempty"` + // Time of the push that contained the commit. + PushedTime *azuredevops.Time `json:"pushedTime,omitempty"` + // Push Id that contained the commit. + PushId *int `json:"pushId,omitempty"` + // Repository name commit was pushed to. + RepoName *string `json:"repoName,omitempty"` +} + +// Real time event (SignalR) for a source/target branch update on a pull request +type BranchUpdatedEvent struct { + // The id of this event. Can be used to track send/receive state between client and server. + EventId *uuid.UUID `json:"eventId,omitempty"` + // The id of the pull request this event was generated for. + PullRequestId *int `json:"pullRequestId,omitempty"` + // If true, the source branch of the pull request was updated + IsSourceUpdate *bool `json:"isSourceUpdate,omitempty"` +} + +// Represents a comment which is one of potentially many in a comment thread. +type Comment struct { + // Links to other related objects. + Links interface{} `json:"_links,omitempty"` + // The author of the comment. + Author *webapi.IdentityRef `json:"author,omitempty"` + // The comment type at the time of creation. + CommentType *CommentType `json:"commentType,omitempty"` + // The comment content. + Content *string `json:"content,omitempty"` + // The comment ID. IDs start at 1 and are unique to a pull request. + Id *int `json:"id,omitempty"` + // Whether or not this comment was soft-deleted. + IsDeleted *bool `json:"isDeleted,omitempty"` + // The date the comment's content was last updated. + LastContentUpdatedDate *azuredevops.Time `json:"lastContentUpdatedDate,omitempty"` + // The date the comment was last updated. + LastUpdatedDate *azuredevops.Time `json:"lastUpdatedDate,omitempty"` + // The ID of the parent comment. This is used for replies. + ParentCommentId *int `json:"parentCommentId,omitempty"` + // The date the comment was first published. + PublishedDate *azuredevops.Time `json:"publishedDate,omitempty"` + // A list of the users who have liked this comment. + UsersLiked *[]webapi.IdentityRef `json:"usersLiked,omitempty"` +} + +// Comment iteration context is used to identify which diff was being viewed when the thread was created. +type CommentIterationContext struct { + // The iteration of the file on the left side of the diff when the thread was created. If this value is equal to SecondComparingIteration, then this version is the common commit between the source and target branches of the pull request. + FirstComparingIteration *int `json:"firstComparingIteration,omitempty"` + // The iteration of the file on the right side of the diff when the thread was created. + SecondComparingIteration *int `json:"secondComparingIteration,omitempty"` +} + +type CommentPosition struct { + // The line number of a thread's position. Starts at 1. + Line *int `json:"line,omitempty"` + // The character offset of a thread's position inside of a line. Starts at 0. + Offset *int `json:"offset,omitempty"` +} + +// Represents a comment thread of a pull request. A thread contains meta data about the file it was left on along with one or more comments (an initial comment and the subsequent replies). +type CommentThread struct { + // Links to other related objects. + Links interface{} `json:"_links,omitempty"` + // A list of the comments. + Comments *[]Comment `json:"comments,omitempty"` + // The comment thread id. + Id *int `json:"id,omitempty"` + // Set of identities related to this thread + Identities *map[string]webapi.IdentityRef `json:"identities,omitempty"` + // Specify if the thread is deleted which happens when all comments are deleted. + IsDeleted *bool `json:"isDeleted,omitempty"` + // The time this thread was last updated. + LastUpdatedDate *azuredevops.Time `json:"lastUpdatedDate,omitempty"` + // Optional properties associated with the thread as a collection of key-value pairs. + Properties interface{} `json:"properties,omitempty"` + // The time this thread was published. + PublishedDate *azuredevops.Time `json:"publishedDate,omitempty"` + // The status of the comment thread. + Status *CommentThreadStatus `json:"status,omitempty"` + // Specify thread context such as position in left/right file. + ThreadContext *CommentThreadContext `json:"threadContext,omitempty"` +} + +type CommentThreadContext struct { + // File path relative to the root of the repository. It's up to the client to use any path format. + FilePath *string `json:"filePath,omitempty"` + // Position of last character of the thread's span in left file. + LeftFileEnd *CommentPosition `json:"leftFileEnd,omitempty"` + // Position of first character of the thread's span in left file. + LeftFileStart *CommentPosition `json:"leftFileStart,omitempty"` + // Position of last character of the thread's span in right file. + RightFileEnd *CommentPosition `json:"rightFileEnd,omitempty"` + // Position of first character of the thread's span in right file. + RightFileStart *CommentPosition `json:"rightFileStart,omitempty"` +} + +// The status of a comment thread. +type CommentThreadStatus string + +type commentThreadStatusValuesType struct { + Unknown CommentThreadStatus + Active CommentThreadStatus + Fixed CommentThreadStatus + WontFix CommentThreadStatus + Closed CommentThreadStatus + ByDesign CommentThreadStatus + Pending CommentThreadStatus +} + +var CommentThreadStatusValues = commentThreadStatusValuesType{ + // The thread status is unknown. + Unknown: "unknown", + // The thread status is active. + Active: "active", + // The thread status is resolved as fixed. + Fixed: "fixed", + // The thread status is resolved as won't fix. + WontFix: "wontFix", + // The thread status is closed. + Closed: "closed", + // The thread status is resolved as by design. + ByDesign: "byDesign", + // The thread status is pending. + Pending: "pending", +} + +// Comment tracking criteria is used to identify which iteration context the thread has been tracked to (if any) along with some detail about the original position and filename. +type CommentTrackingCriteria struct { + // The iteration of the file on the left side of the diff that the thread will be tracked to. Threads were tracked if this is greater than 0. + FirstComparingIteration *int `json:"firstComparingIteration,omitempty"` + // Original filepath the thread was created on before tracking. This will be different than the current thread filepath if the file in question was renamed in a later iteration. + OrigFilePath *string `json:"origFilePath,omitempty"` + // Original position of last character of the thread's span in left file. + OrigLeftFileEnd *CommentPosition `json:"origLeftFileEnd,omitempty"` + // Original position of first character of the thread's span in left file. + OrigLeftFileStart *CommentPosition `json:"origLeftFileStart,omitempty"` + // Original position of last character of the thread's span in right file. + OrigRightFileEnd *CommentPosition `json:"origRightFileEnd,omitempty"` + // Original position of first character of the thread's span in right file. + OrigRightFileStart *CommentPosition `json:"origRightFileStart,omitempty"` + // The iteration of the file on the right side of the diff that the thread will be tracked to. Threads were tracked if this is greater than 0. + SecondComparingIteration *int `json:"secondComparingIteration,omitempty"` +} + +// The type of a comment. +type CommentType string + +type commentTypeValuesType struct { + Unknown CommentType + Text CommentType + CodeChange CommentType + System CommentType +} + +var CommentTypeValues = commentTypeValuesType{ + // The comment type is not known. + Unknown: "unknown", + // This is a regular user comment. + Text: "text", + // The comment comes as a result of a code change. + CodeChange: "codeChange", + // The comment represents a system message. + System: "system", +} + +// Real time event (SignalR) for a completion errors on a pull request +type CompletionErrorsEvent struct { + // The id of this event. Can be used to track send/receive state between client and server. + EventId *uuid.UUID `json:"eventId,omitempty"` + // The id of the pull request this event was generated for. + PullRequestId *int `json:"pullRequestId,omitempty"` + // The error message associated with the completion error + ErrorMessage *string `json:"errorMessage,omitempty"` +} + +// Real time event (SignalR) for a discussions update on a pull request +type DiscussionsUpdatedEvent struct { + // The id of this event. Can be used to track send/receive state between client and server. + EventId *uuid.UUID `json:"eventId,omitempty"` + // The id of the pull request this event was generated for. + PullRequestId *int `json:"pullRequestId,omitempty"` +} + +type FileContentMetadata struct { + ContentType *string `json:"contentType,omitempty"` + Encoding *int `json:"encoding,omitempty"` + Extension *string `json:"extension,omitempty"` + FileName *string `json:"fileName,omitempty"` + IsBinary *bool `json:"isBinary,omitempty"` + IsImage *bool `json:"isImage,omitempty"` + VsLink *string `json:"vsLink,omitempty"` +} + +// Provides properties that describe file differences +type FileDiff struct { + // The collection of line diff blocks + LineDiffBlocks *[]LineDiffBlock `json:"lineDiffBlocks,omitempty"` + // Original path of item if different from current path. + OriginalPath *string `json:"originalPath,omitempty"` + // Current path of item + Path *string `json:"path,omitempty"` +} + +// Provides parameters that describe inputs for the file diff +type FileDiffParams struct { + // Original path of the file + OriginalPath *string `json:"originalPath,omitempty"` + // Current path of the file + Path *string `json:"path,omitempty"` +} + +// Provides properties that describe inputs for the file diffs +type FileDiffsCriteria struct { + // Commit ID of the base version + BaseVersionCommit *string `json:"baseVersionCommit,omitempty"` + // List of parameters for each of the files for which we need to get the file diff + FileDiffParams *[]FileDiffParams `json:"fileDiffParams,omitempty"` + // Commit ID of the target version + TargetVersionCommit *string `json:"targetVersionCommit,omitempty"` +} + +// A Git annotated tag. +type GitAnnotatedTag struct { + // The tagging Message + Message *string `json:"message,omitempty"` + // The name of the annotated tag. + Name *string `json:"name,omitempty"` + // The objectId (Sha1Id) of the tag. + ObjectId *string `json:"objectId,omitempty"` + // User info and date of tagging. + TaggedBy *GitUserDate `json:"taggedBy,omitempty"` + // Tagged git object. + TaggedObject *GitObject `json:"taggedObject,omitempty"` + Url *string `json:"url,omitempty"` +} + +// Current status of the asynchronous operation. +type GitAsyncOperationStatus string + +type gitAsyncOperationStatusValuesType struct { + Queued GitAsyncOperationStatus + InProgress GitAsyncOperationStatus + Completed GitAsyncOperationStatus + Failed GitAsyncOperationStatus + Abandoned GitAsyncOperationStatus +} + +var GitAsyncOperationStatusValues = gitAsyncOperationStatusValuesType{ + // The operation is waiting in a queue and has not yet started. + Queued: "queued", + // The operation is currently in progress. + InProgress: "inProgress", + // The operation has completed. + Completed: "completed", + // The operation has failed. Check for an error message. + Failed: "failed", + // The operation has been abandoned. + Abandoned: "abandoned", +} + +type GitAsyncRefOperation struct { + Links interface{} `json:"_links,omitempty"` + DetailedStatus *GitAsyncRefOperationDetail `json:"detailedStatus,omitempty"` + Parameters *GitAsyncRefOperationParameters `json:"parameters,omitempty"` + Status *GitAsyncOperationStatus `json:"status,omitempty"` + // A URL that can be used to make further requests for status about the operation + Url *string `json:"url,omitempty"` +} + +// Information about the progress of a cherry pick or revert operation. +type GitAsyncRefOperationDetail struct { + // Indicates if there was a conflict generated when trying to cherry pick or revert the changes. + Conflict *bool `json:"conflict,omitempty"` + // The current commit from the list of commits that are being cherry picked or reverted. + CurrentCommitId *string `json:"currentCommitId,omitempty"` + // Detailed information about why the cherry pick or revert failed to complete. + FailureMessage *string `json:"failureMessage,omitempty"` + // A number between 0 and 1 indicating the percent complete of the operation. + Progress *float64 `json:"progress,omitempty"` + // Provides a status code that indicates the reason the cherry pick or revert failed. + Status *GitAsyncRefOperationFailureStatus `json:"status,omitempty"` + // Indicates if the operation went beyond the maximum time allowed for a cherry pick or revert operation. + Timedout *bool `json:"timedout,omitempty"` +} + +type GitAsyncRefOperationFailureStatus string + +type gitAsyncRefOperationFailureStatusValuesType struct { + None GitAsyncRefOperationFailureStatus + InvalidRefName GitAsyncRefOperationFailureStatus + RefNameConflict GitAsyncRefOperationFailureStatus + CreateBranchPermissionRequired GitAsyncRefOperationFailureStatus + WritePermissionRequired GitAsyncRefOperationFailureStatus + TargetBranchDeleted GitAsyncRefOperationFailureStatus + GitObjectTooLarge GitAsyncRefOperationFailureStatus + OperationIndentityNotFound GitAsyncRefOperationFailureStatus + AsyncOperationNotFound GitAsyncRefOperationFailureStatus + Other GitAsyncRefOperationFailureStatus + EmptyCommitterSignature GitAsyncRefOperationFailureStatus +} + +var GitAsyncRefOperationFailureStatusValues = gitAsyncRefOperationFailureStatusValuesType{ + // No status + None: "none", + // Indicates that the ref update request could not be completed because the ref name presented in the request was not valid. + InvalidRefName: "invalidRefName", + // The ref update could not be completed because, in case-insensitive mode, the ref name conflicts with an existing, differently-cased ref name. + RefNameConflict: "refNameConflict", + // The ref update request could not be completed because the user lacks the permission to create a branch + CreateBranchPermissionRequired: "createBranchPermissionRequired", + // The ref update request could not be completed because the user lacks write permissions required to write this ref + WritePermissionRequired: "writePermissionRequired", + // Target branch was deleted after Git async operation started + TargetBranchDeleted: "targetBranchDeleted", + // Git object is too large to materialize into memory + GitObjectTooLarge: "gitObjectTooLarge", + // Identity who authorized the operation was not found + OperationIndentityNotFound: "operationIndentityNotFound", + // Async operation was not found + AsyncOperationNotFound: "asyncOperationNotFound", + // Unexpected failure + Other: "other", + // Initiator of async operation has signature with empty name or email + EmptyCommitterSignature: "emptyCommitterSignature", +} + +// Parameters that are provided in the request body when requesting to cherry pick or revert. +type GitAsyncRefOperationParameters struct { + // Proposed target branch name for the cherry pick or revert operation. + GeneratedRefName *string `json:"generatedRefName,omitempty"` + // The target branch for the cherry pick or revert operation. + OntoRefName *string `json:"ontoRefName,omitempty"` + // The git repository for the cherry pick or revert operation. + Repository *GitRepository `json:"repository,omitempty"` + // Details about the source of the cherry pick or revert operation (e.g. A pull request or a specific commit). + Source *GitAsyncRefOperationSource `json:"source,omitempty"` +} + +// GitAsyncRefOperationSource specifies the pull request or list of commits to use when making a cherry pick and revert operation request. Only one should be provided. +type GitAsyncRefOperationSource struct { + // A list of commits to cherry pick or revert + CommitList *[]GitCommitRef `json:"commitList,omitempty"` + // Id of the pull request to cherry pick or revert + PullRequestId *int `json:"pullRequestId,omitempty"` +} + +type GitBaseVersionDescriptor struct { + // Version string identifier (name of tag/branch, SHA1 of commit) + Version *string `json:"version,omitempty"` + // Version options - Specify additional modifiers to version (e.g Previous) + VersionOptions *GitVersionOptions `json:"versionOptions,omitempty"` + // Version type (branch, tag, or commit). Determines how Id is interpreted + VersionType *GitVersionType `json:"versionType,omitempty"` + // Version string identifier (name of tag/branch, SHA1 of commit) + BaseVersion *string `json:"baseVersion,omitempty"` + // Version options - Specify additional modifiers to version (e.g Previous) + BaseVersionOptions *GitVersionOptions `json:"baseVersionOptions,omitempty"` + // Version type (branch, tag, or commit). Determines how Id is interpreted + BaseVersionType *GitVersionType `json:"baseVersionType,omitempty"` +} + +type GitBlobRef struct { + Links interface{} `json:"_links,omitempty"` + // SHA1 hash of git object + ObjectId *string `json:"objectId,omitempty"` + // Size of blob content (in bytes) + Size *uint64 `json:"size,omitempty"` + Url *string `json:"url,omitempty"` +} + +// Ahead and behind counts for a particular ref. +type GitBranchStats struct { + // Number of commits ahead. + AheadCount *int `json:"aheadCount,omitempty"` + // Number of commits behind. + BehindCount *int `json:"behindCount,omitempty"` + // Current commit. + Commit *GitCommitRef `json:"commit,omitempty"` + // True if this is the result for the base version. + IsBaseVersion *bool `json:"isBaseVersion,omitempty"` + // Name of the ref. + Name *string `json:"name,omitempty"` +} + +type GitCommit struct { + // A collection of related REST reference links. + Links interface{} `json:"_links,omitempty"` + // Author of the commit. + Author *GitUserDate `json:"author,omitempty"` + // Comment or message of the commit. + Comment *string `json:"comment,omitempty"` + // Indicates if the comment is truncated from the full Git commit comment message. + CommentTruncated *bool `json:"commentTruncated,omitempty"` + // ID (SHA-1) of the commit. + CommitId *string `json:"commitId,omitempty"` + // Committer of the commit. + Committer *GitUserDate `json:"committer,omitempty"` + // Indicates that commit contains too many changes to be displayed + CommitTooManyChanges *bool `json:"commitTooManyChanges,omitempty"` + // Counts of the types of changes (edits, deletes, etc.) included with the commit. + ChangeCounts *ChangeCountDictionary `json:"changeCounts,omitempty"` + // An enumeration of the changes included with the commit. + Changes *[]interface{} `json:"changes,omitempty"` + // An enumeration of the parent commit IDs for this commit. + Parents *[]string `json:"parents,omitempty"` + // The push associated with this commit. + Push *GitPushRef `json:"push,omitempty"` + // Remote URL path to the commit. + RemoteUrl *string `json:"remoteUrl,omitempty"` + // A list of status metadata from services and extensions that may associate additional information to the commit. + Statuses *[]GitStatus `json:"statuses,omitempty"` + // REST URL for this resource. + Url *string `json:"url,omitempty"` + // A list of workitems associated with this commit. + WorkItems *[]webapi.ResourceRef `json:"workItems,omitempty"` + TreeId *string `json:"treeId,omitempty"` +} + +type GitCommitDiffs struct { + AheadCount *int `json:"aheadCount,omitempty"` + AllChangesIncluded *bool `json:"allChangesIncluded,omitempty"` + BaseCommit *string `json:"baseCommit,omitempty"` + BehindCount *int `json:"behindCount,omitempty"` + CommonCommit *string `json:"commonCommit,omitempty"` + ChangeCounts *map[VersionControlChangeType]int `json:"changeCounts,omitempty"` + Changes *[]interface{} `json:"changes,omitempty"` + TargetCommit *string `json:"targetCommit,omitempty"` +} + +type GitCommitChanges struct { + ChangeCounts *ChangeCountDictionary `json:"changeCounts,omitempty"` + Changes *[]interface{} `json:"changes,omitempty"` +} + +// Provides properties that describe a Git commit and associated metadata. +type GitCommitRef struct { + // A collection of related REST reference links. + Links interface{} `json:"_links,omitempty"` + // Author of the commit. + Author *GitUserDate `json:"author,omitempty"` + // Comment or message of the commit. + Comment *string `json:"comment,omitempty"` + // Indicates if the comment is truncated from the full Git commit comment message. + CommentTruncated *bool `json:"commentTruncated,omitempty"` + // ID (SHA-1) of the commit. + CommitId *string `json:"commitId,omitempty"` + // Committer of the commit. + Committer *GitUserDate `json:"committer,omitempty"` + // Indicates that commit contains too many changes to be displayed + CommitTooManyChanges *bool `json:"commitTooManyChanges,omitempty"` + // Counts of the types of changes (edits, deletes, etc.) included with the commit. + ChangeCounts *ChangeCountDictionary `json:"changeCounts,omitempty"` + // An enumeration of the changes included with the commit. + Changes *[]interface{} `json:"changes,omitempty"` + // An enumeration of the parent commit IDs for this commit. + Parents *[]string `json:"parents,omitempty"` + // The push associated with this commit. + Push *GitPushRef `json:"push,omitempty"` + // Remote URL path to the commit. + RemoteUrl *string `json:"remoteUrl,omitempty"` + // A list of status metadata from services and extensions that may associate additional information to the commit. + Statuses *[]GitStatus `json:"statuses,omitempty"` + // REST URL for this resource. + Url *string `json:"url,omitempty"` + // A list of workitems associated with this commit. + WorkItems *[]webapi.ResourceRef `json:"workItems,omitempty"` +} + +type GitCommitToCreate struct { + BaseRef *GitRef `json:"baseRef,omitempty"` + Comment *string `json:"comment,omitempty"` + PathActions *[]GitPathAction `json:"pathActions,omitempty"` +} + +type GitConflict struct { + Links interface{} `json:"_links,omitempty"` + ConflictId *int `json:"conflictId,omitempty"` + ConflictPath *string `json:"conflictPath,omitempty"` + ConflictType *GitConflictType `json:"conflictType,omitempty"` + MergeBaseCommit *GitCommitRef `json:"mergeBaseCommit,omitempty"` + MergeOrigin *GitMergeOriginRef `json:"mergeOrigin,omitempty"` + MergeSourceCommit *GitCommitRef `json:"mergeSourceCommit,omitempty"` + MergeTargetCommit *GitCommitRef `json:"mergeTargetCommit,omitempty"` + ResolutionError *GitResolutionError `json:"resolutionError,omitempty"` + ResolutionStatus *GitResolutionStatus `json:"resolutionStatus,omitempty"` + ResolvedBy *webapi.IdentityRef `json:"resolvedBy,omitempty"` + ResolvedDate *azuredevops.Time `json:"resolvedDate,omitempty"` + Url *string `json:"url,omitempty"` +} + +// Data object for AddAdd conflict +type GitConflictAddAdd struct { + Links interface{} `json:"_links,omitempty"` + ConflictId *int `json:"conflictId,omitempty"` + ConflictPath *string `json:"conflictPath,omitempty"` + ConflictType *GitConflictType `json:"conflictType,omitempty"` + MergeBaseCommit *GitCommitRef `json:"mergeBaseCommit,omitempty"` + MergeOrigin *GitMergeOriginRef `json:"mergeOrigin,omitempty"` + MergeSourceCommit *GitCommitRef `json:"mergeSourceCommit,omitempty"` + MergeTargetCommit *GitCommitRef `json:"mergeTargetCommit,omitempty"` + ResolutionError *GitResolutionError `json:"resolutionError,omitempty"` + ResolutionStatus *GitResolutionStatus `json:"resolutionStatus,omitempty"` + ResolvedBy *webapi.IdentityRef `json:"resolvedBy,omitempty"` + ResolvedDate *azuredevops.Time `json:"resolvedDate,omitempty"` + Url *string `json:"url,omitempty"` + Resolution *GitResolutionMergeContent `json:"resolution,omitempty"` + SourceBlob *GitBlobRef `json:"sourceBlob,omitempty"` + TargetBlob *GitBlobRef `json:"targetBlob,omitempty"` +} + +// Data object for RenameAdd conflict +type GitConflictAddRename struct { + Links interface{} `json:"_links,omitempty"` + ConflictId *int `json:"conflictId,omitempty"` + ConflictPath *string `json:"conflictPath,omitempty"` + ConflictType *GitConflictType `json:"conflictType,omitempty"` + MergeBaseCommit *GitCommitRef `json:"mergeBaseCommit,omitempty"` + MergeOrigin *GitMergeOriginRef `json:"mergeOrigin,omitempty"` + MergeSourceCommit *GitCommitRef `json:"mergeSourceCommit,omitempty"` + MergeTargetCommit *GitCommitRef `json:"mergeTargetCommit,omitempty"` + ResolutionError *GitResolutionError `json:"resolutionError,omitempty"` + ResolutionStatus *GitResolutionStatus `json:"resolutionStatus,omitempty"` + ResolvedBy *webapi.IdentityRef `json:"resolvedBy,omitempty"` + ResolvedDate *azuredevops.Time `json:"resolvedDate,omitempty"` + Url *string `json:"url,omitempty"` + BaseBlob *GitBlobRef `json:"baseBlob,omitempty"` + Resolution *GitResolutionPathConflict `json:"resolution,omitempty"` + SourceBlob *GitBlobRef `json:"sourceBlob,omitempty"` + TargetBlob *GitBlobRef `json:"targetBlob,omitempty"` + TargetOriginalPath *string `json:"targetOriginalPath,omitempty"` +} + +// Data object for EditDelete conflict +type GitConflictDeleteEdit struct { + Links interface{} `json:"_links,omitempty"` + ConflictId *int `json:"conflictId,omitempty"` + ConflictPath *string `json:"conflictPath,omitempty"` + ConflictType *GitConflictType `json:"conflictType,omitempty"` + MergeBaseCommit *GitCommitRef `json:"mergeBaseCommit,omitempty"` + MergeOrigin *GitMergeOriginRef `json:"mergeOrigin,omitempty"` + MergeSourceCommit *GitCommitRef `json:"mergeSourceCommit,omitempty"` + MergeTargetCommit *GitCommitRef `json:"mergeTargetCommit,omitempty"` + ResolutionError *GitResolutionError `json:"resolutionError,omitempty"` + ResolutionStatus *GitResolutionStatus `json:"resolutionStatus,omitempty"` + ResolvedBy *webapi.IdentityRef `json:"resolvedBy,omitempty"` + ResolvedDate *azuredevops.Time `json:"resolvedDate,omitempty"` + Url *string `json:"url,omitempty"` + BaseBlob *GitBlobRef `json:"baseBlob,omitempty"` + Resolution *GitResolutionPickOneAction `json:"resolution,omitempty"` + TargetBlob *GitBlobRef `json:"targetBlob,omitempty"` +} + +// Data object for RenameDelete conflict +type GitConflictDeleteRename struct { + Links interface{} `json:"_links,omitempty"` + ConflictId *int `json:"conflictId,omitempty"` + ConflictPath *string `json:"conflictPath,omitempty"` + ConflictType *GitConflictType `json:"conflictType,omitempty"` + MergeBaseCommit *GitCommitRef `json:"mergeBaseCommit,omitempty"` + MergeOrigin *GitMergeOriginRef `json:"mergeOrigin,omitempty"` + MergeSourceCommit *GitCommitRef `json:"mergeSourceCommit,omitempty"` + MergeTargetCommit *GitCommitRef `json:"mergeTargetCommit,omitempty"` + ResolutionError *GitResolutionError `json:"resolutionError,omitempty"` + ResolutionStatus *GitResolutionStatus `json:"resolutionStatus,omitempty"` + ResolvedBy *webapi.IdentityRef `json:"resolvedBy,omitempty"` + ResolvedDate *azuredevops.Time `json:"resolvedDate,omitempty"` + Url *string `json:"url,omitempty"` + BaseBlob *GitBlobRef `json:"baseBlob,omitempty"` + Resolution *GitResolutionPickOneAction `json:"resolution,omitempty"` + TargetBlob *GitBlobRef `json:"targetBlob,omitempty"` + TargetNewPath *string `json:"targetNewPath,omitempty"` +} + +// Data object for FileDirectory conflict +type GitConflictDirectoryFile struct { + Links interface{} `json:"_links,omitempty"` + ConflictId *int `json:"conflictId,omitempty"` + ConflictPath *string `json:"conflictPath,omitempty"` + ConflictType *GitConflictType `json:"conflictType,omitempty"` + MergeBaseCommit *GitCommitRef `json:"mergeBaseCommit,omitempty"` + MergeOrigin *GitMergeOriginRef `json:"mergeOrigin,omitempty"` + MergeSourceCommit *GitCommitRef `json:"mergeSourceCommit,omitempty"` + MergeTargetCommit *GitCommitRef `json:"mergeTargetCommit,omitempty"` + ResolutionError *GitResolutionError `json:"resolutionError,omitempty"` + ResolutionStatus *GitResolutionStatus `json:"resolutionStatus,omitempty"` + ResolvedBy *webapi.IdentityRef `json:"resolvedBy,omitempty"` + ResolvedDate *azuredevops.Time `json:"resolvedDate,omitempty"` + Url *string `json:"url,omitempty"` + Resolution *GitResolutionPathConflict `json:"resolution,omitempty"` + SourceTree *GitTreeRef `json:"sourceTree,omitempty"` + TargetBlob *GitBlobRef `json:"targetBlob,omitempty"` +} + +// Data object for DeleteEdit conflict +type GitConflictEditDelete struct { + Links interface{} `json:"_links,omitempty"` + ConflictId *int `json:"conflictId,omitempty"` + ConflictPath *string `json:"conflictPath,omitempty"` + ConflictType *GitConflictType `json:"conflictType,omitempty"` + MergeBaseCommit *GitCommitRef `json:"mergeBaseCommit,omitempty"` + MergeOrigin *GitMergeOriginRef `json:"mergeOrigin,omitempty"` + MergeSourceCommit *GitCommitRef `json:"mergeSourceCommit,omitempty"` + MergeTargetCommit *GitCommitRef `json:"mergeTargetCommit,omitempty"` + ResolutionError *GitResolutionError `json:"resolutionError,omitempty"` + ResolutionStatus *GitResolutionStatus `json:"resolutionStatus,omitempty"` + ResolvedBy *webapi.IdentityRef `json:"resolvedBy,omitempty"` + ResolvedDate *azuredevops.Time `json:"resolvedDate,omitempty"` + Url *string `json:"url,omitempty"` + BaseBlob *GitBlobRef `json:"baseBlob,omitempty"` + Resolution *GitResolutionPickOneAction `json:"resolution,omitempty"` + SourceBlob *GitBlobRef `json:"sourceBlob,omitempty"` +} + +// Data object for EditEdit conflict +type GitConflictEditEdit struct { + Links interface{} `json:"_links,omitempty"` + ConflictId *int `json:"conflictId,omitempty"` + ConflictPath *string `json:"conflictPath,omitempty"` + ConflictType *GitConflictType `json:"conflictType,omitempty"` + MergeBaseCommit *GitCommitRef `json:"mergeBaseCommit,omitempty"` + MergeOrigin *GitMergeOriginRef `json:"mergeOrigin,omitempty"` + MergeSourceCommit *GitCommitRef `json:"mergeSourceCommit,omitempty"` + MergeTargetCommit *GitCommitRef `json:"mergeTargetCommit,omitempty"` + ResolutionError *GitResolutionError `json:"resolutionError,omitempty"` + ResolutionStatus *GitResolutionStatus `json:"resolutionStatus,omitempty"` + ResolvedBy *webapi.IdentityRef `json:"resolvedBy,omitempty"` + ResolvedDate *azuredevops.Time `json:"resolvedDate,omitempty"` + Url *string `json:"url,omitempty"` + BaseBlob *GitBlobRef `json:"baseBlob,omitempty"` + Resolution *GitResolutionMergeContent `json:"resolution,omitempty"` + SourceBlob *GitBlobRef `json:"sourceBlob,omitempty"` + TargetBlob *GitBlobRef `json:"targetBlob,omitempty"` +} + +// Data object for DirectoryFile conflict +type GitConflictFileDirectory struct { + Links interface{} `json:"_links,omitempty"` + ConflictId *int `json:"conflictId,omitempty"` + ConflictPath *string `json:"conflictPath,omitempty"` + ConflictType *GitConflictType `json:"conflictType,omitempty"` + MergeBaseCommit *GitCommitRef `json:"mergeBaseCommit,omitempty"` + MergeOrigin *GitMergeOriginRef `json:"mergeOrigin,omitempty"` + MergeSourceCommit *GitCommitRef `json:"mergeSourceCommit,omitempty"` + MergeTargetCommit *GitCommitRef `json:"mergeTargetCommit,omitempty"` + ResolutionError *GitResolutionError `json:"resolutionError,omitempty"` + ResolutionStatus *GitResolutionStatus `json:"resolutionStatus,omitempty"` + ResolvedBy *webapi.IdentityRef `json:"resolvedBy,omitempty"` + ResolvedDate *azuredevops.Time `json:"resolvedDate,omitempty"` + Url *string `json:"url,omitempty"` + Resolution *GitResolutionPathConflict `json:"resolution,omitempty"` + SourceBlob *GitBlobRef `json:"sourceBlob,omitempty"` + TargetTree *GitTreeRef `json:"targetTree,omitempty"` +} + +// Data object for Rename1to2 conflict +type GitConflictRename1to2 struct { + Links interface{} `json:"_links,omitempty"` + ConflictId *int `json:"conflictId,omitempty"` + ConflictPath *string `json:"conflictPath,omitempty"` + ConflictType *GitConflictType `json:"conflictType,omitempty"` + MergeBaseCommit *GitCommitRef `json:"mergeBaseCommit,omitempty"` + MergeOrigin *GitMergeOriginRef `json:"mergeOrigin,omitempty"` + MergeSourceCommit *GitCommitRef `json:"mergeSourceCommit,omitempty"` + MergeTargetCommit *GitCommitRef `json:"mergeTargetCommit,omitempty"` + ResolutionError *GitResolutionError `json:"resolutionError,omitempty"` + ResolutionStatus *GitResolutionStatus `json:"resolutionStatus,omitempty"` + ResolvedBy *webapi.IdentityRef `json:"resolvedBy,omitempty"` + ResolvedDate *azuredevops.Time `json:"resolvedDate,omitempty"` + Url *string `json:"url,omitempty"` + BaseBlob *GitBlobRef `json:"baseBlob,omitempty"` + Resolution *GitResolutionRename1to2 `json:"resolution,omitempty"` + SourceBlob *GitBlobRef `json:"sourceBlob,omitempty"` + SourceNewPath *string `json:"sourceNewPath,omitempty"` + TargetBlob *GitBlobRef `json:"targetBlob,omitempty"` + TargetNewPath *string `json:"targetNewPath,omitempty"` +} + +// Data object for Rename2to1 conflict +type GitConflictRename2to1 struct { + Links interface{} `json:"_links,omitempty"` + ConflictId *int `json:"conflictId,omitempty"` + ConflictPath *string `json:"conflictPath,omitempty"` + ConflictType *GitConflictType `json:"conflictType,omitempty"` + MergeBaseCommit *GitCommitRef `json:"mergeBaseCommit,omitempty"` + MergeOrigin *GitMergeOriginRef `json:"mergeOrigin,omitempty"` + MergeSourceCommit *GitCommitRef `json:"mergeSourceCommit,omitempty"` + MergeTargetCommit *GitCommitRef `json:"mergeTargetCommit,omitempty"` + ResolutionError *GitResolutionError `json:"resolutionError,omitempty"` + ResolutionStatus *GitResolutionStatus `json:"resolutionStatus,omitempty"` + ResolvedBy *webapi.IdentityRef `json:"resolvedBy,omitempty"` + ResolvedDate *azuredevops.Time `json:"resolvedDate,omitempty"` + Url *string `json:"url,omitempty"` + Resolution *GitResolutionPathConflict `json:"resolution,omitempty"` + SourceNewBlob *GitBlobRef `json:"sourceNewBlob,omitempty"` + SourceOriginalBlob *GitBlobRef `json:"sourceOriginalBlob,omitempty"` + SourceOriginalPath *string `json:"sourceOriginalPath,omitempty"` + TargetNewBlob *GitBlobRef `json:"targetNewBlob,omitempty"` + TargetOriginalBlob *GitBlobRef `json:"targetOriginalBlob,omitempty"` + TargetOriginalPath *string `json:"targetOriginalPath,omitempty"` +} + +// Data object for AddRename conflict +type GitConflictRenameAdd struct { + Links interface{} `json:"_links,omitempty"` + ConflictId *int `json:"conflictId,omitempty"` + ConflictPath *string `json:"conflictPath,omitempty"` + ConflictType *GitConflictType `json:"conflictType,omitempty"` + MergeBaseCommit *GitCommitRef `json:"mergeBaseCommit,omitempty"` + MergeOrigin *GitMergeOriginRef `json:"mergeOrigin,omitempty"` + MergeSourceCommit *GitCommitRef `json:"mergeSourceCommit,omitempty"` + MergeTargetCommit *GitCommitRef `json:"mergeTargetCommit,omitempty"` + ResolutionError *GitResolutionError `json:"resolutionError,omitempty"` + ResolutionStatus *GitResolutionStatus `json:"resolutionStatus,omitempty"` + ResolvedBy *webapi.IdentityRef `json:"resolvedBy,omitempty"` + ResolvedDate *azuredevops.Time `json:"resolvedDate,omitempty"` + Url *string `json:"url,omitempty"` + BaseBlob *GitBlobRef `json:"baseBlob,omitempty"` + Resolution *GitResolutionPathConflict `json:"resolution,omitempty"` + SourceBlob *GitBlobRef `json:"sourceBlob,omitempty"` + SourceOriginalPath *string `json:"sourceOriginalPath,omitempty"` + TargetBlob *GitBlobRef `json:"targetBlob,omitempty"` +} + +// Data object for DeleteRename conflict +type GitConflictRenameDelete struct { + Links interface{} `json:"_links,omitempty"` + ConflictId *int `json:"conflictId,omitempty"` + ConflictPath *string `json:"conflictPath,omitempty"` + ConflictType *GitConflictType `json:"conflictType,omitempty"` + MergeBaseCommit *GitCommitRef `json:"mergeBaseCommit,omitempty"` + MergeOrigin *GitMergeOriginRef `json:"mergeOrigin,omitempty"` + MergeSourceCommit *GitCommitRef `json:"mergeSourceCommit,omitempty"` + MergeTargetCommit *GitCommitRef `json:"mergeTargetCommit,omitempty"` + ResolutionError *GitResolutionError `json:"resolutionError,omitempty"` + ResolutionStatus *GitResolutionStatus `json:"resolutionStatus,omitempty"` + ResolvedBy *webapi.IdentityRef `json:"resolvedBy,omitempty"` + ResolvedDate *azuredevops.Time `json:"resolvedDate,omitempty"` + Url *string `json:"url,omitempty"` + BaseBlob *GitBlobRef `json:"baseBlob,omitempty"` + Resolution *GitResolutionPickOneAction `json:"resolution,omitempty"` + SourceBlob *GitBlobRef `json:"sourceBlob,omitempty"` + SourceNewPath *string `json:"sourceNewPath,omitempty"` +} + +// Data object for RenameRename conflict +type GitConflictRenameRename struct { + Links interface{} `json:"_links,omitempty"` + ConflictId *int `json:"conflictId,omitempty"` + ConflictPath *string `json:"conflictPath,omitempty"` + ConflictType *GitConflictType `json:"conflictType,omitempty"` + MergeBaseCommit *GitCommitRef `json:"mergeBaseCommit,omitempty"` + MergeOrigin *GitMergeOriginRef `json:"mergeOrigin,omitempty"` + MergeSourceCommit *GitCommitRef `json:"mergeSourceCommit,omitempty"` + MergeTargetCommit *GitCommitRef `json:"mergeTargetCommit,omitempty"` + ResolutionError *GitResolutionError `json:"resolutionError,omitempty"` + ResolutionStatus *GitResolutionStatus `json:"resolutionStatus,omitempty"` + ResolvedBy *webapi.IdentityRef `json:"resolvedBy,omitempty"` + ResolvedDate *azuredevops.Time `json:"resolvedDate,omitempty"` + Url *string `json:"url,omitempty"` + BaseBlob *GitBlobRef `json:"baseBlob,omitempty"` + OriginalPath *string `json:"originalPath,omitempty"` + Resolution *GitResolutionMergeContent `json:"resolution,omitempty"` + SourceBlob *GitBlobRef `json:"sourceBlob,omitempty"` + TargetBlob *GitBlobRef `json:"targetBlob,omitempty"` +} + +// The type of a merge conflict. +type GitConflictType string + +type gitConflictTypeValuesType struct { + None GitConflictType + AddAdd GitConflictType + AddRename GitConflictType + DeleteEdit GitConflictType + DeleteRename GitConflictType + DirectoryFile GitConflictType + DirectoryChild GitConflictType + EditDelete GitConflictType + EditEdit GitConflictType + FileDirectory GitConflictType + Rename1to2 GitConflictType + Rename2to1 GitConflictType + RenameAdd GitConflictType + RenameDelete GitConflictType + RenameRename GitConflictType +} + +var GitConflictTypeValues = gitConflictTypeValuesType{ + // No conflict + None: "none", + // Added on source and target; content differs + AddAdd: "addAdd", + // Added on source and rename destination on target + AddRename: "addRename", + // Deleted on source and edited on target + DeleteEdit: "deleteEdit", + // Deleted on source and renamed on target + DeleteRename: "deleteRename", + // Path is a directory on source and a file on target + DirectoryFile: "directoryFile", + // Children of directory which has DirectoryFile or FileDirectory conflict + DirectoryChild: "directoryChild", + // Edited on source and deleted on target + EditDelete: "editDelete", + // Edited on source and target; content differs + EditEdit: "editEdit", + // Path is a file on source and a directory on target + FileDirectory: "fileDirectory", + // Same file renamed on both source and target; destination paths differ + Rename1to2: "rename1to2", + // Different files renamed to same destination path on both source and target + Rename2to1: "rename2to1", + // Rename destination on source and new file on target + RenameAdd: "renameAdd", + // Renamed on source and deleted on target + RenameDelete: "renameDelete", + // Rename destination on both source and target; content differs + RenameRename: "renameRename", +} + +type GitConflictUpdateResult struct { + // Conflict ID that was provided by input + ConflictId *int `json:"conflictId,omitempty"` + // Reason for failing + CustomMessage *string `json:"customMessage,omitempty"` + // New state of the conflict after updating + UpdatedConflict *GitConflict `json:"updatedConflict,omitempty"` + // Status of the update on the server + UpdateStatus *GitConflictUpdateStatus `json:"updateStatus,omitempty"` +} + +// Represents the possible outcomes from a request to update a pull request conflict +type GitConflictUpdateStatus string + +type gitConflictUpdateStatusValuesType struct { + Succeeded GitConflictUpdateStatus + BadRequest GitConflictUpdateStatus + InvalidResolution GitConflictUpdateStatus + UnsupportedConflictType GitConflictUpdateStatus + NotFound GitConflictUpdateStatus +} + +var GitConflictUpdateStatusValues = gitConflictUpdateStatusValuesType{ + // Indicates that pull request conflict update request was completed successfully + Succeeded: "succeeded", + // Indicates that the update request did not fit the expected data contract + BadRequest: "badRequest", + // Indicates that the requested resolution was not valid + InvalidResolution: "invalidResolution", + // Indicates that the conflict in the update request was not a supported conflict type + UnsupportedConflictType: "unsupportedConflictType", + // Indicates that the conflict could not be found + NotFound: "notFound", +} + +type GitDeletedRepository struct { + CreatedDate *azuredevops.Time `json:"createdDate,omitempty"` + DeletedBy *webapi.IdentityRef `json:"deletedBy,omitempty"` + DeletedDate *azuredevops.Time `json:"deletedDate,omitempty"` + Id *uuid.UUID `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Project *core.TeamProjectReference `json:"project,omitempty"` +} + +type GitFilePathsCollection struct { + CommitId *string `json:"commitId,omitempty"` + Paths *[]string `json:"paths,omitempty"` + Url *string `json:"url,omitempty"` +} + +// Status information about a requested fork operation. +type GitForkOperationStatusDetail struct { + // All valid steps for the forking process + AllSteps *[]string `json:"allSteps,omitempty"` + // Index into AllSteps for the current step + CurrentStep *int `json:"currentStep,omitempty"` + // Error message if the operation failed. + ErrorMessage *string `json:"errorMessage,omitempty"` +} + +// Information about a fork ref. +type GitForkRef struct { + Links interface{} `json:"_links,omitempty"` + Creator *webapi.IdentityRef `json:"creator,omitempty"` + IsLocked *bool `json:"isLocked,omitempty"` + IsLockedBy *webapi.IdentityRef `json:"isLockedBy,omitempty"` + Name *string `json:"name,omitempty"` + ObjectId *string `json:"objectId,omitempty"` + PeeledObjectId *string `json:"peeledObjectId,omitempty"` + Statuses *[]GitStatus `json:"statuses,omitempty"` + Url *string `json:"url,omitempty"` + // The repository ID of the fork. + Repository *GitRepository `json:"repository,omitempty"` +} + +// Request to sync data between two forks. +type GitForkSyncRequest struct { + // Collection of related links + Links interface{} `json:"_links,omitempty"` + DetailedStatus *GitForkOperationStatusDetail `json:"detailedStatus,omitempty"` + // Unique identifier for the operation. + OperationId *int `json:"operationId,omitempty"` + // Fully-qualified identifier for the source repository. + Source *GlobalGitRepositoryKey `json:"source,omitempty"` + // If supplied, the set of ref mappings to use when performing a "sync" or create. If missing, all refs will be synchronized. + SourceToTargetRefs *[]SourceToTargetRef `json:"sourceToTargetRefs,omitempty"` + Status *GitAsyncOperationStatus `json:"status,omitempty"` +} + +// Parameters for creating a fork request +type GitForkSyncRequestParameters struct { + // Fully-qualified identifier for the source repository. + Source *GlobalGitRepositoryKey `json:"source,omitempty"` + // If supplied, the set of ref mappings to use when performing a "sync" or create. If missing, all refs will be synchronized. + SourceToTargetRefs *[]SourceToTargetRef `json:"sourceToTargetRefs,omitempty"` +} + +type GitForkTeamProjectReference struct { + // Project abbreviation. + Abbreviation *string `json:"abbreviation,omitempty"` + // Url to default team identity image. + DefaultTeamImageUrl *string `json:"defaultTeamImageUrl,omitempty"` + // The project's description (if any). + Description *string `json:"description,omitempty"` + // Project identifier. + Id *uuid.UUID `json:"id,omitempty"` + // Project last update time. + LastUpdateTime *azuredevops.Time `json:"lastUpdateTime,omitempty"` + // Project name. + Name *string `json:"name,omitempty"` + // Project revision. + Revision *uint64 `json:"revision,omitempty"` + // Project state. + State *core.ProjectState `json:"state,omitempty"` + // Url to the full version of the object. + Url *string `json:"url,omitempty"` + // Project visibility. + Visibility *core.ProjectVisibility `json:"visibility,omitempty"` +} + +// Accepted types of version +type GitHistoryMode string + +type gitHistoryModeValuesType struct { + SimplifiedHistory GitHistoryMode + FirstParent GitHistoryMode + FullHistory GitHistoryMode + FullHistorySimplifyMerges GitHistoryMode +} + +var GitHistoryModeValues = gitHistoryModeValuesType{ + // The history mode used by `git log`. This is the default. + SimplifiedHistory: "simplifiedHistory", + // The history mode used by `git log --first-parent` + FirstParent: "firstParent", + // The history mode used by `git log --full-history` + FullHistory: "fullHistory", + // The history mode used by `git log --full-history --simplify-merges` + FullHistorySimplifyMerges: "fullHistorySimplifyMerges", +} + +type GitChange struct { + // The type of change that was made to the item. + ChangeType *VersionControlChangeType `json:"changeType,omitempty"` + // Current version. + Item interface{} `json:"item,omitempty"` + // Content of the item after the change. + NewContent *ItemContent `json:"newContent,omitempty"` + // Path of the item on the server. + SourceServerItem *string `json:"sourceServerItem,omitempty"` + // URL to retrieve the item. + Url *string `json:"url,omitempty"` + // ID of the change within the group of changes. + ChangeId *int `json:"changeId,omitempty"` + // New Content template to be used when pushing new changes. + NewContentTemplate *GitTemplate `json:"newContentTemplate,omitempty"` + // Original path of item if different from current path. + OriginalPath *string `json:"originalPath,omitempty"` +} + +// This object is returned from Cherry Pick operations and provides the id and status of the operation +type GitCherryPick struct { + Links interface{} `json:"_links,omitempty"` + DetailedStatus *GitAsyncRefOperationDetail `json:"detailedStatus,omitempty"` + Parameters *GitAsyncRefOperationParameters `json:"parameters,omitempty"` + Status *GitAsyncOperationStatus `json:"status,omitempty"` + // A URL that can be used to make further requests for status about the operation + Url *string `json:"url,omitempty"` + CherryPickId *int `json:"cherryPickId,omitempty"` +} + +type GitImportFailedEvent struct { + SourceRepositoryName *string `json:"sourceRepositoryName,omitempty"` + TargetRepository *GitRepository `json:"targetRepository,omitempty"` +} + +// Parameter for creating a git import request when source is Git version control +type GitImportGitSource struct { + // Tells if this is a sync request or not + Overwrite *bool `json:"overwrite,omitempty"` + // Url for the source repo + Url *string `json:"url,omitempty"` +} + +// A request to import data from a remote source control system. +type GitImportRequest struct { + // Links to related resources. + Links interface{} `json:"_links,omitempty"` + // Detailed status of the import, including the current step and an error message, if applicable. + DetailedStatus *GitImportStatusDetail `json:"detailedStatus,omitempty"` + // The unique identifier for this import request. + ImportRequestId *int `json:"importRequestId,omitempty"` + // Parameters for creating the import request. + Parameters *GitImportRequestParameters `json:"parameters,omitempty"` + // The target repository for this import. + Repository *GitRepository `json:"repository,omitempty"` + // Current status of the import. + Status *GitAsyncOperationStatus `json:"status,omitempty"` + // A link back to this import request resource. + Url *string `json:"url,omitempty"` +} + +// Parameters for creating an import request +type GitImportRequestParameters struct { + // Option to delete service endpoint when import is done + DeleteServiceEndpointAfterImportIsDone *bool `json:"deleteServiceEndpointAfterImportIsDone,omitempty"` + // Source for importing git repository + GitSource *GitImportGitSource `json:"gitSource,omitempty"` + // Service Endpoint for connection to external endpoint + ServiceEndpointId *uuid.UUID `json:"serviceEndpointId,omitempty"` + // Source for importing tfvc repository + TfvcSource *GitImportTfvcSource `json:"tfvcSource,omitempty"` +} + +// Additional status information about an import request. +type GitImportStatusDetail struct { + // All valid steps for the import process + AllSteps *[]string `json:"allSteps,omitempty"` + // Index into AllSteps for the current step + CurrentStep *int `json:"currentStep,omitempty"` + // Error message if the operation failed. + ErrorMessage *string `json:"errorMessage,omitempty"` +} + +type GitImportSucceededEvent struct { + SourceRepositoryName *string `json:"sourceRepositoryName,omitempty"` + TargetRepository *GitRepository `json:"targetRepository,omitempty"` +} + +// Parameter for creating a git import request when source is tfvc version control +type GitImportTfvcSource struct { + // Set true to import History, false otherwise + ImportHistory *bool `json:"importHistory,omitempty"` + // Get history for last n days (max allowed value is 180 days) + ImportHistoryDurationInDays *int `json:"importHistoryDurationInDays,omitempty"` + // Path which we want to import (this can be copied from Path Control in Explorer) + Path *string `json:"path,omitempty"` +} + +type GitItem struct { + Links interface{} `json:"_links,omitempty"` + Content *string `json:"content,omitempty"` + ContentMetadata *FileContentMetadata `json:"contentMetadata,omitempty"` + IsFolder *bool `json:"isFolder,omitempty"` + IsSymLink *bool `json:"isSymLink,omitempty"` + Path *string `json:"path,omitempty"` + Url *string `json:"url,omitempty"` + // SHA1 of commit item was fetched at + CommitId *string `json:"commitId,omitempty"` + // Type of object (Commit, Tree, Blob, Tag, ...) + GitObjectType *GitObjectType `json:"gitObjectType,omitempty"` + // Shallow ref to commit that last changed this item Only populated if latestProcessedChange is requested May not be accurate if latest change is not yet cached + LatestProcessedChange *GitCommitRef `json:"latestProcessedChange,omitempty"` + // Git object id + ObjectId *string `json:"objectId,omitempty"` + // Git object id + OriginalObjectId *string `json:"originalObjectId,omitempty"` +} + +type GitItemDescriptor struct { + // Path to item + Path *string `json:"path,omitempty"` + // Specifies whether to include children (OneLevel), all descendants (Full), or None + RecursionLevel *VersionControlRecursionType `json:"recursionLevel,omitempty"` + // Version string (interpretation based on VersionType defined in subclass + Version *string `json:"version,omitempty"` + // Version modifiers (e.g. previous) + VersionOptions *GitVersionOptions `json:"versionOptions,omitempty"` + // How to interpret version (branch,tag,commit) + VersionType *GitVersionType `json:"versionType,omitempty"` +} + +type GitItemRequestData struct { + // Whether to include metadata for all items + IncludeContentMetadata *bool `json:"includeContentMetadata,omitempty"` + // Whether to include the _links field on the shallow references + IncludeLinks *bool `json:"includeLinks,omitempty"` + // Collection of items to fetch, including path, version, and recursion level + ItemDescriptors *[]GitItemDescriptor `json:"itemDescriptors,omitempty"` + // Whether to include shallow ref to commit that last changed each item + LatestProcessedChange *bool `json:"latestProcessedChange,omitempty"` +} + +type GitLastChangeItem struct { + // Gets or sets the commit Id this item was modified most recently for the provided version. + CommitId *string `json:"commitId,omitempty"` + // Gets or sets the path of the item. + Path *string `json:"path,omitempty"` +} + +type GitLastChangeTreeItems struct { + // The list of commits referenced by Items, if they were requested. + Commits *[]GitCommitRef `json:"commits,omitempty"` + // The last change of items. + Items *[]GitLastChangeItem `json:"items,omitempty"` + // The last explored time, in case the result is not comprehensive. Null otherwise. + LastExploredTime *azuredevops.Time `json:"lastExploredTime,omitempty"` +} + +type GitMerge struct { + // Comment or message of the commit. + Comment *string `json:"comment,omitempty"` + // An enumeration of the parent commit IDs for the merge commit. + Parents *[]string `json:"parents,omitempty"` + // Reference links. + Links interface{} `json:"_links,omitempty"` + // Detailed status of the merge operation. + DetailedStatus *GitMergeOperationStatusDetail `json:"detailedStatus,omitempty"` + // Unique identifier for the merge operation. + MergeOperationId *int `json:"mergeOperationId,omitempty"` + // Status of the merge operation. + Status *GitAsyncOperationStatus `json:"status,omitempty"` +} + +// Status information about a requested merge operation. +type GitMergeOperationStatusDetail struct { + // Error message if the operation failed. + FailureMessage *string `json:"failureMessage,omitempty"` + // The commitId of the resultant merge commit. + MergeCommitId *string `json:"mergeCommitId,omitempty"` +} + +type GitMergeOriginRef struct { + CherryPickId *int `json:"cherryPickId,omitempty"` + PullRequestId *int `json:"pullRequestId,omitempty"` + RevertId *int `json:"revertId,omitempty"` +} + +// Parameters required for performing git merge. +type GitMergeParameters struct { + // Comment or message of the commit. + Comment *string `json:"comment,omitempty"` + // An enumeration of the parent commit IDs for the merge commit. + Parents *[]string `json:"parents,omitempty"` +} + +// Git object identifier and type information. +type GitObject struct { + // Object Id (Sha1Id). + ObjectId *string `json:"objectId,omitempty"` + // Type of object (Commit, Tree, Blob, Tag) + ObjectType *GitObjectType `json:"objectType,omitempty"` +} + +type GitObjectType string + +type gitObjectTypeValuesType struct { + Bad GitObjectType + Commit GitObjectType + Tree GitObjectType + Blob GitObjectType + Tag GitObjectType + Ext2 GitObjectType + OfsDelta GitObjectType + RefDelta GitObjectType +} + +var GitObjectTypeValues = gitObjectTypeValuesType{ + Bad: "bad", + Commit: "commit", + Tree: "tree", + Blob: "blob", + Tag: "tag", + Ext2: "ext2", + OfsDelta: "ofsDelta", + RefDelta: "refDelta", +} + +type GitPathAction struct { + Action *GitPathActions `json:"action,omitempty"` + Base64Content *string `json:"base64Content,omitempty"` + Path *string `json:"path,omitempty"` + RawTextContent *string `json:"rawTextContent,omitempty"` + TargetPath *string `json:"targetPath,omitempty"` +} + +type GitPathActions string + +type gitPathActionsValuesType struct { + None GitPathActions + Edit GitPathActions + Delete GitPathActions + Add GitPathActions + Rename GitPathActions +} + +var GitPathActionsValues = gitPathActionsValuesType{ + None: "none", + Edit: "edit", + Delete: "delete", + Add: "add", + Rename: "rename", +} + +type GitPathToItemsCollection struct { + Items *map[string][]GitItem `json:"items,omitempty"` +} + +type GitPolicyConfigurationResponse struct { + // The HTTP client methods find the continuation token header in the response and populate this field. + ContinuationToken *string `json:"continuationToken,omitempty"` + PolicyConfigurations *[]policy.PolicyConfiguration `json:"policyConfigurations,omitempty"` +} + +// Represents all the data associated with a pull request. +type GitPullRequest struct { + // Links to other related objects. + Links interface{} `json:"_links,omitempty"` + // A string which uniquely identifies this pull request. To generate an artifact ID for a pull request, use this template: ```vstfs:///Git/PullRequestId/{projectId}/{repositoryId}/{pullRequestId}``` + ArtifactId *string `json:"artifactId,omitempty"` + // If set, auto-complete is enabled for this pull request and this is the identity that enabled it. + AutoCompleteSetBy *webapi.IdentityRef `json:"autoCompleteSetBy,omitempty"` + // The user who closed the pull request. + ClosedBy *webapi.IdentityRef `json:"closedBy,omitempty"` + // The date when the pull request was closed (completed, abandoned, or merged externally). + ClosedDate *azuredevops.Time `json:"closedDate,omitempty"` + // The code review ID of the pull request. Used internally. + CodeReviewId *int `json:"codeReviewId,omitempty"` + // The commits contained in the pull request. + Commits *[]GitCommitRef `json:"commits,omitempty"` + // Options which affect how the pull request will be merged when it is completed. + CompletionOptions *GitPullRequestCompletionOptions `json:"completionOptions,omitempty"` + // The most recent date at which the pull request entered the queue to be completed. Used internally. + CompletionQueueTime *azuredevops.Time `json:"completionQueueTime,omitempty"` + // The identity of the user who created the pull request. + CreatedBy *webapi.IdentityRef `json:"createdBy,omitempty"` + // The date when the pull request was created. + CreationDate *azuredevops.Time `json:"creationDate,omitempty"` + // The description of the pull request. + Description *string `json:"description,omitempty"` + // If this is a PR from a fork this will contain information about its source. + ForkSource *GitForkRef `json:"forkSource,omitempty"` + // Multiple mergebases warning + HasMultipleMergeBases *bool `json:"hasMultipleMergeBases,omitempty"` + // Draft / WIP pull request. + IsDraft *bool `json:"isDraft,omitempty"` + // The labels associated with the pull request. + Labels *[]core.WebApiTagDefinition `json:"labels,omitempty"` + // The commit of the most recent pull request merge. If empty, the most recent merge is in progress or was unsuccessful. + LastMergeCommit *GitCommitRef `json:"lastMergeCommit,omitempty"` + // The commit at the head of the source branch at the time of the last pull request merge. + LastMergeSourceCommit *GitCommitRef `json:"lastMergeSourceCommit,omitempty"` + // The commit at the head of the target branch at the time of the last pull request merge. + LastMergeTargetCommit *GitCommitRef `json:"lastMergeTargetCommit,omitempty"` + // If set, pull request merge failed for this reason. + MergeFailureMessage *string `json:"mergeFailureMessage,omitempty"` + // The type of failure (if any) of the pull request merge. + MergeFailureType *PullRequestMergeFailureType `json:"mergeFailureType,omitempty"` + // The ID of the job used to run the pull request merge. Used internally. + MergeId *uuid.UUID `json:"mergeId,omitempty"` + // Options used when the pull request merge runs. These are separate from completion options since completion happens only once and a new merge will run every time the source branch of the pull request changes. + MergeOptions *GitPullRequestMergeOptions `json:"mergeOptions,omitempty"` + // The current status of the pull request merge. + MergeStatus *PullRequestAsyncStatus `json:"mergeStatus,omitempty"` + // The ID of the pull request. + PullRequestId *int `json:"pullRequestId,omitempty"` + // Used internally. + RemoteUrl *string `json:"remoteUrl,omitempty"` + // The repository containing the target branch of the pull request. + Repository *GitRepository `json:"repository,omitempty"` + // A list of reviewers on the pull request along with the state of their votes. + Reviewers *[]IdentityRefWithVote `json:"reviewers,omitempty"` + // The name of the source branch of the pull request. + SourceRefName *string `json:"sourceRefName,omitempty"` + // The status of the pull request. + Status *PullRequestStatus `json:"status,omitempty"` + // If true, this pull request supports multiple iterations. Iteration support means individual pushes to the source branch of the pull request can be reviewed and comments left in one iteration will be tracked across future iterations. + SupportsIterations *bool `json:"supportsIterations,omitempty"` + // The name of the target branch of the pull request. + TargetRefName *string `json:"targetRefName,omitempty"` + // The title of the pull request. + Title *string `json:"title,omitempty"` + // Used internally. + Url *string `json:"url,omitempty"` + // Any work item references associated with this pull request. + WorkItemRefs *[]webapi.ResourceRef `json:"workItemRefs,omitempty"` +} + +// Represents a comment thread of a pull request. A thread contains meta data about the file it was left on (if any) along with one or more comments (an initial comment and the subsequent replies). +type GitPullRequestCommentThread struct { + // Links to other related objects. + Links interface{} `json:"_links,omitempty"` + // A list of the comments. + Comments *[]Comment `json:"comments,omitempty"` + // The comment thread id. + Id *int `json:"id,omitempty"` + // Set of identities related to this thread + Identities *map[string]webapi.IdentityRef `json:"identities,omitempty"` + // Specify if the thread is deleted which happens when all comments are deleted. + IsDeleted *bool `json:"isDeleted,omitempty"` + // The time this thread was last updated. + LastUpdatedDate *azuredevops.Time `json:"lastUpdatedDate,omitempty"` + // Optional properties associated with the thread as a collection of key-value pairs. + Properties interface{} `json:"properties,omitempty"` + // The time this thread was published. + PublishedDate *azuredevops.Time `json:"publishedDate,omitempty"` + // The status of the comment thread. + Status *CommentThreadStatus `json:"status,omitempty"` + // Specify thread context such as position in left/right file. + ThreadContext *CommentThreadContext `json:"threadContext,omitempty"` + // Extended context information unique to pull requests + PullRequestThreadContext *GitPullRequestCommentThreadContext `json:"pullRequestThreadContext,omitempty"` +} + +// Comment thread context contains details about what diffs were being viewed at the time of thread creation and whether or not the thread has been tracked from that original diff. +type GitPullRequestCommentThreadContext struct { + // Used to track a comment across iterations. This value can be found by looking at the iteration's changes list. Must be set for pull requests with iteration support. Otherwise, it's not required for 'legacy' pull requests. + ChangeTrackingId *int `json:"changeTrackingId,omitempty"` + // The iteration context being viewed when the thread was created. + IterationContext *CommentIterationContext `json:"iterationContext,omitempty"` + // The criteria used to track this thread. If this property is filled out when the thread is returned, then the thread has been tracked from its original location using the given criteria. + TrackingCriteria *CommentTrackingCriteria `json:"trackingCriteria,omitempty"` +} + +// Preferences about how the pull request should be completed. +type GitPullRequestCompletionOptions struct { + // List of any policy configuration Id's which auto-complete should not wait for. Only applies to optional policies (isBlocking == false). Auto-complete always waits for required policies (isBlocking == true). + AutoCompleteIgnoreConfigIds *[]int `json:"autoCompleteIgnoreConfigIds,omitempty"` + // If true, policies will be explicitly bypassed while the pull request is completed. + BypassPolicy *bool `json:"bypassPolicy,omitempty"` + // If policies are bypassed, this reason is stored as to why bypass was used. + BypassReason *string `json:"bypassReason,omitempty"` + // If true, the source branch of the pull request will be deleted after completion. + DeleteSourceBranch *bool `json:"deleteSourceBranch,omitempty"` + // If set, this will be used as the commit message of the merge commit. + MergeCommitMessage *string `json:"mergeCommitMessage,omitempty"` + // Specify the strategy used to merge the pull request during completion. If MergeStrategy is not set to any value, a no-FF merge will be created if SquashMerge == false. If MergeStrategy is not set to any value, the pull request commits will be squashed if SquashMerge == true. The SquashMerge property is deprecated. It is recommended that you explicitly set MergeStrategy in all cases. If an explicit value is provided for MergeStrategy, the SquashMerge property will be ignored. + MergeStrategy *GitPullRequestMergeStrategy `json:"mergeStrategy,omitempty"` + // SquashMerge is deprecated. You should explicitly set the value of MergeStrategy. If MergeStrategy is set to any value, the SquashMerge value will be ignored. If MergeStrategy is not set, the merge strategy will be no-fast-forward if this flag is false, or squash if true. + SquashMerge *bool `json:"squashMerge,omitempty"` + // If true, we will attempt to transition any work items linked to the pull request into the next logical state (i.e. Active -> Resolved) + TransitionWorkItems *bool `json:"transitionWorkItems,omitempty"` + // If true, the current completion attempt was triggered via auto-complete. Used internally. + TriggeredByAutoComplete *bool `json:"triggeredByAutoComplete,omitempty"` +} + +// Change made in a pull request. +type GitPullRequestChange struct { + // The type of change that was made to the item. + ChangeType *VersionControlChangeType `json:"changeType,omitempty"` + // Current version. + Item interface{} `json:"item,omitempty"` + // Content of the item after the change. + NewContent *ItemContent `json:"newContent,omitempty"` + // Path of the item on the server. + SourceServerItem *string `json:"sourceServerItem,omitempty"` + // URL to retrieve the item. + Url *string `json:"url,omitempty"` + // ID of the change within the group of changes. + ChangeId *int `json:"changeId,omitempty"` + // New Content template to be used when pushing new changes. + NewContentTemplate *GitTemplate `json:"newContentTemplate,omitempty"` + // Original path of item if different from current path. + OriginalPath *string `json:"originalPath,omitempty"` + // ID used to track files through multiple changes. + ChangeTrackingId *int `json:"changeTrackingId,omitempty"` +} + +// Provides properties that describe a Git pull request iteration. Iterations are created as a result of creating and pushing updates to a pull request. +type GitPullRequestIteration struct { + // A collection of related REST reference links. + Links interface{} `json:"_links,omitempty"` + // Author of the pull request iteration. + Author *webapi.IdentityRef `json:"author,omitempty"` + // The commits included with the pull request iteration. + Commits *[]GitCommitRef `json:"commits,omitempty"` + // The first common Git commit of the source and target refs. + CommonRefCommit *GitCommitRef `json:"commonRefCommit,omitempty"` + // The creation date of the pull request iteration. + CreatedDate *azuredevops.Time `json:"createdDate,omitempty"` + // Description of the pull request iteration. + Description *string `json:"description,omitempty"` + // Indicates if the Commits property contains a truncated list of commits in this pull request iteration. + HasMoreCommits *bool `json:"hasMoreCommits,omitempty"` + // Changes included with the pull request iteration. + ChangeList *[]GitPullRequestChange `json:"changeList,omitempty"` + // ID of the pull request iteration. Iterations are created as a result of creating and pushing updates to a pull request. + Id *int `json:"id,omitempty"` + // If the iteration reason is Retarget, this is the refName of the new target + NewTargetRefName *string `json:"newTargetRefName,omitempty"` + // If the iteration reason is Retarget, this is the original target refName + OldTargetRefName *string `json:"oldTargetRefName,omitempty"` + // The Git push information associated with this pull request iteration. + Push *GitPushRef `json:"push,omitempty"` + // The reason for which the pull request iteration was created. + Reason *IterationReason `json:"reason,omitempty"` + // The source Git commit of this iteration. + SourceRefCommit *GitCommitRef `json:"sourceRefCommit,omitempty"` + // The target Git commit of this iteration. + TargetRefCommit *GitCommitRef `json:"targetRefCommit,omitempty"` + // The updated date of the pull request iteration. + UpdatedDate *azuredevops.Time `json:"updatedDate,omitempty"` +} + +// Collection of changes made in a pull request. +type GitPullRequestIterationChanges struct { + // Changes made in the iteration. + ChangeEntries *[]GitPullRequestChange `json:"changeEntries,omitempty"` + // Value to specify as skip to get the next page of changes. This will be zero if there are no more changes. + NextSkip *int `json:"nextSkip,omitempty"` + // Value to specify as top to get the next page of changes. This will be zero if there are no more changes. + NextTop *int `json:"nextTop,omitempty"` +} + +// The options which are used when a pull request merge is created. +type GitPullRequestMergeOptions struct { + // If true, conflict resolutions applied during the merge will be put in separate commits to preserve authorship info for git blame, etc. + ConflictAuthorshipCommits *bool `json:"conflictAuthorshipCommits,omitempty"` + DetectRenameFalsePositives *bool `json:"detectRenameFalsePositives,omitempty"` + // If true, rename detection will not be performed during the merge. + DisableRenames *bool `json:"disableRenames,omitempty"` +} + +// Enumeration of possible merge strategies which can be used to complete a pull request. +type GitPullRequestMergeStrategy string + +type gitPullRequestMergeStrategyValuesType struct { + NoFastForward GitPullRequestMergeStrategy + Squash GitPullRequestMergeStrategy + Rebase GitPullRequestMergeStrategy + RebaseMerge GitPullRequestMergeStrategy +} + +var GitPullRequestMergeStrategyValues = gitPullRequestMergeStrategyValuesType{ + // A two-parent, no-fast-forward merge. The source branch is unchanged. This is the default behavior. + NoFastForward: "noFastForward", + // Put all changes from the pull request into a single-parent commit. + Squash: "squash", + // Rebase the source branch on top of the target branch HEAD commit, and fast-forward the target branch. The source branch is updated during the rebase operation. + Rebase: "rebase", + // Rebase the source branch on top of the target branch HEAD commit, and create a two-parent, no-fast-forward merge. The source branch is updated during the rebase operation. + RebaseMerge: "rebaseMerge", +} + +// A set of pull request queries and their results. +type GitPullRequestQuery struct { + // The queries to perform. + Queries *[]GitPullRequestQueryInput `json:"queries,omitempty"` + // The results of the queries. This matches the QueryInputs list so Results[n] are the results of QueryInputs[n]. Each entry in the list is a dictionary of commit->pull requests. + Results *[]map[string][]GitPullRequest `json:"results,omitempty"` +} + +// Pull request query input parameters. +type GitPullRequestQueryInput struct { + // The list of commit IDs to search for. + Items *[]string `json:"items,omitempty"` + // The type of query to perform. + Type *GitPullRequestQueryType `json:"type,omitempty"` +} + +// Accepted types of pull request queries. +type GitPullRequestQueryType string + +type gitPullRequestQueryTypeValuesType struct { + NotSet GitPullRequestQueryType + LastMergeCommit GitPullRequestQueryType + Commit GitPullRequestQueryType +} + +var GitPullRequestQueryTypeValues = gitPullRequestQueryTypeValuesType{ + // No query type set. + NotSet: "notSet", + // Search for pull requests that created the supplied merge commits. + LastMergeCommit: "lastMergeCommit", + // Search for pull requests that merged the supplied commits. + Commit: "commit", +} + +type GitPullRequestReviewFileContentInfo struct { + Links interface{} `json:"_links,omitempty"` + // The file change path. + Path *string `json:"path,omitempty"` + // Content hash of on-disk representation of file content. Its calculated by the client by using SHA1 hash function. Ensure that uploaded file has same encoding as in source control. + ShA1Hash *string `json:"shA1Hash,omitempty"` +} + +type GitPullRequestReviewFileType string + +type gitPullRequestReviewFileTypeValuesType struct { + ChangeEntry GitPullRequestReviewFileType + Attachment GitPullRequestReviewFileType +} + +var GitPullRequestReviewFileTypeValues = gitPullRequestReviewFileTypeValuesType{ + ChangeEntry: "changeEntry", + Attachment: "attachment", +} + +// Pull requests can be searched for matching this criteria. +type GitPullRequestSearchCriteria struct { + // If set, search for pull requests that were created by this identity. + CreatorId *uuid.UUID `json:"creatorId,omitempty"` + // Whether to include the _links field on the shallow references + IncludeLinks *bool `json:"includeLinks,omitempty"` + // If set, search for pull requests whose target branch is in this repository. + RepositoryId *uuid.UUID `json:"repositoryId,omitempty"` + // If set, search for pull requests that have this identity as a reviewer. + ReviewerId *uuid.UUID `json:"reviewerId,omitempty"` + // If set, search for pull requests from this branch. + SourceRefName *string `json:"sourceRefName,omitempty"` + // If set, search for pull requests whose source branch is in this repository. + SourceRepositoryId *uuid.UUID `json:"sourceRepositoryId,omitempty"` + // If set, search for pull requests that are in this state. Defaults to Active if unset. + Status *PullRequestStatus `json:"status,omitempty"` + // If set, search for pull requests into this branch. + TargetRefName *string `json:"targetRefName,omitempty"` +} + +// This class contains the metadata of a service/extension posting pull request status. Status can be associated with a pull request or an iteration. +type GitPullRequestStatus struct { + // Reference links. + Links interface{} `json:"_links,omitempty"` + // Context of the status. + Context *GitStatusContext `json:"context,omitempty"` + // Identity that created the status. + CreatedBy *webapi.IdentityRef `json:"createdBy,omitempty"` + // Creation date and time of the status. + CreationDate *azuredevops.Time `json:"creationDate,omitempty"` + // Status description. Typically describes current state of the status. + Description *string `json:"description,omitempty"` + // Status identifier. + Id *int `json:"id,omitempty"` + // State of the status. + State *GitStatusState `json:"state,omitempty"` + // URL with status details. + TargetUrl *string `json:"targetUrl,omitempty"` + // Last update date and time of the status. + UpdatedDate *azuredevops.Time `json:"updatedDate,omitempty"` + // ID of the iteration to associate status with. Minimum value is 1. + IterationId *int `json:"iterationId,omitempty"` + // Custom properties of the status. + Properties interface{} `json:"properties,omitempty"` +} + +type GitPush struct { + Links interface{} `json:"_links,omitempty"` + Date *azuredevops.Time `json:"date,omitempty"` + PushCorrelationId *uuid.UUID `json:"pushCorrelationId,omitempty"` + PushedBy *webapi.IdentityRef `json:"pushedBy,omitempty"` + PushId *int `json:"pushId,omitempty"` + Url *string `json:"url,omitempty"` + Commits *[]GitCommitRef `json:"commits,omitempty"` + RefUpdates *[]GitRefUpdate `json:"refUpdates,omitempty"` + Repository *GitRepository `json:"repository,omitempty"` +} + +type GitPushEventData struct { + AfterId *string `json:"afterId,omitempty"` + BeforeId *string `json:"beforeId,omitempty"` + Branch *string `json:"branch,omitempty"` + Commits *[]GitCommit `json:"commits,omitempty"` + Repository *GitRepository `json:"repository,omitempty"` +} + +type GitPushRef struct { + Links interface{} `json:"_links,omitempty"` + Date *azuredevops.Time `json:"date,omitempty"` + // Deprecated: This is unused as of Dev15 M115 and may be deleted in the future + PushCorrelationId *uuid.UUID `json:"pushCorrelationId,omitempty"` + PushedBy *webapi.IdentityRef `json:"pushedBy,omitempty"` + PushId *int `json:"pushId,omitempty"` + Url *string `json:"url,omitempty"` +} + +type GitPushSearchCriteria struct { + FromDate *azuredevops.Time `json:"fromDate,omitempty"` + // Whether to include the _links field on the shallow references + IncludeLinks *bool `json:"includeLinks,omitempty"` + IncludeRefUpdates *bool `json:"includeRefUpdates,omitempty"` + PusherId *uuid.UUID `json:"pusherId,omitempty"` + RefName *string `json:"refName,omitempty"` + ToDate *azuredevops.Time `json:"toDate,omitempty"` +} + +type GitQueryBranchStatsCriteria struct { + BaseCommit *GitVersionDescriptor `json:"baseCommit,omitempty"` + TargetCommits *[]GitVersionDescriptor `json:"targetCommits,omitempty"` +} + +type GitQueryCommitsCriteria struct { + // Number of entries to skip + Skip *int `json:"$skip,omitempty"` + // Maximum number of entries to retrieve + Top *int `json:"$top,omitempty"` + // Alias or display name of the author + Author *string `json:"author,omitempty"` + // Only applicable when ItemVersion specified. If provided, start walking history starting at this commit. + CompareVersion *GitVersionDescriptor `json:"compareVersion,omitempty"` + // Only applies when an itemPath is specified. This determines whether to exclude delete entries of the specified path. + ExcludeDeletes *bool `json:"excludeDeletes,omitempty"` + // If provided, a lower bound for filtering commits alphabetically + FromCommitId *string `json:"fromCommitId,omitempty"` + // If provided, only include history entries created after this date (string) + FromDate *string `json:"fromDate,omitempty"` + // What Git history mode should be used. This only applies to the search criteria when Ids = null and an itemPath is specified. + HistoryMode *GitHistoryMode `json:"historyMode,omitempty"` + // If provided, specifies the exact commit ids of the commits to fetch. May not be combined with other parameters. + Ids *[]string `json:"ids,omitempty"` + // Whether to include the _links field on the shallow references + IncludeLinks *bool `json:"includeLinks,omitempty"` + // Whether to include the push information + IncludePushData *bool `json:"includePushData,omitempty"` + // Whether to include the image Url for committers and authors + IncludeUserImageUrl *bool `json:"includeUserImageUrl,omitempty"` + // Whether to include linked work items + IncludeWorkItems *bool `json:"includeWorkItems,omitempty"` + // Path of item to search under + ItemPath *string `json:"itemPath,omitempty"` + // If provided, identifies the commit or branch to search + ItemVersion *GitVersionDescriptor `json:"itemVersion,omitempty"` + // If enabled, this option will ignore the itemVersion and compareVersion parameters + ShowOldestCommitsFirst *bool `json:"showOldestCommitsFirst,omitempty"` + // If provided, an upper bound for filtering commits alphabetically + ToCommitId *string `json:"toCommitId,omitempty"` + // If provided, only include history entries created before this date (string) + ToDate *string `json:"toDate,omitempty"` + // Alias or display name of the committer + User *string `json:"user,omitempty"` +} + +type GitQueryRefsCriteria struct { + // List of commit Ids to be searched + CommitIds *[]string `json:"commitIds,omitempty"` + // List of complete or partial names for refs to be searched + RefNames *[]string `json:"refNames,omitempty"` + // Type of search on refNames, if provided + SearchType *GitRefSearchType `json:"searchType,omitempty"` +} + +type GitRecycleBinRepositoryDetails struct { + // Setting to false will undo earlier deletion and restore the repository. + Deleted *bool `json:"deleted,omitempty"` +} + +type GitRef struct { + Links interface{} `json:"_links,omitempty"` + Creator *webapi.IdentityRef `json:"creator,omitempty"` + IsLocked *bool `json:"isLocked,omitempty"` + IsLockedBy *webapi.IdentityRef `json:"isLockedBy,omitempty"` + Name *string `json:"name,omitempty"` + ObjectId *string `json:"objectId,omitempty"` + PeeledObjectId *string `json:"peeledObjectId,omitempty"` + Statuses *[]GitStatus `json:"statuses,omitempty"` + Url *string `json:"url,omitempty"` +} + +type GitRefFavorite struct { + Links interface{} `json:"_links,omitempty"` + Id *int `json:"id,omitempty"` + IdentityId *uuid.UUID `json:"identityId,omitempty"` + Name *string `json:"name,omitempty"` + RepositoryId *uuid.UUID `json:"repositoryId,omitempty"` + Type *RefFavoriteType `json:"type,omitempty"` + Url *string `json:"url,omitempty"` +} + +// Search type on ref name +type GitRefSearchType string + +type gitRefSearchTypeValuesType struct { + Exact GitRefSearchType + StartsWith GitRefSearchType + Contains GitRefSearchType +} + +var GitRefSearchTypeValues = gitRefSearchTypeValuesType{ + Exact: "exact", + StartsWith: "startsWith", + Contains: "contains", +} + +type GitRefUpdate struct { + IsLocked *bool `json:"isLocked,omitempty"` + Name *string `json:"name,omitempty"` + NewObjectId *string `json:"newObjectId,omitempty"` + OldObjectId *string `json:"oldObjectId,omitempty"` + RepositoryId *uuid.UUID `json:"repositoryId,omitempty"` +} + +// Enumerates the modes under which ref updates can be written to their repositories. +type GitRefUpdateMode string + +type gitRefUpdateModeValuesType struct { + BestEffort GitRefUpdateMode + AllOrNone GitRefUpdateMode +} + +var GitRefUpdateModeValues = gitRefUpdateModeValuesType{ + // Indicates the Git protocol model where any refs that can be updated will be updated, but any failures will not prevent other updates from succeeding. + BestEffort: "bestEffort", + // Indicates that all ref updates must succeed or none will succeed. All ref updates will be atomically written. If any failure is encountered, previously successful updates will be rolled back and the entire operation will fail. + AllOrNone: "allOrNone", +} + +type GitRefUpdateResult struct { + // Custom message for the result object For instance, Reason for failing. + CustomMessage *string `json:"customMessage,omitempty"` + // Whether the ref is locked or not + IsLocked *bool `json:"isLocked,omitempty"` + // Ref name + Name *string `json:"name,omitempty"` + // New object ID + NewObjectId *string `json:"newObjectId,omitempty"` + // Old object ID + OldObjectId *string `json:"oldObjectId,omitempty"` + // Name of the plugin that rejected the updated. + RejectedBy *string `json:"rejectedBy,omitempty"` + // Repository ID + RepositoryId *uuid.UUID `json:"repositoryId,omitempty"` + // True if the ref update succeeded, false otherwise + Success *bool `json:"success,omitempty"` + // Status of the update from the TFS server. + UpdateStatus *GitRefUpdateStatus `json:"updateStatus,omitempty"` +} + +// Represents the possible outcomes from a request to update a ref in a repository. +type GitRefUpdateStatus string + +type gitRefUpdateStatusValuesType struct { + Succeeded GitRefUpdateStatus + ForcePushRequired GitRefUpdateStatus + StaleOldObjectId GitRefUpdateStatus + InvalidRefName GitRefUpdateStatus + Unprocessed GitRefUpdateStatus + UnresolvableToCommit GitRefUpdateStatus + WritePermissionRequired GitRefUpdateStatus + ManageNotePermissionRequired GitRefUpdateStatus + CreateBranchPermissionRequired GitRefUpdateStatus + CreateTagPermissionRequired GitRefUpdateStatus + RejectedByPlugin GitRefUpdateStatus + Locked GitRefUpdateStatus + RefNameConflict GitRefUpdateStatus + RejectedByPolicy GitRefUpdateStatus + SucceededNonExistentRef GitRefUpdateStatus + SucceededCorruptRef GitRefUpdateStatus +} + +var GitRefUpdateStatusValues = gitRefUpdateStatusValuesType{ + // Indicates that the ref update request was completed successfully. + Succeeded: "succeeded", + // Indicates that the ref update request could not be completed because part of the graph would be disconnected by this change, and the caller does not have ForcePush permission on the repository. + ForcePushRequired: "forcePushRequired", + // Indicates that the ref update request could not be completed because the old object ID presented in the request was not the object ID of the ref when the database attempted the update. The most likely scenario is that the caller lost a race to update the ref. + StaleOldObjectId: "staleOldObjectId", + // Indicates that the ref update request could not be completed because the ref name presented in the request was not valid. + InvalidRefName: "invalidRefName", + // The request was not processed + Unprocessed: "unprocessed", + // The ref update request could not be completed because the new object ID for the ref could not be resolved to a commit object (potentially through any number of tags) + UnresolvableToCommit: "unresolvableToCommit", + // The ref update request could not be completed because the user lacks write permissions required to write this ref + WritePermissionRequired: "writePermissionRequired", + // The ref update request could not be completed because the user lacks note creation permissions required to write this note + ManageNotePermissionRequired: "manageNotePermissionRequired", + // The ref update request could not be completed because the user lacks the permission to create a branch + CreateBranchPermissionRequired: "createBranchPermissionRequired", + // The ref update request could not be completed because the user lacks the permission to create a tag + CreateTagPermissionRequired: "createTagPermissionRequired", + // The ref update could not be completed because it was rejected by the plugin. + RejectedByPlugin: "rejectedByPlugin", + // The ref update could not be completed because the ref is locked by another user. + Locked: "locked", + // The ref update could not be completed because, in case-insensitive mode, the ref name conflicts with an existing, differently-cased ref name. + RefNameConflict: "refNameConflict", + // The ref update could not be completed because it was rejected by policy. + RejectedByPolicy: "rejectedByPolicy", + // Indicates that the ref update request was completed successfully, but the ref doesn't actually exist so no changes were made. This should only happen during deletes. + SucceededNonExistentRef: "succeededNonExistentRef", + // Indicates that the ref update request was completed successfully, but the passed-in ref was corrupt - as in, the old object ID was bad. This should only happen during deletes. + SucceededCorruptRef: "succeededCorruptRef", +} + +type GitRepository struct { + Links interface{} `json:"_links,omitempty"` + DefaultBranch *string `json:"defaultBranch,omitempty"` + Id *uuid.UUID `json:"id,omitempty"` + // True if the repository is disabled. False otherwise. + IsDisabled *bool `json:"isDisabled,omitempty"` + // True if the repository was created as a fork. + IsFork *bool `json:"isFork,omitempty"` + // True if the repository is in maintenance. False otherwise. + IsInMaintenance *bool `json:"isInMaintenance,omitempty"` + Name *string `json:"name,omitempty"` + ParentRepository *GitRepositoryRef `json:"parentRepository,omitempty"` + Project *core.TeamProjectReference `json:"project,omitempty"` + RemoteUrl *string `json:"remoteUrl,omitempty"` + // Compressed size (bytes) of the repository. + Size *uint64 `json:"size,omitempty"` + SshUrl *string `json:"sshUrl,omitempty"` + Url *string `json:"url,omitempty"` + ValidRemoteUrls *[]string `json:"validRemoteUrls,omitempty"` + WebUrl *string `json:"webUrl,omitempty"` +} + +type GitRepositoryCreateOptions struct { + Name *string `json:"name,omitempty"` + ParentRepository *GitRepositoryRef `json:"parentRepository,omitempty"` + Project *core.TeamProjectReference `json:"project,omitempty"` +} + +type GitRepositoryRef struct { + // Team Project Collection where this Fork resides + Collection *core.TeamProjectCollectionReference `json:"collection,omitempty"` + Id *uuid.UUID `json:"id,omitempty"` + // True if the repository was created as a fork + IsFork *bool `json:"isFork,omitempty"` + Name *string `json:"name,omitempty"` + Project *core.TeamProjectReference `json:"project,omitempty"` + RemoteUrl *string `json:"remoteUrl,omitempty"` + SshUrl *string `json:"sshUrl,omitempty"` + Url *string `json:"url,omitempty"` +} + +type GitRepositoryStats struct { + ActivePullRequestsCount *int `json:"activePullRequestsCount,omitempty"` + BranchesCount *int `json:"branchesCount,omitempty"` + CommitsCount *int `json:"commitsCount,omitempty"` + RepositoryId *string `json:"repositoryId,omitempty"` +} + +type GitResolution struct { + // User who created the resolution. + Author *webapi.IdentityRef `json:"author,omitempty"` +} + +// The type of a merge conflict. +type GitResolutionError string + +type gitResolutionErrorValuesType struct { + None GitResolutionError + MergeContentNotFound GitResolutionError + PathInUse GitResolutionError + InvalidPath GitResolutionError + UnknownAction GitResolutionError + UnknownMergeType GitResolutionError + OtherError GitResolutionError +} + +var GitResolutionErrorValues = gitResolutionErrorValuesType{ + // No error + None: "none", + // User set a blob id for resolving a content merge, but blob was not found in repo during application + MergeContentNotFound: "mergeContentNotFound", + // Attempted to resolve a conflict by moving a file to another path, but path was already in use + PathInUse: "pathInUse", + // No error + InvalidPath: "invalidPath", + // GitResolutionAction was set to an unrecognized value + UnknownAction: "unknownAction", + // GitResolutionMergeType was set to an unrecognized value + UnknownMergeType: "unknownMergeType", + // Any error for which a more specific code doesn't apply + OtherError: "otherError", +} + +type GitResolutionMergeContent struct { + // User who created the resolution. + Author *webapi.IdentityRef `json:"author,omitempty"` + MergeType *GitResolutionMergeType `json:"mergeType,omitempty"` + UserMergedBlob *GitBlobRef `json:"userMergedBlob,omitempty"` + UserMergedContent *[]byte `json:"userMergedContent,omitempty"` +} + +type GitResolutionMergeType string + +type gitResolutionMergeTypeValuesType struct { + Undecided GitResolutionMergeType + TakeSourceContent GitResolutionMergeType + TakeTargetContent GitResolutionMergeType + AutoMerged GitResolutionMergeType + UserMerged GitResolutionMergeType +} + +var GitResolutionMergeTypeValues = gitResolutionMergeTypeValuesType{ + Undecided: "undecided", + TakeSourceContent: "takeSourceContent", + TakeTargetContent: "takeTargetContent", + AutoMerged: "autoMerged", + UserMerged: "userMerged", +} + +type GitResolutionPathConflict struct { + // User who created the resolution. + Author *webapi.IdentityRef `json:"author,omitempty"` + Action *GitResolutionPathConflictAction `json:"action,omitempty"` + RenamePath *string `json:"renamePath,omitempty"` +} + +type GitResolutionPathConflictAction string + +type gitResolutionPathConflictActionValuesType struct { + Undecided GitResolutionPathConflictAction + KeepSourceRenameTarget GitResolutionPathConflictAction + KeepSourceDeleteTarget GitResolutionPathConflictAction + KeepTargetRenameSource GitResolutionPathConflictAction + KeepTargetDeleteSource GitResolutionPathConflictAction +} + +var GitResolutionPathConflictActionValues = gitResolutionPathConflictActionValuesType{ + Undecided: "undecided", + KeepSourceRenameTarget: "keepSourceRenameTarget", + KeepSourceDeleteTarget: "keepSourceDeleteTarget", + KeepTargetRenameSource: "keepTargetRenameSource", + KeepTargetDeleteSource: "keepTargetDeleteSource", +} + +type GitResolutionPickOneAction struct { + // User who created the resolution. + Author *webapi.IdentityRef `json:"author,omitempty"` + Action *GitResolutionWhichAction `json:"action,omitempty"` +} + +type GitResolutionRename1to2 struct { + // User who created the resolution. + Author *webapi.IdentityRef `json:"author,omitempty"` + MergeType *GitResolutionMergeType `json:"mergeType,omitempty"` + UserMergedBlob *GitBlobRef `json:"userMergedBlob,omitempty"` + UserMergedContent *[]byte `json:"userMergedContent,omitempty"` + Action *GitResolutionRename1to2Action `json:"action,omitempty"` +} + +type GitResolutionRename1to2Action string + +type gitResolutionRename1to2ActionValuesType struct { + Undecided GitResolutionRename1to2Action + KeepSourcePath GitResolutionRename1to2Action + KeepTargetPath GitResolutionRename1to2Action + KeepBothFiles GitResolutionRename1to2Action +} + +var GitResolutionRename1to2ActionValues = gitResolutionRename1to2ActionValuesType{ + Undecided: "undecided", + KeepSourcePath: "keepSourcePath", + KeepTargetPath: "keepTargetPath", + KeepBothFiles: "keepBothFiles", +} + +// Resolution status of a conflict. +type GitResolutionStatus string + +type gitResolutionStatusValuesType struct { + Unresolved GitResolutionStatus + PartiallyResolved GitResolutionStatus + Resolved GitResolutionStatus +} + +var GitResolutionStatusValues = gitResolutionStatusValuesType{ + Unresolved: "unresolved", + PartiallyResolved: "partiallyResolved", + Resolved: "resolved", +} + +type GitResolutionWhichAction string + +type gitResolutionWhichActionValuesType struct { + Undecided GitResolutionWhichAction + PickSourceAction GitResolutionWhichAction + PickTargetAction GitResolutionWhichAction +} + +var GitResolutionWhichActionValues = gitResolutionWhichActionValuesType{ + Undecided: "undecided", + PickSourceAction: "pickSourceAction", + PickTargetAction: "pickTargetAction", +} + +type GitRevert struct { + Links interface{} `json:"_links,omitempty"` + DetailedStatus *GitAsyncRefOperationDetail `json:"detailedStatus,omitempty"` + Parameters *GitAsyncRefOperationParameters `json:"parameters,omitempty"` + Status *GitAsyncOperationStatus `json:"status,omitempty"` + // A URL that can be used to make further requests for status about the operation + Url *string `json:"url,omitempty"` + RevertId *int `json:"revertId,omitempty"` +} + +// This class contains the metadata of a service/extension posting a status. +type GitStatus struct { + // Reference links. + Links interface{} `json:"_links,omitempty"` + // Context of the status. + Context *GitStatusContext `json:"context,omitempty"` + // Identity that created the status. + CreatedBy *webapi.IdentityRef `json:"createdBy,omitempty"` + // Creation date and time of the status. + CreationDate *azuredevops.Time `json:"creationDate,omitempty"` + // Status description. Typically describes current state of the status. + Description *string `json:"description,omitempty"` + // Status identifier. + Id *int `json:"id,omitempty"` + // State of the status. + State *GitStatusState `json:"state,omitempty"` + // URL with status details. + TargetUrl *string `json:"targetUrl,omitempty"` + // Last update date and time of the status. + UpdatedDate *azuredevops.Time `json:"updatedDate,omitempty"` +} + +// Status context that uniquely identifies the status. +type GitStatusContext struct { + // Genre of the status. Typically name of the service/tool generating the status, can be empty. + Genre *string `json:"genre,omitempty"` + // Name identifier of the status, cannot be null or empty. + Name *string `json:"name,omitempty"` +} + +// State of the status. +type GitStatusState string + +type gitStatusStateValuesType struct { + NotSet GitStatusState + Pending GitStatusState + Succeeded GitStatusState + Failed GitStatusState + Error GitStatusState + NotApplicable GitStatusState +} + +var GitStatusStateValues = gitStatusStateValuesType{ + // Status state not set. Default state. + NotSet: "notSet", + // Status pending. + Pending: "pending", + // Status succeeded. + Succeeded: "succeeded", + // Status failed. + Failed: "failed", + // Status with an error. + Error: "error", + // Status is not applicable to the target object. + NotApplicable: "notApplicable", +} + +// An object describing the git suggestion. Git suggestions are currently limited to suggested pull requests. +type GitSuggestion struct { + // Specific properties describing the suggestion. + Properties *map[string]interface{} `json:"properties,omitempty"` + // The type of suggestion (e.g. pull request). + Type *string `json:"type,omitempty"` +} + +type GitTargetVersionDescriptor struct { + // Version string identifier (name of tag/branch, SHA1 of commit) + Version *string `json:"version,omitempty"` + // Version options - Specify additional modifiers to version (e.g Previous) + VersionOptions *GitVersionOptions `json:"versionOptions,omitempty"` + // Version type (branch, tag, or commit). Determines how Id is interpreted + VersionType *GitVersionType `json:"versionType,omitempty"` + // Version string identifier (name of tag/branch, SHA1 of commit) + TargetVersion *string `json:"targetVersion,omitempty"` + // Version options - Specify additional modifiers to version (e.g Previous) + TargetVersionOptions *GitVersionOptions `json:"targetVersionOptions,omitempty"` + // Version type (branch, tag, or commit). Determines how Id is interpreted + TargetVersionType *GitVersionType `json:"targetVersionType,omitempty"` +} + +type GitTemplate struct { + // Name of the Template + Name *string `json:"name,omitempty"` + // Type of the Template + Type *string `json:"type,omitempty"` +} + +type GitTreeDiff struct { + // ObjectId of the base tree of this diff. + BaseTreeId *string `json:"baseTreeId,omitempty"` + // List of tree entries that differ between the base and target tree. Renames and object type changes are returned as a delete for the old object and add for the new object. If a continuation token is returned in the response header, some tree entries are yet to be processed and may yield more diff entries. If the continuation token is not returned all the diff entries have been included in this response. + DiffEntries *[]GitTreeDiffEntry `json:"diffEntries,omitempty"` + // ObjectId of the target tree of this diff. + TargetTreeId *string `json:"targetTreeId,omitempty"` + // REST Url to this resource. + Url *string `json:"url,omitempty"` +} + +type GitTreeDiffEntry struct { + // SHA1 hash of the object in the base tree, if it exists. Will be null in case of adds. + BaseObjectId *string `json:"baseObjectId,omitempty"` + // Type of change that affected this entry. + ChangeType *VersionControlChangeType `json:"changeType,omitempty"` + // Object type of the tree entry. Blob, Tree or Commit("submodule") + ObjectType *GitObjectType `json:"objectType,omitempty"` + // Relative path in base and target trees. + Path *string `json:"path,omitempty"` + // SHA1 hash of the object in the target tree, if it exists. Will be null in case of deletes. + TargetObjectId *string `json:"targetObjectId,omitempty"` +} + +type GitTreeDiffResponse struct { + // The HTTP client methods find the continuation token header in the response and populate this field. + ContinuationToken *[]string `json:"continuationToken,omitempty"` + TreeDiff *GitTreeDiff `json:"treeDiff,omitempty"` +} + +type GitTreeEntryRef struct { + // Blob or tree + GitObjectType *GitObjectType `json:"gitObjectType,omitempty"` + // Mode represented as octal string + Mode *string `json:"mode,omitempty"` + // SHA1 hash of git object + ObjectId *string `json:"objectId,omitempty"` + // Path relative to parent tree object + RelativePath *string `json:"relativePath,omitempty"` + // Size of content + Size *uint64 `json:"size,omitempty"` + // url to retrieve tree or blob + Url *string `json:"url,omitempty"` +} + +type GitTreeRef struct { + Links interface{} `json:"_links,omitempty"` + // SHA1 hash of git object + ObjectId *string `json:"objectId,omitempty"` + // Sum of sizes of all children + Size *uint64 `json:"size,omitempty"` + // Blobs and trees under this tree + TreeEntries *[]GitTreeEntryRef `json:"treeEntries,omitempty"` + // Url to tree + Url *string `json:"url,omitempty"` +} + +// User info and date for Git operations. +type GitUserDate struct { + // Date of the Git operation. + Date *azuredevops.Time `json:"date,omitempty"` + // Email address of the user performing the Git operation. + Email *string `json:"email,omitempty"` + // Url for the user's avatar. + ImageUrl *string `json:"imageUrl,omitempty"` + // Name of the user performing the Git operation. + Name *string `json:"name,omitempty"` +} + +type GitVersionDescriptor struct { + // Version string identifier (name of tag/branch, SHA1 of commit) + Version *string `json:"version,omitempty"` + // Version options - Specify additional modifiers to version (e.g Previous) + VersionOptions *GitVersionOptions `json:"versionOptions,omitempty"` + // Version type (branch, tag, or commit). Determines how Id is interpreted + VersionType *GitVersionType `json:"versionType,omitempty"` +} + +// Accepted types of version options +type GitVersionOptions string + +type gitVersionOptionsValuesType struct { + None GitVersionOptions + PreviousChange GitVersionOptions + FirstParent GitVersionOptions +} + +var GitVersionOptionsValues = gitVersionOptionsValuesType{ + // Not specified + None: "none", + // Commit that changed item prior to the current version + PreviousChange: "previousChange", + // First parent of commit (HEAD^) + FirstParent: "firstParent", +} + +// Accepted types of version +type GitVersionType string + +type gitVersionTypeValuesType struct { + Branch GitVersionType + Tag GitVersionType + Commit GitVersionType +} + +var GitVersionTypeValues = gitVersionTypeValuesType{ + // Interpret the version as a branch name + Branch: "branch", + // Interpret the version as a tag name + Tag: "tag", + // Interpret the version as a commit ID (SHA1) + Commit: "commit", +} + +// Globally unique key for a repository. +type GlobalGitRepositoryKey struct { + // Team Project Collection ID of the collection for the repository. + CollectionId *uuid.UUID `json:"collectionId,omitempty"` + // Team Project ID of the project for the repository. + ProjectId *uuid.UUID `json:"projectId,omitempty"` + // ID of the repository. + RepositoryId *uuid.UUID `json:"repositoryId,omitempty"` +} + +type HistoryEntry struct { + // The Change list (changeset/commit/shelveset) for this point in history + ChangeList interface{} `json:"changeList,omitempty"` + // The change made to the item from this change list (only relevant for File history, not folders) + ItemChangeType *VersionControlChangeType `json:"itemChangeType,omitempty"` + // The path of the item at this point in history (only relevant for File history, not folders) + ServerItem *string `json:"serverItem,omitempty"` +} + +type Change struct { + // The type of change that was made to the item. + ChangeType *VersionControlChangeType `json:"changeType,omitempty"` + // Current version. + Item interface{} `json:"item,omitempty"` + // Content of the item after the change. + NewContent *ItemContent `json:"newContent,omitempty"` + // Path of the item on the server. + SourceServerItem *string `json:"sourceServerItem,omitempty"` + // URL to retrieve the item. + Url *string `json:"url,omitempty"` +} + +type ChangeCountDictionary struct { +} + +type ChangeList struct { + AllChangesIncluded *bool `json:"allChangesIncluded,omitempty"` + Comment *string `json:"comment,omitempty"` + CommentTruncated *bool `json:"commentTruncated,omitempty"` + CreationDate *azuredevops.Time `json:"creationDate,omitempty"` + ChangeCounts *map[VersionControlChangeType]int `json:"changeCounts,omitempty"` + Changes *[]interface{} `json:"changes,omitempty"` + Notes *[]CheckinNote `json:"notes,omitempty"` + Owner *string `json:"owner,omitempty"` + OwnerDisplayName *string `json:"ownerDisplayName,omitempty"` + OwnerId *uuid.UUID `json:"ownerId,omitempty"` + SortDate *azuredevops.Time `json:"sortDate,omitempty"` + Version *string `json:"version,omitempty"` +} + +// Criteria used in a search for change lists +type ChangeListSearchCriteria struct { + // If provided, a version descriptor to compare against base + CompareVersion *string `json:"compareVersion,omitempty"` + // If true, don't include delete history entries + ExcludeDeletes *bool `json:"excludeDeletes,omitempty"` + // Whether or not to follow renames for the given item being queried + FollowRenames *bool `json:"followRenames,omitempty"` + // If provided, only include history entries created after this date (string) + FromDate *string `json:"fromDate,omitempty"` + // If provided, a version descriptor for the earliest change list to include + FromVersion *string `json:"fromVersion,omitempty"` + // Path of item to search under. If the itemPaths memebr is used then it will take precedence over this. + ItemPath *string `json:"itemPath,omitempty"` + // List of item paths to search under. If this member is used then itemPath will be ignored. + ItemPaths *[]string `json:"itemPaths,omitempty"` + // Version of the items to search + ItemVersion *string `json:"itemVersion,omitempty"` + // Number of results to skip (used when clicking more...) + Skip *int `json:"skip,omitempty"` + // If provided, only include history entries created before this date (string) + ToDate *string `json:"toDate,omitempty"` + // If provided, the maximum number of history entries to return + Top *int `json:"top,omitempty"` + // If provided, a version descriptor for the latest change list to include + ToVersion *string `json:"toVersion,omitempty"` + // Alias or display name of user who made the changes + User *string `json:"user,omitempty"` +} + +type CheckinNote struct { + Name *string `json:"name,omitempty"` + Value *string `json:"value,omitempty"` +} + +// Identity information including a vote on a pull request. +type IdentityRefWithVote struct { + // This field contains zero or more interesting links about the graph subject. These links may be invoked to obtain additional relationships or more detailed information about this graph subject. + Links interface{} `json:"_links,omitempty"` + // The descriptor is the primary way to reference the graph subject while the system is running. This field will uniquely identify the same graph subject across both Accounts and Organizations. + Descriptor *string `json:"descriptor,omitempty"` + // This is the non-unique display name of the graph subject. To change this field, you must alter its value in the source provider. + DisplayName *string `json:"displayName,omitempty"` + // This url is the full route to the source resource of this graph subject. + Url *string `json:"url,omitempty"` + // Deprecated - Can be retrieved by querying the Graph user referenced in the "self" entry of the IdentityRef "_links" dictionary + DirectoryAlias *string `json:"directoryAlias,omitempty"` + Id *string `json:"id,omitempty"` + // Deprecated - Available in the "avatar" entry of the IdentityRef "_links" dictionary + ImageUrl *string `json:"imageUrl,omitempty"` + // Deprecated - Can be retrieved by querying the Graph membership state referenced in the "membershipState" entry of the GraphUser "_links" dictionary + Inactive *bool `json:"inactive,omitempty"` + // Deprecated - Can be inferred from the subject type of the descriptor (Descriptor.IsAadUserType/Descriptor.IsAadGroupType) + IsAadIdentity *bool `json:"isAadIdentity,omitempty"` + // Deprecated - Can be inferred from the subject type of the descriptor (Descriptor.IsGroupType) + IsContainer *bool `json:"isContainer,omitempty"` + IsDeletedInOrigin *bool `json:"isDeletedInOrigin,omitempty"` + // Deprecated - not in use in most preexisting implementations of ToIdentityRef + ProfileUrl *string `json:"profileUrl,omitempty"` + // Deprecated - use Domain+PrincipalName instead + UniqueName *string `json:"uniqueName,omitempty"` + // Indicates if this reviewer has declined to review this pull request. + HasDeclined *bool `json:"hasDeclined,omitempty"` + // Indicates if this reviewer is flagged for attention on this pull request. + IsFlagged *bool `json:"isFlagged,omitempty"` + // Indicates if this is a required reviewer for this pull request.
Branches can have policies that require particular reviewers are required for pull requests. + IsRequired *bool `json:"isRequired,omitempty"` + // URL to retrieve information about this identity + ReviewerUrl *string `json:"reviewerUrl,omitempty"` + // Vote on a pull request:
10 - approved 5 - approved with suggestions 0 - no vote -5 - waiting for author -10 - rejected + Vote *int `json:"vote,omitempty"` + // Groups or teams that this reviewer contributed to.
Groups and teams can be reviewers on pull requests but can not vote directly. When a member of the group or team votes, that vote is rolled up into the group or team vote. VotedFor is a list of such votes. + VotedFor *[]IdentityRefWithVote `json:"votedFor,omitempty"` +} + +type ImportRepositoryValidation struct { + GitSource *GitImportGitSource `json:"gitSource,omitempty"` + Password *string `json:"password,omitempty"` + TfvcSource *GitImportTfvcSource `json:"tfvcSource,omitempty"` + Username *string `json:"username,omitempty"` +} + +type IncludedGitCommit struct { + CommitId *string `json:"commitId,omitempty"` + CommitTime *azuredevops.Time `json:"commitTime,omitempty"` + ParentCommitIds *[]string `json:"parentCommitIds,omitempty"` + RepositoryId *uuid.UUID `json:"repositoryId,omitempty"` +} + +// Real time event (SignalR) for IsDraft update on a pull request +type IsDraftUpdatedEvent struct { + // The id of this event. Can be used to track send/receive state between client and server. + EventId *uuid.UUID `json:"eventId,omitempty"` + // The id of the pull request this event was generated for. + PullRequestId *int `json:"pullRequestId,omitempty"` +} + +type ItemContent struct { + Content *string `json:"content,omitempty"` + ContentType *ItemContentType `json:"contentType,omitempty"` +} + +// [Flags] +type ItemContentType string + +type itemContentTypeValuesType struct { + RawText ItemContentType + Base64Encoded ItemContentType +} + +var ItemContentTypeValues = itemContentTypeValuesType{ + RawText: "rawText", + Base64Encoded: "base64Encoded", +} + +// Optional details to include when returning an item model +type ItemDetailsOptions struct { + // If true, include metadata about the file type + IncludeContentMetadata *bool `json:"includeContentMetadata,omitempty"` + // Specifies whether to include children (OneLevel), all descendants (Full) or None for folder items + RecursionLevel *VersionControlRecursionType `json:"recursionLevel,omitempty"` +} + +type ItemModel struct { + Links interface{} `json:"_links,omitempty"` + Content *string `json:"content,omitempty"` + ContentMetadata *FileContentMetadata `json:"contentMetadata,omitempty"` + IsFolder *bool `json:"isFolder,omitempty"` + IsSymLink *bool `json:"isSymLink,omitempty"` + Path *string `json:"path,omitempty"` + Url *string `json:"url,omitempty"` +} + +// [Flags] The reason for which the pull request iteration was created. +type IterationReason string + +type iterationReasonValuesType struct { + Push IterationReason + ForcePush IterationReason + Create IterationReason + Rebase IterationReason + Unknown IterationReason + Retarget IterationReason + ResolveConflicts IterationReason +} + +var IterationReasonValues = iterationReasonValuesType{ + Push: "push", + ForcePush: "forcePush", + Create: "create", + Rebase: "rebase", + Unknown: "unknown", + Retarget: "retarget", + ResolveConflicts: "resolveConflicts", +} + +// Real time event (SignalR) for updated labels on a pull request +type LabelsUpdatedEvent struct { + // The id of this event. Can be used to track send/receive state between client and server. + EventId *uuid.UUID `json:"eventId,omitempty"` + // The id of the pull request this event was generated for. + PullRequestId *int `json:"pullRequestId,omitempty"` +} + +// The class to represent the line diff block +type LineDiffBlock struct { + // Type of change that was made to the block. + ChangeType *LineDiffBlockChangeType `json:"changeType,omitempty"` + // Line number where this block starts in modified file. + ModifiedLineNumberStart *int `json:"modifiedLineNumberStart,omitempty"` + // Count of lines in this block in modified file. + ModifiedLinesCount *int `json:"modifiedLinesCount,omitempty"` + // Line number where this block starts in original file. + OriginalLineNumberStart *int `json:"originalLineNumberStart,omitempty"` + // Count of lines in this block in original file. + OriginalLinesCount *int `json:"originalLinesCount,omitempty"` +} + +// Type of change for a line diff block +type LineDiffBlockChangeType string + +type lineDiffBlockChangeTypeValuesType struct { + None LineDiffBlockChangeType + Add LineDiffBlockChangeType + Delete LineDiffBlockChangeType + Edit LineDiffBlockChangeType +} + +var LineDiffBlockChangeTypeValues = lineDiffBlockChangeTypeValuesType{ + // No change - both the blocks are identical + None: "none", + // Lines were added to the block in the modified file + Add: "add", + // Lines were deleted from the block in the original file + Delete: "delete", + // Lines were modified + Edit: "edit", +} + +// Real time event (SignalR) for a merge completed on a pull request +type MergeCompletedEvent struct { + // The id of this event. Can be used to track send/receive state between client and server. + EventId *uuid.UUID `json:"eventId,omitempty"` + // The id of the pull request this event was generated for. + PullRequestId *int `json:"pullRequestId,omitempty"` +} + +// Real time event (SignalR) for a policy evaluation update on a pull request +type PolicyEvaluationUpdatedEvent struct { + // The id of this event. Can be used to track send/receive state between client and server. + EventId *uuid.UUID `json:"eventId,omitempty"` + // The id of the pull request this event was generated for. + PullRequestId *int `json:"pullRequestId,omitempty"` +} + +// The status of a pull request merge. +type PullRequestAsyncStatus string + +type pullRequestAsyncStatusValuesType struct { + NotSet PullRequestAsyncStatus + Queued PullRequestAsyncStatus + Conflicts PullRequestAsyncStatus + Succeeded PullRequestAsyncStatus + RejectedByPolicy PullRequestAsyncStatus + Failure PullRequestAsyncStatus +} + +var PullRequestAsyncStatusValues = pullRequestAsyncStatusValuesType{ + // Status is not set. Default state. + NotSet: "notSet", + // Pull request merge is queued. + Queued: "queued", + // Pull request merge failed due to conflicts. + Conflicts: "conflicts", + // Pull request merge succeeded. + Succeeded: "succeeded", + // Pull request merge rejected by policy. + RejectedByPolicy: "rejectedByPolicy", + // Pull request merge failed. + Failure: "failure", +} + +// Real time event (SignalR) for pull request creation +type PullRequestCreatedEvent struct { + // The id of this event. Can be used to track send/receive state between client and server. + EventId *uuid.UUID `json:"eventId,omitempty"` + // The id of the pull request this event was generated for. + PullRequestId *int `json:"pullRequestId,omitempty"` +} + +// The specific type of a pull request merge failure. +type PullRequestMergeFailureType string + +type pullRequestMergeFailureTypeValuesType struct { + None PullRequestMergeFailureType + Unknown PullRequestMergeFailureType + CaseSensitive PullRequestMergeFailureType + ObjectTooLarge PullRequestMergeFailureType +} + +var PullRequestMergeFailureTypeValues = pullRequestMergeFailureTypeValuesType{ + // Type is not set. Default type. + None: "none", + // Pull request merge failure type unknown. + Unknown: "unknown", + // Pull request merge failed due to case mismatch. + CaseSensitive: "caseSensitive", + // Pull request merge failed due to an object being too large. + ObjectTooLarge: "objectTooLarge", +} + +// Status of a pull request. +type PullRequestStatus string + +type pullRequestStatusValuesType struct { + NotSet PullRequestStatus + Active PullRequestStatus + Abandoned PullRequestStatus + Completed PullRequestStatus + All PullRequestStatus +} + +var PullRequestStatusValues = pullRequestStatusValuesType{ + // Status not set. Default state. + NotSet: "notSet", + // Pull request is active. + Active: "active", + // Pull request is abandoned. + Abandoned: "abandoned", + // Pull request is completed. + Completed: "completed", + // Used in pull request search criteria to include all statuses. + All: "all", +} + +// Initial config contract sent to extensions creating tabs on the pull request page +type PullRequestTabExtensionConfig struct { + PullRequestId *int `json:"pullRequestId,omitempty"` + RepositoryId *string `json:"repositoryId,omitempty"` +} + +// Base contract for a real time pull request event (SignalR) +type RealTimePullRequestEvent struct { + // The id of this event. Can be used to track send/receive state between client and server. + EventId *uuid.UUID `json:"eventId,omitempty"` + // The id of the pull request this event was generated for. + PullRequestId *int `json:"pullRequestId,omitempty"` +} + +type RefFavoriteType string + +type refFavoriteTypeValuesType struct { + Invalid RefFavoriteType + Folder RefFavoriteType + Ref RefFavoriteType +} + +var RefFavoriteTypeValues = refFavoriteTypeValuesType{ + Invalid: "invalid", + Folder: "folder", + Ref: "ref", +} + +// Real time event (SignalR) for when the target branch of a pull request is changed +type RetargetEvent struct { + // The id of this event. Can be used to track send/receive state between client and server. + EventId *uuid.UUID `json:"eventId,omitempty"` + // The id of the pull request this event was generated for. + PullRequestId *int `json:"pullRequestId,omitempty"` +} + +// Real time event (SignalR) for an update to reviewers on a pull request +type ReviewersUpdatedEvent struct { + // The id of this event. Can be used to track send/receive state between client and server. + EventId *uuid.UUID `json:"eventId,omitempty"` + // The id of the pull request this event was generated for. + PullRequestId *int `json:"pullRequestId,omitempty"` +} + +// Real time event (SignalR) for reviewer votes being reset on a pull request +type ReviewersVotesResetEvent struct { + // The id of this event. Can be used to track send/receive state between client and server. + EventId *uuid.UUID `json:"eventId,omitempty"` + // The id of the pull request this event was generated for. + PullRequestId *int `json:"pullRequestId,omitempty"` +} + +// Real time event (SignalR) for a reviewer vote update on a pull request +type ReviewerVoteUpdatedEvent struct { + // The id of this event. Can be used to track send/receive state between client and server. + EventId *uuid.UUID `json:"eventId,omitempty"` + // The id of the pull request this event was generated for. + PullRequestId *int `json:"pullRequestId,omitempty"` +} + +// Context used while sharing a pull request. +type ShareNotificationContext struct { + // Optional user note or message. + Message *string `json:"message,omitempty"` + // Identities of users who will receive a share notification. + Receivers *[]webapi.IdentityRef `json:"receivers,omitempty"` +} + +type SourceToTargetRef struct { + // The source ref to copy. For example, refs/heads/master. + SourceRef *string `json:"sourceRef,omitempty"` + // The target ref to update. For example, refs/heads/master. + TargetRef *string `json:"targetRef,omitempty"` +} + +// Real time event (SignalR) for an added status on a pull request +type StatusAddedEvent struct { + // The id of this event. Can be used to track send/receive state between client and server. + EventId *uuid.UUID `json:"eventId,omitempty"` + // The id of the pull request this event was generated for. + PullRequestId *int `json:"pullRequestId,omitempty"` +} + +// Real time event (SignalR) for deleted statuses on a pull request +type StatusesDeletedEvent struct { + // The id of this event. Can be used to track send/receive state between client and server. + EventId *uuid.UUID `json:"eventId,omitempty"` + // The id of the pull request this event was generated for. + PullRequestId *int `json:"pullRequestId,omitempty"` +} + +// Real time event (SignalR) for a status update on a pull request +type StatusUpdatedEvent struct { + // The id of this event. Can be used to track send/receive state between client and server. + EventId *uuid.UUID `json:"eventId,omitempty"` + // The id of the pull request this event was generated for. + PullRequestId *int `json:"pullRequestId,omitempty"` +} + +// Represents a Supported IDE entity. +type SupportedIde struct { + // The download URL for the IDE. + DownloadUrl *string `json:"downloadUrl,omitempty"` + // The type of the IDE. + IdeType *SupportedIdeType `json:"ideType,omitempty"` + // The name of the IDE. + Name *string `json:"name,omitempty"` + // The URL to open the protocol handler for the IDE. + ProtocolHandlerUrl *string `json:"protocolHandlerUrl,omitempty"` + // A list of SupportedPlatforms. + SupportedPlatforms *[]string `json:"supportedPlatforms,omitempty"` +} + +// Enumeration that represents the types of IDEs supported. +type SupportedIdeType string + +type supportedIdeTypeValuesType struct { + Unknown SupportedIdeType + AndroidStudio SupportedIdeType + AppCode SupportedIdeType + CLion SupportedIdeType + DataGrip SupportedIdeType + Eclipse SupportedIdeType + IntelliJ SupportedIdeType + Mps SupportedIdeType + PhpStorm SupportedIdeType + PyCharm SupportedIdeType + RubyMine SupportedIdeType + Tower SupportedIdeType + VisualStudio SupportedIdeType + VsCode SupportedIdeType + WebStorm SupportedIdeType +} + +var SupportedIdeTypeValues = supportedIdeTypeValuesType{ + Unknown: "unknown", + AndroidStudio: "androidStudio", + AppCode: "appCode", + CLion: "cLion", + DataGrip: "dataGrip", + Eclipse: "eclipse", + IntelliJ: "intelliJ", + Mps: "mps", + PhpStorm: "phpStorm", + PyCharm: "pyCharm", + RubyMine: "rubyMine", + Tower: "tower", + VisualStudio: "visualStudio", + VsCode: "vsCode", + WebStorm: "webStorm", +} + +// Class representing a branch object. +type TfvcBranch struct { + // Path for the branch. + Path *string `json:"path,omitempty"` + // A collection of REST reference links. + Links interface{} `json:"_links,omitempty"` + // Creation date of the branch. + CreatedDate *azuredevops.Time `json:"createdDate,omitempty"` + // Branch description. + Description *string `json:"description,omitempty"` + // Is the branch deleted? + IsDeleted *bool `json:"isDeleted,omitempty"` + // Alias or display name of user + Owner *webapi.IdentityRef `json:"owner,omitempty"` + // URL to retrieve the item. + Url *string `json:"url,omitempty"` + // List of children for the branch. + Children *[]TfvcBranch `json:"children,omitempty"` + // List of branch mappings. + Mappings *[]TfvcBranchMapping `json:"mappings,omitempty"` + // Path of the branch's parent. + Parent *TfvcShallowBranchRef `json:"parent,omitempty"` + // List of paths of the related branches. + RelatedBranches *[]TfvcShallowBranchRef `json:"relatedBranches,omitempty"` +} + +// A branch mapping. +type TfvcBranchMapping struct { + // Depth of the branch. + Depth *string `json:"depth,omitempty"` + // Server item for the branch. + ServerItem *string `json:"serverItem,omitempty"` + // Type of the branch. + Type *string `json:"type,omitempty"` +} + +// Metadata for a branchref. +type TfvcBranchRef struct { + // Path for the branch. + Path *string `json:"path,omitempty"` + // A collection of REST reference links. + Links interface{} `json:"_links,omitempty"` + // Creation date of the branch. + CreatedDate *azuredevops.Time `json:"createdDate,omitempty"` + // Branch description. + Description *string `json:"description,omitempty"` + // Is the branch deleted? + IsDeleted *bool `json:"isDeleted,omitempty"` + // Alias or display name of user + Owner *webapi.IdentityRef `json:"owner,omitempty"` + // URL to retrieve the item. + Url *string `json:"url,omitempty"` +} + +type TfvcHistoryEntry struct { + // The Change list (changeset/commit/shelveset) for this point in history + ChangeList interface{} `json:"changeList,omitempty"` + // The change made to the item from this change list (only relevant for File history, not folders) + ItemChangeType *VersionControlChangeType `json:"itemChangeType,omitempty"` + // The path of the item at this point in history (only relevant for File history, not folders) + ServerItem *string `json:"serverItem,omitempty"` + // The encoding of the item at this point in history (only relevant for File history, not folders) + Encoding *int `json:"encoding,omitempty"` + // The file id of the item at this point in history (only relevant for File history, not folders) + FileId *int `json:"fileId,omitempty"` +} + +// A change. +type TfvcChange struct { + // The type of change that was made to the item. + ChangeType *VersionControlChangeType `json:"changeType,omitempty"` + // Current version. + Item interface{} `json:"item,omitempty"` + // Content of the item after the change. + NewContent *ItemContent `json:"newContent,omitempty"` + // Path of the item on the server. + SourceServerItem *string `json:"sourceServerItem,omitempty"` + // URL to retrieve the item. + Url *string `json:"url,omitempty"` + // List of merge sources in case of rename or branch creation. + MergeSources *[]TfvcMergeSource `json:"mergeSources,omitempty"` + // Version at which a (shelved) change was pended against + PendingVersion *int `json:"pendingVersion,omitempty"` +} + +// A collection of changes. +type TfvcChangeset struct { + // A collection of REST reference links. + Links interface{} `json:"_links,omitempty"` + // Alias or display name of user. + Author *webapi.IdentityRef `json:"author,omitempty"` + // Comment for the changeset. + Comment *string `json:"comment,omitempty"` + // Was the Comment result truncated? + CommentTruncated *bool `json:"commentTruncated,omitempty"` + // Creation date of the changeset. + CreatedDate *azuredevops.Time `json:"createdDate,omitempty"` + // Changeset Id. + ChangesetId *int `json:"changesetId,omitempty"` + // Alias or display name of user. + CheckedInBy *webapi.IdentityRef `json:"checkedInBy,omitempty"` + // URL to retrieve the item. + Url *string `json:"url,omitempty"` + // Changeset Account Id also known as Organization Id. + AccountId *uuid.UUID `json:"accountId,omitempty"` + // Changeset collection Id. + CollectionId *uuid.UUID `json:"collectionId,omitempty"` + // True if more changes are available. + HasMoreChanges *bool `json:"hasMoreChanges,omitempty"` + // List of associated changes. + Changes *[]TfvcChange `json:"changes,omitempty"` + // List of Checkin Notes for the changeset. + CheckinNotes *[]CheckinNote `json:"checkinNotes,omitempty"` + // Policy Override for the changeset. + PolicyOverride *TfvcPolicyOverrideInfo `json:"policyOverride,omitempty"` + // Team Project Ids for the changeset. + TeamProjectIds *[]uuid.UUID `json:"teamProjectIds,omitempty"` + // List of work items associated with the changeset. + WorkItems *[]AssociatedWorkItem `json:"workItems,omitempty"` +} + +// Metadata for a changeset. +type TfvcChangesetRef struct { + // A collection of REST reference links. + Links interface{} `json:"_links,omitempty"` + // Alias or display name of user. + Author *webapi.IdentityRef `json:"author,omitempty"` + // Comment for the changeset. + Comment *string `json:"comment,omitempty"` + // Was the Comment result truncated? + CommentTruncated *bool `json:"commentTruncated,omitempty"` + // Creation date of the changeset. + CreatedDate *azuredevops.Time `json:"createdDate,omitempty"` + // Changeset Id. + ChangesetId *int `json:"changesetId,omitempty"` + // Alias or display name of user. + CheckedInBy *webapi.IdentityRef `json:"checkedInBy,omitempty"` + // URL to retrieve the item. + Url *string `json:"url,omitempty"` +} + +// Criteria used in a search for change lists. +type TfvcChangesetSearchCriteria struct { + // Alias or display name of user who made the changes. + Author *string `json:"author,omitempty"` + // Whether or not to follow renames for the given item being queried. + FollowRenames *bool `json:"followRenames,omitempty"` + // If provided, only include changesets created after this date (string). + FromDate *string `json:"fromDate,omitempty"` + // If provided, only include changesets after this changesetID. + FromId *int `json:"fromId,omitempty"` + // Whether to include the _links field on the shallow references. + IncludeLinks *bool `json:"includeLinks,omitempty"` + // Path of item to search under. + ItemPath *string `json:"itemPath,omitempty"` + Mappings *[]TfvcMappingFilter `json:"mappings,omitempty"` + // If provided, only include changesets created before this date (string). + ToDate *string `json:"toDate,omitempty"` + // If provided, a version descriptor for the latest change list to include. + ToId *int `json:"toId,omitempty"` +} + +// Request body for Get batched changesets. +type TfvcChangesetsRequestData struct { + // Max length of the comment. + CommentLength *int `json:"commentLength,omitempty"` + // List of changeset Ids. + ChangesetIds *[]int `json:"changesetIds,omitempty"` + // Whether to include the _links field on the shallow references + IncludeLinks *bool `json:"includeLinks,omitempty"` +} + +type TfvcCheckinEventData struct { + Changeset *TfvcChangeset `json:"changeset,omitempty"` + Project *core.TeamProjectReference `json:"project,omitempty"` +} + +// Metadata for an item. +type TfvcItem struct { + Links interface{} `json:"_links,omitempty"` + Content *string `json:"content,omitempty"` + ContentMetadata *FileContentMetadata `json:"contentMetadata,omitempty"` + IsFolder *bool `json:"isFolder,omitempty"` + IsSymLink *bool `json:"isSymLink,omitempty"` + Path *string `json:"path,omitempty"` + Url *string `json:"url,omitempty"` + // Greater than 0 if item is deleted. + DeletionId *int `json:"deletionId,omitempty"` + // File encoding from database, -1 represents binary. + Encoding *int `json:"encoding,omitempty"` + // MD5 hash as a base 64 string, applies to files only. + HashValue *string `json:"hashValue,omitempty"` + // Item changed datetime. + ChangeDate *azuredevops.Time `json:"changeDate,omitempty"` + // True if item is a branch. + IsBranch *bool `json:"isBranch,omitempty"` + // True if there is a change pending. + IsPendingChange *bool `json:"isPendingChange,omitempty"` + // The size of the file, if applicable. + Size *uint64 `json:"size,omitempty"` + // Changeset version Id. + Version *int `json:"version,omitempty"` +} + +// Item path and Version descriptor properties +type TfvcItemDescriptor struct { + // Item path. + Path *string `json:"path,omitempty"` + // Defaults to OneLevel. + RecursionLevel *VersionControlRecursionType `json:"recursionLevel,omitempty"` + // Specify the desired version, can be null or empty string only if VersionType is latest or tip. + Version *string `json:"version,omitempty"` + // Defaults to None. + VersionOption *TfvcVersionOption `json:"versionOption,omitempty"` + // Defaults to Latest. + VersionType *TfvcVersionType `json:"versionType,omitempty"` +} + +// Metadata for an item including the previous hash value for files. +type TfvcItemPreviousHash struct { + Links interface{} `json:"_links,omitempty"` + Content *string `json:"content,omitempty"` + ContentMetadata *FileContentMetadata `json:"contentMetadata,omitempty"` + IsFolder *bool `json:"isFolder,omitempty"` + IsSymLink *bool `json:"isSymLink,omitempty"` + Path *string `json:"path,omitempty"` + Url *string `json:"url,omitempty"` + // Greater than 0 if item is deleted. + DeletionId *int `json:"deletionId,omitempty"` + // File encoding from database, -1 represents binary. + Encoding *int `json:"encoding,omitempty"` + // MD5 hash as a base 64 string, applies to files only. + HashValue *string `json:"hashValue,omitempty"` + // Item changed datetime. + ChangeDate *azuredevops.Time `json:"changeDate,omitempty"` + // True if item is a branch. + IsBranch *bool `json:"isBranch,omitempty"` + // True if there is a change pending. + IsPendingChange *bool `json:"isPendingChange,omitempty"` + // The size of the file, if applicable. + Size *uint64 `json:"size,omitempty"` + // Changeset version Id. + Version *int `json:"version,omitempty"` + // MD5 hash as a base 64 string, applies to files only. + PreviousHashValue *string `json:"previousHashValue,omitempty"` +} + +// Request body used by Get Items Batch +type TfvcItemRequestData struct { + // If true, include metadata about the file type + IncludeContentMetadata *bool `json:"includeContentMetadata,omitempty"` + // Whether to include the _links field on the shallow references + IncludeLinks *bool `json:"includeLinks,omitempty"` + ItemDescriptors *[]TfvcItemDescriptor `json:"itemDescriptors,omitempty"` +} + +// Metadata for a label. +type TfvcLabel struct { + // Collection of reference links. + Links interface{} `json:"_links,omitempty"` + // Label description. + Description *string `json:"description,omitempty"` + // Label Id. + Id *int `json:"id,omitempty"` + // Label scope. + LabelScope *string `json:"labelScope,omitempty"` + // Last modified datetime for the label. + ModifiedDate *azuredevops.Time `json:"modifiedDate,omitempty"` + // Label name. + Name *string `json:"name,omitempty"` + // Label owner. + Owner *webapi.IdentityRef `json:"owner,omitempty"` + // Label Url. + Url *string `json:"url,omitempty"` + // List of items. + Items *[]TfvcItem `json:"items,omitempty"` +} + +// Metadata for a Label. +type TfvcLabelRef struct { + // Collection of reference links. + Links interface{} `json:"_links,omitempty"` + // Label description. + Description *string `json:"description,omitempty"` + // Label Id. + Id *int `json:"id,omitempty"` + // Label scope. + LabelScope *string `json:"labelScope,omitempty"` + // Last modified datetime for the label. + ModifiedDate *azuredevops.Time `json:"modifiedDate,omitempty"` + // Label name. + Name *string `json:"name,omitempty"` + // Label owner. + Owner *webapi.IdentityRef `json:"owner,omitempty"` + // Label Url. + Url *string `json:"url,omitempty"` +} + +type TfvcLabelRequestData struct { + // Whether to include the _links field on the shallow references + IncludeLinks *bool `json:"includeLinks,omitempty"` + ItemLabelFilter *string `json:"itemLabelFilter,omitempty"` + LabelScope *string `json:"labelScope,omitempty"` + MaxItemCount *int `json:"maxItemCount,omitempty"` + Name *string `json:"name,omitempty"` + Owner *string `json:"owner,omitempty"` +} + +// MappingFilter can be used to include or exclude specific paths. +type TfvcMappingFilter struct { + // True if ServerPath should be excluded. + Exclude *bool `json:"exclude,omitempty"` + // Path to be included or excluded. + ServerPath *string `json:"serverPath,omitempty"` +} + +type TfvcMergeSource struct { + // Indicates if this a rename source. If false, it is a merge source. + IsRename *bool `json:"isRename,omitempty"` + // The server item of the merge source. + ServerItem *string `json:"serverItem,omitempty"` + // Start of the version range. + VersionFrom *int `json:"versionFrom,omitempty"` + // End of the version range. + VersionTo *int `json:"versionTo,omitempty"` +} + +// Policy failure information. +type TfvcPolicyFailureInfo struct { + // Policy failure message. + Message *string `json:"message,omitempty"` + // Name of the policy that failed. + PolicyName *string `json:"policyName,omitempty"` +} + +// Information on the policy override. +type TfvcPolicyOverrideInfo struct { + // Overidden policy comment. + Comment *string `json:"comment,omitempty"` + // Information on the failed policy that was overridden. + PolicyFailures *[]TfvcPolicyFailureInfo `json:"policyFailures,omitempty"` +} + +// This is the shallow branchref class. +type TfvcShallowBranchRef struct { + // Path for the branch. + Path *string `json:"path,omitempty"` +} + +// Metadata for a shelveset. +type TfvcShelveset struct { + // List of reference links for the shelveset. + Links interface{} `json:"_links,omitempty"` + // Shelveset comment. + Comment *string `json:"comment,omitempty"` + // Shelveset comment truncated as applicable. + CommentTruncated *bool `json:"commentTruncated,omitempty"` + // Shelveset create date. + CreatedDate *azuredevops.Time `json:"createdDate,omitempty"` + // Shelveset Id. + Id *string `json:"id,omitempty"` + // Shelveset name. + Name *string `json:"name,omitempty"` + // Shelveset Owner. + Owner *webapi.IdentityRef `json:"owner,omitempty"` + // Shelveset Url. + Url *string `json:"url,omitempty"` + // List of changes. + Changes *[]TfvcChange `json:"changes,omitempty"` + // List of checkin notes. + Notes *[]CheckinNote `json:"notes,omitempty"` + // Policy override information if applicable. + PolicyOverride *TfvcPolicyOverrideInfo `json:"policyOverride,omitempty"` + // List of associated workitems. + WorkItems *[]AssociatedWorkItem `json:"workItems,omitempty"` +} + +// Metadata for a shallow shelveset. +type TfvcShelvesetRef struct { + // List of reference links for the shelveset. + Links interface{} `json:"_links,omitempty"` + // Shelveset comment. + Comment *string `json:"comment,omitempty"` + // Shelveset comment truncated as applicable. + CommentTruncated *bool `json:"commentTruncated,omitempty"` + // Shelveset create date. + CreatedDate *azuredevops.Time `json:"createdDate,omitempty"` + // Shelveset Id. + Id *string `json:"id,omitempty"` + // Shelveset name. + Name *string `json:"name,omitempty"` + // Shelveset Owner. + Owner *webapi.IdentityRef `json:"owner,omitempty"` + // Shelveset Url. + Url *string `json:"url,omitempty"` +} + +type TfvcShelvesetRequestData struct { + // Whether to include policyOverride and notes Only applies when requesting a single deep shelveset + IncludeDetails *bool `json:"includeDetails,omitempty"` + // Whether to include the _links field on the shallow references. Does not apply when requesting a single deep shelveset object. Links will always be included in the deep shelveset. + IncludeLinks *bool `json:"includeLinks,omitempty"` + // Whether to include workItems + IncludeWorkItems *bool `json:"includeWorkItems,omitempty"` + // Max length of comment + MaxCommentLength *int `json:"maxCommentLength,omitempty"` + // Max number of changes to include + MaxChangeCount *int `json:"maxChangeCount,omitempty"` + // Shelveset name + Name *string `json:"name,omitempty"` + // Owner's ID. Could be a name or a guid. + Owner *string `json:"owner,omitempty"` +} + +type TfvcStatistics struct { + // Count of files at the requested scope. + FileCountTotal *uint64 `json:"fileCountTotal,omitempty"` + // Id of the last changeset the stats are based on. + ChangesetId *int `json:"changesetId,omitempty"` +} + +// Version descriptor properties. +type TfvcVersionDescriptor struct { + // Version object. + Version *string `json:"version,omitempty"` + VersionOption *TfvcVersionOption `json:"versionOption,omitempty"` + VersionType *TfvcVersionType `json:"versionType,omitempty"` +} + +// Options for Version handling. +type TfvcVersionOption string + +type tfvcVersionOptionValuesType struct { + None TfvcVersionOption + Previous TfvcVersionOption + UseRename TfvcVersionOption +} + +var TfvcVersionOptionValues = tfvcVersionOptionValuesType{ + // None. + None: "none", + // Return the previous version. + Previous: "previous", + // Only usuable with versiontype MergeSource and integer versions, uses RenameSource identifier instead of Merge identifier. + UseRename: "useRename", +} + +// Type of Version object +type TfvcVersionType string + +type tfvcVersionTypeValuesType struct { + None TfvcVersionType + Changeset TfvcVersionType + Shelveset TfvcVersionType + Change TfvcVersionType + Date TfvcVersionType + Latest TfvcVersionType + Tip TfvcVersionType + MergeSource TfvcVersionType +} + +var TfvcVersionTypeValues = tfvcVersionTypeValuesType{ + // Version is treated as a ChangesetId. + None: "none", + // Version is treated as a ChangesetId. + Changeset: "changeset", + // Version is treated as a Shelveset name and owner. + Shelveset: "shelveset", + // Version is treated as a Change. + Change: "change", + // Version is treated as a Date. + Date: "date", + // If Version is defined the Latest of that Version will be used, if no version is defined the latest ChangesetId will be used. + Latest: "latest", + // Version will be treated as a Tip, if no version is defined latest will be used. + Tip: "tip", + // Version will be treated as a MergeSource. + MergeSource: "mergeSource", +} + +// Real time event (SignalR) for a title/description update on a pull request +type TitleDescriptionUpdatedEvent struct { + // The id of this event. Can be used to track send/receive state between client and server. + EventId *uuid.UUID `json:"eventId,omitempty"` + // The id of the pull request this event was generated for. + PullRequestId *int `json:"pullRequestId,omitempty"` +} + +type UpdateRefsRequest struct { + RefUpdateRequests *[]GitRefUpdate `json:"refUpdateRequests,omitempty"` + UpdateMode *GitRefUpdateMode `json:"updateMode,omitempty"` +} + +// [Flags] +type VersionControlChangeType string + +type versionControlChangeTypeValuesType struct { + None VersionControlChangeType + Add VersionControlChangeType + Edit VersionControlChangeType + Encoding VersionControlChangeType + Rename VersionControlChangeType + Delete VersionControlChangeType + Undelete VersionControlChangeType + Branch VersionControlChangeType + Merge VersionControlChangeType + Lock VersionControlChangeType + Rollback VersionControlChangeType + SourceRename VersionControlChangeType + TargetRename VersionControlChangeType + Property VersionControlChangeType + All VersionControlChangeType +} + +var VersionControlChangeTypeValues = versionControlChangeTypeValuesType{ + None: "none", + Add: "add", + Edit: "edit", + Encoding: "encoding", + Rename: "rename", + Delete: "delete", + Undelete: "undelete", + Branch: "branch", + Merge: "merge", + Lock: "lock", + Rollback: "rollback", + SourceRename: "sourceRename", + TargetRename: "targetRename", + Property: "property", + All: "all", +} + +type VersionControlProjectInfo struct { + DefaultSourceControlType *core.SourceControlTypes `json:"defaultSourceControlType,omitempty"` + Project *core.TeamProjectReference `json:"project,omitempty"` + SupportsGit *bool `json:"supportsGit,omitempty"` + SupportsTFVC *bool `json:"supportsTFVC,omitempty"` +} + +type VersionControlRecursionType string + +type versionControlRecursionTypeValuesType struct { + None VersionControlRecursionType + OneLevel VersionControlRecursionType + OneLevelPlusNestedEmptyFolders VersionControlRecursionType + Full VersionControlRecursionType +} + +var VersionControlRecursionTypeValues = versionControlRecursionTypeValuesType{ + // Only return the specified item. + None: "none", + // Return the specified item and its direct children. + OneLevel: "oneLevel", + // Return the specified item and its direct children, as well as recursive chains of nested child folders that only contain a single folder. + OneLevelPlusNestedEmptyFolders: "oneLevelPlusNestedEmptyFolders", + // Return specified item and all descendants + Full: "full", +} diff --git a/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/identity/client.go b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/identity/client.go new file mode 100644 index 000000000..a613e83b0 --- /dev/null +++ b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/identity/client.go @@ -0,0 +1,1097 @@ +// -------------------------------------------------------------------------------------------- +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// -------------------------------------------------------------------------------------------- +// Generated file, DO NOT EDIT +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// -------------------------------------------------------------------------------------------- + +package identity + +import ( + "bytes" + "context" + "encoding/json" + "github.com/google/uuid" + "github.com/microsoft/azure-devops-go-api/azuredevops/v7" + "github.com/microsoft/azure-devops-go-api/azuredevops/v7/delegatedauthorization" + "github.com/microsoft/azure-devops-go-api/azuredevops/v7/webapi" + "net/http" + "net/url" + "strconv" +) + +var ResourceAreaId, _ = uuid.Parse("8a3d49b8-91f0-46ef-b33d-dda338c25db3") + +type Client interface { + // [Preview API] + AddMember(context.Context, AddMemberArgs) (*bool, error) + // [Preview API] + CreateGroups(context.Context, CreateGroupsArgs) (*[]Identity, error) + // [Preview API] + CreateIdentity(context.Context, CreateIdentityArgs) (*Identity, error) + // [Preview API] + CreateOrBindWithClaims(context.Context, CreateOrBindWithClaimsArgs) (*Identity, error) + // [Preview API] + CreateScope(context.Context, CreateScopeArgs) (*IdentityScope, error) + // [Preview API] + DeleteGroup(context.Context, DeleteGroupArgs) error + // [Preview API] + DeleteScope(context.Context, DeleteScopeArgs) error + // [Preview API] + ForceRemoveMember(context.Context, ForceRemoveMemberArgs) (*bool, error) + // [Preview API] + GetDescriptorById(context.Context, GetDescriptorByIdArgs) (*string, error) + // [Preview API] + GetIdentityChanges(context.Context, GetIdentityChangesArgs) (*ChangedIdentities, error) + // [Preview API] + GetIdentitySnapshot(context.Context, GetIdentitySnapshotArgs) (*IdentitySnapshot, error) + // [Preview API] Read the max sequence id of all the identities. + GetMaxSequenceId(context.Context, GetMaxSequenceIdArgs) (*uint64, error) + // [Preview API] + GetScopeById(context.Context, GetScopeByIdArgs) (*IdentityScope, error) + // [Preview API] + GetScopeByName(context.Context, GetScopeByNameArgs) (*IdentityScope, error) + // [Preview API] Read identity of the home tenant request user. + GetSelf(context.Context, GetSelfArgs) (*IdentitySelf, error) + // [Preview API] + GetSignedInToken(context.Context, GetSignedInTokenArgs) (*delegatedauthorization.AccessTokenResult, error) + // [Preview API] + GetSignoutToken(context.Context, GetSignoutTokenArgs) (*delegatedauthorization.AccessTokenResult, error) + // [Preview API] + GetTenant(context.Context, GetTenantArgs) (*TenantInfo, error) + // [Preview API] + GetUserIdentityIdsByDomainId(context.Context, GetUserIdentityIdsByDomainIdArgs) (*[]uuid.UUID, error) + // [Preview API] + ListGroups(context.Context, ListGroupsArgs) (*[]Identity, error) + // [Preview API] Resolve legacy identity information for use with older APIs such as the Security APIs + ReadIdentities(context.Context, ReadIdentitiesArgs) (*[]Identity, error) + // [Preview API] + ReadIdentitiesByScope(context.Context, ReadIdentitiesByScopeArgs) (*[]Identity, error) + // [Preview API] + ReadIdentity(context.Context, ReadIdentityArgs) (*Identity, error) + // [Preview API] + ReadIdentityBatch(context.Context, ReadIdentityBatchArgs) (*[]Identity, error) + // [Preview API] + ReadMember(context.Context, ReadMemberArgs) (*string, error) + // [Preview API] + ReadMemberOf(context.Context, ReadMemberOfArgs) (*string, error) + // [Preview API] + ReadMembers(context.Context, ReadMembersArgs) (*[]string, error) + // [Preview API] + ReadMembersOf(context.Context, ReadMembersOfArgs) (*[]string, error) + // [Preview API] + RefreshMembersOf(context.Context, RefreshMembersOfArgs) (*[]string, error) + // [Preview API] + RemoveMember(context.Context, RemoveMemberArgs) (*bool, error) + // [Preview API] + UpdateIdentities(context.Context, UpdateIdentitiesArgs) (*[]IdentityUpdateData, error) + // [Preview API] + UpdateIdentity(context.Context, UpdateIdentityArgs) error + // [Preview API] + UpdateScope(context.Context, UpdateScopeArgs) error +} + +type ClientImpl struct { + Client azuredevops.Client +} + +func NewClient(ctx context.Context, connection *azuredevops.Connection) (Client, error) { + client, err := connection.GetClientByResourceAreaId(ctx, ResourceAreaId) + if err != nil { + return nil, err + } + return &ClientImpl{ + Client: *client, + }, nil +} + +// [Preview API] +func (client *ClientImpl) AddMember(ctx context.Context, args AddMemberArgs) (*bool, error) { + routeValues := make(map[string]string) + if args.ContainerId == nil || *args.ContainerId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.ContainerId"} + } + routeValues["containerId"] = *args.ContainerId + if args.MemberId == nil || *args.MemberId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.MemberId"} + } + routeValues["memberId"] = *args.MemberId + + locationId, _ := uuid.Parse("8ba35978-138e-41f8-8963-7b1ea2c5f775") + resp, err := client.Client.Send(ctx, http.MethodPut, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue bool + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the AddMember function +type AddMemberArgs struct { + // (required) + ContainerId *string + // (required) + MemberId *string +} + +// [Preview API] +func (client *ClientImpl) CreateGroups(ctx context.Context, args CreateGroupsArgs) (*[]Identity, error) { + if args.Container == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.Container"} + } + body, marshalErr := json.Marshal(args.Container) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("5966283b-4196-4d57-9211-1b68f41ec1c2") + resp, err := client.Client.Send(ctx, http.MethodPost, locationId, "7.1-preview.1", nil, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []Identity + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the CreateGroups function +type CreateGroupsArgs struct { + // (required) + Container interface{} +} + +// [Preview API] +func (client *ClientImpl) CreateIdentity(ctx context.Context, args CreateIdentityArgs) (*Identity, error) { + if args.FrameworkIdentityInfo == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.FrameworkIdentityInfo"} + } + body, marshalErr := json.Marshal(*args.FrameworkIdentityInfo) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("dd55f0eb-6ea2-4fe4-9ebe-919e7dd1dfb4") + resp, err := client.Client.Send(ctx, http.MethodPut, locationId, "7.1-preview.1", nil, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue Identity + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the CreateIdentity function +type CreateIdentityArgs struct { + // (required) + FrameworkIdentityInfo *FrameworkIdentityInfo +} + +// [Preview API] +func (client *ClientImpl) CreateOrBindWithClaims(ctx context.Context, args CreateOrBindWithClaimsArgs) (*Identity, error) { + if args.SourceIdentity == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.SourceIdentity"} + } + body, marshalErr := json.Marshal(*args.SourceIdentity) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("90ddfe71-171c-446c-bf3b-b597cd562afd") + resp, err := client.Client.Send(ctx, http.MethodPut, locationId, "7.1-preview.1", nil, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue Identity + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the CreateOrBindWithClaims function +type CreateOrBindWithClaimsArgs struct { + // (required) + SourceIdentity *Identity +} + +// [Preview API] +func (client *ClientImpl) CreateScope(ctx context.Context, args CreateScopeArgs) (*IdentityScope, error) { + if args.Info == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.Info"} + } + routeValues := make(map[string]string) + if args.ScopeId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.ScopeId"} + } + routeValues["scopeId"] = (*args.ScopeId).String() + + body, marshalErr := json.Marshal(*args.Info) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("4e11e2bf-1e79-4eb5-8f34-a6337bd0de38") + resp, err := client.Client.Send(ctx, http.MethodPut, locationId, "7.1-preview.2", routeValues, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue IdentityScope + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the CreateScope function +type CreateScopeArgs struct { + // (required) + Info *CreateScopeInfo + // (required) + ScopeId *uuid.UUID +} + +// [Preview API] +func (client *ClientImpl) DeleteGroup(ctx context.Context, args DeleteGroupArgs) error { + routeValues := make(map[string]string) + if args.GroupId == nil || *args.GroupId == "" { + return &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.GroupId"} + } + routeValues["groupId"] = *args.GroupId + + locationId, _ := uuid.Parse("5966283b-4196-4d57-9211-1b68f41ec1c2") + _, err := client.Client.Send(ctx, http.MethodDelete, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return err + } + + return nil +} + +// Arguments for the DeleteGroup function +type DeleteGroupArgs struct { + // (required) + GroupId *string +} + +// [Preview API] +func (client *ClientImpl) DeleteScope(ctx context.Context, args DeleteScopeArgs) error { + routeValues := make(map[string]string) + if args.ScopeId == nil { + return &azuredevops.ArgumentNilError{ArgumentName: "args.ScopeId"} + } + routeValues["scopeId"] = (*args.ScopeId).String() + + locationId, _ := uuid.Parse("4e11e2bf-1e79-4eb5-8f34-a6337bd0de38") + _, err := client.Client.Send(ctx, http.MethodDelete, locationId, "7.1-preview.2", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return err + } + + return nil +} + +// Arguments for the DeleteScope function +type DeleteScopeArgs struct { + // (required) + ScopeId *uuid.UUID +} + +// [Preview API] +func (client *ClientImpl) ForceRemoveMember(ctx context.Context, args ForceRemoveMemberArgs) (*bool, error) { + routeValues := make(map[string]string) + if args.ContainerId == nil || *args.ContainerId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.ContainerId"} + } + routeValues["containerId"] = *args.ContainerId + if args.MemberId == nil || *args.MemberId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.MemberId"} + } + routeValues["memberId"] = *args.MemberId + + queryParams := url.Values{} + if args.ForceRemove == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "forceRemove"} + } + queryParams.Add("forceRemove", strconv.FormatBool(*args.ForceRemove)) + locationId, _ := uuid.Parse("8ba35978-138e-41f8-8963-7b1ea2c5f775") + resp, err := client.Client.Send(ctx, http.MethodDelete, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue bool + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the ForceRemoveMember function +type ForceRemoveMemberArgs struct { + // (required) + ContainerId *string + // (required) + MemberId *string + // (required) + ForceRemove *bool +} + +// [Preview API] +func (client *ClientImpl) GetDescriptorById(ctx context.Context, args GetDescriptorByIdArgs) (*string, error) { + routeValues := make(map[string]string) + if args.Id == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.Id"} + } + routeValues["id"] = (*args.Id).String() + + queryParams := url.Values{} + if args.IsMasterId != nil { + queryParams.Add("isMasterId", strconv.FormatBool(*args.IsMasterId)) + } + locationId, _ := uuid.Parse("a230389a-94f2-496c-839f-c929787496dd") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue string + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetDescriptorById function +type GetDescriptorByIdArgs struct { + // (required) + Id *uuid.UUID + // (optional) + IsMasterId *bool +} + +// [Preview API] +func (client *ClientImpl) GetIdentityChanges(ctx context.Context, args GetIdentityChangesArgs) (*ChangedIdentities, error) { + queryParams := url.Values{} + if args.IdentitySequenceId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "identitySequenceId"} + } + queryParams.Add("identitySequenceId", strconv.Itoa(*args.IdentitySequenceId)) + if args.GroupSequenceId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "groupSequenceId"} + } + queryParams.Add("groupSequenceId", strconv.Itoa(*args.GroupSequenceId)) + if args.OrganizationIdentitySequenceId != nil { + queryParams.Add("organizationIdentitySequenceId", strconv.Itoa(*args.OrganizationIdentitySequenceId)) + } + if args.PageSize != nil { + queryParams.Add("pageSize", strconv.Itoa(*args.PageSize)) + } + if args.ScopeId != nil { + queryParams.Add("scopeId", (*args.ScopeId).String()) + } + locationId, _ := uuid.Parse("28010c54-d0c0-4c89-a5b0-1c9e188b9fb7") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", nil, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue ChangedIdentities + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetIdentityChanges function +type GetIdentityChangesArgs struct { + // (required) + IdentitySequenceId *int + // (required) + GroupSequenceId *int + // (optional) + OrganizationIdentitySequenceId *int + // (optional) + PageSize *int + // (optional) + ScopeId *uuid.UUID +} + +// [Preview API] +func (client *ClientImpl) GetIdentitySnapshot(ctx context.Context, args GetIdentitySnapshotArgs) (*IdentitySnapshot, error) { + routeValues := make(map[string]string) + if args.ScopeId == nil || *args.ScopeId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.ScopeId"} + } + routeValues["scopeId"] = *args.ScopeId + + locationId, _ := uuid.Parse("d56223df-8ccd-45c9-89b4-eddf692400d7") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue IdentitySnapshot + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetIdentitySnapshot function +type GetIdentitySnapshotArgs struct { + // (required) + ScopeId *string +} + +// [Preview API] Read the max sequence id of all the identities. +func (client *ClientImpl) GetMaxSequenceId(ctx context.Context, args GetMaxSequenceIdArgs) (*uint64, error) { + locationId, _ := uuid.Parse("e4a70778-cb2c-4e85-b7cc-3f3c7ae2d408") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", nil, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue uint64 + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetMaxSequenceId function +type GetMaxSequenceIdArgs struct { +} + +// [Preview API] +func (client *ClientImpl) GetScopeById(ctx context.Context, args GetScopeByIdArgs) (*IdentityScope, error) { + routeValues := make(map[string]string) + if args.ScopeId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.ScopeId"} + } + routeValues["scopeId"] = (*args.ScopeId).String() + + locationId, _ := uuid.Parse("4e11e2bf-1e79-4eb5-8f34-a6337bd0de38") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.2", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue IdentityScope + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetScopeById function +type GetScopeByIdArgs struct { + // (required) + ScopeId *uuid.UUID +} + +// [Preview API] +func (client *ClientImpl) GetScopeByName(ctx context.Context, args GetScopeByNameArgs) (*IdentityScope, error) { + queryParams := url.Values{} + if args.ScopeName == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "scopeName"} + } + queryParams.Add("scopeName", *args.ScopeName) + locationId, _ := uuid.Parse("4e11e2bf-1e79-4eb5-8f34-a6337bd0de38") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.2", nil, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue IdentityScope + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetScopeByName function +type GetScopeByNameArgs struct { + // (required) + ScopeName *string +} + +// [Preview API] Read identity of the home tenant request user. +func (client *ClientImpl) GetSelf(ctx context.Context, args GetSelfArgs) (*IdentitySelf, error) { + locationId, _ := uuid.Parse("4bb02b5b-c120-4be2-b68e-21f7c50a4b82") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", nil, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue IdentitySelf + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetSelf function +type GetSelfArgs struct { +} + +// [Preview API] +func (client *ClientImpl) GetSignedInToken(ctx context.Context, args GetSignedInTokenArgs) (*delegatedauthorization.AccessTokenResult, error) { + locationId, _ := uuid.Parse("6074ff18-aaad-4abb-a41e-5c75f6178057") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", nil, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue delegatedauthorization.AccessTokenResult + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetSignedInToken function +type GetSignedInTokenArgs struct { +} + +// [Preview API] +func (client *ClientImpl) GetSignoutToken(ctx context.Context, args GetSignoutTokenArgs) (*delegatedauthorization.AccessTokenResult, error) { + locationId, _ := uuid.Parse("be39e83c-7529-45e9-9c67-0410885880da") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", nil, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue delegatedauthorization.AccessTokenResult + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetSignoutToken function +type GetSignoutTokenArgs struct { +} + +// [Preview API] +func (client *ClientImpl) GetTenant(ctx context.Context, args GetTenantArgs) (*TenantInfo, error) { + routeValues := make(map[string]string) + if args.TenantId == nil || *args.TenantId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.TenantId"} + } + routeValues["tenantId"] = *args.TenantId + + locationId, _ := uuid.Parse("5f0a1723-2e2c-4c31-8cae-002d01bdd592") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue TenantInfo + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetTenant function +type GetTenantArgs struct { + // (required) + TenantId *string +} + +// [Preview API] +func (client *ClientImpl) GetUserIdentityIdsByDomainId(ctx context.Context, args GetUserIdentityIdsByDomainIdArgs) (*[]uuid.UUID, error) { + queryParams := url.Values{} + if args.DomainId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "domainId"} + } + queryParams.Add("domainId", (*args.DomainId).String()) + locationId, _ := uuid.Parse("28010c54-d0c0-4c89-a5b0-1c9e188b9fb7") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", nil, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []uuid.UUID + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetUserIdentityIdsByDomainId function +type GetUserIdentityIdsByDomainIdArgs struct { + // (required) + DomainId *uuid.UUID +} + +// [Preview API] +func (client *ClientImpl) ListGroups(ctx context.Context, args ListGroupsArgs) (*[]Identity, error) { + queryParams := url.Values{} + if args.ScopeIds != nil { + queryParams.Add("scopeIds", *args.ScopeIds) + } + if args.Recurse != nil { + queryParams.Add("recurse", strconv.FormatBool(*args.Recurse)) + } + if args.Deleted != nil { + queryParams.Add("deleted", strconv.FormatBool(*args.Deleted)) + } + if args.Properties != nil { + queryParams.Add("properties", *args.Properties) + } + locationId, _ := uuid.Parse("5966283b-4196-4d57-9211-1b68f41ec1c2") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", nil, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []Identity + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the ListGroups function +type ListGroupsArgs struct { + // (optional) + ScopeIds *string + // (optional) + Recurse *bool + // (optional) + Deleted *bool + // (optional) + Properties *string +} + +// [Preview API] Resolve legacy identity information for use with older APIs such as the Security APIs +func (client *ClientImpl) ReadIdentities(ctx context.Context, args ReadIdentitiesArgs) (*[]Identity, error) { + queryParams := url.Values{} + if args.Descriptors != nil { + queryParams.Add("descriptors", *args.Descriptors) + } + if args.IdentityIds != nil { + queryParams.Add("identityIds", *args.IdentityIds) + } + if args.SubjectDescriptors != nil { + queryParams.Add("subjectDescriptors", *args.SubjectDescriptors) + } + if args.SocialDescriptors != nil { + queryParams.Add("socialDescriptors", *args.SocialDescriptors) + } + if args.SearchFilter != nil { + queryParams.Add("searchFilter", *args.SearchFilter) + } + if args.FilterValue != nil { + queryParams.Add("filterValue", *args.FilterValue) + } + if args.QueryMembership != nil { + queryParams.Add("queryMembership", string(*args.QueryMembership)) + } + if args.Properties != nil { + queryParams.Add("properties", *args.Properties) + } + if args.IncludeRestrictedVisibility != nil { + queryParams.Add("includeRestrictedVisibility", strconv.FormatBool(*args.IncludeRestrictedVisibility)) + } + if args.Options != nil { + queryParams.Add("options", string(*args.Options)) + } + locationId, _ := uuid.Parse("28010c54-d0c0-4c89-a5b0-1c9e188b9fb7") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", nil, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []Identity + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the ReadIdentities function +type ReadIdentitiesArgs struct { + // (optional) A comma separated list of identity descriptors to resolve + Descriptors *string + // (optional) A comma seperated list of storage keys to resolve + IdentityIds *string + // (optional) A comma seperated list of subject descriptors to resolve + SubjectDescriptors *string + // (optional) + SocialDescriptors *string + // (optional) The type of search to perform. Values can be AccountName (domain\alias), DisplayName, MailAddress, General (display name, account name, or unique name), or LocalGroupName (only search Azure Devops groups). + SearchFilter *string + // (optional) The search value, as specified by the searchFilter. + FilterValue *string + // (optional) The membership information to include with the identities. Values can be None for no membership data or Direct to include the groups that the identity is a member of and the identities that are a member of this identity (groups only) + QueryMembership *QueryMembership + // (optional) + Properties *string + // (optional) + IncludeRestrictedVisibility *bool + // (optional) + Options *ReadIdentitiesOptions +} + +// [Preview API] +func (client *ClientImpl) ReadIdentitiesByScope(ctx context.Context, args ReadIdentitiesByScopeArgs) (*[]Identity, error) { + queryParams := url.Values{} + if args.ScopeId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "scopeId"} + } + queryParams.Add("scopeId", (*args.ScopeId).String()) + if args.QueryMembership != nil { + queryParams.Add("queryMembership", string(*args.QueryMembership)) + } + if args.Properties != nil { + queryParams.Add("properties", *args.Properties) + } + locationId, _ := uuid.Parse("28010c54-d0c0-4c89-a5b0-1c9e188b9fb7") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", nil, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []Identity + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the ReadIdentitiesByScope function +type ReadIdentitiesByScopeArgs struct { + // (required) + ScopeId *uuid.UUID + // (optional) + QueryMembership *QueryMembership + // (optional) + Properties *string +} + +// [Preview API] +func (client *ClientImpl) ReadIdentity(ctx context.Context, args ReadIdentityArgs) (*Identity, error) { + routeValues := make(map[string]string) + if args.IdentityId == nil || *args.IdentityId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.IdentityId"} + } + routeValues["identityId"] = *args.IdentityId + + queryParams := url.Values{} + if args.QueryMembership != nil { + queryParams.Add("queryMembership", string(*args.QueryMembership)) + } + if args.Properties != nil { + queryParams.Add("properties", *args.Properties) + } + locationId, _ := uuid.Parse("28010c54-d0c0-4c89-a5b0-1c9e188b9fb7") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue Identity + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the ReadIdentity function +type ReadIdentityArgs struct { + // (required) + IdentityId *string + // (optional) + QueryMembership *QueryMembership + // (optional) + Properties *string +} + +// [Preview API] +func (client *ClientImpl) ReadIdentityBatch(ctx context.Context, args ReadIdentityBatchArgs) (*[]Identity, error) { + if args.BatchInfo == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.BatchInfo"} + } + body, marshalErr := json.Marshal(*args.BatchInfo) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("299e50df-fe45-4d3a-8b5b-a5836fac74dc") + resp, err := client.Client.Send(ctx, http.MethodPost, locationId, "7.1-preview.1", nil, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []Identity + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the ReadIdentityBatch function +type ReadIdentityBatchArgs struct { + // (required) + BatchInfo *IdentityBatchInfo +} + +// [Preview API] +func (client *ClientImpl) ReadMember(ctx context.Context, args ReadMemberArgs) (*string, error) { + routeValues := make(map[string]string) + if args.ContainerId == nil || *args.ContainerId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.ContainerId"} + } + routeValues["containerId"] = *args.ContainerId + if args.MemberId == nil || *args.MemberId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.MemberId"} + } + routeValues["memberId"] = *args.MemberId + + queryParams := url.Values{} + if args.QueryMembership != nil { + queryParams.Add("queryMembership", string(*args.QueryMembership)) + } + locationId, _ := uuid.Parse("8ba35978-138e-41f8-8963-7b1ea2c5f775") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue string + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the ReadMember function +type ReadMemberArgs struct { + // (required) + ContainerId *string + // (required) + MemberId *string + // (optional) + QueryMembership *QueryMembership +} + +// [Preview API] +func (client *ClientImpl) ReadMemberOf(ctx context.Context, args ReadMemberOfArgs) (*string, error) { + routeValues := make(map[string]string) + if args.MemberId == nil || *args.MemberId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.MemberId"} + } + routeValues["memberId"] = *args.MemberId + if args.ContainerId == nil || *args.ContainerId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.ContainerId"} + } + routeValues["containerId"] = *args.ContainerId + + queryParams := url.Values{} + if args.QueryMembership != nil { + queryParams.Add("queryMembership", string(*args.QueryMembership)) + } + locationId, _ := uuid.Parse("22865b02-9e4a-479e-9e18-e35b8803b8a0") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.2", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue string + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the ReadMemberOf function +type ReadMemberOfArgs struct { + // (required) + MemberId *string + // (required) + ContainerId *string + // (optional) + QueryMembership *QueryMembership +} + +// [Preview API] +func (client *ClientImpl) ReadMembers(ctx context.Context, args ReadMembersArgs) (*[]string, error) { + routeValues := make(map[string]string) + if args.ContainerId == nil || *args.ContainerId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.ContainerId"} + } + routeValues["containerId"] = *args.ContainerId + + queryParams := url.Values{} + if args.QueryMembership != nil { + queryParams.Add("queryMembership", string(*args.QueryMembership)) + } + locationId, _ := uuid.Parse("8ba35978-138e-41f8-8963-7b1ea2c5f775") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []string + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the ReadMembers function +type ReadMembersArgs struct { + // (required) + ContainerId *string + // (optional) + QueryMembership *QueryMembership +} + +// [Preview API] +func (client *ClientImpl) ReadMembersOf(ctx context.Context, args ReadMembersOfArgs) (*[]string, error) { + routeValues := make(map[string]string) + if args.MemberId == nil || *args.MemberId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.MemberId"} + } + routeValues["memberId"] = *args.MemberId + + queryParams := url.Values{} + if args.QueryMembership != nil { + queryParams.Add("queryMembership", string(*args.QueryMembership)) + } + locationId, _ := uuid.Parse("22865b02-9e4a-479e-9e18-e35b8803b8a0") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.2", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []string + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the ReadMembersOf function +type ReadMembersOfArgs struct { + // (required) + MemberId *string + // (optional) + QueryMembership *QueryMembership +} + +// [Preview API] +func (client *ClientImpl) RefreshMembersOf(ctx context.Context, args RefreshMembersOfArgs) (*[]string, error) { + routeValues := make(map[string]string) + if args.MemberId == nil || *args.MemberId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.MemberId"} + } + routeValues["memberId"] = *args.MemberId + + queryParams := url.Values{} + if args.QueryMembership != nil { + queryParams.Add("queryMembership", string(*args.QueryMembership)) + } + locationId, _ := uuid.Parse("22865b02-9e4a-479e-9e18-e35b8803b8a0") + resp, err := client.Client.Send(ctx, http.MethodPost, locationId, "7.1-preview.2", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []string + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the RefreshMembersOf function +type RefreshMembersOfArgs struct { + // (required) + MemberId *string + // (optional) + QueryMembership *QueryMembership +} + +// [Preview API] +func (client *ClientImpl) RemoveMember(ctx context.Context, args RemoveMemberArgs) (*bool, error) { + routeValues := make(map[string]string) + if args.ContainerId == nil || *args.ContainerId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.ContainerId"} + } + routeValues["containerId"] = *args.ContainerId + if args.MemberId == nil || *args.MemberId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.MemberId"} + } + routeValues["memberId"] = *args.MemberId + + locationId, _ := uuid.Parse("8ba35978-138e-41f8-8963-7b1ea2c5f775") + resp, err := client.Client.Send(ctx, http.MethodDelete, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue bool + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the RemoveMember function +type RemoveMemberArgs struct { + // (required) + ContainerId *string + // (required) + MemberId *string +} + +// [Preview API] +func (client *ClientImpl) UpdateIdentities(ctx context.Context, args UpdateIdentitiesArgs) (*[]IdentityUpdateData, error) { + if args.Identities == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.Identities"} + } + queryParams := url.Values{} + if args.AllowMetaDataUpdate != nil { + queryParams.Add("allowMetaDataUpdate", strconv.FormatBool(*args.AllowMetaDataUpdate)) + } + body, marshalErr := json.Marshal(*args.Identities) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("28010c54-d0c0-4c89-a5b0-1c9e188b9fb7") + resp, err := client.Client.Send(ctx, http.MethodPut, locationId, "7.1-preview.1", nil, queryParams, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []IdentityUpdateData + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the UpdateIdentities function +type UpdateIdentitiesArgs struct { + // (required) + Identities *azuredevops.VssJsonCollectionWrapper + // (optional) + AllowMetaDataUpdate *bool +} + +// [Preview API] +func (client *ClientImpl) UpdateIdentity(ctx context.Context, args UpdateIdentityArgs) error { + if args.Identity == nil { + return &azuredevops.ArgumentNilError{ArgumentName: "args.Identity"} + } + routeValues := make(map[string]string) + if args.IdentityId == nil { + return &azuredevops.ArgumentNilError{ArgumentName: "args.IdentityId"} + } + routeValues["identityId"] = (*args.IdentityId).String() + + body, marshalErr := json.Marshal(*args.Identity) + if marshalErr != nil { + return marshalErr + } + locationId, _ := uuid.Parse("28010c54-d0c0-4c89-a5b0-1c9e188b9fb7") + _, err := client.Client.Send(ctx, http.MethodPut, locationId, "7.1-preview.1", routeValues, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return err + } + + return nil +} + +// Arguments for the UpdateIdentity function +type UpdateIdentityArgs struct { + // (required) + Identity *Identity + // (required) + IdentityId *uuid.UUID +} + +// [Preview API] +func (client *ClientImpl) UpdateScope(ctx context.Context, args UpdateScopeArgs) error { + if args.PatchDocument == nil { + return &azuredevops.ArgumentNilError{ArgumentName: "args.PatchDocument"} + } + routeValues := make(map[string]string) + if args.ScopeId == nil { + return &azuredevops.ArgumentNilError{ArgumentName: "args.ScopeId"} + } + routeValues["scopeId"] = (*args.ScopeId).String() + + body, marshalErr := json.Marshal(*args.PatchDocument) + if marshalErr != nil { + return marshalErr + } + locationId, _ := uuid.Parse("4e11e2bf-1e79-4eb5-8f34-a6337bd0de38") + _, err := client.Client.Send(ctx, http.MethodPatch, locationId, "7.1-preview.2", routeValues, nil, bytes.NewReader(body), "application/json-patch+json", "application/json", nil) + if err != nil { + return err + } + + return nil +} + +// Arguments for the UpdateScope function +type UpdateScopeArgs struct { + // (required) + PatchDocument *[]webapi.JsonPatchOperation + // (required) + ScopeId *uuid.UUID +} diff --git a/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/identity/models.go b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/identity/models.go new file mode 100644 index 000000000..3e597ca47 --- /dev/null +++ b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/identity/models.go @@ -0,0 +1,253 @@ +// -------------------------------------------------------------------------------------------- +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// -------------------------------------------------------------------------------------------- +// Generated file, DO NOT EDIT +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// -------------------------------------------------------------------------------------------- + +package identity + +import ( + "github.com/google/uuid" +) + +type CreateScopeInfo struct { + AdminGroupDescription *string `json:"adminGroupDescription,omitempty"` + AdminGroupName *string `json:"adminGroupName,omitempty"` + CreatorId *uuid.UUID `json:"creatorId,omitempty"` + ParentScopeId *uuid.UUID `json:"parentScopeId,omitempty"` + ScopeName *string `json:"scopeName,omitempty"` + ScopeType *GroupScopeType `json:"scopeType,omitempty"` +} + +type FrameworkIdentityInfo struct { + DisplayName *string `json:"displayName,omitempty"` + Identifier *string `json:"identifier,omitempty"` + IdentityType *FrameworkIdentityType `json:"identityType,omitempty"` + Role *string `json:"role,omitempty"` +} + +type FrameworkIdentityType string + +type frameworkIdentityTypeValuesType struct { + None FrameworkIdentityType + ServiceIdentity FrameworkIdentityType + AggregateIdentity FrameworkIdentityType + ImportedIdentity FrameworkIdentityType +} + +var FrameworkIdentityTypeValues = frameworkIdentityTypeValuesType{ + None: "none", + ServiceIdentity: "serviceIdentity", + AggregateIdentity: "aggregateIdentity", + ImportedIdentity: "importedIdentity", +} + +type GroupMembership struct { + Active *bool `json:"active,omitempty"` + Descriptor *string `json:"descriptor,omitempty"` + Id *uuid.UUID `json:"id,omitempty"` + QueriedId *uuid.UUID `json:"queriedId,omitempty"` +} + +type GroupScopeType string + +type groupScopeTypeValuesType struct { + Generic GroupScopeType + ServiceHost GroupScopeType + TeamProject GroupScopeType +} + +var GroupScopeTypeValues = groupScopeTypeValuesType{ + Generic: "generic", + ServiceHost: "serviceHost", + TeamProject: "teamProject", +} + +// Container class for changed identities +type ChangedIdentities struct { + // Changed Identities + Identities *[]Identity `json:"identities,omitempty"` + // More data available, set to true if pagesize is specified. + MoreData *bool `json:"moreData,omitempty"` + // Last Identity SequenceId + SequenceContext *ChangedIdentitiesContext `json:"sequenceContext,omitempty"` +} + +// Context class for changed identities +type ChangedIdentitiesContext struct { + // Last Group SequenceId + GroupSequenceId *int `json:"groupSequenceId,omitempty"` + // Last Identity SequenceId + IdentitySequenceId *int `json:"identitySequenceId,omitempty"` + // Last Group OrganizationIdentitySequenceId + OrganizationIdentitySequenceId *int `json:"organizationIdentitySequenceId,omitempty"` + // Page size + PageSize *int `json:"pageSize,omitempty"` +} + +type Identity struct { + // The custom display name for the identity (if any). Setting this property to an empty string will clear the existing custom display name. Setting this property to null will not affect the existing persisted value (since null values do not get sent over the wire or to the database) + CustomDisplayName *string `json:"customDisplayName,omitempty"` + Descriptor *string `json:"descriptor,omitempty"` + // Identity Identifier. Also called Storage Key, or VSID + Id *uuid.UUID `json:"id,omitempty"` + // True if the identity has a membership in any Azure Devops group in the organization. + IsActive *bool `json:"isActive,omitempty"` + // True if the identity is a group. + IsContainer *bool `json:"isContainer,omitempty"` + MasterId *uuid.UUID `json:"masterId,omitempty"` + // Id of the members of the identity (groups only). + MemberIds *[]uuid.UUID `json:"memberIds,omitempty"` + MemberOf *[]string `json:"memberOf,omitempty"` + Members *[]string `json:"members,omitempty"` + MetaTypeId *int `json:"metaTypeId,omitempty"` + Properties interface{} `json:"properties,omitempty"` + // The display name for the identity as specified by the source identity provider. + ProviderDisplayName *string `json:"providerDisplayName,omitempty"` + ResourceVersion *int `json:"resourceVersion,omitempty"` + SocialDescriptor *string `json:"socialDescriptor,omitempty"` + // Subject descriptor of a Graph entity. + SubjectDescriptor *string `json:"subjectDescriptor,omitempty"` + UniqueUserId *int `json:"uniqueUserId,omitempty"` +} + +// Base Identity class to allow "trimmed" identity class in the GetConnectionData API Makes sure that on-the-wire representations of the derived classes are compatible with each other (e.g. Server responds with PublicIdentity object while client deserializes it as Identity object) Derived classes should not have additional [DataMember] properties +type IdentityBase struct { + // The custom display name for the identity (if any). Setting this property to an empty string will clear the existing custom display name. Setting this property to null will not affect the existing persisted value (since null values do not get sent over the wire or to the database) + CustomDisplayName *string `json:"customDisplayName,omitempty"` + Descriptor *string `json:"descriptor,omitempty"` + // Identity Identifier. Also called Storage Key, or VSID + Id *uuid.UUID `json:"id,omitempty"` + // True if the identity has a membership in any Azure Devops group in the organization. + IsActive *bool `json:"isActive,omitempty"` + // True if the identity is a group. + IsContainer *bool `json:"isContainer,omitempty"` + MasterId *uuid.UUID `json:"masterId,omitempty"` + // Id of the members of the identity (groups only). + MemberIds *[]uuid.UUID `json:"memberIds,omitempty"` + MemberOf *[]string `json:"memberOf,omitempty"` + Members *[]string `json:"members,omitempty"` + MetaTypeId *int `json:"metaTypeId,omitempty"` + Properties interface{} `json:"properties,omitempty"` + // The display name for the identity as specified by the source identity provider. + ProviderDisplayName *string `json:"providerDisplayName,omitempty"` + ResourceVersion *int `json:"resourceVersion,omitempty"` + SocialDescriptor *string `json:"socialDescriptor,omitempty"` + // Subject descriptor of a Graph entity. + SubjectDescriptor *string `json:"subjectDescriptor,omitempty"` + UniqueUserId *int `json:"uniqueUserId,omitempty"` +} + +type IdentityBatchInfo struct { + Descriptors *[]string `json:"descriptors,omitempty"` + IdentityIds *[]uuid.UUID `json:"identityIds,omitempty"` + IncludeRestrictedVisibility *bool `json:"includeRestrictedVisibility,omitempty"` + PropertyNames *[]string `json:"propertyNames,omitempty"` + QueryMembership *QueryMembership `json:"queryMembership,omitempty"` + SocialDescriptors *[]string `json:"socialDescriptors,omitempty"` + SubjectDescriptors *[]string `json:"subjectDescriptors,omitempty"` +} + +type IdentityRightsTransferData struct { + UserPrincipalNameMappings *map[string]string `json:"userPrincipalNameMappings,omitempty"` +} + +type IdentityScope struct { + Administrators *string `json:"administrators,omitempty"` + Id *uuid.UUID `json:"id,omitempty"` + IsActive *bool `json:"isActive,omitempty"` + IsGlobal *bool `json:"isGlobal,omitempty"` + LocalScopeId *uuid.UUID `json:"localScopeId,omitempty"` + Name *string `json:"name,omitempty"` + ParentId *uuid.UUID `json:"parentId,omitempty"` + ScopeType *GroupScopeType `json:"scopeType,omitempty"` + SecuringHostId *uuid.UUID `json:"securingHostId,omitempty"` + SubjectDescriptor *string `json:"subjectDescriptor,omitempty"` +} + +// Identity information. +type IdentitySelf struct { + // The UserPrincipalName (UPN) of the account. This value comes from the source provider. + AccountName *string `json:"accountName,omitempty"` + // The display name. For AAD accounts with multiple tenants this is the display name of the profile in the home tenant. + DisplayName *string `json:"displayName,omitempty"` + // This represents the name of the container of origin. For AAD accounts this is the tenantID of the home tenant. For MSA accounts this is the string "Windows Live ID". + Domain *string `json:"domain,omitempty"` + // This is the VSID of the home tenant profile. If the profile is signed into the home tenant or if the profile has no tenants then this Id is the same as the Id returned by the profile/profiles/me endpoint. Going forward it is recommended that you use the combined values of Origin, OriginId and Domain to uniquely identify a user rather than this Id. + Id *uuid.UUID `json:"id,omitempty"` + // The type of source provider for the origin identifier. For MSA accounts this is "msa". For AAD accounts this is "aad". + Origin *string `json:"origin,omitempty"` + // The unique identifier from the system of origin. If there are multiple tenants this is the unique identifier of the account in the home tenant. (For MSA this is the PUID in hex notation, for AAD this is the object id.) + OriginId *string `json:"originId,omitempty"` + // For AAD accounts this is all of the tenants that this account is a member of. + Tenants *[]TenantInfo `json:"tenants,omitempty"` +} + +type IdentitySnapshot struct { + Groups *[]Identity `json:"groups,omitempty"` + IdentityIds *[]uuid.UUID `json:"identityIds,omitempty"` + Memberships *[]GroupMembership `json:"memberships,omitempty"` + ScopeId *uuid.UUID `json:"scopeId,omitempty"` + Scopes *[]IdentityScope `json:"scopes,omitempty"` +} + +type IdentityUpdateData struct { + Id *uuid.UUID `json:"id,omitempty"` + Index *int `json:"index,omitempty"` + Updated *bool `json:"updated,omitempty"` +} + +type PagedIdentities struct { + ContinuationToken *[]string `json:"continuationToken,omitempty"` + Identities *[]Identity `json:"identities,omitempty"` +} + +type QueryMembership string + +type queryMembershipValuesType struct { + None QueryMembership + Direct QueryMembership + Expanded QueryMembership + ExpandedUp QueryMembership + ExpandedDown QueryMembership +} + +var QueryMembershipValues = queryMembershipValuesType{ + // Query will not return any membership data + None: "none", + // Query will return only direct membership data + Direct: "direct", + // Query will return expanded membership data + Expanded: "expanded", + // Query will return expanded up membership data (parents only) + ExpandedUp: "expandedUp", + // Query will return expanded down membership data (children only) + ExpandedDown: "expandedDown", +} + +// [Flags] +type ReadIdentitiesOptions string + +type readIdentitiesOptionsValuesType struct { + None ReadIdentitiesOptions + FilterIllegalMemberships ReadIdentitiesOptions +} + +var ReadIdentitiesOptionsValues = readIdentitiesOptionsValuesType{ + None: "none", + FilterIllegalMemberships: "filterIllegalMemberships", +} + +type SwapIdentityInfo struct { + Id1 *uuid.UUID `json:"id1,omitempty"` + Id2 *uuid.UUID `json:"id2,omitempty"` +} + +type TenantInfo struct { + HomeTenant *bool `json:"homeTenant,omitempty"` + TenantId *uuid.UUID `json:"tenantId,omitempty"` + TenantName *string `json:"tenantName,omitempty"` + VerifiedDomains *[]string `json:"verifiedDomains,omitempty"` +} diff --git a/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/models.go b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/models.go new file mode 100644 index 000000000..0079749ff --- /dev/null +++ b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/models.go @@ -0,0 +1,149 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azuredevops + +import ( + "encoding/json" + "strconv" + "strings" + "time" + + "github.com/google/uuid" +) + +// ApiResourceLocation Information about the location of a REST API resource +type ApiResourceLocation struct { + // Area name for this resource + Area *string `json:"area,omitempty"` + // Unique Identifier for this location + Id *uuid.UUID `json:"id,omitempty"` + // Maximum api version that this resource supports (current server version for this resource) + MaxVersion *string `json:"maxVersion,omitempty"` + // Minimum api version that this resource supports + MinVersion *string `json:"minVersion,omitempty"` + // The latest version of this resource location that is in "Release" (non-preview) mode + ReleasedVersion *string `json:"releasedVersion,omitempty"` + // Resource name + ResourceName *string `json:"resourceName,omitempty"` + // The current resource version supported by this resource location + ResourceVersion *int `json:"resourceVersion,omitempty"` + // This location's route template (templated relative path) + RouteTemplate *string `json:"routeTemplate,omitempty"` +} + +// WrappedImproperError +type WrappedImproperError struct { + Count *int `json:"count,omitempty"` + Value *ImproperError `json:"value,omitempty"` +} + +// ImproperError +type ImproperError struct { + Message *string `json:"Message,omitempty"` +} + +// KeyValuePair +type KeyValuePair struct { + Key *interface{} `json:"key,omitempty"` + Value *interface{} `json:"value,omitempty"` +} + +// ResourceAreaInfo +type ResourceAreaInfo struct { + Id *uuid.UUID `json:"id,omitempty"` + LocationUrl *string `json:"locationUrl,omitempty"` + Name *string `json:"name,omitempty"` +} + +type Time struct { + Time time.Time +} + +func (t *Time) UnmarshalJSON(b []byte) error { + t2 := time.Time{} + err := json.Unmarshal(b, &t2) + + if err != nil { + parseError, ok := err.(*time.ParseError) + if ok { + if parseError.Value == "\"0001-01-01T00:00:00\"" { + // ignore errors for 0001-01-01T00:00:00 dates. The Azure DevOps service + // returns default dates in a format that is invalid for a time.Time. The + // correct value would have a 'z' at the end to represent utc. We are going + // to ignore this error, and set the value to the default time.Time value. + // https://github.com/microsoft/azure-devops-go-api/issues/17 + err = nil + } else { + // workaround for bug https://github.com/microsoft/azure-devops-go-api/issues/59 + // policy.CreatePolicyConfiguration returns an invalid date format of form + // "2006-01-02T15:04:05.999999999" + var innerError error + t2, innerError = time.Parse("2006-01-02T15:04:05.999999999", strings.Trim(parseError.Value, "\"")) + if innerError == nil { + err = nil + } + } + } + } + + t.Time = t2 + return err +} + +func (t *Time) MarshalJSON() ([]byte, error) { + return json.Marshal(t.Time) +} + +// AsQueryParameter formats time value for query parameter usage. +func (t Time) AsQueryParameter() string { + return t.Time.Format(time.RFC3339Nano) +} + +func (t Time) String() string { + return t.Time.String() +} + +func (t Time) Equal(u Time) bool { + return t.Time.Equal(u.Time) +} + +// ServerSystemError +type ServerSystemError struct { + ClassName *string `json:"className,omitempty"` + InnerException *ServerSystemError `json:"innerException,omitempty"` + Message *string `json:"message,omitempty"` +} + +func (e ServerSystemError) Error() string { + return *e.Message +} + +// VssJsonCollectionWrapper - +type VssJsonCollectionWrapper struct { + Count *int `json:"count"` + Value *[]interface{} `json:"value"` +} + +// WrappedError +type WrappedError struct { + ExceptionId *string `json:"$id,omitempty"` + InnerError *WrappedError `json:"innerException,omitempty"` + Message *string `json:"message,omitempty"` + TypeName *string `json:"typeName,omitempty"` + TypeKey *string `json:"typeKey,omitempty"` + ErrorCode *int `json:"errorCode,omitempty"` + EventId *int `json:"eventId,omitempty"` + CustomProperties *map[string]interface{} `json:"customProperties,omitempty"` + StatusCode *int +} + +func (e WrappedError) Error() string { + if e.Message == nil { + if e.StatusCode != nil { + return "REST call returned status code " + strconv.Itoa(*e.StatusCode) + } + return "" + } + return *e.Message +} diff --git a/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/notification/client.go b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/notification/client.go new file mode 100644 index 000000000..19f9c1eac --- /dev/null +++ b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/notification/client.go @@ -0,0 +1,549 @@ +// -------------------------------------------------------------------------------------------- +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// -------------------------------------------------------------------------------------------- +// Generated file, DO NOT EDIT +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// -------------------------------------------------------------------------------------------- + +package notification + +import ( + "bytes" + "context" + "encoding/json" + "github.com/google/uuid" + "github.com/microsoft/azure-devops-go-api/azuredevops/v7" + "net/http" + "net/url" + "strings" +) + +type Client interface { + // [Preview API] Create a new subscription. + CreateSubscription(context.Context, CreateSubscriptionArgs) (*NotificationSubscription, error) + // [Preview API] Delete a subscription. + DeleteSubscription(context.Context, DeleteSubscriptionArgs) error + // [Preview API] Get a specific event type. + GetEventType(context.Context, GetEventTypeArgs) (*NotificationEventType, error) + // [Preview API] + GetSettings(context.Context, GetSettingsArgs) (*NotificationAdminSettings, error) + // [Preview API] Get delivery preferences of a notifications subscriber. + GetSubscriber(context.Context, GetSubscriberArgs) (*NotificationSubscriber, error) + // [Preview API] Get a notification subscription by its ID. + GetSubscription(context.Context, GetSubscriptionArgs) (*NotificationSubscription, error) + // [Preview API] Get the diagnostics settings for a subscription. + GetSubscriptionDiagnostics(context.Context, GetSubscriptionDiagnosticsArgs) (*SubscriptionDiagnostics, error) + // [Preview API] Get available subscription templates. + GetSubscriptionTemplates(context.Context, GetSubscriptionTemplatesArgs) (*[]NotificationSubscriptionTemplate, error) + // [Preview API] List available event types for this service. Optionally filter by only event types for the specified publisher. + ListEventTypes(context.Context, ListEventTypesArgs) (*[]NotificationEventType, error) + // [Preview API] Get a list of diagnostic logs for this service. + ListLogs(context.Context, ListLogsArgs) (*[]INotificationDiagnosticLog, error) + // [Preview API] Get a list of notification subscriptions, either by subscription IDs or by all subscriptions for a given user or group. + ListSubscriptions(context.Context, ListSubscriptionsArgs) (*[]NotificationSubscription, error) + // [Preview API] Query for subscriptions. A subscription is returned if it matches one or more of the specified conditions. + QuerySubscriptions(context.Context, QuerySubscriptionsArgs) (*[]NotificationSubscription, error) + // [Preview API] + UpdateSettings(context.Context, UpdateSettingsArgs) (*NotificationAdminSettings, error) + // [Preview API] Update delivery preferences of a notifications subscriber. + UpdateSubscriber(context.Context, UpdateSubscriberArgs) (*NotificationSubscriber, error) + // [Preview API] Update an existing subscription. Depending on the type of subscription and permissions, the caller can update the description, filter settings, channel (delivery) settings and more. + UpdateSubscription(context.Context, UpdateSubscriptionArgs) (*NotificationSubscription, error) + // [Preview API] Update the diagnostics settings for a subscription. + UpdateSubscriptionDiagnostics(context.Context, UpdateSubscriptionDiagnosticsArgs) (*SubscriptionDiagnostics, error) + // [Preview API] Update the specified user's settings for the specified subscription. This API is typically used to opt in or out of a shared subscription. User settings can only be applied to shared subscriptions, like team subscriptions or default subscriptions. + UpdateSubscriptionUserSettings(context.Context, UpdateSubscriptionUserSettingsArgs) (*SubscriptionUserSettings, error) +} + +type ClientImpl struct { + Client azuredevops.Client +} + +func NewClient(ctx context.Context, connection *azuredevops.Connection) Client { + client := connection.GetClientByUrl(connection.BaseUrl) + return &ClientImpl{ + Client: *client, + } +} + +// [Preview API] Create a new subscription. +func (client *ClientImpl) CreateSubscription(ctx context.Context, args CreateSubscriptionArgs) (*NotificationSubscription, error) { + if args.CreateParameters == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.CreateParameters"} + } + body, marshalErr := json.Marshal(*args.CreateParameters) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("70f911d6-abac-488c-85b3-a206bf57e165") + resp, err := client.Client.Send(ctx, http.MethodPost, locationId, "7.1-preview.1", nil, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue NotificationSubscription + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the CreateSubscription function +type CreateSubscriptionArgs struct { + // (required) + CreateParameters *NotificationSubscriptionCreateParameters +} + +// [Preview API] Delete a subscription. +func (client *ClientImpl) DeleteSubscription(ctx context.Context, args DeleteSubscriptionArgs) error { + routeValues := make(map[string]string) + if args.SubscriptionId == nil || *args.SubscriptionId == "" { + return &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.SubscriptionId"} + } + routeValues["subscriptionId"] = *args.SubscriptionId + + locationId, _ := uuid.Parse("70f911d6-abac-488c-85b3-a206bf57e165") + _, err := client.Client.Send(ctx, http.MethodDelete, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return err + } + + return nil +} + +// Arguments for the DeleteSubscription function +type DeleteSubscriptionArgs struct { + // (required) + SubscriptionId *string +} + +// [Preview API] Get a specific event type. +func (client *ClientImpl) GetEventType(ctx context.Context, args GetEventTypeArgs) (*NotificationEventType, error) { + routeValues := make(map[string]string) + if args.EventType == nil || *args.EventType == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.EventType"} + } + routeValues["eventType"] = *args.EventType + + locationId, _ := uuid.Parse("cc84fb5f-6247-4c7a-aeae-e5a3c3fddb21") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue NotificationEventType + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetEventType function +type GetEventTypeArgs struct { + // (required) The ID of the event type. + EventType *string +} + +// [Preview API] +func (client *ClientImpl) GetSettings(ctx context.Context, args GetSettingsArgs) (*NotificationAdminSettings, error) { + locationId, _ := uuid.Parse("cbe076d8-2803-45ff-8d8d-44653686ea2a") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", nil, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue NotificationAdminSettings + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetSettings function +type GetSettingsArgs struct { +} + +// [Preview API] Get delivery preferences of a notifications subscriber. +func (client *ClientImpl) GetSubscriber(ctx context.Context, args GetSubscriberArgs) (*NotificationSubscriber, error) { + routeValues := make(map[string]string) + if args.SubscriberId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.SubscriberId"} + } + routeValues["subscriberId"] = (*args.SubscriberId).String() + + locationId, _ := uuid.Parse("4d5caff1-25ba-430b-b808-7a1f352cc197") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue NotificationSubscriber + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetSubscriber function +type GetSubscriberArgs struct { + // (required) ID of the user or group. + SubscriberId *uuid.UUID +} + +// [Preview API] Get a notification subscription by its ID. +func (client *ClientImpl) GetSubscription(ctx context.Context, args GetSubscriptionArgs) (*NotificationSubscription, error) { + routeValues := make(map[string]string) + if args.SubscriptionId == nil || *args.SubscriptionId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.SubscriptionId"} + } + routeValues["subscriptionId"] = *args.SubscriptionId + + queryParams := url.Values{} + if args.QueryFlags != nil { + queryParams.Add("queryFlags", string(*args.QueryFlags)) + } + locationId, _ := uuid.Parse("70f911d6-abac-488c-85b3-a206bf57e165") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue NotificationSubscription + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetSubscription function +type GetSubscriptionArgs struct { + // (required) + SubscriptionId *string + // (optional) + QueryFlags *SubscriptionQueryFlags +} + +// [Preview API] Get the diagnostics settings for a subscription. +func (client *ClientImpl) GetSubscriptionDiagnostics(ctx context.Context, args GetSubscriptionDiagnosticsArgs) (*SubscriptionDiagnostics, error) { + routeValues := make(map[string]string) + if args.SubscriptionId == nil || *args.SubscriptionId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.SubscriptionId"} + } + routeValues["subscriptionId"] = *args.SubscriptionId + + locationId, _ := uuid.Parse("20f1929d-4be7-4c2e-a74e-d47640ff3418") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue SubscriptionDiagnostics + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetSubscriptionDiagnostics function +type GetSubscriptionDiagnosticsArgs struct { + // (required) The id of the notifications subscription. + SubscriptionId *string +} + +// [Preview API] Get available subscription templates. +func (client *ClientImpl) GetSubscriptionTemplates(ctx context.Context, args GetSubscriptionTemplatesArgs) (*[]NotificationSubscriptionTemplate, error) { + locationId, _ := uuid.Parse("fa5d24ba-7484-4f3d-888d-4ec6b1974082") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", nil, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []NotificationSubscriptionTemplate + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetSubscriptionTemplates function +type GetSubscriptionTemplatesArgs struct { +} + +// [Preview API] List available event types for this service. Optionally filter by only event types for the specified publisher. +func (client *ClientImpl) ListEventTypes(ctx context.Context, args ListEventTypesArgs) (*[]NotificationEventType, error) { + queryParams := url.Values{} + if args.PublisherId != nil { + queryParams.Add("publisherId", *args.PublisherId) + } + locationId, _ := uuid.Parse("cc84fb5f-6247-4c7a-aeae-e5a3c3fddb21") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", nil, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []NotificationEventType + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the ListEventTypes function +type ListEventTypesArgs struct { + // (optional) Limit to event types for this publisher + PublisherId *string +} + +// [Preview API] Get a list of diagnostic logs for this service. +func (client *ClientImpl) ListLogs(ctx context.Context, args ListLogsArgs) (*[]INotificationDiagnosticLog, error) { + routeValues := make(map[string]string) + if args.Source == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.Source"} + } + routeValues["source"] = (*args.Source).String() + if args.EntryId != nil { + routeValues["entryId"] = (*args.EntryId).String() + } + + queryParams := url.Values{} + if args.StartTime != nil { + queryParams.Add("startTime", (*args.StartTime).AsQueryParameter()) + } + if args.EndTime != nil { + queryParams.Add("endTime", (*args.EndTime).AsQueryParameter()) + } + locationId, _ := uuid.Parse("991842f3-eb16-4aea-ac81-81353ef2b75c") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []INotificationDiagnosticLog + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the ListLogs function +type ListLogsArgs struct { + // (required) ID specifying which type of logs to check diagnostics for. + Source *uuid.UUID + // (optional) The ID of the specific log to query for. + EntryId *uuid.UUID + // (optional) Start time for the time range to query in. + StartTime *azuredevops.Time + // (optional) End time for the time range to query in. + EndTime *azuredevops.Time +} + +// [Preview API] Get a list of notification subscriptions, either by subscription IDs or by all subscriptions for a given user or group. +func (client *ClientImpl) ListSubscriptions(ctx context.Context, args ListSubscriptionsArgs) (*[]NotificationSubscription, error) { + queryParams := url.Values{} + if args.TargetId != nil { + queryParams.Add("targetId", (*args.TargetId).String()) + } + if args.Ids != nil { + listAsString := strings.Join((*args.Ids)[:], ",") + queryParams.Add("ids", listAsString) + } + if args.QueryFlags != nil { + queryParams.Add("queryFlags", string(*args.QueryFlags)) + } + locationId, _ := uuid.Parse("70f911d6-abac-488c-85b3-a206bf57e165") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", nil, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []NotificationSubscription + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the ListSubscriptions function +type ListSubscriptionsArgs struct { + // (optional) User or Group ID + TargetId *uuid.UUID + // (optional) List of subscription IDs + Ids *[]string + // (optional) + QueryFlags *SubscriptionQueryFlags +} + +// [Preview API] Query for subscriptions. A subscription is returned if it matches one or more of the specified conditions. +func (client *ClientImpl) QuerySubscriptions(ctx context.Context, args QuerySubscriptionsArgs) (*[]NotificationSubscription, error) { + if args.SubscriptionQuery == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.SubscriptionQuery"} + } + body, marshalErr := json.Marshal(*args.SubscriptionQuery) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("6864db85-08c0-4006-8e8e-cc1bebe31675") + resp, err := client.Client.Send(ctx, http.MethodPost, locationId, "7.1-preview.1", nil, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []NotificationSubscription + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the QuerySubscriptions function +type QuerySubscriptionsArgs struct { + // (required) + SubscriptionQuery *SubscriptionQuery +} + +// [Preview API] +func (client *ClientImpl) UpdateSettings(ctx context.Context, args UpdateSettingsArgs) (*NotificationAdminSettings, error) { + if args.UpdateParameters == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.UpdateParameters"} + } + body, marshalErr := json.Marshal(*args.UpdateParameters) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("cbe076d8-2803-45ff-8d8d-44653686ea2a") + resp, err := client.Client.Send(ctx, http.MethodPatch, locationId, "7.1-preview.1", nil, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue NotificationAdminSettings + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the UpdateSettings function +type UpdateSettingsArgs struct { + // (required) + UpdateParameters *NotificationAdminSettingsUpdateParameters +} + +// [Preview API] Update delivery preferences of a notifications subscriber. +func (client *ClientImpl) UpdateSubscriber(ctx context.Context, args UpdateSubscriberArgs) (*NotificationSubscriber, error) { + if args.UpdateParameters == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.UpdateParameters"} + } + routeValues := make(map[string]string) + if args.SubscriberId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.SubscriberId"} + } + routeValues["subscriberId"] = (*args.SubscriberId).String() + + body, marshalErr := json.Marshal(*args.UpdateParameters) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("4d5caff1-25ba-430b-b808-7a1f352cc197") + resp, err := client.Client.Send(ctx, http.MethodPatch, locationId, "7.1-preview.1", routeValues, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue NotificationSubscriber + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the UpdateSubscriber function +type UpdateSubscriberArgs struct { + // (required) + UpdateParameters *NotificationSubscriberUpdateParameters + // (required) ID of the user or group. + SubscriberId *uuid.UUID +} + +// [Preview API] Update an existing subscription. Depending on the type of subscription and permissions, the caller can update the description, filter settings, channel (delivery) settings and more. +func (client *ClientImpl) UpdateSubscription(ctx context.Context, args UpdateSubscriptionArgs) (*NotificationSubscription, error) { + if args.UpdateParameters == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.UpdateParameters"} + } + routeValues := make(map[string]string) + if args.SubscriptionId == nil || *args.SubscriptionId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.SubscriptionId"} + } + routeValues["subscriptionId"] = *args.SubscriptionId + + body, marshalErr := json.Marshal(*args.UpdateParameters) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("70f911d6-abac-488c-85b3-a206bf57e165") + resp, err := client.Client.Send(ctx, http.MethodPatch, locationId, "7.1-preview.1", routeValues, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue NotificationSubscription + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the UpdateSubscription function +type UpdateSubscriptionArgs struct { + // (required) + UpdateParameters *NotificationSubscriptionUpdateParameters + // (required) + SubscriptionId *string +} + +// [Preview API] Update the diagnostics settings for a subscription. +func (client *ClientImpl) UpdateSubscriptionDiagnostics(ctx context.Context, args UpdateSubscriptionDiagnosticsArgs) (*SubscriptionDiagnostics, error) { + if args.UpdateParameters == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.UpdateParameters"} + } + routeValues := make(map[string]string) + if args.SubscriptionId == nil || *args.SubscriptionId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.SubscriptionId"} + } + routeValues["subscriptionId"] = *args.SubscriptionId + + body, marshalErr := json.Marshal(*args.UpdateParameters) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("20f1929d-4be7-4c2e-a74e-d47640ff3418") + resp, err := client.Client.Send(ctx, http.MethodPut, locationId, "7.1-preview.1", routeValues, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue SubscriptionDiagnostics + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the UpdateSubscriptionDiagnostics function +type UpdateSubscriptionDiagnosticsArgs struct { + // (required) + UpdateParameters *UpdateSubscripitonDiagnosticsParameters + // (required) The id of the notifications subscription. + SubscriptionId *string +} + +// [Preview API] Update the specified user's settings for the specified subscription. This API is typically used to opt in or out of a shared subscription. User settings can only be applied to shared subscriptions, like team subscriptions or default subscriptions. +func (client *ClientImpl) UpdateSubscriptionUserSettings(ctx context.Context, args UpdateSubscriptionUserSettingsArgs) (*SubscriptionUserSettings, error) { + if args.UserSettings == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.UserSettings"} + } + routeValues := make(map[string]string) + if args.SubscriptionId == nil || *args.SubscriptionId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.SubscriptionId"} + } + routeValues["subscriptionId"] = *args.SubscriptionId + if args.UserId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.UserId"} + } + routeValues["userId"] = (*args.UserId).String() + + body, marshalErr := json.Marshal(*args.UserSettings) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("ed5a3dff-aeb5-41b1-b4f7-89e66e58b62e") + resp, err := client.Client.Send(ctx, http.MethodPut, locationId, "7.1-preview.1", routeValues, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue SubscriptionUserSettings + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the UpdateSubscriptionUserSettings function +type UpdateSubscriptionUserSettingsArgs struct { + // (required) + UserSettings *SubscriptionUserSettings + // (required) + SubscriptionId *string + // (required) ID of the user + UserId *uuid.UUID +} diff --git a/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/notification/models.go b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/notification/models.go new file mode 100644 index 000000000..788032382 --- /dev/null +++ b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/notification/models.go @@ -0,0 +1,1353 @@ +// -------------------------------------------------------------------------------------------- +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// -------------------------------------------------------------------------------------------- +// Generated file, DO NOT EDIT +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// -------------------------------------------------------------------------------------------- + +package notification + +import ( + "github.com/google/uuid" + "github.com/microsoft/azure-devops-go-api/azuredevops/v7" + "github.com/microsoft/azure-devops-go-api/azuredevops/v7/forminput" + "github.com/microsoft/azure-devops-go-api/azuredevops/v7/webapi" +) + +type ActorFilter struct { + EventType *string `json:"eventType,omitempty"` + Criteria *ExpressionFilterModel `json:"criteria,omitempty"` + Type *string `json:"type,omitempty"` + Exclusions *[]string `json:"exclusions,omitempty"` + Inclusions *[]string `json:"inclusions,omitempty"` +} + +type ActorNotificationReason struct { + NotificationReasonType *NotificationReasonType `json:"notificationReasonType,omitempty"` + TargetIdentities *[]webapi.IdentityRef `json:"targetIdentities,omitempty"` + MatchedRoles *[]string `json:"matchedRoles,omitempty"` +} + +// Artifact filter options. Used in "follow" subscriptions. +type ArtifactFilter struct { + EventType *string `json:"eventType,omitempty"` + ArtifactId *string `json:"artifactId,omitempty"` + ArtifactType *string `json:"artifactType,omitempty"` + ArtifactUri *string `json:"artifactUri,omitempty"` + Type *string `json:"type,omitempty"` +} + +type BaseSubscriptionFilter struct { + EventType *string `json:"eventType,omitempty"` + Type *string `json:"type,omitempty"` +} + +type BatchNotificationOperation struct { + NotificationOperation *NotificationOperation `json:"notificationOperation,omitempty"` + NotificationQueryConditions *[]NotificationQueryCondition `json:"notificationQueryConditions,omitempty"` +} + +type BlockFilter struct { + EventType *string `json:"eventType,omitempty"` + Criteria *ExpressionFilterModel `json:"criteria,omitempty"` + Type *string `json:"type,omitempty"` + Exclusions *[]string `json:"exclusions,omitempty"` + Inclusions *[]string `json:"inclusions,omitempty"` +} + +type BlockSubscriptionChannel struct { + Type *string `json:"type,omitempty"` +} + +// Default delivery preference for group subscribers. Indicates how the subscriber should be notified. +type DefaultGroupDeliveryPreference string + +type defaultGroupDeliveryPreferenceValuesType struct { + NoDelivery DefaultGroupDeliveryPreference + EachMember DefaultGroupDeliveryPreference +} + +var DefaultGroupDeliveryPreferenceValues = defaultGroupDeliveryPreferenceValuesType{ + NoDelivery: "noDelivery", + EachMember: "eachMember", +} + +type DiagnosticIdentity struct { + DisplayName *string `json:"displayName,omitempty"` + EmailAddress *string `json:"emailAddress,omitempty"` + Id *uuid.UUID `json:"id,omitempty"` +} + +type DiagnosticNotification struct { + EventId *int `json:"eventId,omitempty"` + EventType *string `json:"eventType,omitempty"` + Id *int `json:"id,omitempty"` + Messages *[]NotificationDiagnosticLogMessage `json:"messages,omitempty"` + Recipients *map[uuid.UUID]DiagnosticRecipient `json:"recipients,omitempty"` + Result *string `json:"result,omitempty"` + Stats *map[string]int `json:"stats,omitempty"` + SubscriptionId *string `json:"subscriptionId,omitempty"` +} + +type DiagnosticRecipient struct { + Recipient *DiagnosticIdentity `json:"recipient,omitempty"` + Status *string `json:"status,omitempty"` +} + +type EmailHtmlSubscriptionChannel struct { + Address *string `json:"address,omitempty"` + UseCustomAddress *bool `json:"useCustomAddress,omitempty"` + Type *string `json:"type,omitempty"` +} + +type EmailPlaintextSubscriptionChannel struct { + Address *string `json:"address,omitempty"` + UseCustomAddress *bool `json:"useCustomAddress,omitempty"` + Type *string `json:"type,omitempty"` +} + +// Describes the subscription evaluation operation status. +type EvaluationOperationStatus string + +type evaluationOperationStatusValuesType struct { + NotSet EvaluationOperationStatus + Queued EvaluationOperationStatus + InProgress EvaluationOperationStatus + Cancelled EvaluationOperationStatus + Succeeded EvaluationOperationStatus + Failed EvaluationOperationStatus + TimedOut EvaluationOperationStatus + NotFound EvaluationOperationStatus +} + +var EvaluationOperationStatusValues = evaluationOperationStatusValuesType{ + // The operation object does not have the status set. + NotSet: "notSet", + // The operation has been queued. + Queued: "queued", + // The operation is in progress. + InProgress: "inProgress", + // The operation was cancelled by the user. + Cancelled: "cancelled", + // The operation completed successfully. + Succeeded: "succeeded", + // The operation completed with a failure. + Failed: "failed", + // The operation timed out. + TimedOut: "timedOut", + // The operation could not be found. + NotFound: "notFound", +} + +type EventBacklogStatus struct { + CaptureTime *azuredevops.Time `json:"captureTime,omitempty"` + JobId *uuid.UUID `json:"jobId,omitempty"` + LastEventBatchStartTime *azuredevops.Time `json:"lastEventBatchStartTime,omitempty"` + LastEventProcessedTime *azuredevops.Time `json:"lastEventProcessedTime,omitempty"` + LastJobBatchStartTime *azuredevops.Time `json:"lastJobBatchStartTime,omitempty"` + LastJobProcessedTime *azuredevops.Time `json:"lastJobProcessedTime,omitempty"` + OldestPendingEventTime *azuredevops.Time `json:"oldestPendingEventTime,omitempty"` + Publisher *string `json:"publisher,omitempty"` + UnprocessedEvents *int `json:"unprocessedEvents,omitempty"` +} + +type EventBatch struct { + EndTime interface{} `json:"endTime,omitempty"` + EventCounts *map[string]int `json:"eventCounts,omitempty"` + EventIds *string `json:"eventIds,omitempty"` + NotificationCounts *map[string]int `json:"notificationCounts,omitempty"` + PreProcessEndTime interface{} `json:"preProcessEndTime,omitempty"` + PreProcessStartTime interface{} `json:"preProcessStartTime,omitempty"` + ProcessEndTime interface{} `json:"processEndTime,omitempty"` + ProcessStartTime interface{} `json:"processStartTime,omitempty"` + StartTime interface{} `json:"startTime,omitempty"` + SubscriptionCounts *map[string]int `json:"subscriptionCounts,omitempty"` +} + +type EventProcessingLog struct { + // Identifier used for correlating to other diagnostics that may have been recorded elsewhere. + ActivityId *uuid.UUID `json:"activityId,omitempty"` + Description *string `json:"description,omitempty"` + EndTime *azuredevops.Time `json:"endTime,omitempty"` + Errors *int `json:"errors,omitempty"` + // Unique instance identifier. + Id *uuid.UUID `json:"id,omitempty"` + LogType *string `json:"logType,omitempty"` + Messages *[]NotificationDiagnosticLogMessage `json:"messages,omitempty"` + Properties *map[string]string `json:"properties,omitempty"` + // This identifier depends on the logType. For notification jobs, this will be the job Id. For subscription tracing, this will be a special root Guid with the subscription Id encoded. + Source *uuid.UUID `json:"source,omitempty"` + StartTime *azuredevops.Time `json:"startTime,omitempty"` + Warnings *int `json:"warnings,omitempty"` + Result *string `json:"result,omitempty"` + Stats *map[string]map[string]int `json:"stats,omitempty"` + Batches *[]EventBatch `json:"batches,omitempty"` + MatcherResults *[]MatcherResult `json:"matcherResults,omitempty"` +} + +// [Flags] Set of flags used to determine which set of information is retrieved when querying for event publishers +type EventPublisherQueryFlags string + +type eventPublisherQueryFlagsValuesType struct { + None EventPublisherQueryFlags + IncludeRemoteServices EventPublisherQueryFlags +} + +var EventPublisherQueryFlagsValues = eventPublisherQueryFlagsValuesType{ + None: "none", + // Include event types from the remote services too + IncludeRemoteServices: "includeRemoteServices", +} + +// Encapsulates events result properties. It defines the total number of events used and the number of matched events. +type EventsEvaluationResult struct { + // Count of events evaluated. + Count *int `json:"count,omitempty"` + // Count of matched events. + MatchedCount *int `json:"matchedCount,omitempty"` +} + +// A transform request specify the properties of a notification event to be transformed. +type EventTransformRequest struct { + // Event payload. + EventPayload *string `json:"eventPayload,omitempty"` + // Event type. + EventType *string `json:"eventType,omitempty"` + // System inputs. + SystemInputs *map[string]string `json:"systemInputs,omitempty"` +} + +// Result of transforming a notification event. +type EventTransformResult struct { + // Transformed html content. + Content *string `json:"content,omitempty"` + // Calculated data. + Data interface{} `json:"data,omitempty"` + // Calculated system inputs. + SystemInputs *map[string]string `json:"systemInputs,omitempty"` +} + +// [Flags] Set of flags used to determine which set of information is retrieved when querying for eventtypes +type EventTypeQueryFlags string + +type eventTypeQueryFlagsValuesType struct { + None EventTypeQueryFlags + IncludeFields EventTypeQueryFlags +} + +var EventTypeQueryFlagsValues = eventTypeQueryFlagsValuesType{ + None: "none", + // IncludeFields will include all fields and their types + IncludeFields: "includeFields", +} + +type ExpressionFilter struct { + EventType *string `json:"eventType,omitempty"` + Criteria *ExpressionFilterModel `json:"criteria,omitempty"` + Type *string `json:"type,omitempty"` +} + +// Subscription Filter Clause represents a single clause in a subscription filter e.g. If the subscription has the following criteria "Project Name = [Current Project] AND Assigned To = [Me] it will be represented as two Filter Clauses Clause 1: Index = 1, Logical Operator: NULL , FieldName = 'Project Name', Operator = '=', Value = '[Current Project]' Clause 2: Index = 2, Logical Operator: 'AND' , FieldName = 'Assigned To' , Operator = '=', Value = '[Me]' +type ExpressionFilterClause struct { + FieldName *string `json:"fieldName,omitempty"` + // The order in which this clause appeared in the filter query + Index *int `json:"index,omitempty"` + // Logical Operator 'AND', 'OR' or NULL (only for the first clause in the filter) + LogicalOperator *string `json:"logicalOperator,omitempty"` + Operator *string `json:"operator,omitempty"` + Value *string `json:"value,omitempty"` +} + +// Represents a hierarchy of SubscritionFilterClauses that have been grouped together through either adding a group in the WebUI or using parethesis in the Subscription condition string +type ExpressionFilterGroup struct { + // The index of the last FilterClause in this group + End *int `json:"end,omitempty"` + // Level of the group, since groups can be nested for each nested group the level will increase by 1 + Level *int `json:"level,omitempty"` + // The index of the first FilterClause in this group + Start *int `json:"start,omitempty"` +} + +type ExpressionFilterModel struct { + // Flat list of clauses in this subscription + Clauses *[]ExpressionFilterClause `json:"clauses,omitempty"` + // Grouping of clauses in the subscription + Groups *[]ExpressionFilterGroup `json:"groups,omitempty"` + // Max depth of the Subscription tree + MaxGroupLevel *int `json:"maxGroupLevel,omitempty"` +} + +type FieldInputValues struct { + // The default value to use for this input + DefaultValue *string `json:"defaultValue,omitempty"` + // Errors encountered while computing dynamic values. + Error *forminput.InputValuesError `json:"error,omitempty"` + // The id of the input + InputId *string `json:"inputId,omitempty"` + // Should this input be disabled + IsDisabled *bool `json:"isDisabled,omitempty"` + // Should the value be restricted to one of the values in the PossibleValues (True) or are the values in PossibleValues just a suggestion (False) + IsLimitedToPossibleValues *bool `json:"isLimitedToPossibleValues,omitempty"` + // Should this input be made read-only + IsReadOnly *bool `json:"isReadOnly,omitempty"` + // Possible values that this input can take + PossibleValues *[]forminput.InputValue `json:"possibleValues,omitempty"` + Operators *[]byte `json:"operators,omitempty"` +} + +type FieldValuesQuery struct { + CurrentValues *map[string]string `json:"currentValues,omitempty"` + // Subscription containing information about the publisher/consumer and the current input values + Resource interface{} `json:"resource,omitempty"` + InputValues *[]FieldInputValues `json:"inputValues,omitempty"` + Scope *string `json:"scope,omitempty"` +} + +type GeneratedNotification struct { + Recipients *[]DiagnosticIdentity `json:"recipients,omitempty"` +} + +type GroupSubscriptionChannel struct { + Address *string `json:"address,omitempty"` + UseCustomAddress *bool `json:"useCustomAddress,omitempty"` + Type *string `json:"type,omitempty"` +} + +// Abstraction interface for the diagnostic log. Primarily for deserialization. +type INotificationDiagnosticLog struct { + // Identifier used for correlating to other diagnostics that may have been recorded elsewhere. + ActivityId *uuid.UUID `json:"activityId,omitempty"` + // Description of what subscription or notification job is being logged. + Description *string `json:"description,omitempty"` + // Time the log ended. + EndTime *azuredevops.Time `json:"endTime,omitempty"` + // Unique instance identifier. + Id *uuid.UUID `json:"id,omitempty"` + // Type of information being logged. + LogType *string `json:"logType,omitempty"` + // List of log messages. + Messages *[]NotificationDiagnosticLogMessage `json:"messages,omitempty"` + // Dictionary of log properties and settings for the job. + Properties *map[string]string `json:"properties,omitempty"` + // This identifier depends on the logType. For notification jobs, this will be the job Id. For subscription tracing, this will be a special root Guid with the subscription Id encoded. + Source *uuid.UUID `json:"source,omitempty"` + // Time the log started. + StartTime *azuredevops.Time `json:"startTime,omitempty"` +} + +type ISubscriptionFilter struct { + EventType *string `json:"eventType,omitempty"` + Type *string `json:"type,omitempty"` +} + +type ISubscriptionChannel struct { + Type *string `json:"type,omitempty"` +} + +type MatcherResult struct { + Matcher *string `json:"matcher,omitempty"` + Stats *map[string]map[string]int `json:"stats,omitempty"` +} + +type MessageQueueSubscriptionChannel struct { + Type *string `json:"type,omitempty"` +} + +type NotificationAdminSettings struct { + // The default group delivery preference for groups in this collection + DefaultGroupDeliveryPreference *DefaultGroupDeliveryPreference `json:"defaultGroupDeliveryPreference,omitempty"` +} + +type NotificationAdminSettingsUpdateParameters struct { + DefaultGroupDeliveryPreference *DefaultGroupDeliveryPreference `json:"defaultGroupDeliveryPreference,omitempty"` +} + +type NotificationBacklogStatus struct { + CaptureTime *azuredevops.Time `json:"captureTime,omitempty"` + Channel *string `json:"channel,omitempty"` + JobId *uuid.UUID `json:"jobId,omitempty"` + LastJobBatchStartTime *azuredevops.Time `json:"lastJobBatchStartTime,omitempty"` + LastJobProcessedTime *azuredevops.Time `json:"lastJobProcessedTime,omitempty"` + LastNotificationBatchStartTime *azuredevops.Time `json:"lastNotificationBatchStartTime,omitempty"` + LastNotificationProcessedTime *azuredevops.Time `json:"lastNotificationProcessedTime,omitempty"` + OldestPendingNotificationTime *azuredevops.Time `json:"oldestPendingNotificationTime,omitempty"` + Publisher *string `json:"publisher,omitempty"` + // Null status is unprocessed + Status *string `json:"status,omitempty"` + UnprocessedNotifications *int `json:"unprocessedNotifications,omitempty"` +} + +type NotificationBatch struct { + EndTime interface{} `json:"endTime,omitempty"` + NotificationCount *int `json:"notificationCount,omitempty"` + NotificationIds *string `json:"notificationIds,omitempty"` + ProblematicNotifications *[]DiagnosticNotification `json:"problematicNotifications,omitempty"` + StartTime interface{} `json:"startTime,omitempty"` +} + +type NotificationDeliveryLog struct { + // Identifier used for correlating to other diagnostics that may have been recorded elsewhere. + ActivityId *uuid.UUID `json:"activityId,omitempty"` + Description *string `json:"description,omitempty"` + EndTime *azuredevops.Time `json:"endTime,omitempty"` + Errors *int `json:"errors,omitempty"` + // Unique instance identifier. + Id *uuid.UUID `json:"id,omitempty"` + LogType *string `json:"logType,omitempty"` + Messages *[]NotificationDiagnosticLogMessage `json:"messages,omitempty"` + Properties *map[string]string `json:"properties,omitempty"` + // This identifier depends on the logType. For notification jobs, this will be the job Id. For subscription tracing, this will be a special root Guid with the subscription Id encoded. + Source *uuid.UUID `json:"source,omitempty"` + StartTime *azuredevops.Time `json:"startTime,omitempty"` + Warnings *int `json:"warnings,omitempty"` + Result *string `json:"result,omitempty"` + Stats *map[string]map[string]int `json:"stats,omitempty"` + Batches *[]NotificationBatch `json:"batches,omitempty"` +} + +// Abstract base class for all of the diagnostic logs. +type NotificationDiagnosticLog struct { + // Identifier used for correlating to other diagnostics that may have been recorded elsewhere. + ActivityId *uuid.UUID `json:"activityId,omitempty"` + Description *string `json:"description,omitempty"` + EndTime *azuredevops.Time `json:"endTime,omitempty"` + Errors *int `json:"errors,omitempty"` + // Unique instance identifier. + Id *uuid.UUID `json:"id,omitempty"` + LogType *string `json:"logType,omitempty"` + Messages *[]NotificationDiagnosticLogMessage `json:"messages,omitempty"` + Properties *map[string]string `json:"properties,omitempty"` + // This identifier depends on the logType. For notification jobs, this will be the job Id. For subscription tracing, this will be a special root Guid with the subscription Id encoded. + Source *uuid.UUID `json:"source,omitempty"` + StartTime *azuredevops.Time `json:"startTime,omitempty"` + Warnings *int `json:"warnings,omitempty"` +} + +type NotificationDiagnosticLogMessage struct { + // Corresponds to .Net TraceLevel enumeration + Level *int `json:"level,omitempty"` + Message *string `json:"message,omitempty"` + Time interface{} `json:"time,omitempty"` +} + +type NotificationEventBacklogStatus struct { + EventBacklogStatus *[]EventBacklogStatus `json:"eventBacklogStatus,omitempty"` + NotificationBacklogStatus *[]NotificationBacklogStatus `json:"notificationBacklogStatus,omitempty"` +} + +// Encapsulates the properties of a filterable field. A filterable field is a field in an event that can used to filter notifications for a certain event type. +type NotificationEventField struct { + // Gets or sets the type of this field. + FieldType *NotificationEventFieldType `json:"fieldType,omitempty"` + // Gets or sets the unique identifier of this field. + Id *string `json:"id,omitempty"` + // Gets or sets the name of this field. + Name *string `json:"name,omitempty"` + // Gets or sets the path to the field in the event object. This path can be either Json Path or XPath, depending on if the event will be serialized into Json or XML + Path *string `json:"path,omitempty"` + // Gets or sets the scopes that this field supports. If not specified then the event type scopes apply. + SupportedScopes *[]string `json:"supportedScopes,omitempty"` +} + +// Encapsulates the properties of a field type. It includes a unique id for the operator and a localized string for display name +type NotificationEventFieldOperator struct { + // Gets or sets the display name of an operator + DisplayName *string `json:"displayName,omitempty"` + // Gets or sets the id of an operator + Id *string `json:"id,omitempty"` +} + +// Encapsulates the properties of a field type. It describes the data type of a field, the operators it support and how to populate it in the UI +type NotificationEventFieldType struct { + // Gets or sets the unique identifier of this field type. + Id *string `json:"id,omitempty"` + OperatorConstraints *[]OperatorConstraint `json:"operatorConstraints,omitempty"` + // Gets or sets the list of operators that this type supports. + Operators *[]NotificationEventFieldOperator `json:"operators,omitempty"` + SubscriptionFieldType *SubscriptionFieldType `json:"subscriptionFieldType,omitempty"` + // Gets or sets the value definition of this field like the getValuesMethod and template to display in the UI + Value *ValueDefinition `json:"value,omitempty"` +} + +// Encapsulates the properties of a notification event publisher. +type NotificationEventPublisher struct { + Id *string `json:"id,omitempty"` + SubscriptionManagementInfo *SubscriptionManagement `json:"subscriptionManagementInfo,omitempty"` + Url *string `json:"url,omitempty"` +} + +// Encapsulates the properties of an event role. An event Role is used for role based subscription for example for a buildCompletedEvent, one role is request by field +type NotificationEventRole struct { + // Gets or sets an Id for that role, this id is used by the event. + Id *string `json:"id,omitempty"` + // Gets or sets the Name for that role, this name is used for UI display. + Name *string `json:"name,omitempty"` + // Gets or sets whether this role can be a group or just an individual user + SupportsGroups *bool `json:"supportsGroups,omitempty"` +} + +// Encapsulates the properties of an event type. It defines the fields, that can be used for filtering, for that event type. +type NotificationEventType struct { + Category *NotificationEventTypeCategory `json:"category,omitempty"` + // Gets or sets the color representing this event type. Example: rgb(128,245,211) or #fafafa + Color *string `json:"color,omitempty"` + CustomSubscriptionsAllowed *bool `json:"customSubscriptionsAllowed,omitempty"` + EventPublisher *NotificationEventPublisher `json:"eventPublisher,omitempty"` + Fields *map[string]NotificationEventField `json:"fields,omitempty"` + HasInitiator *bool `json:"hasInitiator,omitempty"` + // Gets or sets the icon representing this event type. Can be a URL or a CSS class. Example: css://some-css-class + Icon *string `json:"icon,omitempty"` + // Gets or sets the unique identifier of this event definition. + Id *string `json:"id,omitempty"` + // Gets or sets the name of this event definition. + Name *string `json:"name,omitempty"` + Roles *[]NotificationEventRole `json:"roles,omitempty"` + // Gets or sets the scopes that this event type supports + SupportedScopes *[]string `json:"supportedScopes,omitempty"` + // Gets or sets the rest end point to get this event type details (fields, fields types) + Url *string `json:"url,omitempty"` +} + +// Encapsulates the properties of a category. A category will be used by the UI to group event types +type NotificationEventTypeCategory struct { + // Gets or sets the unique identifier of this category. + Id *string `json:"id,omitempty"` + // Gets or sets the friendly name of this category. + Name *string `json:"name,omitempty"` +} + +type NotificationJobDiagnosticLog struct { + // Identifier used for correlating to other diagnostics that may have been recorded elsewhere. + ActivityId *uuid.UUID `json:"activityId,omitempty"` + Description *string `json:"description,omitempty"` + EndTime *azuredevops.Time `json:"endTime,omitempty"` + Errors *int `json:"errors,omitempty"` + // Unique instance identifier. + Id *uuid.UUID `json:"id,omitempty"` + LogType *string `json:"logType,omitempty"` + Messages *[]NotificationDiagnosticLogMessage `json:"messages,omitempty"` + Properties *map[string]string `json:"properties,omitempty"` + // This identifier depends on the logType. For notification jobs, this will be the job Id. For subscription tracing, this will be a special root Guid with the subscription Id encoded. + Source *uuid.UUID `json:"source,omitempty"` + StartTime *azuredevops.Time `json:"startTime,omitempty"` + Warnings *int `json:"warnings,omitempty"` + Result *string `json:"result,omitempty"` + Stats *map[string]map[string]int `json:"stats,omitempty"` +} + +type NotificationOperation string + +type notificationOperationValuesType struct { + None NotificationOperation + SuspendUnprocessed NotificationOperation +} + +var NotificationOperationValues = notificationOperationValuesType{ + None: "none", + SuspendUnprocessed: "suspendUnprocessed", +} + +type NotificationQueryCondition struct { + EventInitiator *uuid.UUID `json:"eventInitiator,omitempty"` + EventType *string `json:"eventType,omitempty"` + Subscriber *uuid.UUID `json:"subscriber,omitempty"` + SubscriptionId *string `json:"subscriptionId,omitempty"` +} + +type NotificationReason struct { + NotificationReasonType *NotificationReasonType `json:"notificationReasonType,omitempty"` + TargetIdentities *[]webapi.IdentityRef `json:"targetIdentities,omitempty"` +} + +type NotificationReasonType string + +type notificationReasonTypeValuesType struct { + Unknown NotificationReasonType + Follows NotificationReasonType + Personal NotificationReasonType + PersonalAlias NotificationReasonType + DirectMember NotificationReasonType + IndirectMember NotificationReasonType + GroupAlias NotificationReasonType + SubscriptionAlias NotificationReasonType + SingleRole NotificationReasonType + DirectMemberGroupRole NotificationReasonType + InDirectMemberGroupRole NotificationReasonType + AliasMemberGroupRole NotificationReasonType +} + +var NotificationReasonTypeValues = notificationReasonTypeValuesType{ + Unknown: "unknown", + Follows: "follows", + Personal: "personal", + PersonalAlias: "personalAlias", + DirectMember: "directMember", + IndirectMember: "indirectMember", + GroupAlias: "groupAlias", + SubscriptionAlias: "subscriptionAlias", + SingleRole: "singleRole", + DirectMemberGroupRole: "directMemberGroupRole", + InDirectMemberGroupRole: "inDirectMemberGroupRole", + AliasMemberGroupRole: "aliasMemberGroupRole", +} + +// Encapsulates notifications result properties. It defines the number of notifications and the recipients of notifications. +type NotificationsEvaluationResult struct { + // Count of generated notifications + Count *int `json:"count,omitempty"` +} + +type NotificationStatistic struct { + Date *azuredevops.Time `json:"date,omitempty"` + HitCount *int `json:"hitCount,omitempty"` + Path *string `json:"path,omitempty"` + Type *NotificationStatisticType `json:"type,omitempty"` + User *webapi.IdentityRef `json:"user,omitempty"` +} + +type NotificationStatisticsQuery struct { + Conditions *[]NotificationStatisticsQueryConditions `json:"conditions,omitempty"` +} + +type NotificationStatisticsQueryConditions struct { + EndDate *azuredevops.Time `json:"endDate,omitempty"` + HitCountMinimum *int `json:"hitCountMinimum,omitempty"` + Path *string `json:"path,omitempty"` + StartDate *azuredevops.Time `json:"startDate,omitempty"` + Type *NotificationStatisticType `json:"type,omitempty"` + User *webapi.IdentityRef `json:"user,omitempty"` +} + +type NotificationStatisticType string + +type notificationStatisticTypeValuesType struct { + NotificationBySubscription NotificationStatisticType + EventsByEventType NotificationStatisticType + NotificationByEventType NotificationStatisticType + EventsByEventTypePerUser NotificationStatisticType + NotificationByEventTypePerUser NotificationStatisticType + Events NotificationStatisticType + Notifications NotificationStatisticType + NotificationFailureBySubscription NotificationStatisticType + UnprocessedRangeStart NotificationStatisticType + UnprocessedEventsByPublisher NotificationStatisticType + UnprocessedEventDelayByPublisher NotificationStatisticType + UnprocessedNotificationsByChannelByPublisher NotificationStatisticType + UnprocessedNotificationDelayByChannelByPublisher NotificationStatisticType + DelayRangeStart NotificationStatisticType + TotalPipelineTime NotificationStatisticType + NotificationPipelineTime NotificationStatisticType + EventPipelineTime NotificationStatisticType + HourlyRangeStart NotificationStatisticType + HourlyNotificationBySubscription NotificationStatisticType + HourlyEventsByEventTypePerUser NotificationStatisticType + HourlyEvents NotificationStatisticType + HourlyNotifications NotificationStatisticType + HourlyUnprocessedEventsByPublisher NotificationStatisticType + HourlyUnprocessedEventDelayByPublisher NotificationStatisticType + HourlyUnprocessedNotificationsByChannelByPublisher NotificationStatisticType + HourlyUnprocessedNotificationDelayByChannelByPublisher NotificationStatisticType + HourlyTotalPipelineTime NotificationStatisticType + HourlyNotificationPipelineTime NotificationStatisticType + HourlyEventPipelineTime NotificationStatisticType +} + +var NotificationStatisticTypeValues = notificationStatisticTypeValuesType{ + NotificationBySubscription: "notificationBySubscription", + EventsByEventType: "eventsByEventType", + NotificationByEventType: "notificationByEventType", + EventsByEventTypePerUser: "eventsByEventTypePerUser", + NotificationByEventTypePerUser: "notificationByEventTypePerUser", + Events: "events", + Notifications: "notifications", + NotificationFailureBySubscription: "notificationFailureBySubscription", + UnprocessedRangeStart: "unprocessedRangeStart", + UnprocessedEventsByPublisher: "unprocessedEventsByPublisher", + UnprocessedEventDelayByPublisher: "unprocessedEventDelayByPublisher", + UnprocessedNotificationsByChannelByPublisher: "unprocessedNotificationsByChannelByPublisher", + UnprocessedNotificationDelayByChannelByPublisher: "unprocessedNotificationDelayByChannelByPublisher", + DelayRangeStart: "delayRangeStart", + TotalPipelineTime: "totalPipelineTime", + NotificationPipelineTime: "notificationPipelineTime", + EventPipelineTime: "eventPipelineTime", + HourlyRangeStart: "hourlyRangeStart", + HourlyNotificationBySubscription: "hourlyNotificationBySubscription", + HourlyEventsByEventTypePerUser: "hourlyEventsByEventTypePerUser", + HourlyEvents: "hourlyEvents", + HourlyNotifications: "hourlyNotifications", + HourlyUnprocessedEventsByPublisher: "hourlyUnprocessedEventsByPublisher", + HourlyUnprocessedEventDelayByPublisher: "hourlyUnprocessedEventDelayByPublisher", + HourlyUnprocessedNotificationsByChannelByPublisher: "hourlyUnprocessedNotificationsByChannelByPublisher", + HourlyUnprocessedNotificationDelayByChannelByPublisher: "hourlyUnprocessedNotificationDelayByChannelByPublisher", + HourlyTotalPipelineTime: "hourlyTotalPipelineTime", + HourlyNotificationPipelineTime: "hourlyNotificationPipelineTime", + HourlyEventPipelineTime: "hourlyEventPipelineTime", +} + +// A subscriber is a user or group that has the potential to receive notifications. +type NotificationSubscriber struct { + // Indicates how the subscriber should be notified by default. + DeliveryPreference *NotificationSubscriberDeliveryPreference `json:"deliveryPreference,omitempty"` + Flags *SubscriberFlags `json:"flags,omitempty"` + // Identifier of the subscriber. + Id *uuid.UUID `json:"id,omitempty"` + // Preferred email address of the subscriber. A null or empty value indicates no preferred email address has been set. + PreferredEmailAddress *string `json:"preferredEmailAddress,omitempty"` +} + +// Delivery preference for a subscriber. Indicates how the subscriber should be notified. +type NotificationSubscriberDeliveryPreference string + +type notificationSubscriberDeliveryPreferenceValuesType struct { + NoDelivery NotificationSubscriberDeliveryPreference + PreferredEmailAddress NotificationSubscriberDeliveryPreference + EachMember NotificationSubscriberDeliveryPreference + UseDefault NotificationSubscriberDeliveryPreference +} + +var NotificationSubscriberDeliveryPreferenceValues = notificationSubscriberDeliveryPreferenceValuesType{ + // Do not send notifications by default. Note: notifications can still be delivered to this subscriber, for example via a custom subscription. + NoDelivery: "noDelivery", + // Deliver notifications to the subscriber's preferred email address. + PreferredEmailAddress: "preferredEmailAddress", + // Deliver notifications to each member of the group representing the subscriber. Only applicable when the subscriber is a group. + EachMember: "eachMember", + // Use default + UseDefault: "useDefault", +} + +// Updates to a subscriber. Typically used to change (or set) a preferred email address or default delivery preference. +type NotificationSubscriberUpdateParameters struct { + // New delivery preference for the subscriber (indicates how the subscriber should be notified). + DeliveryPreference *NotificationSubscriberDeliveryPreference `json:"deliveryPreference,omitempty"` + // New preferred email address for the subscriber. Specify an empty string to clear the current address. + PreferredEmailAddress *string `json:"preferredEmailAddress,omitempty"` +} + +// A subscription defines criteria for matching events and how the subscription's subscriber should be notified about those events. +type NotificationSubscription struct { + // Links to related resources, APIs, and views for the subscription. + Links interface{} `json:"_links,omitempty"` + // Admin-managed settings for the subscription. Only applies when the subscriber is a group. + AdminSettings *SubscriptionAdminSettings `json:"adminSettings,omitempty"` + // Description of the subscription. Typically describes filter criteria which helps identity the subscription. + Description *string `json:"description,omitempty"` + // Diagnostics for this subscription. + Diagnostics *SubscriptionDiagnostics `json:"diagnostics,omitempty"` + // Any extra properties like detailed description for different contexts, user/group contexts + ExtendedProperties *map[string]string `json:"extendedProperties,omitempty"` + // Matching criteria for the subscription. ExpressionFilter + Filter *ISubscriptionFilter `json:"filter,omitempty"` + // Read-only indicators that further describe the subscription. + Flags *SubscriptionFlags `json:"flags,omitempty"` + // Channel for delivering notifications triggered by the subscription. + Channel *ISubscriptionChannel `json:"channel,omitempty"` + // Subscription identifier. + Id *string `json:"id,omitempty"` + // User that last modified (or created) the subscription. + LastModifiedBy *webapi.IdentityRef `json:"lastModifiedBy,omitempty"` + // Date when the subscription was last modified. If the subscription has not been updated since it was created, this value will indicate when the subscription was created. + ModifiedDate *azuredevops.Time `json:"modifiedDate,omitempty"` + // The permissions the user have for this subscriptions. + Permissions *SubscriptionPermissions `json:"permissions,omitempty"` + // The container in which events must be published from in order to be matched by the subscription. If empty, the scope is the current host (typically an account or project collection). For example, a subscription scoped to project A will not produce notifications for events published from project B. + Scope *SubscriptionScope `json:"scope,omitempty"` + // Status of the subscription. Typically indicates whether the subscription is enabled or not. + Status *SubscriptionStatus `json:"status,omitempty"` + // Message that provides more details about the status of the subscription. + StatusMessage *string `json:"statusMessage,omitempty"` + // User or group that will receive notifications for events matching the subscription's filter criteria. + Subscriber *webapi.IdentityRef `json:"subscriber,omitempty"` + // REST API URL of the subscription. + Url *string `json:"url,omitempty"` + // User-managed settings for the subscription. Only applies when the subscriber is a group. Typically used to indicate whether the calling user is opted in or out of a group subscription. + UserSettings *SubscriptionUserSettings `json:"userSettings,omitempty"` +} + +// Parameters for creating a new subscription. A subscription defines criteria for matching events and how the subscription's subscriber should be notified about those events. +type NotificationSubscriptionCreateParameters struct { + // Brief description for the new subscription. Typically describes filter criteria which helps identity the subscription. + Description *string `json:"description,omitempty"` + // Matching criteria for the new subscription. ExpressionFilter + Filter *ISubscriptionFilter `json:"filter,omitempty"` + // Channel for delivering notifications triggered by the new subscription. + Channel *ISubscriptionChannel `json:"channel,omitempty"` + // The container in which events must be published from in order to be matched by the new subscription. If not specified, defaults to the current host (typically an account or project collection). For example, a subscription scoped to project A will not produce notifications for events published from project B. + Scope *SubscriptionScope `json:"scope,omitempty"` + // User or group that will receive notifications for events matching the subscription's filter criteria. If not specified, defaults to the calling user. + Subscriber *webapi.IdentityRef `json:"subscriber,omitempty"` +} + +type NotificationSubscriptionTemplate struct { + Description *string `json:"description,omitempty"` + Filter *ISubscriptionFilter `json:"filter,omitempty"` + Id *string `json:"id,omitempty"` + NotificationEventInformation *NotificationEventType `json:"notificationEventInformation,omitempty"` + Type *SubscriptionTemplateType `json:"type,omitempty"` +} + +// Parameters for updating an existing subscription. A subscription defines criteria for matching events and how the subscription's subscriber should be notified about those events. Note: only the fields to be updated should be set. +type NotificationSubscriptionUpdateParameters struct { + // Admin-managed settings for the subscription. Only applies to subscriptions where the subscriber is a group. + AdminSettings *SubscriptionAdminSettings `json:"adminSettings,omitempty"` + // Updated description for the subscription. Typically describes filter criteria which helps identity the subscription. + Description *string `json:"description,omitempty"` + // Matching criteria for the subscription. ExpressionFilter + Filter *ISubscriptionFilter `json:"filter,omitempty"` + // Channel for delivering notifications triggered by the subscription. + Channel *ISubscriptionChannel `json:"channel,omitempty"` + // The container in which events must be published from in order to be matched by the new subscription. If not specified, defaults to the current host (typically the current account or project collection). For example, a subscription scoped to project A will not produce notifications for events published from project B. + Scope *SubscriptionScope `json:"scope,omitempty"` + // Updated status for the subscription. Typically used to enable or disable a subscription. + Status *SubscriptionStatus `json:"status,omitempty"` + // Optional message that provides more details about the updated status. + StatusMessage *string `json:"statusMessage,omitempty"` + // User-managed settings for the subscription. Only applies to subscriptions where the subscriber is a group. Typically used to opt-in or opt-out a user from a group subscription. + UserSettings *SubscriptionUserSettings `json:"userSettings,omitempty"` +} + +// Encapsulates the properties of an operator constraint. An operator constraint defines if some operator is available only for specific scope like a project scope. +type OperatorConstraint struct { + Operator *string `json:"operator,omitempty"` + // Gets or sets the list of scopes that this type supports. + SupportedScopes *[]string `json:"supportedScopes,omitempty"` +} + +type ProcessedEvent struct { + // All of the users that were associated with this event and their role. + Actors *[]webapi.EventActor `json:"actors,omitempty"` + AllowedChannels *string `json:"allowedChannels,omitempty"` + ArtifactUri *string `json:"artifactUri,omitempty"` + DeliveryIdentities *ProcessingIdentities `json:"deliveryIdentities,omitempty"` + // Evaluations for each user + Evaluations *map[uuid.UUID]SubscriptionEvaluation `json:"evaluations,omitempty"` + EventId *int `json:"eventId,omitempty"` + // Which members were excluded from evaluation (only applies to ActorMatcher subscriptions) + Exclusions *[]webapi.EventActor `json:"exclusions,omitempty"` + // Which members were included for evaluation (only applies to ActorMatcher subscriptions) + Inclusions *[]webapi.EventActor `json:"inclusions,omitempty"` + Notifications *[]GeneratedNotification `json:"notifications,omitempty"` +} + +type ProcessingDiagnosticIdentity struct { + DisplayName *string `json:"displayName,omitempty"` + EmailAddress *string `json:"emailAddress,omitempty"` + Id *uuid.UUID `json:"id,omitempty"` + DeliveryPreference *string `json:"deliveryPreference,omitempty"` + IsActive *bool `json:"isActive,omitempty"` + IsGroup *bool `json:"isGroup,omitempty"` + Message *string `json:"message,omitempty"` +} + +type ProcessingIdentities struct { + ExcludedIdentities *map[uuid.UUID]ProcessingDiagnosticIdentity `json:"excludedIdentities,omitempty"` + IncludedIdentities *map[uuid.UUID]ProcessingDiagnosticIdentity `json:"includedIdentities,omitempty"` + Messages *[]NotificationDiagnosticLogMessage `json:"messages,omitempty"` + MissingIdentities *[]uuid.UUID `json:"missingIdentities,omitempty"` + Properties *map[string]string `json:"properties,omitempty"` +} + +type RoleBasedFilter struct { + EventType *string `json:"eventType,omitempty"` + Criteria *ExpressionFilterModel `json:"criteria,omitempty"` + Type *string `json:"type,omitempty"` + Exclusions *[]string `json:"exclusions,omitempty"` + Inclusions *[]string `json:"inclusions,omitempty"` +} + +type ServiceBusSubscriptionChannel struct { + Type *string `json:"type,omitempty"` +} + +type ServiceHooksSubscriptionChannel struct { + Type *string `json:"type,omitempty"` +} + +type SoapSubscriptionChannel struct { + Address *string `json:"address,omitempty"` + UseCustomAddress *bool `json:"useCustomAddress,omitempty"` + Type *string `json:"type,omitempty"` +} + +// [Flags] +type SubscriberFlags string + +type subscriberFlagsValuesType struct { + None SubscriberFlags + DeliveryPreferencesEditable SubscriberFlags + SupportsPreferredEmailAddressDelivery SubscriberFlags + SupportsEachMemberDelivery SubscriberFlags + SupportsNoDelivery SubscriberFlags + IsUser SubscriberFlags + IsGroup SubscriberFlags + IsTeam SubscriberFlags +} + +var SubscriberFlagsValues = subscriberFlagsValuesType{ + None: "none", + // Subscriber's delivery preferences could be updated + DeliveryPreferencesEditable: "deliveryPreferencesEditable", + // Subscriber's delivery preferences supports email delivery + SupportsPreferredEmailAddressDelivery: "supportsPreferredEmailAddressDelivery", + // Subscriber's delivery preferences supports individual members delivery(group expansion) + SupportsEachMemberDelivery: "supportsEachMemberDelivery", + // Subscriber's delivery preferences supports no delivery + SupportsNoDelivery: "supportsNoDelivery", + // Subscriber is a user + IsUser: "isUser", + // Subscriber is a group + IsGroup: "isGroup", + // Subscriber is a team + IsTeam: "isTeam", +} + +// Admin-managed settings for a group subscription. +type SubscriptionAdminSettings struct { + // If true, members of the group subscribed to the associated subscription cannot opt (choose not to get notified) + BlockUserOptOut *bool `json:"blockUserOptOut,omitempty"` +} + +// Contains all the diagnostics settings for a subscription. +type SubscriptionDiagnostics struct { + // Diagnostics settings for retaining delivery results. Used for Service Hooks subscriptions. + DeliveryResults *SubscriptionTracing `json:"deliveryResults,omitempty"` + // Diagnostics settings for troubleshooting notification delivery. + DeliveryTracing *SubscriptionTracing `json:"deliveryTracing,omitempty"` + // Diagnostics settings for troubleshooting event matching. + EvaluationTracing *SubscriptionTracing `json:"evaluationTracing,omitempty"` +} + +type SubscriptionEvaluation struct { + Clauses *[]SubscriptionEvaluationClause `json:"clauses,omitempty"` + User *DiagnosticIdentity `json:"user,omitempty"` +} + +type SubscriptionEvaluationClause struct { + Clause *string `json:"clause,omitempty"` + Order *int `json:"order,omitempty"` + Result *bool `json:"result,omitempty"` +} + +// Encapsulates the properties of a SubscriptionEvaluationRequest. It defines the subscription to be evaluated and time interval for events used in evaluation. +type SubscriptionEvaluationRequest struct { + // The min created date for the events used for matching in UTC. Use all events created since this date + MinEventsCreatedDate *azuredevops.Time `json:"minEventsCreatedDate,omitempty"` + // User or group that will receive notifications for events matching the subscription's filter criteria. If not specified, defaults to the calling user. + SubscriptionCreateParameters *NotificationSubscriptionCreateParameters `json:"subscriptionCreateParameters,omitempty"` +} + +// Encapsulates the subscription evaluation results. It defines the Date Interval that was used, number of events evaluated and events and notifications results +type SubscriptionEvaluationResult struct { + // Subscription evaluation job status + EvaluationJobStatus *EvaluationOperationStatus `json:"evaluationJobStatus,omitempty"` + // Subscription evaluation events results. + Events *EventsEvaluationResult `json:"events,omitempty"` + // The requestId which is the subscription evaluation jobId + Id *uuid.UUID `json:"id,omitempty"` + // Subscription evaluation notification results. + Notifications *NotificationsEvaluationResult `json:"notifications,omitempty"` +} + +// Encapsulates the subscription evaluation settings needed for the UI +type SubscriptionEvaluationSettings struct { + // Indicates whether subscription evaluation before saving is enabled or not + Enabled *bool `json:"enabled,omitempty"` + // Time interval to check on subscription evaluation job in seconds + Interval *int `json:"interval,omitempty"` + // Threshold on the number of notifications for considering a subscription too noisy + Threshold *int `json:"threshold,omitempty"` + // Time out for the subscription evaluation check in seconds + TimeOut *int `json:"timeOut,omitempty"` +} + +type SubscriptionFieldType string + +type subscriptionFieldTypeValuesType struct { + String SubscriptionFieldType + Integer SubscriptionFieldType + DateTime SubscriptionFieldType + PlainText SubscriptionFieldType + Html SubscriptionFieldType + TreePath SubscriptionFieldType + History SubscriptionFieldType + Double SubscriptionFieldType + Guid SubscriptionFieldType + Boolean SubscriptionFieldType + Identity SubscriptionFieldType + PicklistInteger SubscriptionFieldType + PicklistString SubscriptionFieldType + PicklistDouble SubscriptionFieldType + TeamProject SubscriptionFieldType +} + +var SubscriptionFieldTypeValues = subscriptionFieldTypeValuesType{ + String: "string", + Integer: "integer", + DateTime: "dateTime", + PlainText: "plainText", + Html: "html", + TreePath: "treePath", + History: "history", + Double: "double", + Guid: "guid", + Boolean: "boolean", + Identity: "identity", + PicklistInteger: "picklistInteger", + PicklistString: "picklistString", + PicklistDouble: "picklistDouble", + TeamProject: "teamProject", +} + +// [Flags] Read-only indicators that further describe the subscription. +type SubscriptionFlags string + +type subscriptionFlagsValuesType struct { + None SubscriptionFlags + GroupSubscription SubscriptionFlags + ContributedSubscription SubscriptionFlags + CanOptOut SubscriptionFlags + TeamSubscription SubscriptionFlags + OneActorMatches SubscriptionFlags +} + +var SubscriptionFlagsValues = subscriptionFlagsValuesType{ + // None + None: "none", + // Subscription's subscriber is a group, not a user + GroupSubscription: "groupSubscription", + // Subscription is contributed and not persisted. This means certain fields of the subscription, like Filter, are read-only. + ContributedSubscription: "contributedSubscription", + // A user that is member of the subscription's subscriber group can opt in/out of the subscription. + CanOptOut: "canOptOut", + // If the subscriber is a group, is it a team. + TeamSubscription: "teamSubscription", + // For role based subscriptions, there is an expectation that there will always be at least one actor that matches + OneActorMatches: "oneActorMatches", +} + +type SubscriptionChannelWithAddress struct { + Address *string `json:"address,omitempty"` + Type *string `json:"type,omitempty"` + UseCustomAddress *bool `json:"useCustomAddress,omitempty"` +} + +// Encapsulates the properties needed to manage subscriptions, opt in and out of subscriptions. +type SubscriptionManagement struct { + ServiceInstanceType *uuid.UUID `json:"serviceInstanceType,omitempty"` + Url *string `json:"url,omitempty"` +} + +// [Flags] The permissions that a user has to a certain subscription +type SubscriptionPermissions string + +type subscriptionPermissionsValuesType struct { + None SubscriptionPermissions + View SubscriptionPermissions + Edit SubscriptionPermissions + Delete SubscriptionPermissions +} + +var SubscriptionPermissionsValues = subscriptionPermissionsValuesType{ + // None + None: "none", + // full view of description, filters, etc. Not limited. + View: "view", + // update subscription + Edit: "edit", + // delete subscription + Delete: "delete", +} + +// Notification subscriptions query input. +type SubscriptionQuery struct { + // One or more conditions to query on. If more than 2 conditions are specified, the combined results of each condition is returned (i.e. conditions are logically OR'ed). + Conditions *[]SubscriptionQueryCondition `json:"conditions,omitempty"` + // Flags the refine the types of subscriptions that will be returned from the query. + QueryFlags *SubscriptionQueryFlags `json:"queryFlags,omitempty"` +} + +// Conditions a subscription must match to qualify for the query result set. Not all fields are required. A subscription must match all conditions specified in order to qualify for the result set. +type SubscriptionQueryCondition struct { + // Filter conditions that matching subscriptions must have. Typically only the filter's type and event type are used for matching. + Filter *ISubscriptionFilter `json:"filter,omitempty"` + // Flags to specify the type subscriptions to query for. + Flags *SubscriptionFlags `json:"flags,omitempty"` + // Scope that matching subscriptions must have. + Scope *string `json:"scope,omitempty"` + // ID of the subscriber (user or group) that matching subscriptions must be subscribed to. + SubscriberId *uuid.UUID `json:"subscriberId,omitempty"` + // ID of the subscription to query for. + SubscriptionId *string `json:"subscriptionId,omitempty"` +} + +// [Flags] Flags that influence the result set of a subscription query. +type SubscriptionQueryFlags string + +type subscriptionQueryFlagsValuesType struct { + None SubscriptionQueryFlags + IncludeInvalidSubscriptions SubscriptionQueryFlags + IncludeDeletedSubscriptions SubscriptionQueryFlags + IncludeFilterDetails SubscriptionQueryFlags + AlwaysReturnBasicInformation SubscriptionQueryFlags + IncludeSystemSubscriptions SubscriptionQueryFlags +} + +var SubscriptionQueryFlagsValues = subscriptionQueryFlagsValuesType{ + None: "none", + // Include subscriptions with invalid subscribers. + IncludeInvalidSubscriptions: "includeInvalidSubscriptions", + // Include subscriptions marked for deletion. + IncludeDeletedSubscriptions: "includeDeletedSubscriptions", + // Include the full filter details with each subscription. + IncludeFilterDetails: "includeFilterDetails", + // For a subscription the caller does not have permission to view, return basic (non-confidential) information. + AlwaysReturnBasicInformation: "alwaysReturnBasicInformation", + // Include system subscriptions. + IncludeSystemSubscriptions: "includeSystemSubscriptions", +} + +// A resource, typically an account or project, in which events are published from. +type SubscriptionScope struct { + // Required: This is the identity of the scope for the type. + Id *uuid.UUID `json:"id,omitempty"` + // Optional: The display name of the scope + Name *string `json:"name,omitempty"` + // Required: The event specific type of a scope. + Type *string `json:"type,omitempty"` +} + +// Subscription status values. A value greater than or equal to zero indicates the subscription is enabled. A negative value indicates the subscription is disabled. +type SubscriptionStatus string + +type subscriptionStatusValuesType struct { + JailedByNotificationsVolume SubscriptionStatus + PendingDeletion SubscriptionStatus + DisabledArgumentException SubscriptionStatus + DisabledProjectInvalid SubscriptionStatus + DisabledMissingPermissions SubscriptionStatus + DisabledFromProbation SubscriptionStatus + DisabledInactiveIdentity SubscriptionStatus + DisabledMessageQueueNotSupported SubscriptionStatus + DisabledMissingIdentity SubscriptionStatus + DisabledInvalidRoleExpression SubscriptionStatus + DisabledInvalidPathClause SubscriptionStatus + DisabledAsDuplicateOfDefault SubscriptionStatus + DisabledByAdmin SubscriptionStatus + Disabled SubscriptionStatus + Enabled SubscriptionStatus + EnabledOnProbation SubscriptionStatus +} + +var SubscriptionStatusValues = subscriptionStatusValuesType{ + // Subscription is disabled because it generated a high volume of notifications. + JailedByNotificationsVolume: "jailedByNotificationsVolume", + // Subscription is disabled and will be deleted. + PendingDeletion: "pendingDeletion", + // Subscription is disabled because of an Argument Exception while processing the subscription + DisabledArgumentException: "disabledArgumentException", + // Subscription is disabled because the project is invalid + DisabledProjectInvalid: "disabledProjectInvalid", + // Subscription is disabled because the identity does not have the appropriate permissions + DisabledMissingPermissions: "disabledMissingPermissions", + // Subscription is disabled service due to failures. + DisabledFromProbation: "disabledFromProbation", + // Subscription is disabled because the identity is no longer active + DisabledInactiveIdentity: "disabledInactiveIdentity", + // Subscription is disabled because message queue is not supported. + DisabledMessageQueueNotSupported: "disabledMessageQueueNotSupported", + // Subscription is disabled because its subscriber is unknown. + DisabledMissingIdentity: "disabledMissingIdentity", + // Subscription is disabled because it has an invalid role expression. + DisabledInvalidRoleExpression: "disabledInvalidRoleExpression", + // Subscription is disabled because it has an invalid filter expression. + DisabledInvalidPathClause: "disabledInvalidPathClause", + // Subscription is disabled because it is a duplicate of a default subscription. + DisabledAsDuplicateOfDefault: "disabledAsDuplicateOfDefault", + // Subscription is disabled by an administrator, not the subscription's subscriber. + DisabledByAdmin: "disabledByAdmin", + // Subscription is disabled, typically by the owner of the subscription, and will not produce any notifications. + Disabled: "disabled", + // Subscription is active. + Enabled: "enabled", + // Subscription is active, but is on probation due to failed deliveries or other issues with the subscription. + EnabledOnProbation: "enabledOnProbation", +} + +// [Flags] Set of flags used to determine which set of templates is retrieved when querying for subscription templates +type SubscriptionTemplateQueryFlags string + +type subscriptionTemplateQueryFlagsValuesType struct { + None SubscriptionTemplateQueryFlags + IncludeUser SubscriptionTemplateQueryFlags + IncludeGroup SubscriptionTemplateQueryFlags + IncludeUserAndGroup SubscriptionTemplateQueryFlags + IncludeEventTypeInformation SubscriptionTemplateQueryFlags +} + +var SubscriptionTemplateQueryFlagsValues = subscriptionTemplateQueryFlagsValuesType{ + None: "none", + // Include user templates + IncludeUser: "includeUser", + // Include group templates + IncludeGroup: "includeGroup", + // Include user and group templates + IncludeUserAndGroup: "includeUserAndGroup", + // Include the event type details like the fields and operators + IncludeEventTypeInformation: "includeEventTypeInformation", +} + +type SubscriptionTemplateType string + +type subscriptionTemplateTypeValuesType struct { + User SubscriptionTemplateType + Team SubscriptionTemplateType + Both SubscriptionTemplateType + None SubscriptionTemplateType +} + +var SubscriptionTemplateTypeValues = subscriptionTemplateTypeValuesType{ + User: "user", + Team: "team", + Both: "both", + None: "none", +} + +type SubscriptionTraceDiagnosticLog struct { + // Identifier used for correlating to other diagnostics that may have been recorded elsewhere. + ActivityId *uuid.UUID `json:"activityId,omitempty"` + Description *string `json:"description,omitempty"` + EndTime *azuredevops.Time `json:"endTime,omitempty"` + Errors *int `json:"errors,omitempty"` + // Unique instance identifier. + Id *uuid.UUID `json:"id,omitempty"` + LogType *string `json:"logType,omitempty"` + Messages *[]NotificationDiagnosticLogMessage `json:"messages,omitempty"` + Properties *map[string]string `json:"properties,omitempty"` + // This identifier depends on the logType. For notification jobs, this will be the job Id. For subscription tracing, this will be a special root Guid with the subscription Id encoded. + Source *uuid.UUID `json:"source,omitempty"` + StartTime *azuredevops.Time `json:"startTime,omitempty"` + Warnings *int `json:"warnings,omitempty"` + // Indicates the job Id that processed or delivered this subscription + JobId *uuid.UUID `json:"jobId,omitempty"` + // Indicates unique instance identifier for the job that processed or delivered this subscription + JobInstanceId *uuid.UUID `json:"jobInstanceId,omitempty"` + SubscriptionId *string `json:"subscriptionId,omitempty"` +} + +type SubscriptionTraceEventProcessingLog struct { + // Identifier used for correlating to other diagnostics that may have been recorded elsewhere. + ActivityId *uuid.UUID `json:"activityId,omitempty"` + Description *string `json:"description,omitempty"` + EndTime *azuredevops.Time `json:"endTime,omitempty"` + Errors *int `json:"errors,omitempty"` + // Unique instance identifier. + Id *uuid.UUID `json:"id,omitempty"` + LogType *string `json:"logType,omitempty"` + Messages *[]NotificationDiagnosticLogMessage `json:"messages,omitempty"` + Properties *map[string]string `json:"properties,omitempty"` + // This identifier depends on the logType. For notification jobs, this will be the job Id. For subscription tracing, this will be a special root Guid with the subscription Id encoded. + Source *uuid.UUID `json:"source,omitempty"` + StartTime *azuredevops.Time `json:"startTime,omitempty"` + Warnings *int `json:"warnings,omitempty"` + // Indicates the job Id that processed or delivered this subscription + JobId *uuid.UUID `json:"jobId,omitempty"` + // Indicates unique instance identifier for the job that processed or delivered this subscription + JobInstanceId *uuid.UUID `json:"jobInstanceId,omitempty"` + SubscriptionId *string `json:"subscriptionId,omitempty"` + EvaluationIdentities *ProcessingIdentities `json:"evaluationIdentities,omitempty"` + Channel *string `json:"channel,omitempty"` + // Which members opted out from receiving notifications from this subscription + OptedOut *[]DiagnosticIdentity `json:"optedOut,omitempty"` + ProcessedEvents *map[int]ProcessedEvent `json:"processedEvents,omitempty"` +} + +type SubscriptionTraceNotificationDeliveryLog struct { + // Identifier used for correlating to other diagnostics that may have been recorded elsewhere. + ActivityId *uuid.UUID `json:"activityId,omitempty"` + Description *string `json:"description,omitempty"` + EndTime *azuredevops.Time `json:"endTime,omitempty"` + Errors *int `json:"errors,omitempty"` + // Unique instance identifier. + Id *uuid.UUID `json:"id,omitempty"` + LogType *string `json:"logType,omitempty"` + Messages *[]NotificationDiagnosticLogMessage `json:"messages,omitempty"` + Properties *map[string]string `json:"properties,omitempty"` + // This identifier depends on the logType. For notification jobs, this will be the job Id. For subscription tracing, this will be a special root Guid with the subscription Id encoded. + Source *uuid.UUID `json:"source,omitempty"` + StartTime *azuredevops.Time `json:"startTime,omitempty"` + Warnings *int `json:"warnings,omitempty"` + // Indicates the job Id that processed or delivered this subscription + JobId *uuid.UUID `json:"jobId,omitempty"` + // Indicates unique instance identifier for the job that processed or delivered this subscription + JobInstanceId *uuid.UUID `json:"jobInstanceId,omitempty"` + SubscriptionId *string `json:"subscriptionId,omitempty"` + Notifications *[]DiagnosticNotification `json:"notifications,omitempty"` +} + +// Data controlling a single diagnostic setting for a subscription. +type SubscriptionTracing struct { + // Indicates whether the diagnostic tracing is enabled or not. + Enabled *bool `json:"enabled,omitempty"` + // Trace until the specified end date. + EndDate *azuredevops.Time `json:"endDate,omitempty"` + // The maximum number of result details to trace. + MaxTracedEntries *int `json:"maxTracedEntries,omitempty"` + // The date and time tracing started. + StartDate *azuredevops.Time `json:"startDate,omitempty"` + // Trace until remaining count reaches 0. + TracedEntries *int `json:"tracedEntries,omitempty"` +} + +// User-managed settings for a group subscription. +type SubscriptionUserSettings struct { + // Indicates whether the user will receive notifications for the associated group subscription. + OptedOut *bool `json:"optedOut,omitempty"` +} + +type UnsupportedFilter struct { + EventType *string `json:"eventType,omitempty"` + Type *string `json:"type,omitempty"` +} + +type UnsupportedSubscriptionChannel struct { + Type *string `json:"type,omitempty"` +} + +// Parameters to update diagnostics settings for a subscription. +type UpdateSubscripitonDiagnosticsParameters struct { + // Diagnostics settings for retaining delivery results. Used for Service Hooks subscriptions. + DeliveryResults *UpdateSubscripitonTracingParameters `json:"deliveryResults,omitempty"` + // Diagnostics settings for troubleshooting notification delivery. + DeliveryTracing *UpdateSubscripitonTracingParameters `json:"deliveryTracing,omitempty"` + // Diagnostics settings for troubleshooting event matching. + EvaluationTracing *UpdateSubscripitonTracingParameters `json:"evaluationTracing,omitempty"` +} + +// Parameters to update a specific diagnostic setting. +type UpdateSubscripitonTracingParameters struct { + // Indicates whether to enable to disable the diagnostic tracing. + Enabled *bool `json:"enabled,omitempty"` +} + +type UserSubscriptionChannel struct { + Address *string `json:"address,omitempty"` + UseCustomAddress *bool `json:"useCustomAddress,omitempty"` + Type *string `json:"type,omitempty"` +} + +type UserSystemSubscriptionChannel struct { + Address *string `json:"address,omitempty"` + UseCustomAddress *bool `json:"useCustomAddress,omitempty"` + Type *string `json:"type,omitempty"` +} + +// Encapsulates the properties of a field value definition. It has the information needed to retrieve the list of possible values for a certain field and how to handle that field values in the UI. This information includes what type of object this value represents, which property to use for UI display and which property to use for saving the subscription +type ValueDefinition struct { + // Gets or sets the data source. + DataSource *[]forminput.InputValue `json:"dataSource,omitempty"` + // Gets or sets the rest end point. + EndPoint *string `json:"endPoint,omitempty"` + // Gets or sets the result template. + ResultTemplate *string `json:"resultTemplate,omitempty"` +} diff --git a/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/operations/client.go b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/operations/client.go new file mode 100644 index 000000000..05f687896 --- /dev/null +++ b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/operations/client.go @@ -0,0 +1,64 @@ +// -------------------------------------------------------------------------------------------- +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// -------------------------------------------------------------------------------------------- +// Generated file, DO NOT EDIT +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// -------------------------------------------------------------------------------------------- + +package operations + +import ( + "context" + "github.com/google/uuid" + "github.com/microsoft/azure-devops-go-api/azuredevops/v7" + "net/http" + "net/url" +) + +type Client interface { + // [Preview API] Gets an operation from the operationId using the given pluginId. + GetOperation(context.Context, GetOperationArgs) (*Operation, error) +} + +type ClientImpl struct { + Client azuredevops.Client +} + +func NewClient(ctx context.Context, connection *azuredevops.Connection) Client { + client := connection.GetClientByUrl(connection.BaseUrl) + return &ClientImpl{ + Client: *client, + } +} + +// [Preview API] Gets an operation from the operationId using the given pluginId. +func (client *ClientImpl) GetOperation(ctx context.Context, args GetOperationArgs) (*Operation, error) { + routeValues := make(map[string]string) + if args.OperationId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.OperationId"} + } + routeValues["operationId"] = (*args.OperationId).String() + + queryParams := url.Values{} + if args.PluginId != nil { + queryParams.Add("pluginId", (*args.PluginId).String()) + } + locationId, _ := uuid.Parse("9a1b74b4-2ca8-4a9f-8470-c2f2e6fdc949") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue Operation + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetOperation function +type GetOperationArgs struct { + // (required) The ID for the operation. + OperationId *uuid.UUID + // (optional) The ID for the plugin. + PluginId *uuid.UUID +} diff --git a/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/operations/models.go b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/operations/models.go new file mode 100644 index 000000000..49abd0b04 --- /dev/null +++ b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/operations/models.go @@ -0,0 +1,77 @@ +// -------------------------------------------------------------------------------------------- +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// -------------------------------------------------------------------------------------------- +// Generated file, DO NOT EDIT +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// -------------------------------------------------------------------------------------------- + +package operations + +import ( + "github.com/google/uuid" +) + +// Contains information about the progress or result of an async operation. +type Operation struct { + // Unique identifier for the operation. + Id *uuid.UUID `json:"id,omitempty"` + // Unique identifier for the plugin. + PluginId *uuid.UUID `json:"pluginId,omitempty"` + // The current status of the operation. + Status *OperationStatus `json:"status,omitempty"` + // URL to get the full operation object. + Url *string `json:"url,omitempty"` + // Links to other related objects. + Links interface{} `json:"_links,omitempty"` + // Detailed messaged about the status of an operation. + DetailedMessage *string `json:"detailedMessage,omitempty"` + // Result message for an operation. + ResultMessage *string `json:"resultMessage,omitempty"` + // URL to the operation result. + ResultUrl *OperationResultReference `json:"resultUrl,omitempty"` +} + +// Reference for an async operation. +type OperationReference struct { + // Unique identifier for the operation. + Id *uuid.UUID `json:"id,omitempty"` + // Unique identifier for the plugin. + PluginId *uuid.UUID `json:"pluginId,omitempty"` + // The current status of the operation. + Status *OperationStatus `json:"status,omitempty"` + // URL to get the full operation object. + Url *string `json:"url,omitempty"` +} + +type OperationResultReference struct { + // URL to the operation result. + ResultUrl *string `json:"resultUrl,omitempty"` +} + +// The status of an operation. +type OperationStatus string + +type operationStatusValuesType struct { + NotSet OperationStatus + Queued OperationStatus + InProgress OperationStatus + Cancelled OperationStatus + Succeeded OperationStatus + Failed OperationStatus +} + +var OperationStatusValues = operationStatusValuesType{ + // The operation does not have a status set. + NotSet: "notSet", + // The operation has been queued. + Queued: "queued", + // The operation is in progress. + InProgress: "inProgress", + // The operation was cancelled by the user. + Cancelled: "cancelled", + // The operation completed successfully. + Succeeded: "succeeded", + // The operation completed with a failure. + Failed: "failed", +} diff --git a/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/policy/client.go b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/policy/client.go new file mode 100644 index 000000000..33b492450 --- /dev/null +++ b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/policy/client.go @@ -0,0 +1,484 @@ +// -------------------------------------------------------------------------------------------- +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// -------------------------------------------------------------------------------------------- +// Generated file, DO NOT EDIT +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// -------------------------------------------------------------------------------------------- + +package policy + +import ( + "bytes" + "context" + "encoding/json" + "github.com/google/uuid" + "github.com/microsoft/azure-devops-go-api/azuredevops/v7" + "net/http" + "net/url" + "strconv" +) + +var ResourceAreaId, _ = uuid.Parse("fb13a388-40dd-4a04-b530-013a739c72ef") + +type Client interface { + // [Preview API] Create a policy configuration of a given policy type. + CreatePolicyConfiguration(context.Context, CreatePolicyConfigurationArgs) (*PolicyConfiguration, error) + // [Preview API] Delete a policy configuration by its ID. + DeletePolicyConfiguration(context.Context, DeletePolicyConfigurationArgs) error + // [Preview API] Get a policy configuration by its ID. + GetPolicyConfiguration(context.Context, GetPolicyConfigurationArgs) (*PolicyConfiguration, error) + // [Preview API] Retrieve a specific revision of a given policy by ID. + GetPolicyConfigurationRevision(context.Context, GetPolicyConfigurationRevisionArgs) (*PolicyConfiguration, error) + // [Preview API] Retrieve all revisions for a given policy. + GetPolicyConfigurationRevisions(context.Context, GetPolicyConfigurationRevisionsArgs) (*[]PolicyConfiguration, error) + // [Preview API] Get a list of policy configurations in a project. + GetPolicyConfigurations(context.Context, GetPolicyConfigurationsArgs) (*GetPolicyConfigurationsResponseValue, error) + // [Preview API] Gets the present evaluation state of a policy. + GetPolicyEvaluation(context.Context, GetPolicyEvaluationArgs) (*PolicyEvaluationRecord, error) + // [Preview API] Retrieves a list of all the policy evaluation statuses for a specific pull request. + GetPolicyEvaluations(context.Context, GetPolicyEvaluationsArgs) (*[]PolicyEvaluationRecord, error) + // [Preview API] Retrieve a specific policy type by ID. + GetPolicyType(context.Context, GetPolicyTypeArgs) (*PolicyType, error) + // [Preview API] Retrieve all available policy types. + GetPolicyTypes(context.Context, GetPolicyTypesArgs) (*[]PolicyType, error) + // [Preview API] Requeue the policy evaluation. + RequeuePolicyEvaluation(context.Context, RequeuePolicyEvaluationArgs) (*PolicyEvaluationRecord, error) + // [Preview API] Update a policy configuration by its ID. + UpdatePolicyConfiguration(context.Context, UpdatePolicyConfigurationArgs) (*PolicyConfiguration, error) +} + +type ClientImpl struct { + Client azuredevops.Client +} + +func NewClient(ctx context.Context, connection *azuredevops.Connection) (Client, error) { + client, err := connection.GetClientByResourceAreaId(ctx, ResourceAreaId) + if err != nil { + return nil, err + } + return &ClientImpl{ + Client: *client, + }, nil +} + +// [Preview API] Create a policy configuration of a given policy type. +func (client *ClientImpl) CreatePolicyConfiguration(ctx context.Context, args CreatePolicyConfigurationArgs) (*PolicyConfiguration, error) { + if args.Configuration == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.Configuration"} + } + routeValues := make(map[string]string) + if args.Project == nil || *args.Project == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.Project"} + } + routeValues["project"] = *args.Project + + body, marshalErr := json.Marshal(*args.Configuration) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("dad91cbe-d183-45f8-9c6e-9c1164472121") + resp, err := client.Client.Send(ctx, http.MethodPost, locationId, "7.1-preview.1", routeValues, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue PolicyConfiguration + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the CreatePolicyConfiguration function +type CreatePolicyConfigurationArgs struct { + // (required) The policy configuration to create. + Configuration *PolicyConfiguration + // (required) Project ID or project name + Project *string +} + +// [Preview API] Delete a policy configuration by its ID. +func (client *ClientImpl) DeletePolicyConfiguration(ctx context.Context, args DeletePolicyConfigurationArgs) error { + routeValues := make(map[string]string) + if args.Project == nil || *args.Project == "" { + return &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.Project"} + } + routeValues["project"] = *args.Project + if args.ConfigurationId == nil { + return &azuredevops.ArgumentNilError{ArgumentName: "args.ConfigurationId"} + } + routeValues["configurationId"] = strconv.Itoa(*args.ConfigurationId) + + locationId, _ := uuid.Parse("dad91cbe-d183-45f8-9c6e-9c1164472121") + _, err := client.Client.Send(ctx, http.MethodDelete, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return err + } + + return nil +} + +// Arguments for the DeletePolicyConfiguration function +type DeletePolicyConfigurationArgs struct { + // (required) Project ID or project name + Project *string + // (required) ID of the policy configuration to delete. + ConfigurationId *int +} + +// [Preview API] Get a policy configuration by its ID. +func (client *ClientImpl) GetPolicyConfiguration(ctx context.Context, args GetPolicyConfigurationArgs) (*PolicyConfiguration, error) { + routeValues := make(map[string]string) + if args.Project == nil || *args.Project == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.Project"} + } + routeValues["project"] = *args.Project + if args.ConfigurationId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.ConfigurationId"} + } + routeValues["configurationId"] = strconv.Itoa(*args.ConfigurationId) + + locationId, _ := uuid.Parse("dad91cbe-d183-45f8-9c6e-9c1164472121") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue PolicyConfiguration + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetPolicyConfiguration function +type GetPolicyConfigurationArgs struct { + // (required) Project ID or project name + Project *string + // (required) ID of the policy configuration + ConfigurationId *int +} + +// [Preview API] Retrieve a specific revision of a given policy by ID. +func (client *ClientImpl) GetPolicyConfigurationRevision(ctx context.Context, args GetPolicyConfigurationRevisionArgs) (*PolicyConfiguration, error) { + routeValues := make(map[string]string) + if args.Project == nil || *args.Project == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.Project"} + } + routeValues["project"] = *args.Project + if args.ConfigurationId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.ConfigurationId"} + } + routeValues["configurationId"] = strconv.Itoa(*args.ConfigurationId) + if args.RevisionId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.RevisionId"} + } + routeValues["revisionId"] = strconv.Itoa(*args.RevisionId) + + locationId, _ := uuid.Parse("fe1e68a2-60d3-43cb-855b-85e41ae97c95") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue PolicyConfiguration + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetPolicyConfigurationRevision function +type GetPolicyConfigurationRevisionArgs struct { + // (required) Project ID or project name + Project *string + // (required) The policy configuration ID. + ConfigurationId *int + // (required) The revision ID. + RevisionId *int +} + +// [Preview API] Retrieve all revisions for a given policy. +func (client *ClientImpl) GetPolicyConfigurationRevisions(ctx context.Context, args GetPolicyConfigurationRevisionsArgs) (*[]PolicyConfiguration, error) { + routeValues := make(map[string]string) + if args.Project == nil || *args.Project == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.Project"} + } + routeValues["project"] = *args.Project + if args.ConfigurationId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.ConfigurationId"} + } + routeValues["configurationId"] = strconv.Itoa(*args.ConfigurationId) + + queryParams := url.Values{} + if args.Top != nil { + queryParams.Add("$top", strconv.Itoa(*args.Top)) + } + if args.Skip != nil { + queryParams.Add("$skip", strconv.Itoa(*args.Skip)) + } + locationId, _ := uuid.Parse("fe1e68a2-60d3-43cb-855b-85e41ae97c95") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []PolicyConfiguration + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetPolicyConfigurationRevisions function +type GetPolicyConfigurationRevisionsArgs struct { + // (required) Project ID or project name + Project *string + // (required) The policy configuration ID. + ConfigurationId *int + // (optional) The number of revisions to retrieve. + Top *int + // (optional) The number of revisions to ignore. For example, to retrieve results 101-150, set top to 50 and skip to 100. + Skip *int +} + +// [Preview API] Get a list of policy configurations in a project. +func (client *ClientImpl) GetPolicyConfigurations(ctx context.Context, args GetPolicyConfigurationsArgs) (*GetPolicyConfigurationsResponseValue, error) { + routeValues := make(map[string]string) + if args.Project == nil || *args.Project == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.Project"} + } + routeValues["project"] = *args.Project + + queryParams := url.Values{} + if args.Scope != nil { + queryParams.Add("scope", *args.Scope) + } + if args.PolicyType != nil { + queryParams.Add("policyType", (*args.PolicyType).String()) + } + locationId, _ := uuid.Parse("dad91cbe-d183-45f8-9c6e-9c1164472121") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue GetPolicyConfigurationsResponseValue + responseValue.ContinuationToken = resp.Header.Get(azuredevops.HeaderKeyContinuationToken) + err = client.Client.UnmarshalCollectionBody(resp, &responseValue.Value) + return &responseValue, err +} + +// Arguments for the GetPolicyConfigurations function +type GetPolicyConfigurationsArgs struct { + // (required) Project ID or project name + Project *string + // (optional) [Provided for legacy reasons] The scope on which a subset of policies is defined. + Scope *string + // (optional) Filter returned policies to only this type + PolicyType *uuid.UUID +} + +// Return type for the GetPolicyConfigurations function +type GetPolicyConfigurationsResponseValue struct { + Value []PolicyConfiguration + ContinuationToken string +} + +// [Preview API] Gets the present evaluation state of a policy. +func (client *ClientImpl) GetPolicyEvaluation(ctx context.Context, args GetPolicyEvaluationArgs) (*PolicyEvaluationRecord, error) { + routeValues := make(map[string]string) + if args.Project == nil || *args.Project == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.Project"} + } + routeValues["project"] = *args.Project + if args.EvaluationId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.EvaluationId"} + } + routeValues["evaluationId"] = (*args.EvaluationId).String() + + locationId, _ := uuid.Parse("46aecb7a-5d2c-4647-897b-0209505a9fe4") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue PolicyEvaluationRecord + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetPolicyEvaluation function +type GetPolicyEvaluationArgs struct { + // (required) Project ID or project name + Project *string + // (required) ID of the policy evaluation to be retrieved. + EvaluationId *uuid.UUID +} + +// [Preview API] Retrieves a list of all the policy evaluation statuses for a specific pull request. +func (client *ClientImpl) GetPolicyEvaluations(ctx context.Context, args GetPolicyEvaluationsArgs) (*[]PolicyEvaluationRecord, error) { + routeValues := make(map[string]string) + if args.Project == nil || *args.Project == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.Project"} + } + routeValues["project"] = *args.Project + + queryParams := url.Values{} + if args.ArtifactId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "artifactId"} + } + queryParams.Add("artifactId", *args.ArtifactId) + if args.IncludeNotApplicable != nil { + queryParams.Add("includeNotApplicable", strconv.FormatBool(*args.IncludeNotApplicable)) + } + if args.Top != nil { + queryParams.Add("$top", strconv.Itoa(*args.Top)) + } + if args.Skip != nil { + queryParams.Add("$skip", strconv.Itoa(*args.Skip)) + } + locationId, _ := uuid.Parse("c23ddff5-229c-4d04-a80b-0fdce9f360c8") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []PolicyEvaluationRecord + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetPolicyEvaluations function +type GetPolicyEvaluationsArgs struct { + // (required) Project ID or project name + Project *string + // (required) A string which uniquely identifies the target of a policy evaluation. + ArtifactId *string + // (optional) Some policies might determine that they do not apply to a specific pull request. Setting this parameter to true will return evaluation records even for policies which don't apply to this pull request. + IncludeNotApplicable *bool + // (optional) The number of policy evaluation records to retrieve. + Top *int + // (optional) The number of policy evaluation records to ignore. For example, to retrieve results 101-150, set top to 50 and skip to 100. + Skip *int +} + +// [Preview API] Retrieve a specific policy type by ID. +func (client *ClientImpl) GetPolicyType(ctx context.Context, args GetPolicyTypeArgs) (*PolicyType, error) { + routeValues := make(map[string]string) + if args.Project == nil || *args.Project == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.Project"} + } + routeValues["project"] = *args.Project + if args.TypeId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.TypeId"} + } + routeValues["typeId"] = (*args.TypeId).String() + + locationId, _ := uuid.Parse("44096322-2d3d-466a-bb30-d1b7de69f61f") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue PolicyType + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetPolicyType function +type GetPolicyTypeArgs struct { + // (required) Project ID or project name + Project *string + // (required) The policy ID. + TypeId *uuid.UUID +} + +// [Preview API] Retrieve all available policy types. +func (client *ClientImpl) GetPolicyTypes(ctx context.Context, args GetPolicyTypesArgs) (*[]PolicyType, error) { + routeValues := make(map[string]string) + if args.Project == nil || *args.Project == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.Project"} + } + routeValues["project"] = *args.Project + + locationId, _ := uuid.Parse("44096322-2d3d-466a-bb30-d1b7de69f61f") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []PolicyType + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetPolicyTypes function +type GetPolicyTypesArgs struct { + // (required) Project ID or project name + Project *string +} + +// [Preview API] Requeue the policy evaluation. +func (client *ClientImpl) RequeuePolicyEvaluation(ctx context.Context, args RequeuePolicyEvaluationArgs) (*PolicyEvaluationRecord, error) { + routeValues := make(map[string]string) + if args.Project == nil || *args.Project == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.Project"} + } + routeValues["project"] = *args.Project + if args.EvaluationId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.EvaluationId"} + } + routeValues["evaluationId"] = (*args.EvaluationId).String() + + locationId, _ := uuid.Parse("46aecb7a-5d2c-4647-897b-0209505a9fe4") + resp, err := client.Client.Send(ctx, http.MethodPatch, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue PolicyEvaluationRecord + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the RequeuePolicyEvaluation function +type RequeuePolicyEvaluationArgs struct { + // (required) Project ID or project name + Project *string + // (required) ID of the policy evaluation to be retrieved. + EvaluationId *uuid.UUID +} + +// [Preview API] Update a policy configuration by its ID. +func (client *ClientImpl) UpdatePolicyConfiguration(ctx context.Context, args UpdatePolicyConfigurationArgs) (*PolicyConfiguration, error) { + if args.Configuration == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.Configuration"} + } + routeValues := make(map[string]string) + if args.Project == nil || *args.Project == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.Project"} + } + routeValues["project"] = *args.Project + if args.ConfigurationId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.ConfigurationId"} + } + routeValues["configurationId"] = strconv.Itoa(*args.ConfigurationId) + + body, marshalErr := json.Marshal(*args.Configuration) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("dad91cbe-d183-45f8-9c6e-9c1164472121") + resp, err := client.Client.Send(ctx, http.MethodPut, locationId, "7.1-preview.1", routeValues, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue PolicyConfiguration + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the UpdatePolicyConfiguration function +type UpdatePolicyConfigurationArgs struct { + // (required) The policy configuration to update. + Configuration *PolicyConfiguration + // (required) Project ID or project name + Project *string + // (required) ID of the existing policy configuration to be updated. + ConfigurationId *int +} diff --git a/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/policy/models.go b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/policy/models.go new file mode 100644 index 000000000..de7700ee6 --- /dev/null +++ b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/policy/models.go @@ -0,0 +1,136 @@ +// -------------------------------------------------------------------------------------------- +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// -------------------------------------------------------------------------------------------- +// Generated file, DO NOT EDIT +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// -------------------------------------------------------------------------------------------- + +package policy + +import ( + "github.com/google/uuid" + "github.com/microsoft/azure-devops-go-api/azuredevops/v7" + "github.com/microsoft/azure-devops-go-api/azuredevops/v7/webapi" +) + +// The full policy configuration with settings. +type PolicyConfiguration struct { + // The policy configuration ID. + Id *int `json:"id,omitempty"` + // The policy configuration type. + Type *PolicyTypeRef `json:"type,omitempty"` + // The URL where the policy configuration can be retrieved. + Url *string `json:"url,omitempty"` + // The policy configuration revision ID. + Revision *int `json:"revision,omitempty"` + // The links to other objects related to this object. + Links interface{} `json:"_links,omitempty"` + // A reference to the identity that created the policy. + CreatedBy *webapi.IdentityRef `json:"createdBy,omitempty"` + // The date and time when the policy was created. + CreatedDate *azuredevops.Time `json:"createdDate,omitempty"` + // Indicates whether the policy is blocking. + IsBlocking *bool `json:"isBlocking,omitempty"` + // Indicates whether the policy has been (soft) deleted. + IsDeleted *bool `json:"isDeleted,omitempty"` + // Indicates whether the policy is enabled. + IsEnabled *bool `json:"isEnabled,omitempty"` + // If set, this policy requires "Manage Enterprise Policies" permission to create, edit, or delete. + IsEnterpriseManaged *bool `json:"isEnterpriseManaged,omitempty"` + // The policy configuration settings. + Settings interface{} `json:"settings,omitempty"` +} + +// Policy configuration reference. +type PolicyConfigurationRef struct { + // The policy configuration ID. + Id *int `json:"id,omitempty"` + // The policy configuration type. + Type *PolicyTypeRef `json:"type,omitempty"` + // The URL where the policy configuration can be retrieved. + Url *string `json:"url,omitempty"` +} + +// This record encapsulates the current state of a policy as it applies to one specific pull request. Each pull request has a unique PolicyEvaluationRecord for each pull request which the policy applies to. +type PolicyEvaluationRecord struct { + // Links to other related objects + Links interface{} `json:"_links,omitempty"` + // A string which uniquely identifies the target of a policy evaluation. + ArtifactId *string `json:"artifactId,omitempty"` + // Time when this policy finished evaluating on this pull request. + CompletedDate *azuredevops.Time `json:"completedDate,omitempty"` + // Contains all configuration data for the policy which is being evaluated. + Configuration *PolicyConfiguration `json:"configuration,omitempty"` + // Internal context data of this policy evaluation. + Context interface{} `json:"context,omitempty"` + // Guid which uniquely identifies this evaluation record (one policy running on one pull request). + EvaluationId *uuid.UUID `json:"evaluationId,omitempty"` + // Time when this policy was first evaluated on this pull request. + StartedDate *azuredevops.Time `json:"startedDate,omitempty"` + // Status of the policy (Running, Approved, Failed, etc.) + Status *PolicyEvaluationStatus `json:"status,omitempty"` +} + +// Status of a policy which is running against a specific pull request. +type PolicyEvaluationStatus string + +type policyEvaluationStatusValuesType struct { + Queued PolicyEvaluationStatus + Running PolicyEvaluationStatus + Approved PolicyEvaluationStatus + Rejected PolicyEvaluationStatus + NotApplicable PolicyEvaluationStatus + Broken PolicyEvaluationStatus +} + +var PolicyEvaluationStatusValues = policyEvaluationStatusValuesType{ + // The policy is either queued to run, or is waiting for some event before progressing. + Queued: "queued", + // The policy is currently running. + Running: "running", + // The policy has been fulfilled for this pull request. + Approved: "approved", + // The policy has rejected this pull request. + Rejected: "rejected", + // The policy does not apply to this pull request. + NotApplicable: "notApplicable", + // The policy has encountered an unexpected error. + Broken: "broken", +} + +// User-friendly policy type with description (used for querying policy types). +type PolicyType struct { + // Display name of the policy type. + DisplayName *string `json:"displayName,omitempty"` + // The policy type ID. + Id *uuid.UUID `json:"id,omitempty"` + // The URL where the policy type can be retrieved. + Url *string `json:"url,omitempty"` + // The links to other objects related to this object. + Links interface{} `json:"_links,omitempty"` + // Detailed description of the policy type. + Description *string `json:"description,omitempty"` +} + +// Policy type reference. +type PolicyTypeRef struct { + // Display name of the policy type. + DisplayName *string `json:"displayName,omitempty"` + // The policy type ID. + Id *uuid.UUID `json:"id,omitempty"` + // The URL where the policy type can be retrieved. + Url *string `json:"url,omitempty"` +} + +// A particular revision for a policy configuration. +type VersionedPolicyConfigurationRef struct { + // The policy configuration ID. + Id *int `json:"id,omitempty"` + // The policy configuration type. + Type *PolicyTypeRef `json:"type,omitempty"` + // The URL where the policy configuration can be retrieved. + Url *string `json:"url,omitempty"` + // The policy configuration revision ID. + Revision *int `json:"revision,omitempty"` +} diff --git a/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/servicehooks/client.go b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/servicehooks/client.go new file mode 100644 index 000000000..bb6bb141a --- /dev/null +++ b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/servicehooks/client.go @@ -0,0 +1,720 @@ +// -------------------------------------------------------------------------------------------- +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// -------------------------------------------------------------------------------------------- +// Generated file, DO NOT EDIT +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// -------------------------------------------------------------------------------------------- + +package servicehooks + +import ( + "bytes" + "context" + "encoding/json" + "github.com/google/uuid" + "github.com/microsoft/azure-devops-go-api/azuredevops/v7" + "github.com/microsoft/azure-devops-go-api/azuredevops/v7/forminput" + "github.com/microsoft/azure-devops-go-api/azuredevops/v7/notification" + "net/http" + "net/url" + "strconv" +) + +type Client interface { + // [Preview API] Create a subscription. + CreateSubscription(context.Context, CreateSubscriptionArgs) (*Subscription, error) + // [Preview API] Query for service hook subscriptions. + CreateSubscriptionsQuery(context.Context, CreateSubscriptionsQueryArgs) (*SubscriptionsQuery, error) + // [Preview API] Sends a test notification. This is useful for verifying the configuration of an updated or new service hooks subscription. + CreateTestNotification(context.Context, CreateTestNotificationArgs) (*Notification, error) + // [Preview API] Delete a specific service hooks subscription. + DeleteSubscription(context.Context, DeleteSubscriptionArgs) error + // [Preview API] Get a specific consumer service. Optionally filter out consumer actions that do not support any event types for the specified publisher. + GetConsumer(context.Context, GetConsumerArgs) (*Consumer, error) + // [Preview API] Get details about a specific consumer action. + GetConsumerAction(context.Context, GetConsumerActionArgs) (*ConsumerAction, error) + // [Preview API] Get a specific event type. + GetEventType(context.Context, GetEventTypeArgs) (*EventTypeDescriptor, error) + // [Preview API] Get a specific notification for a subscription. + GetNotification(context.Context, GetNotificationArgs) (*Notification, error) + // [Preview API] Get a list of notifications for a specific subscription. A notification includes details about the event, the request to and the response from the consumer service. + GetNotifications(context.Context, GetNotificationsArgs) (*[]Notification, error) + // [Preview API] Get a specific service hooks publisher. + GetPublisher(context.Context, GetPublisherArgs) (*Publisher, error) + // [Preview API] Get a specific service hooks subscription. + GetSubscription(context.Context, GetSubscriptionArgs) (*Subscription, error) + // [Preview API] + GetSubscriptionDiagnostics(context.Context, GetSubscriptionDiagnosticsArgs) (*notification.SubscriptionDiagnostics, error) + // [Preview API] Get a list of consumer actions for a specific consumer. + ListConsumerActions(context.Context, ListConsumerActionsArgs) (*[]ConsumerAction, error) + // [Preview API] Get a list of available service hook consumer services. Optionally filter by consumers that support at least one event type from the specific publisher. + ListConsumers(context.Context, ListConsumersArgs) (*[]Consumer, error) + // [Preview API] Get the event types for a specific publisher. + ListEventTypes(context.Context, ListEventTypesArgs) (*[]EventTypeDescriptor, error) + // [Preview API] Get a list of publishers. + ListPublishers(context.Context, ListPublishersArgs) (*[]Publisher, error) + // [Preview API] Get a list of subscriptions. + ListSubscriptions(context.Context, ListSubscriptionsArgs) (*[]Subscription, error) + // [Preview API] + QueryInputValues(context.Context, QueryInputValuesArgs) (*forminput.InputValuesQuery, error) + // [Preview API] Query for notifications. A notification includes details about the event, the request to and the response from the consumer service. + QueryNotifications(context.Context, QueryNotificationsArgs) (*NotificationsQuery, error) + // [Preview API] Query for service hook publishers. + QueryPublishers(context.Context, QueryPublishersArgs) (*PublishersQuery, error) + // [Preview API] Update a subscription. ID for a subscription that you wish to update. + ReplaceSubscription(context.Context, ReplaceSubscriptionArgs) (*Subscription, error) + // [Preview API] + UpdateSubscriptionDiagnostics(context.Context, UpdateSubscriptionDiagnosticsArgs) (*notification.SubscriptionDiagnostics, error) +} + +type ClientImpl struct { + Client azuredevops.Client +} + +func NewClient(ctx context.Context, connection *azuredevops.Connection) Client { + client := connection.GetClientByUrl(connection.BaseUrl) + return &ClientImpl{ + Client: *client, + } +} + +// [Preview API] Create a subscription. +func (client *ClientImpl) CreateSubscription(ctx context.Context, args CreateSubscriptionArgs) (*Subscription, error) { + if args.Subscription == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.Subscription"} + } + body, marshalErr := json.Marshal(*args.Subscription) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("fc50d02a-849f-41fb-8af1-0a5216103269") + resp, err := client.Client.Send(ctx, http.MethodPost, locationId, "7.1-preview.1", nil, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue Subscription + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the CreateSubscription function +type CreateSubscriptionArgs struct { + // (required) Subscription to be created. + Subscription *Subscription +} + +// [Preview API] Query for service hook subscriptions. +func (client *ClientImpl) CreateSubscriptionsQuery(ctx context.Context, args CreateSubscriptionsQueryArgs) (*SubscriptionsQuery, error) { + if args.Query == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.Query"} + } + body, marshalErr := json.Marshal(*args.Query) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("c7c3c1cf-9e05-4c0d-a425-a0f922c2c6ed") + resp, err := client.Client.Send(ctx, http.MethodPost, locationId, "7.1-preview.1", nil, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue SubscriptionsQuery + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the CreateSubscriptionsQuery function +type CreateSubscriptionsQueryArgs struct { + // (required) + Query *SubscriptionsQuery +} + +// [Preview API] Sends a test notification. This is useful for verifying the configuration of an updated or new service hooks subscription. +func (client *ClientImpl) CreateTestNotification(ctx context.Context, args CreateTestNotificationArgs) (*Notification, error) { + if args.TestNotification == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.TestNotification"} + } + queryParams := url.Values{} + if args.UseRealData != nil { + queryParams.Add("useRealData", strconv.FormatBool(*args.UseRealData)) + } + body, marshalErr := json.Marshal(*args.TestNotification) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("1139462c-7e27-4524-a997-31b9b73551fe") + resp, err := client.Client.Send(ctx, http.MethodPost, locationId, "7.1-preview.1", nil, queryParams, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue Notification + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the CreateTestNotification function +type CreateTestNotificationArgs struct { + // (required) + TestNotification *Notification + // (optional) Only allow testing with real data in existing subscriptions. + UseRealData *bool +} + +// [Preview API] Delete a specific service hooks subscription. +func (client *ClientImpl) DeleteSubscription(ctx context.Context, args DeleteSubscriptionArgs) error { + routeValues := make(map[string]string) + if args.SubscriptionId == nil { + return &azuredevops.ArgumentNilError{ArgumentName: "args.SubscriptionId"} + } + routeValues["subscriptionId"] = (*args.SubscriptionId).String() + + locationId, _ := uuid.Parse("fc50d02a-849f-41fb-8af1-0a5216103269") + _, err := client.Client.Send(ctx, http.MethodDelete, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return err + } + + return nil +} + +// Arguments for the DeleteSubscription function +type DeleteSubscriptionArgs struct { + // (required) ID for a subscription. + SubscriptionId *uuid.UUID +} + +// [Preview API] Get a specific consumer service. Optionally filter out consumer actions that do not support any event types for the specified publisher. +func (client *ClientImpl) GetConsumer(ctx context.Context, args GetConsumerArgs) (*Consumer, error) { + routeValues := make(map[string]string) + if args.ConsumerId == nil || *args.ConsumerId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.ConsumerId"} + } + routeValues["consumerId"] = *args.ConsumerId + + queryParams := url.Values{} + if args.PublisherId != nil { + queryParams.Add("publisherId", *args.PublisherId) + } + locationId, _ := uuid.Parse("4301c514-5f34-4f5d-a145-f0ea7b5b7d19") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue Consumer + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetConsumer function +type GetConsumerArgs struct { + // (required) ID for a consumer. + ConsumerId *string + // (optional) + PublisherId *string +} + +// [Preview API] Get details about a specific consumer action. +func (client *ClientImpl) GetConsumerAction(ctx context.Context, args GetConsumerActionArgs) (*ConsumerAction, error) { + routeValues := make(map[string]string) + if args.ConsumerId == nil || *args.ConsumerId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.ConsumerId"} + } + routeValues["consumerId"] = *args.ConsumerId + if args.ConsumerActionId == nil || *args.ConsumerActionId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.ConsumerActionId"} + } + routeValues["consumerActionId"] = *args.ConsumerActionId + + queryParams := url.Values{} + if args.PublisherId != nil { + queryParams.Add("publisherId", *args.PublisherId) + } + locationId, _ := uuid.Parse("c3428e90-7a69-4194-8ed8-0f153185ee0d") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue ConsumerAction + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetConsumerAction function +type GetConsumerActionArgs struct { + // (required) ID for a consumer. + ConsumerId *string + // (required) ID for a consumerActionId. + ConsumerActionId *string + // (optional) + PublisherId *string +} + +// [Preview API] Get a specific event type. +func (client *ClientImpl) GetEventType(ctx context.Context, args GetEventTypeArgs) (*EventTypeDescriptor, error) { + routeValues := make(map[string]string) + if args.PublisherId == nil || *args.PublisherId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.PublisherId"} + } + routeValues["publisherId"] = *args.PublisherId + if args.EventTypeId == nil || *args.EventTypeId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.EventTypeId"} + } + routeValues["eventTypeId"] = *args.EventTypeId + + locationId, _ := uuid.Parse("db4777cd-8e08-4a84-8ba3-c974ea033718") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue EventTypeDescriptor + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetEventType function +type GetEventTypeArgs struct { + // (required) ID for a publisher. + PublisherId *string + // (required) + EventTypeId *string +} + +// [Preview API] Get a specific notification for a subscription. +func (client *ClientImpl) GetNotification(ctx context.Context, args GetNotificationArgs) (*Notification, error) { + routeValues := make(map[string]string) + if args.SubscriptionId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.SubscriptionId"} + } + routeValues["subscriptionId"] = (*args.SubscriptionId).String() + if args.NotificationId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.NotificationId"} + } + routeValues["notificationId"] = strconv.Itoa(*args.NotificationId) + + locationId, _ := uuid.Parse("0c62d343-21b0-4732-997b-017fde84dc28") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue Notification + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetNotification function +type GetNotificationArgs struct { + // (required) ID for a subscription. + SubscriptionId *uuid.UUID + // (required) + NotificationId *int +} + +// [Preview API] Get a list of notifications for a specific subscription. A notification includes details about the event, the request to and the response from the consumer service. +func (client *ClientImpl) GetNotifications(ctx context.Context, args GetNotificationsArgs) (*[]Notification, error) { + routeValues := make(map[string]string) + if args.SubscriptionId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.SubscriptionId"} + } + routeValues["subscriptionId"] = (*args.SubscriptionId).String() + + queryParams := url.Values{} + if args.MaxResults != nil { + queryParams.Add("maxResults", strconv.Itoa(*args.MaxResults)) + } + if args.Status != nil { + queryParams.Add("status", string(*args.Status)) + } + if args.Result != nil { + queryParams.Add("result", string(*args.Result)) + } + locationId, _ := uuid.Parse("0c62d343-21b0-4732-997b-017fde84dc28") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []Notification + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetNotifications function +type GetNotificationsArgs struct { + // (required) ID for a subscription. + SubscriptionId *uuid.UUID + // (optional) Maximum number of notifications to return. Default is **100**. + MaxResults *int + // (optional) Get only notifications with this status. + Status *NotificationStatus + // (optional) Get only notifications with this result type. + Result *NotificationResult +} + +// [Preview API] Get a specific service hooks publisher. +func (client *ClientImpl) GetPublisher(ctx context.Context, args GetPublisherArgs) (*Publisher, error) { + routeValues := make(map[string]string) + if args.PublisherId == nil || *args.PublisherId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.PublisherId"} + } + routeValues["publisherId"] = *args.PublisherId + + locationId, _ := uuid.Parse("1e83a210-5b53-43bc-90f0-d476a4e5d731") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue Publisher + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetPublisher function +type GetPublisherArgs struct { + // (required) ID for a publisher. + PublisherId *string +} + +// [Preview API] Get a specific service hooks subscription. +func (client *ClientImpl) GetSubscription(ctx context.Context, args GetSubscriptionArgs) (*Subscription, error) { + routeValues := make(map[string]string) + if args.SubscriptionId == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.SubscriptionId"} + } + routeValues["subscriptionId"] = (*args.SubscriptionId).String() + + locationId, _ := uuid.Parse("fc50d02a-849f-41fb-8af1-0a5216103269") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue Subscription + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetSubscription function +type GetSubscriptionArgs struct { + // (required) ID for a subscription. + SubscriptionId *uuid.UUID +} + +// [Preview API] +func (client *ClientImpl) GetSubscriptionDiagnostics(ctx context.Context, args GetSubscriptionDiagnosticsArgs) (*notification.SubscriptionDiagnostics, error) { + routeValues := make(map[string]string) + if args.SubscriptionId == nil || *args.SubscriptionId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.SubscriptionId"} + } + routeValues["subscriptionId"] = *args.SubscriptionId + + locationId, _ := uuid.Parse("3b36bcb5-02ad-43c6-bbfa-6dfc6f8e9d68") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue notification.SubscriptionDiagnostics + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the GetSubscriptionDiagnostics function +type GetSubscriptionDiagnosticsArgs struct { + // (required) + SubscriptionId *string +} + +// [Preview API] Get a list of consumer actions for a specific consumer. +func (client *ClientImpl) ListConsumerActions(ctx context.Context, args ListConsumerActionsArgs) (*[]ConsumerAction, error) { + routeValues := make(map[string]string) + if args.ConsumerId == nil || *args.ConsumerId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.ConsumerId"} + } + routeValues["consumerId"] = *args.ConsumerId + + queryParams := url.Values{} + if args.PublisherId != nil { + queryParams.Add("publisherId", *args.PublisherId) + } + locationId, _ := uuid.Parse("c3428e90-7a69-4194-8ed8-0f153185ee0d") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []ConsumerAction + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the ListConsumerActions function +type ListConsumerActionsArgs struct { + // (required) ID for a consumer. + ConsumerId *string + // (optional) + PublisherId *string +} + +// [Preview API] Get a list of available service hook consumer services. Optionally filter by consumers that support at least one event type from the specific publisher. +func (client *ClientImpl) ListConsumers(ctx context.Context, args ListConsumersArgs) (*[]Consumer, error) { + queryParams := url.Values{} + if args.PublisherId != nil { + queryParams.Add("publisherId", *args.PublisherId) + } + locationId, _ := uuid.Parse("4301c514-5f34-4f5d-a145-f0ea7b5b7d19") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", nil, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []Consumer + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the ListConsumers function +type ListConsumersArgs struct { + // (optional) + PublisherId *string +} + +// [Preview API] Get the event types for a specific publisher. +func (client *ClientImpl) ListEventTypes(ctx context.Context, args ListEventTypesArgs) (*[]EventTypeDescriptor, error) { + routeValues := make(map[string]string) + if args.PublisherId == nil || *args.PublisherId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.PublisherId"} + } + routeValues["publisherId"] = *args.PublisherId + + locationId, _ := uuid.Parse("db4777cd-8e08-4a84-8ba3-c974ea033718") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", routeValues, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []EventTypeDescriptor + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the ListEventTypes function +type ListEventTypesArgs struct { + // (required) ID for a publisher. + PublisherId *string +} + +// [Preview API] Get a list of publishers. +func (client *ClientImpl) ListPublishers(ctx context.Context, args ListPublishersArgs) (*[]Publisher, error) { + locationId, _ := uuid.Parse("1e83a210-5b53-43bc-90f0-d476a4e5d731") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", nil, nil, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []Publisher + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the ListPublishers function +type ListPublishersArgs struct { +} + +// [Preview API] Get a list of subscriptions. +func (client *ClientImpl) ListSubscriptions(ctx context.Context, args ListSubscriptionsArgs) (*[]Subscription, error) { + queryParams := url.Values{} + if args.PublisherId != nil { + queryParams.Add("publisherId", *args.PublisherId) + } + if args.EventType != nil { + queryParams.Add("eventType", *args.EventType) + } + if args.ConsumerId != nil { + queryParams.Add("consumerId", *args.ConsumerId) + } + if args.ConsumerActionId != nil { + queryParams.Add("consumerActionId", *args.ConsumerActionId) + } + locationId, _ := uuid.Parse("fc50d02a-849f-41fb-8af1-0a5216103269") + resp, err := client.Client.Send(ctx, http.MethodGet, locationId, "7.1-preview.1", nil, queryParams, nil, "", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue []Subscription + err = client.Client.UnmarshalCollectionBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the ListSubscriptions function +type ListSubscriptionsArgs struct { + // (optional) ID for a subscription. + PublisherId *string + // (optional) The event type to filter on (if any). + EventType *string + // (optional) ID for a consumer. + ConsumerId *string + // (optional) ID for a consumerActionId. + ConsumerActionId *string +} + +// [Preview API] +func (client *ClientImpl) QueryInputValues(ctx context.Context, args QueryInputValuesArgs) (*forminput.InputValuesQuery, error) { + if args.InputValuesQuery == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.InputValuesQuery"} + } + routeValues := make(map[string]string) + if args.PublisherId == nil || *args.PublisherId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.PublisherId"} + } + routeValues["publisherId"] = *args.PublisherId + + body, marshalErr := json.Marshal(*args.InputValuesQuery) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("d815d352-a566-4dc1-a3e3-fd245acf688c") + resp, err := client.Client.Send(ctx, http.MethodPost, locationId, "7.1-preview.1", routeValues, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue forminput.InputValuesQuery + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the QueryInputValues function +type QueryInputValuesArgs struct { + // (required) + InputValuesQuery *forminput.InputValuesQuery + // (required) + PublisherId *string +} + +// [Preview API] Query for notifications. A notification includes details about the event, the request to and the response from the consumer service. +func (client *ClientImpl) QueryNotifications(ctx context.Context, args QueryNotificationsArgs) (*NotificationsQuery, error) { + if args.Query == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.Query"} + } + body, marshalErr := json.Marshal(*args.Query) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("1a57562f-160a-4b5c-9185-905e95b39d36") + resp, err := client.Client.Send(ctx, http.MethodPost, locationId, "7.1-preview.1", nil, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue NotificationsQuery + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the QueryNotifications function +type QueryNotificationsArgs struct { + // (required) + Query *NotificationsQuery +} + +// [Preview API] Query for service hook publishers. +func (client *ClientImpl) QueryPublishers(ctx context.Context, args QueryPublishersArgs) (*PublishersQuery, error) { + if args.Query == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.Query"} + } + body, marshalErr := json.Marshal(*args.Query) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("99b44a8a-65a8-4670-8f3e-e7f7842cce64") + resp, err := client.Client.Send(ctx, http.MethodPost, locationId, "7.1-preview.1", nil, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue PublishersQuery + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the QueryPublishers function +type QueryPublishersArgs struct { + // (required) + Query *PublishersQuery +} + +// [Preview API] Update a subscription. ID for a subscription that you wish to update. +func (client *ClientImpl) ReplaceSubscription(ctx context.Context, args ReplaceSubscriptionArgs) (*Subscription, error) { + if args.Subscription == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.Subscription"} + } + routeValues := make(map[string]string) + if args.SubscriptionId != nil { + routeValues["subscriptionId"] = (*args.SubscriptionId).String() + } + + body, marshalErr := json.Marshal(*args.Subscription) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("fc50d02a-849f-41fb-8af1-0a5216103269") + resp, err := client.Client.Send(ctx, http.MethodPut, locationId, "7.1-preview.1", routeValues, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue Subscription + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the ReplaceSubscription function +type ReplaceSubscriptionArgs struct { + // (required) + Subscription *Subscription + // (optional) + SubscriptionId *uuid.UUID +} + +// [Preview API] +func (client *ClientImpl) UpdateSubscriptionDiagnostics(ctx context.Context, args UpdateSubscriptionDiagnosticsArgs) (*notification.SubscriptionDiagnostics, error) { + if args.UpdateParameters == nil { + return nil, &azuredevops.ArgumentNilError{ArgumentName: "args.UpdateParameters"} + } + routeValues := make(map[string]string) + if args.SubscriptionId == nil || *args.SubscriptionId == "" { + return nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: "args.SubscriptionId"} + } + routeValues["subscriptionId"] = *args.SubscriptionId + + body, marshalErr := json.Marshal(*args.UpdateParameters) + if marshalErr != nil { + return nil, marshalErr + } + locationId, _ := uuid.Parse("3b36bcb5-02ad-43c6-bbfa-6dfc6f8e9d68") + resp, err := client.Client.Send(ctx, http.MethodPut, locationId, "7.1-preview.1", routeValues, nil, bytes.NewReader(body), "application/json", "application/json", nil) + if err != nil { + return nil, err + } + + var responseValue notification.SubscriptionDiagnostics + err = client.Client.UnmarshalBody(resp, &responseValue) + return &responseValue, err +} + +// Arguments for the UpdateSubscriptionDiagnostics function +type UpdateSubscriptionDiagnosticsArgs struct { + // (required) + UpdateParameters *notification.UpdateSubscripitonDiagnosticsParameters + // (required) + SubscriptionId *string +} diff --git a/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/servicehooks/models.go b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/servicehooks/models.go new file mode 100644 index 000000000..2b2d90c3f --- /dev/null +++ b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/servicehooks/models.go @@ -0,0 +1,468 @@ +// -------------------------------------------------------------------------------------------- +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// -------------------------------------------------------------------------------------------- +// Generated file, DO NOT EDIT +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// -------------------------------------------------------------------------------------------- + +package servicehooks + +import ( + "github.com/google/uuid" + "github.com/microsoft/azure-devops-go-api/azuredevops/v7" + "github.com/microsoft/azure-devops-go-api/azuredevops/v7/forminput" + "github.com/microsoft/azure-devops-go-api/azuredevops/v7/webapi" +) + +// Enumerates consumer authentication types. +type AuthenticationType string + +type authenticationTypeValuesType struct { + None AuthenticationType + OAuth AuthenticationType + External AuthenticationType +} + +var AuthenticationTypeValues = authenticationTypeValuesType{ + // No authentication is required. + None: "none", + // OAuth authentication. + OAuth: "oAuth", + // Externally-configured authentication. + External: "external", +} + +// Defines the data contract of a consumer. +type Consumer struct { + // Reference Links + Links interface{} `json:"_links,omitempty"` + // Gets this consumer's actions. + Actions *[]ConsumerAction `json:"actions,omitempty"` + // Gets or sets this consumer's authentication type. + AuthenticationType *AuthenticationType `json:"authenticationType,omitempty"` + // Gets or sets this consumer's localized description. + Description *string `json:"description,omitempty"` + // Non-null only if subscriptions for this consumer are configured externally. + ExternalConfiguration *ExternalConfigurationDescriptor `json:"externalConfiguration,omitempty"` + // Gets or sets this consumer's identifier. + Id *string `json:"id,omitempty"` + // Gets or sets this consumer's image URL, if any. + ImageUrl *string `json:"imageUrl,omitempty"` + // Gets or sets this consumer's information URL, if any. + InformationUrl *string `json:"informationUrl,omitempty"` + // Gets or sets this consumer's input descriptors. + InputDescriptors *[]forminput.InputDescriptor `json:"inputDescriptors,omitempty"` + // Gets or sets this consumer's localized name. + Name *string `json:"name,omitempty"` + // The url for this resource + Url *string `json:"url,omitempty"` +} + +// Defines the data contract of a consumer action. +type ConsumerAction struct { + // Reference Links + Links interface{} `json:"_links,omitempty"` + // Gets or sets the flag indicating if resource version can be overridden when creating or editing a subscription. + AllowResourceVersionOverride *bool `json:"allowResourceVersionOverride,omitempty"` + // Gets or sets the identifier of the consumer to which this action belongs. + ConsumerId *string `json:"consumerId,omitempty"` + // Gets or sets this action's localized description. + Description *string `json:"description,omitempty"` + // Gets or sets this action's identifier. + Id *string `json:"id,omitempty"` + // Gets or sets this action's input descriptors. + InputDescriptors *[]forminput.InputDescriptor `json:"inputDescriptors,omitempty"` + // Gets or sets this action's localized name. + Name *string `json:"name,omitempty"` + // Gets or sets this action's supported event identifiers. + SupportedEventTypes *[]string `json:"supportedEventTypes,omitempty"` + // Gets or sets this action's supported resource versions. + SupportedResourceVersions *map[string][]string `json:"supportedResourceVersions,omitempty"` + // The url for this resource + Url *string `json:"url,omitempty"` +} + +// Encapsulates the properties of an event. +type Event struct { + // Gets or sets the UTC-based date and time that this event was created. + CreatedDate *azuredevops.Time `json:"createdDate,omitempty"` + // Gets or sets the detailed message associated with this event. + DetailedMessage *FormattedEventMessage `json:"detailedMessage,omitempty"` + // Gets or sets the type of this event. + EventType *string `json:"eventType,omitempty"` + // Gets or sets the unique identifier of this event. + Id *uuid.UUID `json:"id,omitempty"` + // Gets or sets the (brief) message associated with this event. + Message *FormattedEventMessage `json:"message,omitempty"` + // Gets or sets the identifier of the publisher that raised this event. + PublisherId *string `json:"publisherId,omitempty"` + // Gets or sets the data associated with this event. + Resource interface{} `json:"resource,omitempty"` + // Gets or sets the resource containers. + ResourceContainers *map[string]ResourceContainer `json:"resourceContainers,omitempty"` + // Gets or sets the version of the data associated with this event. + ResourceVersion *string `json:"resourceVersion,omitempty"` + // Gets or sets the Session Token that can be used in further interactions + SessionToken *SessionToken `json:"sessionToken,omitempty"` +} + +// Describes a type of event +type EventTypeDescriptor struct { + // A localized description of the event type + Description *string `json:"description,omitempty"` + // A unique id for the event type + Id *string `json:"id,omitempty"` + // Event-specific inputs + InputDescriptors *[]forminput.InputDescriptor `json:"inputDescriptors,omitempty"` + // A localized friendly name for the event type + Name *string `json:"name,omitempty"` + // A unique id for the publisher of this event type + PublisherId *string `json:"publisherId,omitempty"` + // Supported versions for the event's resource payloads. + SupportedResourceVersions *[]string `json:"supportedResourceVersions,omitempty"` + // The url for this resource + Url *string `json:"url,omitempty"` +} + +// Describes how to configure a subscription that is managed externally. +type ExternalConfigurationDescriptor struct { + // Url of the site to create this type of subscription. + CreateSubscriptionUrl *string `json:"createSubscriptionUrl,omitempty"` + // The name of an input property that contains the URL to edit a subscription. + EditSubscriptionPropertyName *string `json:"editSubscriptionPropertyName,omitempty"` + // True if the external configuration applies only to hosted. + HostedOnly *bool `json:"hostedOnly,omitempty"` +} + +// Provides different formats of an event message +type FormattedEventMessage struct { + // Gets or sets the html format of the message + Html *string `json:"html,omitempty"` + // Gets or sets the markdown format of the message + Markdown *string `json:"markdown,omitempty"` + // Gets or sets the raw text of the message + Text *string `json:"text,omitempty"` +} + +// Defines the data contract of the result of processing an event for a subscription. +type Notification struct { + // Gets or sets date and time that this result was created. + CreatedDate *azuredevops.Time `json:"createdDate,omitempty"` + // Details about this notification (if available) + Details *NotificationDetails `json:"details,omitempty"` + // The event id associated with this notification + EventId *uuid.UUID `json:"eventId,omitempty"` + // The notification id + Id *int `json:"id,omitempty"` + // Gets or sets date and time that this result was last modified. + ModifiedDate *azuredevops.Time `json:"modifiedDate,omitempty"` + // Result of the notification + Result *NotificationResult `json:"result,omitempty"` + // Status of the notification + Status *NotificationStatus `json:"status,omitempty"` + // The subscriber Id associated with this notification. This is the last identity who touched in the subscription. In case of test notifications it can be the tester if the subscription is not created yet. + SubscriberId *uuid.UUID `json:"subscriberId,omitempty"` + // The subscription id associated with this notification + SubscriptionId *uuid.UUID `json:"subscriptionId,omitempty"` +} + +// Defines the data contract of notification details. +type NotificationDetails struct { + // Gets or sets the time that this notification was completed (response received from the consumer) + CompletedDate *azuredevops.Time `json:"completedDate,omitempty"` + // Gets or sets this notification detail's consumer action identifier. + ConsumerActionId *string `json:"consumerActionId,omitempty"` + // Gets or sets this notification detail's consumer identifier. + ConsumerId *string `json:"consumerId,omitempty"` + // Gets or sets this notification detail's consumer inputs. + ConsumerInputs *map[string]string `json:"consumerInputs,omitempty"` + // Gets or sets the time that this notification was dequeued for processing + DequeuedDate *azuredevops.Time `json:"dequeuedDate,omitempty"` + // Gets or sets this notification detail's error detail. + ErrorDetail *string `json:"errorDetail,omitempty"` + // Gets or sets this notification detail's error message. + ErrorMessage *string `json:"errorMessage,omitempty"` + // Gets or sets this notification detail's event content. + Event *Event `json:"event,omitempty"` + // Gets or sets this notification detail's event type. + EventType *string `json:"eventType,omitempty"` + // Gets or sets the time that this notification was finished processing (just before the request is sent to the consumer) + ProcessedDate *azuredevops.Time `json:"processedDate,omitempty"` + // Gets or sets this notification detail's publisher identifier. + PublisherId *string `json:"publisherId,omitempty"` + // Gets or sets this notification detail's publisher inputs. + PublisherInputs *map[string]string `json:"publisherInputs,omitempty"` + // Gets or sets the time that this notification was queued (created) + QueuedDate *azuredevops.Time `json:"queuedDate,omitempty"` + // Gets or sets this notification detail's request. + Request *string `json:"request,omitempty"` + // Number of requests attempted to be sent to the consumer + RequestAttempts *int `json:"requestAttempts,omitempty"` + // Duration of the request to the consumer in seconds + RequestDuration *float64 `json:"requestDuration,omitempty"` + // Gets or sets this notification detail's response. + Response *string `json:"response,omitempty"` +} + +// Enumerates possible result types of a notification. +type NotificationResult string + +type notificationResultValuesType struct { + Pending NotificationResult + Succeeded NotificationResult + Failed NotificationResult + Filtered NotificationResult +} + +var NotificationResultValues = notificationResultValuesType{ + // The notification has not yet completed + Pending: "pending", + // The notification was sent successfully + Succeeded: "succeeded", + // The notification failed to be sent successfully to the consumer + Failed: "failed", + // The notification was filtered by the Delivery Job + Filtered: "filtered", +} + +// Summary of a particular result and count. +type NotificationResultsSummaryDetail struct { + // Count of notification sent out with a matching result. + NotificationCount *int `json:"notificationCount,omitempty"` + // Result of the notification + Result *NotificationResult `json:"result,omitempty"` +} + +// Defines a query for service hook notifications. +type NotificationsQuery struct { + // The subscriptions associated with the notifications returned from the query + AssociatedSubscriptions *[]Subscription `json:"associatedSubscriptions,omitempty"` + // If true, we will return all notification history for the query provided; otherwise, the summary is returned. + IncludeDetails *bool `json:"includeDetails,omitempty"` + // Optional maximum date at which the notification was created + MaxCreatedDate *azuredevops.Time `json:"maxCreatedDate,omitempty"` + // Optional maximum number of overall results to include + MaxResults *int `json:"maxResults,omitempty"` + // Optional maximum number of results for each subscription. Only takes effect when a list of subscription ids is supplied in the query. + MaxResultsPerSubscription *int `json:"maxResultsPerSubscription,omitempty"` + // Optional minimum date at which the notification was created + MinCreatedDate *azuredevops.Time `json:"minCreatedDate,omitempty"` + // Optional publisher id to restrict the results to + PublisherId *string `json:"publisherId,omitempty"` + // Results from the query + Results *[]Notification `json:"results,omitempty"` + // Optional notification result type to filter results to + ResultType *NotificationResult `json:"resultType,omitempty"` + // Optional notification status to filter results to + Status *NotificationStatus `json:"status,omitempty"` + // Optional list of subscription ids to restrict the results to + SubscriptionIds *[]uuid.UUID `json:"subscriptionIds,omitempty"` + // Summary of notifications - the count of each result type (success, fail, ..). + Summary *[]NotificationSummary `json:"summary,omitempty"` +} + +// Enumerates possible status' of a notification. +type NotificationStatus string + +type notificationStatusValuesType struct { + Queued NotificationStatus + Processing NotificationStatus + RequestInProgress NotificationStatus + Completed NotificationStatus +} + +var NotificationStatusValues = notificationStatusValuesType{ + // The notification has been queued + Queued: "queued", + // The notification has been dequeued and has begun processing. + Processing: "processing", + // The consumer action has processed the notification. The request is in progress. + RequestInProgress: "requestInProgress", + // The request completed + Completed: "completed", +} + +// Summary of the notifications for a subscription. +type NotificationSummary struct { + // The notification results for this particular subscription. + Results *[]NotificationResultsSummaryDetail `json:"results,omitempty"` + // The subscription id associated with this notification + SubscriptionId *uuid.UUID `json:"subscriptionId,omitempty"` +} + +// Defines the data contract of an event publisher. +type Publisher struct { + // Reference Links + Links interface{} `json:"_links,omitempty"` + // Gets this publisher's localized description. + Description *string `json:"description,omitempty"` + // Gets this publisher's identifier. + Id *string `json:"id,omitempty"` + // Publisher-specific inputs + InputDescriptors *[]forminput.InputDescriptor `json:"inputDescriptors,omitempty"` + // Gets this publisher's localized name. + Name *string `json:"name,omitempty"` + // The service instance type of the first party publisher. + ServiceInstanceType *string `json:"serviceInstanceType,omitempty"` + // Gets this publisher's supported event types. + SupportedEvents *[]EventTypeDescriptor `json:"supportedEvents,omitempty"` + // The url for this resource + Url *string `json:"url,omitempty"` +} + +// Wrapper around an event which is being published +type PublisherEvent struct { + // Add key/value pairs which will be stored with a published notification in the SH service DB. This key/value pairs are for diagnostic purposes only and will have not effect on the delivery of a notification. + Diagnostics *map[string]string `json:"diagnostics,omitempty"` + // The event being published + Event *Event `json:"event,omitempty"` + // Gets or sets flag for filtered events + IsFilteredEvent *bool `json:"isFilteredEvent,omitempty"` + // Additional data that needs to be sent as part of notification to complement the Resource data in the Event + NotificationData *map[string]string `json:"notificationData,omitempty"` + // Gets or sets the array of older supported resource versions. + OtherResourceVersions *[]VersionedResource `json:"otherResourceVersions,omitempty"` + // Optional publisher-input filters which restricts the set of subscriptions which are triggered by the event + PublisherInputFilters *[]forminput.InputFilter `json:"publisherInputFilters,omitempty"` + // Gets or sets matched hooks subscription which caused this event. + Subscription *Subscription `json:"subscription,omitempty"` +} + +// Defines a query for service hook publishers. +type PublishersQuery struct { + // Optional list of publisher ids to restrict the results to + PublisherIds *[]string `json:"publisherIds,omitempty"` + // Filter for publisher inputs + PublisherInputs *map[string]string `json:"publisherInputs,omitempty"` + // Results from the query + Results *[]Publisher `json:"results,omitempty"` +} + +// The base class for all resource containers, i.e. Account, Collection, Project +type ResourceContainer struct { + // Gets or sets the container's base URL, i.e. the URL of the host (collection, application, or deployment) containing the container resource. + BaseUrl *string `json:"baseUrl,omitempty"` + // Gets or sets the container's specific Id. + Id *uuid.UUID `json:"id,omitempty"` + // Gets or sets the container's name. + Name *string `json:"name,omitempty"` + // Gets or sets the container's REST API URL. + Url *string `json:"url,omitempty"` +} + +// Represents a session token to be attached in Events for Consumer actions that need it. +type SessionToken struct { + // The error message in case of error + Error *string `json:"error,omitempty"` + // The access token + Token *string `json:"token,omitempty"` + // The expiration date in UTC + ValidTo *azuredevops.Time `json:"validTo,omitempty"` +} + +// Encapsulates an event subscription. +type Subscription struct { + // Reference Links + Links interface{} `json:"_links,omitempty"` + ActionDescription *string `json:"actionDescription,omitempty"` + ConsumerActionId *string `json:"consumerActionId,omitempty"` + ConsumerId *string `json:"consumerId,omitempty"` + // Consumer input values + ConsumerInputs *map[string]string `json:"consumerInputs,omitempty"` + CreatedBy *webapi.IdentityRef `json:"createdBy,omitempty"` + CreatedDate *azuredevops.Time `json:"createdDate,omitempty"` + EventDescription *string `json:"eventDescription,omitempty"` + EventType *string `json:"eventType,omitempty"` + Id *uuid.UUID `json:"id,omitempty"` + LastProbationRetryDate *azuredevops.Time `json:"lastProbationRetryDate,omitempty"` + ModifiedBy *webapi.IdentityRef `json:"modifiedBy,omitempty"` + ModifiedDate *azuredevops.Time `json:"modifiedDate,omitempty"` + ProbationRetries *byte `json:"probationRetries,omitempty"` + PublisherId *string `json:"publisherId,omitempty"` + // Publisher input values + PublisherInputs *map[string]string `json:"publisherInputs,omitempty"` + ResourceVersion *string `json:"resourceVersion,omitempty"` + Status *SubscriptionStatus `json:"status,omitempty"` + Subscriber *webapi.IdentityRef `json:"subscriber,omitempty"` + Url *string `json:"url,omitempty"` +} + +// The scope to which a subscription input applies +type SubscriptionInputScope string + +type subscriptionInputScopeValuesType struct { + Publisher SubscriptionInputScope + Consumer SubscriptionInputScope +} + +var SubscriptionInputScopeValues = subscriptionInputScopeValuesType{ + // An input defined and consumed by a Publisher or Publisher Event Type + Publisher: "publisher", + // An input defined and consumed by a Consumer or Consumer Action + Consumer: "consumer", +} + +// Query for obtaining information about the possible/allowed values for one or more subscription inputs +type SubscriptionInputValuesQuery struct { + // The input values to return on input, and the result from the consumer on output. + InputValues *[]forminput.InputValues `json:"inputValues,omitempty"` + // The scope at which the properties to query belong + Scope *SubscriptionInputScope `json:"scope,omitempty"` + // Subscription containing information about the publisher/consumer and the current input values + Subscription *Subscription `json:"subscription,omitempty"` +} + +// Defines a query for service hook subscriptions. +type SubscriptionsQuery struct { + // Optional consumer action id to restrict the results to (null for any) + ConsumerActionId *string `json:"consumerActionId,omitempty"` + // Optional consumer id to restrict the results to (null for any) + ConsumerId *string `json:"consumerId,omitempty"` + // Filter for subscription consumer inputs + ConsumerInputFilters *[]forminput.InputFilter `json:"consumerInputFilters,omitempty"` + // Optional event type id to restrict the results to (null for any) + EventType *string `json:"eventType,omitempty"` + // Optional publisher id to restrict the results to (null for any) + PublisherId *string `json:"publisherId,omitempty"` + // Filter for subscription publisher inputs + PublisherInputFilters *[]forminput.InputFilter `json:"publisherInputFilters,omitempty"` + // Results from the query + Results *[]Subscription `json:"results,omitempty"` + // Optional subscriber filter. + SubscriberId *uuid.UUID `json:"subscriberId,omitempty"` +} + +// Enumerates possible states of a subscription. +type SubscriptionStatus string + +type subscriptionStatusValuesType struct { + Enabled SubscriptionStatus + OnProbation SubscriptionStatus + DisabledByUser SubscriptionStatus + DisabledBySystem SubscriptionStatus + DisabledByInactiveIdentity SubscriptionStatus +} + +var SubscriptionStatusValues = subscriptionStatusValuesType{ + // The subscription is enabled. + Enabled: "enabled", + // The subscription is temporarily on probation by the system. + OnProbation: "onProbation", + // The subscription is disabled by a user. + DisabledByUser: "disabledByUser", + // The subscription is disabled by the system. + DisabledBySystem: "disabledBySystem", + // The subscription is disabled because the owner is inactive or is missing permissions. + DisabledByInactiveIdentity: "disabledByInactiveIdentity", +} + +// Encapsulates the resource version and its data or reference to the compatible version. Only one of the two last fields should be not null. +type VersionedResource struct { + // Gets or sets the reference to the compatible version. + CompatibleWith *string `json:"compatibleWith,omitempty"` + // Gets or sets the resource data. + Resource interface{} `json:"resource,omitempty"` + // Gets or sets the version of the resource data. + ResourceVersion *string `json:"resourceVersion,omitempty"` +} diff --git a/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/system/models.go b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/system/models.go new file mode 100644 index 000000000..245ca996a --- /dev/null +++ b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/system/models.go @@ -0,0 +1,97 @@ +// -------------------------------------------------------------------------------------------- +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// -------------------------------------------------------------------------------------------- +// Generated file, DO NOT EDIT +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// -------------------------------------------------------------------------------------------- + +package system + +type SqlDbType string + +type sqlDbTypeValuesType struct { + BigInt SqlDbType + Binary SqlDbType + Bit SqlDbType + Char SqlDbType + DateTime SqlDbType + Decimal SqlDbType + Float SqlDbType + Image SqlDbType + Int SqlDbType + Money SqlDbType + NChar SqlDbType + NText SqlDbType + NVarChar SqlDbType + Real SqlDbType + UniqueIdentifier SqlDbType + SmallDateTime SqlDbType + SmallInt SqlDbType + SmallMoney SqlDbType + Text SqlDbType + Timestamp SqlDbType + TinyInt SqlDbType + VarBinary SqlDbType + VarChar SqlDbType + Variant SqlDbType + Xml SqlDbType + Udt SqlDbType + Structured SqlDbType + Date SqlDbType + Time SqlDbType + DateTime2 SqlDbType + DateTimeOffset SqlDbType +} + +var SqlDbTypeValues = sqlDbTypeValuesType{ + BigInt: "bigInt", + Binary: "binary", + Bit: "bit", + Char: "char", + DateTime: "dateTime", + Decimal: "decimal", + Float: "float", + Image: "image", + Int: "int", + Money: "money", + NChar: "nChar", + NText: "nText", + NVarChar: "nVarChar", + Real: "real", + UniqueIdentifier: "uniqueIdentifier", + SmallDateTime: "smallDateTime", + SmallInt: "smallInt", + SmallMoney: "smallMoney", + Text: "text", + Timestamp: "timestamp", + TinyInt: "tinyInt", + VarBinary: "varBinary", + VarChar: "varChar", + Variant: "variant", + Xml: "xml", + Udt: "udt", + Structured: "structured", + Date: "date", + Time: "time", + DateTime2: "dateTime2", + DateTimeOffset: "dateTimeOffset", +} + +type TraceLevel string + +type traceLevelValuesType struct { + Off TraceLevel + Error TraceLevel + Warning TraceLevel + Info TraceLevel + Verbose TraceLevel +} + +var TraceLevelValues = traceLevelValuesType{ + Off: "off", + Error: "error", + Warning: "warning", + Info: "info", + Verbose: "verbose", +} diff --git a/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/version.go b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/version.go new file mode 100644 index 000000000..443147c51 --- /dev/null +++ b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/version.go @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azuredevops + +import ( + "strconv" + "strings" +) + +type Version struct { + Major int + Minor int +} + +func NewVersion(version string) (*Version, error) { + split := strings.Split(version, ".") + if len(split) > 1 { + major, err := strconv.Atoi(split[0]) + if err != nil { + return nil, err + } + minor, err := strconv.Atoi(split[1]) + if err != nil { + return nil, err + } + return &Version{ + Major: major, + Minor: minor, + }, nil + } + return nil, &InvalidVersionStringError{version: version} +} + +func (version Version) CompareTo(compareToVersion Version) int { + if version.Major > compareToVersion.Major { + return 1 + } else if version.Major < compareToVersion.Major { + return -1 + } else if version.Minor > compareToVersion.Minor { + return 1 + } else if version.Minor < compareToVersion.Minor { + return -1 + } + return 0 +} + +func (version Version) String() string { + return strconv.Itoa(version.Major) + "." + strconv.Itoa(version.Minor) +} + +type InvalidVersionStringError struct { + version string +} + +func (e *InvalidVersionStringError) Error() string { + return "The version string was invalid: " + e.version +} diff --git a/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/versionnegotiation.go b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/versionnegotiation.go new file mode 100644 index 000000000..f1a2a2f33 --- /dev/null +++ b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/versionnegotiation.go @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azuredevops + +import "strconv" + +func negotiateRequestVersion(location *ApiResourceLocation, apiVersion string) (string, error) { + if apiVersion == "" { + // if no api-version is sent to the server, the server will decide the version. The server uses the latest + // released version if the endpoint has been released, otherwise it will use the latest preview version. + return apiVersion, nil + } + + matches := apiVersionRegEx.FindStringSubmatch(apiVersion) + if len(matches) == 0 && matches[0] != "" { + return apiVersion, &InvalidApiVersion{apiVersion} + } + + requestedApiVersion, err := NewVersion(matches[1]) + if err != nil { + return apiVersion, err + } + locationMinVersion, err := NewVersion(*location.MinVersion) + if err != nil { + return apiVersion, err + } + if locationMinVersion.CompareTo(*requestedApiVersion) > 0 { + // Client is older than the server. The server no longer supports this + // resource (deprecated). + return apiVersion, nil + } else { + locationMaxVersion, err := NewVersion(*location.MaxVersion) + if err != nil { + return apiVersion, err + } + if locationMaxVersion.CompareTo(*requestedApiVersion) < 0 { + // Client is newer than the server. Negotiate down to the latest version + // on the server + negotiatedVersion := string(*location.MaxVersion) + if *location.ReleasedVersion < *location.MaxVersion { + negotiatedVersion += "-preview" + } + return negotiatedVersion, nil + } else { + // We can send at the requested api version. Make sure the resource version + // is not bigger than what the server supports + negotiatedVersion := matches[1] + if len(matches) > 3 && matches[3] != "" { // matches '-preview' + negotiatedVersion += "-preview" + if len(matches) > 5 && matches[5] != "" { // has a resource version + requestedResourceVersion, _ := strconv.Atoi(matches[5]) + if *location.ResourceVersion < requestedResourceVersion { + negotiatedVersion += "." + strconv.Itoa(*location.ResourceVersion) + } else { + negotiatedVersion += "." + matches[5] + } + } + } else { + // requesting released version, ensure server supports a released version, and if not append '-preview' + locationReleasedVersion, err := NewVersion(*location.ReleasedVersion) + if err != nil { + return apiVersion, err + } + if (locationReleasedVersion.Major == 0 && locationReleasedVersion.Minor == 0) || locationReleasedVersion.CompareTo(*requestedApiVersion) < 0 { + negotiatedVersion += "-preview" + } + } + return negotiatedVersion, nil + } + } +} diff --git a/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/webapi/models.go b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/webapi/models.go new file mode 100644 index 000000000..5f7be1f02 --- /dev/null +++ b/vendor/github.com/microsoft/azure-devops-go-api/azuredevops/v7/webapi/models.go @@ -0,0 +1,339 @@ +// -------------------------------------------------------------------------------------------- +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// -------------------------------------------------------------------------------------------- +// Generated file, DO NOT EDIT +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// -------------------------------------------------------------------------------------------- + +package webapi + +import ( + "github.com/google/uuid" + "github.com/microsoft/azure-devops-go-api/azuredevops/v7" + "github.com/microsoft/azure-devops-go-api/azuredevops/v7/system" +) + +// Information about the location of a REST API resource +type ApiResourceLocation struct { + // Area name for this resource + Area *string `json:"area,omitempty"` + // Unique Identifier for this location + Id *uuid.UUID `json:"id,omitempty"` + // Maximum api version that this resource supports (current server version for this resource) + MaxVersion *string `json:"maxVersion,omitempty"` + // Minimum api version that this resource supports + MinVersion *string `json:"minVersion,omitempty"` + // The latest version of this resource location that is in "Release" (non-preview) mode + ReleasedVersion *string `json:"releasedVersion,omitempty"` + // Resource name + ResourceName *string `json:"resourceName,omitempty"` + // The current resource version supported by this resource location + ResourceVersion *int `json:"resourceVersion,omitempty"` + // This location's route template (templated relative path) + RouteTemplate *string `json:"routeTemplate,omitempty"` +} + +// [Flags] Enumeration of the options that can be passed in on Connect. +type ConnectOptions string + +type connectOptionsValuesType struct { + None ConnectOptions + IncludeServices ConnectOptions + IncludeLastUserAccess ConnectOptions + IncludeInheritedDefinitionsOnly ConnectOptions + IncludeNonInheritedDefinitionsOnly ConnectOptions +} + +var ConnectOptionsValues = connectOptionsValuesType{ + // Retrieve no optional data. + None: "none", + // Includes information about AccessMappings and ServiceDefinitions. + IncludeServices: "includeServices", + // Includes the last user access for this host. + IncludeLastUserAccess: "includeLastUserAccess", + // This is only valid on the deployment host and when true. Will only return inherited definitions. + IncludeInheritedDefinitionsOnly: "includeInheritedDefinitionsOnly", + // When true will only return non inherited definitions. Only valid at non-deployment host. + IncludeNonInheritedDefinitionsOnly: "includeNonInheritedDefinitionsOnly", +} + +// [Flags] +type DeploymentFlags string + +type deploymentFlagsValuesType struct { + None DeploymentFlags + Hosted DeploymentFlags + OnPremises DeploymentFlags +} + +var DeploymentFlagsValues = deploymentFlagsValuesType{ + None: "none", + Hosted: "hosted", + OnPremises: "onPremises", +} + +// Defines an "actor" for an event. +type EventActor struct { + // Required: This is the identity of the user for the specified role. + Id *uuid.UUID `json:"id,omitempty"` + // Required: The event specific name of a role. + Role *string `json:"role,omitempty"` +} + +// Defines a scope for an event. +type EventScope struct { + // Required: This is the identity of the scope for the type. + Id *uuid.UUID `json:"id,omitempty"` + // Optional: The display name of the scope + Name *string `json:"name,omitempty"` + // Required: The event specific type of a scope. + Type *string `json:"type,omitempty"` +} + +type IdentityRef struct { + // This field contains zero or more interesting links about the graph subject. These links may be invoked to obtain additional relationships or more detailed information about this graph subject. + Links interface{} `json:"_links,omitempty"` + // The descriptor is the primary way to reference the graph subject while the system is running. This field will uniquely identify the same graph subject across both Accounts and Organizations. + Descriptor *string `json:"descriptor,omitempty"` + // This is the non-unique display name of the graph subject. To change this field, you must alter its value in the source provider. + DisplayName *string `json:"displayName,omitempty"` + // This url is the full route to the source resource of this graph subject. + Url *string `json:"url,omitempty"` + // Deprecated - Can be retrieved by querying the Graph user referenced in the "self" entry of the IdentityRef "_links" dictionary + DirectoryAlias *string `json:"directoryAlias,omitempty"` + Id *string `json:"id,omitempty"` + // Deprecated - Available in the "avatar" entry of the IdentityRef "_links" dictionary + ImageUrl *string `json:"imageUrl,omitempty"` + // Deprecated - Can be retrieved by querying the Graph membership state referenced in the "membershipState" entry of the GraphUser "_links" dictionary + Inactive *bool `json:"inactive,omitempty"` + // Deprecated - Can be inferred from the subject type of the descriptor (Descriptor.IsAadUserType/Descriptor.IsAadGroupType) + IsAadIdentity *bool `json:"isAadIdentity,omitempty"` + // Deprecated - Can be inferred from the subject type of the descriptor (Descriptor.IsGroupType) + IsContainer *bool `json:"isContainer,omitempty"` + IsDeletedInOrigin *bool `json:"isDeletedInOrigin,omitempty"` + // Deprecated - not in use in most preexisting implementations of ToIdentityRef + ProfileUrl *string `json:"profileUrl,omitempty"` + // Deprecated - use Domain+PrincipalName instead + UniqueName *string `json:"uniqueName,omitempty"` +} + +type IdentityRefWithEmail struct { + // This field contains zero or more interesting links about the graph subject. These links may be invoked to obtain additional relationships or more detailed information about this graph subject. + Links interface{} `json:"_links,omitempty"` + // The descriptor is the primary way to reference the graph subject while the system is running. This field will uniquely identify the same graph subject across both Accounts and Organizations. + Descriptor *string `json:"descriptor,omitempty"` + // This is the non-unique display name of the graph subject. To change this field, you must alter its value in the source provider. + DisplayName *string `json:"displayName,omitempty"` + // This url is the full route to the source resource of this graph subject. + Url *string `json:"url,omitempty"` + // Deprecated - Can be retrieved by querying the Graph user referenced in the "self" entry of the IdentityRef "_links" dictionary + DirectoryAlias *string `json:"directoryAlias,omitempty"` + Id *string `json:"id,omitempty"` + // Deprecated - Available in the "avatar" entry of the IdentityRef "_links" dictionary + ImageUrl *string `json:"imageUrl,omitempty"` + // Deprecated - Can be retrieved by querying the Graph membership state referenced in the "membershipState" entry of the GraphUser "_links" dictionary + Inactive *bool `json:"inactive,omitempty"` + // Deprecated - Can be inferred from the subject type of the descriptor (Descriptor.IsAadUserType/Descriptor.IsAadGroupType) + IsAadIdentity *bool `json:"isAadIdentity,omitempty"` + // Deprecated - Can be inferred from the subject type of the descriptor (Descriptor.IsGroupType) + IsContainer *bool `json:"isContainer,omitempty"` + IsDeletedInOrigin *bool `json:"isDeletedInOrigin,omitempty"` + // Deprecated - not in use in most preexisting implementations of ToIdentityRef + ProfileUrl *string `json:"profileUrl,omitempty"` + // Deprecated - use Domain+PrincipalName instead + UniqueName *string `json:"uniqueName,omitempty"` + PreferredEmailAddress *string `json:"preferredEmailAddress,omitempty"` +} + +// The JSON model for a JSON Patch operation +type JsonPatchOperation struct { + // The path to copy from for the Move/Copy operation. + From *string `json:"from,omitempty"` + // The patch operation + Op *Operation `json:"op,omitempty"` + // The path for the operation. In the case of an array, a zero based index can be used to specify the position in the array (e.g. /biscuits/0/name). The "-" character can be used instead of an index to insert at the end of the array (e.g. /biscuits/-). + Path *string `json:"path,omitempty"` + // The value for the operation. This is either a primitive or a JToken. + Value interface{} `json:"value,omitempty"` +} + +type JsonWebToken struct { + // Gets a value indicating whether or not this token has been successfully authenticated with the remote server. + IsAuthenticated *bool `json:"isAuthenticated,omitempty"` + // Metadata about the token in a collection of properties. + Properties *map[string]string `json:"properties,omitempty"` +} + +type JWTAlgorithm string + +type jwtAlgorithmValuesType struct { + None JWTAlgorithm + HS256 JWTAlgorithm + RS256 JWTAlgorithm +} + +var JWTAlgorithmValues = jwtAlgorithmValuesType{ + None: "none", + HS256: "hS256", + RS256: "rS256", +} + +type Operation string + +type operationValuesType struct { + Add Operation + Remove Operation + Replace Operation + Move Operation + Copy Operation + Test Operation +} + +var OperationValues = operationValuesType{ + Add: "add", + Remove: "remove", + Replace: "replace", + Move: "move", + Copy: "copy", + Test: "test", +} + +// Represents the public key portion of an RSA asymmetric key. +type PublicKey struct { + // Gets or sets the exponent for the public key. + Exponent *[]byte `json:"exponent,omitempty"` + // Gets or sets the modulus for the public key. + Modulus *[]byte `json:"modulus,omitempty"` +} + +type Publisher struct { + // Name of the publishing service. + Name *string `json:"name,omitempty"` + // Service Owner Guid Eg. Tfs : 00025394-6065-48CA-87D9-7F5672854EF7 + ServiceOwnerId *uuid.UUID `json:"serviceOwnerId,omitempty"` +} + +// The class to represent a REST reference link. RFC: http://tools.ietf.org/html/draft-kelly-json-hal-06 The RFC is not fully implemented, additional properties are allowed on the reference link but as of yet we don't have a need for them. +type ReferenceLink struct { + Href *string `json:"href,omitempty"` +} + +type ResourceRef struct { + Id *string `json:"id,omitempty"` + Url *string `json:"url,omitempty"` +} + +type ServiceEvent struct { + // This is the id of the type. Constants that will be used by subscribers to identify/filter events being published on a topic. + EventType *string `json:"eventType,omitempty"` + // This is the service that published this event. + Publisher *Publisher `json:"publisher,omitempty"` + // The resource object that carries specific information about the event. The object must have the ServiceEventObject applied for serialization/deserialization to work. + Resource interface{} `json:"resource,omitempty"` + // This dictionary carries the context descriptors along with their ids. + ResourceContainers *map[string]interface{} `json:"resourceContainers,omitempty"` + // This is the version of the resource. + ResourceVersion *string `json:"resourceVersion,omitempty"` +} + +// A signed url allowing limited-time anonymous access to private resources. +type SignedUrl struct { + // Timestamp when access expires. + SignatureExpires *azuredevops.Time `json:"signatureExpires,omitempty"` + // The URL to allow access to. + Url *string `json:"url,omitempty"` +} + +type TeamMember struct { + Identity *IdentityRef `json:"identity,omitempty"` + IsTeamAdmin *bool `json:"isTeamAdmin,omitempty"` +} + +// A single secured timing consisting of a duration and start time +type TimingEntry struct { + // Duration of the entry in ticks + ElapsedTicks *uint64 `json:"elapsedTicks,omitempty"` + // Properties to distinguish timings within the same group or to provide data to send with telemetry + Properties *map[string]interface{} `json:"properties,omitempty"` + // Offset from Server Request Context start time in microseconds + StartOffset *uint64 `json:"startOffset,omitempty"` +} + +// A set of secured performance timings all keyed off of the same string +type TimingGroup struct { + // The total number of timing entries associated with this group + Count *int `json:"count,omitempty"` + // Overall duration of all entries in this group in ticks + ElapsedTicks *uint64 `json:"elapsedTicks,omitempty"` + // A list of timing entries in this group. Only the first few entries in each group are collected. + Timings *[]TimingEntry `json:"timings,omitempty"` +} + +// This class describes a trace filter, i.e. a set of criteria on whether or not a trace event should be emitted +type TraceFilter struct { + Area *string `json:"area,omitempty"` + ExceptionType *string `json:"exceptionType,omitempty"` + IsEnabled *bool `json:"isEnabled,omitempty"` + Layer *string `json:"layer,omitempty"` + Level *system.TraceLevel `json:"level,omitempty"` + Method *string `json:"method,omitempty"` + // Used to serialize additional identity information (display name, etc) to clients. Not set by default. Server-side callers should use OwnerId. + Owner *IdentityRef `json:"owner,omitempty"` + OwnerId *uuid.UUID `json:"ownerId,omitempty"` + Path *string `json:"path,omitempty"` + ProcessName *string `json:"processName,omitempty"` + Service *string `json:"service,omitempty"` + ServiceHost *uuid.UUID `json:"serviceHost,omitempty"` + TimeCreated *azuredevops.Time `json:"timeCreated,omitempty"` + TraceId *uuid.UUID `json:"traceId,omitempty"` + Tracepoint *int `json:"tracepoint,omitempty"` + Uri *string `json:"uri,omitempty"` + UserAgent *string `json:"userAgent,omitempty"` + UserLogin *string `json:"userLogin,omitempty"` +} + +type VssJsonCollectionWrapper struct { + // The number of serialized items. + Count *int `json:"count,omitempty"` + Value *[]interface{} `json:"value,omitempty"` +} + +type VssJsonCollectionWrapperBase struct { + // The number of serialized items. + Count *int `json:"count,omitempty"` +} + +// This is the type used for firing notifications intended for the subsystem in the Notifications SDK. For components that can't take a dependency on the Notifications SDK directly, they can use ITeamFoundationEventService.PublishNotification and the Notifications SDK ISubscriber implementation will get it. +type VssNotificationEvent struct { + // Optional: A list of actors which are additional identities with corresponding roles that are relevant to the event. + Actors *[]EventActor `json:"actors,omitempty"` + // Optional: A list of artifacts referenced or impacted by this event. + ArtifactUris *[]string `json:"artifactUris,omitempty"` + // Required: The event payload. If Data is a string, it must be in Json or XML format. Otherwise it must have a serialization format attribute. + Data interface{} `json:"data,omitempty"` + // Required: The name of the event. This event must be registered in the context it is being fired. + EventType *string `json:"eventType,omitempty"` + // How long before the event expires and will be cleaned up. The default is to use the system default. + ExpiresIn interface{} `json:"expiresIn,omitempty"` + // The id of the item, artifact, extension, project, etc. + ItemId *string `json:"itemId,omitempty"` + // How long to wait before processing this event. The default is to process immediately. + ProcessDelay interface{} `json:"processDelay,omitempty"` + // Optional: A list of scopes which are relevant to the event. + Scopes *[]EventScope `json:"scopes,omitempty"` + // This is the time the original source event for this VssNotificationEvent was created. For example, for something like a build completion notification SourceEventCreatedTime should be the time the build finished not the time this event was raised. + SourceEventCreatedTime *azuredevops.Time `json:"sourceEventCreatedTime,omitempty"` +} + +type WrappedException struct { + CustomProperties *map[string]interface{} `json:"customProperties,omitempty"` + ErrorCode *int `json:"errorCode,omitempty"` + EventId *int `json:"eventId,omitempty"` + HelpLink *string `json:"helpLink,omitempty"` + InnerException *WrappedException `json:"innerException,omitempty"` + Message *string `json:"message,omitempty"` + StackTrace *string `json:"stackTrace,omitempty"` + TypeKey *string `json:"typeKey,omitempty"` + TypeName *string `json:"typeName,omitempty"` +} diff --git a/vendor/modules.txt b/vendor/modules.txt index fbee9cd3c..f8e185db8 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -283,14 +283,20 @@ github.com/mattn/go-isatty # github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d ## explicit github.com/mgutz/ansi -# github.com/microsoft/azure-devops-go-api/azuredevops v1.0.0-b5 -## explicit; go 1.12 # github.com/microsoft/azure-devops-go-api/azuredevops/v7 v7.1.0 ## explicit; go 1.12 github.com/microsoft/azure-devops-go-api/azuredevops/v7 github.com/microsoft/azure-devops-go-api/azuredevops/v7/core +github.com/microsoft/azure-devops-go-api/azuredevops/v7/delegatedauthorization +github.com/microsoft/azure-devops-go-api/azuredevops/v7/forminput github.com/microsoft/azure-devops-go-api/azuredevops/v7/git +github.com/microsoft/azure-devops-go-api/azuredevops/v7/identity +github.com/microsoft/azure-devops-go-api/azuredevops/v7/notification +github.com/microsoft/azure-devops-go-api/azuredevops/v7/operations +github.com/microsoft/azure-devops-go-api/azuredevops/v7/policy github.com/microsoft/azure-devops-go-api/azuredevops/v7/servicehooks +github.com/microsoft/azure-devops-go-api/azuredevops/v7/system +github.com/microsoft/azure-devops-go-api/azuredevops/v7/webapi # github.com/mitchellh/mapstructure v1.5.0 ## explicit; go 1.14 github.com/mitchellh/mapstructure From e5f94893a554a7dff4db440df67f4f36bebecba9 Mon Sep 17 00:00:00 2001 From: ayesha arshad Date: Mon, 8 Apr 2024 19:59:37 +0200 Subject: [PATCH 04/16] fixed status --- go.sum | 5 ++++ pkg/apis/pipelinesascode/keys/keys.go | 2 ++ pkg/kubeinteraction/labels.go | 11 +++++++ pkg/provider/azuredevops/azuredevops.go | 36 ++++++++++------------- pkg/provider/azuredevops/parse_payload.go | 4 +-- pkg/reconciler/emit_metrics.go | 2 +- pkg/reconciler/event.go | 11 +++++++ 7 files changed, 47 insertions(+), 24 deletions(-) diff --git a/go.sum b/go.sum index 22823c030..2369ff821 100644 --- a/go.sum +++ b/go.sum @@ -887,6 +887,7 @@ github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm4 github.com/google/s2a-go v0.1.0/go.mod h1:OJpEgntRZo8ugHpF9hkoLJbS5dSI20XZeXJ9JVywLlM= github.com/google/s2a-go v0.1.3/go.mod h1:Ej+mSEMGRnqRzjc7VtF+jdBwYG5fuJfiZ8ELkjEwM0A= github.com/google/s2a-go v0.1.4/go.mod h1:Ej+mSEMGRnqRzjc7VtF+jdBwYG5fuJfiZ8ELkjEwM0A= +github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= @@ -1019,6 +1020,10 @@ github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5 github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE= github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d h1:5PJl274Y63IEHC+7izoQE9x6ikvDFZS2mDVS3drnohI= github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE= +github.com/microsoft/azure-devops-go-api/azuredevops v1.0.0-b5 h1:YH424zrwLTlyHSH/GzLMJeu5zhYVZSx5RQxGKm1h96s= +github.com/microsoft/azure-devops-go-api/azuredevops v1.0.0-b5/go.mod h1:PoGiBqKSQK1vIfQ+yVaFcGjDySHvym6FM1cNYnwzbrY= +github.com/microsoft/azure-devops-go-api/azuredevops/v7 v7.1.0 h1:mmJCWLe63QvybxhW1iBmQWEaCKdc4SKgALfTNZ+OphU= +github.com/microsoft/azure-devops-go-api/azuredevops/v7 v7.1.0/go.mod h1:mDunUZ1IUJdJIRHvFb+LPBUtxe3AYB5MI6BMXNg8194= github.com/minio/asm2plan9s v0.0.0-20200509001527-cdd76441f9d8/go.mod h1:mC1jAcsrzbxHt8iiaC+zU4b1ylILSosueou12R++wfY= github.com/minio/c2goasm v0.0.0-20190812172519-36a3d3bbc4f3/go.mod h1:RagcQ7I8IeTMnF8JTXieKnO4Z6JCsikNEzj0DwauVzE= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= diff --git a/pkg/apis/pipelinesascode/keys/keys.go b/pkg/apis/pipelinesascode/keys/keys.go index 151e4caf9..32f456c93 100644 --- a/pkg/apis/pipelinesascode/keys/keys.go +++ b/pkg/apis/pipelinesascode/keys/keys.go @@ -54,6 +54,8 @@ const ( MaxKeepRuns = pipelinesascode.GroupName + "/max-keep-runs" LogURL = pipelinesascode.GroupName + "/log-url" ExecutionOrder = pipelinesascode.GroupName + "/execution-order" + ProjectId = pipelinesascode.GroupName + "/project-id" + RepositoryId = pipelinesascode.GroupName + "/repository-id" // PublicGithubAPIURL default is "https://api.github.com" but it can be overridden by X-GitHub-Enterprise-Host header. PublicGithubAPIURL = "https://api.github.com" // InstallationURL gives us the Installation ID for the GitHub Application. diff --git a/pkg/kubeinteraction/labels.go b/pkg/kubeinteraction/labels.go index ee5d55f7c..888fa0f22 100644 --- a/pkg/kubeinteraction/labels.go +++ b/pkg/kubeinteraction/labels.go @@ -55,6 +55,8 @@ func AddLabelsAndAnnotations(event *info.Event, pipelineRun *tektonv1.PipelineRu keys.GitProvider: providerConfig.Name, keys.State: StateStarted, keys.ControllerInfo: fmt.Sprintf(`{"name":"%s","configmap":"%s","secret":"%s"}`, paramsinfo.Controller.Name, paramsinfo.Controller.Configmap, paramsinfo.Controller.Secret), + keys.RepositoryId: event.RepositoryId, + keys.ProjectId: event.ProjectId, } if event.PullRequestNumber != 0 { @@ -80,6 +82,15 @@ func AddLabelsAndAnnotations(event *info.Event, pipelineRun *tektonv1.PipelineRu annotations[keys.TargetProjectID] = strconv.Itoa(event.TargetProjectID) } + // Azure devops + + if event.RepositoryId != "" { + annotations[keys.RepositoryId] = event.RepositoryId + } + if event.ProjectId != "" { + annotations[keys.ProjectId] = event.ProjectId + } + for k, v := range labels { pipelineRun.Labels[k] = v } diff --git a/pkg/provider/azuredevops/azuredevops.go b/pkg/provider/azuredevops/azuredevops.go index b751bbf68..ad943bef6 100644 --- a/pkg/provider/azuredevops/azuredevops.go +++ b/pkg/provider/azuredevops/azuredevops.go @@ -6,7 +6,6 @@ import ( "fmt" "io" "log" - "os" "strings" "github.com/microsoft/azure-devops-go-api/azuredevops/v7" @@ -54,21 +53,16 @@ func (v *Provider) CreateStatus(ctx context.Context, event *info.Event, statusOp return fmt.Errorf("cannot set status on azuredevops no token or url set") } - logger := log.New(os.Stdout, "INFO: ", log.Ldate|log.Ltime|log.Lshortfile) - var gitStatusState git.GitStatusState - logger.Println("statusOpts.Conclusion ", statusOpts.Conclusion) - logger.Println("statusOpts.Status ", statusOpts.Status) - switch statusOpts.Conclusion { - case "succeeded": + case "success": statusOpts.Title = "Success" - statusOpts.Summary = "has successfully validated your commit." + statusOpts.Summary = "has successfully validated your commit." gitStatusState = git.GitStatusStateValues.Succeeded - case "failed": + case "failure": statusOpts.Title = "failure" - statusOpts.Summary = "has failed." + statusOpts.Summary = "has failed." gitStatusState = git.GitStatusStateValues.Failed case "pending": statusOpts.Title = "Pending" @@ -98,21 +92,21 @@ func (v *Provider) CreateStatus(ctx context.Context, event *info.Event, statusOp } statusOpts.Summary = fmt.Sprintf("%s%s %s", v.run.Info.Pac.ApplicationName, onPr, statusOpts.Summary) - logger.Println("statusOpts.Summary ", statusOpts.Summary) - - // Preparing the GitStatus object with the updated status + genreValue := "pipeline-as-code" gitStatus := git.GitStatus{ State: &gitStatusState, - TargetUrl: &event.HeadURL, + TargetUrl: &event.URL, Description: &statusOpts.Summary, Context: &git.GitStatusContext{ - Name: &statusOpts.Title, + Name: &statusOpts.Title, + Genre: &genreValue, }, } + // Posting the status to Azure DevOps if _, err := v.Client.CreateCommitStatus(ctx, git.CreateCommitStatusArgs{ - Project: &event.Organization, - RepositoryId: &event.Repository, + Project: &event.ProjectId, + RepositoryId: &event.RepositoryId, CommitId: &event.SHA, GitCommitStatusToCreate: &gitStatus, }); err != nil { @@ -132,7 +126,7 @@ func (v *Provider) GetCommitInfo(ctx context.Context, event *info.Event) error { "exiting... (hint: did you forget setting a secret on your repo?)") } - repository := event.Repository + RepositoryId := event.RepositoryId projectId := event.ProjectId sha := event.SHA @@ -142,7 +136,7 @@ func (v *Provider) GetCommitInfo(ctx context.Context, event *info.Event) error { refName := fmt.Sprintf("refs/heads/%s", event.HeadBranch) refs, err := v.Client.GetRefs(ctx, git.GetRefsArgs{ - RepositoryId: &repository, + RepositoryId: &RepositoryId, Filter: &refName, Project: &projectId, }) @@ -155,7 +149,7 @@ func (v *Provider) GetCommitInfo(ctx context.Context, event *info.Event) error { } } else if event.PullRequestNumber != 0 { pr, err := v.Client.GetPullRequest(ctx, git.GetPullRequestArgs{ - RepositoryId: &repository, + RepositoryId: &RepositoryId, PullRequestId: &event.PullRequestNumber, Project: &projectId, }) @@ -170,7 +164,7 @@ func (v *Provider) GetCommitInfo(ctx context.Context, event *info.Event) error { if sha != "" { commit, err := v.Client.GetCommit(ctx, git.GetCommitArgs{ CommitId: &sha, - RepositoryId: &repository, + RepositoryId: &RepositoryId, Project: &projectId, }) if err != nil { diff --git a/pkg/provider/azuredevops/parse_payload.go b/pkg/provider/azuredevops/parse_payload.go index 9681799e9..4a674b53d 100644 --- a/pkg/provider/azuredevops/parse_payload.go +++ b/pkg/provider/azuredevops/parse_payload.go @@ -51,7 +51,7 @@ func (v *Provider) ParsePayload(_ context.Context, _ *params.Run, request *http. processedEvent.EventType = *genericEvent.EventType processedEvent.Sender = pushEvent.PushedBy.DisplayName - processedEvent.Repository = pushEvent.Repository.Name + processedEvent.Repository = pushEvent.Repository.RemoteUrl processedEvent.RepositoryId = pushEvent.Repository.Id processedEvent.ProjectId = pushEvent.Repository.Project.Id processedEvent.Organization = pushEvent.Repository.Project.Name @@ -94,7 +94,7 @@ func (v *Provider) ParsePayload(_ context.Context, _ *params.Run, request *http. processedEvent.HeadURL = fmt.Sprintf("%s?version=GB%s", remoteUrl, headBranch) processedEvent.TriggerTarget = triggertype.PullRequest - processedEvent.Repository = prEvent.Repository.Name + processedEvent.Repository = prEvent.Repository.RemoteUrl processedEvent.RepositoryId = prEvent.Repository.Id processedEvent.ProjectId = prEvent.Repository.Project.Id processedEvent.URL = prEvent.Repository.RemoteUrl diff --git a/pkg/reconciler/emit_metrics.go b/pkg/reconciler/emit_metrics.go index af0769200..c07059bd0 100644 --- a/pkg/reconciler/emit_metrics.go +++ b/pkg/reconciler/emit_metrics.go @@ -18,7 +18,7 @@ func (r *Reconciler) emitMetrics(pr *tektonv1.PipelineRun) error { } else { gitProvider += "-webhook" } - case "gitlab", "gitea", "bitbucket-cloud", "bitbucket-server": + case "gitlab", "gitea", "bitbucket-cloud", "bitbucket-server", "azuredevops": gitProvider += "-webhook" default: return fmt.Errorf("no supported Git provider") diff --git a/pkg/reconciler/event.go b/pkg/reconciler/event.go index cf69c816e..d3fbd8a29 100644 --- a/pkg/reconciler/event.go +++ b/pkg/reconciler/event.go @@ -10,6 +10,7 @@ import ( "github.com/openshift-pipelines/pipelines-as-code/pkg/params/info" "github.com/openshift-pipelines/pipelines-as-code/pkg/params/triggertype" "github.com/openshift-pipelines/pipelines-as-code/pkg/provider" + "github.com/openshift-pipelines/pipelines-as-code/pkg/provider/azuredevops" "github.com/openshift-pipelines/pipelines-as-code/pkg/provider/bitbucketcloud" "github.com/openshift-pipelines/pipelines-as-code/pkg/provider/bitbucketserver" "github.com/openshift-pipelines/pipelines-as-code/pkg/provider/gitea" @@ -47,6 +48,8 @@ func (r *Reconciler) detectProvider(ctx context.Context, logger *zap.SugaredLogg provider = &bitbucketserver.Provider{} case "gitea": provider = &gitea.Provider{} + case "azuredevops": + provider = &azuredevops.Provider{} default: return nil, nil, fmt.Errorf("failed to detect provider for pipelinerun: %s : unknown provider", pr.GetName()) } @@ -94,5 +97,13 @@ func buildEventFromPipelineRun(pr *tektonv1.PipelineRun) *info.Event { if projectID, ok := prAnno[keys.TargetProjectID]; ok { event.TargetProjectID, _ = strconv.Atoi(projectID) } + + // AzureDevops + if projectID, ok := prAnno[keys.ProjectId]; ok { + event.ProjectId = projectID + } + if repositoryID, ok := prAnno[keys.RepositoryId]; ok { + event.RepositoryId = repositoryID + } return event } From 59a78f8b7485fb9a7e1c45b90a7d7251ee61b092 Mon Sep 17 00:00:00 2001 From: ayesha arshad Date: Thu, 11 Apr 2024 11:26:26 +0200 Subject: [PATCH 05/16] status on PR --- pkg/provider/azuredevops/acl.go | 4 +- pkg/provider/azuredevops/azuredevops.go | 112 +++++++++++++++++----- pkg/provider/azuredevops/parse_payload.go | 44 ++++++--- pkg/provider/azuredevops/types/types.go | 54 +++++++---- pkg/reconciler/event.go | 16 +++- 5 files changed, 170 insertions(+), 60 deletions(-) diff --git a/pkg/provider/azuredevops/acl.go b/pkg/provider/azuredevops/acl.go index beb11db88..a905fbb67 100644 --- a/pkg/provider/azuredevops/acl.go +++ b/pkg/provider/azuredevops/acl.go @@ -11,9 +11,9 @@ func (v *Provider) CheckPolicyAllowing(context.Context, *info.Event, []string) ( panic("unimplemented") } -// IsAllowed implements provider.Interface. +// ToDo: implement this function func (v *Provider) IsAllowed(context.Context, *info.Event) (bool, error) { - panic("unimplemented") + return true, nil } // IsAllowedOwnersFile implements provider.Interface. diff --git a/pkg/provider/azuredevops/azuredevops.go b/pkg/provider/azuredevops/azuredevops.go index ad943bef6..1acfea670 100644 --- a/pkg/provider/azuredevops/azuredevops.go +++ b/pkg/provider/azuredevops/azuredevops.go @@ -6,10 +6,12 @@ import ( "fmt" "io" "log" + "strconv" "strings" "github.com/microsoft/azure-devops-go-api/azuredevops/v7" "github.com/microsoft/azure-devops-go-api/azuredevops/v7/git" + "github.com/microsoft/azure-devops-go-api/azuredevops/v7/webapi" "github.com/openshift-pipelines/pipelines-as-code/pkg/apis/pipelinesascode/v1alpha1" "github.com/openshift-pipelines/pipelines-as-code/pkg/changedfiles" "github.com/openshift-pipelines/pipelines-as-code/pkg/events" @@ -84,6 +86,8 @@ func (v *Provider) CreateStatus(ctx context.Context, event *info.Event, statusOp if statusOpts.Status == "in_progress" { gitStatusState = git.GitStatusStateValues.Pending + statusOpts.Title = "In Progress" + statusOpts.Summary = "is in progress." } onPr := "" @@ -91,28 +95,101 @@ func (v *Provider) CreateStatus(ctx context.Context, event *info.Event, statusOp onPr = fmt.Sprintf("/%s", statusOpts.PipelineRunName) } statusOpts.Summary = fmt.Sprintf("%s%s %s", v.run.Info.Pac.ApplicationName, onPr, statusOpts.Summary) + genreValue := "PAC" + + switch event.EventType { + case "git.push": + gitStatus := git.GitStatus{ + State: &gitStatusState, + TargetUrl: &event.URL, + Description: &statusOpts.Summary, + Context: &git.GitStatusContext{ + Name: &statusOpts.Title, + Genre: &genreValue, + }, + } + commitStatusArgs := git.CreateCommitStatusArgs{ + Project: &event.ProjectId, + RepositoryId: &event.RepositoryId, + CommitId: &event.SHA, + GitCommitStatusToCreate: &gitStatus, + } + if _, err := v.Client.CreateCommitStatus(ctx, commitStatusArgs); err != nil { + return fmt.Errorf("failed to create commit status: %v", err) + } + case "git.pullrequest.created": + gitPullRequestStatusArgs := git.GetPullRequestStatusesArgs{ + PullRequestId: &event.PullRequestNumber, + Project: &event.ProjectId, + RepositoryId: &event.RepositoryId, + } - genreValue := "pipeline-as-code" - gitStatus := git.GitStatus{ - State: &gitStatusState, + status, err := v.Client.GetPullRequestStatuses(ctx, gitPullRequestStatusArgs) + if err != nil { + return fmt.Errorf("failed to fetch pull request statuses: %v", err) + } + + if status == nil || len(*status) == 0 { + _, err := createPRStatus(ctx, v, event, statusOpts, gitStatusState, genreValue) + if err != nil { + return err + } + } else { + + statusid := (*status)[0].Id + path := "/" + strconv.Itoa(*statusid) + + patchDocument := []webapi.JsonPatchOperation{ + { + Op: &webapi.OperationValues.Remove, + Path: &path, + Value: nil, + From: nil, + }, + } + + gitUpdatePullRequestStatus := git.UpdatePullRequestStatusesArgs{ + PatchDocument: &patchDocument, + Project: &event.ProjectId, + RepositoryId: &event.RepositoryId, + PullRequestId: &event.PullRequestNumber, + } + if err := v.Client.UpdatePullRequestStatuses(ctx, gitUpdatePullRequestStatus); err != nil { + return fmt.Errorf("failed to update pull request status: %v", err) + } + + _, err := createPRStatus(ctx, v, event, statusOpts, gitStatusState, genreValue) + if err != nil { + return err + } + } + } + + return nil +} + +func createPRStatus(ctx context.Context, v *Provider, event *info.Event, statusOpts provider.StatusOpts, gitStatusState git.GitStatusState, genreValue string) (bool, error) { + gitPullRequestStatus := git.GitPullRequestStatus{ + Id: &event.PullRequestNumber, TargetUrl: &event.URL, Description: &statusOpts.Summary, + State: &gitStatusState, Context: &git.GitStatusContext{ Name: &statusOpts.Title, Genre: &genreValue, }, } - // Posting the status to Azure DevOps - if _, err := v.Client.CreateCommitStatus(ctx, git.CreateCommitStatusArgs{ - Project: &event.ProjectId, - RepositoryId: &event.RepositoryId, - CommitId: &event.SHA, - GitCommitStatusToCreate: &gitStatus, - }); err != nil { - return fmt.Errorf("failed to create commit status: %v", err) + prStatusArgs := git.CreatePullRequestStatusArgs{ + PullRequestId: &event.PullRequestNumber, + Project: &event.ProjectId, + RepositoryId: &event.RepositoryId, + Status: &gitPullRequestStatus, } - return nil + if _, err := v.Client.CreatePullRequestStatus(ctx, prStatusArgs); err != nil { + return false, fmt.Errorf("failed to create pull request status: %v", err) + } + return true, nil } // CreateToken implements provider.Interface. @@ -193,7 +270,6 @@ func (v *Provider) GetFileInsideRepo(ctx context.Context, runevent *info.Event, panic("unimplemented") } -// GetFiles implements provider.Interface. func (v *Provider) GetFiles(ctx context.Context, event *info.Event) (changedfiles.ChangedFiles, error) { filesChanged, err := v.Client.GetChanges(ctx, git.GetChangesArgs{ @@ -239,7 +315,6 @@ func (v *Provider) GetFiles(ctx context.Context, event *info.Event) (changedfile return *changedFiles, nil } -// GetTaskURI TODO: Implement ME. func (v *Provider) GetTaskURI(ctx context.Context, event *info.Event, uri string) (bool, string, error) { return false, "", nil } @@ -354,14 +429,7 @@ func (v *Provider) SetClient(_ context.Context, run *params.Run, event *info.Eve return fmt.Errorf("no git_provider.secret has been set in the repo crd") } - // if event.Provider.URL == "" { - // return fmt.Errorf("no provider.url has been set in the repo crd") - // } - - //TODO get organizationUrl from provider.url - organizationUrl := "https://dev.azure.com/ayeshaarshad" - - // Create a connection to your organization + organizationUrl := event.Organization connection := azuredevops.NewPatConnection(organizationUrl, event.Provider.Token) ctx := context.Background() diff --git a/pkg/provider/azuredevops/parse_payload.go b/pkg/provider/azuredevops/parse_payload.go index 4a674b53d..78a71e406 100644 --- a/pkg/provider/azuredevops/parse_payload.go +++ b/pkg/provider/azuredevops/parse_payload.go @@ -5,6 +5,7 @@ import ( "encoding/json" "fmt" "net/http" + "regexp" "strings" "github.com/microsoft/azure-devops-go-api/azuredevops/v7/servicehooks" @@ -51,10 +52,17 @@ func (v *Provider) ParsePayload(_ context.Context, _ *params.Run, request *http. processedEvent.EventType = *genericEvent.EventType processedEvent.Sender = pushEvent.PushedBy.DisplayName + baseURL, err := extractBaseURL(pushEvent.Repository.RemoteUrl) + if err != nil { + fmt.Println("Error:", err) + return nil, fmt.Errorf("not able to extract organization url") + } + processedEvent.Organization = baseURL + fmt.Println("Base URL:", baseURL) + processedEvent.Repository = pushEvent.Repository.RemoteUrl processedEvent.RepositoryId = pushEvent.Repository.Id processedEvent.ProjectId = pushEvent.Repository.Project.Id - processedEvent.Organization = pushEvent.Repository.Project.Name processedEvent.URL = pushEvent.Repository.RemoteUrl processedEvent.DefaultBranch = pushEvent.Repository.DefaultBranch processedEvent.TriggerTarget = triggertype.Push @@ -62,7 +70,7 @@ func (v *Provider) ParsePayload(_ context.Context, _ *params.Run, request *http. processedEvent.BaseURL = pushEvent.Repository.Url // or it could be remoteUrl or it could be other; need to verify processedEvent.HeadURL = pushEvent.Repository.Url // or it could be remoteUrl or it could be othe; need to verify if len(pushEvent.RefUpdates) > 0 { - branchName := pushEvent.RefUpdates[0].Name + branchName := ExtractBranchName(pushEvent.RefUpdates[0].Name) processedEvent.BaseBranch = branchName processedEvent.HeadBranch = branchName } @@ -82,22 +90,27 @@ func (v *Provider) ParsePayload(_ context.Context, _ *params.Run, request *http. // Extract branch names from the ref names // Azure DevOps ref names are full references (refs/heads/branchName), so we'll extract the branch name - processedEvent.BaseBranch = prEvent.TargetRefName - processedEvent.HeadBranch = prEvent.SourceRefName + processedEvent.BaseBranch = ExtractBranchName(prEvent.TargetRefName) + processedEvent.HeadBranch = ExtractBranchName(prEvent.SourceRefName) processedEvent.DefaultBranch = prEvent.Repository.DefaultBranch // Constructing URLs - remoteUrl := prEvent.Repository.RemoteUrl - baseBranch := ExtractBranchName(prEvent.TargetRefName) - headBranch := ExtractBranchName(prEvent.SourceRefName) - processedEvent.BaseURL = fmt.Sprintf("%s?version=GB%s", remoteUrl, baseBranch) - processedEvent.HeadURL = fmt.Sprintf("%s?version=GB%s", remoteUrl, headBranch) + remoteUrl := *prEvent.Repository.WebUrl + processedEvent.BaseURL = fmt.Sprintf("%s?version=GB%s", remoteUrl, processedEvent.BaseBranch) + processedEvent.HeadURL = fmt.Sprintf("%s?version=GB%s", remoteUrl, processedEvent.HeadBranch) processedEvent.TriggerTarget = triggertype.PullRequest - processedEvent.Repository = prEvent.Repository.RemoteUrl + + baseURL, err := extractBaseURL(remoteUrl) + if err != nil { + fmt.Println("Error:", err) + return nil, fmt.Errorf("not able to extract organization url") + } + processedEvent.Organization = baseURL + processedEvent.Repository = *prEvent.Repository.WebUrl processedEvent.RepositoryId = prEvent.Repository.Id processedEvent.ProjectId = prEvent.Repository.Project.Id - processedEvent.URL = prEvent.Repository.RemoteUrl + processedEvent.URL = *prEvent.Repository.WebUrl processedEvent.Sender = prEvent.CreatedBy.DisplayName default: return nil, fmt.Errorf("event type %s is not supported", *genericEvent.EventType) @@ -115,3 +128,12 @@ func ExtractBranchName(refName string) string { } return refName // Return as-is if the format is unexpected } + +func extractBaseURL(url string) (string, error) { + re := regexp.MustCompile(`^(https://dev\.azure\.com/[^/]+)`) + matches := re.FindStringSubmatch(url) + if len(matches) < 2 { + return "", fmt.Errorf("base URL could not be extracted") + } + return matches[1], nil +} diff --git a/pkg/provider/azuredevops/types/types.go b/pkg/provider/azuredevops/types/types.go index 800873a44..445b6d1d7 100644 --- a/pkg/provider/azuredevops/types/types.go +++ b/pkg/provider/azuredevops/types/types.go @@ -7,21 +7,25 @@ import ( type PullRequestEventResource struct { Repository Repository `json:"repository"` PullRequestId int `json:"pullRequestId"` + CodeReviewId int `json:"codeReviewId,omitempty"` Status string `json:"status"` CreatedBy User `json:"createdBy"` CreationDate CustomTime `json:"creationDate"` Title string `json:"title"` - Description string `json:"description"` + Description string `json:"description,omitempty"` SourceRefName string `json:"sourceRefName"` TargetRefName string `json:"targetRefName"` MergeStatus string `json:"mergeStatus"` + IsDraft bool `json:"isDraft,omitempty"` MergeId string `json:"mergeId"` LastMergeSourceCommit Commit `json:"lastMergeSourceCommit"` LastMergeTargetCommit Commit `json:"lastMergeTargetCommit"` - LastMergeCommit Commit `json:"lastMergeCommit"` + LastMergeCommit Commit `json:"lastMergeCommit,omitempty"` Reviewers []User `json:"reviewers"` Url string `json:"url"` Links Links `json:"_links"` + SupportsIterations bool `json:"supportsIterations,omitempty"` + ArtifactId string `json:"artifactId,omitempty"` } type PushEventResource struct { @@ -35,11 +39,11 @@ type PushEventResource struct { } type Commit struct { - CommitId string `json:"commitId"` - Author User `json:"author"` - Committer User `json:"committer"` - Comment string `json:"comment"` - Url string `json:"url"` + CommitId string `json:"commitId,omitempty"` + Author User `json:"author,omitempty"` + Committer User `json:"committer,omitempty"` + Comment string `json:"comment,omitempty"` + Url string `json:"url,omitempty"` } type RefUpdate struct { @@ -49,12 +53,17 @@ type RefUpdate struct { } type Repository struct { - Id string `json:"id"` - Name string `json:"name"` - Url string `json:"url"` - Project Project `json:"project"` - DefaultBranch string `json:"defaultBranch"` - RemoteUrl string `json:"remoteUrl"` + Id string `json:"id"` + Name string `json:"name"` + Url string `json:"url"` + Project Project `json:"project"` + DefaultBranch string `json:"defaultBranch,omitempty"` + Size *int `json:"size,omitempty"` + RemoteUrl string `json:"remoteUrl"` + SshUrl *string `json:"sshUrl,omitempty"` + WebUrl *string `json:"webUrl,omitempty"` + IsDisabled *bool `json:"isDisabled,omitempty"` + IsInMaintenance *bool `json:"isInMaintenance,omitempty"` } type Project struct { @@ -62,18 +71,22 @@ type Project struct { Name string `json:"name"` Url string `json:"url"` State string `json:"state"` + Revision int `json:"revision,omitempty"` Visibility string `json:"visibility"` LastUpdateTime CustomTime `json:"lastUpdateTime"` } type User struct { - Name string `json:"name"` - Email string `json:"email"` - Date CustomTime `json:"date"` - DisplayName string `json:"displayName,omitempty"` // Optional fields use "omitempty" + Name string `json:"name,omitempty"` + Email string `json:"email,omitempty"` + Date CustomTime `json:"date,omitempty"` + DisplayName string `json:"displayName,omitempty"` + Url string `json:"url,omitempty"` + Links Links `json:"_links,omitempty"` Id string `json:"id,omitempty"` UniqueName string `json:"uniqueName,omitempty"` - ImageUrl string `json:"imageUrl,omitempty"` // Added to represent user's image URL + ImageUrl string `json:"imageUrl,omitempty"` + Descriptor string `json:"descriptor,omitempty"` } type ResourceContainers struct { @@ -87,8 +100,9 @@ type Container struct { } type Links struct { - Web Href `json:"web"` - Statuses Href `json:"statuses"` + Web Href `json:"web,omitempty"` + Statuses Href `json:"statuses,omitempty"` + Avatar Href `json:"avatar,omitempty"` } type Href struct { diff --git a/pkg/reconciler/event.go b/pkg/reconciler/event.go index d3fbd8a29..5771bdee2 100644 --- a/pkg/reconciler/event.go +++ b/pkg/reconciler/event.go @@ -99,11 +99,17 @@ func buildEventFromPipelineRun(pr *tektonv1.PipelineRun) *info.Event { } // AzureDevops - if projectID, ok := prAnno[keys.ProjectId]; ok { - event.ProjectId = projectID - } - if repositoryID, ok := prAnno[keys.RepositoryId]; ok { - event.RepositoryId = repositoryID + if pr.GetAnnotations()[keys.GitProvider] == "azuredevops" { + if organizationID, ok := prAnno[keys.URLOrg]; ok { + event.Organization = organizationID + } + if projectID, ok := prAnno[keys.ProjectId]; ok { + event.ProjectId = projectID + } + if repositoryID, ok := prAnno[keys.RepositoryId]; ok { + event.RepositoryId = repositoryID + } } + return event } From 4dfe5b948433d97a0d3919b1c12f72dec3f2255a Mon Sep 17 00:00:00 2001 From: ayesha arshad Date: Thu, 11 Apr 2024 11:46:54 +0200 Subject: [PATCH 06/16] added support for git.pullrequest.updated --- pkg/provider/azuredevops/azuredevops.go | 2 +- pkg/provider/azuredevops/detect.go | 2 +- pkg/provider/azuredevops/parse_payload.go | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pkg/provider/azuredevops/azuredevops.go b/pkg/provider/azuredevops/azuredevops.go index 1acfea670..78def00b6 100644 --- a/pkg/provider/azuredevops/azuredevops.go +++ b/pkg/provider/azuredevops/azuredevops.go @@ -117,7 +117,7 @@ func (v *Provider) CreateStatus(ctx context.Context, event *info.Event, statusOp if _, err := v.Client.CreateCommitStatus(ctx, commitStatusArgs); err != nil { return fmt.Errorf("failed to create commit status: %v", err) } - case "git.pullrequest.created": + case "git.pullrequest.created", "git.pullrequest.updated": gitPullRequestStatusArgs := git.GetPullRequestStatusesArgs{ PullRequestId: &event.PullRequestNumber, Project: &event.ProjectId, diff --git a/pkg/provider/azuredevops/detect.go b/pkg/provider/azuredevops/detect.go index a2fd2cf82..32c3346dc 100644 --- a/pkg/provider/azuredevops/detect.go +++ b/pkg/provider/azuredevops/detect.go @@ -35,7 +35,7 @@ func (v *Provider) Detect(req *http.Request, payload string, logger *zap.Sugared // Simplified switch, expand as needed based on the Azure DevOps events you handle switch eventType { - case "git.push", "git.pullrequest.created": + case "git.push", "git.pullrequest.created", "git.pullrequest.updated": return setLoggerAndProceed(true, "", nil) default: return setLoggerAndProceed(false, fmt.Sprintf("Unsupported event type: %s", eventType), nil) diff --git a/pkg/provider/azuredevops/parse_payload.go b/pkg/provider/azuredevops/parse_payload.go index 78a71e406..8e64f7ec8 100644 --- a/pkg/provider/azuredevops/parse_payload.go +++ b/pkg/provider/azuredevops/parse_payload.go @@ -75,7 +75,7 @@ func (v *Provider) ParsePayload(_ context.Context, _ *params.Run, request *http. processedEvent.HeadBranch = branchName } - case "git.pullrequest.created": + case "git.pullrequest.created", "git.pullrequest.updated": var prEvent types.PullRequestEventResource if err := json.Unmarshal(resourceBytes, &prEvent); err != nil { return nil, fmt.Errorf("error unmarshalling pull request event resource: %v", err) From 0f96dc9e1759e3b0ded9a0f49818154f6382aca2 Mon Sep 17 00:00:00 2001 From: ayesha arshad Date: Thu, 11 Apr 2024 12:26:19 +0200 Subject: [PATCH 07/16] minor cleanup --- pkg/provider/azuredevops/azuredevops.go | 91 +++++++++++-------------- 1 file changed, 38 insertions(+), 53 deletions(-) diff --git a/pkg/provider/azuredevops/azuredevops.go b/pkg/provider/azuredevops/azuredevops.go index 78def00b6..443349848 100644 --- a/pkg/provider/azuredevops/azuredevops.go +++ b/pkg/provider/azuredevops/azuredevops.go @@ -22,23 +22,6 @@ import ( "go.uber.org/zap" ) -const ( - taskStatusTemplate = ` - - - -{{- range $taskrun := .TaskRunList }} - - - -{{- end }} -
StatusDurationName
{{ formatCondition $taskrun.PipelineRunTaskRunStatus.Status.Conditions }}{{ formatDuration $taskrun.PipelineRunTaskRunStatus.Status.StartTime $taskrun.Status.CompletionTime }} - -{{ $taskrun.ConsoleLogURL }} - -
` -) - var _ provider.Interface = (*Provider)(nil) type Provider struct { @@ -49,7 +32,6 @@ type Provider struct { run *params.Run } -// CreateStatus implements provider.Interface. func (v *Provider) CreateStatus(ctx context.Context, event *info.Event, statusOpts provider.StatusOpts) error { if v.Client == nil { return fmt.Errorf("cannot set status on azuredevops no token or url set") @@ -130,45 +112,53 @@ func (v *Provider) CreateStatus(ctx context.Context, event *info.Event, statusOp } if status == nil || len(*status) == 0 { - _, err := createPRStatus(ctx, v, event, statusOpts, gitStatusState, genreValue) + err := createPRStatus(ctx, v, event, statusOpts, gitStatusState, genreValue) if err != nil { return err } } else { + //azure UpdatePullRequestStatuses only Support remove, so first remove the old status and then updated with new one - statusid := (*status)[0].Id - path := "/" + strconv.Itoa(*statusid) - - patchDocument := []webapi.JsonPatchOperation{ - { - Op: &webapi.OperationValues.Remove, - Path: &path, - Value: nil, - From: nil, - }, - } - - gitUpdatePullRequestStatus := git.UpdatePullRequestStatusesArgs{ - PatchDocument: &patchDocument, - Project: &event.ProjectId, - RepositoryId: &event.RepositoryId, - PullRequestId: &event.PullRequestNumber, - } - if err := v.Client.UpdatePullRequestStatuses(ctx, gitUpdatePullRequestStatus); err != nil { - return fmt.Errorf("failed to update pull request status: %v", err) + err := updatePRStatus(ctx, status, event, v) + if err != nil { + return err } - _, err := createPRStatus(ctx, v, event, statusOpts, gitStatusState, genreValue) + err = createPRStatus(ctx, v, event, statusOpts, gitStatusState, genreValue) if err != nil { return err } } } + return nil +} + +func updatePRStatus(ctx context.Context, status *[]git.GitPullRequestStatus, event *info.Event, v *Provider) error { + statusid := (*status)[0].Id + path := "/" + strconv.Itoa(*statusid) + + patchDocument := []webapi.JsonPatchOperation{ + { + Op: &webapi.OperationValues.Remove, + Path: &path, + Value: nil, + From: nil, + }, + } + gitUpdatePullRequestStatus := git.UpdatePullRequestStatusesArgs{ + PatchDocument: &patchDocument, + Project: &event.ProjectId, + RepositoryId: &event.RepositoryId, + PullRequestId: &event.PullRequestNumber, + } + if err := v.Client.UpdatePullRequestStatuses(ctx, gitUpdatePullRequestStatus); err != nil { + return fmt.Errorf("failed to update pull request status: %v", err) + } return nil } -func createPRStatus(ctx context.Context, v *Provider, event *info.Event, statusOpts provider.StatusOpts, gitStatusState git.GitStatusState, genreValue string) (bool, error) { +func createPRStatus(ctx context.Context, v *Provider, event *info.Event, statusOpts provider.StatusOpts, gitStatusState git.GitStatusState, genreValue string) error { gitPullRequestStatus := git.GitPullRequestStatus{ Id: &event.PullRequestNumber, TargetUrl: &event.URL, @@ -187,14 +177,13 @@ func createPRStatus(ctx context.Context, v *Provider, event *info.Event, statusO Status: &gitPullRequestStatus, } if _, err := v.Client.CreatePullRequestStatus(ctx, prStatusArgs); err != nil { - return false, fmt.Errorf("failed to create pull request status: %v", err) + return fmt.Errorf("failed to create pull request status: %v", err) } - return true, nil + return nil } -// CreateToken implements provider.Interface. func (v *Provider) CreateToken(context.Context, []string, *info.Event) (string, error) { - panic("unimplemented") + return "", nil } func (v *Provider) GetCommitInfo(ctx context.Context, event *info.Event) error { @@ -260,14 +249,13 @@ func (v *Provider) GetCommitInfo(ctx context.Context, event *info.Event) error { func (v *Provider) GetConfig() *info.ProviderConfig { return &info.ProviderConfig{ - TaskStatusTMPL: taskStatusTemplate, - Name: "azuredevops", + Name: "azuredevops", } } -// GetFileInsideRepo implements provider.Interface. +// GetFileInsideRepo TODO: Implement ME. func (v *Provider) GetFileInsideRepo(ctx context.Context, runevent *info.Event, path, target string) (string, error) { - panic("unimplemented") + return "", nil } func (v *Provider) GetFiles(ctx context.Context, event *info.Event) (changedfiles.ChangedFiles, error) { @@ -315,6 +303,7 @@ func (v *Provider) GetFiles(ctx context.Context, event *info.Event) (changedfile return *changedFiles, nil } +// GetTaskURI TODO: Implement ME. func (v *Provider) GetTaskURI(ctx context.Context, event *info.Event, uri string) (bool, string, error) { return false, "", nil } @@ -400,7 +389,6 @@ func (v *Provider) concatAllYamlFiles(ctx context.Context, entries *[]git.GitTre return allTemplates, nil } -// getObject fetches the content of a file from an Azure DevOps repository. func (v *Provider) getObject(ctx context.Context, repositoryID string, projectId string, sha string) ([]byte, error) { reader, err := v.Client.GetBlobContent(ctx, git.GetBlobContentArgs{ RepositoryId: &repositoryID, @@ -421,7 +409,6 @@ func (v *Provider) getObject(ctx context.Context, repositoryID string, projectId return content, nil } -// SetClient implements provider.Interface. func (v *Provider) SetClient(_ context.Context, run *params.Run, event *info.Event, _ *v1alpha1.Repository, _ *events.EventEmitter) error { var err error @@ -447,12 +434,10 @@ func (v *Provider) SetClient(_ context.Context, run *params.Run, event *info.Eve return nil } -// SetLogger implements provider.Interface. func (v *Provider) SetLogger(logger *zap.SugaredLogger) { v.Logger = logger } -// Validate implements provider.Interface. func (v *Provider) Validate(ctx context.Context, params *params.Run, event *info.Event) error { return nil } From 94d3f6a8e97027cda03c28587096716b504bdb8b Mon Sep 17 00:00:00 2001 From: ayesha arshad Date: Thu, 11 Apr 2024 15:02:53 +0200 Subject: [PATCH 08/16] added impl of IsAllowedOwnersFile and GetFileInsideRepo --- pkg/provider/azuredevops/acl.go | 29 ++++++++++--- pkg/provider/azuredevops/azuredevops.go | 58 +++++++++++++++++++++---- 2 files changed, 74 insertions(+), 13 deletions(-) diff --git a/pkg/provider/azuredevops/acl.go b/pkg/provider/azuredevops/acl.go index a905fbb67..4a7c409d5 100644 --- a/pkg/provider/azuredevops/acl.go +++ b/pkg/provider/azuredevops/acl.go @@ -2,13 +2,16 @@ package azuredevops import ( "context" + "fmt" + "strings" + "github.com/openshift-pipelines/pipelines-as-code/pkg/acl" "github.com/openshift-pipelines/pipelines-as-code/pkg/params/info" ) -// CheckPolicyAllowing implements provider.Interface. +// ToDo: implement this function func (v *Provider) CheckPolicyAllowing(context.Context, *info.Event, []string) (bool, string) { - panic("unimplemented") + return false, "" } // ToDo: implement this function @@ -16,7 +19,23 @@ func (v *Provider) IsAllowed(context.Context, *info.Event) (bool, error) { return true, nil } -// IsAllowedOwnersFile implements provider.Interface. -func (v *Provider) IsAllowedOwnersFile(context.Context, *info.Event) (bool, error) { - panic("unimplemented") +func (v *Provider) IsAllowedOwnersFile(ctx context.Context, event *info.Event) (bool, error) { + ownerContent, err := v.getFileFromDefaultBranch(ctx, "OWNERS", event) + if err != nil { + if strings.Contains(err.Error(), "cannot find") { + // no owner file, skipping + return false, nil + } + return false, err + } + + return acl.UserInOwnerFile(ownerContent, event.Sender) +} + +func (v *Provider) getFileFromDefaultBranch(ctx context.Context, path string, runevent *info.Event) (string, error) { + tektonyaml, err := v.GetFileInsideRepo(ctx, runevent, path, runevent.DefaultBranch) + if err != nil { + return "", fmt.Errorf("cannot find %s inside the %s branch: %w", path, runevent.DefaultBranch, err) + } + return tektonyaml, err } diff --git a/pkg/provider/azuredevops/azuredevops.go b/pkg/provider/azuredevops/azuredevops.go index 443349848..edc5a9c9f 100644 --- a/pkg/provider/azuredevops/azuredevops.go +++ b/pkg/provider/azuredevops/azuredevops.go @@ -253,11 +253,6 @@ func (v *Provider) GetConfig() *info.ProviderConfig { } } -// GetFileInsideRepo TODO: Implement ME. -func (v *Provider) GetFileInsideRepo(ctx context.Context, runevent *info.Event, path, target string) (string, error) { - return "", nil -} - func (v *Provider) GetFiles(ctx context.Context, event *info.Event) (changedfiles.ChangedFiles, error) { filesChanged, err := v.Client.GetChanges(ctx, git.GetChangesArgs{ @@ -308,25 +303,72 @@ func (v *Provider) GetTaskURI(ctx context.Context, event *info.Event, uri string return false, "", nil } +func (v *Provider) GetFileInsideRepo(ctx context.Context, runevent *info.Event, path, target string) (string, error) { + repositoryID := runevent.RepositoryId + ProjectId := runevent.ProjectId + + version := runevent.SHA + versionType := git.GitVersionTypeValues.Commit + if target != "" { + version = runevent.BaseBranch + versionType = git.GitVersionTypeValues.Branch + } + + gitVersionDescriptor := git.GitVersionDescriptor{ + Version: &version, + VersionType: &versionType, + } + + reader, err := v.Client.GetItemContent(ctx, git.GetItemContentArgs{ + RepositoryId: &repositoryID, + Project: &ProjectId, + Path: &path, + VersionDescriptor: &gitVersionDescriptor, + }) + if err != nil { + return "", err + } + defer reader.Close() + + // Read the content from the reader returned by GetBlobContent + content, err := io.ReadAll(reader) + if err != nil { + return "", err + } + + return string(content), nil + +} + // GetTektonDir implements provider.Interface. func (v *Provider) GetTektonDir(ctx context.Context, runevent *info.Event, path, provenance string) (string, error) { repositoryID := runevent.RepositoryId ProjectId := runevent.ProjectId var version string + var versionType git.GitVersionType if provenance == "default_branch" { version = runevent.DefaultBranch + versionType = git.GitVersionTypeValues.Branch v.Logger.Infof("Using Tekton definition from default branch: %s", version) } else { version = runevent.SHA + versionType = git.GitVersionTypeValues.Commit v.Logger.Infof("Using Tekton definition from commit ID: %s", version) } + + gitVersionDescriptor := git.GitVersionDescriptor{ + Version: &version, + VersionType: &versionType, + } + // Check if the path exists and is a directory item, err := v.Client.GetItem(ctx, git.GetItemArgs{ - RepositoryId: &repositoryID, - Project: &ProjectId, - Path: &path, + RepositoryId: &repositoryID, + Project: &ProjectId, + Path: &path, + VersionDescriptor: &gitVersionDescriptor, }) if err != nil { From f886d4f2d0dafa92687a350c982adca412869234 Mon Sep 17 00:00:00 2001 From: ayesha arshad Date: Thu, 11 Apr 2024 15:19:18 +0200 Subject: [PATCH 09/16] detect_test added --- pkg/provider/azuredevops/detect_test.go | 102 ++++++++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 pkg/provider/azuredevops/detect_test.go diff --git a/pkg/provider/azuredevops/detect_test.go b/pkg/provider/azuredevops/detect_test.go new file mode 100644 index 000000000..3478c4e40 --- /dev/null +++ b/pkg/provider/azuredevops/detect_test.go @@ -0,0 +1,102 @@ +package azuredevops + +import ( + "encoding/json" + "net/http" + "strings" + "testing" + + "github.com/microsoft/azure-devops-go-api/azuredevops/v7/servicehooks" + "github.com/stretchr/testify/assert" + "go.uber.org/zap/zaptest" +) + +func TestProvider_Detect(t *testing.T) { + gitPush := "git.push" + gitPRCreated := "git.pullrequest.created" + gitPRUpdated := "git.pullrequest.updated" + // Define more event types as needed + + tests := []struct { + name string + wantErr bool + wantErrString string + isADO bool + processReq bool + event servicehooks.Event + eventType string + wantReason string + }{ + { + name: "no event type", + eventType: "", + isADO: false, + processReq: false, + wantReason: "no azure devops event", + }, + { + name: "unsupported event type", + eventType: "build.completed", + isADO: true, + processReq: false, + wantReason: "Unsupported event type: build.completed", + }, + { + name: "git push event", + event: servicehooks.Event{ + EventType: &gitPush, + }, + eventType: "git.push", + isADO: true, + processReq: true, + }, + { + name: "pull request created event", + event: servicehooks.Event{ + EventType: &gitPRCreated, + }, + eventType: "git.pullrequest.created", + isADO: true, + processReq: true, + }, + { + name: "pull request updated event", + event: servicehooks.Event{ + EventType: &gitPRUpdated, + }, + eventType: "git.pullrequest.updated", + isADO: true, + processReq: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + logger := zaptest.NewLogger(t).Sugar() + payload, err := json.Marshal(tt.event) + assert.NoError(t, err) + + header := http.Header{} + header.Set("X-Azure-DevOps-EventType", tt.eventType) + req := &http.Request{Header: header} + + v := Provider{} // Assuming Provider is your Azure DevOps provider struct + isADO, processReq, _, reason, err := v.Detect(req, string(payload), logger) + + if tt.wantErr { + assert.Error(t, err) + if tt.wantErrString != "" { + assert.Contains(t, err.Error(), tt.wantErrString) + } + return + } + + assert.NoError(t, err) + assert.Equal(t, tt.isADO, isADO) + assert.Equal(t, tt.processReq, processReq) + if tt.wantReason != "" { + assert.True(t, strings.Contains(reason, tt.wantReason), "Reason should contain the expected message") + } + }) + } +} From 4a8b1e00bb53ab1c3c5fc226071ce55d718a7d8c Mon Sep 17 00:00:00 2001 From: ayesha arshad Date: Thu, 11 Apr 2024 15:51:07 +0200 Subject: [PATCH 10/16] parsepayload tests added --- .../azuredevops/parse_payload_test.go | 192 ++++++++++++++++++ 1 file changed, 192 insertions(+) create mode 100644 pkg/provider/azuredevops/parse_payload_test.go diff --git a/pkg/provider/azuredevops/parse_payload_test.go b/pkg/provider/azuredevops/parse_payload_test.go new file mode 100644 index 000000000..16c17e3e0 --- /dev/null +++ b/pkg/provider/azuredevops/parse_payload_test.go @@ -0,0 +1,192 @@ +package azuredevops + +import ( + "context" + "net/http" + "testing" + + "github.com/openshift-pipelines/pipelines-as-code/pkg/params" + "github.com/openshift-pipelines/pipelines-as-code/pkg/params/info" + "github.com/stretchr/testify/assert" +) + +func TestParsePayload(t *testing.T) { + // Mock request setup + mockRequest := &http.Request{} + + // Mock context + ctx := context.Background() + + tests := []struct { + name string + eventType string + payload string + wantErr bool + wantEvent *info.Event + }{ + { + name: "Git Push Event", + eventType: "git.push", + payload: `{ + "eventType": "git.push", + "resource": { + "commits": [ + { + "commitId": "71ee795c0163eedd69bdec49c1fad2403a49dd25", + "author": { + "name": "John" + }, + "comment": "Renamed pull_request.yaml to pullrequest.yaml", + "url": "https://dev.azure.com/xyz/_apis/git/repositories/f0f58388-1646-4faa-887f-15334faa07b6/commits/71ee795c0163eedd69bdec49c1fad2403a49dd25" + } + ], + "refUpdates": [ + { + "name": "refs/heads/main", + "oldObjectId": "2215f73bc8b77a5a62cf9d833ce411f243d26b0b", + "newObjectId": "71ee795c0163eedd69bdec49c1fad2403a49dd25" + } + ], + "repository": { + "id": "f0f58388-1646-4faa-887f-15334faa07b6", + "name": "TestProject", + "url": "https://dev.azure.com/xyz/_apis/git/repositories/f0f58388-1646-4faa-887f-15334faa07b6", + "project": { + "id": "31488f02-aad9-2222-4139-5a1f24bbbb86", + "name": "TestProject" + }, + "defaultBranch": "refs/heads/main", + "remoteUrl": "https://dev.azure.com/xyz/TestProject/_git/TestProject" + }, + "pushedBy": { + "displayName": "John" + } + } + }`, + wantErr: false, + wantEvent: &info.Event{ + SHA: "71ee795c0163eedd69bdec49c1fad2403a49dd25", + SHAURL: "https://dev.azure.com/xyz/_apis/git/repositories/f0f58388-1646-4faa-887f-15334faa07b6/commits/71ee795c0163eedd69bdec49c1fad2403a49dd25", + SHATitle: "Renamed pull_request.yaml to pullrequest.yaml", + Sender: "John", + EventType: "git.push", + Repository: "https://dev.azure.com/xyz/TestProject/_git/TestProject", + Organization: "TestProject", + }, + }, + { + name: "Git Pull Request Created Event", + eventType: "git.pullrequest.created", + payload: `{ + "eventType": "git.pullrequest.created", + "resource": { + "repository": { + "id": "f0f58388-1646-4faa-887f-15334faa07b6", + "name": "TestProject", + "url": "https://dev.azure.com/xyz/_apis/git/repositories/f0f58388-1646-4faa-887f-15334faa07b6", + "project": { + "id": "31488f02-aad9-2222-4139-5a1f24bbbb86", + "name": "TestProject" + }, + "webUrl": "https://dev.azure.com/xyz/TestProject/_git/TestProject" + }, + "pullRequestId": 2, + "title": "test", + "sourceRefName": "refs/heads/test", + "targetRefName": "refs/heads/main", + "createdBy": { + "displayName": "John" + } + } + }`, + wantErr: false, + wantEvent: &info.Event{ + PullRequestNumber: 2, + PullRequestTitle: "test", + BaseBranch: "main", + HeadBranch: "test", + EventType: "git.pullrequest.created", + Sender: "John", + Repository: "https://dev.azure.com/xyz/TestProject/_git/TestProject", + Organization: "TestProject", + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + v := Provider{} // Assuming this is your Azure DevOps provider + run := ¶ms.Run{} + + gotEvent, err := v.ParsePayload(ctx, run, mockRequest, tt.payload) + if (err != nil) != tt.wantErr { + t.Errorf("ParsePayload() error = %v, wantErr %v", err, tt.wantErr) + return + } + + assert.Equal(t, tt.wantEvent.EventType, gotEvent.EventType) + assert.Equal(t, tt.wantEvent.SHA, gotEvent.SHA) + // Add more assertions as needed + }) + } +} +func TestParsePayload_Errors(t *testing.T) { + tests := []struct { + name string + eventType string + payload string + wantErr bool + }{ + { + name: "Invalid JSON payload", + eventType: "git.push", + payload: `{"eventType": "git.push", "resource": {`, + wantErr: true, + }, + { + name: "Unsupported event type", + eventType: "build.completed", + payload: `{ + "eventType": "build.completed", + "resource": {} + }`, + wantErr: true, + }, + { + name: "Missing event type", + eventType: "", + payload: `{ + "resource": { + "commits": [ + {"commitId": "someId"} + ] + } + }`, + wantErr: true, + }, + { + name: "Bad event type field", + eventType: "git.push", + payload: `{ + "eventType": 123, + "resource": {} + }`, + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ctx := context.Background() + req := &http.Request{} + v := Provider{} + + _, err := v.ParsePayload(ctx, ¶ms.Run{}, req, tt.payload) + if tt.wantErr { + assert.Error(t, err, "ParsePayload() was supposed to error") + } else { + assert.NoError(t, err, "ParsePayload() was not supposed to error") + } + }) + } +} From abcc3dce8883aca1644268a02b6d87e15f4c1927 Mon Sep 17 00:00:00 2001 From: ayesha arshad Date: Tue, 16 Apr 2024 11:33:39 +0200 Subject: [PATCH 11/16] added more tests - Added new unit tests for Azure DevOps support. - Improved test coverage for parse payload functions. --- pkg/provider/azuredevops/azuredevops_test.go | 189 ++++++++++++++++++ pkg/provider/azuredevops/parse_payload.go | 2 +- .../azuredevops/parse_payload_test.go | 47 +++++ 3 files changed, 237 insertions(+), 1 deletion(-) create mode 100644 pkg/provider/azuredevops/azuredevops_test.go diff --git a/pkg/provider/azuredevops/azuredevops_test.go b/pkg/provider/azuredevops/azuredevops_test.go new file mode 100644 index 000000000..4d319f9e1 --- /dev/null +++ b/pkg/provider/azuredevops/azuredevops_test.go @@ -0,0 +1,189 @@ +package azuredevops + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" + + "github.com/microsoft/azure-devops-go-api/azuredevops/v7/git" + "github.com/openshift-pipelines/pipelines-as-code/pkg/params" + "github.com/openshift-pipelines/pipelines-as-code/pkg/params/info" + statusOpts "github.com/openshift-pipelines/pipelines-as-code/pkg/provider" + + "github.com/openshift-pipelines/pipelines-as-code/pkg/params/settings" +) + +type MockGitClient struct { + git.Client // Embedding git.Client for future-proofing against new methods + createCommitStatus func(ctx context.Context, args git.CreateCommitStatusArgs) (*git.GitStatus, error) + getPullRequestStatuses func(ctx context.Context, args git.GetPullRequestStatusesArgs) (*[]git.GitPullRequestStatus, error) + updatePullRequestStatus func(ctx context.Context, args git.UpdatePullRequestStatusesArgs) error + createPullRequestStatus func(ctx context.Context, args git.CreatePullRequestStatusArgs) (*git.GitPullRequestStatus, error) + createAnnotatedTag func(ctx context.Context, args git.CreateAnnotatedTagArgs) (*git.GitAnnotatedTag, error) +} + +func (m *MockGitClient) CreateCommitStatus(ctx context.Context, args git.CreateCommitStatusArgs) (*git.GitStatus, error) { + return m.createCommitStatus(ctx, args) +} + +func (m *MockGitClient) GetPullRequestStatuses(ctx context.Context, args git.GetPullRequestStatusesArgs) (*[]git.GitPullRequestStatus, error) { + return m.getPullRequestStatuses(ctx, args) +} + +func (m *MockGitClient) UpdatePullRequestStatuses(ctx context.Context, args git.UpdatePullRequestStatusesArgs) error { + return m.updatePullRequestStatus(ctx, args) +} + +func (m *MockGitClient) CreatePullRequestStatus(ctx context.Context, args git.CreatePullRequestStatusArgs) (*git.GitPullRequestStatus, error) { + return m.createPullRequestStatus(ctx, args) +} + +func (m *MockGitClient) CreateAnnotatedTag(ctx context.Context, args git.CreateAnnotatedTagArgs) (*git.GitAnnotatedTag, error) { + if m.createAnnotatedTag != nil { + return m.createAnnotatedTag(ctx, args) + } + return nil, nil +} + +func Setup(t *testing.T) (*MockGitClient, *http.ServeMux, func()) { + mux := http.NewServeMux() + server := httptest.NewServer(mux) + tearDown := func() { + server.Close() + } + + mockClient := &MockGitClient{ + createCommitStatus: func(ctx context.Context, args git.CreateCommitStatusArgs) (*git.GitStatus, error) { + return &git.GitStatus{}, nil + }, + getPullRequestStatuses: func(ctx context.Context, args git.GetPullRequestStatusesArgs) (*[]git.GitPullRequestStatus, error) { + return &[]git.GitPullRequestStatus{}, nil + }, + updatePullRequestStatus: func(ctx context.Context, args git.UpdatePullRequestStatusesArgs) error { + return nil + }, + createPullRequestStatus: func(ctx context.Context, args git.CreatePullRequestStatusArgs) (*git.GitPullRequestStatus, error) { + return &git.GitPullRequestStatus{}, nil + }, + createAnnotatedTag: func(ctx context.Context, args git.CreateAnnotatedTagArgs) (*git.GitAnnotatedTag, error) { + return &git.GitAnnotatedTag{}, nil + }, + } + + return mockClient, mux, tearDown +} + +func getProvider(mockClient *MockGitClient) *Provider { + provider := &Provider{ + Client: mockClient, + run: ¶ms.Run{ + Info: info.Info{ + Pac: &info.PacOpts{ + Settings: &settings.Settings{ + ApplicationName: "Pipelines as Code CI", + }, + }, + }, + }, + } + return provider +} + +func TestCreateStatus(t *testing.T) { + mockClient, _, tearDown := Setup(t) + defer tearDown() + + ctx := context.Background() + + provider := getProvider(mockClient) + + testCases := []struct { + name string + event *info.Event + statusOpts statusOpts.StatusOpts + expectError bool + }{ + { + name: "Git Push - Success", + event: &info.Event{ + EventType: "git.push", + }, + + statusOpts: statusOpts.StatusOpts{ + Conclusion: "success", + }, + expectError: false, + }, + { + name: "Git Push - Failed", + event: &info.Event{ + EventType: "git.push", + }, + statusOpts: statusOpts.StatusOpts{ + Conclusion: "failure", + }, + expectError: false, + }, + { + name: "Git Push - Pending", + event: &info.Event{ + EventType: "git.push", + }, + statusOpts: statusOpts.StatusOpts{ + Conclusion: "pending", + Status: "in_progress", + }, + expectError: false, + }, + { + name: "Git Pull Request - Success", + event: &info.Event{ + EventType: "git.pullrequest.created", + }, + statusOpts: statusOpts.StatusOpts{ + Conclusion: "success", + }, + expectError: false, + }, + { + name: "Git Pull Request - Pending", + event: &info.Event{ + EventType: "git.pullrequest.created", + }, + statusOpts: statusOpts.StatusOpts{ + Conclusion: "pending", + }, + expectError: false, + }, + { + name: "Git Push - Unknown status", + event: &info.Event{ + EventType: "git.push", + }, + statusOpts: statusOpts.StatusOpts{ + Conclusion: "abc", + }, + expectError: false, + }, + { + name: "Non-existent Resource", + event: &info.Event{ + EventType: "git.push", + }, + statusOpts: statusOpts.StatusOpts{ + Conclusion: "error", + }, + expectError: false, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + err := provider.CreateStatus(ctx, tc.event, tc.statusOpts) + if (err != nil) != tc.expectError { + t.Errorf("Test %s expected error: %v, got: %v", tc.name, tc.expectError, err) + } + }) + } +} diff --git a/pkg/provider/azuredevops/parse_payload.go b/pkg/provider/azuredevops/parse_payload.go index 8e64f7ec8..f7aae9ff2 100644 --- a/pkg/provider/azuredevops/parse_payload.go +++ b/pkg/provider/azuredevops/parse_payload.go @@ -68,7 +68,7 @@ func (v *Provider) ParsePayload(_ context.Context, _ *params.Run, request *http. processedEvent.TriggerTarget = triggertype.Push // Assuming the repository URL can serve as both BaseURL and HeadURL for viewing purposes processedEvent.BaseURL = pushEvent.Repository.Url // or it could be remoteUrl or it could be other; need to verify - processedEvent.HeadURL = pushEvent.Repository.Url // or it could be remoteUrl or it could be othe; need to verify + processedEvent.HeadURL = pushEvent.Repository.Url // or it could be remoteUrl or it could be other; need to verify if len(pushEvent.RefUpdates) > 0 { branchName := ExtractBranchName(pushEvent.RefUpdates[0].Name) processedEvent.BaseBranch = branchName diff --git a/pkg/provider/azuredevops/parse_payload_test.go b/pkg/provider/azuredevops/parse_payload_test.go index 16c17e3e0..f019c5125 100644 --- a/pkg/provider/azuredevops/parse_payload_test.go +++ b/pkg/provider/azuredevops/parse_payload_test.go @@ -190,3 +190,50 @@ func TestParsePayload_Errors(t *testing.T) { }) } } + +func TestExtractBranchName(t *testing.T) { + tests := []struct { + name string + refName string + wantBranch string + }{ + {"Standard ref name", "refs/heads/master", "master"}, + {"Nested branch name", "refs/heads/feature/new-feature", "new-feature"}, + {"Non-standard format", "master", "master"}, + {"Empty ref name", "", ""}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := ExtractBranchName(tt.refName); got != tt.wantBranch { + t.Errorf("ExtractBranchName(%q) = %q, want %q", tt.refName, got, tt.wantBranch) + } + }) + } +} + +func TestExtractBaseURL(t *testing.T) { + tests := []struct { + name string + url string + wantBaseURL string + wantErr bool + }{ + {"Valid Azure URL", "https://dev.azure.com/exampleOrg/exampleProject", "https://dev.azure.com/exampleOrg", false}, + {"Invalid Azure URL", "https://dev.azure.com/", "", true}, + {"Non-Azure URL", "https://example.com", "", true}, + {"Empty URL", "", "", true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := extractBaseURL(tt.url) + if (err != nil) != tt.wantErr { + t.Errorf("extractBaseURL(%q) expected error? %v, got error? %v", tt.url, tt.wantErr, err != nil) + } + if got != tt.wantBaseURL { + t.Errorf("extractBaseURL(%q) = %q, want %q", tt.url, got, tt.wantBaseURL) + } + }) + } +} From a1af7e8ed9dd71a25ca4dd43c5c9965ed0f7c2ad Mon Sep 17 00:00:00 2001 From: ayesha arshad Date: Tue, 16 Apr 2024 13:30:26 +0200 Subject: [PATCH 12/16] linting - Removed all go-lint issues --- pkg/apis/pipelinesascode/keys/keys.go | 4 +- pkg/kubeinteraction/labels.go | 12 +- pkg/params/info/events.go | 6 +- pkg/provider/azuredevops/acl.go | 4 +- pkg/provider/azuredevops/azuredevops.go | 126 ++++++++---------- pkg/provider/azuredevops/azuredevops_test.go | 14 +- pkg/provider/azuredevops/parse_payload.go | 58 ++++---- .../azuredevops/parse_payload_test.go | 1 + pkg/provider/azuredevops/types/change.go | 6 +- pkg/provider/azuredevops/types/types.go | 44 +++--- pkg/reconciler/event.go | 8 +- 11 files changed, 131 insertions(+), 152 deletions(-) diff --git a/pkg/apis/pipelinesascode/keys/keys.go b/pkg/apis/pipelinesascode/keys/keys.go index 32f456c93..268b4d2e1 100644 --- a/pkg/apis/pipelinesascode/keys/keys.go +++ b/pkg/apis/pipelinesascode/keys/keys.go @@ -54,8 +54,8 @@ const ( MaxKeepRuns = pipelinesascode.GroupName + "/max-keep-runs" LogURL = pipelinesascode.GroupName + "/log-url" ExecutionOrder = pipelinesascode.GroupName + "/execution-order" - ProjectId = pipelinesascode.GroupName + "/project-id" - RepositoryId = pipelinesascode.GroupName + "/repository-id" + ProjectID = pipelinesascode.GroupName + "/project-id" + RepositoryID = pipelinesascode.GroupName + "/repository-id" // PublicGithubAPIURL default is "https://api.github.com" but it can be overridden by X-GitHub-Enterprise-Host header. PublicGithubAPIURL = "https://api.github.com" // InstallationURL gives us the Installation ID for the GitHub Application. diff --git a/pkg/kubeinteraction/labels.go b/pkg/kubeinteraction/labels.go index 888fa0f22..25689a3b5 100644 --- a/pkg/kubeinteraction/labels.go +++ b/pkg/kubeinteraction/labels.go @@ -55,8 +55,8 @@ func AddLabelsAndAnnotations(event *info.Event, pipelineRun *tektonv1.PipelineRu keys.GitProvider: providerConfig.Name, keys.State: StateStarted, keys.ControllerInfo: fmt.Sprintf(`{"name":"%s","configmap":"%s","secret":"%s"}`, paramsinfo.Controller.Name, paramsinfo.Controller.Configmap, paramsinfo.Controller.Secret), - keys.RepositoryId: event.RepositoryId, - keys.ProjectId: event.ProjectId, + keys.RepositoryID: event.RepositoryID, + keys.ProjectID: event.ProjectID, } if event.PullRequestNumber != 0 { @@ -84,11 +84,11 @@ func AddLabelsAndAnnotations(event *info.Event, pipelineRun *tektonv1.PipelineRu // Azure devops - if event.RepositoryId != "" { - annotations[keys.RepositoryId] = event.RepositoryId + if event.RepositoryID != "" { + annotations[keys.RepositoryID] = event.RepositoryID } - if event.ProjectId != "" { - annotations[keys.ProjectId] = event.ProjectId + if event.ProjectID != "" { + annotations[keys.ProjectID] = event.ProjectID } for k, v := range labels { diff --git a/pkg/params/info/events.go b/pkg/params/info/events.go index 85f3e274b..4f68e6908 100644 --- a/pkg/params/info/events.go +++ b/pkg/params/info/events.go @@ -63,9 +63,9 @@ type Event struct { SourceProjectID int TargetProjectID int - //AzureDevops - RepositoryId string - ProjectId string + // AzureDevops + RepositoryID string + ProjectID string } type State struct { diff --git a/pkg/provider/azuredevops/acl.go b/pkg/provider/azuredevops/acl.go index 4a7c409d5..b2daaee84 100644 --- a/pkg/provider/azuredevops/acl.go +++ b/pkg/provider/azuredevops/acl.go @@ -9,12 +9,12 @@ import ( "github.com/openshift-pipelines/pipelines-as-code/pkg/params/info" ) -// ToDo: implement this function +// ToDo: implement this function. func (v *Provider) CheckPolicyAllowing(context.Context, *info.Event, []string) (bool, string) { return false, "" } -// ToDo: implement this function +// ToDo: implement this function. func (v *Provider) IsAllowed(context.Context, *info.Event) (bool, error) { return true, nil } diff --git a/pkg/provider/azuredevops/azuredevops.go b/pkg/provider/azuredevops/azuredevops.go index edc5a9c9f..4843c42d2 100644 --- a/pkg/provider/azuredevops/azuredevops.go +++ b/pkg/provider/azuredevops/azuredevops.go @@ -5,7 +5,6 @@ import ( "encoding/json" "fmt" "io" - "log" "strconv" "strings" @@ -91,24 +90,24 @@ func (v *Provider) CreateStatus(ctx context.Context, event *info.Event, statusOp }, } commitStatusArgs := git.CreateCommitStatusArgs{ - Project: &event.ProjectId, - RepositoryId: &event.RepositoryId, + Project: &event.ProjectID, + RepositoryId: &event.RepositoryID, CommitId: &event.SHA, GitCommitStatusToCreate: &gitStatus, } if _, err := v.Client.CreateCommitStatus(ctx, commitStatusArgs); err != nil { - return fmt.Errorf("failed to create commit status: %v", err) + return fmt.Errorf("failed to create commit status: %w", err) } case "git.pullrequest.created", "git.pullrequest.updated": gitPullRequestStatusArgs := git.GetPullRequestStatusesArgs{ PullRequestId: &event.PullRequestNumber, - Project: &event.ProjectId, - RepositoryId: &event.RepositoryId, + Project: &event.ProjectID, + RepositoryId: &event.RepositoryID, } status, err := v.Client.GetPullRequestStatuses(ctx, gitPullRequestStatusArgs) if err != nil { - return fmt.Errorf("failed to fetch pull request statuses: %v", err) + return fmt.Errorf("failed to fetch pull request statuses: %w", err) } if status == nil || len(*status) == 0 { @@ -117,7 +116,7 @@ func (v *Provider) CreateStatus(ctx context.Context, event *info.Event, statusOp return err } } else { - //azure UpdatePullRequestStatuses only Support remove, so first remove the old status and then updated with new one + // azure UpdatePullRequestStatuses only Support remove, so first remove the old status and then updated with new one err := updatePRStatus(ctx, status, event, v) if err != nil { @@ -148,12 +147,12 @@ func updatePRStatus(ctx context.Context, status *[]git.GitPullRequestStatus, eve gitUpdatePullRequestStatus := git.UpdatePullRequestStatusesArgs{ PatchDocument: &patchDocument, - Project: &event.ProjectId, - RepositoryId: &event.RepositoryId, + Project: &event.ProjectID, + RepositoryId: &event.RepositoryID, PullRequestId: &event.PullRequestNumber, } if err := v.Client.UpdatePullRequestStatuses(ctx, gitUpdatePullRequestStatus); err != nil { - return fmt.Errorf("failed to update pull request status: %v", err) + return fmt.Errorf("failed to update pull request status: %w", err) } return nil } @@ -172,12 +171,12 @@ func createPRStatus(ctx context.Context, v *Provider, event *info.Event, statusO prStatusArgs := git.CreatePullRequestStatusArgs{ PullRequestId: &event.PullRequestNumber, - Project: &event.ProjectId, - RepositoryId: &event.RepositoryId, + Project: &event.ProjectID, + RepositoryId: &event.RepositoryID, Status: &gitPullRequestStatus, } if _, err := v.Client.CreatePullRequestStatus(ctx, prStatusArgs); err != nil { - return fmt.Errorf("failed to create pull request status: %v", err) + return fmt.Errorf("failed to create pull request status: %w", err) } return nil } @@ -192,22 +191,21 @@ func (v *Provider) GetCommitInfo(ctx context.Context, event *info.Event) error { "exiting... (hint: did you forget setting a secret on your repo?)") } - RepositoryId := event.RepositoryId - projectId := event.ProjectId + RepositoryID := event.RepositoryID + projectID := event.ProjectID sha := event.SHA // If SHA is not provided, try to fetch it from the branch or pull request if sha == "" { if event.HeadBranch != "" { - refName := fmt.Sprintf("refs/heads/%s", event.HeadBranch) refs, err := v.Client.GetRefs(ctx, git.GetRefsArgs{ - RepositoryId: &RepositoryId, + RepositoryId: &RepositoryID, Filter: &refName, - Project: &projectId, + Project: &projectID, }) if err != nil { - return fmt.Errorf("failed to get branch info: %v", err) + return fmt.Errorf("failed to get branch info: %w", err) } // Assuming refs is a pointer to a slice, we check its length like this: if len(refs.Value) > 0 { @@ -215,12 +213,12 @@ func (v *Provider) GetCommitInfo(ctx context.Context, event *info.Event) error { } } else if event.PullRequestNumber != 0 { pr, err := v.Client.GetPullRequest(ctx, git.GetPullRequestArgs{ - RepositoryId: &RepositoryId, + RepositoryId: &RepositoryID, PullRequestId: &event.PullRequestNumber, - Project: &projectId, + Project: &projectID, }) if err != nil { - return fmt.Errorf("failed to get pull request: %v", err) + return fmt.Errorf("failed to get pull request: %w", err) } sha = *pr.LastMergeSourceCommit.CommitId event.HeadBranch = *pr.SourceRefName @@ -230,16 +228,15 @@ func (v *Provider) GetCommitInfo(ctx context.Context, event *info.Event) error { if sha != "" { commit, err := v.Client.GetCommit(ctx, git.GetCommitArgs{ CommitId: &sha, - RepositoryId: &RepositoryId, - Project: &projectId, + RepositoryId: &RepositoryID, + Project: &projectID, }) if err != nil { - return fmt.Errorf("failed to get commit: %v", err) + return fmt.Errorf("failed to get commit: %w", err) } event.SHAURL = *commit.RemoteUrl event.SHATitle = strings.Split(*commit.Comment, "\n\n")[0] event.SHA = *commit.CommitId - } else { return fmt.Errorf("unable to determine commit SHA") } @@ -254,44 +251,41 @@ func (v *Provider) GetConfig() *info.ProviderConfig { } func (v *Provider) GetFiles(ctx context.Context, event *info.Event) (changedfiles.ChangedFiles, error) { - filesChanged, err := v.Client.GetChanges(ctx, git.GetChangesArgs{ - RepositoryId: &event.RepositoryId, + RepositoryId: &event.RepositoryID, CommitId: &event.SHA, }) - if err != nil { - v.Logger.Errorf("Failed to get changes for commit %s: %v", &event.SHA, err) + v.Logger.Errorf("Failed to get changes for commit %s: %w", &event.SHA, err) } - changesJson, err := json.Marshal(filesChanged.Changes) + changesJSON, err := json.Marshal(filesChanged.Changes) if err != nil { - v.Logger.Errorf("Failed to marshal changes: %v", err) + v.Logger.Errorf("Failed to marshal changes: %w", err) return changedfiles.ChangedFiles{}, err } var changes []types.Change - if err := json.Unmarshal(changesJson, &changes); err != nil { - log.Fatalf("JSON Unmarshal error: %v", err) + if err := json.Unmarshal(changesJSON, &changes); err != nil { + v.Logger.Errorf("JSON Unmarshal error: %w", err) } changedFiles := &changedfiles.ChangedFiles{} for _, c := range changes { - switch c.ChangeType { case "edit": - changedFiles.All = append(changedFiles.Added, c.Item.Path) - changedFiles.Modified = append(changedFiles.Added, c.Item.Path) + changedFiles.All = append(changedFiles.All, c.Item.Path) + changedFiles.Modified = append(changedFiles.Modified, c.Item.Path) case "add": - changedFiles.All = append(changedFiles.Added, c.Item.Path) + changedFiles.All = append(changedFiles.All, c.Item.Path) changedFiles.Added = append(changedFiles.Added, c.Item.Path) case "delete": - changedFiles.All = append(changedFiles.Added, c.Item.Path) - changedFiles.Deleted = append(changedFiles.Added, c.Item.Path) + changedFiles.All = append(changedFiles.All, c.Item.Path) + changedFiles.Deleted = append(changedFiles.Deleted, c.Item.Path) case "rename": - changedFiles.All = append(changedFiles.Added, c.Item.Path) - changedFiles.Renamed = append(changedFiles.Added, c.Item.Path) + changedFiles.All = append(changedFiles.All, c.Item.Path) + changedFiles.Renamed = append(changedFiles.Renamed, c.Item.Path) } } @@ -299,13 +293,13 @@ func (v *Provider) GetFiles(ctx context.Context, event *info.Event) (changedfile } // GetTaskURI TODO: Implement ME. -func (v *Provider) GetTaskURI(ctx context.Context, event *info.Event, uri string) (bool, string, error) { +func (v *Provider) GetTaskURI(context.Context, *info.Event, string) (bool, string, error) { return false, "", nil } func (v *Provider) GetFileInsideRepo(ctx context.Context, runevent *info.Event, path, target string) (string, error) { - repositoryID := runevent.RepositoryId - ProjectId := runevent.ProjectId + repositoryID := runevent.RepositoryID + ProjectID := runevent.ProjectID version := runevent.SHA versionType := git.GitVersionTypeValues.Commit @@ -321,7 +315,7 @@ func (v *Provider) GetFileInsideRepo(ctx context.Context, runevent *info.Event, reader, err := v.Client.GetItemContent(ctx, git.GetItemContentArgs{ RepositoryId: &repositoryID, - Project: &ProjectId, + Project: &ProjectID, Path: &path, VersionDescriptor: &gitVersionDescriptor, }) @@ -337,14 +331,12 @@ func (v *Provider) GetFileInsideRepo(ctx context.Context, runevent *info.Event, } return string(content), nil - } // GetTektonDir implements provider.Interface. func (v *Provider) GetTektonDir(ctx context.Context, runevent *info.Event, path, provenance string) (string, error) { - - repositoryID := runevent.RepositoryId - ProjectId := runevent.ProjectId + repositoryID := runevent.RepositoryID + ProjectID := runevent.ProjectID var version string var versionType git.GitVersionType @@ -366,13 +358,12 @@ func (v *Provider) GetTektonDir(ctx context.Context, runevent *info.Event, path, // Check if the path exists and is a directory item, err := v.Client.GetItem(ctx, git.GetItemArgs{ RepositoryId: &repositoryID, - Project: &ProjectId, + Project: &ProjectID, Path: &path, VersionDescriptor: &gitVersionDescriptor, }) - if err != nil { - return "", fmt.Errorf("failed to fetch the item: %v", err) + return "", fmt.Errorf("failed to fetch the item: %w", err) } if item == nil { @@ -382,37 +373,33 @@ func (v *Provider) GetTektonDir(ctx context.Context, runevent *info.Event, path, // Get the SHA of the directory and fetch the tree tree, err := v.Client.GetTree(ctx, git.GetTreeArgs{ RepositoryId: &repositoryID, - Project: &ProjectId, + Project: &ProjectID, Sha1: item.ObjectId, Recursive: toBoolPtr(true), }) - if err != nil { - return "", fmt.Errorf("failed to fetch the tree: %v", err) + return "", fmt.Errorf("failed to fetch the tree: %w", err) } // Concatenate all YAML files found within the tree entries - result, err := v.concatAllYamlFiles(ctx, tree.TreeEntries, repositoryID, ProjectId) + result, err := v.concatAllYamlFiles(ctx, tree.TreeEntries, repositoryID, ProjectID) if err != nil { return "", err } return result, nil - } func toBoolPtr(b bool) *bool { return &b } -func (v *Provider) concatAllYamlFiles(ctx context.Context, entries *[]git.GitTreeEntryRef, repositoryID string, projectId string) (string, error) { +func (v *Provider) concatAllYamlFiles(ctx context.Context, entries *[]git.GitTreeEntryRef, repositoryID, projectID string) (string, error) { var allTemplates string for _, entry := range *entries { if *entry.GitObjectType == git.GitObjectTypeValues.Blob && (strings.HasSuffix(*entry.RelativePath, ".yaml") || strings.HasSuffix(*entry.RelativePath, ".yml")) { - // Use the object ID (SHA) of the blob to fetch its content - data, err := v.getObject(ctx, repositoryID, projectId, *entry.ObjectId) - + data, err := v.getObject(ctx, repositoryID, projectID, *entry.ObjectId) if err != nil { return "", err } @@ -431,10 +418,10 @@ func (v *Provider) concatAllYamlFiles(ctx context.Context, entries *[]git.GitTre return allTemplates, nil } -func (v *Provider) getObject(ctx context.Context, repositoryID string, projectId string, sha string) ([]byte, error) { +func (v *Provider) getObject(ctx context.Context, repositoryID, projectID, sha string) ([]byte, error) { reader, err := v.Client.GetBlobContent(ctx, git.GetBlobContentArgs{ RepositoryId: &repositoryID, - Project: &projectId, + Project: &projectID, Sha1: &sha, }) if err != nil { @@ -458,13 +445,10 @@ func (v *Provider) SetClient(_ context.Context, run *params.Run, event *info.Eve return fmt.Errorf("no git_provider.secret has been set in the repo crd") } - organizationUrl := event.Organization - connection := azuredevops.NewPatConnection(organizationUrl, event.Provider.Token) - + organizationURL := event.Organization + connection := azuredevops.NewPatConnection(organizationURL, event.Provider.Token) ctx := context.Background() - v.Client, err = git.NewClient(ctx, connection) - if err != nil { return err } @@ -480,6 +464,6 @@ func (v *Provider) SetLogger(logger *zap.SugaredLogger) { v.Logger = logger } -func (v *Provider) Validate(ctx context.Context, params *params.Run, event *info.Event) error { +func (v *Provider) Validate(context.Context, *params.Run, *info.Event) error { return nil } diff --git a/pkg/provider/azuredevops/azuredevops_test.go b/pkg/provider/azuredevops/azuredevops_test.go index 4d319f9e1..3e14019df 100644 --- a/pkg/provider/azuredevops/azuredevops_test.go +++ b/pkg/provider/azuredevops/azuredevops_test.go @@ -46,7 +46,7 @@ func (m *MockGitClient) CreateAnnotatedTag(ctx context.Context, args git.CreateA return nil, nil } -func Setup(t *testing.T) (*MockGitClient, *http.ServeMux, func()) { +func Setup() (*MockGitClient, *http.ServeMux, func()) { mux := http.NewServeMux() server := httptest.NewServer(mux) tearDown := func() { @@ -54,19 +54,19 @@ func Setup(t *testing.T) (*MockGitClient, *http.ServeMux, func()) { } mockClient := &MockGitClient{ - createCommitStatus: func(ctx context.Context, args git.CreateCommitStatusArgs) (*git.GitStatus, error) { + createCommitStatus: func(context.Context, git.CreateCommitStatusArgs) (*git.GitStatus, error) { return &git.GitStatus{}, nil }, - getPullRequestStatuses: func(ctx context.Context, args git.GetPullRequestStatusesArgs) (*[]git.GitPullRequestStatus, error) { + getPullRequestStatuses: func(context.Context, git.GetPullRequestStatusesArgs) (*[]git.GitPullRequestStatus, error) { return &[]git.GitPullRequestStatus{}, nil }, - updatePullRequestStatus: func(ctx context.Context, args git.UpdatePullRequestStatusesArgs) error { + updatePullRequestStatus: func(context.Context, git.UpdatePullRequestStatusesArgs) error { return nil }, - createPullRequestStatus: func(ctx context.Context, args git.CreatePullRequestStatusArgs) (*git.GitPullRequestStatus, error) { + createPullRequestStatus: func(context.Context, git.CreatePullRequestStatusArgs) (*git.GitPullRequestStatus, error) { return &git.GitPullRequestStatus{}, nil }, - createAnnotatedTag: func(ctx context.Context, args git.CreateAnnotatedTagArgs) (*git.GitAnnotatedTag, error) { + createAnnotatedTag: func(context.Context, git.CreateAnnotatedTagArgs) (*git.GitAnnotatedTag, error) { return &git.GitAnnotatedTag{}, nil }, } @@ -91,7 +91,7 @@ func getProvider(mockClient *MockGitClient) *Provider { } func TestCreateStatus(t *testing.T) { - mockClient, _, tearDown := Setup(t) + mockClient, _, tearDown := Setup() defer tearDown() ctx := context.Background() diff --git a/pkg/provider/azuredevops/parse_payload.go b/pkg/provider/azuredevops/parse_payload.go index f7aae9ff2..3c447de09 100644 --- a/pkg/provider/azuredevops/parse_payload.go +++ b/pkg/provider/azuredevops/parse_payload.go @@ -15,14 +15,11 @@ import ( types "github.com/openshift-pipelines/pipelines-as-code/pkg/provider/azuredevops/types" ) -func (v *Provider) ParsePayload(_ context.Context, _ *params.Run, request *http.Request, - payload string, -) (*info.Event, error) { - +func (v *Provider) ParsePayload(_ context.Context, _ *params.Run, _ *http.Request, payload string) (*info.Event, error) { var genericEvent servicehooks.Event err := json.Unmarshal([]byte(payload), &genericEvent) if err != nil { - return nil, fmt.Errorf("error unmarshalling payload into Event: %v", err) + return nil, fmt.Errorf("error unmarshalling payload into Event: %w", err) } if genericEvent.EventType == nil { @@ -34,7 +31,7 @@ func (v *Provider) ParsePayload(_ context.Context, _ *params.Run, request *http. resourceBytes, err := json.Marshal(genericEvent.Resource) if err != nil { - return nil, fmt.Errorf("error marshalling resource: %v", err) + return nil, fmt.Errorf("error marshalling resource: %w", err) } switch *genericEvent.EventType { @@ -42,33 +39,31 @@ func (v *Provider) ParsePayload(_ context.Context, _ *params.Run, request *http. var pushEvent types.PushEventResource if err := json.Unmarshal(resourceBytes, &pushEvent); err != nil { - return nil, fmt.Errorf("error unmarshalling push event resource: %v", err) + return nil, fmt.Errorf("error unmarshalling push event resource: %w", err) } if len(pushEvent.Commits) > 0 { - processedEvent.SHA = pushEvent.Commits[0].CommitId - processedEvent.SHAURL = pushEvent.Commits[0].Url + processedEvent.SHA = pushEvent.Commits[0].CommitID + processedEvent.SHAURL = pushEvent.Commits[0].URL processedEvent.SHATitle = pushEvent.Commits[0].Comment } processedEvent.EventType = *genericEvent.EventType processedEvent.Sender = pushEvent.PushedBy.DisplayName - baseURL, err := extractBaseURL(pushEvent.Repository.RemoteUrl) + baseURL, err := extractBaseURL(pushEvent.Repository.RemoteURL) if err != nil { - fmt.Println("Error:", err) return nil, fmt.Errorf("not able to extract organization url") } processedEvent.Organization = baseURL - fmt.Println("Base URL:", baseURL) - processedEvent.Repository = pushEvent.Repository.RemoteUrl - processedEvent.RepositoryId = pushEvent.Repository.Id - processedEvent.ProjectId = pushEvent.Repository.Project.Id - processedEvent.URL = pushEvent.Repository.RemoteUrl + processedEvent.Repository = pushEvent.Repository.RemoteURL + processedEvent.RepositoryID = pushEvent.Repository.ID + processedEvent.ProjectID = pushEvent.Repository.Project.ID + processedEvent.URL = pushEvent.Repository.RemoteURL processedEvent.DefaultBranch = pushEvent.Repository.DefaultBranch processedEvent.TriggerTarget = triggertype.Push // Assuming the repository URL can serve as both BaseURL and HeadURL for viewing purposes - processedEvent.BaseURL = pushEvent.Repository.Url // or it could be remoteUrl or it could be other; need to verify - processedEvent.HeadURL = pushEvent.Repository.Url // or it could be remoteUrl or it could be other; need to verify + processedEvent.BaseURL = pushEvent.Repository.URL // or it could be remoteUrl or it could be other; need to verify + processedEvent.HeadURL = pushEvent.Repository.URL // or it could be remoteUrl or it could be other; need to verify if len(pushEvent.RefUpdates) > 0 { branchName := ExtractBranchName(pushEvent.RefUpdates[0].Name) processedEvent.BaseBranch = branchName @@ -78,14 +73,14 @@ func (v *Provider) ParsePayload(_ context.Context, _ *params.Run, request *http. case "git.pullrequest.created", "git.pullrequest.updated": var prEvent types.PullRequestEventResource if err := json.Unmarshal(resourceBytes, &prEvent); err != nil { - return nil, fmt.Errorf("error unmarshalling pull request event resource: %v", err) + return nil, fmt.Errorf("error unmarshalling pull request event resource: %w", err) } processedEvent.EventType = *genericEvent.EventType - processedEvent.PullRequestNumber = prEvent.PullRequestId + processedEvent.PullRequestNumber = prEvent.PullRequestID processedEvent.PullRequestTitle = prEvent.Title - processedEvent.SHA = prEvent.LastMergeSourceCommit.CommitId - processedEvent.SHAURL = prEvent.LastMergeSourceCommit.Url + processedEvent.SHA = prEvent.LastMergeSourceCommit.CommitID + processedEvent.SHAURL = prEvent.LastMergeSourceCommit.URL processedEvent.SHATitle = prEvent.LastMergeSourceCommit.Comment // Extract branch names from the ref names @@ -95,22 +90,21 @@ func (v *Provider) ParsePayload(_ context.Context, _ *params.Run, request *http. processedEvent.DefaultBranch = prEvent.Repository.DefaultBranch // Constructing URLs - remoteUrl := *prEvent.Repository.WebUrl - processedEvent.BaseURL = fmt.Sprintf("%s?version=GB%s", remoteUrl, processedEvent.BaseBranch) - processedEvent.HeadURL = fmt.Sprintf("%s?version=GB%s", remoteUrl, processedEvent.HeadBranch) + remoteURL := *prEvent.Repository.WebURL + processedEvent.BaseURL = fmt.Sprintf("%s?version=GB%s", remoteURL, processedEvent.BaseBranch) + processedEvent.HeadURL = fmt.Sprintf("%s?version=GB%s", remoteURL, processedEvent.HeadBranch) processedEvent.TriggerTarget = triggertype.PullRequest - baseURL, err := extractBaseURL(remoteUrl) + baseURL, err := extractBaseURL(remoteURL) if err != nil { - fmt.Println("Error:", err) return nil, fmt.Errorf("not able to extract organization url") } processedEvent.Organization = baseURL - processedEvent.Repository = *prEvent.Repository.WebUrl - processedEvent.RepositoryId = prEvent.Repository.Id - processedEvent.ProjectId = prEvent.Repository.Project.Id - processedEvent.URL = *prEvent.Repository.WebUrl + processedEvent.Repository = *prEvent.Repository.WebURL + processedEvent.RepositoryID = prEvent.Repository.ID + processedEvent.ProjectID = prEvent.Repository.Project.ID + processedEvent.URL = *prEvent.Repository.WebURL processedEvent.Sender = prEvent.CreatedBy.DisplayName default: return nil, fmt.Errorf("event type %s is not supported", *genericEvent.EventType) @@ -120,7 +114,7 @@ func (v *Provider) ParsePayload(_ context.Context, _ *params.Run, request *http. } // ExtractBranchName extracts the branch name from a full ref name. -// E.g., "refs/heads/master" -> "master" +// E.g., "refs/heads/master" -> "master". func ExtractBranchName(refName string) string { parts := strings.Split(refName, "/") if len(parts) > 2 { diff --git a/pkg/provider/azuredevops/parse_payload_test.go b/pkg/provider/azuredevops/parse_payload_test.go index f019c5125..04af74686 100644 --- a/pkg/provider/azuredevops/parse_payload_test.go +++ b/pkg/provider/azuredevops/parse_payload_test.go @@ -130,6 +130,7 @@ func TestParsePayload(t *testing.T) { }) } } + func TestParsePayload_Errors(t *testing.T) { tests := []struct { name string diff --git a/pkg/provider/azuredevops/types/change.go b/pkg/provider/azuredevops/types/change.go index 73dcccd15..3a87c6cfa 100644 --- a/pkg/provider/azuredevops/types/change.go +++ b/pkg/provider/azuredevops/types/change.go @@ -1,11 +1,11 @@ package azuredevops type Item struct { - CommitId string `json:"commitId"` + CommitID string `json:"commitId"` GitObjectType string `json:"gitObjectType"` IsFolder bool `json:"isFolder"` - ObjectId string `json:"objectId"` - OriginalObjectId string `json:"originalObjectId"` + ObjectID string `json:"objectId"` + OriginalObjectID string `json:"originalObjectId"` Path string `json:"path"` URL string `json:"url"` } diff --git a/pkg/provider/azuredevops/types/types.go b/pkg/provider/azuredevops/types/types.go index 445b6d1d7..ddde82076 100644 --- a/pkg/provider/azuredevops/types/types.go +++ b/pkg/provider/azuredevops/types/types.go @@ -6,8 +6,8 @@ import ( type PullRequestEventResource struct { Repository Repository `json:"repository"` - PullRequestId int `json:"pullRequestId"` - CodeReviewId int `json:"codeReviewId,omitempty"` + PullRequestID int `json:"pullRequestId"` + CodeReviewID int `json:"codeReviewId,omitempty"` Status string `json:"status"` CreatedBy User `json:"createdBy"` CreationDate CustomTime `json:"creationDate"` @@ -17,15 +17,15 @@ type PullRequestEventResource struct { TargetRefName string `json:"targetRefName"` MergeStatus string `json:"mergeStatus"` IsDraft bool `json:"isDraft,omitempty"` - MergeId string `json:"mergeId"` + MergeID string `json:"mergeId"` LastMergeSourceCommit Commit `json:"lastMergeSourceCommit"` LastMergeTargetCommit Commit `json:"lastMergeTargetCommit"` LastMergeCommit Commit `json:"lastMergeCommit,omitempty"` Reviewers []User `json:"reviewers"` - Url string `json:"url"` + URL string `json:"url"` Links Links `json:"_links"` SupportsIterations bool `json:"supportsIterations,omitempty"` - ArtifactId string `json:"artifactId,omitempty"` + ArtifactID string `json:"artifactId,omitempty"` } type PushEventResource struct { @@ -33,43 +33,43 @@ type PushEventResource struct { RefUpdates []RefUpdate `json:"refUpdates"` Repository Repository `json:"repository"` PushedBy User `json:"pushedBy"` - PushId int `json:"pushId"` + PushID int `json:"pushId"` Date CustomTime `json:"date"` - Url string `json:"url"` + URL string `json:"url"` } type Commit struct { - CommitId string `json:"commitId,omitempty"` + CommitID string `json:"commitId,omitempty"` Author User `json:"author,omitempty"` Committer User `json:"committer,omitempty"` Comment string `json:"comment,omitempty"` - Url string `json:"url,omitempty"` + URL string `json:"url,omitempty"` } type RefUpdate struct { Name string `json:"name"` - OldObjectId string `json:"oldObjectId"` - NewObjectId string `json:"newObjectId"` + OldObjectID string `json:"oldObjectId"` + NewObjectID string `json:"newObjectId"` } type Repository struct { - Id string `json:"id"` + ID string `json:"id"` Name string `json:"name"` - Url string `json:"url"` + URL string `json:"url"` Project Project `json:"project"` DefaultBranch string `json:"defaultBranch,omitempty"` Size *int `json:"size,omitempty"` - RemoteUrl string `json:"remoteUrl"` - SshUrl *string `json:"sshUrl,omitempty"` - WebUrl *string `json:"webUrl,omitempty"` + RemoteURL string `json:"remoteUrl"` + SSHURL *string `json:"sshUrl,omitempty"` + WebURL *string `json:"webUrl,omitempty"` IsDisabled *bool `json:"isDisabled,omitempty"` IsInMaintenance *bool `json:"isInMaintenance,omitempty"` } type Project struct { - Id string `json:"id"` + ID string `json:"id"` Name string `json:"name"` - Url string `json:"url"` + URL string `json:"url"` State string `json:"state"` Revision int `json:"revision,omitempty"` Visibility string `json:"visibility"` @@ -81,11 +81,11 @@ type User struct { Email string `json:"email,omitempty"` Date CustomTime `json:"date,omitempty"` DisplayName string `json:"displayName,omitempty"` - Url string `json:"url,omitempty"` + URL string `json:"url,omitempty"` Links Links `json:"_links,omitempty"` - Id string `json:"id,omitempty"` + ID string `json:"id,omitempty"` UniqueName string `json:"uniqueName,omitempty"` - ImageUrl string `json:"imageUrl,omitempty"` + ImageURL string `json:"imageUrl,omitempty"` Descriptor string `json:"descriptor,omitempty"` } @@ -96,7 +96,7 @@ type ResourceContainers struct { } type Container struct { - Id string `json:"id"` + ID string `json:"id"` } type Links struct { diff --git a/pkg/reconciler/event.go b/pkg/reconciler/event.go index 5771bdee2..dca8f3ea9 100644 --- a/pkg/reconciler/event.go +++ b/pkg/reconciler/event.go @@ -103,11 +103,11 @@ func buildEventFromPipelineRun(pr *tektonv1.PipelineRun) *info.Event { if organizationID, ok := prAnno[keys.URLOrg]; ok { event.Organization = organizationID } - if projectID, ok := prAnno[keys.ProjectId]; ok { - event.ProjectId = projectID + if projectID, ok := prAnno[keys.ProjectID]; ok { + event.ProjectID = projectID } - if repositoryID, ok := prAnno[keys.RepositoryId]; ok { - event.RepositoryId = repositoryID + if repositoryID, ok := prAnno[keys.RepositoryID]; ok { + event.RepositoryID = repositoryID } } From af37285ce34423dcba85b6df2d207d0393eb5c0e Mon Sep 17 00:00:00 2001 From: ayesha arshad Date: Sun, 5 May 2024 23:44:14 +0200 Subject: [PATCH 13/16] doc,acl,e2e - documentation - e2e testing - acl implementation --- docs/content/docs/install/azure_devops.md | 58 ++++++++ pkg/provider/azuredevops/acl.go | 67 +++++++++- pkg/provider/azuredevops/acl_test.go | 79 +++++++++++ pkg/provider/azuredevops/azuredevops.go | 49 ++++--- pkg/provider/azuredevops/azuredevops_test.go | 92 ++----------- pkg/provider/azuredevops/detect.go | 22 ++- pkg/provider/azuredevops/parse_payload.go | 57 ++++++-- .../azuredevops/parse_payload_test.go | 2 +- pkg/provider/azuredevops/test/setup.go | 126 ++++++++++++++++++ pkg/provider/azuredevops/types/types.go | 18 +++ test/azuredevops_pullrequest_test.go | 40 ++++++ test/pkg/azuredevops/crd.go | 45 +++++++ test/pkg/azuredevops/pr.go | 122 +++++++++++++++++ test/pkg/azuredevops/setup.go | 117 ++++++++++++++++ test/pkg/options/options.go | 1 + 15 files changed, 771 insertions(+), 124 deletions(-) create mode 100644 docs/content/docs/install/azure_devops.md create mode 100644 pkg/provider/azuredevops/acl_test.go create mode 100644 pkg/provider/azuredevops/test/setup.go create mode 100644 test/azuredevops_pullrequest_test.go create mode 100644 test/pkg/azuredevops/crd.go create mode 100644 test/pkg/azuredevops/pr.go create mode 100644 test/pkg/azuredevops/setup.go diff --git a/docs/content/docs/install/azure_devops.md b/docs/content/docs/install/azure_devops.md new file mode 100644 index 000000000..742c02439 --- /dev/null +++ b/docs/content/docs/install/azure_devops.md @@ -0,0 +1,58 @@ +--- +title: Azure Devops +weight: 17 +--- +# Use Pipelines-as-Code with Azure Devops + +Pipelines-As-Code supports on [Azure Devops](https://azure.microsoft.com/en-us/products/devops) through a webhook. + +Follow the Pipelines-As-Code [installation](/docs/install/installation) according to your Kubernetes cluster. + +* You will have to generate a personal token as the manager of the Project, + follow the steps here: + + + +The token will need to have atleast `Read, write, & manage` permissions under `code`. + +You may want to note somewhere the generated token, or otherwise you will have to +recreate it. + +* Create a Webhook on the repository following this guide : + + +Provide the header value of service hook based on required event type + +| Event Type | Header Value | +| ----------|---------| +| Code Pushed | X-Azure-DevOps-EventType:git.push | +| Pull request created | X-Azure-DevOps-EventType:git.pullrequest.created| +| Pull request updated | X-Azure-DevOps-EventType:git.pullrequest.updated| +| Pull request commented on| X-Azure-DevOps-EventType:git.pullrequest.comment| + +* Create a secret with personal token in the `target-namespace` + + ```shell + kubectl -n target-namespace create secret generic webhook-config \ + --from-literal provider.token="TOKEN_AS_GENERATED_PREVIOUSLY" \ + ``` + +* And finally create Repository CRD with the secret field referencing it. + + * Here is an example of a Repository CRD : + +```yaml + --- + apiVersion: "pipelinesascode.tekton.dev/v1alpha1" + kind: Repository + metadata: + name: my-repo + namespace: target-namespace + spec: + url: 'https://dev.azure.com/YOUR_ORG_NAME/YOUR_PROJ_NAME/_git/YOUR_REPO_NAME' + git_provider: + secret: + name: "webhook-config" + # Set this if you have a different key in your secret + # key: "provider.token" +``` diff --git a/pkg/provider/azuredevops/acl.go b/pkg/provider/azuredevops/acl.go index b2daaee84..587f940c9 100644 --- a/pkg/provider/azuredevops/acl.go +++ b/pkg/provider/azuredevops/acl.go @@ -5,7 +5,9 @@ import ( "fmt" "strings" + "github.com/microsoft/azure-devops-go-api/azuredevops/v7/core" "github.com/openshift-pipelines/pipelines-as-code/pkg/acl" + "github.com/openshift-pipelines/pipelines-as-code/pkg/opscomments" "github.com/openshift-pipelines/pipelines-as-code/pkg/params/info" ) @@ -14,9 +16,64 @@ func (v *Provider) CheckPolicyAllowing(context.Context, *info.Event, []string) ( return false, "" } -// ToDo: implement this function. -func (v *Provider) IsAllowed(context.Context, *info.Event) (bool, error) { - return true, nil +func (v *Provider) IsAllowed(ctx context.Context, event *info.Event) (bool, error) { + + allowed, _ := v.checkMembership(ctx, event) + if allowed { + return true, nil + } + + // Try to parse the comment from an owner who has issues a /ok-to-test + ownerAllowed, err := v.aclAllowedOkToTestFromAnOwner(ctx, event) + if err != nil { + return false, err + } + if ownerAllowed { + return true, nil + } + return false, nil +} + +func (v *Provider) aclAllowedOkToTestFromAnOwner(ctx context.Context, event *info.Event) (bool, error) { + if event.EventType == opscomments.OkToTestCommentEventType.String() { + allowed, _ := v.checkMembership(ctx, event) + if allowed { + return true, nil + } + } + return false, nil +} + +func (v *Provider) checkMembership(ctx context.Context, event *info.Event) (bool, error) { + teams, err := v.CoreClient.GetTeams(ctx, core.GetTeamsArgs{ + ProjectId: &event.ProjectID, + }) + + if err != nil { + return false, err + } + + // Check if the PR author is a member of any team + for _, team := range *teams { + if team.Id == nil { + continue + } + teamIdStr := team.Id.String() + members, err := v.CoreClient.GetTeamMembersWithExtendedProperties(ctx, core.GetTeamMembersWithExtendedPropertiesArgs{ + ProjectId: &event.ProjectID, + TeamId: &teamIdStr, + }) + if err != nil { + continue + } + + for _, member := range *members { + if *member.Identity.Id == event.Sender { + return true, nil + } + } + } + return v.IsAllowedOwnersFile(ctx, event) } func (v *Provider) IsAllowedOwnersFile(ctx context.Context, event *info.Event) (bool, error) { @@ -33,9 +90,9 @@ func (v *Provider) IsAllowedOwnersFile(ctx context.Context, event *info.Event) ( } func (v *Provider) getFileFromDefaultBranch(ctx context.Context, path string, runevent *info.Event) (string, error) { - tektonyaml, err := v.GetFileInsideRepo(ctx, runevent, path, runevent.DefaultBranch) + owner, err := v.GetFileInsideRepo(ctx, runevent, path, runevent.DefaultBranch) if err != nil { return "", fmt.Errorf("cannot find %s inside the %s branch: %w", path, runevent.DefaultBranch, err) } - return tektonyaml, err + return owner, err } diff --git a/pkg/provider/azuredevops/acl_test.go b/pkg/provider/azuredevops/acl_test.go new file mode 100644 index 000000000..703409c3c --- /dev/null +++ b/pkg/provider/azuredevops/acl_test.go @@ -0,0 +1,79 @@ +package azuredevops + +import ( + "testing" + + "github.com/openshift-pipelines/pipelines-as-code/pkg/params/info" + "github.com/openshift-pipelines/pipelines-as-code/pkg/provider/azuredevops/test" + "go.uber.org/zap" + "gotest.tools/v3/assert" + rtesting "knative.dev/pkg/reconciler/testing" +) + +func TestIsAllowedAzureDevOps(t *testing.T) { + + type fields struct { + teamMembers map[string][]string + } + + tests := []struct { + name string + event *info.Event + fields fields + isAllowed bool + wantErrSubstr string + }{ + { + name: "allowed/user is team member", + event: &info.Event{ + Sender: "user123", + ProjectID: "project1", + }, + fields: fields{ + teamMembers: map[string][]string{ + "00000000-0000-0000-0000-000000000000": {"user123", "user456"}, + }, + }, + isAllowed: true, + }, + { + name: "disallowed/user not a team member", + event: &info.Event{ + Sender: "user999", + ProjectID: "project1", + }, + fields: fields{ + teamMembers: map[string][]string{ + "00000000-0000-0000-0000-000000000000": {"user123", "user456"}, + }, + }, + isAllowed: false, + }, + } + + mockGit, mockCore, _, _, tearDown := test.Setup() + + defer tearDown() + + logger := zap.NewExample().Sugar() + defer logger.Sync() + ctx, _ := rtesting.SetupFakeContext(t) + provider := Provider{ + GitClient: mockGit, + CoreClient: mockCore, + Logger: logger, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + mockCore.TeamMembers = tt.fields.teamMembers + got, err := provider.IsAllowed(ctx, tt.event) + if tt.wantErrSubstr != "" { + assert.ErrorContains(t, err, tt.wantErrSubstr) + return + } + assert.NilError(t, err) + assert.Equal(t, tt.isAllowed, got, "Provider.IsAllowed() = %v, want %v", got, tt.isAllowed) + }) + } +} diff --git a/pkg/provider/azuredevops/azuredevops.go b/pkg/provider/azuredevops/azuredevops.go index 4843c42d2..48b64d0fd 100644 --- a/pkg/provider/azuredevops/azuredevops.go +++ b/pkg/provider/azuredevops/azuredevops.go @@ -9,6 +9,7 @@ import ( "strings" "github.com/microsoft/azure-devops-go-api/azuredevops/v7" + "github.com/microsoft/azure-devops-go-api/azuredevops/v7/core" "github.com/microsoft/azure-devops-go-api/azuredevops/v7/git" "github.com/microsoft/azure-devops-go-api/azuredevops/v7/webapi" "github.com/openshift-pipelines/pipelines-as-code/pkg/apis/pipelinesascode/v1alpha1" @@ -24,15 +25,17 @@ import ( var _ provider.Interface = (*Provider)(nil) type Provider struct { - Client git.Client - ctx context.Context - Logger *zap.SugaredLogger - Token *string - run *params.Run + GitClient git.Client + CoreClient core.Client + ctx context.Context + Logger *zap.SugaredLogger + Token *string + run *params.Run + connection *azuredevops.Connection } func (v *Provider) CreateStatus(ctx context.Context, event *info.Event, statusOpts provider.StatusOpts) error { - if v.Client == nil { + if v.GitClient == nil { return fmt.Errorf("cannot set status on azuredevops no token or url set") } @@ -95,7 +98,7 @@ func (v *Provider) CreateStatus(ctx context.Context, event *info.Event, statusOp CommitId: &event.SHA, GitCommitStatusToCreate: &gitStatus, } - if _, err := v.Client.CreateCommitStatus(ctx, commitStatusArgs); err != nil { + if _, err := v.GitClient.CreateCommitStatus(ctx, commitStatusArgs); err != nil { return fmt.Errorf("failed to create commit status: %w", err) } case "git.pullrequest.created", "git.pullrequest.updated": @@ -105,7 +108,7 @@ func (v *Provider) CreateStatus(ctx context.Context, event *info.Event, statusOp RepositoryId: &event.RepositoryID, } - status, err := v.Client.GetPullRequestStatuses(ctx, gitPullRequestStatusArgs) + status, err := v.GitClient.GetPullRequestStatuses(ctx, gitPullRequestStatusArgs) if err != nil { return fmt.Errorf("failed to fetch pull request statuses: %w", err) } @@ -151,7 +154,7 @@ func updatePRStatus(ctx context.Context, status *[]git.GitPullRequestStatus, eve RepositoryId: &event.RepositoryID, PullRequestId: &event.PullRequestNumber, } - if err := v.Client.UpdatePullRequestStatuses(ctx, gitUpdatePullRequestStatus); err != nil { + if err := v.GitClient.UpdatePullRequestStatuses(ctx, gitUpdatePullRequestStatus); err != nil { return fmt.Errorf("failed to update pull request status: %w", err) } return nil @@ -175,7 +178,7 @@ func createPRStatus(ctx context.Context, v *Provider, event *info.Event, statusO RepositoryId: &event.RepositoryID, Status: &gitPullRequestStatus, } - if _, err := v.Client.CreatePullRequestStatus(ctx, prStatusArgs); err != nil { + if _, err := v.GitClient.CreatePullRequestStatus(ctx, prStatusArgs); err != nil { return fmt.Errorf("failed to create pull request status: %w", err) } return nil @@ -186,7 +189,7 @@ func (v *Provider) CreateToken(context.Context, []string, *info.Event) (string, } func (v *Provider) GetCommitInfo(ctx context.Context, event *info.Event) error { - if v.Client == nil { + if v.GitClient == nil { return fmt.Errorf("no Azure DevOps client has been initialized, " + "exiting... (hint: did you forget setting a secret on your repo?)") } @@ -199,7 +202,7 @@ func (v *Provider) GetCommitInfo(ctx context.Context, event *info.Event) error { if sha == "" { if event.HeadBranch != "" { refName := fmt.Sprintf("refs/heads/%s", event.HeadBranch) - refs, err := v.Client.GetRefs(ctx, git.GetRefsArgs{ + refs, err := v.GitClient.GetRefs(ctx, git.GetRefsArgs{ RepositoryId: &RepositoryID, Filter: &refName, Project: &projectID, @@ -212,7 +215,7 @@ func (v *Provider) GetCommitInfo(ctx context.Context, event *info.Event) error { sha = *refs.Value[0].ObjectId } } else if event.PullRequestNumber != 0 { - pr, err := v.Client.GetPullRequest(ctx, git.GetPullRequestArgs{ + pr, err := v.GitClient.GetPullRequest(ctx, git.GetPullRequestArgs{ RepositoryId: &RepositoryID, PullRequestId: &event.PullRequestNumber, Project: &projectID, @@ -226,7 +229,7 @@ func (v *Provider) GetCommitInfo(ctx context.Context, event *info.Event) error { } } if sha != "" { - commit, err := v.Client.GetCommit(ctx, git.GetCommitArgs{ + commit, err := v.GitClient.GetCommit(ctx, git.GetCommitArgs{ CommitId: &sha, RepositoryId: &RepositoryID, Project: &projectID, @@ -251,7 +254,7 @@ func (v *Provider) GetConfig() *info.ProviderConfig { } func (v *Provider) GetFiles(ctx context.Context, event *info.Event) (changedfiles.ChangedFiles, error) { - filesChanged, err := v.Client.GetChanges(ctx, git.GetChangesArgs{ + filesChanged, err := v.GitClient.GetChanges(ctx, git.GetChangesArgs{ RepositoryId: &event.RepositoryID, CommitId: &event.SHA, }) @@ -313,7 +316,7 @@ func (v *Provider) GetFileInsideRepo(ctx context.Context, runevent *info.Event, VersionType: &versionType, } - reader, err := v.Client.GetItemContent(ctx, git.GetItemContentArgs{ + reader, err := v.GitClient.GetItemContent(ctx, git.GetItemContentArgs{ RepositoryId: &repositoryID, Project: &ProjectID, Path: &path, @@ -356,7 +359,7 @@ func (v *Provider) GetTektonDir(ctx context.Context, runevent *info.Event, path, } // Check if the path exists and is a directory - item, err := v.Client.GetItem(ctx, git.GetItemArgs{ + item, err := v.GitClient.GetItem(ctx, git.GetItemArgs{ RepositoryId: &repositoryID, Project: &ProjectID, Path: &path, @@ -371,7 +374,7 @@ func (v *Provider) GetTektonDir(ctx context.Context, runevent *info.Event, path, } // Get the SHA of the directory and fetch the tree - tree, err := v.Client.GetTree(ctx, git.GetTreeArgs{ + tree, err := v.GitClient.GetTree(ctx, git.GetTreeArgs{ RepositoryId: &repositoryID, Project: &ProjectID, Sha1: item.ObjectId, @@ -419,7 +422,7 @@ func (v *Provider) concatAllYamlFiles(ctx context.Context, entries *[]git.GitTre } func (v *Provider) getObject(ctx context.Context, repositoryID, projectID, sha string) ([]byte, error) { - reader, err := v.Client.GetBlobContent(ctx, git.GetBlobContentArgs{ + reader, err := v.GitClient.GetBlobContent(ctx, git.GetBlobContentArgs{ RepositoryId: &repositoryID, Project: &projectID, Sha1: &sha, @@ -448,14 +451,18 @@ func (v *Provider) SetClient(_ context.Context, run *params.Run, event *info.Eve organizationURL := event.Organization connection := azuredevops.NewPatConnection(organizationURL, event.Provider.Token) ctx := context.Background() - v.Client, err = git.NewClient(ctx, connection) + v.GitClient, err = git.NewClient(ctx, connection) + if err != nil { + return err + } + v.CoreClient, err = core.NewClient(ctx, v.connection) if err != nil { return err } - v.Token = &event.Provider.Token v.run = run v.ctx = ctx + v.connection = connection return nil } diff --git a/pkg/provider/azuredevops/azuredevops_test.go b/pkg/provider/azuredevops/azuredevops_test.go index 3e14019df..397f8160d 100644 --- a/pkg/provider/azuredevops/azuredevops_test.go +++ b/pkg/provider/azuredevops/azuredevops_test.go @@ -1,82 +1,28 @@ package azuredevops import ( - "context" - "net/http" - "net/http/httptest" "testing" - "github.com/microsoft/azure-devops-go-api/azuredevops/v7/git" "github.com/openshift-pipelines/pipelines-as-code/pkg/params" "github.com/openshift-pipelines/pipelines-as-code/pkg/params/info" - statusOpts "github.com/openshift-pipelines/pipelines-as-code/pkg/provider" - "github.com/openshift-pipelines/pipelines-as-code/pkg/params/settings" + statusOpts "github.com/openshift-pipelines/pipelines-as-code/pkg/provider" + "github.com/openshift-pipelines/pipelines-as-code/pkg/provider/azuredevops/test" + "go.uber.org/zap" + rtesting "knative.dev/pkg/reconciler/testing" ) -type MockGitClient struct { - git.Client // Embedding git.Client for future-proofing against new methods - createCommitStatus func(ctx context.Context, args git.CreateCommitStatusArgs) (*git.GitStatus, error) - getPullRequestStatuses func(ctx context.Context, args git.GetPullRequestStatusesArgs) (*[]git.GitPullRequestStatus, error) - updatePullRequestStatus func(ctx context.Context, args git.UpdatePullRequestStatusesArgs) error - createPullRequestStatus func(ctx context.Context, args git.CreatePullRequestStatusArgs) (*git.GitPullRequestStatus, error) - createAnnotatedTag func(ctx context.Context, args git.CreateAnnotatedTagArgs) (*git.GitAnnotatedTag, error) -} - -func (m *MockGitClient) CreateCommitStatus(ctx context.Context, args git.CreateCommitStatusArgs) (*git.GitStatus, error) { - return m.createCommitStatus(ctx, args) -} - -func (m *MockGitClient) GetPullRequestStatuses(ctx context.Context, args git.GetPullRequestStatusesArgs) (*[]git.GitPullRequestStatus, error) { - return m.getPullRequestStatuses(ctx, args) -} - -func (m *MockGitClient) UpdatePullRequestStatuses(ctx context.Context, args git.UpdatePullRequestStatusesArgs) error { - return m.updatePullRequestStatus(ctx, args) -} - -func (m *MockGitClient) CreatePullRequestStatus(ctx context.Context, args git.CreatePullRequestStatusArgs) (*git.GitPullRequestStatus, error) { - return m.createPullRequestStatus(ctx, args) -} - -func (m *MockGitClient) CreateAnnotatedTag(ctx context.Context, args git.CreateAnnotatedTagArgs) (*git.GitAnnotatedTag, error) { - if m.createAnnotatedTag != nil { - return m.createAnnotatedTag(ctx, args) - } - return nil, nil -} - -func Setup() (*MockGitClient, *http.ServeMux, func()) { - mux := http.NewServeMux() - server := httptest.NewServer(mux) - tearDown := func() { - server.Close() - } - - mockClient := &MockGitClient{ - createCommitStatus: func(context.Context, git.CreateCommitStatusArgs) (*git.GitStatus, error) { - return &git.GitStatus{}, nil - }, - getPullRequestStatuses: func(context.Context, git.GetPullRequestStatusesArgs) (*[]git.GitPullRequestStatus, error) { - return &[]git.GitPullRequestStatus{}, nil - }, - updatePullRequestStatus: func(context.Context, git.UpdatePullRequestStatusesArgs) error { - return nil - }, - createPullRequestStatus: func(context.Context, git.CreatePullRequestStatusArgs) (*git.GitPullRequestStatus, error) { - return &git.GitPullRequestStatus{}, nil - }, - createAnnotatedTag: func(context.Context, git.CreateAnnotatedTagArgs) (*git.GitAnnotatedTag, error) { - return &git.GitAnnotatedTag{}, nil - }, - } - - return mockClient, mux, tearDown -} +func TestCreateStatus(t *testing.T) { + mockGit, mockCore, _, _, tearDown := test.Setup() + defer tearDown() -func getProvider(mockClient *MockGitClient) *Provider { - provider := &Provider{ - Client: mockClient, + logger := zap.NewExample().Sugar() + defer logger.Sync() + ctx, _ := rtesting.SetupFakeContext(t) + provider := Provider{ + GitClient: mockGit, + CoreClient: mockCore, + Logger: logger, run: ¶ms.Run{ Info: info.Info{ Pac: &info.PacOpts{ @@ -87,16 +33,6 @@ func getProvider(mockClient *MockGitClient) *Provider { }, }, } - return provider -} - -func TestCreateStatus(t *testing.T) { - mockClient, _, tearDown := Setup() - defer tearDown() - - ctx := context.Background() - - provider := getProvider(mockClient) testCases := []struct { name string diff --git a/pkg/provider/azuredevops/detect.go b/pkg/provider/azuredevops/detect.go index 32c3346dc..02f8c07d7 100644 --- a/pkg/provider/azuredevops/detect.go +++ b/pkg/provider/azuredevops/detect.go @@ -4,6 +4,7 @@ import ( "encoding/json" "fmt" "net/http" + "strings" "github.com/microsoft/azure-devops-go-api/azuredevops/v7/servicehooks" "go.uber.org/zap" @@ -31,13 +32,20 @@ func (v *Provider) Detect(req *http.Request, payload string, logger *zap.Sugared if err != nil { return isADO, false, logger, "", err } - logger = logger.With("provider", "azuredevops", "event-type", event.EventType) - // Simplified switch, expand as needed based on the Azure DevOps events you handle - switch eventType { - case "git.push", "git.pullrequest.created", "git.pullrequest.updated": - return setLoggerAndProceed(true, "", nil) - default: - return setLoggerAndProceed(false, fmt.Sprintf("Unsupported event type: %s", eventType), nil) + //check if the event type provided in header and in the event json is same; is it necessary? + // eventtype in comment json is ms.vss-code.git-pullrequest-comment-event so replaceing all - to . to match it with header + normalizedEventType := strings.ReplaceAll(*event.EventType, "-", ".") + if strings.Contains(normalizedEventType, eventType) { + logger = logger.With("provider", "azuredevops", "event-type", eventType) + // Simplified switch, expand as needed based on the Azure DevOps events you handle + switch eventType { + case "git.push", "git.pullrequest.created", "git.pullrequest.updated", "git.pullrequest.comment": + return setLoggerAndProceed(true, "", nil) + default: + return setLoggerAndProceed(false, fmt.Sprintf("Unsupported event type: %s", eventType), nil) + } + } else { + return setLoggerAndProceed(false, fmt.Sprintf("event type in header %s and event json %s does not match", eventType, *event.EventType), nil) } } diff --git a/pkg/provider/azuredevops/parse_payload.go b/pkg/provider/azuredevops/parse_payload.go index 3c447de09..6165fef32 100644 --- a/pkg/provider/azuredevops/parse_payload.go +++ b/pkg/provider/azuredevops/parse_payload.go @@ -9,13 +9,14 @@ import ( "strings" "github.com/microsoft/azure-devops-go-api/azuredevops/v7/servicehooks" + "github.com/openshift-pipelines/pipelines-as-code/pkg/opscomments" "github.com/openshift-pipelines/pipelines-as-code/pkg/params" "github.com/openshift-pipelines/pipelines-as-code/pkg/params/info" "github.com/openshift-pipelines/pipelines-as-code/pkg/params/triggertype" types "github.com/openshift-pipelines/pipelines-as-code/pkg/provider/azuredevops/types" ) -func (v *Provider) ParsePayload(_ context.Context, _ *params.Run, _ *http.Request, payload string) (*info.Event, error) { +func (v *Provider) ParsePayload(_ context.Context, _ *params.Run, req *http.Request, payload string) (*info.Event, error) { var genericEvent servicehooks.Event err := json.Unmarshal([]byte(payload), &genericEvent) if err != nil { @@ -27,14 +28,16 @@ func (v *Provider) ParsePayload(_ context.Context, _ *params.Run, _ *http.Reques } processedEvent := info.NewEvent() - processedEvent.EventType = *genericEvent.EventType + + processedEvent.EventType = req.Header.Get("X-Azure-DevOps-EventType") + // processedEvent.EventType = *genericEvent.EventType resourceBytes, err := json.Marshal(genericEvent.Resource) if err != nil { return nil, fmt.Errorf("error marshalling resource: %w", err) } - switch *genericEvent.EventType { + switch processedEvent.EventType { case "git.push": var pushEvent types.PushEventResource @@ -47,9 +50,8 @@ func (v *Provider) ParsePayload(_ context.Context, _ *params.Run, _ *http.Reques processedEvent.SHATitle = pushEvent.Commits[0].Comment } - processedEvent.EventType = *genericEvent.EventType - processedEvent.Sender = pushEvent.PushedBy.DisplayName - baseURL, err := extractBaseURL(pushEvent.Repository.RemoteURL) + processedEvent.Sender = pushEvent.PushedBy.ID + baseURL, err := ExtractBaseURL(pushEvent.Repository.RemoteURL) if err != nil { return nil, fmt.Errorf("not able to extract organization url") } @@ -62,8 +64,8 @@ func (v *Provider) ParsePayload(_ context.Context, _ *params.Run, _ *http.Reques processedEvent.DefaultBranch = pushEvent.Repository.DefaultBranch processedEvent.TriggerTarget = triggertype.Push // Assuming the repository URL can serve as both BaseURL and HeadURL for viewing purposes - processedEvent.BaseURL = pushEvent.Repository.URL // or it could be remoteUrl or it could be other; need to verify - processedEvent.HeadURL = pushEvent.Repository.URL // or it could be remoteUrl or it could be other; need to verify + processedEvent.BaseURL = pushEvent.Repository.URL + processedEvent.HeadURL = pushEvent.Repository.URL if len(pushEvent.RefUpdates) > 0 { branchName := ExtractBranchName(pushEvent.RefUpdates[0].Name) processedEvent.BaseBranch = branchName @@ -76,7 +78,6 @@ func (v *Provider) ParsePayload(_ context.Context, _ *params.Run, _ *http.Reques return nil, fmt.Errorf("error unmarshalling pull request event resource: %w", err) } - processedEvent.EventType = *genericEvent.EventType processedEvent.PullRequestNumber = prEvent.PullRequestID processedEvent.PullRequestTitle = prEvent.Title processedEvent.SHA = prEvent.LastMergeSourceCommit.CommitID @@ -96,7 +97,7 @@ func (v *Provider) ParsePayload(_ context.Context, _ *params.Run, _ *http.Reques processedEvent.TriggerTarget = triggertype.PullRequest - baseURL, err := extractBaseURL(remoteURL) + baseURL, err := ExtractBaseURL(remoteURL) if err != nil { return nil, fmt.Errorf("not able to extract organization url") } @@ -105,7 +106,39 @@ func (v *Provider) ParsePayload(_ context.Context, _ *params.Run, _ *http.Reques processedEvent.RepositoryID = prEvent.Repository.ID processedEvent.ProjectID = prEvent.Repository.Project.ID processedEvent.URL = *prEvent.Repository.WebURL - processedEvent.Sender = prEvent.CreatedBy.DisplayName + processedEvent.Sender = prEvent.CreatedBy.ID + + case "git.pullrequest.comment": + + var prEvent types.PullRequestCommentEventResource + if err := json.Unmarshal(resourceBytes, &prEvent); err != nil { + return nil, fmt.Errorf("error unmarshalling pull request event resource: %w", err) + } + + processedEvent.PullRequestNumber = prEvent.PullRequest.PullRequestID + processedEvent.PullRequestTitle = prEvent.PullRequest.Title + processedEvent.SHA = prEvent.PullRequest.LastMergeSourceCommit.CommitID + processedEvent.SHAURL = prEvent.PullRequest.LastMergeSourceCommit.URL + processedEvent.SHATitle = prEvent.PullRequest.LastMergeSourceCommit.Comment + + processedEvent.BaseBranch = ExtractBranchName(prEvent.PullRequest.TargetRefName) + processedEvent.HeadBranch = ExtractBranchName(prEvent.PullRequest.SourceRefName) + processedEvent.DefaultBranch = prEvent.PullRequest.Repository.DefaultBranch + + remoteURL := *prEvent.PullRequest.Repository.WebURL + processedEvent.TriggerTarget = triggertype.PullRequest + baseURL, err := ExtractBaseURL(remoteURL) + if err != nil { + return nil, fmt.Errorf("not able to extract organization url") + } + processedEvent.Organization = baseURL + processedEvent.Repository = *prEvent.PullRequest.Repository.WebURL + processedEvent.RepositoryID = prEvent.PullRequest.Repository.ID + processedEvent.ProjectID = prEvent.PullRequest.Repository.Project.ID + processedEvent.URL = *prEvent.PullRequest.Repository.WebURL + processedEvent.Sender = prEvent.PullRequest.CreatedBy.ID + opscomments.SetEventTypeAndTargetPR(processedEvent, prEvent.Comment.Content) + default: return nil, fmt.Errorf("event type %s is not supported", *genericEvent.EventType) } @@ -123,7 +156,7 @@ func ExtractBranchName(refName string) string { return refName // Return as-is if the format is unexpected } -func extractBaseURL(url string) (string, error) { +func ExtractBaseURL(url string) (string, error) { re := regexp.MustCompile(`^(https://dev\.azure\.com/[^/]+)`) matches := re.FindStringSubmatch(url) if len(matches) < 2 { diff --git a/pkg/provider/azuredevops/parse_payload_test.go b/pkg/provider/azuredevops/parse_payload_test.go index 04af74686..38a3508f3 100644 --- a/pkg/provider/azuredevops/parse_payload_test.go +++ b/pkg/provider/azuredevops/parse_payload_test.go @@ -228,7 +228,7 @@ func TestExtractBaseURL(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - got, err := extractBaseURL(tt.url) + got, err := ExtractBaseURL(tt.url) if (err != nil) != tt.wantErr { t.Errorf("extractBaseURL(%q) expected error? %v, got error? %v", tt.url, tt.wantErr, err != nil) } diff --git a/pkg/provider/azuredevops/test/setup.go b/pkg/provider/azuredevops/test/setup.go new file mode 100644 index 000000000..9010378e3 --- /dev/null +++ b/pkg/provider/azuredevops/test/setup.go @@ -0,0 +1,126 @@ +package test + +import ( + "bytes" + "context" + "io" + "net/http" + "net/http/httptest" + + "github.com/google/uuid" + "github.com/microsoft/azure-devops-go-api/azuredevops/v7/core" + "github.com/microsoft/azure-devops-go-api/azuredevops/v7/git" + "github.com/microsoft/azure-devops-go-api/azuredevops/v7/webapi" +) + +type MockGitClient struct { + git.Client + CreateCommitStatusFunc func(ctx context.Context, args git.CreateCommitStatusArgs) (*git.GitStatus, error) + GetPullRequestStatusesFunc func(ctx context.Context, args git.GetPullRequestStatusesArgs) (*[]git.GitPullRequestStatus, error) + UpdatePullRequestStatusFunc func(ctx context.Context, args git.UpdatePullRequestStatusesArgs) error + CreatePullRequestStatusFunc func(ctx context.Context, args git.CreatePullRequestStatusArgs) (*git.GitPullRequestStatus, error) + CreateAnnotatedTagFunc func(ctx context.Context, args git.CreateAnnotatedTagArgs) (*git.GitAnnotatedTag, error) + GetItemContentFunc func(context.Context, git.GetItemContentArgs) (io.ReadCloser, error) +} + +// MockCoreClient mocks the core.Client interface +type MockCoreClient struct { + core.Client + TeamMembers map[string][]string + GetTeamsFunc func(context.Context, core.GetTeamsArgs) (*[]core.WebApiTeam, error) + GetTeamMembersWithExtendedPropertiesFunc func(context.Context, core.GetTeamMembersWithExtendedPropertiesArgs) (*[]webapi.TeamMember, error) +} + +func (m *MockGitClient) CreateCommitStatus(ctx context.Context, args git.CreateCommitStatusArgs) (*git.GitStatus, error) { + return m.CreateCommitStatusFunc(ctx, args) +} + +func (m *MockGitClient) GetPullRequestStatuses(ctx context.Context, args git.GetPullRequestStatusesArgs) (*[]git.GitPullRequestStatus, error) { + return m.GetPullRequestStatusesFunc(ctx, args) +} + +func (m *MockGitClient) UpdatePullRequestStatuses(ctx context.Context, args git.UpdatePullRequestStatusesArgs) error { + return m.UpdatePullRequestStatusFunc(ctx, args) +} + +func (m *MockGitClient) CreatePullRequestStatus(ctx context.Context, args git.CreatePullRequestStatusArgs) (*git.GitPullRequestStatus, error) { + return m.CreatePullRequestStatusFunc(ctx, args) +} + +func (m *MockGitClient) CreateAnnotatedTag(ctx context.Context, args git.CreateAnnotatedTagArgs) (*git.GitAnnotatedTag, error) { + return m.CreateAnnotatedTagFunc(ctx, args) +} + +func (m *MockGitClient) GetItemContent(ctx context.Context, args git.GetItemContentArgs) (io.ReadCloser, error) { + return io.NopCloser(bytes.NewBuffer(nil)), nil +} + +func (m *MockCoreClient) GetTeams(ctx context.Context, args core.GetTeamsArgs) (*[]core.WebApiTeam, error) { + var teams []core.WebApiTeam + for teamID := range m.TeamMembers { + uuidID, _ := uuid.Parse(teamID) + teams = append(teams, core.WebApiTeam{Id: &uuidID, Name: &teamID}) + } + return &teams, nil +} + +func (m *MockCoreClient) GetTeamMembersWithExtendedProperties(ctx context.Context, args core.GetTeamMembersWithExtendedPropertiesArgs) (*[]webapi.TeamMember, error) { + uuidID, err := uuid.Parse(*args.TeamId) + if err != nil { + return nil, err + } + + members, exists := m.TeamMembers[uuidID.String()] + if !exists { + return nil, nil + } + + var teamMembers []webapi.TeamMember + for _, memberID := range members { + identityID := memberID // Simplifying identity ID use case + teamMembers = append(teamMembers, webapi.TeamMember{ + Identity: &webapi.IdentityRef{Id: &identityID}, + }) + } + return &teamMembers, nil +} + +func Setup() (*MockGitClient, *MockCoreClient, *http.ServeMux, *httptest.Server, func()) { + + mux := http.NewServeMux() + server := httptest.NewServer(mux) + + tearDown := func() { + server.Close() + } + + mockGitClient := &MockGitClient{ + CreateCommitStatusFunc: func(ctx context.Context, args git.CreateCommitStatusArgs) (*git.GitStatus, error) { + return &git.GitStatus{}, nil + }, + GetPullRequestStatusesFunc: func(ctx context.Context, args git.GetPullRequestStatusesArgs) (*[]git.GitPullRequestStatus, error) { + return &[]git.GitPullRequestStatus{}, nil + }, + UpdatePullRequestStatusFunc: func(context.Context, git.UpdatePullRequestStatusesArgs) error { + return nil + }, + CreatePullRequestStatusFunc: func(context.Context, git.CreatePullRequestStatusArgs) (*git.GitPullRequestStatus, error) { + return &git.GitPullRequestStatus{}, nil + }, + CreateAnnotatedTagFunc: func(context.Context, git.CreateAnnotatedTagArgs) (*git.GitAnnotatedTag, error) { + return &git.GitAnnotatedTag{}, nil + }, + GetItemContentFunc: func(context.Context, git.GetItemContentArgs) (io.ReadCloser, error) { + return io.NopCloser(bytes.NewBuffer(nil)), nil + }, + } + mockCoreClient := &MockCoreClient{ + GetTeamsFunc: func(ctx context.Context, args core.GetTeamsArgs) (*[]core.WebApiTeam, error) { + return &[]core.WebApiTeam{}, nil + }, + GetTeamMembersWithExtendedPropertiesFunc: func(ctx context.Context, args core.GetTeamMembersWithExtendedPropertiesArgs) (*[]webapi.TeamMember, error) { + return &[]webapi.TeamMember{}, nil + }, + } + return mockGitClient, mockCoreClient, mux, server, tearDown +} diff --git a/pkg/provider/azuredevops/types/types.go b/pkg/provider/azuredevops/types/types.go index ddde82076..0e2d92fec 100644 --- a/pkg/provider/azuredevops/types/types.go +++ b/pkg/provider/azuredevops/types/types.go @@ -4,6 +4,11 @@ import ( "time" ) +type PullRequestCommentEventResource struct { + Comment Comment `json:"comment"` + PullRequest PullRequestEventResource `json:"pullRequest"` +} + type PullRequestEventResource struct { Repository Repository `json:"repository"` PullRequestID int `json:"pullRequestId"` @@ -38,6 +43,19 @@ type PushEventResource struct { URL string `json:"url"` } +type Comment struct { + ID int `json:"id"` + ParentCommentID int `json:"parentCommentId"` + Author User `json:"author"` + Content string `json:"content"` + PublishedDate string `json:"publishedDate"` + LastUpdatedDate string `json:"lastUpdatedDate"` + LastContentUpdatedDate string `json:"lastContentUpdatedDate"` + CommentType string `json:"commentType"` + UsersLiked []string `json:"usersLiked,omitempty"` + Links Links `json:"_links"` +} + type Commit struct { CommitID string `json:"commitId,omitempty"` Author User `json:"author,omitempty"` diff --git a/test/azuredevops_pullrequest_test.go b/test/azuredevops_pullrequest_test.go new file mode 100644 index 000000000..e432b6c11 --- /dev/null +++ b/test/azuredevops_pullrequest_test.go @@ -0,0 +1,40 @@ +//go:build e2e +// +build e2e + +package test + +import ( + "context" + "testing" + + tazdevops "github.com/openshift-pipelines/pipelines-as-code/test/pkg/azuredevops" + "github.com/openshift-pipelines/pipelines-as-code/test/pkg/wait" + "github.com/tektoncd/pipeline/pkg/names" +) + +func TestAzureDevopsPullRequest(t *testing.T) { + targetNS := names.SimpleNameGenerator.RestrictLengthWithRandomSuffix("pac-e2e-ns") + ctx := context.Background() + + runcnx, opts, azprovider, err := tazdevops.Setup(ctx) + if err != nil { + t.Skip(err.Error()) + return + } + tazdevops.CreateCRD(ctx, t, azprovider, runcnx, opts, targetNS) + targetRefName := names.SimpleNameGenerator.RestrictLengthWithRandomSuffix("pac-e2e-test") + title := "TestPullRequest - " + targetRefName + + PullRequestId, RefName, PushID := tazdevops.MakePR(ctx, t, azprovider, opts, title, targetNS, targetRefName) + defer tazdevops.TearDown(ctx, t, runcnx, azprovider, opts, PullRequestId, targetNS, RefName, PushID) + + sopt := wait.SuccessOpt{ + TargetNS: targetNS, + OnEvent: "git.pullrequest.created", + NumberofPRMatch: 1, + SHA: *PushID, + Title: title, + MinNumberStatus: 1, + } + wait.Succeeded(ctx, t, runcnx, opts, sopt) +} diff --git a/test/pkg/azuredevops/crd.go b/test/pkg/azuredevops/crd.go new file mode 100644 index 000000000..805978868 --- /dev/null +++ b/test/pkg/azuredevops/crd.go @@ -0,0 +1,45 @@ +package azuredevops + +import ( + "context" + "os" + "testing" + + "github.com/openshift-pipelines/pipelines-as-code/pkg/apis/pipelinesascode/v1alpha1" + "github.com/openshift-pipelines/pipelines-as-code/pkg/params" + azprovider "github.com/openshift-pipelines/pipelines-as-code/pkg/provider/azuredevops" + "github.com/openshift-pipelines/pipelines-as-code/test/pkg/options" + pacrepo "github.com/openshift-pipelines/pipelines-as-code/test/pkg/repository" + "github.com/openshift-pipelines/pipelines-as-code/test/pkg/secret" + "gotest.tools/v3/assert" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +func CreateCRD(ctx context.Context, t *testing.T, azProvider azprovider.Provider, run *params.Run, opts options.E2E, targetNS string) { + + adoToken := os.Getenv("TEST_AZURE_DEVOPS_TOKEN") + adoRepo := os.Getenv("TEST_AZURE_DEVOPS_REPO") + + err := pacrepo.CreateNS(ctx, targetNS, run) + assert.NilError(t, err) + + err = secret.Create(ctx, run, map[string]string{"token": adoToken}, targetNS, "webhook-token") + assert.NilError(t, err) + + repository := &v1alpha1.Repository{ + ObjectMeta: metav1.ObjectMeta{ + Name: targetNS, + }, + Spec: v1alpha1.RepositorySpec{ + URL: adoRepo, + }, + } + + repository.Spec.GitProvider = &v1alpha1.GitProvider{ + //URL: adoRepo, + Secret: &v1alpha1.Secret{Name: "webhook-token", Key: "token"}, + } + err = pacrepo.CreateRepo(ctx, targetNS, run, repository) + assert.NilError(t, err) + +} diff --git a/test/pkg/azuredevops/pr.go b/test/pkg/azuredevops/pr.go new file mode 100644 index 000000000..1a2e48d0b --- /dev/null +++ b/test/pkg/azuredevops/pr.go @@ -0,0 +1,122 @@ +package azuredevops + +import ( + "context" + "fmt" + "testing" + + "github.com/microsoft/azure-devops-go-api/azuredevops/v7/git" + "github.com/openshift-pipelines/pipelines-as-code/pkg/params/triggertype" + azprovider "github.com/openshift-pipelines/pipelines-as-code/pkg/provider/azuredevops" + "github.com/openshift-pipelines/pipelines-as-code/test/pkg/options" + "github.com/openshift-pipelines/pipelines-as-code/test/pkg/payload" + "gotest.tools/v3/assert" +) + +func MakePR(ctx context.Context, t *testing.T, azProvider azprovider.Provider, opts options.E2E, title, targetNS string, targetRefName string) (*int, *string, *string) { + commitAuthor := "Azure DevOps Pipelines E2E test" + commitEmail := "e2e-pipelines@azure.com" + + entries, err := payload.GetEntries( + map[string]string{".tekton/pipelinerun.yaml": "testdata/pipelinerun.yaml"}, + targetNS, options.MainBranch, triggertype.PullRequest.String(), map[string]string{}) + assert.NilError(t, err) + fileContent := entries[".tekton/pipelinerun.yaml"] + + gitClient := azProvider.Client + filter := "heads/main" + + // Create a new branch from the default branch + defaultBranchRef, err := gitClient.GetRefs(ctx, git.GetRefsArgs{ + RepositoryId: &opts.ProjectName, + Project: &opts.ProjectName, + Filter: &filter, + }) + assert.NilError(t, err) + + defaultBranch := defaultBranchRef.Value[0] + + fullTargetRN := fmt.Sprintf("refs/heads/%s", targetRefName) + + newRef := &git.GitRefUpdate{ + Name: &fullTargetRN, + OldObjectId: defaultBranch.ObjectId, + NewObjectId: defaultBranch.ObjectId, + } + refUpdates := []git.GitRefUpdate{*newRef} + _, err = gitClient.UpdateRefs(ctx, git.UpdateRefsArgs{ + RefUpdates: &refUpdates, + RepositoryId: &opts.ProjectName, + Project: &opts.ProjectName, + }) + assert.NilError(t, err) + + //Comment := fmt.Sprintf("Initial commit of PipelineRun to %s", targetRefName) + Path := ".tekton/pipelinerun.yaml" + + changes := []git.GitChange{ + { + ChangeType: &git.VersionControlChangeTypeValues.Add, + Item: git.GitItem{ + Path: &Path, + }, + NewContent: &git.ItemContent{ + Content: &fileContent, + ContentType: &git.ItemContentTypeValues.RawText, + }, + }, + } + + interfaceChanges := make([]interface{}, len(changes)) + for i, change := range changes { + interfaceChanges[i] = change + } + + commits := []git.GitCommitRef{ + { + Comment: &title, + Changes: &interfaceChanges, + Author: &git.GitUserDate{ + Email: &commitEmail, + Name: &commitAuthor, + }, + Committer: &git.GitUserDate{ + Email: &commitEmail, + Name: &commitAuthor, + }, + }, + } + + push := git.GitPush{ + RefUpdates: &[]git.GitRefUpdate{ + { + Name: &fullTargetRN, + OldObjectId: newRef.NewObjectId, + }, + }, + Commits: &commits, + } + pushResponse, err := gitClient.CreatePush(ctx, git.CreatePushArgs{ + Push: &push, + RepositoryId: &opts.ProjectName, + Project: &opts.ProjectName, + }) + assert.NilError(t, err) + + // Create a pull request + MainRefName := "refs/heads/main" + Description := "A new PR for e2e testing" + pr, err := gitClient.CreatePullRequest(ctx, git.CreatePullRequestArgs{ + GitPullRequestToCreate: &git.GitPullRequest{ + SourceRefName: &fullTargetRN, + TargetRefName: &MainRefName, + Title: &title, + Description: &Description, + }, + RepositoryId: &opts.ProjectName, + Project: &opts.ProjectName, + }) + assert.NilError(t, err) + return pr.PullRequestId, newRef.Name, (*pushResponse.Commits)[0].CommitId + +} diff --git a/test/pkg/azuredevops/setup.go b/test/pkg/azuredevops/setup.go new file mode 100644 index 000000000..24be8f6fe --- /dev/null +++ b/test/pkg/azuredevops/setup.go @@ -0,0 +1,117 @@ +package azuredevops + +import ( + "context" + "fmt" + "net/url" + "os" + "strings" + "testing" + + "github.com/microsoft/azure-devops-go-api/azuredevops/v7/git" + "github.com/openshift-pipelines/pipelines-as-code/pkg/params" + "github.com/openshift-pipelines/pipelines-as-code/pkg/params/info" + azprovider "github.com/openshift-pipelines/pipelines-as-code/pkg/provider/azuredevops" + "github.com/openshift-pipelines/pipelines-as-code/test/pkg/options" + "github.com/openshift-pipelines/pipelines-as-code/test/pkg/repository" + "gotest.tools/v3/assert" +) + +func getProjectNameFromURL(urlStr string) (string, error) { + parsedURL, err := url.Parse(urlStr) + if err != nil { + return "", err + } + pathSegments := strings.Split(parsedURL.Path, "/") + + if len(pathSegments) > 2 { + return pathSegments[2], nil + } + return "", fmt.Errorf("project name not found in the URL") +} + +func Setup(ctx context.Context) (*params.Run, options.E2E, azprovider.Provider, error) { + adoToken := os.Getenv("TEST_AZURE_DEVOPS_TOKEN") + adoRepo := os.Getenv("TEST_AZURE_DEVOPS_REPO") + + for _, value := range []string{"AZURE_DEVOPS_TOKEN", "AZURE_DEVOPS_REPO"} { + if env := os.Getenv("TEST_" + value); env == "" { + return nil, options.E2E{}, azprovider.Provider{}, fmt.Errorf("\"TEST_%s\" env variable is required, skipping", value) + } + } + + adoOrganization, err := azprovider.ExtractBaseURL(adoRepo) + if err != nil { + return nil, options.E2E{}, azprovider.Provider{}, err + } + + adoProject, err := getProjectNameFromURL(adoRepo) + run := params.New() + if err := run.Clients.NewClients(ctx, &run.Info); err != nil { + return nil, options.E2E{}, azprovider.Provider{}, err + } + + e2eoptions := options.E2E{ + Organization: adoOrganization, + Repo: adoRepo, + ProjectName: adoProject, + } + + adoClient := azprovider.Provider{} + event := info.NewEvent() + event.Provider = &info.Provider{ + Token: adoToken, + URL: adoRepo, + } + event.Organization = adoOrganization + + if err := adoClient.SetClient(ctx, nil, event, nil, nil); err != nil { + return nil, options.E2E{}, azprovider.Provider{}, err + } + + return run, e2eoptions, adoClient, nil +} + +func TearDown(ctx context.Context, t *testing.T, runcnx *params.Run, azProvider azprovider.Provider, opts options.E2E, prID *int, targetNS string, ref *string, commitID *string) { + + if os.Getenv("TEST_NOCLEANUP") == "true" { + runcnx.Clients.Log.Infof("Not cleaning up PR since TEST_NOCLEANUP is set") + return + } + runcnx.Clients.Log.Infof("Abandoning PR #%d", prID) + + statusAbandoned := git.PullRequestStatusValues.Abandoned + prUpdate := git.GitPullRequest{ + Status: &statusAbandoned, + } + + runcnx.Clients.Log.Infof("Abandoning PR #%d", prID) + + // Update the pull request to abandon it + _, err := azProvider.Client.UpdatePullRequest(ctx, git.UpdatePullRequestArgs{ + GitPullRequestToUpdate: &prUpdate, + RepositoryId: &opts.ProjectName, + PullRequestId: prID, + Project: &opts.ProjectName, + }) + assert.NilError(t, err) + + //Delete the branch by updating the reference to an empty object ID + emptyObjectID := "0000000000000000000000000000000000000000" // This is used to indicate a deletion + + refUpdate := git.GitRefUpdate{ + Name: ref, + OldObjectId: commitID, + NewObjectId: &emptyObjectID, + } + + refUpdates := []git.GitRefUpdate{refUpdate} + _, err = azProvider.Client.UpdateRefs(ctx, git.UpdateRefsArgs{ + RefUpdates: &refUpdates, + RepositoryId: &opts.ProjectName, + Project: &opts.ProjectName, + }) + assert.NilError(t, err) + + repository.NSTearDown(ctx, t, runcnx, targetNS) +} diff --git a/test/pkg/options/options.go b/test/pkg/options/options.go index 47392b903..c53eeb15b 100644 --- a/test/pkg/options/options.go +++ b/test/pkg/options/options.go @@ -8,6 +8,7 @@ type E2E struct { Concurrency int UserName string Password string + ProjectName string } var ( From 5e62d2de696707e36a7850f0f570dfde2e1d42fb Mon Sep 17 00:00:00 2001 From: ayesha arshad Date: Mon, 6 May 2024 00:03:06 +0200 Subject: [PATCH 14/16] Fix - updated GitClient --- pkg/provider/azuredevops/azuredevops.go | 2 +- test/pkg/azuredevops/pr.go | 2 +- test/pkg/azuredevops/setup.go | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/pkg/provider/azuredevops/azuredevops.go b/pkg/provider/azuredevops/azuredevops.go index 48b64d0fd..90adcf8f5 100644 --- a/pkg/provider/azuredevops/azuredevops.go +++ b/pkg/provider/azuredevops/azuredevops.go @@ -455,7 +455,7 @@ func (v *Provider) SetClient(_ context.Context, run *params.Run, event *info.Eve if err != nil { return err } - v.CoreClient, err = core.NewClient(ctx, v.connection) + v.CoreClient, err = core.NewClient(ctx, connection) if err != nil { return err } diff --git a/test/pkg/azuredevops/pr.go b/test/pkg/azuredevops/pr.go index 1a2e48d0b..a51becabf 100644 --- a/test/pkg/azuredevops/pr.go +++ b/test/pkg/azuredevops/pr.go @@ -23,7 +23,7 @@ func MakePR(ctx context.Context, t *testing.T, azProvider azprovider.Provider, o assert.NilError(t, err) fileContent := entries[".tekton/pipelinerun.yaml"] - gitClient := azProvider.Client + gitClient := azProvider.GitClient filter := "heads/main" // Create a new branch from the default branch diff --git a/test/pkg/azuredevops/setup.go b/test/pkg/azuredevops/setup.go index 24be8f6fe..afb4c52e8 100644 --- a/test/pkg/azuredevops/setup.go +++ b/test/pkg/azuredevops/setup.go @@ -88,7 +88,7 @@ func TearDown(ctx context.Context, t *testing.T, runcnx *params.Run, azProvider runcnx.Clients.Log.Infof("Abandoning PR #%d", prID) // Update the pull request to abandon it - _, err := azProvider.Client.UpdatePullRequest(ctx, git.UpdatePullRequestArgs{ + _, err := azProvider.GitClient.UpdatePullRequest(ctx, git.UpdatePullRequestArgs{ GitPullRequestToUpdate: &prUpdate, RepositoryId: &opts.ProjectName, PullRequestId: prID, @@ -106,7 +106,7 @@ func TearDown(ctx context.Context, t *testing.T, runcnx *params.Run, azProvider } refUpdates := []git.GitRefUpdate{refUpdate} - _, err = azProvider.Client.UpdateRefs(ctx, git.UpdateRefsArgs{ + _, err = azProvider.GitClient.UpdateRefs(ctx, git.UpdateRefsArgs{ RefUpdates: &refUpdates, RepositoryId: &opts.ProjectName, Project: &opts.ProjectName, From 15005da5e3cba9a6260bd40d8a451c3d7f4950ec Mon Sep 17 00:00:00 2001 From: ayesha arshad Date: Mon, 6 May 2024 08:34:41 +0200 Subject: [PATCH 15/16] update - update parse --- pkg/provider/azuredevops/parse_payload.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pkg/provider/azuredevops/parse_payload.go b/pkg/provider/azuredevops/parse_payload.go index 6165fef32..003945261 100644 --- a/pkg/provider/azuredevops/parse_payload.go +++ b/pkg/provider/azuredevops/parse_payload.go @@ -92,8 +92,8 @@ func (v *Provider) ParsePayload(_ context.Context, _ *params.Run, req *http.Requ // Constructing URLs remoteURL := *prEvent.Repository.WebURL - processedEvent.BaseURL = fmt.Sprintf("%s?version=GB%s", remoteURL, processedEvent.BaseBranch) - processedEvent.HeadURL = fmt.Sprintf("%s?version=GB%s", remoteURL, processedEvent.HeadBranch) + // processedEvent.BaseURL = fmt.Sprintf("%s?version=GB%s", remoteURL, processedEvent.BaseBranch) + // processedEvent.HeadURL = fmt.Sprintf("%s?version=GB%s", remoteURL, processedEvent.HeadBranch) processedEvent.TriggerTarget = triggertype.PullRequest From fd7c2c33159ac9f7971383e862dc189accf4384a Mon Sep 17 00:00:00 2001 From: ayesha arshad Date: Mon, 6 May 2024 08:38:25 +0200 Subject: [PATCH 16/16] cleanup - code cleanup --- pkg/provider/azuredevops/detect.go | 1 - pkg/provider/azuredevops/detect_test.go | 3 +-- pkg/provider/azuredevops/parse_payload.go | 11 +---------- pkg/provider/azuredevops/parse_payload_test.go | 4 +--- pkg/provider/azuredevops/test/setup.go | 2 +- 5 files changed, 4 insertions(+), 17 deletions(-) diff --git a/pkg/provider/azuredevops/detect.go b/pkg/provider/azuredevops/detect.go index 02f8c07d7..5bcc7f23f 100644 --- a/pkg/provider/azuredevops/detect.go +++ b/pkg/provider/azuredevops/detect.go @@ -38,7 +38,6 @@ func (v *Provider) Detect(req *http.Request, payload string, logger *zap.Sugared normalizedEventType := strings.ReplaceAll(*event.EventType, "-", ".") if strings.Contains(normalizedEventType, eventType) { logger = logger.With("provider", "azuredevops", "event-type", eventType) - // Simplified switch, expand as needed based on the Azure DevOps events you handle switch eventType { case "git.push", "git.pullrequest.created", "git.pullrequest.updated", "git.pullrequest.comment": return setLoggerAndProceed(true, "", nil) diff --git a/pkg/provider/azuredevops/detect_test.go b/pkg/provider/azuredevops/detect_test.go index 3478c4e40..ab4ec9cc1 100644 --- a/pkg/provider/azuredevops/detect_test.go +++ b/pkg/provider/azuredevops/detect_test.go @@ -15,7 +15,6 @@ func TestProvider_Detect(t *testing.T) { gitPush := "git.push" gitPRCreated := "git.pullrequest.created" gitPRUpdated := "git.pullrequest.updated" - // Define more event types as needed tests := []struct { name string @@ -80,7 +79,7 @@ func TestProvider_Detect(t *testing.T) { header.Set("X-Azure-DevOps-EventType", tt.eventType) req := &http.Request{Header: header} - v := Provider{} // Assuming Provider is your Azure DevOps provider struct + v := Provider{} isADO, processReq, _, reason, err := v.Detect(req, string(payload), logger) if tt.wantErr { diff --git a/pkg/provider/azuredevops/parse_payload.go b/pkg/provider/azuredevops/parse_payload.go index 003945261..19da3e988 100644 --- a/pkg/provider/azuredevops/parse_payload.go +++ b/pkg/provider/azuredevops/parse_payload.go @@ -30,7 +30,6 @@ func (v *Provider) ParsePayload(_ context.Context, _ *params.Run, req *http.Requ processedEvent := info.NewEvent() processedEvent.EventType = req.Header.Get("X-Azure-DevOps-EventType") - // processedEvent.EventType = *genericEvent.EventType resourceBytes, err := json.Marshal(genericEvent.Resource) if err != nil { @@ -63,7 +62,6 @@ func (v *Provider) ParsePayload(_ context.Context, _ *params.Run, req *http.Requ processedEvent.URL = pushEvent.Repository.RemoteURL processedEvent.DefaultBranch = pushEvent.Repository.DefaultBranch processedEvent.TriggerTarget = triggertype.Push - // Assuming the repository URL can serve as both BaseURL and HeadURL for viewing purposes processedEvent.BaseURL = pushEvent.Repository.URL processedEvent.HeadURL = pushEvent.Repository.URL if len(pushEvent.RefUpdates) > 0 { @@ -84,19 +82,12 @@ func (v *Provider) ParsePayload(_ context.Context, _ *params.Run, req *http.Requ processedEvent.SHAURL = prEvent.LastMergeSourceCommit.URL processedEvent.SHATitle = prEvent.LastMergeSourceCommit.Comment - // Extract branch names from the ref names - // Azure DevOps ref names are full references (refs/heads/branchName), so we'll extract the branch name processedEvent.BaseBranch = ExtractBranchName(prEvent.TargetRefName) processedEvent.HeadBranch = ExtractBranchName(prEvent.SourceRefName) processedEvent.DefaultBranch = prEvent.Repository.DefaultBranch - // Constructing URLs - remoteURL := *prEvent.Repository.WebURL - // processedEvent.BaseURL = fmt.Sprintf("%s?version=GB%s", remoteURL, processedEvent.BaseBranch) - // processedEvent.HeadURL = fmt.Sprintf("%s?version=GB%s", remoteURL, processedEvent.HeadBranch) - processedEvent.TriggerTarget = triggertype.PullRequest - + remoteURL := *prEvent.Repository.WebURL baseURL, err := ExtractBaseURL(remoteURL) if err != nil { return nil, fmt.Errorf("not able to extract organization url") diff --git a/pkg/provider/azuredevops/parse_payload_test.go b/pkg/provider/azuredevops/parse_payload_test.go index 38a3508f3..72eb4f210 100644 --- a/pkg/provider/azuredevops/parse_payload_test.go +++ b/pkg/provider/azuredevops/parse_payload_test.go @@ -11,7 +11,6 @@ import ( ) func TestParsePayload(t *testing.T) { - // Mock request setup mockRequest := &http.Request{} // Mock context @@ -115,7 +114,7 @@ func TestParsePayload(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - v := Provider{} // Assuming this is your Azure DevOps provider + v := Provider{} run := ¶ms.Run{} gotEvent, err := v.ParsePayload(ctx, run, mockRequest, tt.payload) @@ -126,7 +125,6 @@ func TestParsePayload(t *testing.T) { assert.Equal(t, tt.wantEvent.EventType, gotEvent.EventType) assert.Equal(t, tt.wantEvent.SHA, gotEvent.SHA) - // Add more assertions as needed }) } } diff --git a/pkg/provider/azuredevops/test/setup.go b/pkg/provider/azuredevops/test/setup.go index 9010378e3..c5c3f0a29 100644 --- a/pkg/provider/azuredevops/test/setup.go +++ b/pkg/provider/azuredevops/test/setup.go @@ -77,7 +77,7 @@ func (m *MockCoreClient) GetTeamMembersWithExtendedProperties(ctx context.Contex var teamMembers []webapi.TeamMember for _, memberID := range members { - identityID := memberID // Simplifying identity ID use case + identityID := memberID teamMembers = append(teamMembers, webapi.TeamMember{ Identity: &webapi.IdentityRef{Id: &identityID}, })