Skip to content
This repository has been archived by the owner on Aug 24, 2023. It is now read-only.

Commit

Permalink
Improved code logic
Browse files Browse the repository at this point in the history
  • Loading branch information
StiviiK committed Sep 16, 2021
1 parent 1d20501 commit 86257e5
Show file tree
Hide file tree
Showing 4 changed files with 99 additions and 73 deletions.
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ Usage:
Flags:
-h, --help help for trigger
-p, --project string Name of the Azure DevOps Project
--targetRefName string (Optional) Specify the GitRef on which the Pipeline should run
--targetVersion string (Optional) Specify the Commit Hash on which the Pipeline should run
-r, --targetRefName string (Optional) Specify the GitRef on which the Pipeline should run
-v, --targetVersion string (Optional) Specify the Commit Hash on which the Pipeline should run
-w, --waitForCompletion (Optional) Specify if the task should block until the target pipeline is completed
Global Flags:
Expand Down Expand Up @@ -49,4 +49,4 @@ steps:
--waitForCompletion \
-- "My Demo Pipeline"
displayName: "Trigger 'My Demo Pipeline' pipeline"
``
```
125 changes: 59 additions & 66 deletions cmd/pipelines/trigger/trigger.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ package trigger
import (
"encoding/json"
"errors"
"fmt"
"time"

"github.com/Azure/go-autorest/autorest/to"
Expand All @@ -44,11 +43,13 @@ var (
}
targetRefNameFlag azure.FlagDefinition = azure.FlagDefinition{
Name: "targetRefName",
Shorthand: "r",
Default: "",
Description: "(Optional) Specify the GitRef on which the Pipeline should run",
}
targetVersionFlag azure.FlagDefinition = azure.FlagDefinition{
Name: "targetVersion",
Shorthand: "v",
Default: "",
Description: "(Optional) Specify the Commit Hash on which the Pipeline should run",
}
Expand Down Expand Up @@ -87,97 +88,89 @@ var Cmd = &cobra.Command{
}

pipelinesClient := pipelines.NewClient(cmd.Context(), connection)
result, err := azure.ListDevOpsPipelines(cmd.Context(), pipelinesClient, &project)
result, err := azure.GetDevOpsPiplines(cmd.Context(), pipelinesClient, project, args)
if err != nil {
return err
}

repositoryResourceParameters := map[string]pipelines.RepositoryResourceParameters{
"self": {},
}
repositoryResourceParameters := pipelines.RepositoryResourceParameters{}
if utils.IsFlagPassed(targetVersionFlag.Name, flags) {
targetVersion, err := flags.GetString(targetVersionFlag.Name)
if err != nil {
return err
}

repositoryResourceParameters.Version = to.StringPtr(targetVersion)
}
if utils.IsFlagPassed(targetRefNameFlag.Name, flags) {
targetRefName, err := flags.GetString(targetRefNameFlag.Name)
if err != nil {
return err
}

if entry, ok := repositoryResourceParameters["self"]; ok {
entry.RefName = to.StringPtr(targetRefName)
repositoryResourceParameters["self"] = entry
}
repositoryResourceParameters.RefName = to.StringPtr(targetRefName)
}

if utils.IsFlagPassed(targetVersionFlag.Name, flags) {
targetVersion, err := flags.GetString(targetVersionFlag.Name)
for _, pipeline := range result {
runResult, err := pipelinesClient.RunPipeline(cmd.Context(), pipelines.RunPipelineArgs{
Project: &project,
PipelineId: pipeline.Id,
RunParameters: &pipelines.RunPipelineParameters{
Resources: &pipelines.RunResourcesParameters{
Repositories: &map[string]pipelines.RepositoryResourceParameters{"self": repositoryResourceParameters},
},
},
})
if err != nil {
return err
}

if entry, ok := repositoryResourceParameters["self"]; ok {
entry.Version = to.StringPtr(targetVersion)
repositoryResourceParameters["self"] = entry
if *runResult.State != pipelines.RunStateValues.InProgress && *runResult.State != pipelines.RunStateValues.Completed {
log.Errorf("unkown error occured, result: %s, state: %s", string(*runResult.Result), string(*runResult.State))
}
}

for _, pipeline := range result {
if utils.StringInSlice(*pipeline.Name, args) {
runResult, err := pipelinesClient.RunPipeline(cmd.Context(), pipelines.RunPipelineArgs{
Project: &project,
PipelineId: pipeline.Id,
RunParameters: &pipelines.RunPipelineParameters{
Resources: &pipelines.RunResourcesParameters{
Repositories: &repositoryResourceParameters,
},
},
})
if err != nil {
return err
}
log.Info(*runResult.Url)

if *runResult.State != pipelines.RunStateValues.InProgress && *runResult.State != pipelines.RunStateValues.Completed {
return fmt.Errorf("unkown error occured, result: %s, state: %s", string(*runResult.Result), string(*runResult.State))
}

log.Info(*runResult.Url)

if wait {
for {
run, err := pipelinesClient.GetRun(cmd.Context(), pipelines.GetRunArgs{
Project: &project,
PipelineId: pipeline.Id,
RunId: runResult.Id,
})
if err != nil {
return err
}
if wait {
__Completion_Check_Loop: // labeled for better code readablilty
for {
run, err := pipelinesClient.GetRun(cmd.Context(), pipelines.GetRunArgs{
Project: &project,
PipelineId: pipeline.Id,
RunId: runResult.Id,
})
if err != nil {
return err
}

if run.Result != nil {
switch *run.Result {
case pipelines.RunResultValues.Succeeded:
json, err := json.Marshal(*run)
if err != nil {
return fmt.Errorf("failed to serialize result into json, %s", err.Error())
} else {
log.Info(string(json))
return nil
}
case pipelines.RunResultValues.Failed:
return fmt.Errorf("pipeline %s failed", *pipeline.Name)
case pipelines.RunResultValues.Canceled:
return fmt.Errorf("pipeline %s was canceled", *pipeline.Name)
if run.Result != nil {
switch *run.Result {
case pipelines.RunResultValues.Succeeded:
json, err := json.Marshal(*run)
if err != nil {
log.Errorf("failed to serialize result into json, %s", err.Error())
} else {
log.Info(string(json))
}
case pipelines.RunResultValues.Failed:
log.Errorf("pipeline %s failed", *pipeline.Name)
case pipelines.RunResultValues.Canceled:
log.Warnf("pipeline %s was canceled", *pipeline.Name)
default:
log.Errorf("pipeline %s, unknown error occured, result: %s", *pipeline.Name, string(*run.Result))
}

time.Sleep(1 * time.Second)
break __Completion_Check_Loop
}

time.Sleep(10 * time.Second)
}
} else {
json, err := json.Marshal(*runResult)
if err != nil {
log.Errorf("pipeline %s, failed to serialize result into json, %s", *&pipeline.Name, err.Error())
} else {
json, err := json.Marshal(*runResult)
if err != nil {
return fmt.Errorf("failed to serialize result into json, %s", err.Error())
} else {
log.Info(string(json))
}
log.Info(string(json))
}
}
}
Expand Down
26 changes: 22 additions & 4 deletions pkg/azure/azure.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,14 @@ package azure

import (
"context"
"fmt"
"strings"

"github.com/microsoft/azure-devops-go-api/azuredevops"
"github.com/microsoft/azure-devops-go-api/azuredevops/pipelines"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/whiteducksoftware/azure-devops-trigger-pipelines-task/pkg/utils"
)

type FlagDefinition struct {
Expand Down Expand Up @@ -93,22 +96,37 @@ func GetDevOpsClient(flags *pflag.FlagSet) (*azuredevops.Connection, error) {
return azuredevops.NewPatConnection(orgURL, pat), nil
}

func ListDevOpsPipelines(ctx context.Context, client pipelines.Client, project *string) ([]pipelines.Pipeline, error) {
output := make([]pipelines.Pipeline, 0)
func GetDevOpsPiplines(ctx context.Context, client pipelines.Client, project string, names []string) ([]pipelines.Pipeline, error) {
var (
output []pipelines.Pipeline
foundNames []string
)

var continuationToken string
for ok := true; ok; ok = continuationToken != "" {
result, err := client.ListPipelines(ctx, pipelines.ListPipelinesArgs{
Project: project,
Project: &project,
ContinuationToken: &continuationToken,
})
if err != nil {
return nil, err
}

output = append(output, result.Value...)
for _, pipeline := range result.Value {
if utils.StringInSlice(*pipeline.Name, names) {
output = append(output, pipeline)
foundNames = append(foundNames, *pipeline.Name)
}
}

continuationToken = result.ContinuationToken
}

// Check if we found all pipelines
if len(names) != len(foundNames) {
missingNames := utils.Diff(names, foundNames)
return nil, fmt.Errorf("following pipelines could not be found: %s", strings.Join(missingNames, ", "))
}

return output, nil
}
15 changes: 15 additions & 0 deletions pkg/utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,18 @@ func IsFlagPassed(name string, flags *pflag.FlagSet) bool {
})
return found
}

// Diff returns the elements in `a` that aren't in `b`.
func Diff(a, b []string) []string {
mb := make(map[string]struct{}, len(b))
for _, x := range b {
mb[x] = struct{}{}
}
var diff []string
for _, x := range a {
if _, found := mb[x]; !found {
diff = append(diff, x)
}
}
return diff
}

0 comments on commit 86257e5

Please sign in to comment.