From c1ff28ef9f0baedc3d6580570ccf2cdf7d6cb933 Mon Sep 17 00:00:00 2001 From: Simone Gotti Date: Wed, 31 Jul 2019 15:39:07 +0200 Subject: [PATCH] *: export clients and related types Export clients and related packages. The main rule is to not import internal packages from exported packages. The gateway client and related types are totally decoupled from the gateway service (not shared types between the client and the server). Instead the configstore and the runservice client currently share many types that are now exported (decoupling them will require that a lot of types must be duplicated and the need of functions to convert between them, this will be done in future when the APIs will be declared as stable). --- .agola/config.jsonnet | 2 +- cmd/agola/cmd/directrunstart.go | 7 +- cmd/agola/cmd/orgcreate.go | 12 +- cmd/agola/cmd/orgdelete.go | 4 +- cmd/agola/cmd/orgmemberadd.go | 8 +- cmd/agola/cmd/orgmemberlist.go | 4 +- cmd/agola/cmd/orgmemberremove.go | 4 +- cmd/agola/cmd/projectcreate.go | 22 ++- cmd/agola/cmd/projectdelete.go | 4 +- cmd/agola/cmd/projectgroupcreate.go | 14 +- cmd/agola/cmd/projectlist.go | 8 +- cmd/agola/cmd/projectreconfig.go | 4 +- cmd/agola/cmd/projectsecretcreate.go | 10 +- cmd/agola/cmd/projectsecretdelete.go | 4 +- cmd/agola/cmd/projectsecretupdate.go | 10 +- cmd/agola/cmd/projectvariablecreate.go | 17 +- cmd/agola/cmd/projectvariabledelete.go | 4 +- cmd/agola/cmd/projectvariableupdate.go | 14 +- cmd/agola/cmd/remotesourcecreate.go | 12 +- cmd/agola/cmd/remotesourcelist.go | 8 +- cmd/agola/cmd/remotesourceupdate.go | 7 +- cmd/agola/cmd/runlist.go | 9 +- cmd/agola/cmd/usercreate.go | 7 +- cmd/agola/cmd/userdelete.go | 4 +- cmd/agola/cmd/userlacreate.go | 7 +- cmd/agola/cmd/userladelete.go | 4 +- cmd/agola/cmd/userlist.go | 8 +- cmd/agola/cmd/usertokencreate.go | 7 +- cmd/agola/cmd/usertokendelete.go | 4 +- internal/config/config.go | 8 +- internal/config/config_test.go | 2 +- internal/gitsources/agolagit/agolagit.go | 1 - internal/runconfig/runconfig.go | 4 +- internal/runconfig/runconfig_test.go | 4 +- internal/services/common/gitsource.go | 2 +- internal/services/common/variables.go | 14 +- internal/services/common/variables_test.go | 79 +++++----- internal/services/configstore/action/org.go | 2 +- .../services/configstore/action/project.go | 2 +- .../configstore/action/projectgroup.go | 2 +- .../configstore/action/remotesource.go | 2 +- .../services/configstore/action/secret.go | 2 +- internal/services/configstore/action/user.go | 2 +- .../services/configstore/action/variable.go | 2 +- internal/services/configstore/api/api.go | 3 +- internal/services/configstore/api/org.go | 22 +-- internal/services/configstore/api/project.go | 25 +-- .../services/configstore/api/projectgroup.go | 25 +-- .../services/configstore/api/remotesource.go | 4 +- internal/services/configstore/api/secret.go | 15 +- internal/services/configstore/api/user.go | 66 ++------ internal/services/configstore/api/variable.go | 15 +- internal/services/configstore/configstore.go | 2 +- .../services/configstore/configstore_test.go | 2 +- internal/services/configstore/readdb/org.go | 2 +- .../services/configstore/readdb/project.go | 2 +- .../configstore/readdb/projectgroup.go | 2 +- .../services/configstore/readdb/readdb.go | 2 +- .../configstore/readdb/remotesource.go | 2 +- .../services/configstore/readdb/resolve.go | 2 +- .../services/configstore/readdb/secret.go | 2 +- internal/services/configstore/readdb/user.go | 2 +- .../services/configstore/readdb/variable.go | 2 +- internal/services/executor/api.go | 2 +- internal/services/executor/driver/docker.go | 40 ++--- internal/services/executor/driver/driver.go | 8 +- internal/services/executor/driver/k8s.go | 16 +- internal/services/executor/executor.go | 8 +- .../services/executor/registry/registry.go | 2 +- internal/services/gateway/action/action.go | 10 +- internal/services/gateway/action/auth.go | 2 +- internal/services/gateway/action/badge.go | 2 +- internal/services/gateway/action/org.go | 2 +- internal/services/gateway/action/project.go | 18 +-- .../services/gateway/action/projectgroup.go | 14 +- .../services/gateway/action/remotesource.go | 2 +- internal/services/gateway/action/run.go | 30 ++-- internal/services/gateway/action/secret.go | 16 +- internal/services/gateway/action/user.go | 18 +-- internal/services/gateway/action/variable.go | 22 +-- internal/services/gateway/api/api.go | 4 +- internal/services/gateway/api/badge.go | 4 - internal/services/gateway/api/oauth2.go | 30 ++-- internal/services/gateway/api/org.go | 67 +++----- internal/services/gateway/api/project.go | 51 ++---- internal/services/gateway/api/projectgroup.go | 43 ++--- internal/services/gateway/api/remoterepo.go | 20 +-- internal/services/gateway/api/remotesource.go | 47 +----- internal/services/gateway/api/run.go | 137 +++------------- internal/services/gateway/api/secret.go | 51 ++---- internal/services/gateway/api/user.go | 140 +++++------------ internal/services/gateway/api/variable.go | 127 ++++++++++----- internal/services/gateway/api/webhook.go | 10 +- internal/services/gateway/gateway.go | 12 +- internal/services/gateway/handlers/auth.go | 6 +- .../services/notification/commitstatus.go | 2 +- .../services/notification/notification.go | 12 +- internal/services/notification/runevents.go | 2 +- internal/services/runservice/action/action.go | 2 +- .../services/runservice/action/action_test.go | 2 +- internal/services/runservice/api/api.go | 86 ++-------- internal/services/runservice/api/executor.go | 2 +- internal/services/runservice/common/events.go | 2 +- internal/services/runservice/readdb/readdb.go | 2 +- internal/services/runservice/runservice.go | 2 +- internal/services/runservice/scheduler.go | 2 +- .../services/runservice/scheduler_test.go | 14 +- internal/services/runservice/store/store.go | 2 +- internal/services/scheduler/scheduler.go | 11 +- services/configstore/api/types/org.go | 28 ++++ services/configstore/api/types/project.go | 31 ++++ .../configstore/api/types/projectgroup.go | 31 ++++ services/configstore/api/types/secret.go | 27 ++++ services/configstore/api/types/user.go | 63 ++++++++ services/configstore/api/types/variable.go | 27 ++++ .../configstore/client}/client.go | 147 +++++++++--------- .../configstore/types/types.go | 2 +- .../configstore/types/types_test.go | 0 services/gateway/api/types/oauth2.go | 20 +++ services/gateway/api/types/org.go | 52 +++++++ services/gateway/api/types/project.go | 45 ++++++ services/gateway/api/types/projectgroup.go | 35 +++++ services/gateway/api/types/remoterepo.go | 20 +++ services/gateway/api/types/remotesource.go | 49 ++++++ services/gateway/api/types/run.go | 130 ++++++++++++++++ services/gateway/api/types/secret.go | 54 +++++++ services/gateway/api/types/user.go | 103 ++++++++++++ services/gateway/api/types/variable.go | 49 ++++++ services/gateway/api/types/visibility.go | 22 +++ services/gateway/api/types/when.go | 38 +++++ .../api => services/gateway/client}/client.go | 131 ++++++++-------- services/runservice/api/types/run.go | 82 ++++++++++ .../runservice/client}/client.go | 46 +++--- .../runservice/types/types.go | 11 +- {internal/common => services/types}/arch.go | 2 +- tests/setup_test.go | 30 ++-- util/pointer.go | 47 ++++++ 137 files changed, 1778 insertions(+), 1202 deletions(-) create mode 100644 services/configstore/api/types/org.go create mode 100644 services/configstore/api/types/project.go create mode 100644 services/configstore/api/types/projectgroup.go create mode 100644 services/configstore/api/types/secret.go create mode 100644 services/configstore/api/types/user.go create mode 100644 services/configstore/api/types/variable.go rename {internal/services/configstore/api => services/configstore/client}/client.go (78%) rename {internal/services => services}/configstore/types/types.go (99%) rename {internal/services => services}/configstore/types/types_test.go (100%) create mode 100644 services/gateway/api/types/oauth2.go create mode 100644 services/gateway/api/types/org.go create mode 100644 services/gateway/api/types/project.go create mode 100644 services/gateway/api/types/projectgroup.go create mode 100644 services/gateway/api/types/remoterepo.go create mode 100644 services/gateway/api/types/remotesource.go create mode 100644 services/gateway/api/types/run.go create mode 100644 services/gateway/api/types/secret.go create mode 100644 services/gateway/api/types/user.go create mode 100644 services/gateway/api/types/variable.go create mode 100644 services/gateway/api/types/visibility.go create mode 100644 services/gateway/api/types/when.go rename {internal/services/gateway/api => services/gateway/client}/client.go (76%) create mode 100644 services/runservice/api/types/run.go rename {internal/services/runservice/api => services/runservice/client}/client.go (85%) rename {internal/services => services}/runservice/types/types.go (98%) rename {internal/common => services/types}/arch.go (98%) create mode 100644 util/pointer.go diff --git a/.agola/config.jsonnet b/.agola/config.jsonnet index 689e644..a1f2ff9 100644 --- a/.agola/config.jsonnet +++ b/.agola/config.jsonnet @@ -36,7 +36,7 @@ local task_build_go(version, arch) = { { type: 'run', command: 'golangci-lint run --deadline 5m' }, { type: 'run', name: 'build docker/k8s drivers tests binary', command: 'CGO_ENABLED=0 go test -c ./internal/services/executor/driver -o ./bin/docker-tests' }, { type: 'run', name: 'build integration tests binary', command: 'go test -tags "sqlite_unlock_notify" -c ./tests -o ./bin/integration-tests' }, - { type: 'run', name: 'run tests', command: 'SKIP_DOCKER_TESTS=1 SKIP_K8S_TESTS=1 go test -v -count 1 ./cmd/... ./internal/...' }, + { type: 'run', name: 'run tests', command: 'SKIP_DOCKER_TESTS=1 SKIP_K8S_TESTS=1 go test -v -count 1 $(go list ./... | grep -v /tests)' }, { type: 'run', name: 'fetch gitea binary for integration tests', command: 'curl -L https://github.com/go-gitea/gitea/releases/download/v1.8.3/gitea-1.8.3-linux-amd64 -o ./bin/gitea && chmod +x ./bin/gitea' }, { type: 'save_to_workspace', contents: [{ source_dir: './bin', dest_dir: '/bin/', paths: ['*'] }] }, ], diff --git a/cmd/agola/cmd/directrunstart.go b/cmd/agola/cmd/directrunstart.go index dc9e7c8..885c36c 100644 --- a/cmd/agola/cmd/directrunstart.go +++ b/cmd/agola/cmd/directrunstart.go @@ -20,8 +20,9 @@ import ( "path" gitsave "agola.io/agola/internal/git-save" - "agola.io/agola/internal/services/gateway/api" "agola.io/agola/internal/util" + gwapitypes "agola.io/agola/services/gateway/api/types" + gwclient "agola.io/agola/services/gateway/client" uuid "github.com/satori/go.uuid" "github.com/spf13/cobra" @@ -62,7 +63,7 @@ func init() { } func directRunStart(cmd *cobra.Command, args []string) error { - gwclient := api.NewClient(gatewayURL, token) + gwclient := gwclient.NewClient(gatewayURL, token) user, _, err := gwclient.GetCurrentUser(context.TODO()) if err != nil { @@ -102,7 +103,7 @@ func directRunStart(cmd *cobra.Command, args []string) error { } log.Infof("starting direct run") - req := &api.UserCreateRunRequest{ + req := &gwapitypes.UserCreateRunRequest{ RepoUUID: repoUUID, RepoPath: repoPath, Branch: branch, diff --git a/cmd/agola/cmd/orgcreate.go b/cmd/agola/cmd/orgcreate.go index e2dff6e..86c50fc 100644 --- a/cmd/agola/cmd/orgcreate.go +++ b/cmd/agola/cmd/orgcreate.go @@ -17,8 +17,8 @@ package cmd import ( "context" - cstypes "agola.io/agola/internal/services/configstore/types" - "agola.io/agola/internal/services/gateway/api" + gwapitypes "agola.io/agola/services/gateway/api/types" + gwclient "agola.io/agola/services/gateway/client" "github.com/spf13/cobra" errors "golang.org/x/xerrors" @@ -55,16 +55,16 @@ func init() { } func orgCreate(cmd *cobra.Command, args []string) error { - gwclient := api.NewClient(gatewayURL, token) + gwclient := gwclient.NewClient(gatewayURL, token) // TODO(sgotti) make this a custom pflag Value? - if !cstypes.IsValidVisibility(cstypes.Visibility(orgCreateOpts.visibility)) { + if !IsValidVisibility(orgCreateOpts.visibility) { return errors.Errorf("invalid visibility %q", orgCreateOpts.visibility) } - req := &api.CreateOrgRequest{ + req := &gwapitypes.CreateOrgRequest{ Name: orgCreateOpts.name, - Visibility: cstypes.Visibility(orgCreateOpts.visibility), + Visibility: gwapitypes.Visibility(orgCreateOpts.visibility), } log.Infof("creating org") diff --git a/cmd/agola/cmd/orgdelete.go b/cmd/agola/cmd/orgdelete.go index cf0a552..9354028 100644 --- a/cmd/agola/cmd/orgdelete.go +++ b/cmd/agola/cmd/orgdelete.go @@ -17,7 +17,7 @@ package cmd import ( "context" - "agola.io/agola/internal/services/gateway/api" + gwclient "agola.io/agola/services/gateway/client" "github.com/spf13/cobra" errors "golang.org/x/xerrors" @@ -52,7 +52,7 @@ func init() { } func orgDelete(cmd *cobra.Command, args []string) error { - gwclient := api.NewClient(gatewayURL, token) + gwclient := gwclient.NewClient(gatewayURL, token) log.Infof("deleting organization %q", orgDeleteOpts.name) if _, err := gwclient.DeleteOrg(context.TODO(), orgDeleteOpts.name); err != nil { diff --git a/cmd/agola/cmd/orgmemberadd.go b/cmd/agola/cmd/orgmemberadd.go index 30d9ef2..26256a7 100644 --- a/cmd/agola/cmd/orgmemberadd.go +++ b/cmd/agola/cmd/orgmemberadd.go @@ -17,8 +17,8 @@ package cmd import ( "context" - cstypes "agola.io/agola/internal/services/configstore/types" - "agola.io/agola/internal/services/gateway/api" + gwapitypes "agola.io/agola/services/gateway/api/types" + gwclient "agola.io/agola/services/gateway/client" "github.com/spf13/cobra" errors "golang.org/x/xerrors" @@ -60,10 +60,10 @@ func init() { } func orgMemberAdd(cmd *cobra.Command, args []string) error { - gwclient := api.NewClient(gatewayURL, token) + gwclient := gwclient.NewClient(gatewayURL, token) log.Infof("adding/updating member %q to organization %q with role %q", orgMemberAddOpts.username, orgMemberAddOpts.orgname, orgMemberAddOpts.role) - _, _, err := gwclient.AddOrgMember(context.TODO(), orgMemberAddOpts.orgname, orgMemberAddOpts.username, cstypes.MemberRole(orgMemberAddOpts.role)) + _, _, err := gwclient.AddOrgMember(context.TODO(), orgMemberAddOpts.orgname, orgMemberAddOpts.username, gwapitypes.MemberRole(orgMemberAddOpts.role)) if err != nil { return errors.Errorf("failed to add/update organization member: %w", err) } diff --git a/cmd/agola/cmd/orgmemberlist.go b/cmd/agola/cmd/orgmemberlist.go index eded209..72c3961 100644 --- a/cmd/agola/cmd/orgmemberlist.go +++ b/cmd/agola/cmd/orgmemberlist.go @@ -19,7 +19,7 @@ import ( "encoding/json" "os" - "agola.io/agola/internal/services/gateway/api" + gwclient "agola.io/agola/services/gateway/client" "github.com/spf13/cobra" errors "golang.org/x/xerrors" @@ -54,7 +54,7 @@ func init() { } func orgMemberList(cmd *cobra.Command, args []string) error { - gwclient := api.NewClient(gatewayURL, token) + gwclient := gwclient.NewClient(gatewayURL, token) orgMembers, _, err := gwclient.GetOrgMembers(context.TODO(), orgMemberListOpts.orgname) if err != nil { diff --git a/cmd/agola/cmd/orgmemberremove.go b/cmd/agola/cmd/orgmemberremove.go index 0d98f2a..a6af19a 100644 --- a/cmd/agola/cmd/orgmemberremove.go +++ b/cmd/agola/cmd/orgmemberremove.go @@ -17,7 +17,7 @@ package cmd import ( "context" - "agola.io/agola/internal/services/gateway/api" + gwclient "agola.io/agola/services/gateway/client" "github.com/spf13/cobra" errors "golang.org/x/xerrors" @@ -57,7 +57,7 @@ func init() { } func orgMemberRemove(cmd *cobra.Command, args []string) error { - gwclient := api.NewClient(gatewayURL, token) + gwclient := gwclient.NewClient(gatewayURL, token) log.Infof("removing member %q from organization %q", orgMemberRemoveOpts.username, orgMemberRemoveOpts.orgname) _, err := gwclient.RemoveOrgMember(context.TODO(), orgMemberRemoveOpts.orgname, orgMemberRemoveOpts.username) diff --git a/cmd/agola/cmd/projectcreate.go b/cmd/agola/cmd/projectcreate.go index b238e99..9a5f1d2 100644 --- a/cmd/agola/cmd/projectcreate.go +++ b/cmd/agola/cmd/projectcreate.go @@ -17,8 +17,8 @@ package cmd import ( "context" - cstypes "agola.io/agola/internal/services/configstore/types" - "agola.io/agola/internal/services/gateway/api" + gwapitypes "agola.io/agola/services/gateway/api/types" + gwclient "agola.io/agola/services/gateway/client" "github.com/spf13/cobra" errors "golang.org/x/xerrors" @@ -71,18 +71,28 @@ func init() { cmdProject.AddCommand(cmdProjectCreate) } +func IsValidVisibility(v string) bool { + switch gwapitypes.Visibility(v) { + case gwapitypes.VisibilityPublic: + case gwapitypes.VisibilityPrivate: + default: + return false + } + return true +} + func projectCreate(cmd *cobra.Command, args []string) error { - gwclient := api.NewClient(gatewayURL, token) + gwclient := gwclient.NewClient(gatewayURL, token) // TODO(sgotti) make this a custom pflag Value? - if !cstypes.IsValidVisibility(cstypes.Visibility(projectCreateOpts.visibility)) { + if !IsValidVisibility(projectCreateOpts.visibility) { return errors.Errorf("invalid visibility %q", projectCreateOpts.visibility) } - req := &api.CreateProjectRequest{ + req := &gwapitypes.CreateProjectRequest{ Name: projectCreateOpts.name, ParentRef: projectCreateOpts.parentPath, - Visibility: cstypes.Visibility(projectCreateOpts.visibility), + Visibility: gwapitypes.Visibility(projectCreateOpts.visibility), RepoPath: projectCreateOpts.repoPath, RemoteSourceName: projectCreateOpts.remoteSourceName, SkipSSHHostKeyCheck: projectCreateOpts.skipSSHHostKeyCheck, diff --git a/cmd/agola/cmd/projectdelete.go b/cmd/agola/cmd/projectdelete.go index dbdfcd1..49915a3 100644 --- a/cmd/agola/cmd/projectdelete.go +++ b/cmd/agola/cmd/projectdelete.go @@ -17,7 +17,7 @@ package cmd import ( "context" - "agola.io/agola/internal/services/gateway/api" + gwclient "agola.io/agola/services/gateway/client" "github.com/spf13/cobra" errors "golang.org/x/xerrors" @@ -52,7 +52,7 @@ func init() { } func projectDelete(cmd *cobra.Command, args []string) error { - gwclient := api.NewClient(gatewayURL, token) + gwclient := gwclient.NewClient(gatewayURL, token) log.Infof("deleting project") diff --git a/cmd/agola/cmd/projectgroupcreate.go b/cmd/agola/cmd/projectgroupcreate.go index 5b5a82f..0a7e003 100644 --- a/cmd/agola/cmd/projectgroupcreate.go +++ b/cmd/agola/cmd/projectgroupcreate.go @@ -17,8 +17,8 @@ package cmd import ( "context" - cstypes "agola.io/agola/internal/services/configstore/types" - "agola.io/agola/internal/services/gateway/api" + gwapitypes "agola.io/agola/services/gateway/api/types" + gwclient "agola.io/agola/services/gateway/client" "github.com/spf13/cobra" errors "golang.org/x/xerrors" @@ -60,17 +60,17 @@ func init() { } func projectGroupCreate(cmd *cobra.Command, args []string) error { - gwclient := api.NewClient(gatewayURL, token) + gwclient := gwclient.NewClient(gatewayURL, token) // TODO(sgotti) make this a custom pflag Value? - if !cstypes.IsValidVisibility(cstypes.Visibility(projectCreateOpts.visibility)) { - return errors.Errorf("invalid visibility %q", projectCreateOpts.visibility) + if !IsValidVisibility(projectGroupCreateOpts.visibility) { + return errors.Errorf("invalid visibility %q", projectGroupCreateOpts.visibility) } - req := &api.CreateProjectGroupRequest{ + req := &gwapitypes.CreateProjectGroupRequest{ Name: projectGroupCreateOpts.name, ParentRef: projectGroupCreateOpts.parentPath, - Visibility: cstypes.Visibility(projectCreateOpts.visibility), + Visibility: gwapitypes.Visibility(projectGroupCreateOpts.visibility), } log.Infof("creating project group") diff --git a/cmd/agola/cmd/projectlist.go b/cmd/agola/cmd/projectlist.go index 6cdf5b1..f5c1381 100644 --- a/cmd/agola/cmd/projectlist.go +++ b/cmd/agola/cmd/projectlist.go @@ -18,7 +18,9 @@ import ( "context" "fmt" - "agola.io/agola/internal/services/gateway/api" + gwapitypes "agola.io/agola/services/gateway/api/types" + gwclient "agola.io/agola/services/gateway/client" + "github.com/spf13/cobra" ) @@ -50,14 +52,14 @@ func init() { cmdProject.AddCommand(cmdProjectList) } -func printProjects(projects []*api.ProjectResponse) { +func printProjects(projects []*gwapitypes.ProjectResponse) { for _, project := range projects { fmt.Printf("%s: Name: %s\n", project.ID, project.Name) } } func projectList(cmd *cobra.Command, args []string) error { - gwclient := api.NewClient(gatewayURL, token) + gwclient := gwclient.NewClient(gatewayURL, token) projects, _, err := gwclient.GetProjectGroupProjects(context.TODO(), projectListOpts.parentPath) if err != nil { diff --git a/cmd/agola/cmd/projectreconfig.go b/cmd/agola/cmd/projectreconfig.go index 0c86c16..35b6b54 100644 --- a/cmd/agola/cmd/projectreconfig.go +++ b/cmd/agola/cmd/projectreconfig.go @@ -17,7 +17,7 @@ package cmd import ( "context" - "agola.io/agola/internal/services/gateway/api" + gwclient "agola.io/agola/services/gateway/client" "github.com/spf13/cobra" errors "golang.org/x/xerrors" @@ -52,7 +52,7 @@ func init() { } func projectReconfig(cmd *cobra.Command, args []string) error { - gwclient := api.NewClient(gatewayURL, token) + gwclient := gwclient.NewClient(gatewayURL, token) log.Infof("reconfiguring remote project") if _, err := gwclient.ReconfigProject(context.TODO(), projectReconfigOpts.name); err != nil { diff --git a/cmd/agola/cmd/projectsecretcreate.go b/cmd/agola/cmd/projectsecretcreate.go index d249b97..71f8b45 100644 --- a/cmd/agola/cmd/projectsecretcreate.go +++ b/cmd/agola/cmd/projectsecretcreate.go @@ -19,8 +19,8 @@ import ( "io/ioutil" "os" - cstypes "agola.io/agola/internal/services/configstore/types" - "agola.io/agola/internal/services/gateway/api" + gwapitypes "agola.io/agola/services/gateway/api/types" + gwclient "agola.io/agola/services/gateway/client" "github.com/ghodss/yaml" "github.com/spf13/cobra" @@ -73,7 +73,7 @@ func init() { } func secretCreate(cmd *cobra.Command, ownertype string, args []string) error { - gwclient := api.NewClient(gatewayURL, token) + gwclient := gwclient.NewClient(gatewayURL, token) // "github.com/ghodss/yaml" doesn't provide a streaming decoder var data []byte @@ -94,9 +94,9 @@ func secretCreate(cmd *cobra.Command, ownertype string, args []string) error { if err := yaml.Unmarshal(data, &secretData); err != nil { log.Fatalf("failed to unmarshal secret: %v", err) } - req := &api.CreateSecretRequest{ + req := &gwapitypes.CreateSecretRequest{ Name: secretCreateOpts.name, - Type: cstypes.SecretTypeInternal, + Type: gwapitypes.SecretTypeInternal, Data: secretData, } diff --git a/cmd/agola/cmd/projectsecretdelete.go b/cmd/agola/cmd/projectsecretdelete.go index e898b34..08a7f72 100644 --- a/cmd/agola/cmd/projectsecretdelete.go +++ b/cmd/agola/cmd/projectsecretdelete.go @@ -17,7 +17,7 @@ package cmd import ( "context" - "agola.io/agola/internal/services/gateway/api" + gwclient "agola.io/agola/services/gateway/client" "github.com/spf13/cobra" errors "golang.org/x/xerrors" @@ -57,7 +57,7 @@ func init() { } func secretDelete(cmd *cobra.Command, ownertype string, args []string) error { - gwclient := api.NewClient(gatewayURL, token) + gwclient := gwclient.NewClient(gatewayURL, token) switch ownertype { case "project": diff --git a/cmd/agola/cmd/projectsecretupdate.go b/cmd/agola/cmd/projectsecretupdate.go index b483fd9..022ced4 100644 --- a/cmd/agola/cmd/projectsecretupdate.go +++ b/cmd/agola/cmd/projectsecretupdate.go @@ -19,8 +19,8 @@ import ( "io/ioutil" "os" - cstypes "agola.io/agola/internal/services/configstore/types" - "agola.io/agola/internal/services/gateway/api" + gwapitypes "agola.io/agola/services/gateway/api/types" + gwclient "agola.io/agola/services/gateway/client" "github.com/ghodss/yaml" "github.com/spf13/cobra" @@ -75,7 +75,7 @@ func init() { } func secretUpdate(cmd *cobra.Command, ownertype string, args []string) error { - gwclient := api.NewClient(gatewayURL, token) + gwclient := gwclient.NewClient(gatewayURL, token) // "github.com/ghodss/yaml" doesn't provide a streaming decoder var data []byte @@ -96,9 +96,9 @@ func secretUpdate(cmd *cobra.Command, ownertype string, args []string) error { if err := yaml.Unmarshal(data, &secretData); err != nil { log.Fatalf("failed to unmarshal secret: %v", err) } - req := &api.UpdateSecretRequest{ + req := &gwapitypes.UpdateSecretRequest{ Name: secretUpdateOpts.name, - Type: cstypes.SecretTypeInternal, + Type: gwapitypes.SecretTypeInternal, Data: secretData, } diff --git a/cmd/agola/cmd/projectvariablecreate.go b/cmd/agola/cmd/projectvariablecreate.go index f3a2272..c3f7925 100644 --- a/cmd/agola/cmd/projectvariablecreate.go +++ b/cmd/agola/cmd/projectvariablecreate.go @@ -19,9 +19,8 @@ import ( "io/ioutil" "os" - "agola.io/agola/internal/config" - cstypes "agola.io/agola/internal/services/configstore/types" - "agola.io/agola/internal/services/gateway/api" + gwapitypes "agola.io/agola/services/gateway/api/types" + gwclient "agola.io/agola/services/gateway/client" "github.com/ghodss/yaml" "github.com/spf13/cobra" @@ -92,11 +91,11 @@ type VariableValue struct { SecretName string `json:"secret_name,omitempty"` SecretVar string `json:"secret_var,omitempty"` - When *config.When `json:"when,omitempty"` + When *gwapitypes.When `json:"when,omitempty"` } func variableCreate(cmd *cobra.Command, ownertype string, args []string) error { - gwclient := api.NewClient(gatewayURL, token) + gwclient := gwclient.NewClient(gatewayURL, token) // "github.com/ghodss/yaml" doesn't provide a streaming decoder var data []byte @@ -117,15 +116,15 @@ func variableCreate(cmd *cobra.Command, ownertype string, args []string) error { if err := yaml.Unmarshal(data, &values); err != nil { log.Fatalf("failed to unmarshal values: %v", err) } - rvalues := []cstypes.VariableValue{} + rvalues := []gwapitypes.VariableValueRequest{} for _, value := range values { - rvalues = append(rvalues, cstypes.VariableValue{ + rvalues = append(rvalues, gwapitypes.VariableValueRequest{ SecretName: value.SecretName, SecretVar: value.SecretVar, - When: (*cstypes.When)(value.When), + When: value.When, }) } - req := &api.CreateVariableRequest{ + req := &gwapitypes.CreateVariableRequest{ Name: variableCreateOpts.name, Values: rvalues, } diff --git a/cmd/agola/cmd/projectvariabledelete.go b/cmd/agola/cmd/projectvariabledelete.go index e7943f0..9d529a7 100644 --- a/cmd/agola/cmd/projectvariabledelete.go +++ b/cmd/agola/cmd/projectvariabledelete.go @@ -17,7 +17,7 @@ package cmd import ( "context" - "agola.io/agola/internal/services/gateway/api" + gwclient "agola.io/agola/services/gateway/client" "github.com/spf13/cobra" errors "golang.org/x/xerrors" @@ -57,7 +57,7 @@ func init() { } func variableDelete(cmd *cobra.Command, ownertype string, args []string) error { - gwclient := api.NewClient(gatewayURL, token) + gwclient := gwclient.NewClient(gatewayURL, token) switch ownertype { case "project": diff --git a/cmd/agola/cmd/projectvariableupdate.go b/cmd/agola/cmd/projectvariableupdate.go index aee4ae8..1b54969 100644 --- a/cmd/agola/cmd/projectvariableupdate.go +++ b/cmd/agola/cmd/projectvariableupdate.go @@ -19,8 +19,8 @@ import ( "io/ioutil" "os" - cstypes "agola.io/agola/internal/services/configstore/types" - "agola.io/agola/internal/services/gateway/api" + gwapitypes "agola.io/agola/services/gateway/api/types" + gwclient "agola.io/agola/services/gateway/client" "github.com/ghodss/yaml" "github.com/spf13/cobra" @@ -68,7 +68,7 @@ func init() { } func variableUpdate(cmd *cobra.Command, ownertype string, args []string) error { - gwclient := api.NewClient(gatewayURL, token) + gwclient := gwclient.NewClient(gatewayURL, token) // "github.com/ghodss/yaml" doesn't provide a streaming decoder var data []byte @@ -89,15 +89,15 @@ func variableUpdate(cmd *cobra.Command, ownertype string, args []string) error { if err := yaml.Unmarshal(data, &values); err != nil { log.Fatalf("failed to unmarshall values: %v", err) } - rvalues := []cstypes.VariableValue{} + rvalues := []gwapitypes.VariableValueRequest{} for _, value := range values { - rvalues = append(rvalues, cstypes.VariableValue{ + rvalues = append(rvalues, gwapitypes.VariableValueRequest{ SecretName: value.SecretName, SecretVar: value.SecretVar, - When: (*cstypes.When)(value.When), + When: value.When, }) } - req := &api.UpdateVariableRequest{ + req := &gwapitypes.UpdateVariableRequest{ Name: variableUpdateOpts.name, Values: rvalues, } diff --git a/cmd/agola/cmd/remotesourcecreate.go b/cmd/agola/cmd/remotesourcecreate.go index 7707b9d..d18e3bb 100644 --- a/cmd/agola/cmd/remotesourcecreate.go +++ b/cmd/agola/cmd/remotesourcecreate.go @@ -18,9 +18,9 @@ import ( "context" "agola.io/agola/internal/gitsources/github" - cstypes "agola.io/agola/internal/services/configstore/types" - "agola.io/agola/internal/services/gateway/api" - "agola.io/agola/internal/util" + gwapitypes "agola.io/agola/services/gateway/api/types" + gwclient "agola.io/agola/services/gateway/client" + "agola.io/agola/util" "github.com/spf13/cobra" errors "golang.org/x/xerrors" @@ -81,10 +81,10 @@ func init() { } func remoteSourceCreate(cmd *cobra.Command, args []string) error { - gwclient := api.NewClient(gatewayURL, token) + gwclient := gwclient.NewClient(gatewayURL, token) // for github remote source type, set defaults for github.com - if remoteSourceCreateOpts.rsType == string(cstypes.RemoteSourceTypeGithub) { + if remoteSourceCreateOpts.rsType == "github" { remoteSourceCreateOpts.apiURL = github.GitHubAPIURL remoteSourceCreateOpts.sshHostKey = github.GitHubSSHHostKey } @@ -93,7 +93,7 @@ func remoteSourceCreate(cmd *cobra.Command, args []string) error { return errors.Errorf(`required flag "api-url" not set`) } - req := &api.CreateRemoteSourceRequest{ + req := &gwapitypes.CreateRemoteSourceRequest{ Name: remoteSourceCreateOpts.name, Type: remoteSourceCreateOpts.rsType, AuthType: remoteSourceCreateOpts.authType, diff --git a/cmd/agola/cmd/remotesourcelist.go b/cmd/agola/cmd/remotesourcelist.go index 6b06dc2..35495ab 100644 --- a/cmd/agola/cmd/remotesourcelist.go +++ b/cmd/agola/cmd/remotesourcelist.go @@ -18,7 +18,9 @@ import ( "context" "fmt" - "agola.io/agola/internal/services/gateway/api" + gwapitypes "agola.io/agola/services/gateway/api/types" + gwclient "agola.io/agola/services/gateway/client" + "github.com/spf13/cobra" ) @@ -48,14 +50,14 @@ func init() { cmdRemoteSource.AddCommand(cmdRemoteSourceList) } -func printRemoteSources(remoteSources []*api.RemoteSourceResponse) { +func printRemoteSources(remoteSources []*gwapitypes.RemoteSourceResponse) { for _, rs := range remoteSources { fmt.Printf("%s: Name: %s\n", rs.ID, rs.Name) } } func remoteSourceList(cmd *cobra.Command, args []string) error { - gwclient := api.NewClient(gatewayURL, token) + gwclient := gwclient.NewClient(gatewayURL, token) remouteSources, _, err := gwclient.GetRemoteSources(context.TODO(), remoteSourceListOpts.start, remoteSourceListOpts.limit, false) if err != nil { diff --git a/cmd/agola/cmd/remotesourceupdate.go b/cmd/agola/cmd/remotesourceupdate.go index b3cdd40..9e72bc8 100644 --- a/cmd/agola/cmd/remotesourceupdate.go +++ b/cmd/agola/cmd/remotesourceupdate.go @@ -17,7 +17,8 @@ package cmd import ( "context" - "agola.io/agola/internal/services/gateway/api" + gwapitypes "agola.io/agola/services/gateway/api/types" + gwclient "agola.io/agola/services/gateway/client" "github.com/spf13/cobra" errors "golang.org/x/xerrors" @@ -71,9 +72,9 @@ func init() { } func remoteSourceUpdate(cmd *cobra.Command, args []string) error { - gwclient := api.NewClient(gatewayURL, token) + gwclient := gwclient.NewClient(gatewayURL, token) - req := &api.UpdateRemoteSourceRequest{} + req := &gwapitypes.UpdateRemoteSourceRequest{} flags := cmd.Flags() if flags.Changed("new-name") { diff --git a/cmd/agola/cmd/runlist.go b/cmd/agola/cmd/runlist.go index c481692..804742e 100644 --- a/cmd/agola/cmd/runlist.go +++ b/cmd/agola/cmd/runlist.go @@ -19,7 +19,8 @@ import ( "fmt" "path" - "agola.io/agola/internal/services/gateway/api" + gwapitypes "agola.io/agola/services/gateway/api/types" + gwclient "agola.io/agola/services/gateway/client" errors "golang.org/x/xerrors" "github.com/spf13/cobra" @@ -59,7 +60,7 @@ func init() { cmdRun.AddCommand(cmdRunList) } -func printRuns(runs []*api.RunResponse) { +func printRuns(runs []*gwapitypes.RunResponse) { for _, run := range runs { fmt.Printf("%s: Phase: %s, Result: %s\n", run.ID, run.Phase, run.Result) for _, task := range run.Tasks { @@ -69,7 +70,7 @@ func printRuns(runs []*api.RunResponse) { } func runList(cmd *cobra.Command, args []string) error { - gwclient := api.NewClient(gatewayURL, token) + gwclient := gwclient.NewClient(gatewayURL, token) project, _, err := gwclient.GetProject(context.TODO(), runListOpts.projectRef) if err != nil { @@ -81,7 +82,7 @@ func runList(cmd *cobra.Command, args []string) error { return err } - runs := make([]*api.RunResponse, len(runsResp)) + runs := make([]*gwapitypes.RunResponse, len(runsResp)) for i, runResponse := range runsResp { run, _, err := gwclient.GetRun(context.TODO(), runResponse.ID) if err != nil { diff --git a/cmd/agola/cmd/usercreate.go b/cmd/agola/cmd/usercreate.go index c523269..5105fe8 100644 --- a/cmd/agola/cmd/usercreate.go +++ b/cmd/agola/cmd/usercreate.go @@ -17,7 +17,8 @@ package cmd import ( "context" - "agola.io/agola/internal/services/gateway/api" + gwapitypes "agola.io/agola/services/gateway/api/types" + gwclient "agola.io/agola/services/gateway/client" "github.com/spf13/cobra" errors "golang.org/x/xerrors" @@ -52,9 +53,9 @@ func init() { } func userCreate(cmd *cobra.Command, args []string) error { - gwclient := api.NewClient(gatewayURL, token) + gwclient := gwclient.NewClient(gatewayURL, token) - req := &api.CreateUserRequest{ + req := &gwapitypes.CreateUserRequest{ UserName: userCreateOpts.username, } diff --git a/cmd/agola/cmd/userdelete.go b/cmd/agola/cmd/userdelete.go index 3c8db0e..3a96d77 100644 --- a/cmd/agola/cmd/userdelete.go +++ b/cmd/agola/cmd/userdelete.go @@ -17,7 +17,7 @@ package cmd import ( "context" - "agola.io/agola/internal/services/gateway/api" + gwclient "agola.io/agola/services/gateway/client" "github.com/spf13/cobra" errors "golang.org/x/xerrors" @@ -52,7 +52,7 @@ func init() { } func userDelete(cmd *cobra.Command, args []string) error { - gwclient := api.NewClient(gatewayURL, token) + gwclient := gwclient.NewClient(gatewayURL, token) log.Infof("deleting user %q", userDeleteOpts.username) if _, err := gwclient.DeleteUser(context.TODO(), userDeleteOpts.username); err != nil { diff --git a/cmd/agola/cmd/userlacreate.go b/cmd/agola/cmd/userlacreate.go index ad4aff4..6c67219 100644 --- a/cmd/agola/cmd/userlacreate.go +++ b/cmd/agola/cmd/userlacreate.go @@ -17,7 +17,8 @@ package cmd import ( "context" - "agola.io/agola/internal/services/gateway/api" + gwapitypes "agola.io/agola/services/gateway/api/types" + gwclient "agola.io/agola/services/gateway/client" "github.com/spf13/cobra" errors "golang.org/x/xerrors" @@ -61,9 +62,9 @@ func init() { } func userLACreate(cmd *cobra.Command, args []string) error { - gwclient := api.NewClient(gatewayURL, token) + gwclient := gwclient.NewClient(gatewayURL, token) - req := &api.CreateUserLARequest{ + req := &gwapitypes.CreateUserLARequest{ RemoteSourceName: userLACreateOpts.remoteSourceName, RemoteSourceLoginName: userLACreateOpts.remoteSourceLoginName, RemoteSourceLoginPassword: userLACreateOpts.remoteSourceLoginPassword, diff --git a/cmd/agola/cmd/userladelete.go b/cmd/agola/cmd/userladelete.go index ccde33c..8c3378c 100644 --- a/cmd/agola/cmd/userladelete.go +++ b/cmd/agola/cmd/userladelete.go @@ -17,7 +17,7 @@ package cmd import ( "context" - "agola.io/agola/internal/services/gateway/api" + gwclient "agola.io/agola/services/gateway/client" "github.com/spf13/cobra" errors "golang.org/x/xerrors" @@ -57,7 +57,7 @@ func init() { } func userLADelete(cmd *cobra.Command, args []string) error { - gwclient := api.NewClient(gatewayURL, token) + gwclient := gwclient.NewClient(gatewayURL, token) userName := userLADeleteOpts.userName laID := userLADeleteOpts.laID diff --git a/cmd/agola/cmd/userlist.go b/cmd/agola/cmd/userlist.go index 1e6afd8..e458bc4 100644 --- a/cmd/agola/cmd/userlist.go +++ b/cmd/agola/cmd/userlist.go @@ -18,7 +18,9 @@ import ( "context" "fmt" - "agola.io/agola/internal/services/gateway/api" + gwapitypes "agola.io/agola/services/gateway/api/types" + gwclient "agola.io/agola/services/gateway/client" + "github.com/spf13/cobra" ) @@ -48,14 +50,14 @@ func init() { cmdUser.AddCommand(cmdUserList) } -func printUsers(users []*api.UserResponse) { +func printUsers(users []*gwapitypes.UserResponse) { for _, user := range users { fmt.Printf("%s: Name: %s\n", user.ID, user.UserName) } } func userList(cmd *cobra.Command, args []string) error { - gwclient := api.NewClient(gatewayURL, token) + gwclient := gwclient.NewClient(gatewayURL, token) users, _, err := gwclient.GetUsers(context.TODO(), userListOpts.start, userListOpts.limit, false) if err != nil { diff --git a/cmd/agola/cmd/usertokencreate.go b/cmd/agola/cmd/usertokencreate.go index ecd8bd5..7e75fbd 100644 --- a/cmd/agola/cmd/usertokencreate.go +++ b/cmd/agola/cmd/usertokencreate.go @@ -18,7 +18,8 @@ import ( "context" "fmt" - "agola.io/agola/internal/services/gateway/api" + gwapitypes "agola.io/agola/services/gateway/api/types" + gwclient "agola.io/agola/services/gateway/client" "github.com/spf13/cobra" errors "golang.org/x/xerrors" @@ -58,9 +59,9 @@ func init() { } func userTokenCreate(cmd *cobra.Command, args []string) error { - gwclient := api.NewClient(gatewayURL, token) + gwclient := gwclient.NewClient(gatewayURL, token) - req := &api.CreateUserTokenRequest{ + req := &gwapitypes.CreateUserTokenRequest{ TokenName: userTokenCreateOpts.tokenName, } diff --git a/cmd/agola/cmd/usertokendelete.go b/cmd/agola/cmd/usertokendelete.go index bfede1c..034a437 100644 --- a/cmd/agola/cmd/usertokendelete.go +++ b/cmd/agola/cmd/usertokendelete.go @@ -17,7 +17,7 @@ package cmd import ( "context" - "agola.io/agola/internal/services/gateway/api" + gwclient "agola.io/agola/services/gateway/client" "github.com/spf13/cobra" errors "golang.org/x/xerrors" @@ -57,7 +57,7 @@ func init() { } func userTokenDelete(cmd *cobra.Command, args []string) error { - gwclient := api.NewClient(gatewayURL, token) + gwclient := gwclient.NewClient(gatewayURL, token) userName := userTokenDeleteOpts.userName tokenName := userTokenDeleteOpts.tokenName diff --git a/internal/config/config.go b/internal/config/config.go index 822dca8..747373f 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -20,9 +20,9 @@ import ( "regexp" "strings" - "agola.io/agola/internal/common" - cstypes "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/util" + cstypes "agola.io/agola/services/configstore/types" + "agola.io/agola/services/types" "github.com/ghodss/yaml" "github.com/google/go-jsonnet" @@ -83,7 +83,7 @@ type DockerRegistryAuth struct { type Runtime struct { Type RuntimeType `json:"type,omitempty"` - Arch common.Arch `json:"arch,omitempty"` + Arch types.Arch `json:"arch,omitempty"` Containers []*Container `json:"containers,omitempty"` } @@ -702,7 +702,7 @@ func checkConfig(config *Config) error { return errors.Errorf("task %q runtime: at least one container must be defined", task.Name) } if r.Arch != "" { - if !common.IsValidArch(r.Arch) { + if !types.IsValidArch(r.Arch) { return errors.Errorf("task %q runtime: invalid arch %q", task.Name, r.Arch) } } diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 6141e74..f15d3d8 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -18,8 +18,8 @@ import ( "fmt" "testing" - "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/util" + "agola.io/agola/services/configstore/types" "github.com/google/go-cmp/cmp" errors "golang.org/x/xerrors" diff --git a/internal/gitsources/agolagit/agolagit.go b/internal/gitsources/agolagit/agolagit.go index 111d179..b0dbad4 100644 --- a/internal/gitsources/agolagit/agolagit.go +++ b/internal/gitsources/agolagit/agolagit.go @@ -35,7 +35,6 @@ var ( tagRefPrefix = "refs/tags/" ) -// Client represents a Gogs API client. type Client struct { url string client *http.Client diff --git a/internal/runconfig/runconfig.go b/internal/runconfig/runconfig.go index 49a6d0b..c3b55a4 100644 --- a/internal/runconfig/runconfig.go +++ b/internal/runconfig/runconfig.go @@ -19,9 +19,9 @@ import ( "strings" "agola.io/agola/internal/config" - cstypes "agola.io/agola/internal/services/configstore/types" - rstypes "agola.io/agola/internal/services/runservice/types" "agola.io/agola/internal/util" + cstypes "agola.io/agola/services/configstore/types" + rstypes "agola.io/agola/services/runservice/types" errors "golang.org/x/xerrors" ) diff --git a/internal/runconfig/runconfig_test.go b/internal/runconfig/runconfig_test.go index 30839a0..c2a6040 100644 --- a/internal/runconfig/runconfig_test.go +++ b/internal/runconfig/runconfig_test.go @@ -20,9 +20,9 @@ import ( "testing" "agola.io/agola/internal/config" - cstypes "agola.io/agola/internal/services/configstore/types" - rstypes "agola.io/agola/internal/services/runservice/types" "agola.io/agola/internal/util" + cstypes "agola.io/agola/services/configstore/types" + rstypes "agola.io/agola/services/runservice/types" "github.com/google/go-cmp/cmp" errors "golang.org/x/xerrors" diff --git a/internal/services/common/gitsource.go b/internal/services/common/gitsource.go index 7a7aa98..298c6d5 100644 --- a/internal/services/common/gitsource.go +++ b/internal/services/common/gitsource.go @@ -19,7 +19,7 @@ import ( "agola.io/agola/internal/gitsources/gitea" "agola.io/agola/internal/gitsources/github" "agola.io/agola/internal/gitsources/gitlab" - cstypes "agola.io/agola/internal/services/configstore/types" + cstypes "agola.io/agola/services/configstore/types" errors "golang.org/x/xerrors" ) diff --git a/internal/services/common/variables.go b/internal/services/common/variables.go index 5f6b45d..feb49d0 100644 --- a/internal/services/common/variables.go +++ b/internal/services/common/variables.go @@ -15,20 +15,20 @@ package common import ( - csapi "agola.io/agola/internal/services/configstore/api" - cstypes "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/util" + csapitypes "agola.io/agola/services/configstore/api/types" + cstypes "agola.io/agola/services/configstore/types" ) -func FilterOverriddenVariables(variables []*csapi.Variable) []*csapi.Variable { - variablesMap := map[string]*csapi.Variable{} +func FilterOverriddenVariables(variables []*csapitypes.Variable) []*csapitypes.Variable { + variablesMap := map[string]*csapitypes.Variable{} for _, v := range variables { if _, ok := variablesMap[v.Name]; !ok { variablesMap[v.Name] = v } } - filteredVariables := make([]*csapi.Variable, len(variablesMap)) + filteredVariables := make([]*csapitypes.Variable, len(variablesMap)) i := 0 // keep the original order for _, v := range variables { @@ -43,9 +43,9 @@ func FilterOverriddenVariables(variables []*csapi.Variable) []*csapi.Variable { return filteredVariables } -func GetVarValueMatchingSecret(varval cstypes.VariableValue, varParentPath string, secrets []*csapi.Secret) *csapi.Secret { +func GetVarValueMatchingSecret(varval cstypes.VariableValue, varParentPath string, secrets []*csapitypes.Secret) *csapitypes.Secret { // get the secret value referenced by the variable, it must be a secret at the same level or a lower level - var secret *csapi.Secret + var secret *csapitypes.Secret for _, s := range secrets { // we assume the root path will be the same if s.Name != varval.SecretName { diff --git a/internal/services/common/variables_test.go b/internal/services/common/variables_test.go index 24c76fc..c47d672 100644 --- a/internal/services/common/variables_test.go +++ b/internal/services/common/variables_test.go @@ -17,84 +17,85 @@ package common import ( "testing" - csapi "agola.io/agola/internal/services/configstore/api" - cstypes "agola.io/agola/internal/services/configstore/types" + csapitypes "agola.io/agola/services/configstore/api/types" + cstypes "agola.io/agola/services/configstore/types" + "github.com/google/go-cmp/cmp" ) func TestFilterOverriddenVariables(t *testing.T) { tests := []struct { name string - variables []*csapi.Variable - out []*csapi.Variable + variables []*csapitypes.Variable + out []*csapitypes.Variable }{ { name: "test empty variables", - variables: []*csapi.Variable{}, - out: []*csapi.Variable{}, + variables: []*csapitypes.Variable{}, + out: []*csapitypes.Variable{}, }, { name: "test variable overrides", - variables: []*csapi.Variable{ + variables: []*csapitypes.Variable{ // variables must be in depth (from leaves to root) order as returned by the // configstore apis - &csapi.Variable{ + &csapitypes.Variable{ Variable: &cstypes.Variable{ Name: "var04", }, ParentPath: "org/org01/projectgroup02/projectgroup03/project02", }, - &csapi.Variable{ + &csapitypes.Variable{ Variable: &cstypes.Variable{ Name: "var03", }, ParentPath: "org/org01/projectgroup01/project01", }, - &csapi.Variable{ + &csapitypes.Variable{ Variable: &cstypes.Variable{ Name: "var02", }, ParentPath: "org/org01/projectgroup01/project01", }, - &csapi.Variable{ + &csapitypes.Variable{ Variable: &cstypes.Variable{ Name: "var02", }, ParentPath: "org/org01/projectgroup01", }, - &csapi.Variable{ + &csapitypes.Variable{ Variable: &cstypes.Variable{ Name: "var01", }, ParentPath: "org/org01/projectgroup01", }, - &csapi.Variable{ + &csapitypes.Variable{ Variable: &cstypes.Variable{ Name: "var01", }, ParentPath: "org/org01", }, }, - out: []*csapi.Variable{ - &csapi.Variable{ + out: []*csapitypes.Variable{ + &csapitypes.Variable{ Variable: &cstypes.Variable{ Name: "var04", }, ParentPath: "org/org01/projectgroup02/projectgroup03/project02", }, - &csapi.Variable{ + &csapitypes.Variable{ Variable: &cstypes.Variable{ Name: "var03", }, ParentPath: "org/org01/projectgroup01/project01", }, - &csapi.Variable{ + &csapitypes.Variable{ Variable: &cstypes.Variable{ Name: "var02", }, ParentPath: "org/org01/projectgroup01/project01", }, - &csapi.Variable{ + &csapitypes.Variable{ Variable: &cstypes.Variable{ Name: "var01", }, @@ -120,8 +121,8 @@ func TestGetVarValueMatchingSecret(t *testing.T) { name string varValue cstypes.VariableValue varParentPath string - secrets []*csapi.Secret - out *csapi.Secret + secrets []*csapitypes.Secret + out *csapitypes.Secret }{ { name: "test empty secrets", @@ -130,7 +131,7 @@ func TestGetVarValueMatchingSecret(t *testing.T) { SecretVar: "secretvar01", }, varParentPath: "org/org01/projectgroup01/project01", - secrets: []*csapi.Secret{}, + secrets: []*csapitypes.Secret{}, out: nil, }, { @@ -140,8 +141,8 @@ func TestGetVarValueMatchingSecret(t *testing.T) { SecretVar: "secretvar01", }, varParentPath: "org/org01/projectgroup01/projectgroup02", - secrets: []*csapi.Secret{ - &csapi.Secret{ + secrets: []*csapitypes.Secret{ + &csapitypes.Secret{ Secret: &cstypes.Secret{ Name: "secret02", }, @@ -157,8 +158,8 @@ func TestGetVarValueMatchingSecret(t *testing.T) { SecretVar: "secretvar01", }, varParentPath: "org/org01/projectgroup01/projectgroup02", - secrets: []*csapi.Secret{ - &csapi.Secret{ + secrets: []*csapitypes.Secret{ + &csapitypes.Secret{ Secret: &cstypes.Secret{ Name: "secret02", }, @@ -174,8 +175,8 @@ func TestGetVarValueMatchingSecret(t *testing.T) { SecretVar: "secretvar01", }, varParentPath: "org/org01/projectgroup01/projectgroup02", - secrets: []*csapi.Secret{ - &csapi.Secret{ + secrets: []*csapitypes.Secret{ + &csapitypes.Secret{ Secret: &cstypes.Secret{ Name: "secret01", }, @@ -191,21 +192,21 @@ func TestGetVarValueMatchingSecret(t *testing.T) { SecretVar: "secretvar01", }, varParentPath: "org/org01/projectgroup01/projectgroup02", - secrets: []*csapi.Secret{ - &csapi.Secret{ + secrets: []*csapitypes.Secret{ + &csapitypes.Secret{ Secret: &cstypes.Secret{ Name: "secret01", }, ParentPath: "org/org01/projectgroup01/projectgroup02/project01", }, - &csapi.Secret{ + &csapitypes.Secret{ Secret: &cstypes.Secret{ Name: "secret01", }, ParentPath: "org/org01/projectgroup01/projectgroup02", }, }, - out: &csapi.Secret{ + out: &csapitypes.Secret{ Secret: &cstypes.Secret{ Name: "secret01", }, @@ -219,15 +220,15 @@ func TestGetVarValueMatchingSecret(t *testing.T) { SecretVar: "secretvar01", }, varParentPath: "org/org01/projectgroup01/projectgroup02", - secrets: []*csapi.Secret{ - &csapi.Secret{ + secrets: []*csapitypes.Secret{ + &csapitypes.Secret{ Secret: &cstypes.Secret{ Name: "secret01", }, ParentPath: "org/org01/projectgroup01", }, }, - out: &csapi.Secret{ + out: &csapitypes.Secret{ Secret: &cstypes.Secret{ Name: "secret01", }, @@ -241,29 +242,29 @@ func TestGetVarValueMatchingSecret(t *testing.T) { SecretVar: "secretvar01", }, varParentPath: "org/org01/projectgroup01/projectgroup02", - secrets: []*csapi.Secret{ + secrets: []*csapitypes.Secret{ // secrets must be in depth (from leaves to root) order as returned by the // configstore apis - &csapi.Secret{ + &csapitypes.Secret{ Secret: &cstypes.Secret{ Name: "secret01", }, ParentPath: "org/org01/projectgroup01/projectgroup02/project01", }, - &csapi.Secret{ + &csapitypes.Secret{ Secret: &cstypes.Secret{ Name: "secret01", }, ParentPath: "org/org01/projectgroup01/projectgroup02", }, - &csapi.Secret{ + &csapitypes.Secret{ Secret: &cstypes.Secret{ Name: "secret01", }, ParentPath: "org/org01/projectgroup01", }, }, - out: &csapi.Secret{ + out: &csapitypes.Secret{ Secret: &cstypes.Secret{ Name: "secret01", }, diff --git a/internal/services/configstore/action/org.go b/internal/services/configstore/action/org.go index 2698151..761fe1e 100644 --- a/internal/services/configstore/action/org.go +++ b/internal/services/configstore/action/org.go @@ -23,8 +23,8 @@ import ( "agola.io/agola/internal/datamanager" "agola.io/agola/internal/db" "agola.io/agola/internal/services/configstore/readdb" - "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/util" + "agola.io/agola/services/configstore/types" uuid "github.com/satori/go.uuid" errors "golang.org/x/xerrors" diff --git a/internal/services/configstore/action/project.go b/internal/services/configstore/action/project.go index 07dc7af..116ee06 100644 --- a/internal/services/configstore/action/project.go +++ b/internal/services/configstore/action/project.go @@ -21,8 +21,8 @@ import ( "agola.io/agola/internal/datamanager" "agola.io/agola/internal/db" - "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/util" + "agola.io/agola/services/configstore/types" uuid "github.com/satori/go.uuid" errors "golang.org/x/xerrors" diff --git a/internal/services/configstore/action/projectgroup.go b/internal/services/configstore/action/projectgroup.go index c56bda1..20137cd 100644 --- a/internal/services/configstore/action/projectgroup.go +++ b/internal/services/configstore/action/projectgroup.go @@ -21,8 +21,8 @@ import ( "agola.io/agola/internal/datamanager" "agola.io/agola/internal/db" - "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/util" + "agola.io/agola/services/configstore/types" uuid "github.com/satori/go.uuid" errors "golang.org/x/xerrors" diff --git a/internal/services/configstore/action/remotesource.go b/internal/services/configstore/action/remotesource.go index 49cecfe..e0d925f 100644 --- a/internal/services/configstore/action/remotesource.go +++ b/internal/services/configstore/action/remotesource.go @@ -20,8 +20,8 @@ import ( "agola.io/agola/internal/datamanager" "agola.io/agola/internal/db" - "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/util" + "agola.io/agola/services/configstore/types" uuid "github.com/satori/go.uuid" errors "golang.org/x/xerrors" diff --git a/internal/services/configstore/action/secret.go b/internal/services/configstore/action/secret.go index fc05c2f..a64576c 100644 --- a/internal/services/configstore/action/secret.go +++ b/internal/services/configstore/action/secret.go @@ -20,8 +20,8 @@ import ( "agola.io/agola/internal/datamanager" "agola.io/agola/internal/db" - "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/util" + "agola.io/agola/services/configstore/types" uuid "github.com/satori/go.uuid" errors "golang.org/x/xerrors" diff --git a/internal/services/configstore/action/user.go b/internal/services/configstore/action/user.go index df9cf23..4a228b7 100644 --- a/internal/services/configstore/action/user.go +++ b/internal/services/configstore/action/user.go @@ -22,8 +22,8 @@ import ( "agola.io/agola/internal/datamanager" "agola.io/agola/internal/db" "agola.io/agola/internal/services/configstore/readdb" - "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/util" + "agola.io/agola/services/configstore/types" uuid "github.com/satori/go.uuid" errors "golang.org/x/xerrors" diff --git a/internal/services/configstore/action/variable.go b/internal/services/configstore/action/variable.go index 078e814..9ec2fc3 100644 --- a/internal/services/configstore/action/variable.go +++ b/internal/services/configstore/action/variable.go @@ -20,8 +20,8 @@ import ( "agola.io/agola/internal/datamanager" "agola.io/agola/internal/db" - "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/util" + "agola.io/agola/services/configstore/types" uuid "github.com/satori/go.uuid" errors "golang.org/x/xerrors" diff --git a/internal/services/configstore/api/api.go b/internal/services/configstore/api/api.go index a48b3d8..a552922 100644 --- a/internal/services/configstore/api/api.go +++ b/internal/services/configstore/api/api.go @@ -19,8 +19,9 @@ import ( "net/http" "net/url" - "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/util" + "agola.io/agola/services/configstore/types" + "github.com/gorilla/mux" errors "golang.org/x/xerrors" ) diff --git a/internal/services/configstore/api/org.go b/internal/services/configstore/api/org.go index eb8c169..5ad4df3 100644 --- a/internal/services/configstore/api/org.go +++ b/internal/services/configstore/api/org.go @@ -22,12 +22,13 @@ import ( "agola.io/agola/internal/db" "agola.io/agola/internal/services/configstore/action" "agola.io/agola/internal/services/configstore/readdb" - "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/util" - errors "golang.org/x/xerrors" + csapitypes "agola.io/agola/services/configstore/api/types" + "agola.io/agola/services/configstore/types" "github.com/gorilla/mux" "go.uber.org/zap" + errors "golang.org/x/xerrors" ) type OrgHandler struct { @@ -180,10 +181,6 @@ func (h *OrgsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } } -type AddOrgMemberRequest struct { - Role types.MemberRole -} - type AddOrgMemberHandler struct { log *zap.SugaredLogger ah *action.ActionHandler @@ -200,7 +197,7 @@ func (h *AddOrgMemberHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) orgRef := vars["orgref"] userRef := vars["userref"] - var req AddOrgMemberRequest + var req csapitypes.AddOrgMemberRequest d := json.NewDecoder(r.Body) if err := d.Decode(&req); err != nil { httpError(w, util.NewErrBadRequest(err)) @@ -245,13 +242,8 @@ func (h *RemoveOrgMemberHandler) ServeHTTP(w http.ResponseWriter, r *http.Reques } } -type OrgMemberResponse struct { - User *types.User - Role types.MemberRole -} - -func orgMemberResponse(orgUser *action.OrgMemberResponse) *OrgMemberResponse { - return &OrgMemberResponse{ +func orgMemberResponse(orgUser *action.OrgMemberResponse) *csapitypes.OrgMemberResponse { + return &csapitypes.OrgMemberResponse{ User: orgUser.User, Role: orgUser.Role, } @@ -277,7 +269,7 @@ func (h *OrgMembersHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } - res := make([]*OrgMemberResponse, len(orgUsers)) + res := make([]*csapitypes.OrgMemberResponse, len(orgUsers)) for i, orgUser := range orgUsers { res[i] = orgMemberResponse(orgUser) } diff --git a/internal/services/configstore/api/project.go b/internal/services/configstore/api/project.go index 3f9a58f..f8386a3 100644 --- a/internal/services/configstore/api/project.go +++ b/internal/services/configstore/api/project.go @@ -24,27 +24,16 @@ import ( "agola.io/agola/internal/db" "agola.io/agola/internal/services/configstore/action" "agola.io/agola/internal/services/configstore/readdb" - "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/util" - errors "golang.org/x/xerrors" + csapitypes "agola.io/agola/services/configstore/api/types" + "agola.io/agola/services/configstore/types" "github.com/gorilla/mux" "go.uber.org/zap" + errors "golang.org/x/xerrors" ) -// Project augments types.Project with dynamic data -type Project struct { - *types.Project - - // dynamic data - OwnerType types.ConfigType - OwnerID string - Path string - ParentPath string - GlobalVisibility types.Visibility -} - -func projectResponse(ctx context.Context, readDB *readdb.ReadDB, project *types.Project) (*Project, error) { +func projectResponse(ctx context.Context, readDB *readdb.ReadDB, project *types.Project) (*csapitypes.Project, error) { r, err := projectsResponse(ctx, readDB, []*types.Project{project}) if err != nil { return nil, err @@ -52,8 +41,8 @@ func projectResponse(ctx context.Context, readDB *readdb.ReadDB, project *types. return r[0], nil } -func projectsResponse(ctx context.Context, readDB *readdb.ReadDB, projects []*types.Project) ([]*Project, error) { - resProjects := make([]*Project, len(projects)) +func projectsResponse(ctx context.Context, readDB *readdb.ReadDB, projects []*types.Project) ([]*csapitypes.Project, error) { + resProjects := make([]*csapitypes.Project, len(projects)) err := readDB.Do(ctx, func(tx *db.Tx) error { for i, project := range projects { @@ -75,7 +64,7 @@ func projectsResponse(ctx context.Context, readDB *readdb.ReadDB, projects []*ty // we calculate the path here from parent path since the db could not yet be // updated on create - resProjects[i] = &Project{ + resProjects[i] = &csapitypes.Project{ Project: project, OwnerType: ownerType, OwnerID: ownerID, diff --git a/internal/services/configstore/api/projectgroup.go b/internal/services/configstore/api/projectgroup.go index c481955..82a0652 100644 --- a/internal/services/configstore/api/projectgroup.go +++ b/internal/services/configstore/api/projectgroup.go @@ -24,27 +24,16 @@ import ( "agola.io/agola/internal/db" "agola.io/agola/internal/services/configstore/action" "agola.io/agola/internal/services/configstore/readdb" - "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/util" - errors "golang.org/x/xerrors" + csapitypes "agola.io/agola/services/configstore/api/types" + "agola.io/agola/services/configstore/types" "github.com/gorilla/mux" "go.uber.org/zap" + errors "golang.org/x/xerrors" ) -// ProjectGroup augments types.ProjectGroup with dynamic data -type ProjectGroup struct { - *types.ProjectGroup - - // dynamic data - OwnerType types.ConfigType - OwnerID string - Path string - ParentPath string - GlobalVisibility types.Visibility -} - -func projectGroupResponse(ctx context.Context, readDB *readdb.ReadDB, projectGroup *types.ProjectGroup) (*ProjectGroup, error) { +func projectGroupResponse(ctx context.Context, readDB *readdb.ReadDB, projectGroup *types.ProjectGroup) (*csapitypes.ProjectGroup, error) { r, err := projectGroupsResponse(ctx, readDB, []*types.ProjectGroup{projectGroup}) if err != nil { return nil, err @@ -52,8 +41,8 @@ func projectGroupResponse(ctx context.Context, readDB *readdb.ReadDB, projectGro return r[0], nil } -func projectGroupsResponse(ctx context.Context, readDB *readdb.ReadDB, projectGroups []*types.ProjectGroup) ([]*ProjectGroup, error) { - resProjectGroups := make([]*ProjectGroup, len(projectGroups)) +func projectGroupsResponse(ctx context.Context, readDB *readdb.ReadDB, projectGroups []*types.ProjectGroup) ([]*csapitypes.ProjectGroup, error) { + resProjectGroups := make([]*csapitypes.ProjectGroup, len(projectGroups)) err := readDB.Do(ctx, func(tx *db.Tx) error { for i, projectGroup := range projectGroups { @@ -75,7 +64,7 @@ func projectGroupsResponse(ctx context.Context, readDB *readdb.ReadDB, projectGr // we calculate the path here from parent path since the db could not yet be // updated on create - resProjectGroups[i] = &ProjectGroup{ + resProjectGroups[i] = &csapitypes.ProjectGroup{ ProjectGroup: projectGroup, OwnerType: ownerType, OwnerID: ownerID, diff --git a/internal/services/configstore/api/remotesource.go b/internal/services/configstore/api/remotesource.go index 4f5faa7..baa5012 100644 --- a/internal/services/configstore/api/remotesource.go +++ b/internal/services/configstore/api/remotesource.go @@ -22,12 +22,12 @@ import ( "agola.io/agola/internal/db" "agola.io/agola/internal/services/configstore/action" "agola.io/agola/internal/services/configstore/readdb" - "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/util" - errors "golang.org/x/xerrors" + "agola.io/agola/services/configstore/types" "github.com/gorilla/mux" "go.uber.org/zap" + errors "golang.org/x/xerrors" ) type RemoteSourceHandler struct { diff --git a/internal/services/configstore/api/secret.go b/internal/services/configstore/api/secret.go index 86f783c..d974eb9 100644 --- a/internal/services/configstore/api/secret.go +++ b/internal/services/configstore/api/secret.go @@ -21,21 +21,14 @@ import ( "agola.io/agola/internal/db" "agola.io/agola/internal/services/configstore/action" "agola.io/agola/internal/services/configstore/readdb" - "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/util" + csapitypes "agola.io/agola/services/configstore/api/types" + "agola.io/agola/services/configstore/types" "github.com/gorilla/mux" "go.uber.org/zap" ) -// Secret augments types.Secret with dynamic data -type Secret struct { - *types.Secret - - // dynamic data - ParentPath string -} - type SecretHandler struct { log *zap.SugaredLogger ah *action.ActionHandler @@ -89,9 +82,9 @@ func (h *SecretsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } - resSecrets := make([]*Secret, len(secrets)) + resSecrets := make([]*csapitypes.Secret, len(secrets)) for i, s := range secrets { - resSecrets[i] = &Secret{Secret: s} + resSecrets[i] = &csapitypes.Secret{Secret: s} } err = h.readDB.Do(ctx, func(tx *db.Tx) error { diff --git a/internal/services/configstore/api/user.go b/internal/services/configstore/api/user.go index de117d7..0c639d5 100644 --- a/internal/services/configstore/api/user.go +++ b/internal/services/configstore/api/user.go @@ -18,17 +18,17 @@ import ( "encoding/json" "net/http" "strconv" - "time" "agola.io/agola/internal/db" action "agola.io/agola/internal/services/configstore/action" "agola.io/agola/internal/services/configstore/readdb" - "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/util" - errors "golang.org/x/xerrors" + csapitypes "agola.io/agola/services/configstore/api/types" + "agola.io/agola/services/configstore/types" "github.com/gorilla/mux" "go.uber.org/zap" + errors "golang.org/x/xerrors" ) type UserHandler struct { @@ -67,12 +67,6 @@ func (h *UserHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } } -type CreateUserRequest struct { - UserName string `json:"user_name"` - - CreateUserLARequest *CreateUserLARequest `json:"create_user_la_request"` -} - type CreateUserHandler struct { log *zap.SugaredLogger ah *action.ActionHandler @@ -85,7 +79,7 @@ func NewCreateUserHandler(logger *zap.Logger, ah *action.ActionHandler) *CreateU func (h *CreateUserHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { ctx := r.Context() - var req *CreateUserRequest + var req *csapitypes.CreateUserRequest d := json.NewDecoder(r.Body) if err := d.Decode(&req); err != nil { httpError(w, util.NewErrBadRequest(err)) @@ -118,10 +112,6 @@ func (h *CreateUserHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } } -type UpdateUserRequest struct { - UserName string `json:"user_name"` -} - type UpdateUserHandler struct { log *zap.SugaredLogger ah *action.ActionHandler @@ -137,7 +127,7 @@ func (h *UpdateUserHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) userRef := vars["userref"] - var req *UpdateUserRequest + var req *csapitypes.UpdateUserRequest d := json.NewDecoder(r.Body) if err := d.Decode(&req); err != nil { httpError(w, util.NewErrBadRequest(err)) @@ -305,16 +295,6 @@ func (h *UsersHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } } -type CreateUserLARequest struct { - RemoteSourceName string `json:"remote_source_name"` - RemoteUserID string `json:"remote_user_id"` - RemoteUserName string `json:"remote_user_name"` - UserAccessToken string `json:"user_access_token"` - Oauth2AccessToken string `json:"oauth2_access_token"` - Oauth2RefreshToken string `json:"oauth2_refresh_token"` - Oauth2AccessTokenExpiresAt time.Time `json:"oauth_2_access_token_expires_at"` -} - type CreateUserLAHandler struct { log *zap.SugaredLogger ah *action.ActionHandler @@ -329,7 +309,7 @@ func (h *CreateUserLAHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) vars := mux.Vars(r) userRef := vars["userref"] - var req CreateUserLARequest + var req csapitypes.CreateUserLARequest d := json.NewDecoder(r.Body) if err := d.Decode(&req); err != nil { httpError(w, util.NewErrBadRequest(err)) @@ -381,15 +361,6 @@ func (h *DeleteUserLAHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) } } -type UpdateUserLARequest struct { - RemoteUserID string `json:"remote_user_id"` - RemoteUserName string `json:"remote_user_name"` - UserAccessToken string `json:"user_access_token"` - Oauth2AccessToken string `json:"oauth2_access_token"` - Oauth2RefreshToken string `json:"oauth2_refresh_token"` - Oauth2AccessTokenExpiresAt time.Time `json:"oauth_2_access_token_expires_at"` -} - type UpdateUserLAHandler struct { log *zap.SugaredLogger ah *action.ActionHandler @@ -405,7 +376,7 @@ func (h *UpdateUserLAHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) userRef := vars["userref"] linkedAccountID := vars["laid"] - var req UpdateUserLARequest + var req csapitypes.UpdateUserLARequest d := json.NewDecoder(r.Body) if err := d.Decode(&req); err != nil { httpError(w, util.NewErrBadRequest(err)) @@ -433,14 +404,6 @@ func (h *UpdateUserLAHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) } } -type CreateUserTokenRequest struct { - TokenName string `json:"token_name"` -} - -type CreateUserTokenResponse struct { - Token string `json:"token"` -} - type CreateUserTokenHandler struct { log *zap.SugaredLogger ah *action.ActionHandler @@ -455,7 +418,7 @@ func (h *CreateUserTokenHandler) ServeHTTP(w http.ResponseWriter, r *http.Reques vars := mux.Vars(r) userRef := vars["userref"] - var req CreateUserTokenRequest + var req csapitypes.CreateUserTokenRequest d := json.NewDecoder(r.Body) if err := d.Decode(&req); err != nil { httpError(w, util.NewErrBadRequest(err)) @@ -468,7 +431,7 @@ func (h *CreateUserTokenHandler) ServeHTTP(w http.ResponseWriter, r *http.Reques return } - resp := &CreateUserTokenResponse{ + resp := &csapitypes.CreateUserTokenResponse{ Token: token, } if err := httpResponse(w, http.StatusCreated, resp); err != nil { @@ -501,13 +464,8 @@ func (h *DeleteUserTokenHandler) ServeHTTP(w http.ResponseWriter, r *http.Reques } } -type UserOrgsResponse struct { - Organization *types.Organization - Role types.MemberRole -} - -func userOrgsResponse(userOrg *action.UserOrgsResponse) *UserOrgsResponse { - return &UserOrgsResponse{ +func userOrgsResponse(userOrg *action.UserOrgsResponse) *csapitypes.UserOrgsResponse { + return &csapitypes.UserOrgsResponse{ Organization: userOrg.Organization, Role: userOrg.Role, } @@ -533,7 +491,7 @@ func (h *UserOrgsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } - res := make([]*UserOrgsResponse, len(userOrgs)) + res := make([]*csapitypes.UserOrgsResponse, len(userOrgs)) for i, userOrg := range userOrgs { res[i] = userOrgsResponse(userOrg) } diff --git a/internal/services/configstore/api/variable.go b/internal/services/configstore/api/variable.go index 30fb46f..88e8b98 100644 --- a/internal/services/configstore/api/variable.go +++ b/internal/services/configstore/api/variable.go @@ -21,21 +21,14 @@ import ( "agola.io/agola/internal/db" "agola.io/agola/internal/services/configstore/action" "agola.io/agola/internal/services/configstore/readdb" - "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/util" + csapitypes "agola.io/agola/services/configstore/api/types" + "agola.io/agola/services/configstore/types" "github.com/gorilla/mux" "go.uber.org/zap" ) -// Variable augments types.Variable with dynamic data -type Variable struct { - *types.Variable - - // dynamic data - ParentPath string -} - type VariablesHandler struct { log *zap.SugaredLogger ah *action.ActionHandler @@ -63,9 +56,9 @@ func (h *VariablesHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } - resVariables := make([]*Variable, len(variables)) + resVariables := make([]*csapitypes.Variable, len(variables)) for i, v := range variables { - resVariables[i] = &Variable{Variable: v} + resVariables[i] = &csapitypes.Variable{Variable: v} } err = h.readDB.Do(ctx, func(tx *db.Tx) error { // populate parent path diff --git a/internal/services/configstore/configstore.go b/internal/services/configstore/configstore.go index 89cf0ce..1033ef8 100644 --- a/internal/services/configstore/configstore.go +++ b/internal/services/configstore/configstore.go @@ -32,8 +32,8 @@ import ( "agola.io/agola/internal/services/configstore/api" "agola.io/agola/internal/services/configstore/common" "agola.io/agola/internal/services/configstore/readdb" - "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/util" + "agola.io/agola/services/configstore/types" "github.com/gorilla/mux" etcdclientv3 "go.etcd.io/etcd/clientv3" diff --git a/internal/services/configstore/configstore_test.go b/internal/services/configstore/configstore_test.go index 70b7698..c597cd1 100644 --- a/internal/services/configstore/configstore_test.go +++ b/internal/services/configstore/configstore_test.go @@ -30,9 +30,9 @@ import ( "agola.io/agola/internal/db" "agola.io/agola/internal/services/config" action "agola.io/agola/internal/services/configstore/action" - "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/testutil" "agola.io/agola/internal/util" + "agola.io/agola/services/configstore/types" "github.com/google/go-cmp/cmp" ) diff --git a/internal/services/configstore/readdb/org.go b/internal/services/configstore/readdb/org.go index b2715dc..7fd3f1a 100644 --- a/internal/services/configstore/readdb/org.go +++ b/internal/services/configstore/readdb/org.go @@ -20,8 +20,8 @@ import ( "agola.io/agola/internal/db" "agola.io/agola/internal/services/configstore/common" - "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/util" + "agola.io/agola/services/configstore/types" sq "github.com/Masterminds/squirrel" errors "golang.org/x/xerrors" diff --git a/internal/services/configstore/readdb/project.go b/internal/services/configstore/readdb/project.go index ce2e1b6..03666bb 100644 --- a/internal/services/configstore/readdb/project.go +++ b/internal/services/configstore/readdb/project.go @@ -22,8 +22,8 @@ import ( "agola.io/agola/internal/db" "agola.io/agola/internal/services/configstore/common" - "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/util" + "agola.io/agola/services/configstore/types" sq "github.com/Masterminds/squirrel" errors "golang.org/x/xerrors" diff --git a/internal/services/configstore/readdb/projectgroup.go b/internal/services/configstore/readdb/projectgroup.go index 4e7138c..5debfe8 100644 --- a/internal/services/configstore/readdb/projectgroup.go +++ b/internal/services/configstore/readdb/projectgroup.go @@ -22,8 +22,8 @@ import ( "agola.io/agola/internal/db" "agola.io/agola/internal/services/configstore/common" - "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/util" + "agola.io/agola/services/configstore/types" sq "github.com/Masterminds/squirrel" errors "golang.org/x/xerrors" diff --git a/internal/services/configstore/readdb/readdb.go b/internal/services/configstore/readdb/readdb.go index a4e3f11..cbec1ba 100644 --- a/internal/services/configstore/readdb/readdb.go +++ b/internal/services/configstore/readdb/readdb.go @@ -30,8 +30,8 @@ import ( "agola.io/agola/internal/objectstorage" ostypes "agola.io/agola/internal/objectstorage/types" "agola.io/agola/internal/sequence" - "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/util" + "agola.io/agola/services/configstore/types" sq "github.com/Masterminds/squirrel" "go.uber.org/zap" diff --git a/internal/services/configstore/readdb/remotesource.go b/internal/services/configstore/readdb/remotesource.go index f6be51b..ecbde98 100644 --- a/internal/services/configstore/readdb/remotesource.go +++ b/internal/services/configstore/readdb/remotesource.go @@ -21,8 +21,8 @@ import ( "agola.io/agola/internal/db" "agola.io/agola/internal/services/configstore/common" - "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/util" + "agola.io/agola/services/configstore/types" sq "github.com/Masterminds/squirrel" errors "golang.org/x/xerrors" diff --git a/internal/services/configstore/readdb/resolve.go b/internal/services/configstore/readdb/resolve.go index f8fc1cd..8959a13 100644 --- a/internal/services/configstore/readdb/resolve.go +++ b/internal/services/configstore/readdb/resolve.go @@ -18,8 +18,8 @@ import ( "path" "agola.io/agola/internal/db" - "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/util" + "agola.io/agola/services/configstore/types" errors "golang.org/x/xerrors" ) diff --git a/internal/services/configstore/readdb/secret.go b/internal/services/configstore/readdb/secret.go index c3eaffa..4894a61 100644 --- a/internal/services/configstore/readdb/secret.go +++ b/internal/services/configstore/readdb/secret.go @@ -19,8 +19,8 @@ import ( "encoding/json" "agola.io/agola/internal/db" - "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/util" + "agola.io/agola/services/configstore/types" sq "github.com/Masterminds/squirrel" errors "golang.org/x/xerrors" diff --git a/internal/services/configstore/readdb/user.go b/internal/services/configstore/readdb/user.go index 952fb55..04545be 100644 --- a/internal/services/configstore/readdb/user.go +++ b/internal/services/configstore/readdb/user.go @@ -20,8 +20,8 @@ import ( "agola.io/agola/internal/db" "agola.io/agola/internal/services/configstore/common" - "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/util" + "agola.io/agola/services/configstore/types" sq "github.com/Masterminds/squirrel" errors "golang.org/x/xerrors" diff --git a/internal/services/configstore/readdb/variable.go b/internal/services/configstore/readdb/variable.go index de7ba65..5d8756c 100644 --- a/internal/services/configstore/readdb/variable.go +++ b/internal/services/configstore/readdb/variable.go @@ -19,8 +19,8 @@ import ( "encoding/json" "agola.io/agola/internal/db" - "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/util" + "agola.io/agola/services/configstore/types" sq "github.com/Masterminds/squirrel" errors "golang.org/x/xerrors" diff --git a/internal/services/executor/api.go b/internal/services/executor/api.go index f400b39..8ed4864 100644 --- a/internal/services/executor/api.go +++ b/internal/services/executor/api.go @@ -23,7 +23,7 @@ import ( "strconv" "time" - "agola.io/agola/internal/services/runservice/types" + "agola.io/agola/services/runservice/types" "go.uber.org/zap" errors "golang.org/x/xerrors" ) diff --git a/internal/services/executor/driver/docker.go b/internal/services/executor/driver/docker.go index edd12d8..b3a6ea7 100644 --- a/internal/services/executor/driver/docker.go +++ b/internal/services/executor/driver/docker.go @@ -28,11 +28,11 @@ import ( "strings" "time" - "agola.io/agola/internal/common" "agola.io/agola/internal/services/executor/registry" + "agola.io/agola/services/types" errors "golang.org/x/xerrors" - "github.com/docker/docker/api/types" + dockertypes "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/filters" "github.com/docker/docker/client" @@ -47,7 +47,7 @@ type DockerDriver struct { initVolumeHostDir string toolboxPath string executorID string - arch common.Arch + arch types.Arch } func NewDockerDriver(logger *zap.Logger, executorID, initVolumeHostDir, toolboxPath string) (*DockerDriver, error) { @@ -62,7 +62,7 @@ func NewDockerDriver(logger *zap.Logger, executorID, initVolumeHostDir, toolboxP initVolumeHostDir: initVolumeHostDir, toolboxPath: toolboxPath, executorID: executorID, - arch: common.ArchFromString(runtime.GOARCH), + arch: types.ArchFromString(runtime.GOARCH), }, nil } @@ -76,7 +76,7 @@ func (d *DockerDriver) Setup(ctx context.Context) error { func (d *DockerDriver) CopyToolbox(ctx context.Context) error { // by default always try to pull the image so we are sure only authorized users can fetch them // see https://kubernetes.io/docs/reference/access-authn-authz/admission-controllers/#alwayspullimages - reader, err := d.client.ImagePull(ctx, "busybox", types.ImagePullOptions{}) + reader, err := d.client.ImagePull(ctx, "busybox", dockertypes.ImagePullOptions{}) if err != nil { return err } @@ -97,7 +97,7 @@ func (d *DockerDriver) CopyToolbox(ctx context.Context) error { containerID := resp.ID - if err := d.client.ContainerStart(ctx, containerID, types.ContainerStartOptions{}); err != nil { + if err := d.client.ContainerStart(ctx, containerID, dockertypes.ContainerStartOptions{}); err != nil { return err } @@ -117,7 +117,7 @@ func (d *DockerDriver) CopyToolbox(ctx context.Context) error { } defer srcArchive.Close() - options := types.CopyToContainerOptions{ + options := dockertypes.CopyToContainerOptions{ AllowOverwriteDirWithFile: false, CopyUIDGID: false, } @@ -127,14 +127,14 @@ func (d *DockerDriver) CopyToolbox(ctx context.Context) error { } // ignore remove error - _ = d.client.ContainerRemove(ctx, containerID, types.ContainerRemoveOptions{Force: true}) + _ = d.client.ContainerRemove(ctx, containerID, dockertypes.ContainerRemoveOptions{Force: true}) return nil } -func (d *DockerDriver) Archs(ctx context.Context) ([]common.Arch, error) { +func (d *DockerDriver) Archs(ctx context.Context) ([]types.Arch, error) { // since we are using the local docker driver we can return our go arch information - return []common.Arch{d.arch}, nil + return []types.Arch{d.arch}, nil } func (d *DockerDriver) NewPod(ctx context.Context, podConfig *PodConfig, out io.Writer) (Pod, error) { @@ -155,7 +155,7 @@ func (d *DockerDriver) NewPod(ctx context.Context, podConfig *PodConfig, out io. mainContainerID = containerID } - if err := d.client.ContainerStart(ctx, containerID, types.ContainerStartOptions{}); err != nil { + if err := d.client.ContainerStart(ctx, containerID, dockertypes.ContainerStartOptions{}); err != nil { return nil, err } } @@ -171,7 +171,7 @@ func (d *DockerDriver) NewPod(ctx context.Context, podConfig *PodConfig, out io. } containers, err := d.client.ContainerList(ctx, - types.ContainerListOptions{ + dockertypes.ContainerListOptions{ Filters: args, }) if err != nil { @@ -241,7 +241,7 @@ func (d *DockerDriver) fetchImage(ctx context.Context, image string, registryCon // by default always try to pull the image so we are sure only authorized users can fetch them // see https://kubernetes.io/docs/reference/access-authn-authz/admission-controllers/#alwayspullimages - reader, err := d.client.ImagePull(ctx, image, types.ImagePullOptions{RegistryAuth: registryAuthEnc}) + reader, err := d.client.ImagePull(ctx, image, dockertypes.ImagePullOptions{RegistryAuth: registryAuthEnc}) if err != nil { return err } @@ -307,7 +307,7 @@ func (d *DockerDriver) GetPods(ctx context.Context, all bool) ([]Pod, error) { args := filters.NewArgs() containers, err := d.client.ContainerList(ctx, - types.ContainerListOptions{ + dockertypes.ContainerListOptions{ Filters: args, All: all, }) @@ -401,7 +401,7 @@ type DockerPod struct { type DockerContainer struct { Index int - types.Container + dockertypes.Container } type ContainerSlice []*DockerContainer @@ -439,7 +439,7 @@ func (dp *DockerPod) Stop(ctx context.Context) error { func (dp *DockerPod) Remove(ctx context.Context) error { errs := []error{} for _, container := range dp.containers { - if err := dp.client.ContainerRemove(ctx, container.ID, types.ContainerRemoveOptions{Force: true}); err != nil { + if err := dp.client.ContainerRemove(ctx, container.ID, dockertypes.ContainerRemoveOptions{Force: true}); err != nil { errs = append(errs, err) } } @@ -451,7 +451,7 @@ func (dp *DockerPod) Remove(ctx context.Context) error { type DockerContainerExec struct { execID string - hresp *types.HijackedResponse + hresp *dockertypes.HijackedResponse client *client.Client endCh chan error @@ -461,7 +461,7 @@ type DockerContainerExec struct { // Stdin is a wrapped HikackedResponse implementing io.WriteCloser so users can // easily close stdin. Internally it will close only the write side of the conn. type Stdin struct { - hresp *types.HijackedResponse + hresp *dockertypes.HijackedResponse } func (s *Stdin) Write(p []byte) (int, error) { @@ -475,7 +475,7 @@ func (s *Stdin) Close() error { func (dp *DockerPod) Exec(ctx context.Context, execConfig *ExecConfig) (ContainerExec, error) { endCh := make(chan error) - dockerExecConfig := types.ExecConfig{ + dockerExecConfig := dockertypes.ExecConfig{ Cmd: execConfig.Cmd, Env: makeEnvSlice(execConfig.Env), Tty: execConfig.Tty, @@ -490,7 +490,7 @@ func (dp *DockerPod) Exec(ctx context.Context, execConfig *ExecConfig) (Containe if err != nil { return nil, err } - execStartCheck := types.ExecStartCheck{ + execStartCheck := dockertypes.ExecStartCheck{ Detach: dockerExecConfig.Detach, Tty: dockerExecConfig.Tty, } diff --git a/internal/services/executor/driver/driver.go b/internal/services/executor/driver/driver.go index 05968dc..5c3a668 100644 --- a/internal/services/executor/driver/driver.go +++ b/internal/services/executor/driver/driver.go @@ -21,8 +21,8 @@ import ( "os" "path/filepath" - "agola.io/agola/internal/common" "agola.io/agola/internal/services/executor/registry" + "agola.io/agola/services/types" ) const ( @@ -53,7 +53,7 @@ type Driver interface { GetPods(ctx context.Context, all bool) ([]Pod, error) ExecutorGroup(ctx context.Context) (string, error) GetExecutors(ctx context.Context) ([]string, error) - Archs(ctx context.Context) ([]common.Arch, error) + Archs(ctx context.Context) ([]types.Arch, error) } type Pod interface { @@ -80,7 +80,7 @@ type PodConfig struct { ID string TaskID string Containers []*ContainerConfig - Arch common.Arch + Arch types.Arch // The container dir where the init volume will be mounted InitVolumeDir string DockerConfig *registry.DockerConfig @@ -106,7 +106,7 @@ type ExecConfig struct { Tty bool } -func toolboxExecPath(toolboxDir string, arch common.Arch) (string, error) { +func toolboxExecPath(toolboxDir string, arch types.Arch) (string, error) { toolboxPath := filepath.Join(toolboxDir, fmt.Sprintf("%s-linux-%s", toolboxPrefix, arch)) _, err := os.Stat(toolboxPath) if err != nil { diff --git a/internal/services/executor/driver/k8s.go b/internal/services/executor/driver/k8s.go index 9270922..126a242 100644 --- a/internal/services/executor/driver/k8s.go +++ b/internal/services/executor/driver/k8s.go @@ -26,8 +26,8 @@ import ( "strings" "time" - "agola.io/agola/internal/common" "agola.io/agola/internal/util" + "agola.io/agola/services/types" "github.com/docker/docker/pkg/archive" uuid "github.com/satori/go.uuid" @@ -248,16 +248,16 @@ func (d *K8sDriver) Setup(ctx context.Context) error { return nil } -func (d *K8sDriver) Archs(ctx context.Context) ([]common.Arch, error) { +func (d *K8sDriver) Archs(ctx context.Context) ([]types.Arch, error) { // TODO(sgotti) use go client listers instead of querying every time nodes, err := d.nodeLister.List(apilabels.SelectorFromSet(nil)) if err != nil { return nil, err } - archsMap := map[common.Arch]struct{}{} - archs := []common.Arch{} + archsMap := map[types.Arch]struct{}{} + archs := []types.Arch{} for _, node := range nodes { - archsMap[common.ArchFromString(node.Status.NodeInfo.Architecture)] = struct{}{} + archsMap[types.ArchFromString(node.Status.NodeInfo.Architecture)] = struct{}{} } for arch := range archsMap { archs = append(archs, arch) @@ -489,12 +489,12 @@ func (d *K8sDriver) NewPod(ctx context.Context, podConfig *PodConfig, out io.Wri } osArch := strings.TrimSpace(stdout.String()) - var arch common.Arch + var arch types.Arch switch osArch { case "x86_64": - arch = common.ArchAMD64 + arch = types.ArchAMD64 case "aarch64": - arch = common.ArchARM64 + arch = types.ArchARM64 default: return nil, errors.Errorf("unsupported pod arch %q", osArch) } diff --git a/internal/services/executor/executor.go b/internal/services/executor/executor.go index 565630a..41909fb 100644 --- a/internal/services/executor/executor.go +++ b/internal/services/executor/executor.go @@ -35,9 +35,9 @@ import ( "agola.io/agola/internal/services/config" "agola.io/agola/internal/services/executor/driver" "agola.io/agola/internal/services/executor/registry" - rsapi "agola.io/agola/internal/services/runservice/api" - "agola.io/agola/internal/services/runservice/types" "agola.io/agola/internal/util" + rsclient "agola.io/agola/services/runservice/client" + "agola.io/agola/services/runservice/types" uuid "github.com/satori/go.uuid" "github.com/gorilla/mux" @@ -1304,7 +1304,7 @@ func (e *Executor) saveExecutorID(id string) error { type Executor struct { c *config.Executor - runserviceClient *rsapi.Client + runserviceClient *rsclient.Client id string runningTasks *runningTasks driver driver.Driver @@ -1325,7 +1325,7 @@ func NewExecutor(c *config.Executor) (*Executor, error) { e := &Executor{ c: c, - runserviceClient: rsapi.NewClient(c.RunserviceURL), + runserviceClient: rsclient.NewClient(c.RunserviceURL), runningTasks: &runningTasks{ tasks: make(map[string]*runningTask), }, diff --git a/internal/services/executor/registry/registry.go b/internal/services/executor/registry/registry.go index d4810c2..14e0cc9 100644 --- a/internal/services/executor/registry/registry.go +++ b/internal/services/executor/registry/registry.go @@ -19,7 +19,7 @@ import ( "fmt" "strings" - "agola.io/agola/internal/services/runservice/types" + "agola.io/agola/services/runservice/types" errors "golang.org/x/xerrors" "github.com/google/go-containerregistry/pkg/name" diff --git a/internal/services/gateway/action/action.go b/internal/services/gateway/action/action.go index e49e43b..bdd61cc 100644 --- a/internal/services/gateway/action/action.go +++ b/internal/services/gateway/action/action.go @@ -18,9 +18,9 @@ import ( "net/http" "agola.io/agola/internal/services/common" - csapi "agola.io/agola/internal/services/configstore/api" - rsapi "agola.io/agola/internal/services/runservice/api" "agola.io/agola/internal/util" + csclient "agola.io/agola/services/configstore/client" + rsclient "agola.io/agola/services/runservice/client" "go.uber.org/zap" ) @@ -28,14 +28,14 @@ import ( type ActionHandler struct { log *zap.SugaredLogger sd *common.TokenSigningData - configstoreClient *csapi.Client - runserviceClient *rsapi.Client + configstoreClient *csclient.Client + runserviceClient *rsclient.Client agolaID string apiExposedURL string webExposedURL string } -func NewActionHandler(logger *zap.Logger, sd *common.TokenSigningData, configstoreClient *csapi.Client, runserviceClient *rsapi.Client, agolaID, apiExposedURL, webExposedURL string) *ActionHandler { +func NewActionHandler(logger *zap.Logger, sd *common.TokenSigningData, configstoreClient *csclient.Client, runserviceClient *rsclient.Client, agolaID, apiExposedURL, webExposedURL string) *ActionHandler { return &ActionHandler{ log: logger.Sugar(), sd: sd, diff --git a/internal/services/gateway/action/auth.go b/internal/services/gateway/action/auth.go index e12c1f0..bc585d3 100644 --- a/internal/services/gateway/action/auth.go +++ b/internal/services/gateway/action/auth.go @@ -18,7 +18,7 @@ import ( "context" "agola.io/agola/internal/services/common" - cstypes "agola.io/agola/internal/services/configstore/types" + cstypes "agola.io/agola/services/configstore/types" errors "golang.org/x/xerrors" ) diff --git a/internal/services/gateway/action/badge.go b/internal/services/gateway/action/badge.go index e8a26fe..cab1059 100644 --- a/internal/services/gateway/action/badge.go +++ b/internal/services/gateway/action/badge.go @@ -20,7 +20,7 @@ import ( "path" "agola.io/agola/internal/services/common" - rstypes "agola.io/agola/internal/services/runservice/types" + rstypes "agola.io/agola/services/runservice/types" ) // GetBadge return a badge for a project branch diff --git a/internal/services/gateway/action/org.go b/internal/services/gateway/action/org.go index 8816c3c..c2135ca 100644 --- a/internal/services/gateway/action/org.go +++ b/internal/services/gateway/action/org.go @@ -17,8 +17,8 @@ package action import ( "context" - cstypes "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/util" + cstypes "agola.io/agola/services/configstore/types" errors "golang.org/x/xerrors" ) diff --git a/internal/services/gateway/action/project.go b/internal/services/gateway/action/project.go index cee237b..8e8e0c4 100644 --- a/internal/services/gateway/action/project.go +++ b/internal/services/gateway/action/project.go @@ -22,15 +22,15 @@ import ( "path" gitsource "agola.io/agola/internal/gitsources" - csapi "agola.io/agola/internal/services/configstore/api" - cstypes "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/services/types" "agola.io/agola/internal/util" + csapitypes "agola.io/agola/services/configstore/api/types" + cstypes "agola.io/agola/services/configstore/types" errors "golang.org/x/xerrors" ) -func (h *ActionHandler) GetProject(ctx context.Context, projectRef string) (*csapi.Project, error) { +func (h *ActionHandler) GetProject(ctx context.Context, projectRef string) (*csapitypes.Project, error) { project, resp, err := h.configstoreClient.GetProject(ctx, projectRef) if err != nil { return nil, ErrFromRemote(resp, err) @@ -59,7 +59,7 @@ type CreateProjectRequest struct { SkipSSHHostKeyCheck bool } -func (h *ActionHandler) CreateProject(ctx context.Context, req *CreateProjectRequest) (*csapi.Project, error) { +func (h *ActionHandler) CreateProject(ctx context.Context, req *CreateProjectRequest) (*csapitypes.Project, error) { curUserID := h.CurrentUserID(ctx) user, resp, err := h.configstoreClient.GetUser(ctx, curUserID) @@ -184,7 +184,7 @@ type UpdateProjectRequest struct { Visibility cstypes.Visibility } -func (h *ActionHandler) UpdateProject(ctx context.Context, projectRef string, req *UpdateProjectRequest) (*csapi.Project, error) { +func (h *ActionHandler) UpdateProject(ctx context.Context, projectRef string, req *UpdateProjectRequest) (*csapitypes.Project, error) { p, resp, err := h.configstoreClient.GetProject(ctx, projectRef) if err != nil { return nil, errors.Errorf("failed to get project %q: %w", projectRef, ErrFromRemote(resp, err)) @@ -211,7 +211,7 @@ func (h *ActionHandler) UpdateProject(ctx context.Context, projectRef string, re return rp, nil } -func (h *ActionHandler) ProjectUpdateRepoLinkedAccount(ctx context.Context, projectRef string) (*csapi.Project, error) { +func (h *ActionHandler) ProjectUpdateRepoLinkedAccount(ctx context.Context, projectRef string) (*csapitypes.Project, error) { curUserID := h.CurrentUserID(ctx) user, resp, err := h.configstoreClient.GetUser(ctx, curUserID) @@ -270,7 +270,7 @@ func (h *ActionHandler) ProjectUpdateRepoLinkedAccount(ctx context.Context, proj return rp, nil } -func (h *ActionHandler) setupGitSourceRepo(ctx context.Context, rs *cstypes.RemoteSource, user *cstypes.User, la *cstypes.LinkedAccount, project *csapi.Project) error { +func (h *ActionHandler) setupGitSourceRepo(ctx context.Context, rs *cstypes.RemoteSource, user *cstypes.User, la *cstypes.LinkedAccount, project *csapitypes.Project) error { gitsource, err := h.GetGitSource(ctx, rs, user.Name, la) if err != nil { return errors.Errorf("failed to create gitsource client: %w", err) @@ -306,7 +306,7 @@ func (h *ActionHandler) setupGitSourceRepo(ctx context.Context, rs *cstypes.Remo return nil } -func (h *ActionHandler) cleanupGitSourceRepo(ctx context.Context, rs *cstypes.RemoteSource, user *cstypes.User, la *cstypes.LinkedAccount, project *csapi.Project) error { +func (h *ActionHandler) cleanupGitSourceRepo(ctx context.Context, rs *cstypes.RemoteSource, user *cstypes.User, la *cstypes.LinkedAccount, project *csapitypes.Project) error { gitsource, err := h.GetGitSource(ctx, rs, user.Name, la) if err != nil { return errors.Errorf("failed to create gitsource client: %w", err) @@ -333,7 +333,7 @@ func (h *ActionHandler) cleanupGitSourceRepo(ctx context.Context, rs *cstypes.Re return nil } -func (h *ActionHandler) genWebhookURL(project *csapi.Project) (string, error) { +func (h *ActionHandler) genWebhookURL(project *csapitypes.Project) (string, error) { baseWebhookURL := fmt.Sprintf("%s/webhooks", h.apiExposedURL) webhookURL, err := url.Parse(baseWebhookURL) if err != nil { diff --git a/internal/services/gateway/action/projectgroup.go b/internal/services/gateway/action/projectgroup.go index 4308cd0..f424ae9 100644 --- a/internal/services/gateway/action/projectgroup.go +++ b/internal/services/gateway/action/projectgroup.go @@ -18,14 +18,14 @@ import ( "context" "path" - csapi "agola.io/agola/internal/services/configstore/api" - cstypes "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/util" + csapitypes "agola.io/agola/services/configstore/api/types" + cstypes "agola.io/agola/services/configstore/types" errors "golang.org/x/xerrors" ) -func (h *ActionHandler) GetProjectGroup(ctx context.Context, projectGroupRef string) (*csapi.ProjectGroup, error) { +func (h *ActionHandler) GetProjectGroup(ctx context.Context, projectGroupRef string) (*csapitypes.ProjectGroup, error) { projectGroup, resp, err := h.configstoreClient.GetProjectGroup(ctx, projectGroupRef) if err != nil { return nil, ErrFromRemote(resp, err) @@ -33,7 +33,7 @@ func (h *ActionHandler) GetProjectGroup(ctx context.Context, projectGroupRef str return projectGroup, nil } -func (h *ActionHandler) GetProjectGroupSubgroups(ctx context.Context, projectGroupRef string) ([]*csapi.ProjectGroup, error) { +func (h *ActionHandler) GetProjectGroupSubgroups(ctx context.Context, projectGroupRef string) ([]*csapitypes.ProjectGroup, error) { projectGroups, resp, err := h.configstoreClient.GetProjectGroupSubgroups(ctx, projectGroupRef) if err != nil { return nil, ErrFromRemote(resp, err) @@ -41,7 +41,7 @@ func (h *ActionHandler) GetProjectGroupSubgroups(ctx context.Context, projectGro return projectGroups, nil } -func (h *ActionHandler) GetProjectGroupProjects(ctx context.Context, projectGroupRef string) ([]*csapi.Project, error) { +func (h *ActionHandler) GetProjectGroupProjects(ctx context.Context, projectGroupRef string) ([]*csapitypes.Project, error) { projects, resp, err := h.configstoreClient.GetProjectGroupProjects(ctx, projectGroupRef) if err != nil { return nil, ErrFromRemote(resp, err) @@ -56,7 +56,7 @@ type CreateProjectGroupRequest struct { Visibility cstypes.Visibility } -func (h *ActionHandler) CreateProjectGroup(ctx context.Context, req *CreateProjectGroupRequest) (*csapi.ProjectGroup, error) { +func (h *ActionHandler) CreateProjectGroup(ctx context.Context, req *CreateProjectGroupRequest) (*csapitypes.ProjectGroup, error) { if !util.ValidateName(req.Name) { return nil, util.NewErrBadRequest(errors.Errorf("invalid projectGroup name %q", req.Name)) } @@ -109,7 +109,7 @@ type UpdateProjectGroupRequest struct { Visibility cstypes.Visibility } -func (h *ActionHandler) UpdateProjectGroup(ctx context.Context, projectGroupRef string, req *UpdateProjectGroupRequest) (*csapi.ProjectGroup, error) { +func (h *ActionHandler) UpdateProjectGroup(ctx context.Context, projectGroupRef string, req *UpdateProjectGroupRequest) (*csapitypes.ProjectGroup, error) { pg, resp, err := h.configstoreClient.GetProjectGroup(ctx, projectGroupRef) if err != nil { return nil, errors.Errorf("failed to get project group %q: %w", projectGroupRef, ErrFromRemote(resp, err)) diff --git a/internal/services/gateway/action/remotesource.go b/internal/services/gateway/action/remotesource.go index 2fe724e..b3239aa 100644 --- a/internal/services/gateway/action/remotesource.go +++ b/internal/services/gateway/action/remotesource.go @@ -17,8 +17,8 @@ package action import ( "context" - cstypes "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/util" + cstypes "agola.io/agola/services/configstore/types" errors "golang.org/x/xerrors" ) diff --git a/internal/services/gateway/action/run.go b/internal/services/gateway/action/run.go index 5a19541..ccc1fe1 100644 --- a/internal/services/gateway/action/run.go +++ b/internal/services/gateway/action/run.go @@ -24,11 +24,11 @@ import ( gitsource "agola.io/agola/internal/gitsources" "agola.io/agola/internal/runconfig" "agola.io/agola/internal/services/common" - cstypes "agola.io/agola/internal/services/configstore/types" - rsapi "agola.io/agola/internal/services/runservice/api" - rstypes "agola.io/agola/internal/services/runservice/types" "agola.io/agola/internal/services/types" "agola.io/agola/internal/util" + cstypes "agola.io/agola/services/configstore/types" + rsapitypes "agola.io/agola/services/runservice/api/types" + rstypes "agola.io/agola/services/runservice/types" errors "golang.org/x/xerrors" ) @@ -65,7 +65,7 @@ const ( AnnotationPullRequestLink = "pull_request_link" ) -func (h *ActionHandler) GetRun(ctx context.Context, runID string) (*rsapi.RunResponse, error) { +func (h *ActionHandler) GetRun(ctx context.Context, runID string) (*rsapitypes.RunResponse, error) { runResp, resp, err := h.runserviceClient.GetRun(ctx, runID, nil) if err != nil { return nil, ErrFromRemote(resp, err) @@ -92,7 +92,7 @@ type GetRunsRequest struct { Asc bool } -func (h *ActionHandler) GetRuns(ctx context.Context, req *GetRunsRequest) (*rsapi.GetRunsResponse, error) { +func (h *ActionHandler) GetRuns(ctx context.Context, req *GetRunsRequest) (*rsapitypes.GetRunsResponse, error) { canGetRun, err := h.CanGetRun(ctx, req.Group) if err != nil { return nil, errors.Errorf("failed to determine permissions: %w", err) @@ -155,7 +155,7 @@ type RunActionsRequest struct { FromStart bool } -func (h *ActionHandler) RunAction(ctx context.Context, req *RunActionsRequest) (*rsapi.RunResponse, error) { +func (h *ActionHandler) RunAction(ctx context.Context, req *RunActionsRequest) (*rsapitypes.RunResponse, error) { runResp, resp, err := h.runserviceClient.GetRun(ctx, req.RunID, nil) if err != nil { return nil, ErrFromRemote(resp, err) @@ -170,7 +170,7 @@ func (h *ActionHandler) RunAction(ctx context.Context, req *RunActionsRequest) ( switch req.ActionType { case RunActionTypeRestart: - rsreq := &rsapi.RunCreateRequest{ + rsreq := &rsapitypes.RunCreateRequest{ RunID: req.RunID, FromStart: req.FromStart, } @@ -181,8 +181,8 @@ func (h *ActionHandler) RunAction(ctx context.Context, req *RunActionsRequest) ( } case RunActionTypeCancel: - rsreq := &rsapi.RunActionsRequest{ - ActionType: rsapi.RunActionTypeChangePhase, + rsreq := &rsapitypes.RunActionsRequest{ + ActionType: rsapitypes.RunActionTypeChangePhase, Phase: rstypes.RunPhaseCancelled, } @@ -192,8 +192,8 @@ func (h *ActionHandler) RunAction(ctx context.Context, req *RunActionsRequest) ( } case RunActionTypeStop: - rsreq := &rsapi.RunActionsRequest{ - ActionType: rsapi.RunActionTypeStop, + rsreq := &rsapitypes.RunActionsRequest{ + ActionType: rsapitypes.RunActionTypeStop, } resp, err = h.runserviceClient.RunActions(ctx, req.RunID, rsreq) @@ -271,8 +271,8 @@ func (h *ActionHandler) RunTaskAction(ctx context.Context, req *RunTaskActionsRe annotations[common.ApproversAnnotation] = string(approversj) - rsreq := &rsapi.RunTaskActionsRequest{ - ActionType: rsapi.RunTaskActionTypeSetAnnotations, + rsreq := &rsapitypes.RunTaskActionsRequest{ + ActionType: rsapitypes.RunTaskActionTypeSetAnnotations, Annotations: annotations, ChangeGroupsUpdateToken: runResp.ChangeGroupsUpdateToken, } @@ -461,7 +461,7 @@ func (h *ActionHandler) CreateRuns(ctx context.Context, req *CreateRunRequest) e // create a run (per config file) with a generic error since we cannot parse // it and know how many runs are defined setupErrors = append(setupErrors, err.Error()) - createRunReq := &rsapi.RunCreateRequest{ + createRunReq := &rsapitypes.RunCreateRequest{ RunConfigTasks: nil, Group: runGroup, SetupErrors: setupErrors, @@ -480,7 +480,7 @@ func (h *ActionHandler) CreateRuns(ctx context.Context, req *CreateRunRequest) e for _, run := range config.Runs { rcts := runconfig.GenRunConfigTasks(util.DefaultUUIDGenerator{}, config, run.Name, variables, req.Branch, req.Tag, req.Ref) - createRunReq := &rsapi.RunCreateRequest{ + createRunReq := &rsapitypes.RunCreateRequest{ RunConfigTasks: rcts, Group: runGroup, SetupErrors: setupErrors, diff --git a/internal/services/gateway/action/secret.go b/internal/services/gateway/action/secret.go index 29901d2..9539611 100644 --- a/internal/services/gateway/action/secret.go +++ b/internal/services/gateway/action/secret.go @@ -18,9 +18,9 @@ import ( "context" "net/http" - csapi "agola.io/agola/internal/services/configstore/api" - cstypes "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/util" + csapitypes "agola.io/agola/services/configstore/api/types" + cstypes "agola.io/agola/services/configstore/types" errors "golang.org/x/xerrors" ) @@ -32,8 +32,8 @@ type GetSecretsRequest struct { Tree bool } -func (h *ActionHandler) GetSecrets(ctx context.Context, req *GetSecretsRequest) ([]*csapi.Secret, error) { - var cssecrets []*csapi.Secret +func (h *ActionHandler) GetSecrets(ctx context.Context, req *GetSecretsRequest) ([]*csapitypes.Secret, error) { + var cssecrets []*csapitypes.Secret var resp *http.Response var err error switch req.ParentType { @@ -65,7 +65,7 @@ type CreateSecretRequest struct { Path string } -func (h *ActionHandler) CreateSecret(ctx context.Context, req *CreateSecretRequest) (*csapi.Secret, error) { +func (h *ActionHandler) CreateSecret(ctx context.Context, req *CreateSecretRequest) (*csapitypes.Secret, error) { isVariableOwner, err := h.IsVariableOwner(ctx, req.ParentType, req.ParentRef) if err != nil { return nil, errors.Errorf("failed to determine ownership: %w", err) @@ -85,7 +85,7 @@ func (h *ActionHandler) CreateSecret(ctx context.Context, req *CreateSecretReque } var resp *http.Response - var rs *csapi.Secret + var rs *csapitypes.Secret switch req.ParentType { case cstypes.ConfigTypeProjectGroup: h.log.Infof("creating project group secret") @@ -120,7 +120,7 @@ type UpdateSecretRequest struct { Path string } -func (h *ActionHandler) UpdateSecret(ctx context.Context, req *UpdateSecretRequest) (*csapi.Secret, error) { +func (h *ActionHandler) UpdateSecret(ctx context.Context, req *UpdateSecretRequest) (*csapitypes.Secret, error) { isVariableOwner, err := h.IsVariableOwner(ctx, req.ParentType, req.ParentRef) if err != nil { return nil, errors.Errorf("failed to determine ownership: %w", err) @@ -140,7 +140,7 @@ func (h *ActionHandler) UpdateSecret(ctx context.Context, req *UpdateSecretReque } var resp *http.Response - var rs *csapi.Secret + var rs *csapitypes.Secret switch req.ParentType { case cstypes.ConfigTypeProjectGroup: h.log.Infof("updating project group secret") diff --git a/internal/services/gateway/action/user.go b/internal/services/gateway/action/user.go index 67664e1..950a7c1 100644 --- a/internal/services/gateway/action/user.go +++ b/internal/services/gateway/action/user.go @@ -24,10 +24,10 @@ import ( gitsource "agola.io/agola/internal/gitsources" "agola.io/agola/internal/gitsources/agolagit" "agola.io/agola/internal/services/common" - csapi "agola.io/agola/internal/services/configstore/api" - cstypes "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/services/types" "agola.io/agola/internal/util" + csapitypes "agola.io/agola/services/configstore/api/types" + cstypes "agola.io/agola/services/configstore/types" jwt "github.com/dgrijalva/jwt-go" errors "golang.org/x/xerrors" @@ -90,7 +90,7 @@ func (h *ActionHandler) CreateUser(ctx context.Context, req *CreateUserRequest) return nil, util.NewErrBadRequest(errors.Errorf("invalid user name %q", req.UserName)) } - creq := &csapi.CreateUserRequest{ + creq := &csapitypes.CreateUserRequest{ UserName: req.UserName, } @@ -137,7 +137,7 @@ func (h *ActionHandler) CreateUserToken(ctx context.Context, req *CreateUserToke } h.log.Infof("creating user token") - creq := &csapi.CreateUserTokenRequest{ + creq := &csapitypes.CreateUserTokenRequest{ TokenName: req.TokenName, } res, resp, err := h.configstoreClient.CreateUserToken(ctx, userRef, creq) @@ -197,7 +197,7 @@ func (h *ActionHandler) CreateUserLA(ctx context.Context, req *CreateUserLAReque return nil, errors.Errorf("empty remote user id for remote source %q", rs.ID) } - creq := &csapi.CreateUserLARequest{ + creq := &csapitypes.CreateUserLARequest{ RemoteSourceName: req.RemoteSourceName, RemoteUserID: remoteUserInfo.ID, RemoteUserName: remoteUserInfo.LoginName, @@ -233,7 +233,7 @@ func (h *ActionHandler) UpdateUserLA(ctx context.Context, userRef string, la *cs return util.NewErrBadRequest(errors.Errorf("user %q doesn't have a linked account with id %q", userRef, la.ID)) } - creq := &csapi.UpdateUserLARequest{ + creq := &csapitypes.UpdateUserLARequest{ RemoteUserID: la.RemoteUserID, RemoteUserName: la.RemoteUserName, UserAccessToken: la.UserAccessToken, @@ -333,9 +333,9 @@ func (h *ActionHandler) RegisterUser(ctx context.Context, req *RegisterUserReque return nil, errors.Errorf("empty remote user id for remote source %q", rs.ID) } - creq := &csapi.CreateUserRequest{ + creq := &csapitypes.CreateUserRequest{ UserName: req.UserName, - CreateUserLARequest: &csapi.CreateUserLARequest{ + CreateUserLARequest: &csapitypes.CreateUserLARequest{ RemoteSourceName: req.RemoteSourceName, RemoteUserID: remoteUserInfo.ID, RemoteUserName: remoteUserInfo.LoginName, @@ -420,7 +420,7 @@ func (h *ActionHandler) LoginUser(ctx context.Context, req *LoginUserRequest) (* la.Oauth2RefreshToken = req.Oauth2RefreshToken la.UserAccessToken = req.UserAccessToken - creq := &csapi.UpdateUserLARequest{ + creq := &csapitypes.UpdateUserLARequest{ RemoteUserID: la.RemoteUserID, RemoteUserName: la.RemoteUserName, UserAccessToken: la.UserAccessToken, diff --git a/internal/services/gateway/action/variable.go b/internal/services/gateway/action/variable.go index e84e889..bb58701 100644 --- a/internal/services/gateway/action/variable.go +++ b/internal/services/gateway/action/variable.go @@ -19,9 +19,9 @@ import ( "net/http" "agola.io/agola/internal/services/common" - csapi "agola.io/agola/internal/services/configstore/api" - cstypes "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/util" + csapitypes "agola.io/agola/services/configstore/api/types" + cstypes "agola.io/agola/services/configstore/types" errors "golang.org/x/xerrors" ) @@ -33,9 +33,9 @@ type GetVariablesRequest struct { RemoveOverridden bool } -func (h *ActionHandler) GetVariables(ctx context.Context, req *GetVariablesRequest) ([]*csapi.Variable, []*csapi.Secret, error) { - var csvars []*csapi.Variable - var cssecrets []*csapi.Secret +func (h *ActionHandler) GetVariables(ctx context.Context, req *GetVariablesRequest) ([]*csapitypes.Variable, []*csapitypes.Secret, error) { + var csvars []*csapitypes.Variable + var cssecrets []*csapitypes.Secret switch req.ParentType { case cstypes.ConfigTypeProjectGroup: @@ -79,7 +79,7 @@ type CreateVariableRequest struct { Values []cstypes.VariableValue } -func (h *ActionHandler) CreateVariable(ctx context.Context, req *CreateVariableRequest) (*csapi.Variable, []*csapi.Secret, error) { +func (h *ActionHandler) CreateVariable(ctx context.Context, req *CreateVariableRequest) (*csapitypes.Variable, []*csapitypes.Secret, error) { isVariableOwner, err := h.IsVariableOwner(ctx, req.ParentType, req.ParentRef) if err != nil { return nil, nil, errors.Errorf("failed to determine ownership: %w", err) @@ -105,8 +105,8 @@ func (h *ActionHandler) CreateVariable(ctx context.Context, req *CreateVariableR Values: req.Values, } - var cssecrets []*csapi.Secret - var rv *csapi.Variable + var cssecrets []*csapitypes.Secret + var rv *csapitypes.Variable switch req.ParentType { case cstypes.ConfigTypeProjectGroup: @@ -152,7 +152,7 @@ type UpdateVariableRequest struct { Values []cstypes.VariableValue } -func (h *ActionHandler) UpdateVariable(ctx context.Context, req *UpdateVariableRequest) (*csapi.Variable, []*csapi.Secret, error) { +func (h *ActionHandler) UpdateVariable(ctx context.Context, req *UpdateVariableRequest) (*csapitypes.Variable, []*csapitypes.Secret, error) { isVariableOwner, err := h.IsVariableOwner(ctx, req.ParentType, req.ParentRef) if err != nil { return nil, nil, errors.Errorf("failed to determine ownership: %w", err) @@ -178,8 +178,8 @@ func (h *ActionHandler) UpdateVariable(ctx context.Context, req *UpdateVariableR Values: req.Values, } - var cssecrets []*csapi.Secret - var rv *csapi.Variable + var cssecrets []*csapitypes.Secret + var rv *csapitypes.Variable switch req.ParentType { case cstypes.ConfigTypeProjectGroup: diff --git a/internal/services/gateway/api/api.go b/internal/services/gateway/api/api.go index 8cfee8e..d18b5b8 100644 --- a/internal/services/gateway/api/api.go +++ b/internal/services/gateway/api/api.go @@ -19,8 +19,8 @@ import ( "net/http" "net/url" - cstypes "agola.io/agola/internal/services/configstore/types" - "agola.io/agola/internal/util" + util "agola.io/agola/internal/util" + cstypes "agola.io/agola/services/configstore/types" "github.com/gorilla/mux" errors "golang.org/x/xerrors" diff --git a/internal/services/gateway/api/badge.go b/internal/services/gateway/api/badge.go index 4ba0ff1..d4d9fb4 100644 --- a/internal/services/gateway/api/badge.go +++ b/internal/services/gateway/api/badge.go @@ -24,10 +24,6 @@ import ( "go.uber.org/zap" ) -type BadgeRequest struct { - Name string `json:"name"` -} - type BadgeHandler struct { log *zap.SugaredLogger ah *action.ActionHandler diff --git a/internal/services/gateway/api/oauth2.go b/internal/services/gateway/api/oauth2.go index 553b839..46cc312 100644 --- a/internal/services/gateway/api/oauth2.go +++ b/internal/services/gateway/api/oauth2.go @@ -19,6 +19,7 @@ import ( "agola.io/agola/internal/services/gateway/action" "agola.io/agola/internal/util" + gwapitypes "agola.io/agola/services/gateway/api/types" "go.uber.org/zap" ) @@ -28,11 +29,6 @@ type OAuth2CallbackHandler struct { ah *action.ActionHandler } -type RemoteSourceAuthResult struct { - RequestType string `json:"request_type,omitempty"` - Response interface{} `json:"response,omitempty"` -} - func NewOAuth2CallbackHandler(logger *zap.Logger, ah *action.ActionHandler) *OAuth2CallbackHandler { return &OAuth2CallbackHandler{log: logger.Sugar(), ah: ah} } @@ -54,29 +50,39 @@ func (h *OAuth2CallbackHandler) ServeHTTP(w http.ResponseWriter, r *http.Request switch cresp.RequestType { case action.RemoteSourceRequestTypeCreateUserLA: authresp := cresp.Response.(*action.CreateUserLAResponse) - response = &CreateUserLAResponse{ - LinkedAccount: authresp.LinkedAccount, + response = &gwapitypes.CreateUserLAResponse{ + LinkedAccount: &gwapitypes.LinkedAccount{ + ID: authresp.LinkedAccount.ID, + RemoteUserID: authresp.LinkedAccount.RemoteUserID, + RemoteUserName: authresp.LinkedAccount.RemoteUserName, + RemoteUserAvatarURL: authresp.LinkedAccount.RemoteUserAvatarURL, + RemoteSourceID: authresp.LinkedAccount.RemoteUserID, + }, } case action.RemoteSourceRequestTypeLoginUser: authresp := cresp.Response.(*action.LoginUserResponse) - response = &LoginUserResponse{ + response = &gwapitypes.LoginUserResponse{ Token: authresp.Token, User: createUserResponse(authresp.User), } case action.RemoteSourceRequestTypeAuthorize: authresp := cresp.Response.(*action.AuthorizeResponse) - response = &AuthorizeResponse{ - RemoteUserInfo: authresp.RemoteUserInfo, + response = &gwapitypes.AuthorizeResponse{ + RemoteUserInfo: &gwapitypes.UserInfo{ + ID: authresp.RemoteUserInfo.ID, + LoginName: authresp.RemoteUserInfo.LoginName, + Email: authresp.RemoteUserInfo.Email, + }, RemoteSourceName: authresp.RemoteSourceName, } case action.RemoteSourceRequestTypeRegisterUser: - response = &RegisterUserResponse{} + response = &gwapitypes.RegisterUserResponse{} } - res := RemoteSourceAuthResult{ + res := gwapitypes.RemoteSourceAuthResult{ RequestType: string(cresp.RequestType), Response: response, } diff --git a/internal/services/gateway/api/org.go b/internal/services/gateway/api/org.go index bfe334b..ddb9ec6 100644 --- a/internal/services/gateway/api/org.go +++ b/internal/services/gateway/api/org.go @@ -19,20 +19,16 @@ import ( "net/http" "strconv" - cstypes "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/services/gateway/action" "agola.io/agola/internal/util" + cstypes "agola.io/agola/services/configstore/types" + gwapitypes "agola.io/agola/services/gateway/api/types" "go.uber.org/zap" errors "golang.org/x/xerrors" "github.com/gorilla/mux" ) -type CreateOrgRequest struct { - Name string `json:"name"` - Visibility cstypes.Visibility `json:"visibility"` -} - type CreateOrgHandler struct { log *zap.SugaredLogger ah *action.ActionHandler @@ -51,7 +47,7 @@ func (h *CreateOrgHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { userID = userIDVal.(string) } - var req CreateOrgRequest + var req gwapitypes.CreateOrgRequest d := json.NewDecoder(r.Body) if err := d.Decode(&req); err != nil { httpError(w, util.NewErrBadRequest(err)) @@ -60,7 +56,7 @@ func (h *CreateOrgHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { creq := &action.CreateOrgRequest{ Name: req.Name, - Visibility: req.Visibility, + Visibility: cstypes.Visibility(req.Visibility), CreatorUserID: userID, } @@ -127,17 +123,11 @@ func (h *OrgHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } } -type OrgResponse struct { - ID string `json:"id"` - Name string `json:"name"` - Visibility cstypes.Visibility `json:"visibility,omitempty"` -} - -func createOrgResponse(o *cstypes.Organization) *OrgResponse { - org := &OrgResponse{ +func createOrgResponse(o *cstypes.Organization) *gwapitypes.OrgResponse { + org := &gwapitypes.OrgResponse{ ID: o.ID, Name: o.Name, - Visibility: o.Visibility, + Visibility: gwapitypes.Visibility(o.Visibility), } return org } @@ -190,7 +180,7 @@ func (h *OrgsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } - orgs := make([]*OrgResponse, len(csorgs)) + orgs := make([]*gwapitypes.OrgResponse, len(csorgs)) for i, p := range csorgs { orgs[i] = createOrgResponse(p) } @@ -199,20 +189,10 @@ func (h *OrgsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } } -type OrgMembersResponse struct { - Organization *OrgResponse `json:"organization"` - Members []*OrgMemberResponse `json:"members"` -} - -type OrgMemberResponse struct { - User *UserResponse `json:"user"` - Role cstypes.MemberRole `json:"role"` -} - -func createOrgMemberResponse(user *cstypes.User, role cstypes.MemberRole) *OrgMemberResponse { - return &OrgMemberResponse{ +func createOrgMemberResponse(user *cstypes.User, role cstypes.MemberRole) *gwapitypes.OrgMemberResponse { + return &gwapitypes.OrgMemberResponse{ User: createUserResponse(user), - Role: role, + Role: gwapitypes.MemberRole(role), } } @@ -237,9 +217,9 @@ func (h *OrgMembersHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } - res := &OrgMembersResponse{ + res := &gwapitypes.OrgMembersResponse{ Organization: createOrgResponse(ares.Organization), - Members: make([]*OrgMemberResponse, len(ares.Members)), + Members: make([]*gwapitypes.OrgMemberResponse, len(ares.Members)), } for i, m := range ares.Members { res.Members[i] = createOrgMemberResponse(m.User, m.Role) @@ -249,25 +229,16 @@ func (h *OrgMembersHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } } -type AddOrgMemberResponse struct { - Organization *OrgResponse `json:"organization"` - OrgMemberResponse -} - -func createAddOrgMemberResponse(org *cstypes.Organization, user *cstypes.User, role cstypes.MemberRole) *AddOrgMemberResponse { - return &AddOrgMemberResponse{ +func createAddOrgMemberResponse(org *cstypes.Organization, user *cstypes.User, role cstypes.MemberRole) *gwapitypes.AddOrgMemberResponse { + return &gwapitypes.AddOrgMemberResponse{ Organization: createOrgResponse(org), - OrgMemberResponse: OrgMemberResponse{ + OrgMemberResponse: gwapitypes.OrgMemberResponse{ User: createUserResponse(user), - Role: role, + Role: gwapitypes.MemberRole(role), }, } } -type AddOrgMemberRequest struct { - Role cstypes.MemberRole `json:"role"` -} - type AddOrgMemberHandler struct { log *zap.SugaredLogger ah *action.ActionHandler @@ -284,14 +255,14 @@ func (h *AddOrgMemberHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) orgRef := vars["orgref"] userRef := vars["userref"] - var req AddOrgMemberRequest + var req gwapitypes.AddOrgMemberRequest d := json.NewDecoder(r.Body) if err := d.Decode(&req); err != nil { httpError(w, util.NewErrBadRequest(err)) return } - ares, err := h.ah.AddOrgMember(ctx, orgRef, userRef, req.Role) + ares, err := h.ah.AddOrgMember(ctx, orgRef, userRef, cstypes.MemberRole(req.Role)) if httpError(w, err) { h.log.Errorf("err: %+v", err) return diff --git a/internal/services/gateway/api/project.go b/internal/services/gateway/api/project.go index 1f4890d..4c03c87 100644 --- a/internal/services/gateway/api/project.go +++ b/internal/services/gateway/api/project.go @@ -19,24 +19,16 @@ import ( "net/http" "net/url" - csapi "agola.io/agola/internal/services/configstore/api" - cstypes "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/services/gateway/action" "agola.io/agola/internal/util" + csapitypes "agola.io/agola/services/configstore/api/types" + cstypes "agola.io/agola/services/configstore/types" + gwapitypes "agola.io/agola/services/gateway/api/types" "github.com/gorilla/mux" "go.uber.org/zap" ) -type CreateProjectRequest struct { - Name string `json:"name,omitempty"` - ParentRef string `json:"parent_ref,omitempty"` - Visibility cstypes.Visibility `json:"visibility,omitempty"` - RepoPath string `json:"repo_path,omitempty"` - RemoteSourceName string `json:"remote_source_name,omitempty"` - SkipSSHHostKeyCheck bool `json:"skip_ssh_host_key_check,omitempty"` -} - type CreateProjectHandler struct { log *zap.SugaredLogger ah *action.ActionHandler @@ -49,7 +41,7 @@ func NewCreateProjectHandler(logger *zap.Logger, ah *action.ActionHandler) *Crea func (h *CreateProjectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { ctx := r.Context() - var req CreateProjectRequest + var req gwapitypes.CreateProjectRequest d := json.NewDecoder(r.Body) if err := d.Decode(&req); err != nil { httpError(w, util.NewErrBadRequest(err)) @@ -59,7 +51,7 @@ func (h *CreateProjectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) areq := &action.CreateProjectRequest{ Name: req.Name, ParentRef: req.ParentRef, - Visibility: req.Visibility, + Visibility: cstypes.Visibility(req.Visibility), RepoPath: req.RepoPath, RemoteSourceName: req.RemoteSourceName, SkipSSHHostKeyCheck: req.SkipSSHHostKeyCheck, @@ -77,11 +69,6 @@ func (h *CreateProjectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) } } -type UpdateProjectRequest struct { - Name string `json:"name,omitempty"` - Visibility cstypes.Visibility `json:"visibility,omitempty"` -} - type UpdateProjectHandler struct { log *zap.SugaredLogger ah *action.ActionHandler @@ -100,7 +87,7 @@ func (h *UpdateProjectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) return } - var req UpdateProjectRequest + var req gwapitypes.UpdateProjectRequest d := json.NewDecoder(r.Body) if err := d.Decode(&req); err != nil { httpError(w, util.NewErrBadRequest(err)) @@ -109,7 +96,7 @@ func (h *UpdateProjectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) areq := &action.UpdateProjectRequest{ Name: req.Name, - Visibility: req.Visibility, + Visibility: cstypes.Visibility(req.Visibility), } project, err := h.ah.UpdateProject(ctx, projectRef, areq) if httpError(w, err) { @@ -239,35 +226,19 @@ func (h *ProjectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } } -type ProjectResponse struct { - ID string `json:"id,omitempty"` - Name string `json:"name,omitempty"` - Path string `json:"path,omitempty"` - ParentPath string `json:"parent_path,omitempty"` - Visibility cstypes.Visibility `json:"visibility,omitempty"` - GlobalVisibility string `json:"global_visibility,omitempty"` -} - -func createProjectResponse(r *csapi.Project) *ProjectResponse { - res := &ProjectResponse{ +func createProjectResponse(r *csapitypes.Project) *gwapitypes.ProjectResponse { + res := &gwapitypes.ProjectResponse{ ID: r.ID, Name: r.Name, Path: r.Path, ParentPath: r.ParentPath, - Visibility: r.Visibility, + Visibility: gwapitypes.Visibility(r.Visibility), GlobalVisibility: string(r.GlobalVisibility), } return res } -type ProjectCreateRunRequest struct { - Branch string `json:"branch,omitempty"` - Tag string `json:"tag,omitempty"` - Ref string `json:"ref,omitempty"` - CommitSHA string `json:"commit_sha,omitempty"` -} - type ProjectCreateRunHandler struct { log *zap.SugaredLogger ah *action.ActionHandler @@ -286,7 +257,7 @@ func (h *ProjectCreateRunHandler) ServeHTTP(w http.ResponseWriter, r *http.Reque return } - var req ProjectCreateRunRequest + var req gwapitypes.ProjectCreateRunRequest d := json.NewDecoder(r.Body) if err := d.Decode(&req); err != nil { httpError(w, util.NewErrBadRequest(err)) diff --git a/internal/services/gateway/api/projectgroup.go b/internal/services/gateway/api/projectgroup.go index f30ec21..0b01c10 100644 --- a/internal/services/gateway/api/projectgroup.go +++ b/internal/services/gateway/api/projectgroup.go @@ -19,22 +19,17 @@ import ( "net/http" "net/url" - csapi "agola.io/agola/internal/services/configstore/api" - cstypes "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/services/gateway/action" "agola.io/agola/internal/util" + csapitypes "agola.io/agola/services/configstore/api/types" + cstypes "agola.io/agola/services/configstore/types" + gwapitypes "agola.io/agola/services/gateway/api/types" errors "golang.org/x/xerrors" "github.com/gorilla/mux" "go.uber.org/zap" ) -type CreateProjectGroupRequest struct { - Name string `json:"name"` - ParentRef string `json:"parent_ref"` - Visibility cstypes.Visibility `json:"visibility"` -} - type CreateProjectGroupHandler struct { log *zap.SugaredLogger ah *action.ActionHandler @@ -47,7 +42,7 @@ func NewCreateProjectGroupHandler(logger *zap.Logger, ah *action.ActionHandler) func (h *CreateProjectGroupHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { ctx := r.Context() - var req CreateProjectGroupRequest + var req gwapitypes.CreateProjectGroupRequest d := json.NewDecoder(r.Body) if err := d.Decode(&req); err != nil { httpError(w, util.NewErrBadRequest(err)) @@ -64,7 +59,7 @@ func (h *CreateProjectGroupHandler) ServeHTTP(w http.ResponseWriter, r *http.Req creq := &action.CreateProjectGroupRequest{ Name: req.Name, ParentRef: req.ParentRef, - Visibility: req.Visibility, + Visibility: cstypes.Visibility(req.Visibility), CurrentUserID: userID, } @@ -80,11 +75,6 @@ func (h *CreateProjectGroupHandler) ServeHTTP(w http.ResponseWriter, r *http.Req } } -type UpdateProjectGroupRequest struct { - Name string `json:"name,omitempty"` - Visibility cstypes.Visibility `json:"visibility,omitempty"` -} - type UpdateProjectGroupHandler struct { log *zap.SugaredLogger ah *action.ActionHandler @@ -103,7 +93,7 @@ func (h *UpdateProjectGroupHandler) ServeHTTP(w http.ResponseWriter, r *http.Req return } - var req UpdateProjectGroupRequest + var req gwapitypes.UpdateProjectGroupRequest d := json.NewDecoder(r.Body) if err := d.Decode(&req); err != nil { httpError(w, util.NewErrBadRequest(err)) @@ -112,7 +102,7 @@ func (h *UpdateProjectGroupHandler) ServeHTTP(w http.ResponseWriter, r *http.Req areq := &action.UpdateProjectGroupRequest{ Name: req.Name, - Visibility: req.Visibility, + Visibility: cstypes.Visibility(req.Visibility), } projectGroup, err := h.ah.UpdateProjectGroup(ctx, projectGroupRef, areq) if httpError(w, err) { @@ -209,7 +199,7 @@ func (h *ProjectGroupProjectsHandler) ServeHTTP(w http.ResponseWriter, r *http.R return } - projects := make([]*ProjectResponse, len(csprojects)) + projects := make([]*gwapitypes.ProjectResponse, len(csprojects)) for i, p := range csprojects { projects[i] = createProjectResponse(p) } @@ -243,7 +233,7 @@ func (h *ProjectGroupSubgroupsHandler) ServeHTTP(w http.ResponseWriter, r *http. return } - subgroups := make([]*ProjectGroupResponse, len(cssubgroups)) + subgroups := make([]*gwapitypes.ProjectGroupResponse, len(cssubgroups)) for i, g := range cssubgroups { subgroups[i] = createProjectGroupResponse(g) } @@ -253,22 +243,13 @@ func (h *ProjectGroupSubgroupsHandler) ServeHTTP(w http.ResponseWriter, r *http. } } -type ProjectGroupResponse struct { - ID string `json:"id"` - Name string `json:"name"` - Path string `json:"path"` - ParentPath string `json:"parent_path"` - Visibility cstypes.Visibility `json:"visibility"` - GlobalVisibility string `json:"global_visibility"` -} - -func createProjectGroupResponse(r *csapi.ProjectGroup) *ProjectGroupResponse { - run := &ProjectGroupResponse{ +func createProjectGroupResponse(r *csapitypes.ProjectGroup) *gwapitypes.ProjectGroupResponse { + run := &gwapitypes.ProjectGroupResponse{ ID: r.ID, Name: r.Name, Path: r.Path, ParentPath: r.ParentPath, - Visibility: r.Visibility, + Visibility: gwapitypes.Visibility(r.Visibility), GlobalVisibility: string(r.GlobalVisibility), } diff --git a/internal/services/gateway/api/remoterepo.go b/internal/services/gateway/api/remoterepo.go index 2db303b..a8aa724 100644 --- a/internal/services/gateway/api/remoterepo.go +++ b/internal/services/gateway/api/remoterepo.go @@ -18,23 +18,19 @@ import ( "net/http" gitsource "agola.io/agola/internal/gitsources" - csapi "agola.io/agola/internal/services/configstore/api" - cstypes "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/services/gateway/action" "agola.io/agola/internal/util" + csclient "agola.io/agola/services/configstore/client" + cstypes "agola.io/agola/services/configstore/types" + gwapitypes "agola.io/agola/services/gateway/api/types" "github.com/gorilla/mux" "go.uber.org/zap" errors "golang.org/x/xerrors" ) -type RemoteRepoResponse struct { - ID string `json:"id,omitempty"` - Path string `json:"path,omitempty"` -} - -func createRemoteRepoResponse(r *gitsource.RepoInfo) *RemoteRepoResponse { - rr := &RemoteRepoResponse{ +func createRemoteRepoResponse(r *gitsource.RepoInfo) *gwapitypes.RemoteRepoResponse { + rr := &gwapitypes.RemoteRepoResponse{ ID: r.ID, Path: r.Path, } @@ -45,10 +41,10 @@ func createRemoteRepoResponse(r *gitsource.RepoInfo) *RemoteRepoResponse { type UserRemoteReposHandler struct { log *zap.SugaredLogger ah *action.ActionHandler - configstoreClient *csapi.Client + configstoreClient *csclient.Client } -func NewUserRemoteReposHandler(logger *zap.Logger, ah *action.ActionHandler, configstoreClient *csapi.Client) *UserRemoteReposHandler { +func NewUserRemoteReposHandler(logger *zap.Logger, ah *action.ActionHandler, configstoreClient *csclient.Client) *UserRemoteReposHandler { return &UserRemoteReposHandler{log: logger.Sugar(), ah: ah, configstoreClient: configstoreClient} } @@ -105,7 +101,7 @@ func (h *UserRemoteReposHandler) ServeHTTP(w http.ResponseWriter, r *http.Reques return } - repos := make([]*RemoteRepoResponse, len(remoteRepos)) + repos := make([]*gwapitypes.RemoteRepoResponse, len(remoteRepos)) for i, r := range remoteRepos { repos[i] = createRemoteRepoResponse(r) } diff --git a/internal/services/gateway/api/remotesource.go b/internal/services/gateway/api/remotesource.go index 2de0831..b718838 100644 --- a/internal/services/gateway/api/remotesource.go +++ b/internal/services/gateway/api/remotesource.go @@ -19,29 +19,16 @@ import ( "net/http" "strconv" - cstypes "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/services/gateway/action" "agola.io/agola/internal/util" + cstypes "agola.io/agola/services/configstore/types" + gwapitypes "agola.io/agola/services/gateway/api/types" "go.uber.org/zap" "github.com/gorilla/mux" errors "golang.org/x/xerrors" ) -type CreateRemoteSourceRequest struct { - Name string `json:"name"` - APIURL string `json:"apiurl"` - Type string `json:"type"` - AuthType string `json:"auth_type"` - SkipVerify bool `json:"skip_verify"` - Oauth2ClientID string `json:"oauth_2_client_id"` - Oauth2ClientSecret string `json:"oauth_2_client_secret"` - SSHHostKey string `json:"ssh_host_key"` - SkipSSHHostKeyCheck bool `json:"skip_ssh_host_key_check"` - RegistrationEnabled *bool `json:"registration_enabled"` - LoginEnabled *bool `json:"login_enabled"` -} - type CreateRemoteSourceHandler struct { log *zap.SugaredLogger ah *action.ActionHandler @@ -54,7 +41,7 @@ func NewCreateRemoteSourceHandler(logger *zap.Logger, ah *action.ActionHandler) func (h *CreateRemoteSourceHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { ctx := r.Context() - var req CreateRemoteSourceRequest + var req gwapitypes.CreateRemoteSourceRequest d := json.NewDecoder(r.Body) if err := d.Decode(&req); err != nil { httpError(w, util.NewErrBadRequest(err)) @@ -86,18 +73,6 @@ func (h *CreateRemoteSourceHandler) ServeHTTP(w http.ResponseWriter, r *http.Req } } -type UpdateRemoteSourceRequest struct { - Name *string `json:"name"` - APIURL *string `json:"apiurl"` - SkipVerify *bool `json:"skip_verify"` - Oauth2ClientID *string `json:"oauth_2_client_id"` - Oauth2ClientSecret *string `json:"oauth_2_client_secret"` - SSHHostKey *string `json:"ssh_host_key"` - SkipSSHHostKeyCheck *bool `json:"skip_ssh_host_key_check"` - RegistrationEnabled *bool `json:"registration_enabled"` - LoginEnabled *bool `json:"login_enabled"` -} - type UpdateRemoteSourceHandler struct { log *zap.SugaredLogger ah *action.ActionHandler @@ -112,7 +87,7 @@ func (h *UpdateRemoteSourceHandler) ServeHTTP(w http.ResponseWriter, r *http.Req vars := mux.Vars(r) rsRef := vars["remotesourceref"] - var req UpdateRemoteSourceRequest + var req gwapitypes.UpdateRemoteSourceRequest d := json.NewDecoder(r.Body) if err := d.Decode(&req); err != nil { httpError(w, util.NewErrBadRequest(err)) @@ -144,16 +119,8 @@ func (h *UpdateRemoteSourceHandler) ServeHTTP(w http.ResponseWriter, r *http.Req } } -type RemoteSourceResponse struct { - ID string `json:"id"` - Name string `json:"name"` - AuthType string `json:"auth_type"` - RegistrationEnabled bool `json:"registration_enabled"` - LoginEnabled bool `json:"login_enabled"` -} - -func createRemoteSourceResponse(r *cstypes.RemoteSource) *RemoteSourceResponse { - rs := &RemoteSourceResponse{ +func createRemoteSourceResponse(r *cstypes.RemoteSource) *gwapitypes.RemoteSourceResponse { + rs := &gwapitypes.RemoteSourceResponse{ ID: r.ID, Name: r.Name, AuthType: string(r.AuthType), @@ -237,7 +204,7 @@ func (h *RemoteSourcesHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) return } - remoteSources := make([]*RemoteSourceResponse, len(csRemoteSources)) + remoteSources := make([]*gwapitypes.RemoteSourceResponse, len(csRemoteSources)) for i, rs := range csRemoteSources { remoteSources[i] = createRemoteSourceResponse(rs) } diff --git a/internal/services/gateway/api/run.go b/internal/services/gateway/api/run.go index 70e0f07..37a90d9 100644 --- a/internal/services/gateway/api/run.go +++ b/internal/services/gateway/api/run.go @@ -19,103 +19,19 @@ import ( "io" "net/http" "strconv" - "time" "agola.io/agola/internal/services/gateway/action" - rstypes "agola.io/agola/internal/services/runservice/types" "agola.io/agola/internal/util" - "go.uber.org/zap" - errors "golang.org/x/xerrors" + gwapitypes "agola.io/agola/services/gateway/api/types" + rstypes "agola.io/agola/services/runservice/types" "github.com/gorilla/mux" + "go.uber.org/zap" + errors "golang.org/x/xerrors" ) -type RunsResponse struct { - ID string `json:"id"` - Counter uint64 `json:"counter"` - Name string `json:"name"` - Annotations map[string]string `json:"annotations"` - Phase rstypes.RunPhase `json:"phase"` - Result rstypes.RunResult `json:"result"` - - TasksWaitingApproval []string `json:"tasks_waiting_approval"` - - EnqueueTime *time.Time `json:"enqueue_time"` - StartTime *time.Time `json:"start_time"` - EndTime *time.Time `json:"end_time"` -} - -type RunResponse struct { - ID string `json:"id"` - Counter uint64 `json:"counter"` - Name string `json:"name"` - Annotations map[string]string `json:"annotations"` - Phase rstypes.RunPhase `json:"phase"` - Result rstypes.RunResult `json:"result"` - SetupErrors []string `json:"setup_errors"` - Stopping bool `json:"stopping"` - - Tasks map[string]*RunResponseTask `json:"tasks"` - TasksWaitingApproval []string `json:"tasks_waiting_approval"` - - EnqueueTime *time.Time `json:"enqueue_time"` - StartTime *time.Time `json:"start_time"` - EndTime *time.Time `json:"end_time"` - - CanRestartFromScratch bool `json:"can_restart_from_scratch"` - CanRestartFromFailedTasks bool `json:"can_restart_from_failed_tasks"` -} - -type RunResponseTask struct { - ID string `json:"id"` - Name string `json:"name"` - Status rstypes.RunTaskStatus `json:"status"` - Level int `json:"level"` - Depends map[string]*rstypes.RunConfigTaskDepend `json:"depends"` - - WaitingApproval bool `json:"waiting_approval"` - Approved bool `json:"approved"` - ApprovalAnnotations map[string]string `json:"approval_annotations"` - - StartTime *time.Time `json:"start_time"` - EndTime *time.Time `json:"end_time"` -} - -type RunTaskResponse struct { - ID string `json:"id"` - Name string `json:"name"` - Status rstypes.RunTaskStatus `json:"status"` - - WaitingApproval bool `json:"waiting_approval"` - Approved bool `json:"approved"` - ApprovalAnnotations map[string]string `json:"approval_annotations"` - - SetupStep *RunTaskResponseSetupStep `json:"setup_step"` - Steps []*RunTaskResponseStep `json:"steps"` - - StartTime *time.Time `json:"start_time"` - EndTime *time.Time `json:"end_time"` -} - -type RunTaskResponseSetupStep struct { - Phase rstypes.ExecutorTaskPhase `json:"phase"` - Name string `json:"name"` - - StartTime *time.Time `json:"start_time"` - EndTime *time.Time `json:"end_time"` -} - -type RunTaskResponseStep struct { - Phase rstypes.ExecutorTaskPhase `json:"phase"` - Name string `json:"name"` - Command string `json:"command"` - - StartTime *time.Time `json:"start_time"` - EndTime *time.Time `json:"end_time"` -} - -func createRunResponse(r *rstypes.Run, rc *rstypes.RunConfig) *RunResponse { - run := &RunResponse{ +func createRunResponse(r *rstypes.Run, rc *rstypes.RunConfig) *gwapitypes.RunResponse { + run := &gwapitypes.RunResponse{ ID: r.ID, Counter: r.Counter, Name: r.Name, @@ -125,7 +41,7 @@ func createRunResponse(r *rstypes.Run, rc *rstypes.RunConfig) *RunResponse { Stopping: r.Stop, SetupErrors: rc.SetupErrors, - Tasks: make(map[string]*RunResponseTask), + Tasks: make(map[string]*gwapitypes.RunResponseTask), TasksWaitingApproval: r.TasksWaitingApproval(), EnqueueTime: r.EnqueueTime, @@ -144,8 +60,8 @@ func createRunResponse(r *rstypes.Run, rc *rstypes.RunConfig) *RunResponse { return run } -func createRunResponseTask(r *rstypes.Run, rt *rstypes.RunTask, rct *rstypes.RunConfigTask) *RunResponseTask { - t := &RunResponseTask{ +func createRunResponseTask(r *rstypes.Run, rt *rstypes.RunTask, rct *rstypes.RunConfigTask) *gwapitypes.RunResponseTask { + t := &gwapitypes.RunResponseTask{ ID: rt.ID, Name: rct.Name, Status: rt.Status, @@ -164,8 +80,8 @@ func createRunResponseTask(r *rstypes.Run, rt *rstypes.RunTask, rct *rstypes.Run return t } -func createRunTaskResponse(rt *rstypes.RunTask, rct *rstypes.RunConfigTask) *RunTaskResponse { - t := &RunTaskResponse{ +func createRunTaskResponse(rt *rstypes.RunTask, rct *rstypes.RunConfigTask) *gwapitypes.RunTaskResponse { + t := &gwapitypes.RunTaskResponse{ ID: rt.ID, Name: rct.Name, Status: rt.Status, @@ -174,13 +90,13 @@ func createRunTaskResponse(rt *rstypes.RunTask, rct *rstypes.RunConfigTask) *Run Approved: rt.Approved, ApprovalAnnotations: rt.Annotations, - Steps: make([]*RunTaskResponseStep, len(rt.Steps)), + Steps: make([]*gwapitypes.RunTaskResponseStep, len(rt.Steps)), StartTime: rt.StartTime, EndTime: rt.EndTime, } - t.SetupStep = &RunTaskResponseSetupStep{ + t.SetupStep = &gwapitypes.RunTaskResponseSetupStep{ Name: "Task setup", Phase: rt.SetupStep.Phase, StartTime: rt.SetupStep.StartTime, @@ -188,7 +104,7 @@ func createRunTaskResponse(rt *rstypes.RunTask, rct *rstypes.RunConfigTask) *Run } for i := 0; i < len(t.Steps); i++ { - s := &RunTaskResponseStep{ + s := &gwapitypes.RunTaskResponseStep{ Phase: rt.Steps[i].Phase, StartTime: rt.Steps[i].StartTime, EndTime: rt.Steps[i].EndTime, @@ -282,8 +198,8 @@ const ( MaxRunsLimit = 40 ) -func createRunsResponse(r *rstypes.Run) *RunsResponse { - run := &RunsResponse{ +func createRunsResponse(r *rstypes.Run) *gwapitypes.RunsResponse { + run := &gwapitypes.RunsResponse{ ID: r.ID, Counter: r.Counter, Name: r.Name, @@ -368,7 +284,7 @@ func (h *RunsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } - runs := make([]*RunsResponse, len(runsResp.Runs)) + runs := make([]*gwapitypes.RunsResponse, len(runsResp.Runs)) for i, r := range runsResp.Runs { runs[i] = createRunsResponse(r) } @@ -377,13 +293,6 @@ func (h *RunsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } } -type RunActionsRequest struct { - ActionType action.RunActionType `json:"action_type"` - - // Restart - FromStart bool `json:"from_start"` -} - type RunActionsHandler struct { log *zap.SugaredLogger ah *action.ActionHandler @@ -398,7 +307,7 @@ func (h *RunActionsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) runID := vars["runid"] - var req RunActionsRequest + var req gwapitypes.RunActionsRequest d := json.NewDecoder(r.Body) if err := d.Decode(&req); err != nil { httpError(w, util.NewErrBadRequest(err)) @@ -407,7 +316,7 @@ func (h *RunActionsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { areq := &action.RunActionsRequest{ RunID: runID, - ActionType: req.ActionType, + ActionType: action.RunActionType(req.ActionType), FromStart: req.FromStart, } @@ -423,10 +332,6 @@ func (h *RunActionsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } } -type RunTaskActionsRequest struct { - ActionType action.RunTaskActionType `json:"action_type"` -} - type RunTaskActionsHandler struct { log *zap.SugaredLogger ah *action.ActionHandler @@ -442,7 +347,7 @@ func (h *RunTaskActionsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request runID := vars["runid"] taskID := vars["taskid"] - var req RunTaskActionsRequest + var req gwapitypes.RunTaskActionsRequest d := json.NewDecoder(r.Body) if err := d.Decode(&req); err != nil { httpError(w, util.NewErrBadRequest(err)) @@ -452,7 +357,7 @@ func (h *RunTaskActionsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request areq := &action.RunTaskActionsRequest{ RunID: runID, TaskID: taskID, - ActionType: req.ActionType, + ActionType: action.RunTaskActionType(req.ActionType), } err := h.ah.RunTaskAction(ctx, areq) diff --git a/internal/services/gateway/api/secret.go b/internal/services/gateway/api/secret.go index 4348149..92acd72 100644 --- a/internal/services/gateway/api/secret.go +++ b/internal/services/gateway/api/secret.go @@ -18,23 +18,18 @@ import ( "encoding/json" "net/http" - csapi "agola.io/agola/internal/services/configstore/api" - cstypes "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/services/gateway/action" "agola.io/agola/internal/util" + csapitypes "agola.io/agola/services/configstore/api/types" + cstypes "agola.io/agola/services/configstore/types" + gwapitypes "agola.io/agola/services/gateway/api/types" "github.com/gorilla/mux" "go.uber.org/zap" ) -type SecretResponse struct { - ID string `json:"id"` - Name string `json:"name"` - ParentPath string `json:"parent_path"` -} - -func createSecretResponse(s *csapi.Secret) *SecretResponse { - return &SecretResponse{ +func createSecretResponse(s *csapitypes.Secret) *gwapitypes.SecretResponse { + return &gwapitypes.SecretResponse{ ID: s.ID, Name: s.Name, ParentPath: s.ParentPath, @@ -72,7 +67,7 @@ func (h *SecretHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } - secrets := make([]*SecretResponse, len(cssecrets)) + secrets := make([]*gwapitypes.SecretResponse, len(cssecrets)) for i, s := range cssecrets { secrets[i] = createSecretResponse(s) } @@ -82,19 +77,6 @@ func (h *SecretHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } } -type CreateSecretRequest struct { - Name string `json:"name,omitempty"` - - Type cstypes.SecretType `json:"type,omitempty"` - - // internal secret - Data map[string]string `json:"data,omitempty"` - - // external secret - SecretProviderID string `json:"secret_provider_id,omitempty"` - Path string `json:"path,omitempty"` -} - type CreateSecretHandler struct { log *zap.SugaredLogger ah *action.ActionHandler @@ -111,7 +93,7 @@ func (h *CreateSecretHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) return } - var req CreateSecretRequest + var req gwapitypes.CreateSecretRequest d := json.NewDecoder(r.Body) if err := d.Decode(&req); err != nil { httpError(w, util.NewErrBadRequest(err)) @@ -122,7 +104,7 @@ func (h *CreateSecretHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) Name: req.Name, ParentType: parentType, ParentRef: parentRef, - Type: req.Type, + Type: cstypes.SecretType(req.Type), Data: req.Data, SecretProviderID: req.SecretProviderID, Path: req.Path, @@ -139,19 +121,6 @@ func (h *CreateSecretHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) } } -type UpdateSecretRequest struct { - Name string `json:"name,omitempty"` - - Type cstypes.SecretType `json:"type,omitempty"` - - // internal secret - Data map[string]string `json:"data,omitempty"` - - // external secret - SecretProviderID string `json:"secret_provider_id,omitempty"` - Path string `json:"path,omitempty"` -} - type UpdateSecretHandler struct { log *zap.SugaredLogger ah *action.ActionHandler @@ -172,7 +141,7 @@ func (h *UpdateSecretHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) return } - var req UpdateSecretRequest + var req gwapitypes.UpdateSecretRequest d := json.NewDecoder(r.Body) if err := d.Decode(&req); err != nil { httpError(w, util.NewErrBadRequest(err)) @@ -184,7 +153,7 @@ func (h *UpdateSecretHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) Name: req.Name, ParentType: parentType, ParentRef: parentRef, - Type: req.Type, + Type: cstypes.SecretType(req.Type), Data: req.Data, SecretProviderID: req.SecretProviderID, Path: req.Path, diff --git a/internal/services/gateway/api/user.go b/internal/services/gateway/api/user.go index 1b1fa38..6d6e73c 100644 --- a/internal/services/gateway/api/user.go +++ b/internal/services/gateway/api/user.go @@ -21,20 +21,16 @@ import ( "sort" "strconv" - gitsource "agola.io/agola/internal/gitsources" - cstypes "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/services/gateway/action" "agola.io/agola/internal/util" + cstypes "agola.io/agola/services/configstore/types" + gwapitypes "agola.io/agola/services/gateway/api/types" "github.com/gorilla/mux" "go.uber.org/zap" errors "golang.org/x/xerrors" ) -type CreateUserRequest struct { - UserName string `json:"username"` -} - type CreateUserHandler struct { log *zap.SugaredLogger ah *action.ActionHandler @@ -47,7 +43,7 @@ func NewCreateUserHandler(logger *zap.Logger, ah *action.ActionHandler) *CreateU func (h *CreateUserHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { ctx := r.Context() - var req CreateUserRequest + var req gwapitypes.CreateUserRequest d := json.NewDecoder(r.Body) if err := d.Decode(&req); err != nil { httpError(w, util.NewErrBadRequest(err)) @@ -152,26 +148,12 @@ func (h *UserHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } } -type UserResponse struct { - ID string `json:"id"` - UserName string `json:"username"` - Tokens []string `json:"tokens"` - LinkedAccounts []*LinkedAccountResponse `json:"linked_accounts"` -} - -type LinkedAccountResponse struct { - ID string `json:"id"` - RemoteSourceID string `json:"remote_source_id"` - RemoteUserName string `json:"remote_user_name"` - RemoteUserAvatarURL string `json:"remote_user_avatar_url"` -} - -func createUserResponse(u *cstypes.User) *UserResponse { - user := &UserResponse{ +func createUserResponse(u *cstypes.User) *gwapitypes.UserResponse { + user := &gwapitypes.UserResponse{ ID: u.ID, UserName: u.Name, Tokens: make([]string, 0, len(u.Tokens)), - LinkedAccounts: make([]*LinkedAccountResponse, 0, len(u.LinkedAccounts)), + LinkedAccounts: make([]*gwapitypes.LinkedAccountResponse, 0, len(u.LinkedAccounts)), } for tokenName := range u.Tokens { user.Tokens = append(user.Tokens, tokenName) @@ -179,7 +161,7 @@ func createUserResponse(u *cstypes.User) *UserResponse { sort.Strings(user.Tokens) for _, la := range u.LinkedAccounts { - user.LinkedAccounts = append(user.LinkedAccounts, &LinkedAccountResponse{ + user.LinkedAccounts = append(user.LinkedAccounts, &gwapitypes.LinkedAccountResponse{ ID: la.ID, RemoteSourceID: la.RemoteSourceID, RemoteUserName: la.RemoteUserName, @@ -239,7 +221,7 @@ func (h *UsersHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } - users := make([]*UserResponse, len(csusers)) + users := make([]*gwapitypes.UserResponse, len(csusers)) for i, p := range csusers { users[i] = createUserResponse(p) } @@ -249,17 +231,6 @@ func (h *UsersHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } } -type CreateUserLARequest struct { - RemoteSourceName string `json:"remote_source_name"` - RemoteSourceLoginName string `json:"remote_source_login_name"` - RemoteSourceLoginPassword string `json:"remote_source_login_password"` -} - -type CreateUserLAResponse struct { - LinkedAccount *cstypes.LinkedAccount `json:"linked_account"` - Oauth2Redirect string `json:"oauth2_redirect"` -} - type CreateUserLAHandler struct { log *zap.SugaredLogger ah *action.ActionHandler @@ -274,7 +245,7 @@ func (h *CreateUserLAHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) vars := mux.Vars(r) userRef := vars["userref"] - var req *CreateUserLARequest + var req *gwapitypes.CreateUserLARequest d := json.NewDecoder(r.Body) if err := d.Decode(&req); err != nil { httpError(w, util.NewErrBadRequest(err)) @@ -292,7 +263,7 @@ func (h *CreateUserLAHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) } } -func (h *CreateUserLAHandler) createUserLA(ctx context.Context, userRef string, req *CreateUserLARequest) (*CreateUserLAResponse, error) { +func (h *CreateUserLAHandler) createUserLA(ctx context.Context, userRef string, req *gwapitypes.CreateUserLARequest) (*gwapitypes.CreateUserLAResponse, error) { creq := &action.CreateUserLARequest{ UserRef: userRef, RemoteSourceName: req.RemoteSourceName, @@ -304,14 +275,20 @@ func (h *CreateUserLAHandler) createUserLA(ctx context.Context, userRef string, return nil, err } if cresp.Oauth2Redirect != "" { - return &CreateUserLAResponse{ + return &gwapitypes.CreateUserLAResponse{ Oauth2Redirect: cresp.Oauth2Redirect, }, nil } authresp := cresp.Response.(*action.CreateUserLAResponse) - resp := &CreateUserLAResponse{ - LinkedAccount: authresp.LinkedAccount, + resp := &gwapitypes.CreateUserLAResponse{ + LinkedAccount: &gwapitypes.LinkedAccount{ + ID: authresp.LinkedAccount.ID, + RemoteUserID: authresp.LinkedAccount.RemoteUserID, + RemoteUserName: authresp.LinkedAccount.RemoteUserName, + RemoteUserAvatarURL: authresp.LinkedAccount.RemoteUserAvatarURL, + RemoteSourceID: authresp.LinkedAccount.RemoteUserID, + }, } h.log.Infof("linked account %q for user %q created", resp.LinkedAccount.ID, userRef) return resp, nil @@ -343,14 +320,6 @@ func (h *DeleteUserLAHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) } } -type CreateUserTokenRequest struct { - TokenName string `json:"token_name"` -} - -type CreateUserTokenResponse struct { - Token string `json:"token"` -} - type CreateUserTokenHandler struct { log *zap.SugaredLogger ah *action.ActionHandler @@ -365,7 +334,7 @@ func (h *CreateUserTokenHandler) ServeHTTP(w http.ResponseWriter, r *http.Reques vars := mux.Vars(r) userRef := vars["userref"] - var req CreateUserTokenRequest + var req gwapitypes.CreateUserTokenRequest d := json.NewDecoder(r.Body) if err := d.Decode(&req); err != nil { httpError(w, util.NewErrBadRequest(err)) @@ -383,7 +352,7 @@ func (h *CreateUserTokenHandler) ServeHTTP(w http.ResponseWriter, r *http.Reques return } - res := &CreateUserTokenResponse{ + res := &gwapitypes.CreateUserTokenResponse{ Token: token, } @@ -419,20 +388,11 @@ func (h *DeleteUserTokenHandler) ServeHTTP(w http.ResponseWriter, r *http.Reques } } -type RegisterUserRequest struct { - CreateUserRequest - CreateUserLARequest -} - type RegisterUserHandler struct { log *zap.SugaredLogger ah *action.ActionHandler } -type RegisterUserResponse struct { - Oauth2Redirect string `json:"oauth2_redirect"` -} - func NewRegisterUserHandler(logger *zap.Logger, ah *action.ActionHandler) *RegisterUserHandler { return &RegisterUserHandler{log: logger.Sugar(), ah: ah} } @@ -440,7 +400,7 @@ func NewRegisterUserHandler(logger *zap.Logger, ah *action.ActionHandler) *Regis func (h *RegisterUserHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { ctx := r.Context() - var req *RegisterUserRequest + var req *gwapitypes.RegisterUserRequest d := json.NewDecoder(r.Body) if err := d.Decode(&req); err != nil { httpError(w, util.NewErrBadRequest(err)) @@ -458,7 +418,7 @@ func (h *RegisterUserHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) } } -func (h *RegisterUserHandler) registerUser(ctx context.Context, req *RegisterUserRequest) (*RegisterUserResponse, error) { +func (h *RegisterUserHandler) registerUser(ctx context.Context, req *gwapitypes.RegisterUserRequest) (*gwapitypes.RegisterUserResponse, error) { creq := &action.RegisterUserRequest{ UserName: req.CreateUserRequest.UserName, RemoteSourceName: req.CreateUserLARequest.RemoteSourceName, @@ -469,13 +429,13 @@ func (h *RegisterUserHandler) registerUser(ctx context.Context, req *RegisterUse return nil, err } if cresp.Oauth2Redirect != "" { - return &RegisterUserResponse{ + return &gwapitypes.RegisterUserResponse{ Oauth2Redirect: cresp.Oauth2Redirect, }, nil } //authresp := cresp.Response.(*action.RegisterUserResponse) - resp := &RegisterUserResponse{} + resp := &gwapitypes.RegisterUserResponse{} return resp, nil } @@ -484,12 +444,6 @@ type AuthorizeHandler struct { ah *action.ActionHandler } -type AuthorizeResponse struct { - Oauth2Redirect string `json:"oauth2_redirect"` - RemoteUserInfo *gitsource.UserInfo `json:"remote_user_info"` - RemoteSourceName string `json:"remote_source_name"` -} - func NewAuthorizeHandler(logger *zap.Logger, ah *action.ActionHandler) *AuthorizeHandler { return &AuthorizeHandler{log: logger.Sugar(), ah: ah} } @@ -497,7 +451,7 @@ func NewAuthorizeHandler(logger *zap.Logger, ah *action.ActionHandler) *Authoriz func (h *AuthorizeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { ctx := r.Context() - var req *LoginUserRequest + var req *gwapitypes.LoginUserRequest d := json.NewDecoder(r.Body) if err := d.Decode(&req); err != nil { httpError(w, util.NewErrBadRequest(err)) @@ -515,7 +469,7 @@ func (h *AuthorizeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } } -func (h *AuthorizeHandler) authorize(ctx context.Context, req *LoginUserRequest) (*AuthorizeResponse, error) { +func (h *AuthorizeHandler) authorize(ctx context.Context, req *gwapitypes.LoginUserRequest) (*gwapitypes.AuthorizeResponse, error) { creq := &action.LoginUserRequest{ RemoteSourceName: req.RemoteSourceName, } @@ -525,31 +479,23 @@ func (h *AuthorizeHandler) authorize(ctx context.Context, req *LoginUserRequest) return nil, err } if cresp.Oauth2Redirect != "" { - return &AuthorizeResponse{ + return &gwapitypes.AuthorizeResponse{ Oauth2Redirect: cresp.Oauth2Redirect, }, nil } authresp := cresp.Response.(*action.AuthorizeResponse) - resp := &AuthorizeResponse{ - RemoteUserInfo: authresp.RemoteUserInfo, + resp := &gwapitypes.AuthorizeResponse{ + RemoteUserInfo: &gwapitypes.UserInfo{ + ID: authresp.RemoteUserInfo.ID, + LoginName: authresp.RemoteUserInfo.LoginName, + Email: authresp.RemoteUserInfo.Email, + }, RemoteSourceName: authresp.RemoteSourceName, } return resp, nil } -type LoginUserRequest struct { - RemoteSourceName string `json:"remote_source_name"` - LoginName string `json:"login_name"` - LoginPassword string `json:"password"` -} - -type LoginUserResponse struct { - Oauth2Redirect string `json:"oauth2_redirect"` - Token string `json:"token"` - User *UserResponse `json:"user"` -} - type LoginUserHandler struct { log *zap.SugaredLogger ah *action.ActionHandler @@ -562,7 +508,7 @@ func NewLoginUserHandler(logger *zap.Logger, ah *action.ActionHandler) *LoginUse func (h *LoginUserHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { ctx := r.Context() - var req *LoginUserRequest + var req *gwapitypes.LoginUserRequest d := json.NewDecoder(r.Body) if err := d.Decode(&req); err != nil { httpError(w, util.NewErrBadRequest(err)) @@ -580,7 +526,7 @@ func (h *LoginUserHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } } -func (h *LoginUserHandler) loginUser(ctx context.Context, req *LoginUserRequest) (*LoginUserResponse, error) { +func (h *LoginUserHandler) loginUser(ctx context.Context, req *gwapitypes.LoginUserRequest) (*gwapitypes.LoginUserResponse, error) { creq := &action.LoginUserRequest{ RemoteSourceName: req.RemoteSourceName, } @@ -591,27 +537,19 @@ func (h *LoginUserHandler) loginUser(ctx context.Context, req *LoginUserRequest) return nil, err } if cresp.Oauth2Redirect != "" { - return &LoginUserResponse{ + return &gwapitypes.LoginUserResponse{ Oauth2Redirect: cresp.Oauth2Redirect, }, nil } authresp := cresp.Response.(*action.LoginUserResponse) - resp := &LoginUserResponse{ + resp := &gwapitypes.LoginUserResponse{ Token: authresp.Token, User: createUserResponse(authresp.User), } return resp, nil } -type UserCreateRunRequest struct { - RepoUUID string `json:"repo_uuid,omitempty"` - RepoPath string `json:"repo_path,omitempty"` - Branch string `json:"branch,omitempty"` - CommitSHA string `json:"commit_sha,omitempty"` - Message string `json:"message,omitempty"` -} - type UserCreateRunHandler struct { log *zap.SugaredLogger ah *action.ActionHandler @@ -624,7 +562,7 @@ func NewUserCreateRunHandler(logger *zap.Logger, ah *action.ActionHandler) *User func (h *UserCreateRunHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { ctx := r.Context() - var req UserCreateRunRequest + var req gwapitypes.UserCreateRunRequest d := json.NewDecoder(r.Body) if err := d.Decode(&req); err != nil { httpError(w, util.NewErrBadRequest(err)) diff --git a/internal/services/gateway/api/variable.go b/internal/services/gateway/api/variable.go index fad56c8..cb82490 100644 --- a/internal/services/gateway/api/variable.go +++ b/internal/services/gateway/api/variable.go @@ -19,43 +19,29 @@ import ( "net/http" "agola.io/agola/internal/services/common" - csapi "agola.io/agola/internal/services/configstore/api" - cstypes "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/services/gateway/action" "agola.io/agola/internal/util" - "go.uber.org/zap" + csapitypes "agola.io/agola/services/configstore/api/types" + cstypes "agola.io/agola/services/configstore/types" + gwapitypes "agola.io/agola/services/gateway/api/types" "github.com/gorilla/mux" + "go.uber.org/zap" ) -type VariableValue struct { - SecretName string `json:"secret_name"` - SecretVar string `json:"secret_var"` - MatchingSecretParentPath string `json:"matching_secret_parent_path"` - - When *cstypes.When `json:"when"` -} - -type VariableResponse struct { - ID string `json:"id"` - Name string `json:"name"` - Values []VariableValue `json:"values"` - ParentPath string `json:"parent_path"` -} - -func createVariableResponse(v *csapi.Variable, secrets []*csapi.Secret) *VariableResponse { - nv := &VariableResponse{ +func createVariableResponse(v *csapitypes.Variable, secrets []*csapitypes.Secret) *gwapitypes.VariableResponse { + nv := &gwapitypes.VariableResponse{ ID: v.ID, Name: v.Name, - Values: make([]VariableValue, len(v.Values)), + Values: make([]gwapitypes.VariableValue, len(v.Values)), ParentPath: v.ParentPath, } for i, varvalue := range v.Values { - nv.Values[i] = VariableValue{ + nv.Values[i] = gwapitypes.VariableValue{ SecretName: varvalue.SecretName, SecretVar: varvalue.SecretVar, - When: varvalue.When, + When: fromCsWhen(varvalue.When), } // get matching secret for var value secret := common.GetVarValueMatchingSecret(varvalue, v.ParentPath, secrets) @@ -100,7 +86,7 @@ func (h *VariableHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } - variables := make([]*VariableResponse, len(csvars)) + variables := make([]*gwapitypes.VariableResponse, len(csvars)) for i, v := range csvars { variables[i] = createVariableResponse(v, cssecrets) } @@ -110,12 +96,6 @@ func (h *VariableHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } } -type CreateVariableRequest struct { - Name string `json:"name,omitempty"` - - Values []cstypes.VariableValue `json:"values,omitempty"` -} - type CreateVariableHandler struct { log *zap.SugaredLogger ah *action.ActionHandler @@ -133,7 +113,7 @@ func (h *CreateVariableHandler) ServeHTTP(w http.ResponseWriter, r *http.Request return } - var req CreateVariableRequest + var req gwapitypes.CreateVariableRequest d := json.NewDecoder(r.Body) if err := d.Decode(&req); err != nil { httpError(w, util.NewErrBadRequest(err)) @@ -143,7 +123,7 @@ func (h *CreateVariableHandler) ServeHTTP(w http.ResponseWriter, r *http.Request Name: req.Name, ParentType: parentType, ParentRef: parentRef, - Values: req.Values, + Values: fromApiVariableValues(req.Values), } csvar, cssecrets, err := h.ah.CreateVariable(ctx, areq) if httpError(w, err) { @@ -157,12 +137,6 @@ func (h *CreateVariableHandler) ServeHTTP(w http.ResponseWriter, r *http.Request } } -type UpdateVariableRequest struct { - Name string `json:"name,omitempty"` - - Values []cstypes.VariableValue `json:"values,omitempty"` -} - type UpdateVariableHandler struct { log *zap.SugaredLogger ah *action.ActionHandler @@ -183,19 +157,20 @@ func (h *UpdateVariableHandler) ServeHTTP(w http.ResponseWriter, r *http.Request return } - var req UpdateVariableRequest + var req gwapitypes.UpdateVariableRequest d := json.NewDecoder(r.Body) if err := d.Decode(&req); err != nil { httpError(w, util.NewErrBadRequest(err)) return } + areq := &action.UpdateVariableRequest{ VariableName: variableName, Name: req.Name, ParentType: parentType, ParentRef: parentRef, - Values: req.Values, + Values: fromApiVariableValues(req.Values), } csvar, cssecrets, err := h.ah.UpdateVariable(ctx, areq) if httpError(w, err) { @@ -239,3 +214,75 @@ func (h *DeleteVariableHandler) ServeHTTP(w http.ResponseWriter, r *http.Request h.log.Errorf("err: %+v", err) } } + +func fromApiVariableValues(apivalues []gwapitypes.VariableValueRequest) []cstypes.VariableValue { + values := make([]cstypes.VariableValue, len(apivalues)) + for i, v := range apivalues { + values[i] = cstypes.VariableValue{ + SecretName: v.SecretName, + SecretVar: v.SecretVar, + When: fromApiWhen(v.When), + } + } + return values +} + +func fromApiWhenCondition(apiwc gwapitypes.WhenCondition) cstypes.WhenCondition { + return cstypes.WhenCondition{ + Type: cstypes.WhenConditionType(apiwc.Type), + Match: apiwc.Match, + } +} + +func fromApiWhenConditions(apiwcs *gwapitypes.WhenConditions) *cstypes.WhenConditions { + wcs := &cstypes.WhenConditions{ + Include: make([]cstypes.WhenCondition, len(apiwcs.Include)), + Exclude: make([]cstypes.WhenCondition, len(apiwcs.Exclude)), + } + for i, include := range apiwcs.Include { + wcs.Include[i] = fromApiWhenCondition(include) + } + for i, exclude := range apiwcs.Exclude { + wcs.Exclude[i] = fromApiWhenCondition(exclude) + } + + return wcs +} + +func fromApiWhen(apiwhen *gwapitypes.When) *cstypes.When { + return &cstypes.When{ + Branch: fromApiWhenConditions(apiwhen.Branch), + Tag: fromApiWhenConditions(apiwhen.Tag), + Ref: fromApiWhenConditions(apiwhen.Ref), + } +} + +func fromCsWhenCondition(apiwc cstypes.WhenCondition) gwapitypes.WhenCondition { + return gwapitypes.WhenCondition{ + Type: gwapitypes.WhenConditionType(apiwc.Type), + Match: apiwc.Match, + } +} + +func fromCsWhenConditions(apiwcs *cstypes.WhenConditions) *gwapitypes.WhenConditions { + wcs := &gwapitypes.WhenConditions{ + Include: make([]gwapitypes.WhenCondition, len(apiwcs.Include)), + Exclude: make([]gwapitypes.WhenCondition, len(apiwcs.Exclude)), + } + for i, include := range apiwcs.Include { + wcs.Include[i] = fromCsWhenCondition(include) + } + for i, exclude := range apiwcs.Exclude { + wcs.Exclude[i] = fromCsWhenCondition(exclude) + } + + return wcs +} + +func fromCsWhen(apiwhen *cstypes.When) *gwapitypes.When { + return &gwapitypes.When{ + Branch: fromCsWhenConditions(apiwhen.Branch), + Tag: fromCsWhenConditions(apiwhen.Tag), + Ref: fromCsWhenConditions(apiwhen.Ref), + } +} diff --git a/internal/services/gateway/api/webhook.go b/internal/services/gateway/api/webhook.go index a95c349..05a5bb9 100644 --- a/internal/services/gateway/api/webhook.go +++ b/internal/services/gateway/api/webhook.go @@ -18,11 +18,11 @@ import ( "net/http" "agola.io/agola/internal/services/common" - csapi "agola.io/agola/internal/services/configstore/api" "agola.io/agola/internal/services/gateway/action" - rsapi "agola.io/agola/internal/services/runservice/api" "agola.io/agola/internal/services/types" "agola.io/agola/internal/util" + csclient "agola.io/agola/services/configstore/client" + rsclient "agola.io/agola/services/runservice/client" "go.uber.org/zap" errors "golang.org/x/xerrors" @@ -31,12 +31,12 @@ import ( type webhooksHandler struct { log *zap.SugaredLogger ah *action.ActionHandler - configstoreClient *csapi.Client - runserviceClient *rsapi.Client + configstoreClient *csclient.Client + runserviceClient *rsclient.Client apiExposedURL string } -func NewWebhooksHandler(logger *zap.Logger, ah *action.ActionHandler, configstoreClient *csapi.Client, runserviceClient *rsapi.Client, apiExposedURL string) *webhooksHandler { +func NewWebhooksHandler(logger *zap.Logger, ah *action.ActionHandler, configstoreClient *csclient.Client, runserviceClient *rsclient.Client, apiExposedURL string) *webhooksHandler { return &webhooksHandler{ log: logger.Sugar(), ah: ah, diff --git a/internal/services/gateway/gateway.go b/internal/services/gateway/gateway.go index ddee92a..48a4252 100644 --- a/internal/services/gateway/gateway.go +++ b/internal/services/gateway/gateway.go @@ -25,12 +25,12 @@ import ( "agola.io/agola/internal/objectstorage" "agola.io/agola/internal/services/common" "agola.io/agola/internal/services/config" - csapi "agola.io/agola/internal/services/configstore/api" "agola.io/agola/internal/services/gateway/action" "agola.io/agola/internal/services/gateway/api" "agola.io/agola/internal/services/gateway/handlers" - rsapi "agola.io/agola/internal/services/runservice/api" "agola.io/agola/internal/util" + csclient "agola.io/agola/services/configstore/client" + rsclient "agola.io/agola/services/runservice/client" jwt "github.com/dgrijalva/jwt-go" ghandlers "github.com/gorilla/handlers" @@ -52,8 +52,8 @@ type Gateway struct { c *config.Gateway ost *objectstorage.ObjStorage - runserviceClient *rsapi.Client - configstoreClient *csapi.Client + runserviceClient *rsclient.Client + configstoreClient *csclient.Client ah *action.ActionHandler sd *common.TokenSigningData } @@ -121,8 +121,8 @@ func NewGateway(gc *config.Config) (*Gateway, error) { return nil, err } - configstoreClient := csapi.NewClient(c.ConfigstoreURL) - runserviceClient := rsapi.NewClient(c.RunserviceURL) + configstoreClient := csclient.NewClient(c.ConfigstoreURL) + runserviceClient := rsclient.NewClient(c.RunserviceURL) ah := action.NewActionHandler(logger, sd, configstoreClient, runserviceClient, gc.ID, c.APIExposedURL, c.WebExposedURL) diff --git a/internal/services/gateway/handlers/auth.go b/internal/services/gateway/handlers/auth.go index 6097288..072f566 100644 --- a/internal/services/gateway/handlers/auth.go +++ b/internal/services/gateway/handlers/auth.go @@ -20,7 +20,7 @@ import ( "strings" "agola.io/agola/internal/services/common" - csapi "agola.io/agola/internal/services/configstore/api" + csclient "agola.io/agola/services/configstore/client" jwt "github.com/dgrijalva/jwt-go" jwtrequest "github.com/dgrijalva/jwt-go/request" @@ -32,7 +32,7 @@ type AuthHandler struct { log *zap.SugaredLogger next http.Handler - configstoreClient *csapi.Client + configstoreClient *csclient.Client adminToken string sd *common.TokenSigningData @@ -40,7 +40,7 @@ type AuthHandler struct { required bool } -func NewAuthHandler(logger *zap.Logger, configstoreClient *csapi.Client, adminToken string, sd *common.TokenSigningData, required bool) func(http.Handler) http.Handler { +func NewAuthHandler(logger *zap.Logger, configstoreClient *csclient.Client, adminToken string, sd *common.TokenSigningData, required bool) func(http.Handler) http.Handler { return func(h http.Handler) http.Handler { return &AuthHandler{ log: logger.Sugar(), diff --git a/internal/services/notification/commitstatus.go b/internal/services/notification/commitstatus.go index dc53a5e..b8a5e55 100644 --- a/internal/services/notification/commitstatus.go +++ b/internal/services/notification/commitstatus.go @@ -22,7 +22,7 @@ import ( gitsource "agola.io/agola/internal/gitsources" "agola.io/agola/internal/services/common" "agola.io/agola/internal/services/gateway/action" - rstypes "agola.io/agola/internal/services/runservice/types" + rstypes "agola.io/agola/services/runservice/types" errors "golang.org/x/xerrors" ) diff --git a/internal/services/notification/notification.go b/internal/services/notification/notification.go index 96697c9..d3000f2 100644 --- a/internal/services/notification/notification.go +++ b/internal/services/notification/notification.go @@ -21,8 +21,8 @@ import ( "agola.io/agola/internal/etcd" slog "agola.io/agola/internal/log" "agola.io/agola/internal/services/config" - csapi "agola.io/agola/internal/services/configstore/api" - rsapi "agola.io/agola/internal/services/runservice/api" + csclient "agola.io/agola/services/configstore/client" + rsclient "agola.io/agola/services/runservice/client" "go.uber.org/zap" "go.uber.org/zap/zapcore" @@ -38,8 +38,8 @@ type NotificationService struct { e *etcd.Store - runserviceClient *rsapi.Client - configstoreClient *csapi.Client + runserviceClient *rsclient.Client + configstoreClient *csclient.Client } func NewNotificationService(gc *config.Config) (*NotificationService, error) { @@ -53,8 +53,8 @@ func NewNotificationService(gc *config.Config) (*NotificationService, error) { return nil, err } - configstoreClient := csapi.NewClient(c.ConfigstoreURL) - runserviceClient := rsapi.NewClient(c.RunserviceURL) + configstoreClient := csclient.NewClient(c.ConfigstoreURL) + runserviceClient := rsclient.NewClient(c.RunserviceURL) return &NotificationService{ gc: gc, diff --git a/internal/services/notification/runevents.go b/internal/services/notification/runevents.go index acfeb90..1d18f13 100644 --- a/internal/services/notification/runevents.go +++ b/internal/services/notification/runevents.go @@ -24,7 +24,7 @@ import ( "path" "time" - rstypes "agola.io/agola/internal/services/runservice/types" + rstypes "agola.io/agola/services/runservice/types" "go.etcd.io/etcd/clientv3/concurrency" errors "golang.org/x/xerrors" diff --git a/internal/services/runservice/action/action.go b/internal/services/runservice/action/action.go index 1f6d2ca..cd4da6c 100644 --- a/internal/services/runservice/action/action.go +++ b/internal/services/runservice/action/action.go @@ -29,8 +29,8 @@ import ( "agola.io/agola/internal/services/runservice/common" "agola.io/agola/internal/services/runservice/readdb" "agola.io/agola/internal/services/runservice/store" - "agola.io/agola/internal/services/runservice/types" "agola.io/agola/internal/util" + "agola.io/agola/services/runservice/types" "go.uber.org/zap" errors "golang.org/x/xerrors" diff --git a/internal/services/runservice/action/action_test.go b/internal/services/runservice/action/action_test.go index 08c084a..f520850 100644 --- a/internal/services/runservice/action/action_test.go +++ b/internal/services/runservice/action/action_test.go @@ -17,8 +17,8 @@ package action import ( "testing" - "agola.io/agola/internal/services/runservice/types" "agola.io/agola/internal/util" + "agola.io/agola/services/runservice/types" "github.com/google/go-cmp/cmp" ) diff --git a/internal/services/runservice/api/api.go b/internal/services/runservice/api/api.go index beffd66..5accebe 100644 --- a/internal/services/runservice/api/api.go +++ b/internal/services/runservice/api/api.go @@ -31,8 +31,9 @@ import ( "agola.io/agola/internal/services/runservice/common" "agola.io/agola/internal/services/runservice/readdb" "agola.io/agola/internal/services/runservice/store" - "agola.io/agola/internal/services/runservice/types" "agola.io/agola/internal/util" + rsapitypes "agola.io/agola/services/runservice/api/types" + "agola.io/agola/services/runservice/types" "github.com/gorilla/mux" etcdclientv3 "go.etcd.io/etcd/clientv3" @@ -350,12 +351,6 @@ func (h *ChangeGroupsUpdateTokensHandler) ServeHTTP(w http.ResponseWriter, r *ht } } -type RunResponse struct { - Run *types.Run `json:"run"` - RunConfig *types.RunConfig `json:"run_config"` - ChangeGroupsUpdateToken string `json:"change_groups_update_tokens"` -} - type RunHandler struct { log *zap.SugaredLogger e *etcd.Store @@ -415,7 +410,7 @@ func (h *RunHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } - res := &RunResponse{ + res := &rsapitypes.RunResponse{ Run: run, RunConfig: rc, ChangeGroupsUpdateToken: cgts, @@ -431,11 +426,6 @@ const ( MaxRunsLimit = 40 ) -type GetRunsResponse struct { - Runs []*types.Run `json:"runs"` - ChangeGroupsUpdateToken string `json:"change_groups_update_tokens"` -} - type RunsHandler struct { log *zap.SugaredLogger readDB *readdb.ReadDB @@ -507,7 +497,7 @@ func (h *RunsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } - res := &GetRunsResponse{ + res := &rsapitypes.GetRunsResponse{ Runs: runs, ChangeGroupsUpdateToken: cgts, } @@ -516,27 +506,6 @@ func (h *RunsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } } -type RunCreateRequest struct { - // new run fields - RunConfigTasks map[string]*types.RunConfigTask `json:"run_config_tasks"` - Name string `json:"name"` - Group string `json:"group"` - SetupErrors []string `json:"setup_errors"` - StaticEnvironment map[string]string `json:"static_environment"` - CacheGroup string `json:"cache_group"` - - // existing run fields - RunID string `json:"run_id"` - FromStart bool `json:"from_start"` - ResetTasks []string `json:"reset_tasks"` - - // common fields - Environment map[string]string `json:"environment"` - Annotations map[string]string `json:"annotations"` - - ChangeGroupsUpdateToken string `json:"changeup_update_tokens"` -} - type RunCreateHandler struct { log *zap.SugaredLogger ah *action.ActionHandler @@ -552,7 +521,7 @@ func NewRunCreateHandler(logger *zap.Logger, ah *action.ActionHandler) *RunCreat func (h *RunCreateHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { ctx := r.Context() - var req RunCreateRequest + var req rsapitypes.RunCreateRequest d := json.NewDecoder(r.Body) if err := d.Decode(&req); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) @@ -582,7 +551,7 @@ func (h *RunCreateHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } - res := &RunResponse{ + res := &rsapitypes.RunResponse{ Run: rb.Run, RunConfig: rb.Rc, } @@ -592,20 +561,6 @@ func (h *RunCreateHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } } -type RunActionType string - -const ( - RunActionTypeChangePhase RunActionType = "changephase" - RunActionTypeStop RunActionType = "stop" -) - -type RunActionsRequest struct { - ActionType RunActionType `json:"action_type"` - - Phase types.RunPhase `json:"phase"` - ChangeGroupsUpdateToken string `json:"change_groups_update_tokens"` -} - type RunActionsHandler struct { log *zap.SugaredLogger ah *action.ActionHandler @@ -623,7 +578,7 @@ func (h *RunActionsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) runID := vars["runid"] - var req RunActionsRequest + var req rsapitypes.RunActionsRequest d := json.NewDecoder(r.Body) if err := d.Decode(&req); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) @@ -631,7 +586,7 @@ func (h *RunActionsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } switch req.ActionType { - case RunActionTypeChangePhase: + case rsapitypes.RunActionTypeChangePhase: creq := &action.RunChangePhaseRequest{ RunID: runID, Phase: req.Phase, @@ -642,7 +597,7 @@ func (h *RunActionsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { httpError(w, err) return } - case RunActionTypeStop: + case rsapitypes.RunActionTypeStop: creq := &action.RunStopRequest{ RunID: runID, ChangeGroupsUpdateToken: req.ChangeGroupsUpdateToken, @@ -658,23 +613,6 @@ func (h *RunActionsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } } -type RunTaskActionType string - -const ( - RunTaskActionTypeSetAnnotations RunTaskActionType = "setannotations" - RunTaskActionTypeApprove RunTaskActionType = "approve" -) - -type RunTaskActionsRequest struct { - ActionType RunTaskActionType `json:"action_type"` - - // set Annotations fields - Annotations map[string]string `json:"annotations,omitempty"` - - // global fields - ChangeGroupsUpdateToken string `json:"change_groups_update_tokens"` -} - type RunTaskActionsHandler struct { log *zap.SugaredLogger ah *action.ActionHandler @@ -693,7 +631,7 @@ func (h *RunTaskActionsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request runID := vars["runid"] taskID := vars["taskid"] - var req RunTaskActionsRequest + var req rsapitypes.RunTaskActionsRequest d := json.NewDecoder(r.Body) if err := d.Decode(&req); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) @@ -701,7 +639,7 @@ func (h *RunTaskActionsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request } switch req.ActionType { - case RunTaskActionTypeSetAnnotations: + case rsapitypes.RunTaskActionTypeSetAnnotations: creq := &action.RunTaskSetAnnotationsRequest{ RunID: runID, TaskID: taskID, @@ -714,7 +652,7 @@ func (h *RunTaskActionsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request return } - case RunTaskActionTypeApprove: + case rsapitypes.RunTaskActionTypeApprove: creq := &action.RunTaskApproveRequest{ RunID: runID, TaskID: taskID, diff --git a/internal/services/runservice/api/executor.go b/internal/services/runservice/api/executor.go index 70a7b05..5993d38 100644 --- a/internal/services/runservice/api/executor.go +++ b/internal/services/runservice/api/executor.go @@ -29,7 +29,7 @@ import ( "agola.io/agola/internal/services/runservice/action" "agola.io/agola/internal/services/runservice/common" "agola.io/agola/internal/services/runservice/store" - "agola.io/agola/internal/services/runservice/types" + "agola.io/agola/services/runservice/types" "github.com/gorilla/mux" "go.uber.org/zap" diff --git a/internal/services/runservice/common/events.go b/internal/services/runservice/common/events.go index bef804a..50a4fdf 100644 --- a/internal/services/runservice/common/events.go +++ b/internal/services/runservice/common/events.go @@ -19,7 +19,7 @@ import ( "agola.io/agola/internal/etcd" "agola.io/agola/internal/sequence" - "agola.io/agola/internal/services/runservice/types" + "agola.io/agola/services/runservice/types" ) func NewRunEvent(ctx context.Context, e *etcd.Store, runID string, phase types.RunPhase, result types.RunResult) (*types.RunEvent, error) { diff --git a/internal/services/runservice/readdb/readdb.go b/internal/services/runservice/readdb/readdb.go index 066dc39..890b715 100644 --- a/internal/services/runservice/readdb/readdb.go +++ b/internal/services/runservice/readdb/readdb.go @@ -36,8 +36,8 @@ import ( "agola.io/agola/internal/sequence" "agola.io/agola/internal/services/runservice/common" "agola.io/agola/internal/services/runservice/store" - "agola.io/agola/internal/services/runservice/types" "agola.io/agola/internal/util" + "agola.io/agola/services/runservice/types" sq "github.com/Masterminds/squirrel" etcdclientv3 "go.etcd.io/etcd/clientv3" diff --git a/internal/services/runservice/runservice.go b/internal/services/runservice/runservice.go index 58ad414..a10d976 100644 --- a/internal/services/runservice/runservice.go +++ b/internal/services/runservice/runservice.go @@ -31,8 +31,8 @@ import ( "agola.io/agola/internal/services/runservice/api" "agola.io/agola/internal/services/runservice/common" "agola.io/agola/internal/services/runservice/readdb" - "agola.io/agola/internal/services/runservice/types" "agola.io/agola/internal/util" + "agola.io/agola/services/runservice/types" "github.com/gorilla/mux" etcdclientv3 "go.etcd.io/etcd/clientv3" diff --git a/internal/services/runservice/scheduler.go b/internal/services/runservice/scheduler.go index ea265a5..51c149c 100644 --- a/internal/services/runservice/scheduler.go +++ b/internal/services/runservice/scheduler.go @@ -31,8 +31,8 @@ import ( "agola.io/agola/internal/runconfig" "agola.io/agola/internal/services/runservice/common" "agola.io/agola/internal/services/runservice/store" - "agola.io/agola/internal/services/runservice/types" "agola.io/agola/internal/util" + "agola.io/agola/services/runservice/types" etcdclientv3 "go.etcd.io/etcd/clientv3" "go.etcd.io/etcd/clientv3/concurrency" diff --git a/internal/services/runservice/scheduler_test.go b/internal/services/runservice/scheduler_test.go index 620e630..e3ea1a8 100644 --- a/internal/services/runservice/scheduler_test.go +++ b/internal/services/runservice/scheduler_test.go @@ -20,8 +20,8 @@ import ( "testing" "time" - "agola.io/agola/internal/common" - "agola.io/agola/internal/services/runservice/types" + "agola.io/agola/services/runservice/types" + ctypes "agola.io/agola/services/types" "github.com/google/go-cmp/cmp" ) @@ -543,7 +543,7 @@ func TestGetTasksToRun(t *testing.T) { func TestChooseExecutor(t *testing.T) { executorOK := &types.Executor{ ID: "executorOK", - Archs: []common.Arch{common.ArchAMD64}, + Archs: []ctypes.Arch{ctypes.ArchAMD64}, ActiveTasksLimit: 2, ActiveTasks: 0, LastStatusUpdateTime: time.Now(), @@ -566,7 +566,7 @@ func TestChooseExecutor(t *testing.T) { executorOKMultipleArchs := func() *types.Executor { e := executorOK.DeepCopy() e.ID = "executorOKMultipleArchs" - e.Archs = []common.Arch{common.ArchAMD64, common.ArchARM64} + e.Archs = []ctypes.Arch{ctypes.ArchAMD64, ctypes.ArchARM64} return e }() @@ -582,7 +582,7 @@ func TestChooseExecutor(t *testing.T) { ID: "task01", Name: "task01", Runtime: &types.Runtime{Type: types.RuntimeType("pod"), - Arch: common.ArchAMD64, + Arch: ctypes.ArchAMD64, }, } @@ -590,7 +590,7 @@ func TestChooseExecutor(t *testing.T) { ID: "task01", Name: "task01", Runtime: &types.Runtime{Type: types.RuntimeType("pod"), - Arch: common.ArchAMD64, + Arch: ctypes.ArchAMD64, Containers: []*types.Container{ { Privileged: true, @@ -629,7 +629,7 @@ func TestChooseExecutor(t *testing.T) { name: "test single executor with different arch", executors: func() []*types.Executor { e := executorOK.DeepCopy() - e.Archs = []common.Arch{common.ArchARM64} + e.Archs = []ctypes.Arch{ctypes.ArchARM64} return []*types.Executor{e} }(), rct: rct, diff --git a/internal/services/runservice/store/store.go b/internal/services/runservice/store/store.go index 3591048..81b213c 100644 --- a/internal/services/runservice/store/store.go +++ b/internal/services/runservice/store/store.go @@ -26,8 +26,8 @@ import ( "agola.io/agola/internal/etcd" ostypes "agola.io/agola/internal/objectstorage/types" "agola.io/agola/internal/services/runservice/common" - "agola.io/agola/internal/services/runservice/types" "agola.io/agola/internal/util" + "agola.io/agola/services/runservice/types" etcdclientv3 "go.etcd.io/etcd/clientv3" errors "golang.org/x/xerrors" diff --git a/internal/services/scheduler/scheduler.go b/internal/services/scheduler/scheduler.go index d6edeac..3fcda2c 100644 --- a/internal/services/scheduler/scheduler.go +++ b/internal/services/scheduler/scheduler.go @@ -23,8 +23,9 @@ import ( slog "agola.io/agola/internal/log" "agola.io/agola/internal/services/common" "agola.io/agola/internal/services/config" - rsapi "agola.io/agola/internal/services/runservice/api" "agola.io/agola/internal/util" + rsapitypes "agola.io/agola/services/runservice/api/types" + rsclient "agola.io/agola/services/runservice/client" "go.uber.org/zap" "go.uber.org/zap/zapcore" @@ -178,8 +179,8 @@ func (s *Scheduler) approveRunTasks(ctx context.Context, runID string) error { } // TODO(sgotti) change when we introduce a config the set the minimum number of required approvers if len(approvers) > 0 { - rsreq := &rsapi.RunTaskActionsRequest{ - ActionType: rsapi.RunTaskActionTypeApprove, + rsreq := &rsapitypes.RunTaskActionsRequest{ + ActionType: rsapitypes.RunTaskActionTypeApprove, ChangeGroupsUpdateToken: runResp.ChangeGroupsUpdateToken, } if _, err := s.runserviceClient.RunTaskActions(ctx, run.ID, rt.ID, rsreq); err != nil { @@ -193,7 +194,7 @@ func (s *Scheduler) approveRunTasks(ctx context.Context, runID string) error { type Scheduler struct { c *config.Scheduler - runserviceClient *rsapi.Client + runserviceClient *rsclient.Client } func NewScheduler(c *config.Scheduler) (*Scheduler, error) { @@ -203,7 +204,7 @@ func NewScheduler(c *config.Scheduler) (*Scheduler, error) { return &Scheduler{ c: c, - runserviceClient: rsapi.NewClient(c.RunserviceURL), + runserviceClient: rsclient.NewClient(c.RunserviceURL), }, nil } diff --git a/services/configstore/api/types/org.go b/services/configstore/api/types/org.go new file mode 100644 index 0000000..7a63f5b --- /dev/null +++ b/services/configstore/api/types/org.go @@ -0,0 +1,28 @@ +// Copyright 2019 Sorint.lab +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied +// See the License for the specific language governing permissions and +// limitations under the License. + +package types + +import ( + cstypes "agola.io/agola/services/configstore/types" +) + +type AddOrgMemberRequest struct { + Role cstypes.MemberRole +} + +type OrgMemberResponse struct { + User *cstypes.User + Role cstypes.MemberRole +} diff --git a/services/configstore/api/types/project.go b/services/configstore/api/types/project.go new file mode 100644 index 0000000..53ed5bc --- /dev/null +++ b/services/configstore/api/types/project.go @@ -0,0 +1,31 @@ +// Copyright 2019 Sorint.lab +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied +// See the License for the specific language governing permissions and +// limitations under the License. + +package types + +import ( + cstypes "agola.io/agola/services/configstore/types" +) + +// Project augments cstypes.Project with dynamic data +type Project struct { + *cstypes.Project + + // dynamic data + OwnerType cstypes.ConfigType + OwnerID string + Path string + ParentPath string + GlobalVisibility cstypes.Visibility +} diff --git a/services/configstore/api/types/projectgroup.go b/services/configstore/api/types/projectgroup.go new file mode 100644 index 0000000..c3743a7 --- /dev/null +++ b/services/configstore/api/types/projectgroup.go @@ -0,0 +1,31 @@ +// Copyright 2019 Sorint.lab +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied +// See the License for the specific language governing permissions and +// limitations under the License. + +package types + +import ( + cstypes "agola.io/agola/services/configstore/types" +) + +// ProjectGroup augments cstypes.ProjectGroup with dynamic data +type ProjectGroup struct { + *cstypes.ProjectGroup + + // dynamic data + OwnerType cstypes.ConfigType + OwnerID string + Path string + ParentPath string + GlobalVisibility cstypes.Visibility +} diff --git a/services/configstore/api/types/secret.go b/services/configstore/api/types/secret.go new file mode 100644 index 0000000..7504d86 --- /dev/null +++ b/services/configstore/api/types/secret.go @@ -0,0 +1,27 @@ +// Copyright 2019 Sorint.lab +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied +// See the License for the specific language governing permissions and +// limitations under the License. + +package types + +import ( + cstypes "agola.io/agola/services/configstore/types" +) + +// Secret augments cstypes.Secret with dynamic data +type Secret struct { + *cstypes.Secret + + // dynamic data + ParentPath string +} diff --git a/services/configstore/api/types/user.go b/services/configstore/api/types/user.go new file mode 100644 index 0000000..b8ce66e --- /dev/null +++ b/services/configstore/api/types/user.go @@ -0,0 +1,63 @@ +// Copyright 2019 Sorint.lab +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied +// See the License for the specific language governing permissions and +// limitations under the License. + +package types + +import ( + "time" + + cstypes "agola.io/agola/services/configstore/types" +) + +type CreateUserRequest struct { + UserName string `json:"user_name"` + + CreateUserLARequest *CreateUserLARequest `json:"create_user_la_request"` +} + +type UpdateUserRequest struct { + UserName string `json:"user_name"` +} + +type CreateUserLARequest struct { + RemoteSourceName string `json:"remote_source_name"` + RemoteUserID string `json:"remote_user_id"` + RemoteUserName string `json:"remote_user_name"` + UserAccessToken string `json:"user_access_token"` + Oauth2AccessToken string `json:"oauth2_access_token"` + Oauth2RefreshToken string `json:"oauth2_refresh_token"` + Oauth2AccessTokenExpiresAt time.Time `json:"oauth_2_access_token_expires_at"` +} + +type UpdateUserLARequest struct { + RemoteUserID string `json:"remote_user_id"` + RemoteUserName string `json:"remote_user_name"` + UserAccessToken string `json:"user_access_token"` + Oauth2AccessToken string `json:"oauth2_access_token"` + Oauth2RefreshToken string `json:"oauth2_refresh_token"` + Oauth2AccessTokenExpiresAt time.Time `json:"oauth_2_access_token_expires_at"` +} + +type CreateUserTokenRequest struct { + TokenName string `json:"token_name"` +} + +type CreateUserTokenResponse struct { + Token string `json:"token"` +} + +type UserOrgsResponse struct { + Organization *cstypes.Organization + Role cstypes.MemberRole +} diff --git a/services/configstore/api/types/variable.go b/services/configstore/api/types/variable.go new file mode 100644 index 0000000..a40d2b6 --- /dev/null +++ b/services/configstore/api/types/variable.go @@ -0,0 +1,27 @@ +// Copyright 2019 Sorint.lab +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied +// See the License for the specific language governing permissions and +// limitations under the License. + +package types + +import ( + cstypes "agola.io/agola/services/configstore/types" +) + +// Variable augments cstypes.Variable with dynamic data +type Variable struct { + *cstypes.Variable + + // dynamic data + ParentPath string +} diff --git a/internal/services/configstore/api/client.go b/services/configstore/client/client.go similarity index 78% rename from internal/services/configstore/api/client.go rename to services/configstore/client/client.go index 44eff33..1f62711 100644 --- a/internal/services/configstore/api/client.go +++ b/services/configstore/client/client.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package api +package client import ( "bytes" @@ -26,14 +26,15 @@ import ( "strconv" "strings" - "agola.io/agola/internal/services/configstore/types" + csapitypes "agola.io/agola/services/configstore/api/types" + "agola.io/agola/services/configstore/types" + cstypes "agola.io/agola/services/configstore/types" errors "golang.org/x/xerrors" ) var jsonContent = http.Header{"Content-Type": []string{"application/json"}} -// Client represents a Gogs API client. type Client struct { url string client *http.Client @@ -106,42 +107,42 @@ func (c *Client) getParsedResponse(ctx context.Context, method, path string, que return resp, d.Decode(obj) } -func (c *Client) GetProjectGroup(ctx context.Context, projectGroupRef string) (*ProjectGroup, *http.Response, error) { - projectGroup := new(ProjectGroup) +func (c *Client) GetProjectGroup(ctx context.Context, projectGroupRef string) (*csapitypes.ProjectGroup, *http.Response, error) { + projectGroup := new(csapitypes.ProjectGroup) resp, err := c.getParsedResponse(ctx, "GET", fmt.Sprintf("/projectgroups/%s", url.PathEscape(projectGroupRef)), nil, jsonContent, nil, projectGroup) return projectGroup, resp, err } -func (c *Client) GetProjectGroupSubgroups(ctx context.Context, projectGroupRef string) ([]*ProjectGroup, *http.Response, error) { - projectGroups := []*ProjectGroup{} +func (c *Client) GetProjectGroupSubgroups(ctx context.Context, projectGroupRef string) ([]*csapitypes.ProjectGroup, *http.Response, error) { + projectGroups := []*csapitypes.ProjectGroup{} resp, err := c.getParsedResponse(ctx, "GET", fmt.Sprintf("/projectgroups/%s/subgroups", url.PathEscape(projectGroupRef)), nil, jsonContent, nil, &projectGroups) return projectGroups, resp, err } -func (c *Client) GetProjectGroupProjects(ctx context.Context, projectGroupRef string) ([]*Project, *http.Response, error) { - projects := []*Project{} +func (c *Client) GetProjectGroupProjects(ctx context.Context, projectGroupRef string) ([]*csapitypes.Project, *http.Response, error) { + projects := []*csapitypes.Project{} resp, err := c.getParsedResponse(ctx, "GET", fmt.Sprintf("/projectgroups/%s/projects", url.PathEscape(projectGroupRef)), nil, jsonContent, nil, &projects) return projects, resp, err } -func (c *Client) CreateProjectGroup(ctx context.Context, projectGroup *types.ProjectGroup) (*ProjectGroup, *http.Response, error) { +func (c *Client) CreateProjectGroup(ctx context.Context, projectGroup *cstypes.ProjectGroup) (*csapitypes.ProjectGroup, *http.Response, error) { pj, err := json.Marshal(projectGroup) if err != nil { return nil, nil, err } - resProjectGroup := new(ProjectGroup) + resProjectGroup := new(csapitypes.ProjectGroup) resp, err := c.getParsedResponse(ctx, "POST", "/projectgroups", nil, jsonContent, bytes.NewReader(pj), resProjectGroup) return resProjectGroup, resp, err } -func (c *Client) UpdateProjectGroup(ctx context.Context, projectGroupRef string, projectGroup *types.ProjectGroup) (*ProjectGroup, *http.Response, error) { +func (c *Client) UpdateProjectGroup(ctx context.Context, projectGroupRef string, projectGroup *cstypes.ProjectGroup) (*csapitypes.ProjectGroup, *http.Response, error) { pj, err := json.Marshal(projectGroup) if err != nil { return nil, nil, err } - resProjectGroup := new(ProjectGroup) + resProjectGroup := new(csapitypes.ProjectGroup) resp, err := c.getParsedResponse(ctx, "PUT", fmt.Sprintf("/projectgroups/%s", url.PathEscape(projectGroupRef)), nil, jsonContent, bytes.NewReader(pj), resProjectGroup) return resProjectGroup, resp, err } @@ -150,30 +151,30 @@ func (c *Client) DeleteProjectGroup(ctx context.Context, projectGroupRef string) return c.getResponse(ctx, "DELETE", fmt.Sprintf("/projectgroups/%s", url.PathEscape(projectGroupRef)), nil, jsonContent, nil) } -func (c *Client) GetProject(ctx context.Context, projectRef string) (*Project, *http.Response, error) { - project := new(Project) +func (c *Client) GetProject(ctx context.Context, projectRef string) (*csapitypes.Project, *http.Response, error) { + project := new(csapitypes.Project) resp, err := c.getParsedResponse(ctx, "GET", fmt.Sprintf("/projects/%s", url.PathEscape(projectRef)), nil, jsonContent, nil, project) return project, resp, err } -func (c *Client) CreateProject(ctx context.Context, project *types.Project) (*Project, *http.Response, error) { +func (c *Client) CreateProject(ctx context.Context, project *cstypes.Project) (*csapitypes.Project, *http.Response, error) { pj, err := json.Marshal(project) if err != nil { return nil, nil, err } - resProject := new(Project) + resProject := new(csapitypes.Project) resp, err := c.getParsedResponse(ctx, "POST", "/projects", nil, jsonContent, bytes.NewReader(pj), resProject) return resProject, resp, err } -func (c *Client) UpdateProject(ctx context.Context, projectRef string, project *types.Project) (*Project, *http.Response, error) { +func (c *Client) UpdateProject(ctx context.Context, projectRef string, project *cstypes.Project) (*csapitypes.Project, *http.Response, error) { pj, err := json.Marshal(project) if err != nil { return nil, nil, err } - resProject := new(Project) + resProject := new(csapitypes.Project) resp, err := c.getParsedResponse(ctx, "PUT", fmt.Sprintf("/projects/%s", url.PathEscape(projectRef)), nil, jsonContent, bytes.NewReader(pj), resProject) return resProject, resp, err } @@ -182,68 +183,68 @@ func (c *Client) DeleteProject(ctx context.Context, projectRef string) (*http.Re return c.getResponse(ctx, "DELETE", fmt.Sprintf("/projects/%s", url.PathEscape(projectRef)), nil, jsonContent, nil) } -func (c *Client) GetProjectGroupSecrets(ctx context.Context, projectGroupRef string, tree bool) ([]*Secret, *http.Response, error) { +func (c *Client) GetProjectGroupSecrets(ctx context.Context, projectGroupRef string, tree bool) ([]*csapitypes.Secret, *http.Response, error) { q := url.Values{} if tree { q.Add("tree", "") } - secrets := []*Secret{} + secrets := []*csapitypes.Secret{} resp, err := c.getParsedResponse(ctx, "GET", fmt.Sprintf("/projectgroups/%s/secrets", url.PathEscape(projectGroupRef)), q, jsonContent, nil, &secrets) return secrets, resp, err } -func (c *Client) GetProjectSecrets(ctx context.Context, projectRef string, tree bool) ([]*Secret, *http.Response, error) { +func (c *Client) GetProjectSecrets(ctx context.Context, projectRef string, tree bool) ([]*csapitypes.Secret, *http.Response, error) { q := url.Values{} if tree { q.Add("tree", "") } - secrets := []*Secret{} + secrets := []*csapitypes.Secret{} resp, err := c.getParsedResponse(ctx, "GET", fmt.Sprintf("/projects/%s/secrets", url.PathEscape(projectRef)), q, jsonContent, nil, &secrets) return secrets, resp, err } -func (c *Client) CreateProjectGroupSecret(ctx context.Context, projectGroupRef string, secret *types.Secret) (*Secret, *http.Response, error) { +func (c *Client) CreateProjectGroupSecret(ctx context.Context, projectGroupRef string, secret *cstypes.Secret) (*csapitypes.Secret, *http.Response, error) { pj, err := json.Marshal(secret) if err != nil { return nil, nil, err } - resSecret := new(Secret) + resSecret := new(csapitypes.Secret) resp, err := c.getParsedResponse(ctx, "POST", fmt.Sprintf("/projectgroups/%s/secrets", url.PathEscape(projectGroupRef)), nil, jsonContent, bytes.NewReader(pj), resSecret) return resSecret, resp, err } -func (c *Client) CreateProjectSecret(ctx context.Context, projectRef string, secret *types.Secret) (*Secret, *http.Response, error) { +func (c *Client) CreateProjectSecret(ctx context.Context, projectRef string, secret *cstypes.Secret) (*csapitypes.Secret, *http.Response, error) { pj, err := json.Marshal(secret) if err != nil { return nil, nil, err } - resSecret := new(Secret) + resSecret := new(csapitypes.Secret) resp, err := c.getParsedResponse(ctx, "POST", fmt.Sprintf("/projects/%s/secrets", url.PathEscape(projectRef)), nil, jsonContent, bytes.NewReader(pj), resSecret) return resSecret, resp, err } -func (c *Client) UpdateProjectGroupSecret(ctx context.Context, projectGroupRef, secretName string, secret *types.Secret) (*Secret, *http.Response, error) { +func (c *Client) UpdateProjectGroupSecret(ctx context.Context, projectGroupRef, secretName string, secret *cstypes.Secret) (*csapitypes.Secret, *http.Response, error) { pj, err := json.Marshal(secret) if err != nil { return nil, nil, err } - resSecret := new(Secret) + resSecret := new(csapitypes.Secret) resp, err := c.getParsedResponse(ctx, "PUT", fmt.Sprintf("/projectgroups/%s/secrets/%s", url.PathEscape(projectGroupRef), secretName), nil, jsonContent, bytes.NewReader(pj), resSecret) return resSecret, resp, err } -func (c *Client) UpdateProjectSecret(ctx context.Context, projectRef, secretName string, secret *types.Secret) (*Secret, *http.Response, error) { +func (c *Client) UpdateProjectSecret(ctx context.Context, projectRef, secretName string, secret *cstypes.Secret) (*csapitypes.Secret, *http.Response, error) { pj, err := json.Marshal(secret) if err != nil { return nil, nil, err } - resSecret := new(Secret) + resSecret := new(csapitypes.Secret) resp, err := c.getParsedResponse(ctx, "PUT", fmt.Sprintf("/projects/%s/secrets/%s", url.PathEscape(projectRef), secretName), nil, jsonContent, bytes.NewReader(pj), resSecret) return resSecret, resp, err } @@ -256,68 +257,68 @@ func (c *Client) DeleteProjectSecret(ctx context.Context, projectRef, secretName return c.getResponse(ctx, "DELETE", fmt.Sprintf("/projects/%s/secrets/%s", url.PathEscape(projectRef), secretName), nil, jsonContent, nil) } -func (c *Client) GetProjectGroupVariables(ctx context.Context, projectGroupRef string, tree bool) ([]*Variable, *http.Response, error) { +func (c *Client) GetProjectGroupVariables(ctx context.Context, projectGroupRef string, tree bool) ([]*csapitypes.Variable, *http.Response, error) { q := url.Values{} if tree { q.Add("tree", "") } - variables := []*Variable{} + variables := []*csapitypes.Variable{} resp, err := c.getParsedResponse(ctx, "GET", fmt.Sprintf("/projectgroups/%s/variables", url.PathEscape(projectGroupRef)), q, jsonContent, nil, &variables) return variables, resp, err } -func (c *Client) GetProjectVariables(ctx context.Context, projectRef string, tree bool) ([]*Variable, *http.Response, error) { +func (c *Client) GetProjectVariables(ctx context.Context, projectRef string, tree bool) ([]*csapitypes.Variable, *http.Response, error) { q := url.Values{} if tree { q.Add("tree", "") } - variables := []*Variable{} + variables := []*csapitypes.Variable{} resp, err := c.getParsedResponse(ctx, "GET", fmt.Sprintf("/projects/%s/variables", url.PathEscape(projectRef)), q, jsonContent, nil, &variables) return variables, resp, err } -func (c *Client) CreateProjectGroupVariable(ctx context.Context, projectGroupRef string, variable *types.Variable) (*Variable, *http.Response, error) { +func (c *Client) CreateProjectGroupVariable(ctx context.Context, projectGroupRef string, variable *cstypes.Variable) (*csapitypes.Variable, *http.Response, error) { pj, err := json.Marshal(variable) if err != nil { return nil, nil, err } - resVariable := new(Variable) + resVariable := new(csapitypes.Variable) resp, err := c.getParsedResponse(ctx, "POST", fmt.Sprintf("/projectgroups/%s/variables", url.PathEscape(projectGroupRef)), nil, jsonContent, bytes.NewReader(pj), resVariable) return resVariable, resp, err } -func (c *Client) UpdateProjectGroupVariable(ctx context.Context, projectGroupRef, variableName string, variable *types.Variable) (*Variable, *http.Response, error) { +func (c *Client) UpdateProjectGroupVariable(ctx context.Context, projectGroupRef, variableName string, variable *cstypes.Variable) (*csapitypes.Variable, *http.Response, error) { pj, err := json.Marshal(variable) if err != nil { return nil, nil, err } - resVariable := new(Variable) + resVariable := new(csapitypes.Variable) resp, err := c.getParsedResponse(ctx, "PUT", fmt.Sprintf("/projectgroups/%s/variables/%s", url.PathEscape(projectGroupRef), variableName), nil, jsonContent, bytes.NewReader(pj), resVariable) return resVariable, resp, err } -func (c *Client) CreateProjectVariable(ctx context.Context, projectRef string, variable *types.Variable) (*Variable, *http.Response, error) { +func (c *Client) CreateProjectVariable(ctx context.Context, projectRef string, variable *cstypes.Variable) (*csapitypes.Variable, *http.Response, error) { pj, err := json.Marshal(variable) if err != nil { return nil, nil, err } - resVariable := new(Variable) + resVariable := new(csapitypes.Variable) resp, err := c.getParsedResponse(ctx, "POST", fmt.Sprintf("/projects/%s/variables", url.PathEscape(projectRef)), nil, jsonContent, bytes.NewReader(pj), resVariable) return resVariable, resp, err } -func (c *Client) UpdateProjectVariable(ctx context.Context, projectRef, variableName string, variable *types.Variable) (*Variable, *http.Response, error) { +func (c *Client) UpdateProjectVariable(ctx context.Context, projectRef, variableName string, variable *cstypes.Variable) (*csapitypes.Variable, *http.Response, error) { pj, err := json.Marshal(variable) if err != nil { return nil, nil, err } - resVariable := new(Variable) + resVariable := new(csapitypes.Variable) resp, err := c.getParsedResponse(ctx, "PUT", fmt.Sprintf("/projects/%s/variables/%s", url.PathEscape(projectRef), variableName), nil, jsonContent, bytes.NewReader(pj), resVariable) return resVariable, resp, err } @@ -330,18 +331,18 @@ func (c *Client) DeleteProjectVariable(ctx context.Context, projectRef, variable return c.getResponse(ctx, "DELETE", fmt.Sprintf("/projects/%s/variables/%s", url.PathEscape(projectRef), variableName), nil, jsonContent, nil) } -func (c *Client) GetUser(ctx context.Context, userRef string) (*types.User, *http.Response, error) { +func (c *Client) GetUser(ctx context.Context, userRef string) (*cstypes.User, *http.Response, error) { user := new(types.User) resp, err := c.getParsedResponse(ctx, "GET", fmt.Sprintf("/users/%s", userRef), nil, jsonContent, nil, user) return user, resp, err } -func (c *Client) GetUserByToken(ctx context.Context, token string) (*types.User, *http.Response, error) { +func (c *Client) GetUserByToken(ctx context.Context, token string) (*cstypes.User, *http.Response, error) { q := url.Values{} q.Add("query_type", "bytoken") q.Add("token", token) - users := []*types.User{} + users := []*cstypes.User{} resp, err := c.getParsedResponse(ctx, "GET", "/users", q, jsonContent, nil, &users) if err != nil { return nil, resp, err @@ -349,13 +350,13 @@ func (c *Client) GetUserByToken(ctx context.Context, token string) (*types.User, return users[0], resp, err } -func (c *Client) GetUserByLinkedAccountRemoteUserAndSource(ctx context.Context, remoteUserID, remoteSourceID string) (*types.User, *http.Response, error) { +func (c *Client) GetUserByLinkedAccountRemoteUserAndSource(ctx context.Context, remoteUserID, remoteSourceID string) (*cstypes.User, *http.Response, error) { q := url.Values{} q.Add("query_type", "byremoteuser") q.Add("remoteuserid", remoteUserID) q.Add("remotesourceid", remoteSourceID) - users := []*types.User{} + users := []*cstypes.User{} resp, err := c.getParsedResponse(ctx, "GET", "/users", q, jsonContent, nil, &users) if err != nil { return nil, resp, err @@ -363,12 +364,12 @@ func (c *Client) GetUserByLinkedAccountRemoteUserAndSource(ctx context.Context, return users[0], resp, err } -func (c *Client) GetUserByLinkedAccount(ctx context.Context, linkedAccountID string) (*types.User, *http.Response, error) { +func (c *Client) GetUserByLinkedAccount(ctx context.Context, linkedAccountID string) (*cstypes.User, *http.Response, error) { q := url.Values{} q.Add("query_type", "bylinkedaccount") q.Add("linkedaccountid", linkedAccountID) - users := []*types.User{} + users := []*cstypes.User{} resp, err := c.getParsedResponse(ctx, "GET", "/users", q, jsonContent, nil, &users) if err != nil { return nil, resp, err @@ -376,7 +377,7 @@ func (c *Client) GetUserByLinkedAccount(ctx context.Context, linkedAccountID str return users[0], resp, err } -func (c *Client) CreateUser(ctx context.Context, req *CreateUserRequest) (*types.User, *http.Response, error) { +func (c *Client) CreateUser(ctx context.Context, req *csapitypes.CreateUserRequest) (*cstypes.User, *http.Response, error) { reqj, err := json.Marshal(req) if err != nil { return nil, nil, err @@ -387,7 +388,7 @@ func (c *Client) CreateUser(ctx context.Context, req *CreateUserRequest) (*types return user, resp, err } -func (c *Client) UpdateUser(ctx context.Context, userRef string, req *UpdateUserRequest) (*types.User, *http.Response, error) { +func (c *Client) UpdateUser(ctx context.Context, userRef string, req *csapitypes.UpdateUserRequest) (*cstypes.User, *http.Response, error) { reqj, err := json.Marshal(req) if err != nil { return nil, nil, err @@ -402,7 +403,7 @@ func (c *Client) DeleteUser(ctx context.Context, userRef string) (*http.Response return c.getResponse(ctx, "DELETE", fmt.Sprintf("/users/%s", userRef), nil, jsonContent, nil) } -func (c *Client) GetUsers(ctx context.Context, start string, limit int, asc bool) ([]*types.User, *http.Response, error) { +func (c *Client) GetUsers(ctx context.Context, start string, limit int, asc bool) ([]*cstypes.User, *http.Response, error) { q := url.Values{} if start != "" { q.Add("start", start) @@ -414,12 +415,12 @@ func (c *Client) GetUsers(ctx context.Context, start string, limit int, asc bool q.Add("asc", "") } - users := []*types.User{} + users := []*cstypes.User{} resp, err := c.getParsedResponse(ctx, "GET", "/users", q, jsonContent, nil, &users) return users, resp, err } -func (c *Client) CreateUserLA(ctx context.Context, userRef string, req *CreateUserLARequest) (*types.LinkedAccount, *http.Response, error) { +func (c *Client) CreateUserLA(ctx context.Context, userRef string, req *csapitypes.CreateUserLARequest) (*cstypes.LinkedAccount, *http.Response, error) { reqj, err := json.Marshal(req) if err != nil { return nil, nil, err @@ -434,7 +435,7 @@ func (c *Client) DeleteUserLA(ctx context.Context, userRef, laID string) (*http. return c.getResponse(ctx, "DELETE", fmt.Sprintf("/users/%s/linkedaccounts/%s", userRef, laID), nil, jsonContent, nil) } -func (c *Client) UpdateUserLA(ctx context.Context, userRef, laID string, req *UpdateUserLARequest) (*types.LinkedAccount, *http.Response, error) { +func (c *Client) UpdateUserLA(ctx context.Context, userRef, laID string, req *csapitypes.UpdateUserLARequest) (*cstypes.LinkedAccount, *http.Response, error) { reqj, err := json.Marshal(req) if err != nil { return nil, nil, err @@ -445,13 +446,13 @@ func (c *Client) UpdateUserLA(ctx context.Context, userRef, laID string, req *Up return la, resp, err } -func (c *Client) CreateUserToken(ctx context.Context, userRef string, req *CreateUserTokenRequest) (*CreateUserTokenResponse, *http.Response, error) { +func (c *Client) CreateUserToken(ctx context.Context, userRef string, req *csapitypes.CreateUserTokenRequest) (*csapitypes.CreateUserTokenResponse, *http.Response, error) { reqj, err := json.Marshal(req) if err != nil { return nil, nil, err } - tresp := new(CreateUserTokenResponse) + tresp := new(csapitypes.CreateUserTokenResponse) resp, err := c.getParsedResponse(ctx, "POST", fmt.Sprintf("/users/%s/tokens", userRef), nil, jsonContent, bytes.NewReader(reqj), tresp) return tresp, resp, err } @@ -460,19 +461,19 @@ func (c *Client) DeleteUserToken(ctx context.Context, userRef, tokenName string) return c.getResponse(ctx, "DELETE", fmt.Sprintf("/users/%s/tokens/%s", userRef, tokenName), nil, jsonContent, nil) } -func (c *Client) GetUserOrgs(ctx context.Context, userRef string) ([]*UserOrgsResponse, *http.Response, error) { - userOrgs := []*UserOrgsResponse{} +func (c *Client) GetUserOrgs(ctx context.Context, userRef string) ([]*csapitypes.UserOrgsResponse, *http.Response, error) { + userOrgs := []*csapitypes.UserOrgsResponse{} resp, err := c.getParsedResponse(ctx, "GET", fmt.Sprintf("/users/%s/orgs", userRef), nil, jsonContent, nil, &userOrgs) return userOrgs, resp, err } -func (c *Client) GetRemoteSource(ctx context.Context, rsRef string) (*types.RemoteSource, *http.Response, error) { +func (c *Client) GetRemoteSource(ctx context.Context, rsRef string) (*cstypes.RemoteSource, *http.Response, error) { rs := new(types.RemoteSource) resp, err := c.getParsedResponse(ctx, "GET", fmt.Sprintf("/remotesources/%s", rsRef), nil, jsonContent, nil, rs) return rs, resp, err } -func (c *Client) GetRemoteSources(ctx context.Context, start string, limit int, asc bool) ([]*types.RemoteSource, *http.Response, error) { +func (c *Client) GetRemoteSources(ctx context.Context, start string, limit int, asc bool) ([]*cstypes.RemoteSource, *http.Response, error) { q := url.Values{} if start != "" { q.Add("start", start) @@ -484,12 +485,12 @@ func (c *Client) GetRemoteSources(ctx context.Context, start string, limit int, q.Add("asc", "") } - rss := []*types.RemoteSource{} + rss := []*cstypes.RemoteSource{} resp, err := c.getParsedResponse(ctx, "GET", "/remotesources", q, jsonContent, nil, &rss) return rss, resp, err } -func (c *Client) CreateRemoteSource(ctx context.Context, rs *types.RemoteSource) (*types.RemoteSource, *http.Response, error) { +func (c *Client) CreateRemoteSource(ctx context.Context, rs *cstypes.RemoteSource) (*types.RemoteSource, *http.Response, error) { rsj, err := json.Marshal(rs) if err != nil { return nil, nil, err @@ -500,7 +501,7 @@ func (c *Client) CreateRemoteSource(ctx context.Context, rs *types.RemoteSource) return rs, resp, err } -func (c *Client) UpdateRemoteSource(ctx context.Context, remoteSourceRef string, remoteSource *types.RemoteSource) (*types.RemoteSource, *http.Response, error) { +func (c *Client) UpdateRemoteSource(ctx context.Context, remoteSourceRef string, remoteSource *cstypes.RemoteSource) (*types.RemoteSource, *http.Response, error) { rsj, err := json.Marshal(remoteSource) if err != nil { return nil, nil, err @@ -515,7 +516,7 @@ func (c *Client) DeleteRemoteSource(ctx context.Context, rsRef string) (*http.Re return c.getResponse(ctx, "DELETE", fmt.Sprintf("/remotesources/%s", rsRef), nil, jsonContent, nil) } -func (c *Client) CreateOrg(ctx context.Context, org *types.Organization) (*types.Organization, *http.Response, error) { +func (c *Client) CreateOrg(ctx context.Context, org *cstypes.Organization) (*types.Organization, *http.Response, error) { oj, err := json.Marshal(org) if err != nil { return nil, nil, err @@ -530,8 +531,8 @@ func (c *Client) DeleteOrg(ctx context.Context, orgRef string) (*http.Response, return c.getResponse(ctx, "DELETE", fmt.Sprintf("/orgs/%s", orgRef), nil, jsonContent, nil) } -func (c *Client) AddOrgMember(ctx context.Context, orgRef, userRef string, role types.MemberRole) (*types.OrganizationMember, *http.Response, error) { - req := &AddOrgMemberRequest{ +func (c *Client) AddOrgMember(ctx context.Context, orgRef, userRef string, role cstypes.MemberRole) (*cstypes.OrganizationMember, *http.Response, error) { + req := &csapitypes.AddOrgMemberRequest{ Role: role, } omj, err := json.Marshal(req) @@ -548,7 +549,7 @@ func (c *Client) RemoveOrgMember(ctx context.Context, orgRef, userRef string) (* return c.getResponse(ctx, "DELETE", fmt.Sprintf("/orgs/%s/members/%s", orgRef, userRef), nil, jsonContent, nil) } -func (c *Client) GetOrgs(ctx context.Context, start string, limit int, asc bool) ([]*types.Organization, *http.Response, error) { +func (c *Client) GetOrgs(ctx context.Context, start string, limit int, asc bool) ([]*cstypes.Organization, *http.Response, error) { q := url.Values{} if start != "" { q.Add("start", start) @@ -560,19 +561,19 @@ func (c *Client) GetOrgs(ctx context.Context, start string, limit int, asc bool) q.Add("asc", "") } - orgs := []*types.Organization{} + orgs := []*cstypes.Organization{} resp, err := c.getParsedResponse(ctx, "GET", "/orgs", q, jsonContent, nil, &orgs) return orgs, resp, err } -func (c *Client) GetOrg(ctx context.Context, orgRef string) (*types.Organization, *http.Response, error) { +func (c *Client) GetOrg(ctx context.Context, orgRef string) (*cstypes.Organization, *http.Response, error) { org := new(types.Organization) resp, err := c.getParsedResponse(ctx, "GET", fmt.Sprintf("/orgs/%s", orgRef), nil, jsonContent, nil, org) return org, resp, err } -func (c *Client) GetOrgMembers(ctx context.Context, orgRef string) ([]*OrgMemberResponse, *http.Response, error) { - orgMembers := []*OrgMemberResponse{} +func (c *Client) GetOrgMembers(ctx context.Context, orgRef string) ([]*csapitypes.OrgMemberResponse, *http.Response, error) { + orgMembers := []*csapitypes.OrgMemberResponse{} resp, err := c.getParsedResponse(ctx, "GET", fmt.Sprintf("/orgs/%s/members", orgRef), nil, jsonContent, nil, &orgMembers) return orgMembers, resp, err } diff --git a/internal/services/configstore/types/types.go b/services/configstore/types/types.go similarity index 99% rename from internal/services/configstore/types/types.go rename to services/configstore/types/types.go index c809171..83be6ef 100644 --- a/internal/services/configstore/types/types.go +++ b/services/configstore/types/types.go @@ -20,7 +20,7 @@ import ( "regexp" "time" - "agola.io/agola/internal/util" + "agola.io/agola/util" ) // Configstore types diff --git a/internal/services/configstore/types/types_test.go b/services/configstore/types/types_test.go similarity index 100% rename from internal/services/configstore/types/types_test.go rename to services/configstore/types/types_test.go diff --git a/services/gateway/api/types/oauth2.go b/services/gateway/api/types/oauth2.go new file mode 100644 index 0000000..0b16d91 --- /dev/null +++ b/services/gateway/api/types/oauth2.go @@ -0,0 +1,20 @@ +// Copyright 2019 Sorint.lab +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied +// See the License for the specific language governing permissions and +// limitations under the License. + +package types + +type RemoteSourceAuthResult struct { + RequestType string `json:"request_type,omitempty"` + Response interface{} `json:"response,omitempty"` +} diff --git a/services/gateway/api/types/org.go b/services/gateway/api/types/org.go new file mode 100644 index 0000000..52ec73f --- /dev/null +++ b/services/gateway/api/types/org.go @@ -0,0 +1,52 @@ +// Copyright 2019 Sorint.lab +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied +// See the License for the specific language governing permissions and +// limitations under the License. + +package types + +type MemberRole string + +const ( + MemberRoleOwner MemberRole = "owner" + MemberRoleMember MemberRole = "member" +) + +type CreateOrgRequest struct { + Name string `json:"name"` + Visibility Visibility `json:"visibility"` +} + +type OrgResponse struct { + ID string `json:"id"` + Name string `json:"name"` + Visibility Visibility `json:"visibility,omitempty"` +} + +type OrgMembersResponse struct { + Organization *OrgResponse `json:"organization"` + Members []*OrgMemberResponse `json:"members"` +} + +type OrgMemberResponse struct { + User *UserResponse `json:"user"` + Role MemberRole `json:"role"` +} + +type AddOrgMemberResponse struct { + Organization *OrgResponse `json:"organization"` + OrgMemberResponse +} + +type AddOrgMemberRequest struct { + Role MemberRole `json:"role"` +} diff --git a/services/gateway/api/types/project.go b/services/gateway/api/types/project.go new file mode 100644 index 0000000..66e2486 --- /dev/null +++ b/services/gateway/api/types/project.go @@ -0,0 +1,45 @@ +// Copyright 2019 Sorint.lab +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied +// See the License for the specific language governing permissions and +// limitations under the License. + +package types + +type CreateProjectRequest struct { + Name string `json:"name,omitempty"` + ParentRef string `json:"parent_ref,omitempty"` + Visibility Visibility `json:"visibility,omitempty"` + RepoPath string `json:"repo_path,omitempty"` + RemoteSourceName string `json:"remote_source_name,omitempty"` + SkipSSHHostKeyCheck bool `json:"skip_ssh_host_key_check,omitempty"` +} + +type UpdateProjectRequest struct { + Name string `json:"name,omitempty"` + Visibility Visibility `json:"visibility,omitempty"` +} + +type ProjectResponse struct { + ID string `json:"id,omitempty"` + Name string `json:"name,omitempty"` + Path string `json:"path,omitempty"` + ParentPath string `json:"parent_path,omitempty"` + Visibility Visibility `json:"visibility,omitempty"` + GlobalVisibility string `json:"global_visibility,omitempty"` +} + +type ProjectCreateRunRequest struct { + Branch string `json:"branch,omitempty"` + Tag string `json:"tag,omitempty"` + Ref string `json:"ref,omitempty"` + CommitSHA string `json:"commit_sha,omitempty"` +} diff --git a/services/gateway/api/types/projectgroup.go b/services/gateway/api/types/projectgroup.go new file mode 100644 index 0000000..dbfd303 --- /dev/null +++ b/services/gateway/api/types/projectgroup.go @@ -0,0 +1,35 @@ +// Copyright 2019 Sorint.lab +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied +// See the License for the specific language governing permissions and +// limitations under the License. + +package types + +type CreateProjectGroupRequest struct { + Name string `json:"name"` + ParentRef string `json:"parent_ref"` + Visibility Visibility `json:"visibility"` +} + +type UpdateProjectGroupRequest struct { + Name string `json:"name,omitempty"` + Visibility Visibility `json:"visibility,omitempty"` +} + +type ProjectGroupResponse struct { + ID string `json:"id"` + Name string `json:"name"` + Path string `json:"path"` + ParentPath string `json:"parent_path"` + Visibility Visibility `json:"visibility"` + GlobalVisibility string `json:"global_visibility"` +} diff --git a/services/gateway/api/types/remoterepo.go b/services/gateway/api/types/remoterepo.go new file mode 100644 index 0000000..a38c0e9 --- /dev/null +++ b/services/gateway/api/types/remoterepo.go @@ -0,0 +1,20 @@ +// Copyright 2019 Sorint.lab +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied +// See the License for the specific language governing permissions and +// limitations under the License. + +package types + +type RemoteRepoResponse struct { + ID string `json:"id,omitempty"` + Path string `json:"path,omitempty"` +} diff --git a/services/gateway/api/types/remotesource.go b/services/gateway/api/types/remotesource.go new file mode 100644 index 0000000..82fffff --- /dev/null +++ b/services/gateway/api/types/remotesource.go @@ -0,0 +1,49 @@ +// Copyright 2019 Sorint.lab +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied +// See the License for the specific language governing permissions and +// limitations under the License. + +package types + +type CreateRemoteSourceRequest struct { + Name string `json:"name"` + APIURL string `json:"apiurl"` + Type string `json:"type"` + AuthType string `json:"auth_type"` + SkipVerify bool `json:"skip_verify"` + Oauth2ClientID string `json:"oauth_2_client_id"` + Oauth2ClientSecret string `json:"oauth_2_client_secret"` + SSHHostKey string `json:"ssh_host_key"` + SkipSSHHostKeyCheck bool `json:"skip_ssh_host_key_check"` + RegistrationEnabled *bool `json:"registration_enabled"` + LoginEnabled *bool `json:"login_enabled"` +} + +type UpdateRemoteSourceRequest struct { + Name *string `json:"name"` + APIURL *string `json:"apiurl"` + SkipVerify *bool `json:"skip_verify"` + Oauth2ClientID *string `json:"oauth_2_client_id"` + Oauth2ClientSecret *string `json:"oauth_2_client_secret"` + SSHHostKey *string `json:"ssh_host_key"` + SkipSSHHostKeyCheck *bool `json:"skip_ssh_host_key_check"` + RegistrationEnabled *bool `json:"registration_enabled"` + LoginEnabled *bool `json:"login_enabled"` +} + +type RemoteSourceResponse struct { + ID string `json:"id"` + Name string `json:"name"` + AuthType string `json:"auth_type"` + RegistrationEnabled bool `json:"registration_enabled"` + LoginEnabled bool `json:"login_enabled"` +} diff --git a/services/gateway/api/types/run.go b/services/gateway/api/types/run.go new file mode 100644 index 0000000..bf36181 --- /dev/null +++ b/services/gateway/api/types/run.go @@ -0,0 +1,130 @@ +// Copyright 2019 Sorint.lab +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied +// See the License for the specific language governing permissions and +// limitations under the License. + +package types + +import ( + "time" + + rstypes "agola.io/agola/services/runservice/types" +) + +type RunsResponse struct { + ID string `json:"id"` + Counter uint64 `json:"counter"` + Name string `json:"name"` + Annotations map[string]string `json:"annotations"` + Phase rstypes.RunPhase `json:"phase"` + Result rstypes.RunResult `json:"result"` + + TasksWaitingApproval []string `json:"tasks_waiting_approval"` + + EnqueueTime *time.Time `json:"enqueue_time"` + StartTime *time.Time `json:"start_time"` + EndTime *time.Time `json:"end_time"` +} + +type RunResponse struct { + ID string `json:"id"` + Counter uint64 `json:"counter"` + Name string `json:"name"` + Annotations map[string]string `json:"annotations"` + Phase rstypes.RunPhase `json:"phase"` + Result rstypes.RunResult `json:"result"` + SetupErrors []string `json:"setup_errors"` + Stopping bool `json:"stopping"` + + Tasks map[string]*RunResponseTask `json:"tasks"` + TasksWaitingApproval []string `json:"tasks_waiting_approval"` + + EnqueueTime *time.Time `json:"enqueue_time"` + StartTime *time.Time `json:"start_time"` + EndTime *time.Time `json:"end_time"` + + CanRestartFromScratch bool `json:"can_restart_from_scratch"` + CanRestartFromFailedTasks bool `json:"can_restart_from_failed_tasks"` +} + +type RunResponseTask struct { + ID string `json:"id"` + Name string `json:"name"` + Status rstypes.RunTaskStatus `json:"status"` + Level int `json:"level"` + Depends map[string]*rstypes.RunConfigTaskDepend `json:"depends"` + + WaitingApproval bool `json:"waiting_approval"` + Approved bool `json:"approved"` + ApprovalAnnotations map[string]string `json:"approval_annotations"` + + StartTime *time.Time `json:"start_time"` + EndTime *time.Time `json:"end_time"` +} + +type RunTaskResponse struct { + ID string `json:"id"` + Name string `json:"name"` + Status rstypes.RunTaskStatus `json:"status"` + + WaitingApproval bool `json:"waiting_approval"` + Approved bool `json:"approved"` + ApprovalAnnotations map[string]string `json:"approval_annotations"` + + SetupStep *RunTaskResponseSetupStep `json:"setup_step"` + Steps []*RunTaskResponseStep `json:"steps"` + + StartTime *time.Time `json:"start_time"` + EndTime *time.Time `json:"end_time"` +} + +type RunTaskResponseSetupStep struct { + Phase rstypes.ExecutorTaskPhase `json:"phase"` + Name string `json:"name"` + + StartTime *time.Time `json:"start_time"` + EndTime *time.Time `json:"end_time"` +} + +type RunTaskResponseStep struct { + Phase rstypes.ExecutorTaskPhase `json:"phase"` + Name string `json:"name"` + Command string `json:"command"` + + StartTime *time.Time `json:"start_time"` + EndTime *time.Time `json:"end_time"` +} + +type RunActionType string + +const ( + RunActionTypeRestart RunActionType = "restart" + RunActionTypeCancel RunActionType = "cancel" + RunActionTypeStop RunActionType = "stop" +) + +type RunActionsRequest struct { + ActionType RunActionType `json:"action_type"` + + // Restart + FromStart bool `json:"from_start"` +} + +type RunTaskActionType string + +const ( + RunTaskActionTypeApprove RunTaskActionType = "approve" +) + +type RunTaskActionsRequest struct { + ActionType RunTaskActionType `json:"action_type"` +} diff --git a/services/gateway/api/types/secret.go b/services/gateway/api/types/secret.go new file mode 100644 index 0000000..bca21a2 --- /dev/null +++ b/services/gateway/api/types/secret.go @@ -0,0 +1,54 @@ +// Copyright 2019 Sorint.lab +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied +// See the License for the specific language governing permissions and +// limitations under the License. + +package types + +type SecretType string + +const ( + SecretTypeInternal SecretType = "internal" + SecretTypeExternal SecretType = "external" +) + +type SecretResponse struct { + ID string `json:"id"` + Name string `json:"name"` + ParentPath string `json:"parent_path"` +} + +type CreateSecretRequest struct { + Name string `json:"name,omitempty"` + + Type SecretType `json:"type,omitempty"` + + // internal secret + Data map[string]string `json:"data,omitempty"` + + // external secret + SecretProviderID string `json:"secret_provider_id,omitempty"` + Path string `json:"path,omitempty"` +} + +type UpdateSecretRequest struct { + Name string `json:"name,omitempty"` + + Type SecretType `json:"type,omitempty"` + + // internal secret + Data map[string]string `json:"data,omitempty"` + + // external secret + SecretProviderID string `json:"secret_provider_id,omitempty"` + Path string `json:"path,omitempty"` +} diff --git a/services/gateway/api/types/user.go b/services/gateway/api/types/user.go new file mode 100644 index 0000000..5294b3f --- /dev/null +++ b/services/gateway/api/types/user.go @@ -0,0 +1,103 @@ +// Copyright 2019 Sorint.lab +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied +// See the License for the specific language governing permissions and +// limitations under the License. + +package types + +type LinkedAccount struct { + ID string `json:"id,omitempty"` + + RemoteUserID string `json:"remote_user_id,omitempty"` + RemoteUserName string `json:"remote_username,omitempty"` + RemoteUserAvatarURL string `json:"remote_user_avatar_url,omitempty"` + + RemoteSourceID string `json:"remote_source_id,omitempty"` +} + +type CreateUserRequest struct { + UserName string `json:"username"` +} + +type UserResponse struct { + ID string `json:"id"` + UserName string `json:"username"` + Tokens []string `json:"tokens"` + LinkedAccounts []*LinkedAccountResponse `json:"linked_accounts"` +} + +type LinkedAccountResponse struct { + ID string `json:"id"` + RemoteSourceID string `json:"remote_source_id"` + RemoteUserName string `json:"remote_user_name"` + RemoteUserAvatarURL string `json:"remote_user_avatar_url"` +} + +type CreateUserLARequest struct { + RemoteSourceName string `json:"remote_source_name"` + RemoteSourceLoginName string `json:"remote_source_login_name"` + RemoteSourceLoginPassword string `json:"remote_source_login_password"` +} + +type CreateUserLAResponse struct { + LinkedAccount *LinkedAccount `json:"linked_account"` + Oauth2Redirect string `json:"oauth2_redirect"` +} + +type CreateUserTokenRequest struct { + TokenName string `json:"token_name"` +} + +type CreateUserTokenResponse struct { + Token string `json:"token"` +} + +type RegisterUserRequest struct { + CreateUserRequest + CreateUserLARequest +} + +type RegisterUserResponse struct { + Oauth2Redirect string `json:"oauth2_redirect"` +} + +type UserInfo struct { + ID string + LoginName string + Email string +} + +type AuthorizeResponse struct { + Oauth2Redirect string `json:"oauth2_redirect"` + RemoteUserInfo *UserInfo `json:"remote_user_info"` + RemoteSourceName string `json:"remote_source_name"` +} + +type LoginUserRequest struct { + RemoteSourceName string `json:"remote_source_name"` + LoginName string `json:"login_name"` + LoginPassword string `json:"password"` +} + +type LoginUserResponse struct { + Oauth2Redirect string `json:"oauth2_redirect"` + Token string `json:"token"` + User *UserResponse `json:"user"` +} + +type UserCreateRunRequest struct { + RepoUUID string `json:"repo_uuid,omitempty"` + RepoPath string `json:"repo_path,omitempty"` + Branch string `json:"branch,omitempty"` + CommitSHA string `json:"commit_sha,omitempty"` + Message string `json:"message,omitempty"` +} diff --git a/services/gateway/api/types/variable.go b/services/gateway/api/types/variable.go new file mode 100644 index 0000000..718d5fe --- /dev/null +++ b/services/gateway/api/types/variable.go @@ -0,0 +1,49 @@ +// Copyright 2019 Sorint.lab +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied +// See the License for the specific language governing permissions and +// limitations under the License. + +package types + +type VariableValueRequest struct { + SecretName string `json:"secret_name"` + SecretVar string `json:"secret_var"` + + When *When `json:"when"` +} + +type VariableValue struct { + SecretName string `json:"secret_name"` + SecretVar string `json:"secret_var"` + MatchingSecretParentPath string `json:"matching_secret_parent_path"` + + When *When `json:"when"` +} + +type VariableResponse struct { + ID string `json:"id"` + Name string `json:"name"` + Values []VariableValue `json:"values"` + ParentPath string `json:"parent_path"` +} + +type CreateVariableRequest struct { + Name string `json:"name,omitempty"` + + Values []VariableValueRequest `json:"values,omitempty"` +} + +type UpdateVariableRequest struct { + Name string `json:"name,omitempty"` + + Values []VariableValueRequest `json:"values,omitempty"` +} diff --git a/services/gateway/api/types/visibility.go b/services/gateway/api/types/visibility.go new file mode 100644 index 0000000..d736b96 --- /dev/null +++ b/services/gateway/api/types/visibility.go @@ -0,0 +1,22 @@ +// Copyright 2019 Sorint.lab +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied +// See the License for the specific language governing permissions and +// limitations under the License. + +package types + +type Visibility string + +const ( + VisibilityPublic Visibility = "public" + VisibilityPrivate Visibility = "private" +) diff --git a/services/gateway/api/types/when.go b/services/gateway/api/types/when.go new file mode 100644 index 0000000..a9d2c5a --- /dev/null +++ b/services/gateway/api/types/when.go @@ -0,0 +1,38 @@ +// Copyright 2019 Sorint.lab +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied +// See the License for the specific language governing permissions and +// limitations under the License. + +package types + +type When struct { + Branch *WhenConditions `json:"branch,omitempty"` + Tag *WhenConditions `json:"tag,omitempty"` + Ref *WhenConditions `json:"ref,omitempty"` +} + +type WhenConditions struct { + Include []WhenCondition `json:"include,omitempty"` + Exclude []WhenCondition `json:"exclude,omitempty"` +} + +type WhenConditionType string + +const ( + WhenConditionTypeSimple WhenConditionType = "simple" + WhenConditionTypeRegExp WhenConditionType = "regexp" +) + +type WhenCondition struct { + Type WhenConditionType `json:"type,omitempty"` + Match string `json:"match,omitempty"` +} diff --git a/internal/services/gateway/api/client.go b/services/gateway/client/client.go similarity index 76% rename from internal/services/gateway/api/client.go rename to services/gateway/client/client.go index 8d3715e..b2759ed 100644 --- a/internal/services/gateway/api/client.go +++ b/services/gateway/client/client.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package api +package client import ( "bytes" @@ -27,14 +27,13 @@ import ( "strconv" "strings" - cstypes "agola.io/agola/internal/services/configstore/types" + gwapitypes "agola.io/agola/services/gateway/api/types" errors "golang.org/x/xerrors" ) var jsonContent = http.Header{"Content-Type": []string{"application/json"}} -// Client represents a Gogs API client. type Client struct { url string client *http.Client @@ -111,37 +110,37 @@ func (c *Client) getParsedResponse(ctx context.Context, method, path string, que return resp, d.Decode(obj) } -func (c *Client) GetProjectGroup(ctx context.Context, projectGroupRef string) (*ProjectGroupResponse, *http.Response, error) { - projectGroup := new(ProjectGroupResponse) +func (c *Client) GetProjectGroup(ctx context.Context, projectGroupRef string) (*gwapitypes.ProjectGroupResponse, *http.Response, error) { + projectGroup := new(gwapitypes.ProjectGroupResponse) resp, err := c.getParsedResponse(ctx, "GET", fmt.Sprintf("/projectgroups/%s", url.PathEscape(projectGroupRef)), nil, jsonContent, nil, projectGroup) return projectGroup, resp, err } -func (c *Client) GetProjectGroupSubgroups(ctx context.Context, projectGroupRef string) ([]*ProjectGroupResponse, *http.Response, error) { - projectGroups := []*ProjectGroupResponse{} +func (c *Client) GetProjectGroupSubgroups(ctx context.Context, projectGroupRef string) ([]*gwapitypes.ProjectGroupResponse, *http.Response, error) { + projectGroups := []*gwapitypes.ProjectGroupResponse{} resp, err := c.getParsedResponse(ctx, "GET", fmt.Sprintf("/projectgroups/%s/subgroups", url.PathEscape(projectGroupRef)), nil, jsonContent, nil, &projectGroups) return projectGroups, resp, err } -func (c *Client) GetProjectGroupProjects(ctx context.Context, projectGroupRef string) ([]*ProjectResponse, *http.Response, error) { - projects := []*ProjectResponse{} +func (c *Client) GetProjectGroupProjects(ctx context.Context, projectGroupRef string) ([]*gwapitypes.ProjectResponse, *http.Response, error) { + projects := []*gwapitypes.ProjectResponse{} resp, err := c.getParsedResponse(ctx, "GET", fmt.Sprintf("/projectgroups/%s/projects", url.PathEscape(projectGroupRef)), nil, jsonContent, nil, &projects) return projects, resp, err } -func (c *Client) GetProject(ctx context.Context, projectRef string) (*ProjectResponse, *http.Response, error) { - project := new(ProjectResponse) +func (c *Client) GetProject(ctx context.Context, projectRef string) (*gwapitypes.ProjectResponse, *http.Response, error) { + project := new(gwapitypes.ProjectResponse) resp, err := c.getParsedResponse(ctx, "GET", fmt.Sprintf("/projects/%s", url.PathEscape(projectRef)), nil, jsonContent, nil, project) return project, resp, err } -func (c *Client) CreateProjectGroup(ctx context.Context, req *CreateProjectGroupRequest) (*ProjectResponse, *http.Response, error) { +func (c *Client) CreateProjectGroup(ctx context.Context, req *gwapitypes.CreateProjectGroupRequest) (*gwapitypes.ProjectResponse, *http.Response, error) { reqj, err := json.Marshal(req) if err != nil { return nil, nil, err } - project := new(ProjectResponse) + project := new(gwapitypes.ProjectResponse) resp, err := c.getParsedResponse(ctx, "POST", "/projectgroups", nil, jsonContent, bytes.NewReader(reqj), project) return project, resp, err } @@ -150,35 +149,35 @@ func (c *Client) DeleteProjectGroup(ctx context.Context, projectGroupRef string) return c.getResponse(ctx, "DELETE", fmt.Sprintf("/projectgroups/%s", url.PathEscape(projectGroupRef)), nil, jsonContent, nil) } -func (c *Client) CreateProject(ctx context.Context, req *CreateProjectRequest) (*ProjectResponse, *http.Response, error) { +func (c *Client) CreateProject(ctx context.Context, req *gwapitypes.CreateProjectRequest) (*gwapitypes.ProjectResponse, *http.Response, error) { reqj, err := json.Marshal(req) if err != nil { return nil, nil, err } - project := new(ProjectResponse) + project := new(gwapitypes.ProjectResponse) resp, err := c.getParsedResponse(ctx, "POST", "/projects", nil, jsonContent, bytes.NewReader(reqj), project) return project, resp, err } -func (c *Client) CreateProjectGroupSecret(ctx context.Context, projectGroupRef string, req *CreateSecretRequest) (*SecretResponse, *http.Response, error) { +func (c *Client) CreateProjectGroupSecret(ctx context.Context, projectGroupRef string, req *gwapitypes.CreateSecretRequest) (*gwapitypes.SecretResponse, *http.Response, error) { reqj, err := json.Marshal(req) if err != nil { return nil, nil, err } - secret := new(SecretResponse) + secret := new(gwapitypes.SecretResponse) resp, err := c.getParsedResponse(ctx, "POST", path.Join("/projectgroups", url.PathEscape(projectGroupRef), "secrets"), nil, jsonContent, bytes.NewReader(reqj), secret) return secret, resp, err } -func (c *Client) UpdateProjectGroupSecret(ctx context.Context, projectGroupRef, secretName string, req *UpdateSecretRequest) (*SecretResponse, *http.Response, error) { +func (c *Client) UpdateProjectGroupSecret(ctx context.Context, projectGroupRef, secretName string, req *gwapitypes.UpdateSecretRequest) (*gwapitypes.SecretResponse, *http.Response, error) { reqj, err := json.Marshal(req) if err != nil { return nil, nil, err } - secret := new(SecretResponse) + secret := new(gwapitypes.SecretResponse) resp, err := c.getParsedResponse(ctx, "PUT", path.Join("/projectgroups", url.PathEscape(projectGroupRef), "secrets", secretName), nil, jsonContent, bytes.NewReader(reqj), secret) return secret, resp, err } @@ -187,24 +186,24 @@ func (c *Client) DeleteProjectGroupSecret(ctx context.Context, projectGroupRef, return c.getResponse(ctx, "DELETE", path.Join("/projectgroups", url.PathEscape(projectGroupRef), "secrets", secretName), nil, jsonContent, nil) } -func (c *Client) CreateProjectSecret(ctx context.Context, projectRef string, req *CreateSecretRequest) (*SecretResponse, *http.Response, error) { +func (c *Client) CreateProjectSecret(ctx context.Context, projectRef string, req *gwapitypes.CreateSecretRequest) (*gwapitypes.SecretResponse, *http.Response, error) { reqj, err := json.Marshal(req) if err != nil { return nil, nil, err } - secret := new(SecretResponse) + secret := new(gwapitypes.SecretResponse) resp, err := c.getParsedResponse(ctx, "POST", path.Join("/projects", url.PathEscape(projectRef), "secrets"), nil, jsonContent, bytes.NewReader(reqj), secret) return secret, resp, err } -func (c *Client) UpdateProjectSecret(ctx context.Context, projectRef, secretName string, req *UpdateSecretRequest) (*SecretResponse, *http.Response, error) { +func (c *Client) UpdateProjectSecret(ctx context.Context, projectRef, secretName string, req *gwapitypes.UpdateSecretRequest) (*gwapitypes.SecretResponse, *http.Response, error) { reqj, err := json.Marshal(req) if err != nil { return nil, nil, err } - secret := new(SecretResponse) + secret := new(gwapitypes.SecretResponse) resp, err := c.getParsedResponse(ctx, "PUT", path.Join("/projects", url.PathEscape(projectRef), "secrets", secretName), nil, jsonContent, bytes.NewReader(reqj), secret) return secret, resp, err } @@ -213,24 +212,24 @@ func (c *Client) DeleteProjectSecret(ctx context.Context, projectRef, secretName return c.getResponse(ctx, "DELETE", path.Join("/projects", url.PathEscape(projectRef), "secrets", secretName), nil, jsonContent, nil) } -func (c *Client) CreateProjectGroupVariable(ctx context.Context, projectGroupRef string, req *CreateVariableRequest) (*VariableResponse, *http.Response, error) { +func (c *Client) CreateProjectGroupVariable(ctx context.Context, projectGroupRef string, req *gwapitypes.CreateVariableRequest) (*gwapitypes.VariableResponse, *http.Response, error) { reqj, err := json.Marshal(req) if err != nil { return nil, nil, err } - variable := new(VariableResponse) + variable := new(gwapitypes.VariableResponse) resp, err := c.getParsedResponse(ctx, "POST", path.Join("/projectgroups", url.PathEscape(projectGroupRef), "variables"), nil, jsonContent, bytes.NewReader(reqj), variable) return variable, resp, err } -func (c *Client) UpdateProjectGroupVariable(ctx context.Context, projectGroupRef, variableName string, req *UpdateVariableRequest) (*VariableResponse, *http.Response, error) { +func (c *Client) UpdateProjectGroupVariable(ctx context.Context, projectGroupRef, variableName string, req *gwapitypes.UpdateVariableRequest) (*gwapitypes.VariableResponse, *http.Response, error) { reqj, err := json.Marshal(req) if err != nil { return nil, nil, err } - variable := new(VariableResponse) + variable := new(gwapitypes.VariableResponse) resp, err := c.getParsedResponse(ctx, "PUT", path.Join("/projectgroups", url.PathEscape(projectGroupRef), "variables", variableName), nil, jsonContent, bytes.NewReader(reqj), variable) return variable, resp, err } @@ -239,24 +238,24 @@ func (c *Client) DeleteProjectGroupVariable(ctx context.Context, projectGroupRef return c.getResponse(ctx, "DELETE", path.Join("/projectgroups", url.PathEscape(projectGroupRef), "variables", variableName), nil, jsonContent, nil) } -func (c *Client) CreateProjectVariable(ctx context.Context, projectRef string, req *CreateVariableRequest) (*VariableResponse, *http.Response, error) { +func (c *Client) CreateProjectVariable(ctx context.Context, projectRef string, req *gwapitypes.CreateVariableRequest) (*gwapitypes.VariableResponse, *http.Response, error) { reqj, err := json.Marshal(req) if err != nil { return nil, nil, err } - variable := new(VariableResponse) + variable := new(gwapitypes.VariableResponse) resp, err := c.getParsedResponse(ctx, "POST", path.Join("/projects", url.PathEscape(projectRef), "variables"), nil, jsonContent, bytes.NewReader(reqj), variable) return variable, resp, err } -func (c *Client) UpdateProjectVariable(ctx context.Context, projectRef, variableName string, req *UpdateVariableRequest) (*VariableResponse, *http.Response, error) { +func (c *Client) UpdateProjectVariable(ctx context.Context, projectRef, variableName string, req *gwapitypes.UpdateVariableRequest) (*gwapitypes.VariableResponse, *http.Response, error) { reqj, err := json.Marshal(req) if err != nil { return nil, nil, err } - variable := new(VariableResponse) + variable := new(gwapitypes.VariableResponse) resp, err := c.getParsedResponse(ctx, "PUT", path.Join("/projects", url.PathEscape(projectRef), "variables", variableName), nil, jsonContent, bytes.NewReader(reqj), variable) return variable, resp, err } @@ -269,7 +268,7 @@ func (c *Client) DeleteProject(ctx context.Context, projectRef string) (*http.Re return c.getResponse(ctx, "DELETE", fmt.Sprintf("/projects/%s", url.PathEscape(projectRef)), nil, jsonContent, nil) } -func (c *Client) ProjectCreateRun(ctx context.Context, projectRef string, req *ProjectCreateRunRequest) (*http.Response, error) { +func (c *Client) ProjectCreateRun(ctx context.Context, projectRef string, req *gwapitypes.ProjectCreateRunRequest) (*http.Response, error) { reqj, err := json.Marshal(req) if err != nil { return nil, err @@ -282,19 +281,19 @@ func (c *Client) ReconfigProject(ctx context.Context, projectRef string) (*http. return c.getResponse(ctx, "PUT", fmt.Sprintf("/projects/%s/reconfig", url.PathEscape(projectRef)), nil, jsonContent, nil) } -func (c *Client) GetCurrentUser(ctx context.Context) (*UserResponse, *http.Response, error) { - user := new(UserResponse) +func (c *Client) GetCurrentUser(ctx context.Context) (*gwapitypes.UserResponse, *http.Response, error) { + user := new(gwapitypes.UserResponse) resp, err := c.getParsedResponse(ctx, "GET", "/user", nil, jsonContent, nil, user) return user, resp, err } -func (c *Client) GetUser(ctx context.Context, userRef string) (*UserResponse, *http.Response, error) { - user := new(UserResponse) +func (c *Client) GetUser(ctx context.Context, userRef string) (*gwapitypes.UserResponse, *http.Response, error) { + user := new(gwapitypes.UserResponse) resp, err := c.getParsedResponse(ctx, "GET", fmt.Sprintf("/users/%s", userRef), nil, jsonContent, nil, user) return user, resp, err } -func (c *Client) GetUsers(ctx context.Context, start string, limit int, asc bool) ([]*UserResponse, *http.Response, error) { +func (c *Client) GetUsers(ctx context.Context, start string, limit int, asc bool) ([]*gwapitypes.UserResponse, *http.Response, error) { q := url.Values{} if start != "" { q.Add("start", start) @@ -306,18 +305,18 @@ func (c *Client) GetUsers(ctx context.Context, start string, limit int, asc bool q.Add("asc", "") } - users := []*UserResponse{} + users := []*gwapitypes.UserResponse{} resp, err := c.getParsedResponse(ctx, "GET", "/users", q, jsonContent, nil, &users) return users, resp, err } -func (c *Client) CreateUser(ctx context.Context, req *CreateUserRequest) (*UserResponse, *http.Response, error) { +func (c *Client) CreateUser(ctx context.Context, req *gwapitypes.CreateUserRequest) (*gwapitypes.UserResponse, *http.Response, error) { reqj, err := json.Marshal(req) if err != nil { return nil, nil, err } - user := new(UserResponse) + user := new(gwapitypes.UserResponse) resp, err := c.getParsedResponse(ctx, "POST", "/users", nil, jsonContent, bytes.NewReader(reqj), user) return user, resp, err } @@ -326,7 +325,7 @@ func (c *Client) DeleteUser(ctx context.Context, userRef string) (*http.Response return c.getResponse(ctx, "DELETE", fmt.Sprintf("/users/%s", userRef), nil, jsonContent, nil) } -func (c *Client) UserCreateRun(ctx context.Context, req *UserCreateRunRequest) (*http.Response, error) { +func (c *Client) UserCreateRun(ctx context.Context, req *gwapitypes.UserCreateRunRequest) (*http.Response, error) { reqj, err := json.Marshal(req) if err != nil { return nil, err @@ -335,13 +334,13 @@ func (c *Client) UserCreateRun(ctx context.Context, req *UserCreateRunRequest) ( return c.getResponse(ctx, "POST", "/user/createrun", nil, jsonContent, bytes.NewReader(reqj)) } -func (c *Client) CreateUserLA(ctx context.Context, userRef string, req *CreateUserLARequest) (*CreateUserLAResponse, *http.Response, error) { +func (c *Client) CreateUserLA(ctx context.Context, userRef string, req *gwapitypes.CreateUserLARequest) (*gwapitypes.CreateUserLAResponse, *http.Response, error) { reqj, err := json.Marshal(req) if err != nil { return nil, nil, err } - la := new(CreateUserLAResponse) + la := new(gwapitypes.CreateUserLAResponse) resp, err := c.getParsedResponse(ctx, "POST", fmt.Sprintf("/users/%s/linkedaccounts", userRef), nil, jsonContent, bytes.NewReader(reqj), la) return la, resp, err } @@ -350,24 +349,24 @@ func (c *Client) DeleteUserLA(ctx context.Context, userRef, laID string) (*http. return c.getResponse(ctx, "DELETE", fmt.Sprintf("/users/%s/linkedaccounts/%s", userRef, laID), nil, jsonContent, nil) } -func (c *Client) RegisterUser(ctx context.Context, req *RegisterUserRequest) (*RegisterUserResponse, *http.Response, error) { +func (c *Client) RegisterUser(ctx context.Context, req *gwapitypes.RegisterUserRequest) (*gwapitypes.RegisterUserResponse, *http.Response, error) { reqj, err := json.Marshal(req) if err != nil { return nil, nil, err } - res := new(RegisterUserResponse) + res := new(gwapitypes.RegisterUserResponse) resp, err := c.getParsedResponse(ctx, "POST", "/register", nil, jsonContent, bytes.NewReader(reqj), res) return res, resp, err } -func (c *Client) CreateUserToken(ctx context.Context, userRef string, req *CreateUserTokenRequest) (*CreateUserTokenResponse, *http.Response, error) { +func (c *Client) CreateUserToken(ctx context.Context, userRef string, req *gwapitypes.CreateUserTokenRequest) (*gwapitypes.CreateUserTokenResponse, *http.Response, error) { reqj, err := json.Marshal(req) if err != nil { return nil, nil, err } - tresp := new(CreateUserTokenResponse) + tresp := new(gwapitypes.CreateUserTokenResponse) resp, err := c.getParsedResponse(ctx, "POST", fmt.Sprintf("/users/%s/tokens", userRef), nil, jsonContent, bytes.NewReader(reqj), tresp) return tresp, resp, err } @@ -376,13 +375,13 @@ func (c *Client) DeleteUserToken(ctx context.Context, userRef, tokenName string) return c.getResponse(ctx, "DELETE", fmt.Sprintf("/users/%s/tokens/%s", userRef, tokenName), nil, jsonContent, nil) } -func (c *Client) GetRun(ctx context.Context, runID string) (*RunResponse, *http.Response, error) { - run := new(RunResponse) +func (c *Client) GetRun(ctx context.Context, runID string) (*gwapitypes.RunResponse, *http.Response, error) { + run := new(gwapitypes.RunResponse) resp, err := c.getParsedResponse(ctx, "GET", fmt.Sprintf("/runs/%s", runID), nil, jsonContent, nil, run) return run, resp, err } -func (c *Client) GetRuns(ctx context.Context, phaseFilter, resultFilter, groups, runGroups []string, start string, limit int, asc bool) ([]*RunsResponse, *http.Response, error) { +func (c *Client) GetRuns(ctx context.Context, phaseFilter, resultFilter, groups, runGroups []string, start string, limit int, asc bool) ([]*gwapitypes.RunsResponse, *http.Response, error) { q := url.Values{} for _, phase := range phaseFilter { q.Add("phase", phase) @@ -406,18 +405,18 @@ func (c *Client) GetRuns(ctx context.Context, phaseFilter, resultFilter, groups, q.Add("asc", "") } - getRunsResponse := []*RunsResponse{} + getRunsResponse := []*gwapitypes.RunsResponse{} resp, err := c.getParsedResponse(ctx, "GET", "/runs", q, jsonContent, nil, &getRunsResponse) return getRunsResponse, resp, err } -func (c *Client) GetRemoteSource(ctx context.Context, rsRef string) (*RemoteSourceResponse, *http.Response, error) { - rs := new(RemoteSourceResponse) +func (c *Client) GetRemoteSource(ctx context.Context, rsRef string) (*gwapitypes.RemoteSourceResponse, *http.Response, error) { + rs := new(gwapitypes.RemoteSourceResponse) resp, err := c.getParsedResponse(ctx, "GET", fmt.Sprintf("/remotesources/%s", rsRef), nil, jsonContent, nil, rs) return rs, resp, err } -func (c *Client) GetRemoteSources(ctx context.Context, start string, limit int, asc bool) ([]*RemoteSourceResponse, *http.Response, error) { +func (c *Client) GetRemoteSources(ctx context.Context, start string, limit int, asc bool) ([]*gwapitypes.RemoteSourceResponse, *http.Response, error) { q := url.Values{} if start != "" { q.Add("start", start) @@ -429,29 +428,29 @@ func (c *Client) GetRemoteSources(ctx context.Context, start string, limit int, q.Add("asc", "") } - rss := []*RemoteSourceResponse{} + rss := []*gwapitypes.RemoteSourceResponse{} resp, err := c.getParsedResponse(ctx, "GET", "/remotesources", q, jsonContent, nil, &rss) return rss, resp, err } -func (c *Client) CreateRemoteSource(ctx context.Context, req *CreateRemoteSourceRequest) (*RemoteSourceResponse, *http.Response, error) { +func (c *Client) CreateRemoteSource(ctx context.Context, req *gwapitypes.CreateRemoteSourceRequest) (*gwapitypes.RemoteSourceResponse, *http.Response, error) { rsj, err := json.Marshal(req) if err != nil { return nil, nil, err } - rs := new(RemoteSourceResponse) + rs := new(gwapitypes.RemoteSourceResponse) resp, err := c.getParsedResponse(ctx, "POST", "/remotesources", nil, jsonContent, bytes.NewReader(rsj), rs) return rs, resp, err } -func (c *Client) UpdateRemoteSource(ctx context.Context, rsRef string, req *UpdateRemoteSourceRequest) (*RemoteSourceResponse, *http.Response, error) { +func (c *Client) UpdateRemoteSource(ctx context.Context, rsRef string, req *gwapitypes.UpdateRemoteSourceRequest) (*gwapitypes.RemoteSourceResponse, *http.Response, error) { rsj, err := json.Marshal(req) if err != nil { return nil, nil, err } - rs := new(RemoteSourceResponse) + rs := new(gwapitypes.RemoteSourceResponse) resp, err := c.getParsedResponse(ctx, "PUT", fmt.Sprintf("/remotesources/%s", rsRef), nil, jsonContent, bytes.NewReader(rsj), rs) return rs, resp, err } @@ -460,13 +459,13 @@ func (c *Client) DeleteRemoteSource(ctx context.Context, rsRef string) (*http.Re return c.getResponse(ctx, "DELETE", fmt.Sprintf("/remotesources/%s", rsRef), nil, jsonContent, nil) } -func (c *Client) CreateOrg(ctx context.Context, req *CreateOrgRequest) (*OrgResponse, *http.Response, error) { +func (c *Client) CreateOrg(ctx context.Context, req *gwapitypes.CreateOrgRequest) (*gwapitypes.OrgResponse, *http.Response, error) { reqj, err := json.Marshal(req) if err != nil { return nil, nil, err } - org := new(OrgResponse) + org := new(gwapitypes.OrgResponse) resp, err := c.getParsedResponse(ctx, "POST", "/orgs", nil, jsonContent, bytes.NewReader(reqj), org) return org, resp, err } @@ -475,8 +474,8 @@ func (c *Client) DeleteOrg(ctx context.Context, orgRef string) (*http.Response, return c.getResponse(ctx, "DELETE", fmt.Sprintf("/orgs/%s", orgRef), nil, jsonContent, nil) } -func (c *Client) AddOrgMember(ctx context.Context, orgRef, userRef string, role cstypes.MemberRole) (*AddOrgMemberResponse, *http.Response, error) { - req := &AddOrgMemberRequest{ +func (c *Client) AddOrgMember(ctx context.Context, orgRef, userRef string, role gwapitypes.MemberRole) (*gwapitypes.AddOrgMemberResponse, *http.Response, error) { + req := &gwapitypes.AddOrgMemberRequest{ Role: role, } omj, err := json.Marshal(req) @@ -484,7 +483,7 @@ func (c *Client) AddOrgMember(ctx context.Context, orgRef, userRef string, role return nil, nil, err } - res := new(AddOrgMemberResponse) + res := new(gwapitypes.AddOrgMemberResponse) resp, err := c.getParsedResponse(ctx, "PUT", fmt.Sprintf("/orgs/%s/members/%s", orgRef, userRef), nil, jsonContent, bytes.NewReader(omj), res) return res, resp, err } @@ -493,8 +492,8 @@ func (c *Client) RemoveOrgMember(ctx context.Context, orgRef, userRef string) (* return c.getResponse(ctx, "DELETE", fmt.Sprintf("/orgs/%s/members/%s", orgRef, userRef), nil, jsonContent, nil) } -func (c *Client) GetOrgMembers(ctx context.Context, orgRef string) (*OrgMembersResponse, *http.Response, error) { - res := &OrgMembersResponse{} +func (c *Client) GetOrgMembers(ctx context.Context, orgRef string) (*gwapitypes.OrgMembersResponse, *http.Response, error) { + res := &gwapitypes.OrgMembersResponse{} resp, err := c.getParsedResponse(ctx, "GET", fmt.Sprintf("/orgs/%s/members", orgRef), nil, jsonContent, nil, &res) return res, resp, err } diff --git a/services/runservice/api/types/run.go b/services/runservice/api/types/run.go new file mode 100644 index 0000000..90e09d1 --- /dev/null +++ b/services/runservice/api/types/run.go @@ -0,0 +1,82 @@ +// Copyright 2019 Sorint.lab +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied +// See the License for the specific language governing permissions and +// limitations under the License. + +package types + +import ( + rstypes "agola.io/agola/services/runservice/types" +) + +type RunResponse struct { + Run *rstypes.Run `json:"run"` + RunConfig *rstypes.RunConfig `json:"run_config"` + ChangeGroupsUpdateToken string `json:"change_groups_update_tokens"` +} + +type GetRunsResponse struct { + Runs []*rstypes.Run `json:"runs"` + ChangeGroupsUpdateToken string `json:"change_groups_update_tokens"` +} + +type RunCreateRequest struct { + // new run fields + RunConfigTasks map[string]*rstypes.RunConfigTask `json:"run_config_tasks"` + Name string `json:"name"` + Group string `json:"group"` + SetupErrors []string `json:"setup_errors"` + StaticEnvironment map[string]string `json:"static_environment"` + CacheGroup string `json:"cache_group"` + + // existing run fields + RunID string `json:"run_id"` + FromStart bool `json:"from_start"` + ResetTasks []string `json:"reset_tasks"` + + // common fields + Environment map[string]string `json:"environment"` + Annotations map[string]string `json:"annotations"` + + ChangeGroupsUpdateToken string `json:"changeup_update_tokens"` +} + +type RunActionType string + +const ( + RunActionTypeChangePhase RunActionType = "changephase" + RunActionTypeStop RunActionType = "stop" +) + +type RunActionsRequest struct { + ActionType RunActionType `json:"action_type"` + + Phase rstypes.RunPhase `json:"phase"` + ChangeGroupsUpdateToken string `json:"change_groups_update_tokens"` +} + +type RunTaskActionType string + +const ( + RunTaskActionTypeSetAnnotations RunTaskActionType = "setannotations" + RunTaskActionTypeApprove RunTaskActionType = "approve" +) + +type RunTaskActionsRequest struct { + ActionType RunTaskActionType `json:"action_type"` + + // set Annotations fields + Annotations map[string]string `json:"annotations,omitempty"` + + // global fields + ChangeGroupsUpdateToken string `json:"change_groups_update_tokens"` +} diff --git a/internal/services/runservice/api/client.go b/services/runservice/client/client.go similarity index 85% rename from internal/services/runservice/api/client.go rename to services/runservice/client/client.go index a1e1695..0e0331c 100644 --- a/internal/services/runservice/api/client.go +++ b/services/runservice/client/client.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package api +package client import ( "bytes" @@ -26,13 +26,13 @@ import ( "strconv" "strings" - rstypes "agola.io/agola/internal/services/runservice/types" + rsapitypes "agola.io/agola/services/runservice/api/types" + rstypes "agola.io/agola/services/runservice/types" errors "golang.org/x/xerrors" ) var jsonContent = http.Header{"Content-Type": []string{"application/json"}} -// Client represents a Gogs API client. type Client struct { url string client *http.Client @@ -165,7 +165,7 @@ func (c *Client) PutCache(ctx context.Context, key string, size int64, r io.Read return c.getResponse(ctx, "POST", fmt.Sprintf("/executor/caches/%s", url.PathEscape(key)), nil, size, nil, r) } -func (c *Client) GetRuns(ctx context.Context, phaseFilter, resultFilter, groups []string, lastRun bool, changeGroups []string, start string, limit int, asc bool) (*GetRunsResponse, *http.Response, error) { +func (c *Client) GetRuns(ctx context.Context, phaseFilter, resultFilter, groups []string, lastRun bool, changeGroups []string, start string, limit int, asc bool) (*rsapitypes.GetRunsResponse, *http.Response, error) { q := url.Values{} for _, phase := range phaseFilter { q.Add("phase", phase) @@ -192,47 +192,47 @@ func (c *Client) GetRuns(ctx context.Context, phaseFilter, resultFilter, groups q.Add("asc", "") } - getRunsResponse := new(GetRunsResponse) + getRunsResponse := new(rsapitypes.GetRunsResponse) resp, err := c.getParsedResponse(ctx, "GET", "/runs", q, jsonContent, nil, getRunsResponse) return getRunsResponse, resp, err } -func (c *Client) GetQueuedRuns(ctx context.Context, start string, limit int, changeGroups []string) (*GetRunsResponse, *http.Response, error) { +func (c *Client) GetQueuedRuns(ctx context.Context, start string, limit int, changeGroups []string) (*rsapitypes.GetRunsResponse, *http.Response, error) { return c.GetRuns(ctx, []string{"queued"}, nil, []string{}, false, changeGroups, start, limit, true) } -func (c *Client) GetRunningRuns(ctx context.Context, start string, limit int, changeGroups []string) (*GetRunsResponse, *http.Response, error) { +func (c *Client) GetRunningRuns(ctx context.Context, start string, limit int, changeGroups []string) (*rsapitypes.GetRunsResponse, *http.Response, error) { return c.GetRuns(ctx, []string{"running"}, nil, []string{}, false, changeGroups, start, limit, true) } -func (c *Client) GetGroupQueuedRuns(ctx context.Context, group string, limit int, changeGroups []string) (*GetRunsResponse, *http.Response, error) { +func (c *Client) GetGroupQueuedRuns(ctx context.Context, group string, limit int, changeGroups []string) (*rsapitypes.GetRunsResponse, *http.Response, error) { return c.GetRuns(ctx, []string{"queued"}, nil, []string{group}, false, changeGroups, "", limit, false) } -func (c *Client) GetGroupRunningRuns(ctx context.Context, group string, limit int, changeGroups []string) (*GetRunsResponse, *http.Response, error) { +func (c *Client) GetGroupRunningRuns(ctx context.Context, group string, limit int, changeGroups []string) (*rsapitypes.GetRunsResponse, *http.Response, error) { return c.GetRuns(ctx, []string{"running"}, nil, []string{group}, false, changeGroups, "", limit, false) } -func (c *Client) GetGroupFirstQueuedRuns(ctx context.Context, group string, changeGroups []string) (*GetRunsResponse, *http.Response, error) { +func (c *Client) GetGroupFirstQueuedRuns(ctx context.Context, group string, changeGroups []string) (*rsapitypes.GetRunsResponse, *http.Response, error) { return c.GetRuns(ctx, []string{"queued"}, nil, []string{group}, false, changeGroups, "", 1, true) } -func (c *Client) GetGroupLastRun(ctx context.Context, group string, changeGroups []string) (*GetRunsResponse, *http.Response, error) { +func (c *Client) GetGroupLastRun(ctx context.Context, group string, changeGroups []string) (*rsapitypes.GetRunsResponse, *http.Response, error) { return c.GetRuns(ctx, nil, nil, []string{group}, false, changeGroups, "", 1, false) } -func (c *Client) CreateRun(ctx context.Context, req *RunCreateRequest) (*RunResponse, *http.Response, error) { +func (c *Client) CreateRun(ctx context.Context, req *rsapitypes.RunCreateRequest) (*rsapitypes.RunResponse, *http.Response, error) { reqj, err := json.Marshal(req) if err != nil { return nil, nil, err } - res := new(RunResponse) + res := new(rsapitypes.RunResponse) resp, err := c.getParsedResponse(ctx, "POST", "/runs", nil, jsonContent, bytes.NewReader(reqj), res) return res, resp, err } -func (c *Client) RunActions(ctx context.Context, runID string, req *RunActionsRequest) (*http.Response, error) { +func (c *Client) RunActions(ctx context.Context, runID string, req *rsapitypes.RunActionsRequest) (*http.Response, error) { reqj, err := json.Marshal(req) if err != nil { return nil, err @@ -241,8 +241,8 @@ func (c *Client) RunActions(ctx context.Context, runID string, req *RunActionsRe } func (c *Client) StartRun(ctx context.Context, runID string, changeGroupsUpdateToken string) (*http.Response, error) { - req := &RunActionsRequest{ - ActionType: RunActionTypeChangePhase, + req := &rsapitypes.RunActionsRequest{ + ActionType: rsapitypes.RunActionTypeChangePhase, Phase: rstypes.RunPhaseRunning, ChangeGroupsUpdateToken: changeGroupsUpdateToken, } @@ -250,7 +250,7 @@ func (c *Client) StartRun(ctx context.Context, runID string, changeGroupsUpdateT return c.RunActions(ctx, runID, req) } -func (c *Client) RunTaskActions(ctx context.Context, runID, taskID string, req *RunTaskActionsRequest) (*http.Response, error) { +func (c *Client) RunTaskActions(ctx context.Context, runID, taskID string, req *rsapitypes.RunTaskActionsRequest) (*http.Response, error) { reqj, err := json.Marshal(req) if err != nil { return nil, err @@ -259,8 +259,8 @@ func (c *Client) RunTaskActions(ctx context.Context, runID, taskID string, req * } func (c *Client) RunTaskSetAnnotations(ctx context.Context, runID, taskID string, annotations map[string]string, changeGroupsUpdateToken string) (*http.Response, error) { - req := &RunTaskActionsRequest{ - ActionType: RunTaskActionTypeSetAnnotations, + req := &rsapitypes.RunTaskActionsRequest{ + ActionType: rsapitypes.RunTaskActionTypeSetAnnotations, Annotations: annotations, ChangeGroupsUpdateToken: changeGroupsUpdateToken, } @@ -269,21 +269,21 @@ func (c *Client) RunTaskSetAnnotations(ctx context.Context, runID, taskID string } func (c *Client) ApproveRunTask(ctx context.Context, runID, taskID string, changeGroupsUpdateToken string) (*http.Response, error) { - req := &RunTaskActionsRequest{ - ActionType: RunTaskActionTypeApprove, + req := &rsapitypes.RunTaskActionsRequest{ + ActionType: rsapitypes.RunTaskActionTypeApprove, ChangeGroupsUpdateToken: changeGroupsUpdateToken, } return c.RunTaskActions(ctx, runID, taskID, req) } -func (c *Client) GetRun(ctx context.Context, runID string, changeGroups []string) (*RunResponse, *http.Response, error) { +func (c *Client) GetRun(ctx context.Context, runID string, changeGroups []string) (*rsapitypes.RunResponse, *http.Response, error) { q := url.Values{} for _, changeGroup := range changeGroups { q.Add("changegroup", changeGroup) } - runResponse := new(RunResponse) + runResponse := new(rsapitypes.RunResponse) resp, err := c.getParsedResponse(ctx, "GET", fmt.Sprintf("/runs/%s", runID), q, jsonContent, nil, runResponse) return runResponse, resp, err } diff --git a/internal/services/runservice/types/types.go b/services/runservice/types/types.go similarity index 98% rename from internal/services/runservice/types/types.go rename to services/runservice/types/types.go index 1420449..b6a51e5 100644 --- a/internal/services/runservice/types/types.go +++ b/services/runservice/types/types.go @@ -20,8 +20,9 @@ import ( "fmt" "time" - "agola.io/agola/internal/common" - "agola.io/agola/internal/util" + "agola.io/agola/services/types" + "agola.io/agola/util" + "github.com/mitchellh/copystructure" ) @@ -393,7 +394,7 @@ type DockerRegistryAuth struct { type Runtime struct { Type RuntimeType `json:"type,omitempty"` - Arch common.Arch `json:"arch,omitempty"` + Arch types.Arch `json:"arch,omitempty"` Containers []*Container `json:"containers,omitempty"` } @@ -463,7 +464,7 @@ type ExecutorTask struct { ID string `json:"id,omitempty"` RunID string `json:"run_id,omitempty"` TaskName string `json:"task_name,omitempty"` - Arch common.Arch `json:"arch,omitempty"` + Arch types.Arch `json:"arch,omitempty"` Containers []*Container `json:"containers,omitempty"` Environment map[string]string `json:"environment,omitempty"` WorkingDir string `json:"working_dir,omitempty"` @@ -612,7 +613,7 @@ type Executor struct { ID string `json:"id,omitempty"` ListenURL string `json:"listenURL,omitempty"` - Archs []common.Arch `json:"archs,omitempty"` + Archs []types.Arch `json:"archs,omitempty"` Labels map[string]string `json:"labels,omitempty"` diff --git a/internal/common/arch.go b/services/types/arch.go similarity index 98% rename from internal/common/arch.go rename to services/types/arch.go index 590b829..34eae00 100644 --- a/internal/common/arch.go +++ b/services/types/arch.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package common +package types type Arch string diff --git a/tests/setup_test.go b/tests/setup_test.go index 86bf79f..512d220 100644 --- a/tests/setup_test.go +++ b/tests/setup_test.go @@ -28,17 +28,17 @@ import ( slog "agola.io/agola/internal/log" "agola.io/agola/internal/services/config" "agola.io/agola/internal/services/configstore" - cstypes "agola.io/agola/internal/services/configstore/types" "agola.io/agola/internal/services/executor" "agola.io/agola/internal/services/gateway" - gwapi "agola.io/agola/internal/services/gateway/api" "agola.io/agola/internal/services/gitserver" "agola.io/agola/internal/services/notification" rsscheduler "agola.io/agola/internal/services/runservice" - rstypes "agola.io/agola/internal/services/runservice/types" "agola.io/agola/internal/services/scheduler" "agola.io/agola/internal/testutil" "agola.io/agola/internal/util" + gwapitypes "agola.io/agola/services/gateway/api/types" + gwclient "agola.io/agola/services/gateway/client" + rstypes "agola.io/agola/services/runservice/types" gtypes "code.gitea.io/gitea/modules/structs" "code.gitea.io/sdk/gitea" @@ -348,20 +348,20 @@ func createLinkedAccount(ctx context.Context, t *testing.T, tgitea *testutil.Tes } t.Logf("created gitea user token: %s", giteaToken.Token) - gwClient := gwapi.NewClient(c.Gateway.APIExposedURL, "admintoken") - user, _, err := gwClient.CreateUser(ctx, &gwapi.CreateUserRequest{UserName: agolaUser01}) + gwClient := gwclient.NewClient(c.Gateway.APIExposedURL, "admintoken") + user, _, err := gwClient.CreateUser(ctx, &gwapitypes.CreateUserRequest{UserName: agolaUser01}) if err != nil { t.Fatalf("unexpected err: %v", err) } t.Logf("created agola user: %s", user.UserName) - token, _, err := gwClient.CreateUserToken(ctx, agolaUser01, &gwapi.CreateUserTokenRequest{TokenName: "token01"}) + token, _, err := gwClient.CreateUserToken(ctx, agolaUser01, &gwapitypes.CreateUserTokenRequest{TokenName: "token01"}) if err != nil { t.Fatalf("unexpected err: %v", err) } t.Logf("created agola user token: %s", token.Token) - rs, _, err := gwClient.CreateRemoteSource(ctx, &gwapi.CreateRemoteSourceRequest{ + rs, _, err := gwClient.CreateRemoteSource(ctx, &gwapitypes.CreateRemoteSourceRequest{ Name: "gitea", APIURL: giteaAPIURL, Type: "gitea", @@ -374,9 +374,9 @@ func createLinkedAccount(ctx context.Context, t *testing.T, tgitea *testutil.Tes t.Logf("created agola remote source: %s", rs.Name) // From now use the user token - gwClient = gwapi.NewClient(c.Gateway.APIExposedURL, token.Token) + gwClient = gwclient.NewClient(c.Gateway.APIExposedURL, token.Token) - la, _, err := gwClient.CreateUserLA(ctx, agolaUser01, &gwapi.CreateUserLARequest{ + la, _, err := gwClient.CreateUserLA(ctx, agolaUser01, &gwapitypes.CreateUserLARequest{ RemoteSourceName: "gitea", RemoteSourceLoginName: giteaUser01, RemoteSourceLoginPassword: "password", @@ -408,12 +408,12 @@ func TestCreateProject(t *testing.T) { giteaToken, token := createLinkedAccount(ctx, t, tgitea, c) giteaClient := gitea.NewClient(giteaAPIURL, giteaToken) - gwClient := gwapi.NewClient(c.Gateway.APIExposedURL, token) + gwClient := gwclient.NewClient(c.Gateway.APIExposedURL, token) createProject(ctx, t, giteaClient, gwClient) } -func createProject(ctx context.Context, t *testing.T, giteaClient *gitea.Client, gwClient *gwapi.Client) (*gtypes.Repository, *gwapi.ProjectResponse) { +func createProject(ctx context.Context, t *testing.T, giteaClient *gitea.Client, gwClient *gwclient.Client) (*gtypes.Repository, *gwapitypes.ProjectResponse) { giteaRepo, err := giteaClient.CreateRepo(gtypes.CreateRepoOption{ Name: "repo01", }) @@ -422,12 +422,12 @@ func createProject(ctx context.Context, t *testing.T, giteaClient *gitea.Client, } t.Logf("created gitea repo: %s", giteaRepo.Name) - project, _, err := gwClient.CreateProject(ctx, &gwapi.CreateProjectRequest{ + project, _, err := gwClient.CreateProject(ctx, &gwapitypes.CreateProjectRequest{ Name: "project01", ParentRef: path.Join("user", agolaUser01), RemoteSourceName: "gitea", RepoPath: path.Join(giteaUser01, "repo01"), - Visibility: cstypes.VisibilityPublic, + Visibility: gwapitypes.VisibilityPublic, }) if err != nil { t.Fatalf("unexpected err: %v", err) @@ -455,7 +455,7 @@ func TestRun(t *testing.T) { giteaToken, token := createLinkedAccount(ctx, t, tgitea, c) giteaClient := gitea.NewClient(giteaAPIURL, giteaToken) - gwClient := gwapi.NewClient(c.Gateway.APIExposedURL, token) + gwClient := gwclient.NewClient(c.Gateway.APIExposedURL, token) giteaRepo, project := createProject(ctx, t, giteaClient, gwClient) @@ -479,7 +479,7 @@ func TestRun(t *testing.T) { }, ], }, - steps: [ + steps: [ { type: 'run', command: 'env' }, ], }, diff --git a/util/pointer.go b/util/pointer.go new file mode 100644 index 0000000..9a04c85 --- /dev/null +++ b/util/pointer.go @@ -0,0 +1,47 @@ +// Copyright 2019 Sorint.lab +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied +// See the License for the specific language governing permissions and +// limitations under the License. + +package util + +import "time" + +func BoolP(b bool) *bool { return &b } + +func ByteP(b byte) *byte { return &b } + +func StringP(s string) *string { return &s } + +func IntP(i int) *int { return &i } + +func Int8P(i int8) *int8 { return &i } + +func Int16P(i int16) *int16 { return &i } + +func Int32P(i int32) *int32 { return &i } + +func Int64P(i int64) *int64 { return &i } + +func UintP(u uint) *uint { return &u } + +func Uint16P(u uint16) *uint16 { return &u } + +func Uint32P(u uint32) *uint32 { return &u } + +func Uint64P(u uint64) *uint64 { return &u } + +func Uint8P(u uint8) *uint8 { return &u } + +func TimeP(t time.Time) *time.Time { return &t } + +func DurationP(d time.Duration) *time.Duration { return &d }