From 5ce7577bba6f5636d605c9029b65346c60fda941 Mon Sep 17 00:00:00 2001 From: Avdhesh Kumar Date: Wed, 19 Jul 2023 15:16:14 +0530 Subject: [PATCH 1/9] add core functions --- pkg/pipeline/CiCdPipelineOrchestrator.go | 56 +++++++++++++++++++++++- 1 file changed, 55 insertions(+), 1 deletion(-) diff --git a/pkg/pipeline/CiCdPipelineOrchestrator.go b/pkg/pipeline/CiCdPipelineOrchestrator.go index 1b89119c0c5..39bb2d86df3 100644 --- a/pkg/pipeline/CiCdPipelineOrchestrator.go +++ b/pkg/pipeline/CiCdPipelineOrchestrator.go @@ -160,13 +160,67 @@ func NewCiCdPipelineOrchestrator( const BEFORE_DOCKER_BUILD string = "BEFORE_DOCKER_BUILD" const AFTER_DOCKER_BUILD string = "AFTER_DOCKER_BUILD" +func (impl CiCdPipelineOrchestratorImpl) PatchCiMaterialSource(ciPipeline *bean.CiPipeline, userId int32) (*bean.CiPipeline, error) { + oldPipeline, err := impl.ciPipelineRepository.FindById(ciPipeline.Id) + if err != nil { + return nil, err + } + materialsUpdate := mapCiMaterialToPipelineMaterial(ciPipeline, userId, oldPipeline) + if err = impl.saveUpdatedMaterial(materialsUpdate); err != nil { + return nil, err + } + return ciPipeline, nil +} + +func mapCiMaterialToPipelineMaterial(ciPipeline *bean.CiPipeline, userId int32, oldPipeline *pipelineConfig.CiPipeline) []*pipelineConfig.CiPipelineMaterial { + createOnTimeMap := make(map[int]time.Time) + createByMap := make(map[int]int32) + materialsUpdate := make([]*pipelineConfig.CiPipelineMaterial, 0) + for _, oldMaterial := range oldPipeline.CiPipelineMaterials { + createOnTimeMap[oldMaterial.GitMaterialId] = oldMaterial.CreatedOn + createByMap[oldMaterial.GitMaterialId] = oldMaterial.CreatedBy + } + for _, ciMaterial := range ciPipeline.CiMaterial { + pipelineMaterial := &pipelineConfig.CiPipelineMaterial{ + Id: ciMaterial.Id, + CiPipelineId: ciPipeline.Id, + Value: ciMaterial.Source.Value, + Type: ciMaterial.Source.Type, + Active: oldPipeline.Active, + Regex: ciMaterial.Source.Regex, + GitMaterialId: ciMaterial.GitMaterialId, + AuditLog: sql.AuditLog{UpdatedBy: userId, UpdatedOn: time.Now(), CreatedBy: createByMap[ciMaterial.GitMaterialId], CreatedOn: createOnTimeMap[ciMaterial.GitMaterialId]}, + } + pipelineMaterial.CiPipelineId = ciMaterial.Id + materialsUpdate = append(materialsUpdate, pipelineMaterial) + } + return materialsUpdate +} + +func (impl CiCdPipelineOrchestratorImpl) saveUpdatedMaterial(materialsUpdate []*pipelineConfig.CiPipelineMaterial) error { + dbConnection := impl.pipelineRepository.GetConnection() + tx, err := dbConnection.Begin() + if err != nil { + return err + } + defer tx.Rollback() + if err = impl.ciPipelineMaterialRepository.Update(tx, materialsUpdate...); err != nil { + return err + } + if err = impl.AddPipelineMaterialInGitSensor(materialsUpdate); err != nil { + return err + } + if err = tx.Commit(); err != nil { + return err + } + return nil +} func (impl CiCdPipelineOrchestratorImpl) PatchMaterialValue(createRequest *bean.CiPipeline, userId int32, oldPipeline *pipelineConfig.CiPipeline) (*bean.CiPipeline, error) { argByte, err := json.Marshal(createRequest.DockerArgs) if err != nil { impl.logger.Error(err) return nil, err } - dbConnection := impl.pipelineRepository.GetConnection() tx, err := dbConnection.Begin() if err != nil { From fb77e5f7e779f8b1ee734dfbfdb76eae8944ea99 Mon Sep 17 00:00:00 2001 From: Avdhesh Kumar Date: Wed, 19 Jul 2023 18:27:13 +0530 Subject: [PATCH 2/9] added the branch change API --- .../app/BuildPipelineRestHandler.go | 64 +++ api/router/PipelineConfigRouter.go | 1 + client/gitSensor/mocks/GitSensorClient.go | 242 ++++++++++ go.mod | 3 + go.sum | 6 + .../mocks/CiPipelineMaterial.go | 212 +++++++++ pkg/pipeline/CiCdPipelineOrchestrator.go | 1 + pkg/pipeline/CiCdPipelineOrchestrator_test.go | 77 ++- pkg/pipeline/PipelineBuilder.go | 5 + vendor/github.com/golang/mock/AUTHORS | 12 + vendor/github.com/golang/mock/CONTRIBUTORS | 37 ++ vendor/github.com/golang/mock/LICENSE | 202 ++++++++ vendor/github.com/golang/mock/gomock/call.go | 445 ++++++++++++++++++ .../github.com/golang/mock/gomock/callset.go | 113 +++++ .../golang/mock/gomock/controller.go | 336 +++++++++++++ .../github.com/golang/mock/gomock/matchers.go | 341 ++++++++++++++ vendor/modules.txt | 7 + 17 files changed, 2100 insertions(+), 4 deletions(-) create mode 100644 client/gitSensor/mocks/GitSensorClient.go create mode 100644 internal/sql/repository/pipelineConfig/mocks/CiPipelineMaterial.go create mode 100644 vendor/github.com/golang/mock/AUTHORS create mode 100644 vendor/github.com/golang/mock/CONTRIBUTORS create mode 100644 vendor/github.com/golang/mock/LICENSE create mode 100644 vendor/github.com/golang/mock/gomock/call.go create mode 100644 vendor/github.com/golang/mock/gomock/callset.go create mode 100644 vendor/github.com/golang/mock/gomock/controller.go create mode 100644 vendor/github.com/golang/mock/gomock/matchers.go diff --git a/api/restHandler/app/BuildPipelineRestHandler.go b/api/restHandler/app/BuildPipelineRestHandler.go index 89b37336453..3324fbd9877 100644 --- a/api/restHandler/app/BuildPipelineRestHandler.go +++ b/api/restHandler/app/BuildPipelineRestHandler.go @@ -43,6 +43,7 @@ type DevtronAppBuildRestHandler interface { GetExternalCi(w http.ResponseWriter, r *http.Request) GetExternalCiById(w http.ResponseWriter, r *http.Request) PatchCiPipelines(w http.ResponseWriter, r *http.Request) + PatchCiPipelinesSource(w http.ResponseWriter, r *http.Request) TriggerCiPipeline(w http.ResponseWriter, r *http.Request) GetCiPipelineMin(w http.ResponseWriter, r *http.Request) GetCIPipelineById(w http.ResponseWriter, r *http.Request) @@ -230,6 +231,69 @@ func (handler PipelineConfigRestHandlerImpl) UpdateBranchCiPipelinesWithRegex(w common.WriteJsonResp(w, err, resp, http.StatusOK) } +func (handler PipelineConfigRestHandlerImpl) parseBranchChangeRequest(w http.ResponseWriter, r *http.Request) (*bean.CiPipeline, int32, error) { + decoder := json.NewDecoder(r.Body) + userId, err := handler.userAuthService.GetLoggedInUser(r) + if userId == 0 || err != nil { + common.WriteJsonResp(w, err, "Unauthorized User", http.StatusUnauthorized) + return nil, 0, err + } + + var patchRequest bean.CiPipeline + err = decoder.Decode(&patchRequest) + + if err != nil { + handler.Logger.Errorw("request err, PatchCiPipelines", "err", err, "PatchCiPipelines", patchRequest) + common.WriteJsonResp(w, err, nil, http.StatusBadRequest) + return nil, 0, err + } + return &patchRequest, userId, nil +} + +func (handler PipelineConfigRestHandlerImpl) authorizeBranchChangeRequest(w http.ResponseWriter, userId int32, patchRequest *bean.CiPipeline, token string) error { + isSuperAdmin, err := handler.userAuthService.IsSuperAdmin(int(userId)) + if err != nil { + common.WriteJsonResp(w, err, "failed to check if user is super admin", http.StatusInternalServerError) + return err + } + handler.Logger.Debugw("update request ", "req", patchRequest) + app, err := handler.pipelineBuilder.GetApp(patchRequest.AppId) + if err != nil { + common.WriteJsonResp(w, err, nil, http.StatusBadRequest) + return err + } + resourceName := handler.enforcerUtil.GetAppRBACName(app.AppName) + var ok bool + if app.AppType == helper.Job { + ok = isSuperAdmin + } else { + ok = handler.enforcer.Enforce(token, casbin.ResourceApplications, casbin.ActionCreate, resourceName) + } + if !ok { + common.WriteJsonResp(w, fmt.Errorf("unauthorized user"), "Unauthorized User", http.StatusForbidden) + return err + } + return nil +} + +func (handler PipelineConfigRestHandlerImpl) PatchCiPipelinesSource(w http.ResponseWriter, r *http.Request) { + patchRequest, userId, err := handler.parseBranchChangeRequest(w, r) + if err != nil { + return + } + token := r.Header.Get("token") + if err = handler.authorizeBranchChangeRequest(w, userId, patchRequest, token); err != nil { + return + } + createResp, err := handler.pipelineBuilder.PatchCiMaterialSource(patchRequest, userId) + if err != nil { + handler.Logger.Errorw("service err, PatchCiPipelines", "err", err, "PatchCiPipelines", patchRequest) + common.WriteJsonResp(w, err, nil, http.StatusInternalServerError) + return + } + common.WriteJsonResp(w, err, createResp, http.StatusOK) +} + func (handler PipelineConfigRestHandlerImpl) PatchCiPipelines(w http.ResponseWriter, r *http.Request) { decoder := json.NewDecoder(r.Body) userId, err := handler.userAuthService.GetLoggedInUser(r) diff --git a/api/router/PipelineConfigRouter.go b/api/router/PipelineConfigRouter.go index bad95d2735a..13fc3803cef 100644 --- a/api/router/PipelineConfigRouter.go +++ b/api/router/PipelineConfigRouter.go @@ -85,6 +85,7 @@ func (router PipelineConfigRouterImpl) initPipelineConfigRouter(configRouter *mu configRouter.Path("/external-ci/{appId}/{externalCiId}").HandlerFunc(router.restHandler.GetExternalCiById).Methods("GET") configRouter.Path("/ci-pipeline/template/patch").HandlerFunc(router.restHandler.UpdateCiTemplate).Methods("POST") configRouter.Path("/ci-pipeline/patch").HandlerFunc(router.restHandler.PatchCiPipelines).Methods("POST") + configRouter.Path("/ci-pipeline/patch-branch").HandlerFunc(router.restHandler.PatchCiPipelinesSource).Methods("PATCH") configRouter.Path("/ci-pipeline/patch/regex").HandlerFunc(router.restHandler.UpdateBranchCiPipelinesWithRegex).Methods("POST") configRouter.Path("/cd-pipeline/{cd_pipeline_id}/material").HandlerFunc(router.restHandler.GetArtifactsByCDPipeline).Methods("GET") diff --git a/client/gitSensor/mocks/GitSensorClient.go b/client/gitSensor/mocks/GitSensorClient.go new file mode 100644 index 00000000000..3eb3e2e9a57 --- /dev/null +++ b/client/gitSensor/mocks/GitSensorClient.go @@ -0,0 +1,242 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: client/gitSensor/GitSensorClient.go + +// Package mock_gitSensor is a generated GoMock package. +package mock_gitSensor + +import ( + context "context" + reflect "reflect" + + gitSensor "github.com/devtron-labs/devtron/client/gitSensor" + gomock "github.com/golang/mock/gomock" +) + +// MockClient is a mock of Client interface. +type MockClient struct { + ctrl *gomock.Controller + recorder *MockClientMockRecorder +} + +// MockClientMockRecorder is the mock recorder for MockClient. +type MockClientMockRecorder struct { + mock *MockClient +} + +// NewMockClient creates a new mock instance. +func NewMockClient(ctrl *gomock.Controller) *MockClient { + mock := &MockClient{ctrl: ctrl} + mock.recorder = &MockClientMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockClient) EXPECT() *MockClientMockRecorder { + return m.recorder +} + +// AddRepo mocks base method. +func (m *MockClient) AddRepo(ctx context.Context, materials []*gitSensor.GitMaterial) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "AddRepo", ctx, materials) + ret0, _ := ret[0].(error) + return ret0 +} + +// AddRepo indicates an expected call of AddRepo. +func (mr *MockClientMockRecorder) AddRepo(ctx, materials interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddRepo", reflect.TypeOf((*MockClient)(nil).AddRepo), ctx, materials) +} + +// FetchChanges mocks base method. +func (m *MockClient) FetchChanges(ctx context.Context, req *gitSensor.FetchScmChangesRequest) (*gitSensor.MaterialChangeResp, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "FetchChanges", ctx, req) + ret0, _ := ret[0].(*gitSensor.MaterialChangeResp) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// FetchChanges indicates an expected call of FetchChanges. +func (mr *MockClientMockRecorder) FetchChanges(ctx, req interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FetchChanges", reflect.TypeOf((*MockClient)(nil).FetchChanges), ctx, req) +} + +// GetAllWebhookEventConfigForHost mocks base method. +func (m *MockClient) GetAllWebhookEventConfigForHost(ctx context.Context, req *gitSensor.WebhookEventConfigRequest) ([]*gitSensor.WebhookEventConfig, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetAllWebhookEventConfigForHost", ctx, req) + ret0, _ := ret[0].([]*gitSensor.WebhookEventConfig) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetAllWebhookEventConfigForHost indicates an expected call of GetAllWebhookEventConfigForHost. +func (mr *MockClientMockRecorder) GetAllWebhookEventConfigForHost(ctx, req interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAllWebhookEventConfigForHost", reflect.TypeOf((*MockClient)(nil).GetAllWebhookEventConfigForHost), ctx, req) +} + +// GetCommitMetadata mocks base method. +func (m *MockClient) GetCommitMetadata(ctx context.Context, req *gitSensor.CommitMetadataRequest) (*gitSensor.GitCommit, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetCommitMetadata", ctx, req) + ret0, _ := ret[0].(*gitSensor.GitCommit) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetCommitMetadata indicates an expected call of GetCommitMetadata. +func (mr *MockClientMockRecorder) GetCommitMetadata(ctx, req interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCommitMetadata", reflect.TypeOf((*MockClient)(nil).GetCommitMetadata), ctx, req) +} + +// GetCommitMetadataForPipelineMaterial mocks base method. +func (m *MockClient) GetCommitMetadataForPipelineMaterial(ctx context.Context, req *gitSensor.CommitMetadataRequest) (*gitSensor.GitCommit, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetCommitMetadataForPipelineMaterial", ctx, req) + ret0, _ := ret[0].(*gitSensor.GitCommit) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetCommitMetadataForPipelineMaterial indicates an expected call of GetCommitMetadataForPipelineMaterial. +func (mr *MockClientMockRecorder) GetCommitMetadataForPipelineMaterial(ctx, req interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCommitMetadataForPipelineMaterial", reflect.TypeOf((*MockClient)(nil).GetCommitMetadataForPipelineMaterial), ctx, req) +} + +// GetHeadForPipelineMaterials mocks base method. +func (m *MockClient) GetHeadForPipelineMaterials(ctx context.Context, req *gitSensor.HeadRequest) ([]*gitSensor.CiPipelineMaterial, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetHeadForPipelineMaterials", ctx, req) + ret0, _ := ret[0].([]*gitSensor.CiPipelineMaterial) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetHeadForPipelineMaterials indicates an expected call of GetHeadForPipelineMaterials. +func (mr *MockClientMockRecorder) GetHeadForPipelineMaterials(ctx, req interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetHeadForPipelineMaterials", reflect.TypeOf((*MockClient)(nil).GetHeadForPipelineMaterials), ctx, req) +} + +// GetWebhookData mocks base method. +func (m *MockClient) GetWebhookData(ctx context.Context, req *gitSensor.WebhookDataRequest) (*gitSensor.WebhookAndCiData, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetWebhookData", ctx, req) + ret0, _ := ret[0].(*gitSensor.WebhookAndCiData) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetWebhookData indicates an expected call of GetWebhookData. +func (mr *MockClientMockRecorder) GetWebhookData(ctx, req interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetWebhookData", reflect.TypeOf((*MockClient)(nil).GetWebhookData), ctx, req) +} + +// GetWebhookEventConfig mocks base method. +func (m *MockClient) GetWebhookEventConfig(ctx context.Context, req *gitSensor.WebhookEventConfigRequest) (*gitSensor.WebhookEventConfig, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetWebhookEventConfig", ctx, req) + ret0, _ := ret[0].(*gitSensor.WebhookEventConfig) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetWebhookEventConfig indicates an expected call of GetWebhookEventConfig. +func (mr *MockClientMockRecorder) GetWebhookEventConfig(ctx, req interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetWebhookEventConfig", reflect.TypeOf((*MockClient)(nil).GetWebhookEventConfig), ctx, req) +} + +// GetWebhookPayloadDataForPipelineMaterialId mocks base method. +func (m *MockClient) GetWebhookPayloadDataForPipelineMaterialId(ctx context.Context, req *gitSensor.WebhookPayloadDataRequest) (*gitSensor.WebhookPayloadDataResponse, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetWebhookPayloadDataForPipelineMaterialId", ctx, req) + ret0, _ := ret[0].(*gitSensor.WebhookPayloadDataResponse) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetWebhookPayloadDataForPipelineMaterialId indicates an expected call of GetWebhookPayloadDataForPipelineMaterialId. +func (mr *MockClientMockRecorder) GetWebhookPayloadDataForPipelineMaterialId(ctx, req interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetWebhookPayloadDataForPipelineMaterialId", reflect.TypeOf((*MockClient)(nil).GetWebhookPayloadDataForPipelineMaterialId), ctx, req) +} + +// GetWebhookPayloadFilterDataForPipelineMaterialId mocks base method. +func (m *MockClient) GetWebhookPayloadFilterDataForPipelineMaterialId(ctx context.Context, req *gitSensor.WebhookPayloadFilterDataRequest) (*gitSensor.WebhookPayloadFilterDataResponse, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetWebhookPayloadFilterDataForPipelineMaterialId", ctx, req) + ret0, _ := ret[0].(*gitSensor.WebhookPayloadFilterDataResponse) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetWebhookPayloadFilterDataForPipelineMaterialId indicates an expected call of GetWebhookPayloadFilterDataForPipelineMaterialId. +func (mr *MockClientMockRecorder) GetWebhookPayloadFilterDataForPipelineMaterialId(ctx, req interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetWebhookPayloadFilterDataForPipelineMaterialId", reflect.TypeOf((*MockClient)(nil).GetWebhookPayloadFilterDataForPipelineMaterialId), ctx, req) +} + +// RefreshGitMaterial mocks base method. +func (m *MockClient) RefreshGitMaterial(ctx context.Context, req *gitSensor.RefreshGitMaterialRequest) (*gitSensor.RefreshGitMaterialResponse, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "RefreshGitMaterial", ctx, req) + ret0, _ := ret[0].(*gitSensor.RefreshGitMaterialResponse) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// RefreshGitMaterial indicates an expected call of RefreshGitMaterial. +func (mr *MockClientMockRecorder) RefreshGitMaterial(ctx, req interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RefreshGitMaterial", reflect.TypeOf((*MockClient)(nil).RefreshGitMaterial), ctx, req) +} + +// SaveGitProvider mocks base method. +func (m *MockClient) SaveGitProvider(ctx context.Context, provider *gitSensor.GitProvider) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "SaveGitProvider", ctx, provider) + ret0, _ := ret[0].(error) + return ret0 +} + +// SaveGitProvider indicates an expected call of SaveGitProvider. +func (mr *MockClientMockRecorder) SaveGitProvider(ctx, provider interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SaveGitProvider", reflect.TypeOf((*MockClient)(nil).SaveGitProvider), ctx, provider) +} + +// SavePipelineMaterial mocks base method. +func (m *MockClient) SavePipelineMaterial(ctx context.Context, ciPipelineMaterials []*gitSensor.CiPipelineMaterial) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "SavePipelineMaterial", ctx, ciPipelineMaterials) + ret0, _ := ret[0].(error) + return ret0 +} + +// SavePipelineMaterial indicates an expected call of SavePipelineMaterial. +func (mr *MockClientMockRecorder) SavePipelineMaterial(ctx, ciPipelineMaterials interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SavePipelineMaterial", reflect.TypeOf((*MockClient)(nil).SavePipelineMaterial), ctx, ciPipelineMaterials) +} + +// UpdateRepo mocks base method. +func (m *MockClient) UpdateRepo(ctx context.Context, material *gitSensor.GitMaterial) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "UpdateRepo", ctx, material) + ret0, _ := ret[0].(error) + return ret0 +} + +// UpdateRepo indicates an expected call of UpdateRepo. +func (mr *MockClientMockRecorder) UpdateRepo(ctx, material interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateRepo", reflect.TypeOf((*MockClient)(nil).UpdateRepo), ctx, material) +} diff --git a/go.mod b/go.mod index a331eaa0258..071b1142a3c 100644 --- a/go.mod +++ b/go.mod @@ -139,6 +139,7 @@ require ( github.com/go-xorm/xorm v0.7.9 // indirect github.com/gobwas/glob v0.2.3 // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect + github.com/golang/mock v1.6.0 // indirect github.com/google/btree v1.0.1 // indirect github.com/google/gnostic v0.5.7-v3refs // indirect github.com/google/go-github/v41 v41.0.0 // indirect @@ -232,12 +233,14 @@ require ( go.uber.org/atomic v1.7.0 // indirect go.uber.org/multierr v1.6.0 // indirect golang.org/x/exp v0.0.0-20220602145555-4a0574d9293f // indirect + golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 // indirect golang.org/x/net v0.0.0-20221012135044-0b7e1fb9d458 // indirect golang.org/x/sync v0.1.0 // indirect golang.org/x/sys v0.0.0-20220919091848-fb04ddd9f9c8 // indirect golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 // indirect golang.org/x/text v0.4.0 // indirect golang.org/x/time v0.0.0-20220922220347-f3bd1da661af // indirect + golang.org/x/tools v0.1.12 // indirect golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirect google.golang.org/api v0.101.0 // indirect google.golang.org/appengine v1.6.7 // indirect diff --git a/go.sum b/go.sum index 20272347cd0..4e7d0fb1c5d 100644 --- a/go.sum +++ b/go.sum @@ -325,6 +325,7 @@ github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.m github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= github.com/envoyproxy/go-control-plane v0.9.9-0.20210512163311-63b5d3c536b0/go.mod h1:hliV/p42l8fGbc6Y9bQ70uLwIvmJyVE5k4iMKlh8wCQ= github.com/envoyproxy/go-control-plane v0.9.10-0.20210907150352-cf90f659a021/go.mod h1:AFq3mo9L8Lqqiid3OhADV3RfLJnjiw63cSpi+fDTRC0= +github.com/envoyproxy/go-control-plane v0.10.2-0.20220325020618-49ff273808a1/go.mod h1:KJwIaB5Mv44NWtYuAOFCVOjcI94vtpEz2JU/D2v6IjE= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/euank/go-kmsg-parser v2.0.0+incompatible/go.mod h1:MhmAMZ8V4CYH4ybgdRwPr2TU5ThnS43puaKEMpja1uw= github.com/evanphx/json-patch v4.11.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= @@ -566,6 +567,7 @@ github.com/googleapis/gax-go/v2 v2.1.1/go.mod h1:hddJymUZASv3XPyGkUpKj8pPO47Rmb0 github.com/googleapis/gax-go/v2 v2.6.0 h1:SXk3ABtQYDT/OH8jAyvEOQ58mgawq5C4o/4/89qN2ZU= github.com/googleapis/gax-go/v2 v2.6.0/go.mod h1:1mjbznJAPHFpesgE5ucqfYEscaz5kMdcIDwU/6+DDoY= github.com/googleapis/gnostic v0.5.1/go.mod h1:6U4PtQXGIEt/Z3h5MAT7FNofLnw9vXk2cUuW7uA/OeU= +github.com/googleapis/go-type-adapters v1.0.0/go.mod h1:zHW75FOG2aur7gAO2B+MLby+cLsWGBF62rFAi7WjWO4= github.com/gophercloud/gophercloud v0.1.0/go.mod h1:vxM41WHh5uqHVBMZHzuwNOHh8XEoIEcSTewFxm1c5g8= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gopherjs/gopherjs v0.0.0-20200217142428-fce0ec30dd00/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= @@ -1323,6 +1325,8 @@ golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.5.1-0.20210830214625-1b1db11ec8f4/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3/go.mod h1:3p9vT2HGsQu2K1YbXdKPJLVgG5VJdoTa1poYQBtP1AY= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 h1:6zppjxzCulZykYSLyVDYbneBfbaBIQPYMevg0bEwv2s= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/net v0.0.0-20180218175443-cbe0f9307d01/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180406214816-61147c48b25b/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -1619,6 +1623,8 @@ golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.4/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.10-0.20220218145154-897bd77cd717/go.mod h1:Uh6Zz+xoGYZom868N8YTex3t7RhtHDBrE8Gzo9bV56E= +golang.org/x/tools v0.1.12 h1:VveCTK38A2rkS8ZqFY25HIDFscX5X9OoEhJd3quQmXU= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/internal/sql/repository/pipelineConfig/mocks/CiPipelineMaterial.go b/internal/sql/repository/pipelineConfig/mocks/CiPipelineMaterial.go new file mode 100644 index 00000000000..67b0709cb93 --- /dev/null +++ b/internal/sql/repository/pipelineConfig/mocks/CiPipelineMaterial.go @@ -0,0 +1,212 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: internal/sql/repository/pipelineConfig/CiPipelineMaterial.go + +// Package mock_pipelineConfig is a generated GoMock package. +package mocks + +import ( + reflect "reflect" + + pipelineConfig "github.com/devtron-labs/devtron/internal/sql/repository/pipelineConfig" + pg "github.com/go-pg/pg" + gomock "github.com/golang/mock/gomock" +) + +// MockCiPipelineMaterialRepository is a mock of CiPipelineMaterialRepository interface. +type MockCiPipelineMaterialRepository struct { + ctrl *gomock.Controller + recorder *MockCiPipelineMaterialRepositoryMockRecorder +} + +// MockCiPipelineMaterialRepositoryMockRecorder is the mock recorder for MockCiPipelineMaterialRepository. +type MockCiPipelineMaterialRepositoryMockRecorder struct { + mock *MockCiPipelineMaterialRepository +} + +// NewMockCiPipelineMaterialRepository creates a new mock instance. +func NewMockCiPipelineMaterialRepository(ctrl *gomock.Controller) *MockCiPipelineMaterialRepository { + mock := &MockCiPipelineMaterialRepository{ctrl: ctrl} + mock.recorder = &MockCiPipelineMaterialRepositoryMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockCiPipelineMaterialRepository) EXPECT() *MockCiPipelineMaterialRepositoryMockRecorder { + return m.recorder +} + +// CheckRegexExistsForMaterial mocks base method. +func (m *MockCiPipelineMaterialRepository) CheckRegexExistsForMaterial(id int) bool { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "CheckRegexExistsForMaterial", id) + ret0, _ := ret[0].(bool) + return ret0 +} + +// CheckRegexExistsForMaterial indicates an expected call of CheckRegexExistsForMaterial. +func (mr *MockCiPipelineMaterialRepositoryMockRecorder) CheckRegexExistsForMaterial(id interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CheckRegexExistsForMaterial", reflect.TypeOf((*MockCiPipelineMaterialRepository)(nil).CheckRegexExistsForMaterial), id) +} + +// FindByCiPipelineIdsIn mocks base method. +func (m *MockCiPipelineMaterialRepository) FindByCiPipelineIdsIn(ids []int) ([]*pipelineConfig.CiPipelineMaterial, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "FindByCiPipelineIdsIn", ids) + ret0, _ := ret[0].([]*pipelineConfig.CiPipelineMaterial) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// FindByCiPipelineIdsIn indicates an expected call of FindByCiPipelineIdsIn. +func (mr *MockCiPipelineMaterialRepositoryMockRecorder) FindByCiPipelineIdsIn(ids interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindByCiPipelineIdsIn", reflect.TypeOf((*MockCiPipelineMaterialRepository)(nil).FindByCiPipelineIdsIn), ids) +} + +// GetById mocks base method. +func (m *MockCiPipelineMaterialRepository) GetById(id int) (*pipelineConfig.CiPipelineMaterial, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetById", id) + ret0, _ := ret[0].(*pipelineConfig.CiPipelineMaterial) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetById indicates an expected call of GetById. +func (mr *MockCiPipelineMaterialRepositoryMockRecorder) GetById(id interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetById", reflect.TypeOf((*MockCiPipelineMaterialRepository)(nil).GetById), id) +} + +// GetByPipelineId mocks base method. +func (m *MockCiPipelineMaterialRepository) GetByPipelineId(id int) ([]*pipelineConfig.CiPipelineMaterial, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetByPipelineId", id) + ret0, _ := ret[0].([]*pipelineConfig.CiPipelineMaterial) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetByPipelineId indicates an expected call of GetByPipelineId. +func (mr *MockCiPipelineMaterialRepositoryMockRecorder) GetByPipelineId(id interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByPipelineId", reflect.TypeOf((*MockCiPipelineMaterialRepository)(nil).GetByPipelineId), id) +} + +// GetByPipelineIdAndGitMaterialId mocks base method. +func (m *MockCiPipelineMaterialRepository) GetByPipelineIdAndGitMaterialId(id, gitMaterialId int) ([]*pipelineConfig.CiPipelineMaterial, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetByPipelineIdAndGitMaterialId", id, gitMaterialId) + ret0, _ := ret[0].([]*pipelineConfig.CiPipelineMaterial) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetByPipelineIdAndGitMaterialId indicates an expected call of GetByPipelineIdAndGitMaterialId. +func (mr *MockCiPipelineMaterialRepositoryMockRecorder) GetByPipelineIdAndGitMaterialId(id, gitMaterialId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByPipelineIdAndGitMaterialId", reflect.TypeOf((*MockCiPipelineMaterialRepository)(nil).GetByPipelineIdAndGitMaterialId), id, gitMaterialId) +} + +// GetByPipelineIdForRegexAndFixed mocks base method. +func (m *MockCiPipelineMaterialRepository) GetByPipelineIdForRegexAndFixed(id int) ([]*pipelineConfig.CiPipelineMaterial, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetByPipelineIdForRegexAndFixed", id) + ret0, _ := ret[0].([]*pipelineConfig.CiPipelineMaterial) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetByPipelineIdForRegexAndFixed indicates an expected call of GetByPipelineIdForRegexAndFixed. +func (mr *MockCiPipelineMaterialRepositoryMockRecorder) GetByPipelineIdForRegexAndFixed(id interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByPipelineIdForRegexAndFixed", reflect.TypeOf((*MockCiPipelineMaterialRepository)(nil).GetByPipelineIdForRegexAndFixed), id) +} + +// GetCheckoutPath mocks base method. +func (m *MockCiPipelineMaterialRepository) GetCheckoutPath(gitMaterialId int) (string, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetCheckoutPath", gitMaterialId) + ret0, _ := ret[0].(string) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetCheckoutPath indicates an expected call of GetCheckoutPath. +func (mr *MockCiPipelineMaterialRepositoryMockRecorder) GetCheckoutPath(gitMaterialId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCheckoutPath", reflect.TypeOf((*MockCiPipelineMaterialRepository)(nil).GetCheckoutPath), gitMaterialId) +} + +// GetRegexByPipelineId mocks base method. +func (m *MockCiPipelineMaterialRepository) GetRegexByPipelineId(id int) ([]*pipelineConfig.CiPipelineMaterial, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetRegexByPipelineId", id) + ret0, _ := ret[0].([]*pipelineConfig.CiPipelineMaterial) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetRegexByPipelineId indicates an expected call of GetRegexByPipelineId. +func (mr *MockCiPipelineMaterialRepositoryMockRecorder) GetRegexByPipelineId(id interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRegexByPipelineId", reflect.TypeOf((*MockCiPipelineMaterialRepository)(nil).GetRegexByPipelineId), id) +} + +// Save mocks base method. +func (m *MockCiPipelineMaterialRepository) Save(tx *pg.Tx, pipeline ...*pipelineConfig.CiPipelineMaterial) error { + m.ctrl.T.Helper() + varargs := []interface{}{tx} + for _, a := range pipeline { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "Save", varargs...) + ret0, _ := ret[0].(error) + return ret0 +} + +// Save indicates an expected call of Save. +func (mr *MockCiPipelineMaterialRepositoryMockRecorder) Save(tx interface{}, pipeline ...interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]interface{}{tx}, pipeline...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Save", reflect.TypeOf((*MockCiPipelineMaterialRepository)(nil).Save), varargs...) +} + +// Update mocks base method. +func (m *MockCiPipelineMaterialRepository) Update(tx *pg.Tx, material ...*pipelineConfig.CiPipelineMaterial) error { + m.ctrl.T.Helper() + varargs := []interface{}{tx} + for _, a := range material { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "Update", varargs...) + ret0, _ := ret[0].(error) + return ret0 +} + +// Update indicates an expected call of Update. +func (mr *MockCiPipelineMaterialRepositoryMockRecorder) Update(tx interface{}, material ...interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]interface{}{tx}, material...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockCiPipelineMaterialRepository)(nil).Update), varargs...) +} + +// UpdateNotNull mocks base method. +func (m *MockCiPipelineMaterialRepository) UpdateNotNull(tx *pg.Tx, material ...*pipelineConfig.CiPipelineMaterial) error { + m.ctrl.T.Helper() + varargs := []interface{}{tx} + for _, a := range material { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "UpdateNotNull", varargs...) + ret0, _ := ret[0].(error) + return ret0 +} + +// UpdateNotNull indicates an expected call of UpdateNotNull. +func (mr *MockCiPipelineMaterialRepositoryMockRecorder) UpdateNotNull(tx interface{}, material ...interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]interface{}{tx}, material...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateNotNull", reflect.TypeOf((*MockCiPipelineMaterialRepository)(nil).UpdateNotNull), varargs...) +} diff --git a/pkg/pipeline/CiCdPipelineOrchestrator.go b/pkg/pipeline/CiCdPipelineOrchestrator.go index 39bb2d86df3..50b51c884c5 100644 --- a/pkg/pipeline/CiCdPipelineOrchestrator.go +++ b/pkg/pipeline/CiCdPipelineOrchestrator.go @@ -69,6 +69,7 @@ type CiCdPipelineOrchestrator interface { DeleteCiPipeline(pipeline *pipelineConfig.CiPipeline, request *bean.CiPatchRequest, tx *pg.Tx) error DeleteCdPipeline(pipelineId int, userId int32, tx *pg.Tx) error PatchMaterialValue(createRequest *bean.CiPipeline, userId int32, oldPipeline *pipelineConfig.CiPipeline) (*bean.CiPipeline, error) + PatchCiMaterialSource(ciPipeline *bean.CiPipeline, userId int32) (*bean.CiPipeline, error) PipelineExists(name string) (bool, error) GetCdPipelinesForApp(appId int) (cdPipelines *bean.CdPipelines, err error) GetCdPipelinesForAppAndEnv(appId int, envId int) (cdPipelines *bean.CdPipelines, err error) diff --git a/pkg/pipeline/CiCdPipelineOrchestrator_test.go b/pkg/pipeline/CiCdPipelineOrchestrator_test.go index 8358705016b..f6b0739559b 100644 --- a/pkg/pipeline/CiCdPipelineOrchestrator_test.go +++ b/pkg/pipeline/CiCdPipelineOrchestrator_test.go @@ -10,17 +10,17 @@ import ( repository2 "github.com/devtron-labs/devtron/internal/sql/repository/dockerRegistry" "github.com/devtron-labs/devtron/internal/sql/repository/helper" "github.com/devtron-labs/devtron/internal/sql/repository/pipelineConfig" + "github.com/devtron-labs/devtron/internal/sql/repository/pipelineConfig/mocks" "github.com/devtron-labs/devtron/internal/util" app2 "github.com/devtron-labs/devtron/pkg/app" - repository3 "github.com/devtron-labs/devtron/pkg/cluster/repository" - repository4 "github.com/devtron-labs/devtron/pkg/pipeline/history/repository" - "log" - "github.com/devtron-labs/devtron/pkg/attributes" "github.com/devtron-labs/devtron/pkg/bean" + repository3 "github.com/devtron-labs/devtron/pkg/cluster/repository" "github.com/devtron-labs/devtron/pkg/pipeline/history" + repository4 "github.com/devtron-labs/devtron/pkg/pipeline/history/repository" "github.com/devtron-labs/devtron/pkg/user" "github.com/stretchr/testify/assert" + "log" "testing" ) @@ -156,3 +156,72 @@ func InitClusterNoteService() { configMapService := NewConfigMapServiceImpl(nil, nil, nil, util.MergeUtil{}, nil, configMapRepository, nil, nil, appRepository, nil, envRepository) ciCdPipelineOrchestrator = NewCiCdPipelineOrchestrator(appRepository, logger, materialRepository, pipelineRepository, ciPipelineRepository, ciPipelineMaterialRepository, GitSensorClient, ciConfig, appWorkflowRepository, envRepository, attributesService, appListingRepository, appLabelsService, userAuthService, prePostCdScriptHistoryService, prePostCiScriptHistoryService, pipelineStageService, ciTemplateOverrideRepository, gitMaterialHistoryService, ciPipelineHistoryService, ciTemplateService, dockerArtifactStoreRepository, configMapService) } + +func TestPatchCiMaterialSourceWhenOldPipelineIsNotFoundItShouldReturnError(t *testing.T) { + //ctrl := gomock.NewController(t) + pipeline := &bean.CiPipeline{Id: 1} + userId := int32(10) + + mockedCiPipelineRepository := mocks.NewCiPipelineRepository(t) + mockedCiPipelineRepository.On("FindById", pipeline.Id).Return(nil, fmt.Errorf("dsfsdf")) + //mockedCiPipelineMaterialRepository := &mocks.MockCiPipelineMaterialRepository{} + //mockedGitSensor := &mock_gitSensor.MockClient{} + impl := CiCdPipelineOrchestratorImpl{ + ciPipelineRepository: mockedCiPipelineRepository, + //ciPipelineMaterialRepository: mockedCiPipelineMaterialRepository, + //GitSensorClient: mockedGitSensor, + } + res, err := impl.PatchCiMaterialSource(pipeline, userId) + assert.Error(t, err) + assert.Nil(t, res) +} + +//func TestPatchCiMaterialSourceWhenOldPipelineExistsAndSaveUpdatedMaterialFailsItShouldReturnError(t *testing.T) { +// //ctrl := gomock.NewController(t) +// userId := int32(10) +// oldPipeline := &bean.CiPipeline{ +// ParentAppId: 0, +// AppId: 4, +// CiMaterial: []*bean.CiMaterial{ +// { +// Source: &bean.SourceTypeConfig{ +// Type: "SOURCE_TYPE_BRANCH_FIXED", +// Value: "main", +// }, +// Id: 0, +// IsRegex: false, +// }, +// }, +// Id: 1, +// Active: false, +// } +// +// newPipeline := &bean.CiPipeline{ +// ParentAppId: 0, +// AppId: 4, +// CiMaterial: []*bean.CiMaterial{ +// { +// Source: &bean.SourceTypeConfig{ +// Type: "SOURCE_TYPE_BRANCH_FIXED", +// Value: "main", +// }, +// Id: 1, +// IsRegex: false, +// }, +// }, +// Id: 0, +// Active: false, +// } +// mockedCiPipelineRepository := mocks.NewCiPipelineRepository(t) +// mockedCiPipelineRepository.On("FindById", newPipeline.Id).Return(oldPipeline, nil) +// //mockedCiPipelineMaterialRepository := &mocks.MockCiPipelineMaterialRepository{} +// //mockedGitSensor := &mock_gitSensor.MockClient{} +// impl := CiCdPipelineOrchestratorImpl{ +// ciPipelineRepository: mockedCiPipelineRepository, +// //ciPipelineMaterialRepository: mockedCiPipelineMaterialRepository, +// //GitSensorClient: mockedGitSensor, +// } +// res, err := impl.PatchCiMaterialSource(pipeline, userId) +// assert.Error(t, err) +// assert.Nil(t, res) +//} diff --git a/pkg/pipeline/PipelineBuilder.go b/pkg/pipeline/PipelineBuilder.go index 8108f1abc9d..fee0f8e309d 100644 --- a/pkg/pipeline/PipelineBuilder.go +++ b/pkg/pipeline/PipelineBuilder.go @@ -112,6 +112,7 @@ type PipelineBuilder interface { GetExternalCiById(appId int, externalCiId int) (ciConfig *bean.ExternalCiConfig, err error) UpdateCiTemplate(updateRequest *bean.CiConfigRequest) (*bean.CiConfigRequest, error) PatchCiPipeline(request *bean.CiPatchRequest) (ciConfig *bean.CiConfigRequest, err error) + PatchCiMaterialSource(ciPipeline *bean.CiPipeline, userId int32) (*bean.CiPipeline, error) CreateCdPipelines(cdPipelines *bean.CdPipelines, ctx context.Context) (*bean.CdPipelines, error) GetApp(appId int) (application *bean.CreateAppDTO, err error) PatchCdPipelines(cdPipelines *bean.CDPatchRequest, ctx context.Context) (*bean.CdPipelines, error) @@ -1628,6 +1629,10 @@ func (impl PipelineBuilderImpl) DeleteCiPipeline(request *bean.CiPatchRequest) ( } +func (impl PipelineBuilderImpl) PatchCiMaterialSource(ciPipeline *bean.CiPipeline, userId int32) (*bean.CiPipeline, error) { + return impl.ciCdPipelineOrchestrator.PatchCiMaterialSource(ciPipeline, userId) +} + func (impl PipelineBuilderImpl) patchCiPipelineUpdateSource(baseCiConfig *bean.CiConfigRequest, modifiedCiPipeline *bean.CiPipeline) (ciConfig *bean.CiConfigRequest, err error) { pipeline, err := impl.ciPipelineRepository.FindById(modifiedCiPipeline.Id) diff --git a/vendor/github.com/golang/mock/AUTHORS b/vendor/github.com/golang/mock/AUTHORS new file mode 100644 index 00000000000..660b8ccc8ae --- /dev/null +++ b/vendor/github.com/golang/mock/AUTHORS @@ -0,0 +1,12 @@ +# This is the official list of GoMock authors for copyright purposes. +# This file is distinct from the CONTRIBUTORS files. +# See the latter for an explanation. + +# Names should be added to this file as +# Name or Organization +# The email address is not required for organizations. + +# Please keep the list sorted. + +Alex Reece +Google Inc. diff --git a/vendor/github.com/golang/mock/CONTRIBUTORS b/vendor/github.com/golang/mock/CONTRIBUTORS new file mode 100644 index 00000000000..def849cab1b --- /dev/null +++ b/vendor/github.com/golang/mock/CONTRIBUTORS @@ -0,0 +1,37 @@ +# This is the official list of people who can contribute (and typically +# have contributed) code to the gomock repository. +# The AUTHORS file lists the copyright holders; this file +# lists people. For example, Google employees are listed here +# but not in AUTHORS, because Google holds the copyright. +# +# The submission process automatically checks to make sure +# that people submitting code are listed in this file (by email address). +# +# Names should be added to this file only after verifying that +# the individual or the individual's organization has agreed to +# the appropriate Contributor License Agreement, found here: +# +# http://code.google.com/legal/individual-cla-v1.0.html +# http://code.google.com/legal/corporate-cla-v1.0.html +# +# The agreement for individuals can be filled out on the web. +# +# When adding J Random Contributor's name to this file, +# either J's name or J's organization's name should be +# added to the AUTHORS file, depending on whether the +# individual or corporate CLA was used. + +# Names should be added to this file like so: +# Name +# +# An entry with two email addresses specifies that the +# first address should be used in the submit logs and +# that the second address should be recognized as the +# same person when interacting with Rietveld. + +# Please keep the list sorted. + +Aaron Jacobs +Alex Reece +David Symonds +Ryan Barrett diff --git a/vendor/github.com/golang/mock/LICENSE b/vendor/github.com/golang/mock/LICENSE new file mode 100644 index 00000000000..d6456956733 --- /dev/null +++ b/vendor/github.com/golang/mock/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/vendor/github.com/golang/mock/gomock/call.go b/vendor/github.com/golang/mock/gomock/call.go new file mode 100644 index 00000000000..13c9f44b1ef --- /dev/null +++ b/vendor/github.com/golang/mock/gomock/call.go @@ -0,0 +1,445 @@ +// Copyright 2010 Google Inc. +// +// 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 gomock + +import ( + "fmt" + "reflect" + "strconv" + "strings" +) + +// Call represents an expected call to a mock. +type Call struct { + t TestHelper // for triggering test failures on invalid call setup + + receiver interface{} // the receiver of the method call + method string // the name of the method + methodType reflect.Type // the type of the method + args []Matcher // the args + origin string // file and line number of call setup + + preReqs []*Call // prerequisite calls + + // Expectations + minCalls, maxCalls int + + numCalls int // actual number made + + // actions are called when this Call is called. Each action gets the args and + // can set the return values by returning a non-nil slice. Actions run in the + // order they are created. + actions []func([]interface{}) []interface{} +} + +// newCall creates a *Call. It requires the method type in order to support +// unexported methods. +func newCall(t TestHelper, receiver interface{}, method string, methodType reflect.Type, args ...interface{}) *Call { + t.Helper() + + // TODO: check arity, types. + mArgs := make([]Matcher, len(args)) + for i, arg := range args { + if m, ok := arg.(Matcher); ok { + mArgs[i] = m + } else if arg == nil { + // Handle nil specially so that passing a nil interface value + // will match the typed nils of concrete args. + mArgs[i] = Nil() + } else { + mArgs[i] = Eq(arg) + } + } + + // callerInfo's skip should be updated if the number of calls between the user's test + // and this line changes, i.e. this code is wrapped in another anonymous function. + // 0 is us, 1 is RecordCallWithMethodType(), 2 is the generated recorder, and 3 is the user's test. + origin := callerInfo(3) + actions := []func([]interface{}) []interface{}{func([]interface{}) []interface{} { + // Synthesize the zero value for each of the return args' types. + rets := make([]interface{}, methodType.NumOut()) + for i := 0; i < methodType.NumOut(); i++ { + rets[i] = reflect.Zero(methodType.Out(i)).Interface() + } + return rets + }} + return &Call{t: t, receiver: receiver, method: method, methodType: methodType, + args: mArgs, origin: origin, minCalls: 1, maxCalls: 1, actions: actions} +} + +// AnyTimes allows the expectation to be called 0 or more times +func (c *Call) AnyTimes() *Call { + c.minCalls, c.maxCalls = 0, 1e8 // close enough to infinity + return c +} + +// MinTimes requires the call to occur at least n times. If AnyTimes or MaxTimes have not been called or if MaxTimes +// was previously called with 1, MinTimes also sets the maximum number of calls to infinity. +func (c *Call) MinTimes(n int) *Call { + c.minCalls = n + if c.maxCalls == 1 { + c.maxCalls = 1e8 + } + return c +} + +// MaxTimes limits the number of calls to n times. If AnyTimes or MinTimes have not been called or if MinTimes was +// previously called with 1, MaxTimes also sets the minimum number of calls to 0. +func (c *Call) MaxTimes(n int) *Call { + c.maxCalls = n + if c.minCalls == 1 { + c.minCalls = 0 + } + return c +} + +// DoAndReturn declares the action to run when the call is matched. +// The return values from this function are returned by the mocked function. +// It takes an interface{} argument to support n-arity functions. +func (c *Call) DoAndReturn(f interface{}) *Call { + // TODO: Check arity and types here, rather than dying badly elsewhere. + v := reflect.ValueOf(f) + + c.addAction(func(args []interface{}) []interface{} { + c.t.Helper() + vArgs := make([]reflect.Value, len(args)) + ft := v.Type() + if c.methodType.NumIn() != ft.NumIn() { + c.t.Fatalf("wrong number of arguments in DoAndReturn func for %T.%v: got %d, want %d [%s]", + c.receiver, c.method, ft.NumIn(), c.methodType.NumIn(), c.origin) + return nil + } + for i := 0; i < len(args); i++ { + if args[i] != nil { + vArgs[i] = reflect.ValueOf(args[i]) + } else { + // Use the zero value for the arg. + vArgs[i] = reflect.Zero(ft.In(i)) + } + } + vRets := v.Call(vArgs) + rets := make([]interface{}, len(vRets)) + for i, ret := range vRets { + rets[i] = ret.Interface() + } + return rets + }) + return c +} + +// Do declares the action to run when the call is matched. The function's +// return values are ignored to retain backward compatibility. To use the +// return values call DoAndReturn. +// It takes an interface{} argument to support n-arity functions. +func (c *Call) Do(f interface{}) *Call { + // TODO: Check arity and types here, rather than dying badly elsewhere. + v := reflect.ValueOf(f) + + c.addAction(func(args []interface{}) []interface{} { + c.t.Helper() + if c.methodType.NumIn() != v.Type().NumIn() { + c.t.Fatalf("wrong number of arguments in Do func for %T.%v: got %d, want %d [%s]", + c.receiver, c.method, v.Type().NumIn(), c.methodType.NumIn(), c.origin) + return nil + } + vArgs := make([]reflect.Value, len(args)) + ft := v.Type() + for i := 0; i < len(args); i++ { + if args[i] != nil { + vArgs[i] = reflect.ValueOf(args[i]) + } else { + // Use the zero value for the arg. + vArgs[i] = reflect.Zero(ft.In(i)) + } + } + v.Call(vArgs) + return nil + }) + return c +} + +// Return declares the values to be returned by the mocked function call. +func (c *Call) Return(rets ...interface{}) *Call { + c.t.Helper() + + mt := c.methodType + if len(rets) != mt.NumOut() { + c.t.Fatalf("wrong number of arguments to Return for %T.%v: got %d, want %d [%s]", + c.receiver, c.method, len(rets), mt.NumOut(), c.origin) + } + for i, ret := range rets { + if got, want := reflect.TypeOf(ret), mt.Out(i); got == want { + // Identical types; nothing to do. + } else if got == nil { + // Nil needs special handling. + switch want.Kind() { + case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: + // ok + default: + c.t.Fatalf("argument %d to Return for %T.%v is nil, but %v is not nillable [%s]", + i, c.receiver, c.method, want, c.origin) + } + } else if got.AssignableTo(want) { + // Assignable type relation. Make the assignment now so that the generated code + // can return the values with a type assertion. + v := reflect.New(want).Elem() + v.Set(reflect.ValueOf(ret)) + rets[i] = v.Interface() + } else { + c.t.Fatalf("wrong type of argument %d to Return for %T.%v: %v is not assignable to %v [%s]", + i, c.receiver, c.method, got, want, c.origin) + } + } + + c.addAction(func([]interface{}) []interface{} { + return rets + }) + + return c +} + +// Times declares the exact number of times a function call is expected to be executed. +func (c *Call) Times(n int) *Call { + c.minCalls, c.maxCalls = n, n + return c +} + +// SetArg declares an action that will set the nth argument's value, +// indirected through a pointer. Or, in the case of a slice, SetArg +// will copy value's elements into the nth argument. +func (c *Call) SetArg(n int, value interface{}) *Call { + c.t.Helper() + + mt := c.methodType + // TODO: This will break on variadic methods. + // We will need to check those at invocation time. + if n < 0 || n >= mt.NumIn() { + c.t.Fatalf("SetArg(%d, ...) called for a method with %d args [%s]", + n, mt.NumIn(), c.origin) + } + // Permit setting argument through an interface. + // In the interface case, we don't (nay, can't) check the type here. + at := mt.In(n) + switch at.Kind() { + case reflect.Ptr: + dt := at.Elem() + if vt := reflect.TypeOf(value); !vt.AssignableTo(dt) { + c.t.Fatalf("SetArg(%d, ...) argument is a %v, not assignable to %v [%s]", + n, vt, dt, c.origin) + } + case reflect.Interface: + // nothing to do + case reflect.Slice: + // nothing to do + default: + c.t.Fatalf("SetArg(%d, ...) referring to argument of non-pointer non-interface non-slice type %v [%s]", + n, at, c.origin) + } + + c.addAction(func(args []interface{}) []interface{} { + v := reflect.ValueOf(value) + switch reflect.TypeOf(args[n]).Kind() { + case reflect.Slice: + setSlice(args[n], v) + default: + reflect.ValueOf(args[n]).Elem().Set(v) + } + return nil + }) + return c +} + +// isPreReq returns true if other is a direct or indirect prerequisite to c. +func (c *Call) isPreReq(other *Call) bool { + for _, preReq := range c.preReqs { + if other == preReq || preReq.isPreReq(other) { + return true + } + } + return false +} + +// After declares that the call may only match after preReq has been exhausted. +func (c *Call) After(preReq *Call) *Call { + c.t.Helper() + + if c == preReq { + c.t.Fatalf("A call isn't allowed to be its own prerequisite") + } + if preReq.isPreReq(c) { + c.t.Fatalf("Loop in call order: %v is a prerequisite to %v (possibly indirectly).", c, preReq) + } + + c.preReqs = append(c.preReqs, preReq) + return c +} + +// Returns true if the minimum number of calls have been made. +func (c *Call) satisfied() bool { + return c.numCalls >= c.minCalls +} + +// Returns true if the maximum number of calls have been made. +func (c *Call) exhausted() bool { + return c.numCalls >= c.maxCalls +} + +func (c *Call) String() string { + args := make([]string, len(c.args)) + for i, arg := range c.args { + args[i] = arg.String() + } + arguments := strings.Join(args, ", ") + return fmt.Sprintf("%T.%v(%s) %s", c.receiver, c.method, arguments, c.origin) +} + +// Tests if the given call matches the expected call. +// If yes, returns nil. If no, returns error with message explaining why it does not match. +func (c *Call) matches(args []interface{}) error { + if !c.methodType.IsVariadic() { + if len(args) != len(c.args) { + return fmt.Errorf("expected call at %s has the wrong number of arguments. Got: %d, want: %d", + c.origin, len(args), len(c.args)) + } + + for i, m := range c.args { + if !m.Matches(args[i]) { + return fmt.Errorf( + "expected call at %s doesn't match the argument at index %d.\nGot: %v\nWant: %v", + c.origin, i, formatGottenArg(m, args[i]), m, + ) + } + } + } else { + if len(c.args) < c.methodType.NumIn()-1 { + return fmt.Errorf("expected call at %s has the wrong number of matchers. Got: %d, want: %d", + c.origin, len(c.args), c.methodType.NumIn()-1) + } + if len(c.args) != c.methodType.NumIn() && len(args) != len(c.args) { + return fmt.Errorf("expected call at %s has the wrong number of arguments. Got: %d, want: %d", + c.origin, len(args), len(c.args)) + } + if len(args) < len(c.args)-1 { + return fmt.Errorf("expected call at %s has the wrong number of arguments. Got: %d, want: greater than or equal to %d", + c.origin, len(args), len(c.args)-1) + } + + for i, m := range c.args { + if i < c.methodType.NumIn()-1 { + // Non-variadic args + if !m.Matches(args[i]) { + return fmt.Errorf("expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v", + c.origin, strconv.Itoa(i), formatGottenArg(m, args[i]), m) + } + continue + } + // The last arg has a possibility of a variadic argument, so let it branch + + // sample: Foo(a int, b int, c ...int) + if i < len(c.args) && i < len(args) { + if m.Matches(args[i]) { + // Got Foo(a, b, c) want Foo(matcherA, matcherB, gomock.Any()) + // Got Foo(a, b, c) want Foo(matcherA, matcherB, someSliceMatcher) + // Got Foo(a, b, c) want Foo(matcherA, matcherB, matcherC) + // Got Foo(a, b) want Foo(matcherA, matcherB) + // Got Foo(a, b, c, d) want Foo(matcherA, matcherB, matcherC, matcherD) + continue + } + } + + // The number of actual args don't match the number of matchers, + // or the last matcher is a slice and the last arg is not. + // If this function still matches it is because the last matcher + // matches all the remaining arguments or the lack of any. + // Convert the remaining arguments, if any, into a slice of the + // expected type. + vArgsType := c.methodType.In(c.methodType.NumIn() - 1) + vArgs := reflect.MakeSlice(vArgsType, 0, len(args)-i) + for _, arg := range args[i:] { + vArgs = reflect.Append(vArgs, reflect.ValueOf(arg)) + } + if m.Matches(vArgs.Interface()) { + // Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, gomock.Any()) + // Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, someSliceMatcher) + // Got Foo(a, b) want Foo(matcherA, matcherB, gomock.Any()) + // Got Foo(a, b) want Foo(matcherA, matcherB, someEmptySliceMatcher) + break + } + // Wrong number of matchers or not match. Fail. + // Got Foo(a, b) want Foo(matcherA, matcherB, matcherC, matcherD) + // Got Foo(a, b, c) want Foo(matcherA, matcherB, matcherC, matcherD) + // Got Foo(a, b, c, d) want Foo(matcherA, matcherB, matcherC, matcherD, matcherE) + // Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, matcherC, matcherD) + // Got Foo(a, b, c) want Foo(matcherA, matcherB) + + return fmt.Errorf("expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v", + c.origin, strconv.Itoa(i), formatGottenArg(m, args[i:]), c.args[i]) + } + } + + // Check that all prerequisite calls have been satisfied. + for _, preReqCall := range c.preReqs { + if !preReqCall.satisfied() { + return fmt.Errorf("expected call at %s doesn't have a prerequisite call satisfied:\n%v\nshould be called before:\n%v", + c.origin, preReqCall, c) + } + } + + // Check that the call is not exhausted. + if c.exhausted() { + return fmt.Errorf("expected call at %s has already been called the max number of times", c.origin) + } + + return nil +} + +// dropPrereqs tells the expected Call to not re-check prerequisite calls any +// longer, and to return its current set. +func (c *Call) dropPrereqs() (preReqs []*Call) { + preReqs = c.preReqs + c.preReqs = nil + return +} + +func (c *Call) call() []func([]interface{}) []interface{} { + c.numCalls++ + return c.actions +} + +// InOrder declares that the given calls should occur in order. +func InOrder(calls ...*Call) { + for i := 1; i < len(calls); i++ { + calls[i].After(calls[i-1]) + } +} + +func setSlice(arg interface{}, v reflect.Value) { + va := reflect.ValueOf(arg) + for i := 0; i < v.Len(); i++ { + va.Index(i).Set(v.Index(i)) + } +} + +func (c *Call) addAction(action func([]interface{}) []interface{}) { + c.actions = append(c.actions, action) +} + +func formatGottenArg(m Matcher, arg interface{}) string { + got := fmt.Sprintf("%v (%T)", arg, arg) + if gs, ok := m.(GotFormatter); ok { + got = gs.Got(arg) + } + return got +} diff --git a/vendor/github.com/golang/mock/gomock/callset.go b/vendor/github.com/golang/mock/gomock/callset.go new file mode 100644 index 00000000000..49dba787a40 --- /dev/null +++ b/vendor/github.com/golang/mock/gomock/callset.go @@ -0,0 +1,113 @@ +// Copyright 2011 Google Inc. +// +// 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 gomock + +import ( + "bytes" + "errors" + "fmt" +) + +// callSet represents a set of expected calls, indexed by receiver and method +// name. +type callSet struct { + // Calls that are still expected. + expected map[callSetKey][]*Call + // Calls that have been exhausted. + exhausted map[callSetKey][]*Call +} + +// callSetKey is the key in the maps in callSet +type callSetKey struct { + receiver interface{} + fname string +} + +func newCallSet() *callSet { + return &callSet{make(map[callSetKey][]*Call), make(map[callSetKey][]*Call)} +} + +// Add adds a new expected call. +func (cs callSet) Add(call *Call) { + key := callSetKey{call.receiver, call.method} + m := cs.expected + if call.exhausted() { + m = cs.exhausted + } + m[key] = append(m[key], call) +} + +// Remove removes an expected call. +func (cs callSet) Remove(call *Call) { + key := callSetKey{call.receiver, call.method} + calls := cs.expected[key] + for i, c := range calls { + if c == call { + // maintain order for remaining calls + cs.expected[key] = append(calls[:i], calls[i+1:]...) + cs.exhausted[key] = append(cs.exhausted[key], call) + break + } + } +} + +// FindMatch searches for a matching call. Returns error with explanation message if no call matched. +func (cs callSet) FindMatch(receiver interface{}, method string, args []interface{}) (*Call, error) { + key := callSetKey{receiver, method} + + // Search through the expected calls. + expected := cs.expected[key] + var callsErrors bytes.Buffer + for _, call := range expected { + err := call.matches(args) + if err != nil { + _, _ = fmt.Fprintf(&callsErrors, "\n%v", err) + } else { + return call, nil + } + } + + // If we haven't found a match then search through the exhausted calls so we + // get useful error messages. + exhausted := cs.exhausted[key] + for _, call := range exhausted { + if err := call.matches(args); err != nil { + _, _ = fmt.Fprintf(&callsErrors, "\n%v", err) + continue + } + _, _ = fmt.Fprintf( + &callsErrors, "all expected calls for method %q have been exhausted", method, + ) + } + + if len(expected)+len(exhausted) == 0 { + _, _ = fmt.Fprintf(&callsErrors, "there are no expected calls of the method %q for that receiver", method) + } + + return nil, errors.New(callsErrors.String()) +} + +// Failures returns the calls that are not satisfied. +func (cs callSet) Failures() []*Call { + failures := make([]*Call, 0, len(cs.expected)) + for _, calls := range cs.expected { + for _, call := range calls { + if !call.satisfied() { + failures = append(failures, call) + } + } + } + return failures +} diff --git a/vendor/github.com/golang/mock/gomock/controller.go b/vendor/github.com/golang/mock/gomock/controller.go new file mode 100644 index 00000000000..f054200d56c --- /dev/null +++ b/vendor/github.com/golang/mock/gomock/controller.go @@ -0,0 +1,336 @@ +// Copyright 2010 Google Inc. +// +// 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 gomock is a mock framework for Go. +// +// Standard usage: +// (1) Define an interface that you wish to mock. +// type MyInterface interface { +// SomeMethod(x int64, y string) +// } +// (2) Use mockgen to generate a mock from the interface. +// (3) Use the mock in a test: +// func TestMyThing(t *testing.T) { +// mockCtrl := gomock.NewController(t) +// defer mockCtrl.Finish() +// +// mockObj := something.NewMockMyInterface(mockCtrl) +// mockObj.EXPECT().SomeMethod(4, "blah") +// // pass mockObj to a real object and play with it. +// } +// +// By default, expected calls are not enforced to run in any particular order. +// Call order dependency can be enforced by use of InOrder and/or Call.After. +// Call.After can create more varied call order dependencies, but InOrder is +// often more convenient. +// +// The following examples create equivalent call order dependencies. +// +// Example of using Call.After to chain expected call order: +// +// firstCall := mockObj.EXPECT().SomeMethod(1, "first") +// secondCall := mockObj.EXPECT().SomeMethod(2, "second").After(firstCall) +// mockObj.EXPECT().SomeMethod(3, "third").After(secondCall) +// +// Example of using InOrder to declare expected call order: +// +// gomock.InOrder( +// mockObj.EXPECT().SomeMethod(1, "first"), +// mockObj.EXPECT().SomeMethod(2, "second"), +// mockObj.EXPECT().SomeMethod(3, "third"), +// ) +package gomock + +import ( + "context" + "fmt" + "reflect" + "runtime" + "sync" +) + +// A TestReporter is something that can be used to report test failures. It +// is satisfied by the standard library's *testing.T. +type TestReporter interface { + Errorf(format string, args ...interface{}) + Fatalf(format string, args ...interface{}) +} + +// TestHelper is a TestReporter that has the Helper method. It is satisfied +// by the standard library's *testing.T. +type TestHelper interface { + TestReporter + Helper() +} + +// cleanuper is used to check if TestHelper also has the `Cleanup` method. A +// common pattern is to pass in a `*testing.T` to +// `NewController(t TestReporter)`. In Go 1.14+, `*testing.T` has a cleanup +// method. This can be utilized to call `Finish()` so the caller of this library +// does not have to. +type cleanuper interface { + Cleanup(func()) +} + +// A Controller represents the top-level control of a mock ecosystem. It +// defines the scope and lifetime of mock objects, as well as their +// expectations. It is safe to call Controller's methods from multiple +// goroutines. Each test should create a new Controller and invoke Finish via +// defer. +// +// func TestFoo(t *testing.T) { +// ctrl := gomock.NewController(t) +// defer ctrl.Finish() +// // .. +// } +// +// func TestBar(t *testing.T) { +// t.Run("Sub-Test-1", st) { +// ctrl := gomock.NewController(st) +// defer ctrl.Finish() +// // .. +// }) +// t.Run("Sub-Test-2", st) { +// ctrl := gomock.NewController(st) +// defer ctrl.Finish() +// // .. +// }) +// }) +type Controller struct { + // T should only be called within a generated mock. It is not intended to + // be used in user code and may be changed in future versions. T is the + // TestReporter passed in when creating the Controller via NewController. + // If the TestReporter does not implement a TestHelper it will be wrapped + // with a nopTestHelper. + T TestHelper + mu sync.Mutex + expectedCalls *callSet + finished bool +} + +// NewController returns a new Controller. It is the preferred way to create a +// Controller. +// +// New in go1.14+, if you are passing a *testing.T into this function you no +// longer need to call ctrl.Finish() in your test methods. +func NewController(t TestReporter) *Controller { + h, ok := t.(TestHelper) + if !ok { + h = &nopTestHelper{t} + } + ctrl := &Controller{ + T: h, + expectedCalls: newCallSet(), + } + if c, ok := isCleanuper(ctrl.T); ok { + c.Cleanup(func() { + ctrl.T.Helper() + ctrl.finish(true, nil) + }) + } + + return ctrl +} + +type cancelReporter struct { + t TestHelper + cancel func() +} + +func (r *cancelReporter) Errorf(format string, args ...interface{}) { + r.t.Errorf(format, args...) +} +func (r *cancelReporter) Fatalf(format string, args ...interface{}) { + defer r.cancel() + r.t.Fatalf(format, args...) +} + +func (r *cancelReporter) Helper() { + r.t.Helper() +} + +// WithContext returns a new Controller and a Context, which is cancelled on any +// fatal failure. +func WithContext(ctx context.Context, t TestReporter) (*Controller, context.Context) { + h, ok := t.(TestHelper) + if !ok { + h = &nopTestHelper{t: t} + } + + ctx, cancel := context.WithCancel(ctx) + return NewController(&cancelReporter{t: h, cancel: cancel}), ctx +} + +type nopTestHelper struct { + t TestReporter +} + +func (h *nopTestHelper) Errorf(format string, args ...interface{}) { + h.t.Errorf(format, args...) +} +func (h *nopTestHelper) Fatalf(format string, args ...interface{}) { + h.t.Fatalf(format, args...) +} + +func (h nopTestHelper) Helper() {} + +// RecordCall is called by a mock. It should not be called by user code. +func (ctrl *Controller) RecordCall(receiver interface{}, method string, args ...interface{}) *Call { + ctrl.T.Helper() + + recv := reflect.ValueOf(receiver) + for i := 0; i < recv.Type().NumMethod(); i++ { + if recv.Type().Method(i).Name == method { + return ctrl.RecordCallWithMethodType(receiver, method, recv.Method(i).Type(), args...) + } + } + ctrl.T.Fatalf("gomock: failed finding method %s on %T", method, receiver) + panic("unreachable") +} + +// RecordCallWithMethodType is called by a mock. It should not be called by user code. +func (ctrl *Controller) RecordCallWithMethodType(receiver interface{}, method string, methodType reflect.Type, args ...interface{}) *Call { + ctrl.T.Helper() + + call := newCall(ctrl.T, receiver, method, methodType, args...) + + ctrl.mu.Lock() + defer ctrl.mu.Unlock() + ctrl.expectedCalls.Add(call) + + return call +} + +// Call is called by a mock. It should not be called by user code. +func (ctrl *Controller) Call(receiver interface{}, method string, args ...interface{}) []interface{} { + ctrl.T.Helper() + + // Nest this code so we can use defer to make sure the lock is released. + actions := func() []func([]interface{}) []interface{} { + ctrl.T.Helper() + ctrl.mu.Lock() + defer ctrl.mu.Unlock() + + expected, err := ctrl.expectedCalls.FindMatch(receiver, method, args) + if err != nil { + // callerInfo's skip should be updated if the number of calls between the user's test + // and this line changes, i.e. this code is wrapped in another anonymous function. + // 0 is us, 1 is controller.Call(), 2 is the generated mock, and 3 is the user's test. + origin := callerInfo(3) + ctrl.T.Fatalf("Unexpected call to %T.%v(%v) at %s because: %s", receiver, method, args, origin, err) + } + + // Two things happen here: + // * the matching call no longer needs to check prerequite calls, + // * and the prerequite calls are no longer expected, so remove them. + preReqCalls := expected.dropPrereqs() + for _, preReqCall := range preReqCalls { + ctrl.expectedCalls.Remove(preReqCall) + } + + actions := expected.call() + if expected.exhausted() { + ctrl.expectedCalls.Remove(expected) + } + return actions + }() + + var rets []interface{} + for _, action := range actions { + if r := action(args); r != nil { + rets = r + } + } + + return rets +} + +// Finish checks to see if all the methods that were expected to be called +// were called. It should be invoked for each Controller. It is not idempotent +// and therefore can only be invoked once. +// +// New in go1.14+, if you are passing a *testing.T into NewController function you no +// longer need to call ctrl.Finish() in your test methods. +func (ctrl *Controller) Finish() { + // If we're currently panicking, probably because this is a deferred call. + // This must be recovered in the deferred function. + err := recover() + ctrl.finish(false, err) +} + +func (ctrl *Controller) finish(cleanup bool, panicErr interface{}) { + ctrl.T.Helper() + + ctrl.mu.Lock() + defer ctrl.mu.Unlock() + + if ctrl.finished { + if _, ok := isCleanuper(ctrl.T); !ok { + ctrl.T.Fatalf("Controller.Finish was called more than once. It has to be called exactly once.") + } + return + } + ctrl.finished = true + + // Short-circuit, pass through the panic. + if panicErr != nil { + panic(panicErr) + } + + // Check that all remaining expected calls are satisfied. + failures := ctrl.expectedCalls.Failures() + for _, call := range failures { + ctrl.T.Errorf("missing call(s) to %v", call) + } + if len(failures) != 0 { + if !cleanup { + ctrl.T.Fatalf("aborting test due to missing call(s)") + return + } + ctrl.T.Errorf("aborting test due to missing call(s)") + } +} + +// callerInfo returns the file:line of the call site. skip is the number +// of stack frames to skip when reporting. 0 is callerInfo's call site. +func callerInfo(skip int) string { + if _, file, line, ok := runtime.Caller(skip + 1); ok { + return fmt.Sprintf("%s:%d", file, line) + } + return "unknown file" +} + +// isCleanuper checks it if t's base TestReporter has a Cleanup method. +func isCleanuper(t TestReporter) (cleanuper, bool) { + tr := unwrapTestReporter(t) + c, ok := tr.(cleanuper) + return c, ok +} + +// unwrapTestReporter unwraps TestReporter to the base implementation. +func unwrapTestReporter(t TestReporter) TestReporter { + tr := t + switch nt := t.(type) { + case *cancelReporter: + tr = nt.t + if h, check := tr.(*nopTestHelper); check { + tr = h.t + } + case *nopTestHelper: + tr = nt.t + default: + // not wrapped + } + return tr +} diff --git a/vendor/github.com/golang/mock/gomock/matchers.go b/vendor/github.com/golang/mock/gomock/matchers.go new file mode 100644 index 00000000000..2822fb2c8c4 --- /dev/null +++ b/vendor/github.com/golang/mock/gomock/matchers.go @@ -0,0 +1,341 @@ +// Copyright 2010 Google Inc. +// +// 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 gomock + +import ( + "fmt" + "reflect" + "strings" +) + +// A Matcher is a representation of a class of values. +// It is used to represent the valid or expected arguments to a mocked method. +type Matcher interface { + // Matches returns whether x is a match. + Matches(x interface{}) bool + + // String describes what the matcher matches. + String() string +} + +// WantFormatter modifies the given Matcher's String() method to the given +// Stringer. This allows for control on how the "Want" is formatted when +// printing . +func WantFormatter(s fmt.Stringer, m Matcher) Matcher { + type matcher interface { + Matches(x interface{}) bool + } + + return struct { + matcher + fmt.Stringer + }{ + matcher: m, + Stringer: s, + } +} + +// StringerFunc type is an adapter to allow the use of ordinary functions as +// a Stringer. If f is a function with the appropriate signature, +// StringerFunc(f) is a Stringer that calls f. +type StringerFunc func() string + +// String implements fmt.Stringer. +func (f StringerFunc) String() string { + return f() +} + +// GotFormatter is used to better print failure messages. If a matcher +// implements GotFormatter, it will use the result from Got when printing +// the failure message. +type GotFormatter interface { + // Got is invoked with the received value. The result is used when + // printing the failure message. + Got(got interface{}) string +} + +// GotFormatterFunc type is an adapter to allow the use of ordinary +// functions as a GotFormatter. If f is a function with the appropriate +// signature, GotFormatterFunc(f) is a GotFormatter that calls f. +type GotFormatterFunc func(got interface{}) string + +// Got implements GotFormatter. +func (f GotFormatterFunc) Got(got interface{}) string { + return f(got) +} + +// GotFormatterAdapter attaches a GotFormatter to a Matcher. +func GotFormatterAdapter(s GotFormatter, m Matcher) Matcher { + return struct { + GotFormatter + Matcher + }{ + GotFormatter: s, + Matcher: m, + } +} + +type anyMatcher struct{} + +func (anyMatcher) Matches(interface{}) bool { + return true +} + +func (anyMatcher) String() string { + return "is anything" +} + +type eqMatcher struct { + x interface{} +} + +func (e eqMatcher) Matches(x interface{}) bool { + // In case, some value is nil + if e.x == nil || x == nil { + return reflect.DeepEqual(e.x, x) + } + + // Check if types assignable and convert them to common type + x1Val := reflect.ValueOf(e.x) + x2Val := reflect.ValueOf(x) + + if x1Val.Type().AssignableTo(x2Val.Type()) { + x1ValConverted := x1Val.Convert(x2Val.Type()) + return reflect.DeepEqual(x1ValConverted.Interface(), x2Val.Interface()) + } + + return false +} + +func (e eqMatcher) String() string { + return fmt.Sprintf("is equal to %v (%T)", e.x, e.x) +} + +type nilMatcher struct{} + +func (nilMatcher) Matches(x interface{}) bool { + if x == nil { + return true + } + + v := reflect.ValueOf(x) + switch v.Kind() { + case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, + reflect.Ptr, reflect.Slice: + return v.IsNil() + } + + return false +} + +func (nilMatcher) String() string { + return "is nil" +} + +type notMatcher struct { + m Matcher +} + +func (n notMatcher) Matches(x interface{}) bool { + return !n.m.Matches(x) +} + +func (n notMatcher) String() string { + return "not(" + n.m.String() + ")" +} + +type assignableToTypeOfMatcher struct { + targetType reflect.Type +} + +func (m assignableToTypeOfMatcher) Matches(x interface{}) bool { + return reflect.TypeOf(x).AssignableTo(m.targetType) +} + +func (m assignableToTypeOfMatcher) String() string { + return "is assignable to " + m.targetType.Name() +} + +type allMatcher struct { + matchers []Matcher +} + +func (am allMatcher) Matches(x interface{}) bool { + for _, m := range am.matchers { + if !m.Matches(x) { + return false + } + } + return true +} + +func (am allMatcher) String() string { + ss := make([]string, 0, len(am.matchers)) + for _, matcher := range am.matchers { + ss = append(ss, matcher.String()) + } + return strings.Join(ss, "; ") +} + +type lenMatcher struct { + i int +} + +func (m lenMatcher) Matches(x interface{}) bool { + v := reflect.ValueOf(x) + switch v.Kind() { + case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice, reflect.String: + return v.Len() == m.i + default: + return false + } +} + +func (m lenMatcher) String() string { + return fmt.Sprintf("has length %d", m.i) +} + +type inAnyOrderMatcher struct { + x interface{} +} + +func (m inAnyOrderMatcher) Matches(x interface{}) bool { + given, ok := m.prepareValue(x) + if !ok { + return false + } + wanted, ok := m.prepareValue(m.x) + if !ok { + return false + } + + if given.Len() != wanted.Len() { + return false + } + + usedFromGiven := make([]bool, given.Len()) + foundFromWanted := make([]bool, wanted.Len()) + for i := 0; i < wanted.Len(); i++ { + wantedMatcher := Eq(wanted.Index(i).Interface()) + for j := 0; j < given.Len(); j++ { + if usedFromGiven[j] { + continue + } + if wantedMatcher.Matches(given.Index(j).Interface()) { + foundFromWanted[i] = true + usedFromGiven[j] = true + break + } + } + } + + missingFromWanted := 0 + for _, found := range foundFromWanted { + if !found { + missingFromWanted++ + } + } + extraInGiven := 0 + for _, used := range usedFromGiven { + if !used { + extraInGiven++ + } + } + + return extraInGiven == 0 && missingFromWanted == 0 +} + +func (m inAnyOrderMatcher) prepareValue(x interface{}) (reflect.Value, bool) { + xValue := reflect.ValueOf(x) + switch xValue.Kind() { + case reflect.Slice, reflect.Array: + return xValue, true + default: + return reflect.Value{}, false + } +} + +func (m inAnyOrderMatcher) String() string { + return fmt.Sprintf("has the same elements as %v", m.x) +} + +// Constructors + +// All returns a composite Matcher that returns true if and only all of the +// matchers return true. +func All(ms ...Matcher) Matcher { return allMatcher{ms} } + +// Any returns a matcher that always matches. +func Any() Matcher { return anyMatcher{} } + +// Eq returns a matcher that matches on equality. +// +// Example usage: +// Eq(5).Matches(5) // returns true +// Eq(5).Matches(4) // returns false +func Eq(x interface{}) Matcher { return eqMatcher{x} } + +// Len returns a matcher that matches on length. This matcher returns false if +// is compared to a type that is not an array, chan, map, slice, or string. +func Len(i int) Matcher { + return lenMatcher{i} +} + +// Nil returns a matcher that matches if the received value is nil. +// +// Example usage: +// var x *bytes.Buffer +// Nil().Matches(x) // returns true +// x = &bytes.Buffer{} +// Nil().Matches(x) // returns false +func Nil() Matcher { return nilMatcher{} } + +// Not reverses the results of its given child matcher. +// +// Example usage: +// Not(Eq(5)).Matches(4) // returns true +// Not(Eq(5)).Matches(5) // returns false +func Not(x interface{}) Matcher { + if m, ok := x.(Matcher); ok { + return notMatcher{m} + } + return notMatcher{Eq(x)} +} + +// AssignableToTypeOf is a Matcher that matches if the parameter to the mock +// function is assignable to the type of the parameter to this function. +// +// Example usage: +// var s fmt.Stringer = &bytes.Buffer{} +// AssignableToTypeOf(s).Matches(time.Second) // returns true +// AssignableToTypeOf(s).Matches(99) // returns false +// +// var ctx = reflect.TypeOf((*context.Context)(nil)).Elem() +// AssignableToTypeOf(ctx).Matches(context.Background()) // returns true +func AssignableToTypeOf(x interface{}) Matcher { + if xt, ok := x.(reflect.Type); ok { + return assignableToTypeOfMatcher{xt} + } + return assignableToTypeOfMatcher{reflect.TypeOf(x)} +} + +// InAnyOrder is a Matcher that returns true for collections of the same elements ignoring the order. +// +// Example usage: +// InAnyOrder([]int{1, 2, 3}).Matches([]int{1, 3, 2}) // returns true +// InAnyOrder([]int{1, 2, 3}).Matches([]int{1, 2}) // returns false +func InAnyOrder(x interface{}) Matcher { + return inAnyOrderMatcher{x} +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 4aceb8b12e4..f572de5674c 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -514,6 +514,9 @@ github.com/golang-jwt/jwt/v4 # github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da ## explicit github.com/golang/groupcache/lru +# github.com/golang/mock v1.6.0 +## explicit; go 1.11 +github.com/golang/mock/gomock # github.com/golang/protobuf v1.5.2 ## explicit; go 1.9 github.com/golang/protobuf/descriptor @@ -1057,6 +1060,8 @@ golang.org/x/crypto/ssh/knownhosts ## explicit; go 1.18 golang.org/x/exp/maps golang.org/x/exp/rand +# golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 +## explicit; go 1.17 # golang.org/x/net v0.0.0-20221012135044-0b7e1fb9d458 ## explicit; go 1.17 golang.org/x/net/context @@ -1113,6 +1118,8 @@ golang.org/x/text/unicode/norm # golang.org/x/time v0.0.0-20220922220347-f3bd1da661af ## explicit golang.org/x/time/rate +# golang.org/x/tools v0.1.12 +## explicit; go 1.18 # golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 ## explicit; go 1.17 golang.org/x/xerrors From 756813e042374112e9c7754a30567d765a17c317 Mon Sep 17 00:00:00 2001 From: Avdhesh Kumar Date: Thu, 20 Jul 2023 18:50:25 +0530 Subject: [PATCH 3/9] Add unit tests --- .../app/BuildPipelineRestHandler.go | 18 +- .../app/BuildPipelineRestHandler_test.go | 251 +++++ api/router/PipelineConfigRouter.go | 2 +- pkg/pipeline/CiCdPipelineOrchestrator.go | 30 +- pkg/pipeline/CiCdPipelineOrchestrator_test.go | 235 ++++- pkg/pipeline/PipelineBuilder.go | 182 ++-- pkg/pipeline/mock_pipeline/PipelineBuilder.go | 933 ++++++++++++++++++ pkg/user/UserService.go | 62 +- pkg/user/mocks/UserService.go | 321 ++++++ pkg/user/mocks/casbin/rbac.go | 144 +++ util/mocks/rbac/EnforcerUtil.go | 436 ++++++++ 11 files changed, 2424 insertions(+), 190 deletions(-) create mode 100644 api/restHandler/app/BuildPipelineRestHandler_test.go create mode 100644 pkg/pipeline/mock_pipeline/PipelineBuilder.go create mode 100644 pkg/user/mocks/UserService.go create mode 100644 pkg/user/mocks/casbin/rbac.go create mode 100644 util/mocks/rbac/EnforcerUtil.go diff --git a/api/restHandler/app/BuildPipelineRestHandler.go b/api/restHandler/app/BuildPipelineRestHandler.go index 3324fbd9877..970ef6535bc 100644 --- a/api/restHandler/app/BuildPipelineRestHandler.go +++ b/api/restHandler/app/BuildPipelineRestHandler.go @@ -43,7 +43,7 @@ type DevtronAppBuildRestHandler interface { GetExternalCi(w http.ResponseWriter, r *http.Request) GetExternalCiById(w http.ResponseWriter, r *http.Request) PatchCiPipelines(w http.ResponseWriter, r *http.Request) - PatchCiPipelinesSource(w http.ResponseWriter, r *http.Request) + PatchCiMaterialSource(w http.ResponseWriter, r *http.Request) TriggerCiPipeline(w http.ResponseWriter, r *http.Request) GetCiPipelineMin(w http.ResponseWriter, r *http.Request) GetCIPipelineById(w http.ResponseWriter, r *http.Request) @@ -250,7 +250,7 @@ func (handler PipelineConfigRestHandlerImpl) parseBranchChangeRequest(w http.Res return &patchRequest, userId, nil } -func (handler PipelineConfigRestHandlerImpl) authorizeBranchChangeRequest(w http.ResponseWriter, userId int32, patchRequest *bean.CiPipeline, token string) error { +func (handler PipelineConfigRestHandlerImpl) authorizeSourceChangeRequest(w http.ResponseWriter, userId int32, patchRequest *bean.CiPipeline, token string) error { isSuperAdmin, err := handler.userAuthService.IsSuperAdmin(int(userId)) if err != nil { common.WriteJsonResp(w, err, "failed to check if user is super admin", http.StatusInternalServerError) @@ -262,27 +262,35 @@ func (handler PipelineConfigRestHandlerImpl) authorizeBranchChangeRequest(w http common.WriteJsonResp(w, err, nil, http.StatusBadRequest) return err } - resourceName := handler.enforcerUtil.GetAppRBACName(app.AppName) + var ok bool if app.AppType == helper.Job { ok = isSuperAdmin } else { + resourceName := handler.enforcerUtil.GetAppRBACName(app.AppName) ok = handler.enforcer.Enforce(token, casbin.ResourceApplications, casbin.ActionCreate, resourceName) } if !ok { common.WriteJsonResp(w, fmt.Errorf("unauthorized user"), "Unauthorized User", http.StatusForbidden) + return fmt.Errorf("unauthorized user") + } + patchRequest.Name = app.AppName + err = handler.validator.Struct(patchRequest) + if err != nil { + handler.Logger.Errorw("validation err", "err", err) + common.WriteJsonResp(w, err, nil, http.StatusBadRequest) return err } return nil } -func (handler PipelineConfigRestHandlerImpl) PatchCiPipelinesSource(w http.ResponseWriter, r *http.Request) { +func (handler PipelineConfigRestHandlerImpl) PatchCiMaterialSource(w http.ResponseWriter, r *http.Request) { patchRequest, userId, err := handler.parseBranchChangeRequest(w, r) if err != nil { return } token := r.Header.Get("token") - if err = handler.authorizeBranchChangeRequest(w, userId, patchRequest, token); err != nil { + if err = handler.authorizeSourceChangeRequest(w, userId, patchRequest, token); err != nil { return } createResp, err := handler.pipelineBuilder.PatchCiMaterialSource(patchRequest, userId) diff --git a/api/restHandler/app/BuildPipelineRestHandler_test.go b/api/restHandler/app/BuildPipelineRestHandler_test.go new file mode 100644 index 00000000000..7d8d391cfed --- /dev/null +++ b/api/restHandler/app/BuildPipelineRestHandler_test.go @@ -0,0 +1,251 @@ +package app + +import ( + "bytes" + "fmt" + "github.com/devtron-labs/devtron/internal/sql/repository/helper" + "github.com/devtron-labs/devtron/internal/util" + "github.com/devtron-labs/devtron/pkg/bean" + "github.com/devtron-labs/devtron/pkg/pipeline/mock_pipeline" + mock_user "github.com/devtron-labs/devtron/pkg/user/mocks" + mock_casbin "github.com/devtron-labs/devtron/pkg/user/mocks/casbin" + mocks_rbac "github.com/devtron-labs/devtron/util/mocks/rbac" + "github.com/golang/mock/gomock" + "github.com/stretchr/testify/assert" + "gopkg.in/go-playground/validator.v9" + "net/http" + "net/http/httptest" + "testing" +) + +func TestPipelineConfigRestHandlerImpl_PatchCiMaterialSource(t *testing.T) { + logger, err := util.NewSugardLogger() + if err != nil { + panic(err) + } + type fields struct { + userAuthService *mock_user.MockUserService + pipelineBuilder *mock_pipeline.MockPipelineBuilder + validator *validator.Validate + enforcer *mock_casbin.MockEnforcer + enforcerUtil *mocks_rbac.MockEnforcerUtil + } + type args struct { + w http.ResponseWriter + r *http.Request + } + tests := []struct { + name string + fields fields + args args + body string + setup func(fields2 *fields) + expectedStatusCode int + }{ + { + name: "when user is not found, it should return unauthorized", + fields: fields{ + validator: validator.New(), + }, + body: "{\"appId\":4, \"id\": 5 ,\"ci--Material\":[{\"gitMaterialId\":4,\"id\":5,\"source\":{\"type\":\"SOURCE_TYPE_BRANCH_FIXED\",\"value\":\"main3\",\"regex\":\"\"}}]}", + setup: func(fields2 *fields) { + ctrl := gomock.NewController(t) + fields2.pipelineBuilder = mock_pipeline.NewMockPipelineBuilder(ctrl) + fields2.enforcer = mock_casbin.NewMockEnforcer(ctrl) + fields2.enforcerUtil = mocks_rbac.NewMockEnforcerUtil(ctrl) + fields2.userAuthService = mock_user.NewMockUserService(ctrl) + fields2.userAuthService.EXPECT().GetLoggedInUser(gomock.Any()).Return(int32(0), fmt.Errorf("user not found")).Times(1) + }, + expectedStatusCode: http.StatusUnauthorized, + }, + { + name: "when request is malformed, it should return bad request", + fields: fields{ + validator: validator.New(), + }, + body: "{\"appId\":4, \"id\": 5 ,-\"ciMaterial\":[{\"gitMaterialId\":4,\"id\":5,\"source\":{\"type\":\"SOURCE_TYPE_BRANCH_FIXED\",\"value\":\"main3\",\"regex\":\"\"}}]}", + setup: func(fields2 *fields) { + ctrl := gomock.NewController(t) + fields2.pipelineBuilder = mock_pipeline.NewMockPipelineBuilder(ctrl) + fields2.enforcer = mock_casbin.NewMockEnforcer(ctrl) + fields2.enforcerUtil = mocks_rbac.NewMockEnforcerUtil(ctrl) + fields2.userAuthService = mock_user.NewMockUserService(ctrl) + fields2.userAuthService.EXPECT().GetLoggedInUser(gomock.Any()).Return(int32(1), nil).Times(1) + }, + expectedStatusCode: http.StatusBadRequest, + }, + { + name: "when super admin check fails, it should return internal server error", + fields: fields{ + validator: validator.New(), + }, + body: "{\"appId\":4, \"id\": 5 ,\"ciMaterial\":[{\"gitMaterialId\":4,\"id\":5,\"source\":{\"type\":\"SOURCE_TYPE_BRANCH_FIXED\",\"value\":\"main3\",\"regex\":\"\"}}]}", + setup: func(fields2 *fields) { + ctrl := gomock.NewController(t) + fields2.pipelineBuilder = mock_pipeline.NewMockPipelineBuilder(ctrl) + fields2.enforcer = mock_casbin.NewMockEnforcer(ctrl) + fields2.enforcerUtil = mocks_rbac.NewMockEnforcerUtil(ctrl) + fields2.userAuthService = mock_user.NewMockUserService(ctrl) + fields2.userAuthService.EXPECT().GetLoggedInUser(gomock.Any()).Return(int32(1), nil).Times(1) + fields2.userAuthService.EXPECT().IsSuperAdmin(1).Return(false, fmt.Errorf("not a super admin")).Times(1) + }, + expectedStatusCode: http.StatusInternalServerError, + }, + { + name: "when app is not found for the given appId, it should return bad request", + fields: fields{ + validator: validator.New(), + }, + body: "{\"appId\":4, \"id\": 5 ,\"ciMaterial\":[{\"gitMaterialId\":4,\"id\":5,\"source\":{\"type\":\"SOURCE_TYPE_BRANCH_FIXED\",\"value\":\"main3\",\"regex\":\"\"}}]}", + setup: func(fields2 *fields) { + ctrl := gomock.NewController(t) + fields2.pipelineBuilder = mock_pipeline.NewMockPipelineBuilder(ctrl) + fields2.pipelineBuilder.EXPECT().GetApp(4).Return(nil, fmt.Errorf("app not found")).Times(1) + fields2.enforcer = mock_casbin.NewMockEnforcer(ctrl) + fields2.enforcerUtil = mocks_rbac.NewMockEnforcerUtil(ctrl) + fields2.userAuthService = mock_user.NewMockUserService(ctrl) + fields2.userAuthService.EXPECT().GetLoggedInUser(gomock.Any()).Return(int32(1), nil).Times(1) + fields2.userAuthService.EXPECT().IsSuperAdmin(1).Return(true, nil).Times(1) + }, + expectedStatusCode: http.StatusBadRequest, + }, + { + name: "when validator fails, it should return Bad request", + fields: fields{ + validator: validator.New(), + }, + body: "{\"appId\":4, \"id\": 5 ,\"ciMaterial\":[{\"gitMaterialId\":4,\"id\":5,\"source\":{\"type\":\"SOURCE_TYPE_BRANCH_FIXED\",\"value\":\"main3\",\"regex\":\"\"}}]}", + setup: func(fields2 *fields) { + ctrl := gomock.NewController(t) + _ = fields2.validator.RegisterValidation("name-component", func(fl validator.FieldLevel) bool { + return false + }) + fields2.pipelineBuilder = mock_pipeline.NewMockPipelineBuilder(ctrl) + fields2.pipelineBuilder.EXPECT().GetApp(4).Return(&bean.CreateAppDTO{AppName: "Super App", Id: 4, AppType: helper.Job}, nil).Times(1) + fields2.enforcer = mock_casbin.NewMockEnforcer(ctrl) + fields2.enforcerUtil = mocks_rbac.NewMockEnforcerUtil(ctrl) + //fields2.enforcerUtil.EXPECT().GetAppRBACName("Super App") + fields2.userAuthService = mock_user.NewMockUserService(ctrl) + fields2.userAuthService.EXPECT().GetLoggedInUser(gomock.Any()).Return(int32(1), nil).Times(1) + fields2.userAuthService.EXPECT().IsSuperAdmin(1).Return(true, nil).Times(1) + + }, + expectedStatusCode: http.StatusBadRequest, + }, + { + name: "when user is not a super admin, it should return forbidden", + fields: fields{ + validator: validator.New(), + }, + body: "{\"appId\":4, \"id\": 5 ,\"ciMaterial\":[{\"gitMaterialId\":4,\"id\":5,\"source\":{\"type\":\"SOURCE_TYPE_BRANCH_FIXED\",\"value\":\"main3\",\"regex\":\"\"}}]}", + setup: func(fields2 *fields) { + ctrl := gomock.NewController(t) + fields2.pipelineBuilder = mock_pipeline.NewMockPipelineBuilder(ctrl) + fields2.pipelineBuilder.EXPECT().GetApp(4).Return(&bean.CreateAppDTO{AppName: "Super App", Id: 4, AppType: helper.Job}, nil).Times(1) + fields2.enforcer = mock_casbin.NewMockEnforcer(ctrl) + fields2.enforcerUtil = mocks_rbac.NewMockEnforcerUtil(ctrl) + //fields2.enforcerUtil.EXPECT().GetAppRBACName("Super App") + fields2.userAuthService = mock_user.NewMockUserService(ctrl) + fields2.userAuthService.EXPECT().GetLoggedInUser(gomock.Any()).Return(int32(1), nil).Times(1) + fields2.userAuthService.EXPECT().IsSuperAdmin(1).Return(false, nil).Times(1) + + }, + expectedStatusCode: http.StatusForbidden, + }, + { + name: "when app is not jobtype and enforce fails, it should return forbidden", + fields: fields{ + validator: validator.New(), + }, + body: "{\"appId\":4, \"id\": 5 ,\"ciMaterial\":[{\"gitMaterialId\":4,\"id\":5,\"source\":{\"type\":\"SOURCE_TYPE_BRANCH_FIXED\",\"value\":\"main3\",\"regex\":\"\"}}]}", + setup: func(fields2 *fields) { + ctrl := gomock.NewController(t) + fields2.pipelineBuilder = mock_pipeline.NewMockPipelineBuilder(ctrl) + fields2.pipelineBuilder.EXPECT().GetApp(4).Return(&bean.CreateAppDTO{AppName: "Super App", Id: 4, AppType: helper.CustomApp}, nil).Times(1) + fields2.enforcer = mock_casbin.NewMockEnforcer(ctrl) + fields2.enforcer.EXPECT().Enforce(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(false).Times(1) + + fields2.enforcerUtil = mocks_rbac.NewMockEnforcerUtil(ctrl) + fields2.enforcerUtil.EXPECT().GetAppRBACName("Super App") + fields2.userAuthService = mock_user.NewMockUserService(ctrl) + fields2.userAuthService.EXPECT().GetLoggedInUser(gomock.Any()).Return(int32(1), nil).Times(1) + fields2.userAuthService.EXPECT().IsSuperAdmin(1).Return(false, nil).Times(1) + + }, + expectedStatusCode: http.StatusForbidden, + }, + { + name: "when PatchCiMaterialSource call fails, it should return internal server error", + fields: fields{ + validator: validator.New(), + }, + body: "{\"appId\":4, \"id\": 5 ,\"ciMaterial\":[{\"gitMaterialId\":4,\"id\":5,\"source\":{\"type\":\"SOURCE_TYPE_BRANCH_FIXED\",\"value\":\"main3\",\"regex\":\"\"}}]}", + setup: func(fields2 *fields) { + _ = fields2.validator.RegisterValidation("name-component", func(fl validator.FieldLevel) bool { + return true + }) + ctrl := gomock.NewController(t) + fields2.pipelineBuilder = mock_pipeline.NewMockPipelineBuilder(ctrl) + fields2.pipelineBuilder.EXPECT().GetApp(4).Return(&bean.CreateAppDTO{AppName: "Super App", Id: 4, AppType: helper.CustomApp}, nil).Times(1) + fields2.pipelineBuilder.EXPECT().PatchCiMaterialSource(gomock.Any(), int32(1)).Return(nil, fmt.Errorf("failed to patch")) + fields2.enforcer = mock_casbin.NewMockEnforcer(ctrl) + fields2.enforcer.EXPECT().Enforce(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(true).Times(1) + fields2.enforcerUtil = mocks_rbac.NewMockEnforcerUtil(ctrl) + fields2.enforcerUtil.EXPECT().GetAppRBACName("Super App") + fields2.userAuthService = mock_user.NewMockUserService(ctrl) + fields2.userAuthService.EXPECT().GetLoggedInUser(gomock.Any()).Return(int32(1), nil).Times(1) + fields2.userAuthService.EXPECT().IsSuperAdmin(1).Return(false, nil).Times(1) + + }, + expectedStatusCode: http.StatusInternalServerError, + }, + { + name: "when PatchCiMaterialSource call passes, it should return statusok", + fields: fields{ + validator: validator.New(), + }, + body: "{\"appId\":4, \"id\": 5 ,\"ciMaterial\":[{\"gitMaterialId\":4,\"id\":5,\"source\":{\"type\":\"SOURCE_TYPE_BRANCH_FIXED\",\"value\":\"main3\",\"regex\":\"\"}}]}", + setup: func(fields2 *fields) { + _ = fields2.validator.RegisterValidation("name-component", func(fl validator.FieldLevel) bool { + return true + }) + ctrl := gomock.NewController(t) + fields2.pipelineBuilder = mock_pipeline.NewMockPipelineBuilder(ctrl) + fields2.pipelineBuilder.EXPECT().GetApp(4).Return(&bean.CreateAppDTO{AppName: "Super App", Id: 4, AppType: helper.CustomApp}, nil).Times(1) + fields2.pipelineBuilder.EXPECT().PatchCiMaterialSource(gomock.Any(), int32(1)).Return(&bean.CiPipeline{Id: 1}, nil) + fields2.enforcer = mock_casbin.NewMockEnforcer(ctrl) + fields2.enforcer.EXPECT().Enforce(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(true).Times(1) + fields2.enforcerUtil = mocks_rbac.NewMockEnforcerUtil(ctrl) + fields2.enforcerUtil.EXPECT().GetAppRBACName("Super App") + fields2.userAuthService = mock_user.NewMockUserService(ctrl) + fields2.userAuthService.EXPECT().GetLoggedInUser(gomock.Any()).Return(int32(1), nil).Times(1) + fields2.userAuthService.EXPECT().IsSuperAdmin(1).Return(false, nil).Times(1) + + }, + expectedStatusCode: http.StatusOK, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.setup(&tt.fields) + handler := PipelineConfigRestHandlerImpl{ + userAuthService: tt.fields.userAuthService, + pipelineBuilder: tt.fields.pipelineBuilder, + validator: tt.fields.validator, + enforcer: tt.fields.enforcer, + enforcerUtil: tt.fields.enforcerUtil, + Logger: logger, + } + + req, err := http.NewRequest("PATCH", "/orchestrator/app/ci-pipeline/patch-branch", bytes.NewBuffer([]byte(tt.body))) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Content-Type", "application/json") + rr := httptest.NewRecorder() + h := http.HandlerFunc(handler.PatchCiMaterialSource) + h.ServeHTTP(rr, req) + assert.Equal(t, rr.Code, tt.expectedStatusCode) + }) + } +} diff --git a/api/router/PipelineConfigRouter.go b/api/router/PipelineConfigRouter.go index 13fc3803cef..908e44754e2 100644 --- a/api/router/PipelineConfigRouter.go +++ b/api/router/PipelineConfigRouter.go @@ -85,7 +85,7 @@ func (router PipelineConfigRouterImpl) initPipelineConfigRouter(configRouter *mu configRouter.Path("/external-ci/{appId}/{externalCiId}").HandlerFunc(router.restHandler.GetExternalCiById).Methods("GET") configRouter.Path("/ci-pipeline/template/patch").HandlerFunc(router.restHandler.UpdateCiTemplate).Methods("POST") configRouter.Path("/ci-pipeline/patch").HandlerFunc(router.restHandler.PatchCiPipelines).Methods("POST") - configRouter.Path("/ci-pipeline/patch-branch").HandlerFunc(router.restHandler.PatchCiPipelinesSource).Methods("PATCH") + configRouter.Path("/ci-pipeline/patch-branch").HandlerFunc(router.restHandler.PatchCiMaterialSource).Methods("PATCH") configRouter.Path("/ci-pipeline/patch/regex").HandlerFunc(router.restHandler.UpdateBranchCiPipelinesWithRegex).Methods("POST") configRouter.Path("/cd-pipeline/{cd_pipeline_id}/material").HandlerFunc(router.restHandler.GetArtifactsByCDPipeline).Methods("GET") diff --git a/pkg/pipeline/CiCdPipelineOrchestrator.go b/pkg/pipeline/CiCdPipelineOrchestrator.go index 50b51c884c5..4a8b3b2c06c 100644 --- a/pkg/pipeline/CiCdPipelineOrchestrator.go +++ b/pkg/pipeline/CiCdPipelineOrchestrator.go @@ -174,28 +174,20 @@ func (impl CiCdPipelineOrchestratorImpl) PatchCiMaterialSource(ciPipeline *bean. } func mapCiMaterialToPipelineMaterial(ciPipeline *bean.CiPipeline, userId int32, oldPipeline *pipelineConfig.CiPipeline) []*pipelineConfig.CiPipelineMaterial { - createOnTimeMap := make(map[int]time.Time) - createByMap := make(map[int]int32) - materialsUpdate := make([]*pipelineConfig.CiPipelineMaterial, 0) + updatedMaterials := make([]*pipelineConfig.CiPipelineMaterial, 0) + oldPipelineMaterials := make(map[int]*pipelineConfig.CiPipelineMaterial) for _, oldMaterial := range oldPipeline.CiPipelineMaterials { - createOnTimeMap[oldMaterial.GitMaterialId] = oldMaterial.CreatedOn - createByMap[oldMaterial.GitMaterialId] = oldMaterial.CreatedBy + oldPipelineMaterials[oldMaterial.Id] = oldMaterial } for _, ciMaterial := range ciPipeline.CiMaterial { - pipelineMaterial := &pipelineConfig.CiPipelineMaterial{ - Id: ciMaterial.Id, - CiPipelineId: ciPipeline.Id, - Value: ciMaterial.Source.Value, - Type: ciMaterial.Source.Type, - Active: oldPipeline.Active, - Regex: ciMaterial.Source.Regex, - GitMaterialId: ciMaterial.GitMaterialId, - AuditLog: sql.AuditLog{UpdatedBy: userId, UpdatedOn: time.Now(), CreatedBy: createByMap[ciMaterial.GitMaterialId], CreatedOn: createOnTimeMap[ciMaterial.GitMaterialId]}, - } - pipelineMaterial.CiPipelineId = ciMaterial.Id - materialsUpdate = append(materialsUpdate, pipelineMaterial) - } - return materialsUpdate + pipelineMaterial := *oldPipelineMaterials[ciMaterial.Id] + pipelineMaterial.Type = ciMaterial.Source.Type + pipelineMaterial.Regex = ciMaterial.Source.Regex + pipelineMaterial.Value = ciMaterial.Source.Value + pipelineMaterial.AuditLog = sql.AuditLog{CreatedOn: oldPipelineMaterials[ciMaterial.Id].CreatedOn, CreatedBy: oldPipelineMaterials[ciMaterial.Id].CreatedBy, UpdatedOn: time.Now(), UpdatedBy: userId} + updatedMaterials = append(updatedMaterials, &pipelineMaterial) + } + return updatedMaterials } func (impl CiCdPipelineOrchestratorImpl) saveUpdatedMaterial(materialsUpdate []*pipelineConfig.CiPipelineMaterial) error { diff --git a/pkg/pipeline/CiCdPipelineOrchestrator_test.go b/pkg/pipeline/CiCdPipelineOrchestrator_test.go index f6b0739559b..c65ab482aed 100644 --- a/pkg/pipeline/CiCdPipelineOrchestrator_test.go +++ b/pkg/pipeline/CiCdPipelineOrchestrator_test.go @@ -18,10 +18,12 @@ import ( repository3 "github.com/devtron-labs/devtron/pkg/cluster/repository" "github.com/devtron-labs/devtron/pkg/pipeline/history" repository4 "github.com/devtron-labs/devtron/pkg/pipeline/history/repository" + "github.com/devtron-labs/devtron/pkg/sql" "github.com/devtron-labs/devtron/pkg/user" "github.com/stretchr/testify/assert" "log" "testing" + "time" ) var ( @@ -176,52 +178,199 @@ func TestPatchCiMaterialSourceWhenOldPipelineIsNotFoundItShouldReturnError(t *te assert.Nil(t, res) } -//func TestPatchCiMaterialSourceWhenOldPipelineExistsAndSaveUpdatedMaterialFailsItShouldReturnError(t *testing.T) { -// //ctrl := gomock.NewController(t) -// userId := int32(10) -// oldPipeline := &bean.CiPipeline{ -// ParentAppId: 0, -// AppId: 4, -// CiMaterial: []*bean.CiMaterial{ -// { -// Source: &bean.SourceTypeConfig{ -// Type: "SOURCE_TYPE_BRANCH_FIXED", -// Value: "main", +// func TestPatchCiMaterialSourceWhenOldPipelineExistsAndSaveUpdatedMaterialFailsItShouldReturnError(t *testing.T) { +// //ctrl := gomock.NewController(t) +// userId := int32(10) +// oldPipeline := &bean.CiPipeline{ +// ParentAppId: 0, +// AppId: 4, +// CiMaterial: []*bean.CiMaterial{ +// { +// Source: &bean.SourceTypeConfig{ +// Type: "SOURCE_TYPE_BRANCH_FIXED", +// Value: "main", +// }, +// Id: 0, +// IsRegex: false, // }, -// Id: 0, -// IsRegex: false, // }, -// }, -// Id: 1, -// Active: false, -// } +// Id: 1, +// Active: false, +// } // -// newPipeline := &bean.CiPipeline{ -// ParentAppId: 0, -// AppId: 4, -// CiMaterial: []*bean.CiMaterial{ -// { -// Source: &bean.SourceTypeConfig{ -// Type: "SOURCE_TYPE_BRANCH_FIXED", -// Value: "main", +// newPipeline := &bean.CiPipeline{ +// ParentAppId: 0, +// AppId: 4, +// CiMaterial: []*bean.CiMaterial{ +// { +// Source: &bean.SourceTypeConfig{ +// Type: "SOURCE_TYPE_BRANCH_FIXED", +// Value: "main", +// }, +// Id: 1, +// IsRegex: false, // }, -// Id: 1, -// IsRegex: false, // }, -// }, -// Id: 0, -// Active: false, -// } -// mockedCiPipelineRepository := mocks.NewCiPipelineRepository(t) -// mockedCiPipelineRepository.On("FindById", newPipeline.Id).Return(oldPipeline, nil) -// //mockedCiPipelineMaterialRepository := &mocks.MockCiPipelineMaterialRepository{} -// //mockedGitSensor := &mock_gitSensor.MockClient{} -// impl := CiCdPipelineOrchestratorImpl{ -// ciPipelineRepository: mockedCiPipelineRepository, -// //ciPipelineMaterialRepository: mockedCiPipelineMaterialRepository, -// //GitSensorClient: mockedGitSensor, +// Id: 0, +// Active: false, +// } +// mockedCiPipelineRepository := mocks.NewCiPipelineRepository(t) +// mockedCiPipelineRepository.On("FindById", newPipeline.Id).Return(oldPipeline, nil) +// //mockedCiPipelineMaterialRepository := &mocks.MockCiPipelineMaterialRepository{} +// //mockedGitSensor := &mock_gitSensor.MockClient{} +// impl := CiCdPipelineOrchestratorImpl{ +// ciPipelineRepository: mockedCiPipelineRepository, +// //ciPipelineMaterialRepository: mockedCiPipelineMaterialRepository, +// //GitSensorClient: mockedGitSensor, +// } +// res, err := impl.PatchCiMaterialSource(pipeline, userId) +// assert.Error(t, err) +// assert.Nil(t, res) // } -// res, err := impl.PatchCiMaterialSource(pipeline, userId) -// assert.Error(t, err) -// assert.Nil(t, res) -//} +func Test_mapCiMaterialToPipelineMaterial(t *testing.T) { + t1 := time.Now() + t2 := time.Now() + type args struct { + ciPipeline *bean.CiPipeline + userId int32 + oldPipeline *pipelineConfig.CiPipeline + } + tests := []struct { + name string + args args + want []*pipelineConfig.CiPipelineMaterial + }{ + { + name: "It should return []*pipelineConfig.CiPipelineMaterial with only source changed", + args: args{ + ciPipeline: &bean.CiPipeline{ + AppId: 0, + CiMaterial: []*bean.CiMaterial{ + { + Source: &bean.SourceTypeConfig{ + Type: "QWERTY", + Value: "masterrrrr", + Regex: "A@$%DS", + }, + Id: 2, + GitMaterialId: 2, + }, + }, + Id: 2, + }, + userId: 1, + oldPipeline: &pipelineConfig.CiPipeline{ + Id: 1, + AppId: 2, + App: nil, + CiTemplateId: 3, + DockerArgs: "abc", + Name: "def", + Version: "234", + Active: true, + Deleted: false, + IsManual: true, + IsExternal: false, + ParentCiPipeline: 0, + ScanEnabled: false, + IsDockerConfigOverridden: false, + AuditLog: sql.AuditLog{ + CreatedOn: t1, + CreatedBy: 2, + UpdatedOn: t2, + UpdatedBy: 1, + }, + CiPipelineMaterials: []*pipelineConfig.CiPipelineMaterial{ + { + Id: 2, + GitMaterialId: 2, + CiPipelineId: 2, + Path: "", + CheckoutPath: "", + Type: "ABC", + Value: "DEF", + ScmId: "", + ScmName: "", + ScmVersion: "", + Active: false, + Regex: "A$%", + GitTag: "", + CiPipeline: nil, + GitMaterial: nil, + AuditLog: sql.AuditLog{ + CreatedOn: t1, + CreatedBy: 2, + UpdatedOn: t1, + UpdatedBy: 2, + }, + }, + { + Id: 3, + GitMaterialId: 2, + CiPipelineId: 2, + Path: "", + CheckoutPath: "", + Type: "ABC123", + Value: "main", + ScmId: "", + ScmName: "", + ScmVersion: "", + Active: false, + Regex: "A$%a3e2", + GitTag: "sdf", + CiPipeline: nil, + GitMaterial: nil, + AuditLog: sql.AuditLog{ + CreatedOn: t1, + CreatedBy: 2, + UpdatedOn: t1, + UpdatedBy: 2, + }, + }, + }, + CiTemplate: nil, + }, + }, + want: []*pipelineConfig.CiPipelineMaterial{ + { + Id: 2, + GitMaterialId: 2, + CiPipelineId: 2, + Path: "", + CheckoutPath: "", + Type: "QWERTY", + Value: "masterrrrr", + Regex: "A@$%DS", + ScmId: "", + ScmName: "", + ScmVersion: "", + Active: false, + GitTag: "", + CiPipeline: nil, + GitMaterial: nil, + AuditLog: sql.AuditLog{ + CreatedOn: t1, + CreatedBy: 2, + UpdatedOn: t2, + UpdatedBy: 1, + }, + }, + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + res := mapCiMaterialToPipelineMaterial(tt.args.ciPipeline, tt.args.userId, tt.args.oldPipeline) + assert.Equal(t, len(res), 1) + assert.Equal(t, tt.want[0].Id, res[0].Id) + assert.Equal(t, tt.want[0].GitMaterialId, res[0].GitMaterialId) + assert.Equal(t, tt.want[0].CiPipelineId, res[0].CiPipelineId) + assert.Equal(t, tt.want[0].Type, res[0].Type) + assert.Equal(t, tt.want[0].Value, res[0].Value) + assert.Equal(t, tt.want[0].Regex, res[0].Regex) + assert.Equal(t, tt.want[0].AuditLog.CreatedBy, res[0].AuditLog.CreatedBy) + assert.Equal(t, tt.want[0].AuditLog.CreatedOn, res[0].AuditLog.CreatedOn) + assert.Equal(t, tt.want[0].AuditLog.UpdatedBy, res[0].AuditLog.UpdatedBy) + }) + } +} diff --git a/pkg/pipeline/PipelineBuilder.go b/pkg/pipeline/PipelineBuilder.go index fee0f8e309d..d152838dff9 100644 --- a/pkg/pipeline/PipelineBuilder.go +++ b/pkg/pipeline/PipelineBuilder.go @@ -373,7 +373,7 @@ func formatDate(t time.Time, layout string) string { return t.Format(layout) } -func (impl PipelineBuilderImpl) CreateApp(request *bean.CreateAppDTO) (*bean.CreateAppDTO, error) { +func (impl *PipelineBuilderImpl) CreateApp(request *bean.CreateAppDTO) (*bean.CreateAppDTO, error) { impl.logger.Debugw("app create request received", "req", request) res, err := impl.ciCdPipelineOrchestrator.CreateApp(request) @@ -383,13 +383,13 @@ func (impl PipelineBuilderImpl) CreateApp(request *bean.CreateAppDTO) (*bean.Cre return res, err } -func (impl PipelineBuilderImpl) DeleteApp(appId int, userId int32) error { +func (impl *PipelineBuilderImpl) DeleteApp(appId int, userId int32) error { impl.logger.Debugw("app delete request received", "app", appId) err := impl.ciCdPipelineOrchestrator.DeleteApp(appId, userId) return err } -func (impl PipelineBuilderImpl) CreateMaterialsForApp(request *bean.CreateMaterialDTO) (*bean.CreateMaterialDTO, error) { +func (impl *PipelineBuilderImpl) CreateMaterialsForApp(request *bean.CreateMaterialDTO) (*bean.CreateMaterialDTO, error) { res, err := impl.ciCdPipelineOrchestrator.CreateMaterials(request) if err != nil { impl.logger.Errorw("error in saving create materials req", "req", request, "err", err) @@ -397,7 +397,7 @@ func (impl PipelineBuilderImpl) CreateMaterialsForApp(request *bean.CreateMateri return res, err } -func (impl PipelineBuilderImpl) UpdateMaterialsForApp(request *bean.UpdateMaterialDTO) (*bean.UpdateMaterialDTO, error) { +func (impl *PipelineBuilderImpl) UpdateMaterialsForApp(request *bean.UpdateMaterialDTO) (*bean.UpdateMaterialDTO, error) { res, err := impl.ciCdPipelineOrchestrator.UpdateMaterial(request) if err != nil { impl.logger.Errorw("error in updating materials req", "req", request, "err", err) @@ -405,7 +405,7 @@ func (impl PipelineBuilderImpl) UpdateMaterialsForApp(request *bean.UpdateMateri return res, err } -func (impl PipelineBuilderImpl) DeleteMaterial(request *bean.UpdateMaterialDTO) error { +func (impl *PipelineBuilderImpl) DeleteMaterial(request *bean.UpdateMaterialDTO) error { //finding ci pipelines for this app; if found any, will not delete git material pipelines, err := impl.ciPipelineRepository.FindByAppId(request.AppId) if err != nil && err != pg.ErrNoRows { @@ -446,7 +446,7 @@ func (impl PipelineBuilderImpl) DeleteMaterial(request *bean.UpdateMaterialDTO) return nil } -func (impl PipelineBuilderImpl) GetApp(appId int) (application *bean.CreateAppDTO, err error) { +func (impl *PipelineBuilderImpl) GetApp(appId int) (application *bean.CreateAppDTO, err error) { app, err := impl.appRepo.FindById(appId) if err != nil { impl.logger.Errorw("error in fetching app", "id", appId, "err", err) @@ -470,7 +470,7 @@ func (impl PipelineBuilderImpl) GetApp(appId int) (application *bean.CreateAppDT return application, nil } -func (impl PipelineBuilderImpl) GetMaterialsForAppId(appId int) []*bean.GitMaterial { +func (impl *PipelineBuilderImpl) GetMaterialsForAppId(appId int) []*bean.GitMaterial { materials, err := impl.materialRepo.FindByAppId(appId) if err != nil { impl.logger.Errorw("error in fetching materials", "appId", appId, "err", err) @@ -510,7 +510,7 @@ func (impl PipelineBuilderImpl) GetMaterialsForAppId(appId int) []*bean.GitMater */ -func (impl PipelineBuilderImpl) getDefaultArtifactStore(id string) (store *dockerRegistryRepository.DockerArtifactStore, err error) { +func (impl *PipelineBuilderImpl) getDefaultArtifactStore(id string) (store *dockerRegistryRepository.DockerArtifactStore, err error) { if id == "" { impl.logger.Debugw("docker repo is empty adding default repo") store, err = impl.dockerArtifactStoreRepository.FindActiveDefaultStore() @@ -521,7 +521,7 @@ func (impl PipelineBuilderImpl) getDefaultArtifactStore(id string) (store *docke return } -func (impl PipelineBuilderImpl) getCiTemplateVariables(appId int) (ciConfig *bean.CiConfigRequest, err error) { +func (impl *PipelineBuilderImpl) getCiTemplateVariables(appId int) (ciConfig *bean.CiConfigRequest, err error) { ciTemplateBean, err := impl.ciTemplateService.FindByAppId(appId) if err != nil && !errors.IsNotFound(err) { impl.logger.Errorw("error in fetching ci pipeline", "appId", appId, "err", err) @@ -585,7 +585,7 @@ func (impl PipelineBuilderImpl) getCiTemplateVariables(appId int) (ciConfig *bea return ciConfig, err } -func (impl PipelineBuilderImpl) getCiTemplateVariablesByAppIds(appIds []int) (map[int]*bean.CiConfigRequest, error) { +func (impl *PipelineBuilderImpl) getCiTemplateVariablesByAppIds(appIds []int) (map[int]*bean.CiConfigRequest, error) { ciConfigMap := make(map[int]*bean.CiConfigRequest) ciTemplateMap, err := impl.ciTemplateService.FindByAppIds(appIds) if err != nil && !errors.IsNotFound(err) { @@ -655,7 +655,7 @@ func (impl PipelineBuilderImpl) getCiTemplateVariablesByAppIds(appIds []int) (ma return ciConfigMap, err } -func (impl PipelineBuilderImpl) GetTriggerViewCiPipeline(appId int) (*bean.TriggerViewCiConfig, error) { +func (impl *PipelineBuilderImpl) GetTriggerViewCiPipeline(appId int) (*bean.TriggerViewCiConfig, error) { triggerViewCiConfig := &bean.TriggerViewCiConfig{} @@ -740,7 +740,7 @@ func (impl PipelineBuilderImpl) GetTriggerViewCiPipeline(appId int) (*bean.Trigg return triggerViewCiConfig, nil } -func (impl PipelineBuilderImpl) GetCiPipeline(appId int) (ciConfig *bean.CiConfigRequest, err error) { +func (impl *PipelineBuilderImpl) GetCiPipeline(appId int) (ciConfig *bean.CiConfigRequest, err error) { ciConfig, err = impl.getCiTemplateVariables(appId) if err != nil { impl.logger.Debugw("error in fetching ci pipeline", "appId", appId, "err", err) @@ -891,7 +891,7 @@ func (impl PipelineBuilderImpl) GetCiPipeline(appId int) (ciConfig *bean.CiConfi return ciConfig, err } -func (impl PipelineBuilderImpl) GetExternalCi(appId int) (ciConfig []*bean.ExternalCiConfig, err error) { +func (impl *PipelineBuilderImpl) GetExternalCi(appId int) (ciConfig []*bean.ExternalCiConfig, err error) { externalCiPipelines, err := impl.ciPipelineRepository.FindExternalCiByAppId(appId) if err != nil && !util.IsErrNoRows(err) { impl.logger.Errorw("error in fetching external ci", "appId", appId, "err", err) @@ -1017,7 +1017,7 @@ func (impl PipelineBuilderImpl) GetExternalCi(appId int) (ciConfig []*bean.Exter return externalCiConfigs, err } -func (impl PipelineBuilderImpl) GetExternalCiById(appId int, externalCiId int) (ciConfig *bean.ExternalCiConfig, err error) { +func (impl *PipelineBuilderImpl) GetExternalCiById(appId int, externalCiId int) (ciConfig *bean.ExternalCiConfig, err error) { externalCiPipeline, err := impl.ciPipelineRepository.FindExternalCiById(externalCiId) if err != nil && !util.IsErrNoRows(err) { @@ -1097,7 +1097,7 @@ func (impl PipelineBuilderImpl) GetExternalCiById(appId int, externalCiId int) ( return externalCiConfig, err } -func (impl PipelineBuilderImpl) GetCiPipelineMin(appId int) ([]*bean.CiPipelineMin, error) { +func (impl *PipelineBuilderImpl) GetCiPipelineMin(appId int) ([]*bean.CiPipelineMin, error) { pipelines, err := impl.ciPipelineRepository.FindByAppId(appId) if err != nil && err != pg.ErrNoRows { impl.logger.Errorw("error in fetching ci pipeline", "appId", appId, "err", err) @@ -1143,7 +1143,7 @@ func (impl PipelineBuilderImpl) GetCiPipelineMin(appId int) ([]*bean.CiPipelineM return ciPipelineResp, err } -func (impl PipelineBuilderImpl) UpdateCiTemplate(updateRequest *bean.CiConfigRequest) (*bean.CiConfigRequest, error) { +func (impl *PipelineBuilderImpl) UpdateCiTemplate(updateRequest *bean.CiConfigRequest) (*bean.CiConfigRequest, error) { originalCiConf, err := impl.getCiTemplateVariables(updateRequest.AppId) if err != nil { impl.logger.Errorw("error in fetching original ciConfig for update", "appId", updateRequest.Id, "err", err) @@ -1249,7 +1249,7 @@ func (impl PipelineBuilderImpl) UpdateCiTemplate(updateRequest *bean.CiConfigReq return originalCiConf, nil } -func (impl PipelineBuilderImpl) CreateCiPipeline(createRequest *bean.CiConfigRequest) (*bean.PipelineCreateResponse, error) { +func (impl *PipelineBuilderImpl) CreateCiPipeline(createRequest *bean.CiConfigRequest) (*bean.PipelineCreateResponse, error) { impl.logger.Debugw("pipeline create request received", "req", createRequest) //-----------fetch data @@ -1359,7 +1359,7 @@ func (impl PipelineBuilderImpl) CreateCiPipeline(createRequest *bean.CiConfigReq return createRes, nil } -func (impl PipelineBuilderImpl) getGitMaterialsForApp(appId int) ([]*bean.GitMaterial, error) { +func (impl *PipelineBuilderImpl) getGitMaterialsForApp(appId int) ([]*bean.GitMaterial, error) { materials, err := impl.materialRepo.FindByAppId(appId) if err != nil { impl.logger.Errorw("error in fetching materials for app", "appId", appId, "err", err) @@ -1404,7 +1404,7 @@ func (impl PipelineBuilderImpl) getGitMaterialsForApp(appId int) ([]*bean.GitMat return gitMaterials, nil } -func (impl PipelineBuilderImpl) addpipelineToTemplate(createRequest *bean.CiConfigRequest) (resp *bean.CiConfigRequest, err error) { +func (impl *PipelineBuilderImpl) addpipelineToTemplate(createRequest *bean.CiConfigRequest) (resp *bean.CiConfigRequest, err error) { if createRequest.AppWorkflowId == 0 { // create workflow @@ -1456,7 +1456,7 @@ func (impl PipelineBuilderImpl) addpipelineToTemplate(createRequest *bean.CiConf return createRequest, err } -func (impl PipelineBuilderImpl) PatchCiPipeline(request *bean.CiPatchRequest) (ciConfig *bean.CiConfigRequest, err error) { +func (impl *PipelineBuilderImpl) PatchCiPipeline(request *bean.CiPatchRequest) (ciConfig *bean.CiConfigRequest, err error) { ciConfig, err = impl.getCiTemplateVariables(request.AppId) if err != nil { impl.logger.Errorw("err in fetching template for pipeline patch, ", "err", err, "appId", request.AppId) @@ -1501,7 +1501,7 @@ func (impl PipelineBuilderImpl) PatchCiPipeline(request *bean.CiPatchRequest) (c } -func (impl PipelineBuilderImpl) PatchRegexCiPipeline(request *bean.CiRegexPatchRequest) (err error) { +func (impl *PipelineBuilderImpl) PatchRegexCiPipeline(request *bean.CiRegexPatchRequest) (err error) { var materials []*pipelineConfig.CiPipelineMaterial for _, material := range request.CiPipelineMaterial { materialDbObject, err := impl.ciPipelineMaterialRepository.GetById(material.Id) @@ -1553,7 +1553,7 @@ func (impl PipelineBuilderImpl) PatchRegexCiPipeline(request *bean.CiRegexPatchR } return nil } -func (impl PipelineBuilderImpl) DeleteCiPipeline(request *bean.CiPatchRequest) (*bean.CiPipeline, error) { +func (impl *PipelineBuilderImpl) DeleteCiPipeline(request *bean.CiPatchRequest) (*bean.CiPipeline, error) { ciPipelineId := request.CiPipeline.Id //wf validation workflowMapping, err := impl.appWorkflowRepository.FindWFCDMappingByCIPipelineId(ciPipelineId) @@ -1629,11 +1629,11 @@ func (impl PipelineBuilderImpl) DeleteCiPipeline(request *bean.CiPatchRequest) ( } -func (impl PipelineBuilderImpl) PatchCiMaterialSource(ciPipeline *bean.CiPipeline, userId int32) (*bean.CiPipeline, error) { +func (impl *PipelineBuilderImpl) PatchCiMaterialSource(ciPipeline *bean.CiPipeline, userId int32) (*bean.CiPipeline, error) { return impl.ciCdPipelineOrchestrator.PatchCiMaterialSource(ciPipeline, userId) } -func (impl PipelineBuilderImpl) patchCiPipelineUpdateSource(baseCiConfig *bean.CiConfigRequest, modifiedCiPipeline *bean.CiPipeline) (ciConfig *bean.CiConfigRequest, err error) { +func (impl *PipelineBuilderImpl) patchCiPipelineUpdateSource(baseCiConfig *bean.CiConfigRequest, modifiedCiPipeline *bean.CiPipeline) (ciConfig *bean.CiConfigRequest, err error) { pipeline, err := impl.ciPipelineRepository.FindById(modifiedCiPipeline.Id) if err != nil { @@ -1664,7 +1664,7 @@ func (impl PipelineBuilderImpl) patchCiPipelineUpdateSource(baseCiConfig *bean.C } -func (impl PipelineBuilderImpl) IsGitopsConfigured() (bool, error) { +func (impl *PipelineBuilderImpl) IsGitopsConfigured() (bool, error) { isGitOpsConfigured := false gitOpsConfig, err := impl.gitOpsRepository.GetGitOpsConfigActive() @@ -1681,7 +1681,7 @@ func (impl PipelineBuilderImpl) IsGitopsConfigured() (bool, error) { } -func (impl PipelineBuilderImpl) ValidateCDPipelineRequest(pipelineCreateRequest *bean.CdPipelines, isGitOpsConfigured, haveAtleastOneGitOps bool) (bool, error) { +func (impl *PipelineBuilderImpl) ValidateCDPipelineRequest(pipelineCreateRequest *bean.CdPipelines, isGitOpsConfigured, haveAtleastOneGitOps bool) (bool, error) { if isGitOpsConfigured == false && haveAtleastOneGitOps { impl.logger.Errorw("Gitops not configured but selected in creating cd pipeline") @@ -1741,7 +1741,7 @@ func (impl PipelineBuilderImpl) ValidateCDPipelineRequest(pipelineCreateRequest } -func (impl PipelineBuilderImpl) RegisterInACD(gitOpsRepoName string, chartGitAttr *util.ChartGitAttribute, userId int32, ctx context.Context) error { +func (impl *PipelineBuilderImpl) RegisterInACD(gitOpsRepoName string, chartGitAttr *util.ChartGitAttribute, userId int32, ctx context.Context) error { err := impl.chartDeploymentService.RegisterInArgo(chartGitAttr, ctx) if err != nil { @@ -1768,7 +1768,7 @@ func (impl PipelineBuilderImpl) RegisterInACD(gitOpsRepoName string, chartGitAtt return nil } -func (impl PipelineBuilderImpl) IsGitOpsRequiredForCD(pipelineCreateRequest *bean.CdPipelines) bool { +func (impl *PipelineBuilderImpl) IsGitOpsRequiredForCD(pipelineCreateRequest *bean.CdPipelines) bool { // if deploymentAppType is not coming in request than hasAtLeastOneGitOps will be false @@ -1781,7 +1781,7 @@ func (impl PipelineBuilderImpl) IsGitOpsRequiredForCD(pipelineCreateRequest *bea return haveAtLeastOneGitOps } -func (impl PipelineBuilderImpl) SetPipelineDeploymentAppType(pipelineCreateRequest *bean.CdPipelines, isGitOpsConfigured bool, deploymentTypeValidationConfig map[string]bool) { +func (impl *PipelineBuilderImpl) SetPipelineDeploymentAppType(pipelineCreateRequest *bean.CdPipelines, isGitOpsConfigured bool, deploymentTypeValidationConfig map[string]bool) { for _, pipeline := range pipelineCreateRequest.Pipelines { // by default both deployment app type are allowed AllowedDeploymentAppTypes := map[string]bool{ @@ -1809,7 +1809,7 @@ func (impl PipelineBuilderImpl) SetPipelineDeploymentAppType(pipelineCreateReque } } -func (impl PipelineBuilderImpl) CreateCdPipelines(pipelineCreateRequest *bean.CdPipelines, ctx context.Context) (*bean.CdPipelines, error) { +func (impl *PipelineBuilderImpl) CreateCdPipelines(pipelineCreateRequest *bean.CdPipelines, ctx context.Context) (*bean.CdPipelines, error) { //Validation for checking deployment App type isGitOpsConfigured, err := impl.IsGitopsConfigured() @@ -1873,7 +1873,7 @@ func (impl PipelineBuilderImpl) CreateCdPipelines(pipelineCreateRequest *bean.Cd return pipelineCreateRequest, nil } -func (impl PipelineBuilderImpl) validateDeploymentAppType(pipeline *bean.CDPipelineConfigObject, deploymentConfig map[string]bool) error { +func (impl *PipelineBuilderImpl) validateDeploymentAppType(pipeline *bean.CDPipelineConfigObject, deploymentConfig map[string]bool) error { // Config value doesn't exist in attribute table if deploymentConfig == nil { @@ -1914,7 +1914,7 @@ func validDeploymentConfigReceived(deploymentConfig map[string]bool, deploymentT return false } -func (impl PipelineBuilderImpl) GetDeploymentConfigMap(environmentId int) (map[string]bool, error) { +func (impl *PipelineBuilderImpl) GetDeploymentConfigMap(environmentId int) (map[string]bool, error) { var deploymentConfig map[string]map[string]bool var deploymentConfigEnv map[string]bool deploymentConfigValues, err := impl.attributesRepository.FindByKey(attributes.ENFORCE_DEPLOYMENT_TYPE_CONFIG) @@ -1936,7 +1936,7 @@ func (impl PipelineBuilderImpl) GetDeploymentConfigMap(environmentId int) (map[s return deploymentConfigEnv, nil } -func (impl PipelineBuilderImpl) PatchCdPipelines(cdPipelines *bean.CDPatchRequest, ctx context.Context) (*bean.CdPipelines, error) { +func (impl *PipelineBuilderImpl) PatchCdPipelines(cdPipelines *bean.CDPatchRequest, ctx context.Context) (*bean.CdPipelines, error) { pipelineRequest := &bean.CdPipelines{ UserId: cdPipelines.UserId, AppId: cdPipelines.AppId, @@ -1977,7 +1977,7 @@ func (impl PipelineBuilderImpl) PatchCdPipelines(cdPipelines *bean.CDPatchReques } } -func (impl PipelineBuilderImpl) DeleteCdPipeline(pipeline *pipelineConfig.Pipeline, ctx context.Context, deleteAction int, deleteFromAcd bool, userId int32) (*bean.AppDeleteResponseDTO, error) { +func (impl *PipelineBuilderImpl) DeleteCdPipeline(pipeline *pipelineConfig.Pipeline, ctx context.Context, deleteAction int, deleteFromAcd bool, userId int32) (*bean.AppDeleteResponseDTO, error) { cascadeDelete := true forceDelete := false deleteResponse := &bean.AppDeleteResponseDTO{ @@ -2171,7 +2171,7 @@ func (impl PipelineBuilderImpl) DeleteCdPipeline(pipeline *pipelineConfig.Pipeli return deleteResponse, nil } -func (impl PipelineBuilderImpl) DeleteCdPipelinePartial(pipeline *pipelineConfig.Pipeline, ctx context.Context, deleteAction int) (*bean.AppDeleteResponseDTO, error) { +func (impl *PipelineBuilderImpl) DeleteCdPipelinePartial(pipeline *pipelineConfig.Pipeline, ctx context.Context, deleteAction int) (*bean.AppDeleteResponseDTO, error) { cascadeDelete := true forceDelete := false deleteResponse := &bean.AppDeleteResponseDTO{ @@ -2277,7 +2277,7 @@ func (impl PipelineBuilderImpl) DeleteCdPipelinePartial(pipeline *pipelineConfig return deleteResponse, nil } -func (impl PipelineBuilderImpl) DeleteACDAppCdPipelineWithNonCascade(pipeline *pipelineConfig.Pipeline, ctx context.Context, forceDelete bool, userId int32) error { +func (impl *PipelineBuilderImpl) DeleteACDAppCdPipelineWithNonCascade(pipeline *pipelineConfig.Pipeline, ctx context.Context, forceDelete bool, userId int32) error { if forceDelete { _, err := impl.DeleteCdPipeline(pipeline, ctx, bean.FORCE_DELETE, false, userId) return err @@ -2311,7 +2311,7 @@ func (impl PipelineBuilderImpl) DeleteACDAppCdPipelineWithNonCascade(pipeline *p // ChangeDeploymentType takes in DeploymentAppTypeChangeRequest struct and // deletes all the cd pipelines for that deployment type in all apps that belongs to // that environment and updates the db with desired deployment app type -func (impl PipelineBuilderImpl) ChangeDeploymentType(ctx context.Context, +func (impl *PipelineBuilderImpl) ChangeDeploymentType(ctx context.Context, request *bean.DeploymentAppTypeChangeRequest) (*bean.DeploymentAppTypeChangeResponse, error) { var response *bean.DeploymentAppTypeChangeResponse @@ -2426,7 +2426,7 @@ func (impl PipelineBuilderImpl) ChangeDeploymentType(ctx context.Context, return response, nil } -func (impl PipelineBuilderImpl) ChangePipelineDeploymentType(ctx context.Context, +func (impl *PipelineBuilderImpl) ChangePipelineDeploymentType(ctx context.Context, request *bean.DeploymentAppTypeChangeRequest) (*bean.DeploymentAppTypeChangeResponse, error) { response := &bean.DeploymentAppTypeChangeResponse{ @@ -2503,7 +2503,7 @@ func (impl PipelineBuilderImpl) ChangePipelineDeploymentType(ctx context.Context return response, nil } -func (impl PipelineBuilderImpl) TriggerDeploymentAfterTypeChange(ctx context.Context, +func (impl *PipelineBuilderImpl) TriggerDeploymentAfterTypeChange(ctx context.Context, request *bean.DeploymentAppTypeChangeRequest) (*bean.DeploymentAppTypeChangeResponse, error) { response := &bean.DeploymentAppTypeChangeResponse{ @@ -2612,7 +2612,7 @@ func (impl PipelineBuilderImpl) TriggerDeploymentAfterTypeChange(ctx context.Con // DeleteDeploymentAppsForEnvironment takes in environment id and current deployment app type // and deletes all the cd pipelines for that deployment type in all apps that belongs to // that environment. -func (impl PipelineBuilderImpl) DeleteDeploymentAppsForEnvironment(ctx context.Context, environmentId int, +func (impl *PipelineBuilderImpl) DeleteDeploymentAppsForEnvironment(ctx context.Context, environmentId int, currentDeploymentAppType bean.DeploymentType, exclusionList []int, includeApps []int, userId int32) (*bean.DeploymentAppTypeChangeResponse, error) { // fetch active pipelines from database for the given environment id and current deployment app type @@ -2638,7 +2638,7 @@ func (impl PipelineBuilderImpl) DeleteDeploymentAppsForEnvironment(ctx context.C // DeleteDeploymentApps takes in a list of pipelines and delete the applications -func (impl PipelineBuilderImpl) DeleteDeploymentApps(ctx context.Context, +func (impl *PipelineBuilderImpl) DeleteDeploymentApps(ctx context.Context, pipelines []*pipelineConfig.Pipeline, userId int32) *bean.DeploymentAppTypeChangeResponse { successfulPipelines := make([]*bean.DeploymentChangeStatus, 0) @@ -2750,7 +2750,7 @@ func (impl PipelineBuilderImpl) DeleteDeploymentApps(ctx context.Context, // from argocd / helm. -func (impl PipelineBuilderImpl) isGitRepoUrlPresent(appId int) bool { +func (impl *PipelineBuilderImpl) isGitRepoUrlPresent(appId int) bool { fetchedChart, err := impl.chartRepository.FindLatestByAppId(appId) if err != nil || len(fetchedChart.GitRepoUrl) == 0 { @@ -2760,7 +2760,7 @@ func (impl PipelineBuilderImpl) isGitRepoUrlPresent(appId int) bool { return true } -func (impl PipelineBuilderImpl) isPipelineInfoValid(pipeline *pipelineConfig.Pipeline, +func (impl *PipelineBuilderImpl) isPipelineInfoValid(pipeline *pipelineConfig.Pipeline, failedPipelines []*bean.DeploymentChangeStatus) ([]*bean.DeploymentChangeStatus, bool) { if len(pipeline.App.AppName) == 0 || len(pipeline.Environment.Name) == 0 { @@ -2775,7 +2775,7 @@ func (impl PipelineBuilderImpl) isPipelineInfoValid(pipeline *pipelineConfig.Pip return failedPipelines, true } -func (impl PipelineBuilderImpl) handleFailedDeploymentAppChange(pipeline *pipelineConfig.Pipeline, +func (impl *PipelineBuilderImpl) handleFailedDeploymentAppChange(pipeline *pipelineConfig.Pipeline, failedPipelines []*bean.DeploymentChangeStatus, err string) []*bean.DeploymentChangeStatus { return impl.appendToDeploymentChangeStatusList( @@ -2785,7 +2785,7 @@ func (impl PipelineBuilderImpl) handleFailedDeploymentAppChange(pipeline *pipeli bean.Failed) } -func (impl PipelineBuilderImpl) handleNotHealthyAppsIfArgoDeploymentType(pipeline *pipelineConfig.Pipeline, +func (impl *PipelineBuilderImpl) handleNotHealthyAppsIfArgoDeploymentType(pipeline *pipelineConfig.Pipeline, failedPipelines []*bean.DeploymentChangeStatus) ([]*bean.DeploymentChangeStatus, error) { if pipeline.DeploymentAppType == bean.ArgoCd { @@ -2816,7 +2816,7 @@ func (impl PipelineBuilderImpl) handleNotHealthyAppsIfArgoDeploymentType(pipelin return failedPipelines, nil } -func (impl PipelineBuilderImpl) handleNotDeployedAppsIfArgoDeploymentType(pipeline *pipelineConfig.Pipeline, +func (impl *PipelineBuilderImpl) handleNotDeployedAppsIfArgoDeploymentType(pipeline *pipelineConfig.Pipeline, failedPipelines []*bean.DeploymentChangeStatus) ([]*bean.DeploymentChangeStatus, error) { if pipeline.DeploymentAppType == string(bean.ArgoCd) { @@ -2847,7 +2847,7 @@ func (impl PipelineBuilderImpl) handleNotDeployedAppsIfArgoDeploymentType(pipeli return failedPipelines, nil } -func (impl PipelineBuilderImpl) FetchDeletedApp(ctx context.Context, +func (impl *PipelineBuilderImpl) FetchDeletedApp(ctx context.Context, pipelines []*pipelineConfig.Pipeline) *bean.DeploymentAppTypeChangeResponse { successfulPipelines := make([]*bean.DeploymentChangeStatus, 0) @@ -2893,7 +2893,7 @@ func (impl PipelineBuilderImpl) FetchDeletedApp(ctx context.Context, // deleteArgoCdApp takes context and deployment app name used in argo cd and deletes // the application in argo cd. -func (impl PipelineBuilderImpl) deleteArgoCdApp(ctx context.Context, pipeline *pipelineConfig.Pipeline, deploymentAppName string, +func (impl *PipelineBuilderImpl) deleteArgoCdApp(ctx context.Context, pipeline *pipelineConfig.Pipeline, deploymentAppName string, cascadeDelete bool) error { if !pipeline.DeploymentAppCreated { @@ -2920,7 +2920,7 @@ func (impl PipelineBuilderImpl) deleteArgoCdApp(ctx context.Context, pipeline *p } // deleteHelmApp takes in context and pipeline object and deletes the release in helm -func (impl PipelineBuilderImpl) deleteHelmApp(ctx context.Context, pipeline *pipelineConfig.Pipeline) error { +func (impl *PipelineBuilderImpl) deleteHelmApp(ctx context.Context, pipeline *pipelineConfig.Pipeline) error { if !pipeline.DeploymentAppCreated { return nil @@ -2952,7 +2952,7 @@ func (impl PipelineBuilderImpl) deleteHelmApp(ctx context.Context, pipeline *pip return nil } -func (impl PipelineBuilderImpl) appendToDeploymentChangeStatusList(pipelines []*bean.DeploymentChangeStatus, +func (impl *PipelineBuilderImpl) appendToDeploymentChangeStatusList(pipelines []*bean.DeploymentChangeStatus, pipeline *pipelineConfig.Pipeline, error string, status bean.Status) []*bean.DeploymentChangeStatus { return append(pipelines, &bean.DeploymentChangeStatus{ @@ -2974,7 +2974,7 @@ type Deployment struct { Strategy map[string]interface{} `json:"strategy"` } -func (impl PipelineBuilderImpl) createCdPipeline(ctx context.Context, app *app2.App, pipeline *bean.CDPipelineConfigObject, userId int32) (pipelineRes int, err error) { +func (impl *PipelineBuilderImpl) createCdPipeline(ctx context.Context, app *app2.App, pipeline *bean.CDPipelineConfigObject, userId int32) (pipelineRes int, err error) { dbConnection := impl.pipelineRepository.GetConnection() tx, err := dbConnection.Begin() if err != nil { @@ -3117,7 +3117,7 @@ func (impl PipelineBuilderImpl) createCdPipeline(ctx context.Context, app *app2. return pipelineId, nil } -func (impl PipelineBuilderImpl) updateCdPipeline(ctx context.Context, pipeline *bean.CDPipelineConfigObject, userID int32) (err error) { +func (impl *PipelineBuilderImpl) updateCdPipeline(ctx context.Context, pipeline *bean.CDPipelineConfigObject, userID int32) (err error) { if len(pipeline.PreStage.Config) > 0 && !strings.Contains(pipeline.PreStage.Config, "beforeStages") { err = &util.ApiError{ @@ -3231,7 +3231,7 @@ func (impl PipelineBuilderImpl) updateCdPipeline(ctx context.Context, pipeline * return nil } -func (impl PipelineBuilderImpl) filterDeploymentTemplate(strategyKey string, pipelineStrategiesJson string) (string, error) { +func (impl *PipelineBuilderImpl) filterDeploymentTemplate(strategyKey string, pipelineStrategiesJson string) (string, error) { var pipelineStrategies DeploymentType err := json.Unmarshal([]byte(pipelineStrategiesJson), &pipelineStrategies) if err != nil { @@ -3257,7 +3257,7 @@ func (impl PipelineBuilderImpl) filterDeploymentTemplate(strategyKey string, pip return pipelineStrategyJson, nil } -func (impl PipelineBuilderImpl) getStrategiesMapping(dbPipelineIds []int) (map[int][]*chartConfig.PipelineStrategy, error) { +func (impl *PipelineBuilderImpl) getStrategiesMapping(dbPipelineIds []int) (map[int][]*chartConfig.PipelineStrategy, error) { strategiesMapping := make(map[int][]*chartConfig.PipelineStrategy) strategiesByPipelineIds, err := impl.pipelineConfigRepository.GetAllStrategyByPipelineIds(dbPipelineIds) if err != nil && !errors.IsNotFound(err) { @@ -3270,7 +3270,7 @@ func (impl PipelineBuilderImpl) getStrategiesMapping(dbPipelineIds []int) (map[i return strategiesMapping, nil } -func (impl PipelineBuilderImpl) GetTriggerViewCdPipelinesForApp(appId int) (cdPipelines *bean.CdPipelines, err error) { +func (impl *PipelineBuilderImpl) GetTriggerViewCdPipelinesForApp(appId int) (cdPipelines *bean.CdPipelines, err error) { triggerViewCdPipelinesResp, err := impl.ciCdPipelineOrchestrator.GetCdPipelinesForApp(appId) if err != nil { impl.logger.Errorw("error in fetching triggerViewCdPipelinesResp by appId", "err", err, "appId", appId) @@ -3303,7 +3303,7 @@ func (impl PipelineBuilderImpl) GetTriggerViewCdPipelinesForApp(appId int) (cdPi return triggerViewCdPipelinesResp, err } -func (impl PipelineBuilderImpl) GetCdPipelinesForApp(appId int) (cdPipelines *bean.CdPipelines, err error) { +func (impl *PipelineBuilderImpl) GetCdPipelinesForApp(appId int) (cdPipelines *bean.CdPipelines, err error) { cdPipelines, err = impl.ciCdPipelineOrchestrator.GetCdPipelinesForApp(appId) if err != nil { impl.logger.Errorw("error in fetching cd Pipelines for appId", "err", err, "appId", appId) @@ -3399,7 +3399,7 @@ func (impl PipelineBuilderImpl) GetCdPipelinesForApp(appId int) (cdPipelines *be return cdPipelines, err } -func (impl PipelineBuilderImpl) GetCdPipelinesForAppAndEnv(appId int, envId int) (cdPipelines *bean.CdPipelines, err error) { +func (impl *PipelineBuilderImpl) GetCdPipelinesForAppAndEnv(appId int, envId int) (cdPipelines *bean.CdPipelines, err error) { return impl.ciCdPipelineOrchestrator.GetCdPipelinesForAppAndEnv(appId, envId) } @@ -3408,7 +3408,7 @@ type ConfigMapSecretsResponse struct { Secrets []bean2.ConfigSecretMap `json:"secrets"` } -func (impl PipelineBuilderImpl) FetchConfigmapSecretsForCdStages(appId, envId, cdPipelineId int) (ConfigMapSecretsResponse, error) { +func (impl *PipelineBuilderImpl) FetchConfigmapSecretsForCdStages(appId, envId, cdPipelineId int) (ConfigMapSecretsResponse, error) { configMapSecrets, err := impl.appService.GetConfigMapAndSecretJson(appId, envId, cdPipelineId) if err != nil { impl.logger.Errorw("error while fetching config secrets ", "err", err) @@ -3424,7 +3424,7 @@ func (impl PipelineBuilderImpl) FetchConfigmapSecretsForCdStages(appId, envId, c } // RetrieveParentDetails returns the parent id and type of the parent -func (impl PipelineBuilderImpl) RetrieveParentDetails(pipelineId int) (parentId int, parentType bean2.WorkflowType, err error) { +func (impl *PipelineBuilderImpl) RetrieveParentDetails(pipelineId int) (parentId int, parentType bean2.WorkflowType, err error) { workflow, err := impl.appWorkflowRepository.GetParentDetailsByPipelineId(pipelineId) if err != nil { @@ -3458,7 +3458,7 @@ func (impl PipelineBuilderImpl) RetrieveParentDetails(pipelineId int) (parentId } // RetrieveArtifactsByCDPipeline returns all the artifacts for the cd pipeline (pre / deploy / post) -func (impl PipelineBuilderImpl) RetrieveArtifactsByCDPipeline(pipeline *pipelineConfig.Pipeline, stage bean2.WorkflowType) (*bean.CiArtifactResponse, error) { +func (impl *PipelineBuilderImpl) RetrieveArtifactsByCDPipeline(pipeline *pipelineConfig.Pipeline, stage bean2.WorkflowType) (*bean.CiArtifactResponse, error) { // retrieve parent details parentId, parentType, err := impl.RetrieveParentDetails(pipeline.Id) @@ -3577,7 +3577,7 @@ func (impl PipelineBuilderImpl) RetrieveArtifactsByCDPipeline(pipeline *pipeline return ciArtifactsResponse, nil } -func (impl PipelineBuilderImpl) BuildArtifactsForParentStage(cdPipelineId int, parentId int, parentType bean2.WorkflowType, ciArtifacts []bean.CiArtifactBean, artifactMap map[int]int, limit int, parentCdId int) ([]bean.CiArtifactBean, error) { +func (impl *PipelineBuilderImpl) BuildArtifactsForParentStage(cdPipelineId int, parentId int, parentType bean2.WorkflowType, ciArtifacts []bean.CiArtifactBean, artifactMap map[int]int, limit int, parentCdId int) ([]bean.CiArtifactBean, error) { var ciArtifactsFinal []bean.CiArtifactBean var err error if parentType == bean2.CI_WORKFLOW_TYPE { @@ -3591,7 +3591,7 @@ func (impl PipelineBuilderImpl) BuildArtifactsForParentStage(cdPipelineId int, p return ciArtifactsFinal, err } -func (impl PipelineBuilderImpl) BuildArtifactsForCdStage(pipelineId int, stageType bean2.WorkflowType, ciArtifacts []bean.CiArtifactBean, artifactMap map[int]int, parent bool, limit int, parentCdId int) ([]bean.CiArtifactBean, map[int]int, int, string, error) { +func (impl *PipelineBuilderImpl) BuildArtifactsForCdStage(pipelineId int, stageType bean2.WorkflowType, ciArtifacts []bean.CiArtifactBean, artifactMap map[int]int, parent bool, limit int, parentCdId int) ([]bean.CiArtifactBean, map[int]int, int, string, error) { //getting running artifact id for parent cd parentCdRunningArtifactId := 0 if parentCdId > 0 && parent { @@ -3662,7 +3662,7 @@ func (impl PipelineBuilderImpl) BuildArtifactsForCdStage(pipelineId int, stageTy // method for building artifacts for parent CI -func (impl PipelineBuilderImpl) BuildArtifactsForCIParent(cdPipelineId int, parentId int, parentType bean2.WorkflowType, ciArtifacts []bean.CiArtifactBean, artifactMap map[int]int, limit int) ([]bean.CiArtifactBean, error) { +func (impl *PipelineBuilderImpl) BuildArtifactsForCIParent(cdPipelineId int, parentId int, parentType bean2.WorkflowType, ciArtifacts []bean.CiArtifactBean, artifactMap map[int]int, limit int) ([]bean.CiArtifactBean, error) { artifacts, err := impl.ciArtifactRepository.GetArtifactsByCDPipeline(cdPipelineId, limit, parentId, parentType) if err != nil { impl.logger.Errorw("error in getting artifacts for ci", "err", err) @@ -3688,7 +3688,7 @@ func (impl PipelineBuilderImpl) BuildArtifactsForCIParent(cdPipelineId int, pare return ciArtifacts, nil } -func (impl PipelineBuilderImpl) FetchArtifactForRollback(cdPipelineId, offset, limit int) (bean.CiArtifactResponse, error) { +func (impl *PipelineBuilderImpl) FetchArtifactForRollback(cdPipelineId, offset, limit int) (bean.CiArtifactResponse, error) { var deployedCiArtifacts []bean.CiArtifactBean var deployedCiArtifactsResponse bean.CiArtifactResponse @@ -3791,7 +3791,7 @@ func parseMaterialInfo(materialInfo json.RawMessage, source string) (json.RawMes return mInfo, err } -func (impl PipelineBuilderImpl) FindAppsByTeamId(teamId int) ([]*AppBean, error) { +func (impl *PipelineBuilderImpl) FindAppsByTeamId(teamId int) ([]*AppBean, error) { var appsRes []*AppBean apps, err := impl.appRepo.FindAppsByTeamId(teamId) if err != nil { @@ -3804,7 +3804,7 @@ func (impl PipelineBuilderImpl) FindAppsByTeamId(teamId int) ([]*AppBean, error) return appsRes, err } -func (impl PipelineBuilderImpl) FindAppsByTeamName(teamName string) ([]AppBean, error) { +func (impl *PipelineBuilderImpl) FindAppsByTeamName(teamName string) ([]AppBean, error) { var appsRes []AppBean apps, err := impl.appRepo.FindAppsByTeamName(teamName) if err != nil { @@ -3817,11 +3817,11 @@ func (impl PipelineBuilderImpl) FindAppsByTeamName(teamName string) ([]AppBean, return appsRes, err } -func (impl PipelineBuilderImpl) FindPipelineById(cdPipelineId int) (*pipelineConfig.Pipeline, error) { +func (impl *PipelineBuilderImpl) FindPipelineById(cdPipelineId int) (*pipelineConfig.Pipeline, error) { return impl.pipelineRepository.FindById(cdPipelineId) } -func (impl PipelineBuilderImpl) FindAppAndEnvDetailsByPipelineId(cdPipelineId int) (*pipelineConfig.Pipeline, error) { +func (impl *PipelineBuilderImpl) FindAppAndEnvDetailsByPipelineId(cdPipelineId int) (*pipelineConfig.Pipeline, error) { return impl.pipelineRepository.FindAppAndEnvDetailsByPipelineId(cdPipelineId) } @@ -3837,7 +3837,7 @@ type AppBean struct { TeamId int `json:"teamId,omitempty"` } -func (impl PipelineBuilderImpl) GetAppList() ([]AppBean, error) { +func (impl *PipelineBuilderImpl) GetAppList() ([]AppBean, error) { var appsRes []AppBean apps, err := impl.appRepo.FindAll() if err != nil { @@ -3850,7 +3850,7 @@ func (impl PipelineBuilderImpl) GetAppList() ([]AppBean, error) { return appsRes, err } -func (impl PipelineBuilderImpl) FetchCDPipelineStrategy(appId int) (PipelineStrategiesResponse, error) { +func (impl *PipelineBuilderImpl) FetchCDPipelineStrategy(appId int) (PipelineStrategiesResponse, error) { pipelineStrategiesResponse := PipelineStrategiesResponse{} chart, err := impl.chartRepository.FindLatestChartForAppByAppId(appId) if err != nil && err != pg.ErrNoRows { @@ -3886,7 +3886,7 @@ func (impl PipelineBuilderImpl) FetchCDPipelineStrategy(appId int) (PipelineStra return pipelineStrategiesResponse, nil } -func (impl PipelineBuilderImpl) FetchDefaultCDPipelineStrategy(appId int, envId int) (PipelineStrategy, error) { +func (impl *PipelineBuilderImpl) FetchDefaultCDPipelineStrategy(appId int, envId int) (PipelineStrategy, error) { pipelineStrategy := PipelineStrategy{} cdPipelines, err := impl.ciCdPipelineOrchestrator.GetCdPipelinesForAppAndEnv(appId, envId) if err != nil || (cdPipelines.Pipelines) == nil || len(cdPipelines.Pipelines) == 0 { @@ -3912,7 +3912,7 @@ type PipelineStrategy struct { Default bool `json:"default"` } -func (impl PipelineBuilderImpl) GetEnvironmentByCdPipelineId(pipelineId int) (int, error) { +func (impl *PipelineBuilderImpl) GetEnvironmentByCdPipelineId(pipelineId int) (int, error) { dbPipeline, err := impl.pipelineRepository.FindById(pipelineId) if err != nil || dbPipeline == nil { impl.logger.Errorw("error in fetching pipeline", "err", err) @@ -3921,7 +3921,7 @@ func (impl PipelineBuilderImpl) GetEnvironmentByCdPipelineId(pipelineId int) (in return dbPipeline.EnvironmentId, err } -func (impl PipelineBuilderImpl) GetCdPipelineById(pipelineId int) (cdPipeline *bean.CDPipelineConfigObject, err error) { +func (impl *PipelineBuilderImpl) GetCdPipelineById(pipelineId int) (cdPipeline *bean.CDPipelineConfigObject, err error) { dbPipeline, err := impl.pipelineRepository.FindById(pipelineId) if err != nil && errors.IsNotFound(err) { impl.logger.Errorw("error in fetching pipeline", "err", err) @@ -4011,7 +4011,7 @@ func (impl PipelineBuilderImpl) GetCdPipelineById(pipelineId int) (cdPipeline *b return cdPipeline, err } -func (impl PipelineBuilderImpl) FindByIds(ids []*int) ([]*AppBean, error) { +func (impl *PipelineBuilderImpl) FindByIds(ids []*int) ([]*AppBean, error) { var appsRes []*AppBean apps, err := impl.appRepo.FindByIds(ids) if err != nil { @@ -4024,7 +4024,7 @@ func (impl PipelineBuilderImpl) FindByIds(ids []*int) ([]*AppBean, error) { return appsRes, err } -func (impl PipelineBuilderImpl) GetCiPipelineById(pipelineId int) (ciPipeline *bean.CiPipeline, err error) { +func (impl *PipelineBuilderImpl) GetCiPipelineById(pipelineId int) (ciPipeline *bean.CiPipeline, err error) { pipeline, err := impl.ciPipelineRepository.FindById(pipelineId) if err != nil && !util.IsErrNoRows(err) { impl.logger.Errorw("error in fetching ci pipeline", "pipelineId", pipelineId, "err", err) @@ -4163,7 +4163,7 @@ func (impl PipelineBuilderImpl) GetCiPipelineById(pipelineId int) (ciPipeline *b return ciPipeline, err } -func (impl PipelineBuilderImpl) FindAllMatchesByAppName(appName string, appType helper.AppType) ([]*AppBean, error) { +func (impl *PipelineBuilderImpl) FindAllMatchesByAppName(appName string, appType helper.AppType) ([]*AppBean, error) { var appsRes []*AppBean var apps []*app2.App var err error @@ -4186,7 +4186,7 @@ func (impl PipelineBuilderImpl) FindAllMatchesByAppName(appName string, appType return appsRes, err } -func (impl PipelineBuilderImpl) updateGitRepoUrlInCharts(appId int, chartGitAttribute *util.ChartGitAttribute, userId int32) error { +func (impl *PipelineBuilderImpl) updateGitRepoUrlInCharts(appId int, chartGitAttribute *util.ChartGitAttribute, userId int32) error { charts, err := impl.chartRepository.FindActiveChartsByAppId(appId) if err != nil && pg.ErrNoRows != err { return err @@ -4206,7 +4206,7 @@ func (impl PipelineBuilderImpl) updateGitRepoUrlInCharts(appId int, chartGitAttr return nil } -func (impl PipelineBuilderImpl) PerformBulkActionOnCdPipelines(dto *bean.CdBulkActionRequestDto, impactedPipelines []*pipelineConfig.Pipeline, ctx context.Context, dryRun bool, userId int32) ([]*bean.CdBulkActionResponseDto, error) { +func (impl *PipelineBuilderImpl) PerformBulkActionOnCdPipelines(dto *bean.CdBulkActionRequestDto, impactedPipelines []*pipelineConfig.Pipeline, ctx context.Context, dryRun bool, userId int32) ([]*bean.CdBulkActionResponseDto, error) { switch dto.Action { case bean.CD_BULK_DELETE: deleteAction := bean.CASCADE_DELETE @@ -4222,7 +4222,7 @@ func (impl PipelineBuilderImpl) PerformBulkActionOnCdPipelines(dto *bean.CdBulkA } } -func (impl PipelineBuilderImpl) BulkDeleteCdPipelines(impactedPipelines []*pipelineConfig.Pipeline, ctx context.Context, dryRun bool, deleteAction int, userId int32) []*bean.CdBulkActionResponseDto { +func (impl *PipelineBuilderImpl) BulkDeleteCdPipelines(impactedPipelines []*pipelineConfig.Pipeline, ctx context.Context, dryRun bool, deleteAction int, userId int32) []*bean.CdBulkActionResponseDto { var respDtos []*bean.CdBulkActionResponseDto for _, pipeline := range impactedPipelines { respDto := &bean.CdBulkActionResponseDto{ @@ -4247,7 +4247,7 @@ func (impl PipelineBuilderImpl) BulkDeleteCdPipelines(impactedPipelines []*pipel } -func (impl PipelineBuilderImpl) GetBulkActionImpactedPipelines(dto *bean.CdBulkActionRequestDto) ([]*pipelineConfig.Pipeline, error) { +func (impl *PipelineBuilderImpl) GetBulkActionImpactedPipelines(dto *bean.CdBulkActionRequestDto) ([]*pipelineConfig.Pipeline, error) { if len(dto.EnvIds) == 0 || (len(dto.AppIds) == 0 && len(dto.ProjectIds) == 0) { //invalid payload, envIds are must and either of appIds or projectIds are must return nil, &util.ApiError{Code: "400", HttpStatusCode: 400, UserMessage: "invalid payload, can not get pipelines for this filter"} @@ -4288,7 +4288,7 @@ func (impl PipelineBuilderImpl) GetBulkActionImpactedPipelines(dto *bean.CdBulkA return pipelines, nil } -func (impl PipelineBuilderImpl) buildExternalCiWebhookSchema() map[string]interface{} { +func (impl *PipelineBuilderImpl) buildExternalCiWebhookSchema() map[string]interface{} { schema := make(map[string]interface{}) schema["dockerImage"] = &bean.SchemaObject{Description: "docker image created for your application (Eg. quay.io/devtron/test:da3ba325-161-467)", DataType: "String", Example: "test-docker-repo/test:b150cc81-5-20", Optional: false} //schema["digest"] = &bean.SchemaObject{Description: "docker image sha1 digest", DataType: "String", Example: "sha256:94180dead8336237430e848ef8145f060b51", Optional: true} @@ -4306,7 +4306,7 @@ func (impl PipelineBuilderImpl) buildExternalCiWebhookSchema() map[string]interf return schema } -func (impl PipelineBuilderImpl) buildPayloadOption() []bean.PayloadOptionObject { +func (impl *PipelineBuilderImpl) buildPayloadOption() []bean.PayloadOptionObject { payloadOption := make([]bean.PayloadOptionObject, 0) payloadOption = append(payloadOption, bean.PayloadOptionObject{ Key: "dockerImage", @@ -4342,7 +4342,7 @@ func (impl PipelineBuilderImpl) buildPayloadOption() []bean.PayloadOptionObject return payloadOption } -func (impl PipelineBuilderImpl) buildResponses() []bean.ResponseSchemaObject { +func (impl *PipelineBuilderImpl) buildResponses() []bean.ResponseSchemaObject { responseSchemaObjects := make([]bean.ResponseSchemaObject, 0) schema := make(map[string]interface{}) schema["code"] = &bean.SchemaObject{Description: "http status code", DataType: "integer", Example: "200,400,401", Optional: false} @@ -4400,7 +4400,7 @@ func (impl PipelineBuilderImpl) buildResponses() []bean.ResponseSchemaObject { return responseSchemaObjects } -func (impl PipelineBuilderImpl) MarkGitOpsDevtronAppsDeletedWhereArgoAppIsDeleted(appId int, envId int, acdToken string, pipeline *pipelineConfig.Pipeline) (bool, error) { +func (impl *PipelineBuilderImpl) MarkGitOpsDevtronAppsDeletedWhereArgoAppIsDeleted(appId int, envId int, acdToken string, pipeline *pipelineConfig.Pipeline) (bool, error) { acdAppFound := false ctx := context.Background() @@ -4422,7 +4422,7 @@ func (impl PipelineBuilderImpl) MarkGitOpsDevtronAppsDeletedWhereArgoAppIsDelete return acdAppFound, nil } -func (impl PipelineBuilderImpl) GetCiPipelineByEnvironment(request appGroup2.AppGroupingRequest) ([]*bean.CiConfigRequest, error) { +func (impl *PipelineBuilderImpl) GetCiPipelineByEnvironment(request appGroup2.AppGroupingRequest) ([]*bean.CiConfigRequest, error) { ciPipelinesConfigByApps := make([]*bean.CiConfigRequest, 0) _, span := otel.Tracer("orchestrator").Start(request.Ctx, "ciHandler.AppGroupingCiPipelinesAuthorization") var cdPipelines []*pipelineConfig.Pipeline @@ -4621,7 +4621,7 @@ func (impl PipelineBuilderImpl) GetCiPipelineByEnvironment(request appGroup2.App return ciPipelinesConfigByApps, err } -func (impl PipelineBuilderImpl) GetCiPipelineByEnvironmentMin(request appGroup2.AppGroupingRequest) ([]*bean.CiPipelineMinResponse, error) { +func (impl *PipelineBuilderImpl) GetCiPipelineByEnvironmentMin(request appGroup2.AppGroupingRequest) ([]*bean.CiPipelineMinResponse, error) { results := make([]*bean.CiPipelineMinResponse, 0) var cdPipelines []*pipelineConfig.Pipeline var err error @@ -4704,7 +4704,7 @@ func (impl PipelineBuilderImpl) GetCiPipelineByEnvironmentMin(request appGroup2. return results, err } -func (impl PipelineBuilderImpl) GetCdPipelinesByEnvironment(request appGroup2.AppGroupingRequest) (cdPipelines *bean.CdPipelines, err error) { +func (impl *PipelineBuilderImpl) GetCdPipelinesByEnvironment(request appGroup2.AppGroupingRequest) (cdPipelines *bean.CdPipelines, err error) { _, span := otel.Tracer("orchestrator").Start(request.Ctx, "cdHandler.authorizationCdPipelinesForAppGrouping") if request.AppGroupId > 0 { appIds, err := impl.appGroupService.GetAppIdsByAppGroupId(request.AppGroupId) @@ -4809,7 +4809,7 @@ func (impl PipelineBuilderImpl) GetCdPipelinesByEnvironment(request appGroup2.Ap return cdPipelines, err } -func (impl PipelineBuilderImpl) GetCdPipelinesByEnvironmentMin(request appGroup2.AppGroupingRequest) (cdPipelines []*bean.CDPipelineConfigObject, err error) { +func (impl *PipelineBuilderImpl) GetCdPipelinesByEnvironmentMin(request appGroup2.AppGroupingRequest) (cdPipelines []*bean.CDPipelineConfigObject, err error) { _, span := otel.Tracer("orchestrator").Start(request.Ctx, "cdHandler.authorizationCdPipelinesForAppGrouping") if request.AppGroupId > 0 { appIds, err := impl.appGroupService.GetAppIdsByAppGroupId(request.AppGroupId) @@ -4860,7 +4860,7 @@ func (impl PipelineBuilderImpl) GetCdPipelinesByEnvironmentMin(request appGroup2 return cdPipelines, err } -func (impl PipelineBuilderImpl) GetExternalCiByEnvironment(request appGroup2.AppGroupingRequest) (ciConfig []*bean.ExternalCiConfig, err error) { +func (impl *PipelineBuilderImpl) GetExternalCiByEnvironment(request appGroup2.AppGroupingRequest) (ciConfig []*bean.ExternalCiConfig, err error) { _, span := otel.Tracer("orchestrator").Start(request.Ctx, "ciHandler.authorizationExternalCiForAppGrouping") externalCiConfigs := make([]*bean.ExternalCiConfig, 0) var cdPipelines []*pipelineConfig.Pipeline @@ -5028,7 +5028,7 @@ func (impl PipelineBuilderImpl) GetExternalCiByEnvironment(request appGroup2.App return externalCiConfigs, err } -func (impl PipelineBuilderImpl) GetEnvironmentListForAutocompleteFilter(envName string, clusterIds []int, offset int, size int, emailId string, checkAuthBatch func(emailId string, appObject []string, envObject []string) (map[string]bool, map[string]bool), ctx context.Context) (*cluster.AppGroupingResponse, error) { +func (impl *PipelineBuilderImpl) GetEnvironmentListForAutocompleteFilter(envName string, clusterIds []int, offset int, size int, emailId string, checkAuthBatch func(emailId string, appObject []string, envObject []string) (map[string]bool, map[string]bool), ctx context.Context) (*cluster.AppGroupingResponse, error) { result := &cluster.AppGroupingResponse{} var models []*repository2.Environment var beans []cluster.EnvironmentBean @@ -5129,7 +5129,7 @@ func (impl PipelineBuilderImpl) GetEnvironmentListForAutocompleteFilter(envName return result, nil } -func (impl PipelineBuilderImpl) GetAppListForEnvironment(request appGroup2.AppGroupingRequest) ([]*AppBean, error) { +func (impl *PipelineBuilderImpl) GetAppListForEnvironment(request appGroup2.AppGroupingRequest) ([]*AppBean, error) { var applicationList []*AppBean var cdPipelines []*pipelineConfig.Pipeline var err error diff --git a/pkg/pipeline/mock_pipeline/PipelineBuilder.go b/pkg/pipeline/mock_pipeline/PipelineBuilder.go new file mode 100644 index 00000000000..fb9ab4a17ff --- /dev/null +++ b/pkg/pipeline/mock_pipeline/PipelineBuilder.go @@ -0,0 +1,933 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: pkg/pipeline/PipelineBuilder.go + +// Package mock_pipeline is a generated GoMock package. +package mock_pipeline + +import ( + context "context" + reflect "reflect" + + bean "github.com/devtron-labs/devtron/api/bean" + helper "github.com/devtron-labs/devtron/internal/sql/repository/helper" + pipelineConfig "github.com/devtron-labs/devtron/internal/sql/repository/pipelineConfig" + appGroup "github.com/devtron-labs/devtron/pkg/appGroup" + bean0 "github.com/devtron-labs/devtron/pkg/bean" + cluster "github.com/devtron-labs/devtron/pkg/cluster" + pipeline "github.com/devtron-labs/devtron/pkg/pipeline" + gomock "github.com/golang/mock/gomock" +) + +// MockPipelineBuilder is a mock of PipelineBuilder interface. +type MockPipelineBuilder struct { + ctrl *gomock.Controller + recorder *MockPipelineBuilderMockRecorder +} + +// MockPipelineBuilderMockRecorder is the mock recorder for MockPipelineBuilder. +type MockPipelineBuilderMockRecorder struct { + mock *MockPipelineBuilder +} + +// NewMockPipelineBuilder creates a new mock instance. +func NewMockPipelineBuilder(ctrl *gomock.Controller) *MockPipelineBuilder { + mock := &MockPipelineBuilder{ctrl: ctrl} + mock.recorder = &MockPipelineBuilderMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockPipelineBuilder) EXPECT() *MockPipelineBuilderMockRecorder { + return m.recorder +} + +// ChangeDeploymentType mocks base method. +func (m *MockPipelineBuilder) ChangeDeploymentType(ctx context.Context, request *bean0.DeploymentAppTypeChangeRequest) (*bean0.DeploymentAppTypeChangeResponse, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ChangeDeploymentType", ctx, request) + ret0, _ := ret[0].(*bean0.DeploymentAppTypeChangeResponse) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ChangeDeploymentType indicates an expected call of ChangeDeploymentType. +func (mr *MockPipelineBuilderMockRecorder) ChangeDeploymentType(ctx, request interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ChangeDeploymentType", reflect.TypeOf((*MockPipelineBuilder)(nil).ChangeDeploymentType), ctx, request) +} + +// ChangePipelineDeploymentType mocks base method. +func (m *MockPipelineBuilder) ChangePipelineDeploymentType(ctx context.Context, request *bean0.DeploymentAppTypeChangeRequest) (*bean0.DeploymentAppTypeChangeResponse, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ChangePipelineDeploymentType", ctx, request) + ret0, _ := ret[0].(*bean0.DeploymentAppTypeChangeResponse) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ChangePipelineDeploymentType indicates an expected call of ChangePipelineDeploymentType. +func (mr *MockPipelineBuilderMockRecorder) ChangePipelineDeploymentType(ctx, request interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ChangePipelineDeploymentType", reflect.TypeOf((*MockPipelineBuilder)(nil).ChangePipelineDeploymentType), ctx, request) +} + +// CreateApp mocks base method. +func (m *MockPipelineBuilder) CreateApp(request *bean0.CreateAppDTO) (*bean0.CreateAppDTO, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "CreateApp", request) + ret0, _ := ret[0].(*bean0.CreateAppDTO) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// CreateApp indicates an expected call of CreateApp. +func (mr *MockPipelineBuilderMockRecorder) CreateApp(request interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateApp", reflect.TypeOf((*MockPipelineBuilder)(nil).CreateApp), request) +} + +// CreateCdPipelines mocks base method. +func (m *MockPipelineBuilder) CreateCdPipelines(cdPipelines *bean0.CdPipelines, ctx context.Context) (*bean0.CdPipelines, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "CreateCdPipelines", cdPipelines, ctx) + ret0, _ := ret[0].(*bean0.CdPipelines) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// CreateCdPipelines indicates an expected call of CreateCdPipelines. +func (mr *MockPipelineBuilderMockRecorder) CreateCdPipelines(cdPipelines, ctx interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateCdPipelines", reflect.TypeOf((*MockPipelineBuilder)(nil).CreateCdPipelines), cdPipelines, ctx) +} + +// CreateCiPipeline mocks base method. +func (m *MockPipelineBuilder) CreateCiPipeline(createRequest *bean0.CiConfigRequest) (*bean0.PipelineCreateResponse, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "CreateCiPipeline", createRequest) + ret0, _ := ret[0].(*bean0.PipelineCreateResponse) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// CreateCiPipeline indicates an expected call of CreateCiPipeline. +func (mr *MockPipelineBuilderMockRecorder) CreateCiPipeline(createRequest interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateCiPipeline", reflect.TypeOf((*MockPipelineBuilder)(nil).CreateCiPipeline), createRequest) +} + +// CreateMaterialsForApp mocks base method. +func (m *MockPipelineBuilder) CreateMaterialsForApp(request *bean0.CreateMaterialDTO) (*bean0.CreateMaterialDTO, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "CreateMaterialsForApp", request) + ret0, _ := ret[0].(*bean0.CreateMaterialDTO) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// CreateMaterialsForApp indicates an expected call of CreateMaterialsForApp. +func (mr *MockPipelineBuilderMockRecorder) CreateMaterialsForApp(request interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateMaterialsForApp", reflect.TypeOf((*MockPipelineBuilder)(nil).CreateMaterialsForApp), request) +} + +// DeleteACDAppCdPipelineWithNonCascade mocks base method. +func (m *MockPipelineBuilder) DeleteACDAppCdPipelineWithNonCascade(pipeline *pipelineConfig.Pipeline, ctx context.Context, forceDelete bool, userId int32) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "DeleteACDAppCdPipelineWithNonCascade", pipeline, ctx, forceDelete, userId) + ret0, _ := ret[0].(error) + return ret0 +} + +// DeleteACDAppCdPipelineWithNonCascade indicates an expected call of DeleteACDAppCdPipelineWithNonCascade. +func (mr *MockPipelineBuilderMockRecorder) DeleteACDAppCdPipelineWithNonCascade(pipeline, ctx, forceDelete, userId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteACDAppCdPipelineWithNonCascade", reflect.TypeOf((*MockPipelineBuilder)(nil).DeleteACDAppCdPipelineWithNonCascade), pipeline, ctx, forceDelete, userId) +} + +// DeleteApp mocks base method. +func (m *MockPipelineBuilder) DeleteApp(appId int, userId int32) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "DeleteApp", appId, userId) + ret0, _ := ret[0].(error) + return ret0 +} + +// DeleteApp indicates an expected call of DeleteApp. +func (mr *MockPipelineBuilderMockRecorder) DeleteApp(appId, userId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteApp", reflect.TypeOf((*MockPipelineBuilder)(nil).DeleteApp), appId, userId) +} + +// DeleteCdPipeline mocks base method. +func (m *MockPipelineBuilder) DeleteCdPipeline(pipeline *pipelineConfig.Pipeline, ctx context.Context, deleteAction int, acdDelete bool, userId int32) (*bean0.AppDeleteResponseDTO, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "DeleteCdPipeline", pipeline, ctx, deleteAction, acdDelete, userId) + ret0, _ := ret[0].(*bean0.AppDeleteResponseDTO) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// DeleteCdPipeline indicates an expected call of DeleteCdPipeline. +func (mr *MockPipelineBuilderMockRecorder) DeleteCdPipeline(pipeline, ctx, deleteAction, acdDelete, userId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteCdPipeline", reflect.TypeOf((*MockPipelineBuilder)(nil).DeleteCdPipeline), pipeline, ctx, deleteAction, acdDelete, userId) +} + +// DeleteCiPipeline mocks base method. +func (m *MockPipelineBuilder) DeleteCiPipeline(request *bean0.CiPatchRequest) (*bean0.CiPipeline, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "DeleteCiPipeline", request) + ret0, _ := ret[0].(*bean0.CiPipeline) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// DeleteCiPipeline indicates an expected call of DeleteCiPipeline. +func (mr *MockPipelineBuilderMockRecorder) DeleteCiPipeline(request interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteCiPipeline", reflect.TypeOf((*MockPipelineBuilder)(nil).DeleteCiPipeline), request) +} + +// DeleteDeploymentApps mocks base method. +func (m *MockPipelineBuilder) DeleteDeploymentApps(ctx context.Context, pipelines []*pipelineConfig.Pipeline, userId int32) *bean0.DeploymentAppTypeChangeResponse { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "DeleteDeploymentApps", ctx, pipelines, userId) + ret0, _ := ret[0].(*bean0.DeploymentAppTypeChangeResponse) + return ret0 +} + +// DeleteDeploymentApps indicates an expected call of DeleteDeploymentApps. +func (mr *MockPipelineBuilderMockRecorder) DeleteDeploymentApps(ctx, pipelines, userId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteDeploymentApps", reflect.TypeOf((*MockPipelineBuilder)(nil).DeleteDeploymentApps), ctx, pipelines, userId) +} + +// DeleteDeploymentAppsForEnvironment mocks base method. +func (m *MockPipelineBuilder) DeleteDeploymentAppsForEnvironment(ctx context.Context, environmentId int, currentDeploymentAppType bean0.DeploymentType, exclusionList, includeApps []int, userId int32) (*bean0.DeploymentAppTypeChangeResponse, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "DeleteDeploymentAppsForEnvironment", ctx, environmentId, currentDeploymentAppType, exclusionList, includeApps, userId) + ret0, _ := ret[0].(*bean0.DeploymentAppTypeChangeResponse) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// DeleteDeploymentAppsForEnvironment indicates an expected call of DeleteDeploymentAppsForEnvironment. +func (mr *MockPipelineBuilderMockRecorder) DeleteDeploymentAppsForEnvironment(ctx, environmentId, currentDeploymentAppType, exclusionList, includeApps, userId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteDeploymentAppsForEnvironment", reflect.TypeOf((*MockPipelineBuilder)(nil).DeleteDeploymentAppsForEnvironment), ctx, environmentId, currentDeploymentAppType, exclusionList, includeApps, userId) +} + +// DeleteMaterial mocks base method. +func (m *MockPipelineBuilder) DeleteMaterial(request *bean0.UpdateMaterialDTO) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "DeleteMaterial", request) + ret0, _ := ret[0].(error) + return ret0 +} + +// DeleteMaterial indicates an expected call of DeleteMaterial. +func (mr *MockPipelineBuilderMockRecorder) DeleteMaterial(request interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteMaterial", reflect.TypeOf((*MockPipelineBuilder)(nil).DeleteMaterial), request) +} + +// FetchArtifactForRollback mocks base method. +func (m *MockPipelineBuilder) FetchArtifactForRollback(cdPipelineId, offset, limit int) (bean0.CiArtifactResponse, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "FetchArtifactForRollback", cdPipelineId, offset, limit) + ret0, _ := ret[0].(bean0.CiArtifactResponse) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// FetchArtifactForRollback indicates an expected call of FetchArtifactForRollback. +func (mr *MockPipelineBuilderMockRecorder) FetchArtifactForRollback(cdPipelineId, offset, limit interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FetchArtifactForRollback", reflect.TypeOf((*MockPipelineBuilder)(nil).FetchArtifactForRollback), cdPipelineId, offset, limit) +} + +// FetchCDPipelineStrategy mocks base method. +func (m *MockPipelineBuilder) FetchCDPipelineStrategy(appId int) (pipeline.PipelineStrategiesResponse, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "FetchCDPipelineStrategy", appId) + ret0, _ := ret[0].(pipeline.PipelineStrategiesResponse) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// FetchCDPipelineStrategy indicates an expected call of FetchCDPipelineStrategy. +func (mr *MockPipelineBuilderMockRecorder) FetchCDPipelineStrategy(appId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FetchCDPipelineStrategy", reflect.TypeOf((*MockPipelineBuilder)(nil).FetchCDPipelineStrategy), appId) +} + +// FetchConfigmapSecretsForCdStages mocks base method. +func (m *MockPipelineBuilder) FetchConfigmapSecretsForCdStages(appId, envId, cdPipelineId int) (pipeline.ConfigMapSecretsResponse, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "FetchConfigmapSecretsForCdStages", appId, envId, cdPipelineId) + ret0, _ := ret[0].(pipeline.ConfigMapSecretsResponse) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// FetchConfigmapSecretsForCdStages indicates an expected call of FetchConfigmapSecretsForCdStages. +func (mr *MockPipelineBuilderMockRecorder) FetchConfigmapSecretsForCdStages(appId, envId, cdPipelineId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FetchConfigmapSecretsForCdStages", reflect.TypeOf((*MockPipelineBuilder)(nil).FetchConfigmapSecretsForCdStages), appId, envId, cdPipelineId) +} + +// FetchDefaultCDPipelineStrategy mocks base method. +func (m *MockPipelineBuilder) FetchDefaultCDPipelineStrategy(appId, envId int) (pipeline.PipelineStrategy, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "FetchDefaultCDPipelineStrategy", appId, envId) + ret0, _ := ret[0].(pipeline.PipelineStrategy) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// FetchDefaultCDPipelineStrategy indicates an expected call of FetchDefaultCDPipelineStrategy. +func (mr *MockPipelineBuilderMockRecorder) FetchDefaultCDPipelineStrategy(appId, envId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FetchDefaultCDPipelineStrategy", reflect.TypeOf((*MockPipelineBuilder)(nil).FetchDefaultCDPipelineStrategy), appId, envId) +} + +// FindAllMatchesByAppName mocks base method. +func (m *MockPipelineBuilder) FindAllMatchesByAppName(appName string, appType helper.AppType) ([]*pipeline.AppBean, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "FindAllMatchesByAppName", appName, appType) + ret0, _ := ret[0].([]*pipeline.AppBean) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// FindAllMatchesByAppName indicates an expected call of FindAllMatchesByAppName. +func (mr *MockPipelineBuilderMockRecorder) FindAllMatchesByAppName(appName, appType interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindAllMatchesByAppName", reflect.TypeOf((*MockPipelineBuilder)(nil).FindAllMatchesByAppName), appName, appType) +} + +// FindAppAndEnvDetailsByPipelineId mocks base method. +func (m *MockPipelineBuilder) FindAppAndEnvDetailsByPipelineId(cdPipelineId int) (*pipelineConfig.Pipeline, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "FindAppAndEnvDetailsByPipelineId", cdPipelineId) + ret0, _ := ret[0].(*pipelineConfig.Pipeline) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// FindAppAndEnvDetailsByPipelineId indicates an expected call of FindAppAndEnvDetailsByPipelineId. +func (mr *MockPipelineBuilderMockRecorder) FindAppAndEnvDetailsByPipelineId(cdPipelineId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindAppAndEnvDetailsByPipelineId", reflect.TypeOf((*MockPipelineBuilder)(nil).FindAppAndEnvDetailsByPipelineId), cdPipelineId) +} + +// FindAppsByTeamId mocks base method. +func (m *MockPipelineBuilder) FindAppsByTeamId(teamId int) ([]*pipeline.AppBean, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "FindAppsByTeamId", teamId) + ret0, _ := ret[0].([]*pipeline.AppBean) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// FindAppsByTeamId indicates an expected call of FindAppsByTeamId. +func (mr *MockPipelineBuilderMockRecorder) FindAppsByTeamId(teamId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindAppsByTeamId", reflect.TypeOf((*MockPipelineBuilder)(nil).FindAppsByTeamId), teamId) +} + +// FindAppsByTeamName mocks base method. +func (m *MockPipelineBuilder) FindAppsByTeamName(teamName string) ([]pipeline.AppBean, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "FindAppsByTeamName", teamName) + ret0, _ := ret[0].([]pipeline.AppBean) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// FindAppsByTeamName indicates an expected call of FindAppsByTeamName. +func (mr *MockPipelineBuilderMockRecorder) FindAppsByTeamName(teamName interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindAppsByTeamName", reflect.TypeOf((*MockPipelineBuilder)(nil).FindAppsByTeamName), teamName) +} + +// FindByIds mocks base method. +func (m *MockPipelineBuilder) FindByIds(ids []*int) ([]*pipeline.AppBean, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "FindByIds", ids) + ret0, _ := ret[0].([]*pipeline.AppBean) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// FindByIds indicates an expected call of FindByIds. +func (mr *MockPipelineBuilderMockRecorder) FindByIds(ids interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindByIds", reflect.TypeOf((*MockPipelineBuilder)(nil).FindByIds), ids) +} + +// FindPipelineById mocks base method. +func (m *MockPipelineBuilder) FindPipelineById(cdPipelineId int) (*pipelineConfig.Pipeline, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "FindPipelineById", cdPipelineId) + ret0, _ := ret[0].(*pipelineConfig.Pipeline) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// FindPipelineById indicates an expected call of FindPipelineById. +func (mr *MockPipelineBuilderMockRecorder) FindPipelineById(cdPipelineId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindPipelineById", reflect.TypeOf((*MockPipelineBuilder)(nil).FindPipelineById), cdPipelineId) +} + +// GetApp mocks base method. +func (m *MockPipelineBuilder) GetApp(appId int) (*bean0.CreateAppDTO, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetApp", appId) + ret0, _ := ret[0].(*bean0.CreateAppDTO) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetApp indicates an expected call of GetApp. +func (mr *MockPipelineBuilderMockRecorder) GetApp(appId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetApp", reflect.TypeOf((*MockPipelineBuilder)(nil).GetApp), appId) +} + +// GetAppList mocks base method. +func (m *MockPipelineBuilder) GetAppList() ([]pipeline.AppBean, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetAppList") + ret0, _ := ret[0].([]pipeline.AppBean) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetAppList indicates an expected call of GetAppList. +func (mr *MockPipelineBuilderMockRecorder) GetAppList() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAppList", reflect.TypeOf((*MockPipelineBuilder)(nil).GetAppList)) +} + +// GetAppListForEnvironment mocks base method. +func (m *MockPipelineBuilder) GetAppListForEnvironment(request appGroup.AppGroupingRequest) ([]*pipeline.AppBean, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetAppListForEnvironment", request) + ret0, _ := ret[0].([]*pipeline.AppBean) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetAppListForEnvironment indicates an expected call of GetAppListForEnvironment. +func (mr *MockPipelineBuilderMockRecorder) GetAppListForEnvironment(request interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAppListForEnvironment", reflect.TypeOf((*MockPipelineBuilder)(nil).GetAppListForEnvironment), request) +} + +// GetBulkActionImpactedPipelines mocks base method. +func (m *MockPipelineBuilder) GetBulkActionImpactedPipelines(dto *bean0.CdBulkActionRequestDto) ([]*pipelineConfig.Pipeline, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetBulkActionImpactedPipelines", dto) + ret0, _ := ret[0].([]*pipelineConfig.Pipeline) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetBulkActionImpactedPipelines indicates an expected call of GetBulkActionImpactedPipelines. +func (mr *MockPipelineBuilderMockRecorder) GetBulkActionImpactedPipelines(dto interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBulkActionImpactedPipelines", reflect.TypeOf((*MockPipelineBuilder)(nil).GetBulkActionImpactedPipelines), dto) +} + +// GetCdPipelineById mocks base method. +func (m *MockPipelineBuilder) GetCdPipelineById(pipelineId int) (*bean0.CDPipelineConfigObject, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetCdPipelineById", pipelineId) + ret0, _ := ret[0].(*bean0.CDPipelineConfigObject) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetCdPipelineById indicates an expected call of GetCdPipelineById. +func (mr *MockPipelineBuilderMockRecorder) GetCdPipelineById(pipelineId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCdPipelineById", reflect.TypeOf((*MockPipelineBuilder)(nil).GetCdPipelineById), pipelineId) +} + +// GetCdPipelinesByEnvironment mocks base method. +func (m *MockPipelineBuilder) GetCdPipelinesByEnvironment(request appGroup.AppGroupingRequest) (*bean0.CdPipelines, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetCdPipelinesByEnvironment", request) + ret0, _ := ret[0].(*bean0.CdPipelines) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetCdPipelinesByEnvironment indicates an expected call of GetCdPipelinesByEnvironment. +func (mr *MockPipelineBuilderMockRecorder) GetCdPipelinesByEnvironment(request interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCdPipelinesByEnvironment", reflect.TypeOf((*MockPipelineBuilder)(nil).GetCdPipelinesByEnvironment), request) +} + +// GetCdPipelinesByEnvironmentMin mocks base method. +func (m *MockPipelineBuilder) GetCdPipelinesByEnvironmentMin(request appGroup.AppGroupingRequest) ([]*bean0.CDPipelineConfigObject, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetCdPipelinesByEnvironmentMin", request) + ret0, _ := ret[0].([]*bean0.CDPipelineConfigObject) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetCdPipelinesByEnvironmentMin indicates an expected call of GetCdPipelinesByEnvironmentMin. +func (mr *MockPipelineBuilderMockRecorder) GetCdPipelinesByEnvironmentMin(request interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCdPipelinesByEnvironmentMin", reflect.TypeOf((*MockPipelineBuilder)(nil).GetCdPipelinesByEnvironmentMin), request) +} + +// GetCdPipelinesForApp mocks base method. +func (m *MockPipelineBuilder) GetCdPipelinesForApp(appId int) (*bean0.CdPipelines, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetCdPipelinesForApp", appId) + ret0, _ := ret[0].(*bean0.CdPipelines) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetCdPipelinesForApp indicates an expected call of GetCdPipelinesForApp. +func (mr *MockPipelineBuilderMockRecorder) GetCdPipelinesForApp(appId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCdPipelinesForApp", reflect.TypeOf((*MockPipelineBuilder)(nil).GetCdPipelinesForApp), appId) +} + +// GetCdPipelinesForAppAndEnv mocks base method. +func (m *MockPipelineBuilder) GetCdPipelinesForAppAndEnv(appId, envId int) (*bean0.CdPipelines, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetCdPipelinesForAppAndEnv", appId, envId) + ret0, _ := ret[0].(*bean0.CdPipelines) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetCdPipelinesForAppAndEnv indicates an expected call of GetCdPipelinesForAppAndEnv. +func (mr *MockPipelineBuilderMockRecorder) GetCdPipelinesForAppAndEnv(appId, envId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCdPipelinesForAppAndEnv", reflect.TypeOf((*MockPipelineBuilder)(nil).GetCdPipelinesForAppAndEnv), appId, envId) +} + +// GetCiPipeline mocks base method. +func (m *MockPipelineBuilder) GetCiPipeline(appId int) (*bean0.CiConfigRequest, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetCiPipeline", appId) + ret0, _ := ret[0].(*bean0.CiConfigRequest) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetCiPipeline indicates an expected call of GetCiPipeline. +func (mr *MockPipelineBuilderMockRecorder) GetCiPipeline(appId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCiPipeline", reflect.TypeOf((*MockPipelineBuilder)(nil).GetCiPipeline), appId) +} + +// GetCiPipelineByEnvironment mocks base method. +func (m *MockPipelineBuilder) GetCiPipelineByEnvironment(request appGroup.AppGroupingRequest) ([]*bean0.CiConfigRequest, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetCiPipelineByEnvironment", request) + ret0, _ := ret[0].([]*bean0.CiConfigRequest) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetCiPipelineByEnvironment indicates an expected call of GetCiPipelineByEnvironment. +func (mr *MockPipelineBuilderMockRecorder) GetCiPipelineByEnvironment(request interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCiPipelineByEnvironment", reflect.TypeOf((*MockPipelineBuilder)(nil).GetCiPipelineByEnvironment), request) +} + +// GetCiPipelineByEnvironmentMin mocks base method. +func (m *MockPipelineBuilder) GetCiPipelineByEnvironmentMin(request appGroup.AppGroupingRequest) ([]*bean0.CiPipelineMinResponse, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetCiPipelineByEnvironmentMin", request) + ret0, _ := ret[0].([]*bean0.CiPipelineMinResponse) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetCiPipelineByEnvironmentMin indicates an expected call of GetCiPipelineByEnvironmentMin. +func (mr *MockPipelineBuilderMockRecorder) GetCiPipelineByEnvironmentMin(request interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCiPipelineByEnvironmentMin", reflect.TypeOf((*MockPipelineBuilder)(nil).GetCiPipelineByEnvironmentMin), request) +} + +// GetCiPipelineById mocks base method. +func (m *MockPipelineBuilder) GetCiPipelineById(pipelineId int) (*bean0.CiPipeline, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetCiPipelineById", pipelineId) + ret0, _ := ret[0].(*bean0.CiPipeline) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetCiPipelineById indicates an expected call of GetCiPipelineById. +func (mr *MockPipelineBuilderMockRecorder) GetCiPipelineById(pipelineId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCiPipelineById", reflect.TypeOf((*MockPipelineBuilder)(nil).GetCiPipelineById), pipelineId) +} + +// GetCiPipelineMin mocks base method. +func (m *MockPipelineBuilder) GetCiPipelineMin(appId int) ([]*bean0.CiPipelineMin, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetCiPipelineMin", appId) + ret0, _ := ret[0].([]*bean0.CiPipelineMin) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetCiPipelineMin indicates an expected call of GetCiPipelineMin. +func (mr *MockPipelineBuilderMockRecorder) GetCiPipelineMin(appId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCiPipelineMin", reflect.TypeOf((*MockPipelineBuilder)(nil).GetCiPipelineMin), appId) +} + +// GetDeploymentConfigMap mocks base method. +func (m *MockPipelineBuilder) GetDeploymentConfigMap(environmentId int) (map[string]bool, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetDeploymentConfigMap", environmentId) + ret0, _ := ret[0].(map[string]bool) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetDeploymentConfigMap indicates an expected call of GetDeploymentConfigMap. +func (mr *MockPipelineBuilderMockRecorder) GetDeploymentConfigMap(environmentId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetDeploymentConfigMap", reflect.TypeOf((*MockPipelineBuilder)(nil).GetDeploymentConfigMap), environmentId) +} + +// GetEnvironmentByCdPipelineId mocks base method. +func (m *MockPipelineBuilder) GetEnvironmentByCdPipelineId(pipelineId int) (int, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetEnvironmentByCdPipelineId", pipelineId) + ret0, _ := ret[0].(int) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetEnvironmentByCdPipelineId indicates an expected call of GetEnvironmentByCdPipelineId. +func (mr *MockPipelineBuilderMockRecorder) GetEnvironmentByCdPipelineId(pipelineId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetEnvironmentByCdPipelineId", reflect.TypeOf((*MockPipelineBuilder)(nil).GetEnvironmentByCdPipelineId), pipelineId) +} + +// GetEnvironmentListForAutocompleteFilter mocks base method. +func (m *MockPipelineBuilder) GetEnvironmentListForAutocompleteFilter(envName string, clusterIds []int, offset, size int, emailId string, checkAuthBatch func(string, []string, []string) (map[string]bool, map[string]bool), ctx context.Context) (*cluster.AppGroupingResponse, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetEnvironmentListForAutocompleteFilter", envName, clusterIds, offset, size, emailId, checkAuthBatch, ctx) + ret0, _ := ret[0].(*cluster.AppGroupingResponse) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetEnvironmentListForAutocompleteFilter indicates an expected call of GetEnvironmentListForAutocompleteFilter. +func (mr *MockPipelineBuilderMockRecorder) GetEnvironmentListForAutocompleteFilter(envName, clusterIds, offset, size, emailId, checkAuthBatch, ctx interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetEnvironmentListForAutocompleteFilter", reflect.TypeOf((*MockPipelineBuilder)(nil).GetEnvironmentListForAutocompleteFilter), envName, clusterIds, offset, size, emailId, checkAuthBatch, ctx) +} + +// GetExternalCi mocks base method. +func (m *MockPipelineBuilder) GetExternalCi(appId int) ([]*bean0.ExternalCiConfig, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetExternalCi", appId) + ret0, _ := ret[0].([]*bean0.ExternalCiConfig) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetExternalCi indicates an expected call of GetExternalCi. +func (mr *MockPipelineBuilderMockRecorder) GetExternalCi(appId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetExternalCi", reflect.TypeOf((*MockPipelineBuilder)(nil).GetExternalCi), appId) +} + +// GetExternalCiByEnvironment mocks base method. +func (m *MockPipelineBuilder) GetExternalCiByEnvironment(request appGroup.AppGroupingRequest) ([]*bean0.ExternalCiConfig, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetExternalCiByEnvironment", request) + ret0, _ := ret[0].([]*bean0.ExternalCiConfig) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetExternalCiByEnvironment indicates an expected call of GetExternalCiByEnvironment. +func (mr *MockPipelineBuilderMockRecorder) GetExternalCiByEnvironment(request interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetExternalCiByEnvironment", reflect.TypeOf((*MockPipelineBuilder)(nil).GetExternalCiByEnvironment), request) +} + +// GetExternalCiById mocks base method. +func (m *MockPipelineBuilder) GetExternalCiById(appId, externalCiId int) (*bean0.ExternalCiConfig, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetExternalCiById", appId, externalCiId) + ret0, _ := ret[0].(*bean0.ExternalCiConfig) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetExternalCiById indicates an expected call of GetExternalCiById. +func (mr *MockPipelineBuilderMockRecorder) GetExternalCiById(appId, externalCiId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetExternalCiById", reflect.TypeOf((*MockPipelineBuilder)(nil).GetExternalCiById), appId, externalCiId) +} + +// GetMaterialsForAppId mocks base method. +func (m *MockPipelineBuilder) GetMaterialsForAppId(appId int) []*bean0.GitMaterial { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetMaterialsForAppId", appId) + ret0, _ := ret[0].([]*bean0.GitMaterial) + return ret0 +} + +// GetMaterialsForAppId indicates an expected call of GetMaterialsForAppId. +func (mr *MockPipelineBuilderMockRecorder) GetMaterialsForAppId(appId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetMaterialsForAppId", reflect.TypeOf((*MockPipelineBuilder)(nil).GetMaterialsForAppId), appId) +} + +// GetTriggerViewCdPipelinesForApp mocks base method. +func (m *MockPipelineBuilder) GetTriggerViewCdPipelinesForApp(appId int) (*bean0.CdPipelines, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetTriggerViewCdPipelinesForApp", appId) + ret0, _ := ret[0].(*bean0.CdPipelines) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetTriggerViewCdPipelinesForApp indicates an expected call of GetTriggerViewCdPipelinesForApp. +func (mr *MockPipelineBuilderMockRecorder) GetTriggerViewCdPipelinesForApp(appId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTriggerViewCdPipelinesForApp", reflect.TypeOf((*MockPipelineBuilder)(nil).GetTriggerViewCdPipelinesForApp), appId) +} + +// GetTriggerViewCiPipeline mocks base method. +func (m *MockPipelineBuilder) GetTriggerViewCiPipeline(appId int) (*bean0.TriggerViewCiConfig, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetTriggerViewCiPipeline", appId) + ret0, _ := ret[0].(*bean0.TriggerViewCiConfig) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetTriggerViewCiPipeline indicates an expected call of GetTriggerViewCiPipeline. +func (mr *MockPipelineBuilderMockRecorder) GetTriggerViewCiPipeline(appId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTriggerViewCiPipeline", reflect.TypeOf((*MockPipelineBuilder)(nil).GetTriggerViewCiPipeline), appId) +} + +// IsGitOpsRequiredForCD mocks base method. +func (m *MockPipelineBuilder) IsGitOpsRequiredForCD(pipelineCreateRequest *bean0.CdPipelines) bool { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "IsGitOpsRequiredForCD", pipelineCreateRequest) + ret0, _ := ret[0].(bool) + return ret0 +} + +// IsGitOpsRequiredForCD indicates an expected call of IsGitOpsRequiredForCD. +func (mr *MockPipelineBuilderMockRecorder) IsGitOpsRequiredForCD(pipelineCreateRequest interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsGitOpsRequiredForCD", reflect.TypeOf((*MockPipelineBuilder)(nil).IsGitOpsRequiredForCD), pipelineCreateRequest) +} + +// IsGitopsConfigured mocks base method. +func (m *MockPipelineBuilder) IsGitopsConfigured() (bool, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "IsGitopsConfigured") + ret0, _ := ret[0].(bool) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// IsGitopsConfigured indicates an expected call of IsGitopsConfigured. +func (mr *MockPipelineBuilderMockRecorder) IsGitopsConfigured() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsGitopsConfigured", reflect.TypeOf((*MockPipelineBuilder)(nil).IsGitopsConfigured)) +} + +// MarkGitOpsDevtronAppsDeletedWhereArgoAppIsDeleted mocks base method. +func (m *MockPipelineBuilder) MarkGitOpsDevtronAppsDeletedWhereArgoAppIsDeleted(appId, envId int, acdToken string, pipeline *pipelineConfig.Pipeline) (bool, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "MarkGitOpsDevtronAppsDeletedWhereArgoAppIsDeleted", appId, envId, acdToken, pipeline) + ret0, _ := ret[0].(bool) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// MarkGitOpsDevtronAppsDeletedWhereArgoAppIsDeleted indicates an expected call of MarkGitOpsDevtronAppsDeletedWhereArgoAppIsDeleted. +func (mr *MockPipelineBuilderMockRecorder) MarkGitOpsDevtronAppsDeletedWhereArgoAppIsDeleted(appId, envId, acdToken, pipeline interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MarkGitOpsDevtronAppsDeletedWhereArgoAppIsDeleted", reflect.TypeOf((*MockPipelineBuilder)(nil).MarkGitOpsDevtronAppsDeletedWhereArgoAppIsDeleted), appId, envId, acdToken, pipeline) +} + +// PatchCdPipelines mocks base method. +func (m *MockPipelineBuilder) PatchCdPipelines(cdPipelines *bean0.CDPatchRequest, ctx context.Context) (*bean0.CdPipelines, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "PatchCdPipelines", cdPipelines, ctx) + ret0, _ := ret[0].(*bean0.CdPipelines) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// PatchCdPipelines indicates an expected call of PatchCdPipelines. +func (mr *MockPipelineBuilderMockRecorder) PatchCdPipelines(cdPipelines, ctx interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PatchCdPipelines", reflect.TypeOf((*MockPipelineBuilder)(nil).PatchCdPipelines), cdPipelines, ctx) +} + +// PatchCiMaterialSource mocks base method. +func (m *MockPipelineBuilder) PatchCiMaterialSource(ciPipeline *bean0.CiPipeline, userId int32) (*bean0.CiPipeline, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "PatchCiMaterialSource", ciPipeline, userId) + ret0, _ := ret[0].(*bean0.CiPipeline) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// PatchCiMaterialSource indicates an expected call of PatchCiMaterialSource. +func (mr *MockPipelineBuilderMockRecorder) PatchCiMaterialSource(ciPipeline, userId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PatchCiMaterialSource", reflect.TypeOf((*MockPipelineBuilder)(nil).PatchCiMaterialSource), ciPipeline, userId) +} + +// PatchCiPipeline mocks base method. +func (m *MockPipelineBuilder) PatchCiPipeline(request *bean0.CiPatchRequest) (*bean0.CiConfigRequest, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "PatchCiPipeline", request) + ret0, _ := ret[0].(*bean0.CiConfigRequest) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// PatchCiPipeline indicates an expected call of PatchCiPipeline. +func (mr *MockPipelineBuilderMockRecorder) PatchCiPipeline(request interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PatchCiPipeline", reflect.TypeOf((*MockPipelineBuilder)(nil).PatchCiPipeline), request) +} + +// PatchRegexCiPipeline mocks base method. +func (m *MockPipelineBuilder) PatchRegexCiPipeline(request *bean0.CiRegexPatchRequest) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "PatchRegexCiPipeline", request) + ret0, _ := ret[0].(error) + return ret0 +} + +// PatchRegexCiPipeline indicates an expected call of PatchRegexCiPipeline. +func (mr *MockPipelineBuilderMockRecorder) PatchRegexCiPipeline(request interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PatchRegexCiPipeline", reflect.TypeOf((*MockPipelineBuilder)(nil).PatchRegexCiPipeline), request) +} + +// PerformBulkActionOnCdPipelines mocks base method. +func (m *MockPipelineBuilder) PerformBulkActionOnCdPipelines(dto *bean0.CdBulkActionRequestDto, impactedPipelines []*pipelineConfig.Pipeline, ctx context.Context, dryRun bool, userId int32) ([]*bean0.CdBulkActionResponseDto, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "PerformBulkActionOnCdPipelines", dto, impactedPipelines, ctx, dryRun, userId) + ret0, _ := ret[0].([]*bean0.CdBulkActionResponseDto) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// PerformBulkActionOnCdPipelines indicates an expected call of PerformBulkActionOnCdPipelines. +func (mr *MockPipelineBuilderMockRecorder) PerformBulkActionOnCdPipelines(dto, impactedPipelines, ctx, dryRun, userId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PerformBulkActionOnCdPipelines", reflect.TypeOf((*MockPipelineBuilder)(nil).PerformBulkActionOnCdPipelines), dto, impactedPipelines, ctx, dryRun, userId) +} + +// RetrieveArtifactsByCDPipeline mocks base method. +func (m *MockPipelineBuilder) RetrieveArtifactsByCDPipeline(pipeline *pipelineConfig.Pipeline, stage bean.WorkflowType) (*bean0.CiArtifactResponse, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "RetrieveArtifactsByCDPipeline", pipeline, stage) + ret0, _ := ret[0].(*bean0.CiArtifactResponse) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// RetrieveArtifactsByCDPipeline indicates an expected call of RetrieveArtifactsByCDPipeline. +func (mr *MockPipelineBuilderMockRecorder) RetrieveArtifactsByCDPipeline(pipeline, stage interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RetrieveArtifactsByCDPipeline", reflect.TypeOf((*MockPipelineBuilder)(nil).RetrieveArtifactsByCDPipeline), pipeline, stage) +} + +// RetrieveParentDetails mocks base method. +func (m *MockPipelineBuilder) RetrieveParentDetails(pipelineId int) (int, bean.WorkflowType, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "RetrieveParentDetails", pipelineId) + ret0, _ := ret[0].(int) + ret1, _ := ret[1].(bean.WorkflowType) + ret2, _ := ret[2].(error) + return ret0, ret1, ret2 +} + +// RetrieveParentDetails indicates an expected call of RetrieveParentDetails. +func (mr *MockPipelineBuilderMockRecorder) RetrieveParentDetails(pipelineId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RetrieveParentDetails", reflect.TypeOf((*MockPipelineBuilder)(nil).RetrieveParentDetails), pipelineId) +} + +// SetPipelineDeploymentAppType mocks base method. +func (m *MockPipelineBuilder) SetPipelineDeploymentAppType(pipelineCreateRequest *bean0.CdPipelines, isGitOpsConfigured bool, deploymentTypeValidationConfig map[string]bool) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SetPipelineDeploymentAppType", pipelineCreateRequest, isGitOpsConfigured, deploymentTypeValidationConfig) +} + +// SetPipelineDeploymentAppType indicates an expected call of SetPipelineDeploymentAppType. +func (mr *MockPipelineBuilderMockRecorder) SetPipelineDeploymentAppType(pipelineCreateRequest, isGitOpsConfigured, deploymentTypeValidationConfig interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetPipelineDeploymentAppType", reflect.TypeOf((*MockPipelineBuilder)(nil).SetPipelineDeploymentAppType), pipelineCreateRequest, isGitOpsConfigured, deploymentTypeValidationConfig) +} + +// TriggerDeploymentAfterTypeChange mocks base method. +func (m *MockPipelineBuilder) TriggerDeploymentAfterTypeChange(ctx context.Context, request *bean0.DeploymentAppTypeChangeRequest) (*bean0.DeploymentAppTypeChangeResponse, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "TriggerDeploymentAfterTypeChange", ctx, request) + ret0, _ := ret[0].(*bean0.DeploymentAppTypeChangeResponse) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// TriggerDeploymentAfterTypeChange indicates an expected call of TriggerDeploymentAfterTypeChange. +func (mr *MockPipelineBuilderMockRecorder) TriggerDeploymentAfterTypeChange(ctx, request interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TriggerDeploymentAfterTypeChange", reflect.TypeOf((*MockPipelineBuilder)(nil).TriggerDeploymentAfterTypeChange), ctx, request) +} + +// UpdateCiTemplate mocks base method. +func (m *MockPipelineBuilder) UpdateCiTemplate(updateRequest *bean0.CiConfigRequest) (*bean0.CiConfigRequest, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "UpdateCiTemplate", updateRequest) + ret0, _ := ret[0].(*bean0.CiConfigRequest) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// UpdateCiTemplate indicates an expected call of UpdateCiTemplate. +func (mr *MockPipelineBuilderMockRecorder) UpdateCiTemplate(updateRequest interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateCiTemplate", reflect.TypeOf((*MockPipelineBuilder)(nil).UpdateCiTemplate), updateRequest) +} + +// UpdateMaterialsForApp mocks base method. +func (m *MockPipelineBuilder) UpdateMaterialsForApp(request *bean0.UpdateMaterialDTO) (*bean0.UpdateMaterialDTO, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "UpdateMaterialsForApp", request) + ret0, _ := ret[0].(*bean0.UpdateMaterialDTO) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// UpdateMaterialsForApp indicates an expected call of UpdateMaterialsForApp. +func (mr *MockPipelineBuilderMockRecorder) UpdateMaterialsForApp(request interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateMaterialsForApp", reflect.TypeOf((*MockPipelineBuilder)(nil).UpdateMaterialsForApp), request) +} diff --git a/pkg/user/UserService.go b/pkg/user/UserService.go index 7edcd133307..73a7f795ebf 100644 --- a/pkg/user/UserService.go +++ b/pkg/user/UserService.go @@ -89,7 +89,7 @@ func NewUserServiceImpl(userAuthRepository repository2.UserAuthRepository, return serviceImpl } -func (impl UserServiceImpl) validateUserRequest(userInfo *bean.UserInfo) (bool, error) { +func (impl *UserServiceImpl) validateUserRequest(userInfo *bean.UserInfo) (bool, error) { if len(userInfo.RoleFilters) == 1 && userInfo.RoleFilters[0].Team == "" && userInfo.RoleFilters[0].Environment == "" && userInfo.RoleFilters[0].Action == "" { //skip @@ -112,7 +112,7 @@ func (impl UserServiceImpl) validateUserRequest(userInfo *bean.UserInfo) (bool, return true, nil } -func (impl UserServiceImpl) SelfRegisterUserIfNotExists(userInfo *bean.UserInfo) ([]*bean.UserInfo, error) { +func (impl *UserServiceImpl) SelfRegisterUserIfNotExists(userInfo *bean.UserInfo) ([]*bean.UserInfo, error) { var pass []string var userResponse []*bean.UserInfo emailIds := strings.Split(userInfo.EmailId, ",") @@ -187,7 +187,7 @@ func (impl UserServiceImpl) SelfRegisterUserIfNotExists(userInfo *bean.UserInfo) return userResponse, nil } -func (impl UserServiceImpl) saveUser(userInfo *bean.UserInfo, emailId string) (*bean.UserInfo, error) { +func (impl *UserServiceImpl) saveUser(userInfo *bean.UserInfo, emailId string) (*bean.UserInfo, error) { dbConnection := impl.userRepository.GetConnection() tx, err := dbConnection.Begin() if err != nil { @@ -225,7 +225,7 @@ func (impl UserServiceImpl) saveUser(userInfo *bean.UserInfo, emailId string) (* return userInfo, nil } -func (impl UserServiceImpl) CreateUser(userInfo *bean.UserInfo, token string, managerAuth func(resource, token string, object string) bool) ([]*bean.UserInfo, error) { +func (impl *UserServiceImpl) CreateUser(userInfo *bean.UserInfo, token string, managerAuth func(resource, token string, object string) bool) ([]*bean.UserInfo, error) { var pass []string var userResponse []*bean.UserInfo @@ -264,7 +264,7 @@ func (impl UserServiceImpl) CreateUser(userInfo *bean.UserInfo, token string, ma return userResponse, nil } -func (impl UserServiceImpl) updateUserIfExists(userInfo *bean.UserInfo, dbUser *repository2.UserModel, emailId string, +func (impl *UserServiceImpl) updateUserIfExists(userInfo *bean.UserInfo, dbUser *repository2.UserModel, emailId string, token string, managerAuth func(resource, token, object string) bool) (*bean.UserInfo, error) { updateUserInfo, err := impl.GetById(dbUser.Id) if err != nil && err != pg.ErrNoRows { @@ -288,7 +288,7 @@ func (impl UserServiceImpl) updateUserIfExists(userInfo *bean.UserInfo, dbUser * return userInfo, nil } -func (impl UserServiceImpl) createUserIfNotExists(userInfo *bean.UserInfo, emailId string, token string, managerAuth func(resource string, token string, object string) bool) (*bean.UserInfo, error) { +func (impl *UserServiceImpl) createUserIfNotExists(userInfo *bean.UserInfo, emailId string, token string, managerAuth func(resource string, token string, object string) bool) (*bean.UserInfo, error) { // if not found, create new user dbConnection := impl.userRepository.GetConnection() tx, err := dbConnection.Begin() @@ -405,7 +405,7 @@ func (impl UserServiceImpl) createUserIfNotExists(userInfo *bean.UserInfo, email return userInfo, nil } -func (impl UserServiceImpl) CreateOrUpdateUserRolesForAllTypes(roleFilter bean.RoleFilter, userId int32, model *repository2.UserModel, existingRoles map[int]repository2.UserRoleModel, token string, managerAuth func(resource string, token string, object string) bool, tx *pg.Tx, entity string, capacity int) ([]casbin2.Policy, bool, error) { +func (impl *UserServiceImpl) CreateOrUpdateUserRolesForAllTypes(roleFilter bean.RoleFilter, userId int32, model *repository2.UserModel, existingRoles map[int]repository2.UserRoleModel, token string, managerAuth func(resource string, token string, object string) bool, tx *pg.Tx, entity string, capacity int) ([]casbin2.Policy, bool, error) { //var policiesToBeAdded []casbin2.Policy var policiesToBeAdded = make([]casbin2.Policy, 0, capacity) var err error @@ -479,7 +479,7 @@ func (impl UserServiceImpl) CreateOrUpdateUserRolesForAllTypes(roleFilter bean.R return policiesToBeAdded, rolesChanged, nil } -func (impl UserServiceImpl) createOrUpdateUserRolesForClusterEntity(roleFilter bean.RoleFilter, userId int32, model *repository2.UserModel, existingRoles map[int]repository2.UserRoleModel, token string, managerAuth func(resource string, token string, object string) bool, tx *pg.Tx, entity string, capacity int) ([]casbin2.Policy, bool, error) { +func (impl *UserServiceImpl) createOrUpdateUserRolesForClusterEntity(roleFilter bean.RoleFilter, userId int32, model *repository2.UserModel, existingRoles map[int]repository2.UserRoleModel, token string, managerAuth func(resource string, token string, object string) bool, tx *pg.Tx, entity string, capacity int) ([]casbin2.Policy, bool, error) { //var policiesToBeAdded []casbin2.Policy rolesChanged := false @@ -556,7 +556,7 @@ func (impl UserServiceImpl) createOrUpdateUserRolesForClusterEntity(roleFilter b return policiesToBeAdded, rolesChanged, nil } -func (impl UserServiceImpl) mergeRoleFilter(oldR []bean.RoleFilter, newR []bean.RoleFilter) []bean.RoleFilter { +func (impl *UserServiceImpl) mergeRoleFilter(oldR []bean.RoleFilter, newR []bean.RoleFilter) []bean.RoleFilter { var roleFilters []bean.RoleFilter keysMap := make(map[string]bool) for _, role := range oldR { @@ -599,7 +599,7 @@ func (impl UserServiceImpl) mergeRoleFilter(oldR []bean.RoleFilter, newR []bean. return roleFilters } -func (impl UserServiceImpl) mergeGroups(oldGroups []string, newGroups []string) []string { +func (impl *UserServiceImpl) mergeGroups(oldGroups []string, newGroups []string) []string { var groups []string keysMap := make(map[string]bool) for _, group := range oldGroups { @@ -616,7 +616,7 @@ func (impl UserServiceImpl) mergeGroups(oldGroups []string, newGroups []string) return groups } -func (impl UserServiceImpl) UpdateUser(userInfo *bean.UserInfo, token string, managerAuth func(resource, token string, object string) bool) (*bean.UserInfo, bool, bool, []string, error) { +func (impl *UserServiceImpl) UpdateUser(userInfo *bean.UserInfo, token string, managerAuth func(resource, token string, object string) bool) (*bean.UserInfo, bool, bool, []string, error) { //validating if action user is not admin and trying to update user who has super admin polices, return 403 isUserSuperAdmin, err := impl.IsSuperAdmin(int(userInfo.Id)) if err != nil { @@ -805,7 +805,7 @@ func (impl UserServiceImpl) UpdateUser(userInfo *bean.UserInfo, token string, ma return userInfo, rolesChanged, groupsModified, restrictedGroups, nil } -func (impl UserServiceImpl) GetById(id int32) (*bean.UserInfo, error) { +func (impl *UserServiceImpl) GetById(id int32) (*bean.UserInfo, error) { model, err := impl.userRepository.GetById(id) if err != nil { impl.logger.Errorw("error while fetching user from db", "error", err) @@ -832,7 +832,7 @@ func (impl UserServiceImpl) GetById(id int32) (*bean.UserInfo, error) { return response, nil } -func (impl UserServiceImpl) getUserMetadata(model *repository2.UserModel) (bool, []bean.RoleFilter, []string) { +func (impl *UserServiceImpl) getUserMetadata(model *repository2.UserModel) (bool, []bean.RoleFilter, []string) { roles, err := impl.userAuthRepository.GetRolesByUserId(model.Id) if err != nil { impl.logger.Debugw("No Roles Found for user", "id", model.Id) @@ -953,7 +953,7 @@ func (impl UserServiceImpl) getUserMetadata(model *repository2.UserModel) (bool, } // GetAll excluding API token user -func (impl UserServiceImpl) GetAll() ([]bean.UserInfo, error) { +func (impl *UserServiceImpl) GetAll() ([]bean.UserInfo, error) { model, err := impl.userRepository.GetAllExcludingApiTokenUser() if err != nil { impl.logger.Errorw("error while fetching user from db", "error", err) @@ -974,7 +974,7 @@ func (impl UserServiceImpl) GetAll() ([]bean.UserInfo, error) { return response, nil } -func (impl UserServiceImpl) GetAllDetailedUsers() ([]bean.UserInfo, error) { +func (impl *UserServiceImpl) GetAllDetailedUsers() ([]bean.UserInfo, error) { models, err := impl.userRepository.GetAllExcludingApiTokenUser() if err != nil { impl.logger.Errorw("error while fetching user from db", "error", err) @@ -1005,7 +1005,7 @@ func (impl UserServiceImpl) GetAllDetailedUsers() ([]bean.UserInfo, error) { return response, nil } -func (impl UserServiceImpl) UserExists(emailId string) bool { +func (impl *UserServiceImpl) UserExists(emailId string) bool { model, err := impl.userRepository.FetchActiveUserByEmail(emailId) if err != nil { impl.logger.Errorw("error while fetching user from db", "error", err) @@ -1018,7 +1018,7 @@ func (impl UserServiceImpl) UserExists(emailId string) bool { return true } } -func (impl UserServiceImpl) SaveLoginAudit(emailId, clientIp string, id int32) { +func (impl *UserServiceImpl) SaveLoginAudit(emailId, clientIp string, id int32) { if emailId != "" && id <= 0 { user, err := impl.GetUserByEmail(emailId) @@ -1042,7 +1042,7 @@ func (impl UserServiceImpl) SaveLoginAudit(emailId, clientIp string, id int32) { } } -func (impl UserServiceImpl) GetUserByEmail(emailId string) (*bean.UserInfo, error) { +func (impl *UserServiceImpl) GetUserByEmail(emailId string) (*bean.UserInfo, error) { model, err := impl.userRepository.FetchActiveUserByEmail(emailId) if err != nil { impl.logger.Errorw("error while fetching user from db", "error", err) @@ -1079,7 +1079,7 @@ func (impl UserServiceImpl) GetUserByEmail(emailId string) (*bean.UserInfo, erro return response, nil } -func (impl UserServiceImpl) GetLoggedInUser(r *http.Request) (int32, error) { +func (impl *UserServiceImpl) GetLoggedInUser(r *http.Request) (int32, error) { _, span := otel.Tracer("userService").Start(r.Context(), "GetLoggedInUser") defer span.End() token := "" @@ -1096,7 +1096,7 @@ func (impl UserServiceImpl) GetLoggedInUser(r *http.Request) (int32, error) { return userId, err } -func (impl UserServiceImpl) GetUserByToken(context context.Context, token string) (int32, string, error) { +func (impl *UserServiceImpl) GetUserByToken(context context.Context, token string) (int32, string, error) { _, span := otel.Tracer("userService").Start(context, "GetUserByToken") email, err := impl.GetEmailFromToken(token) span.End() @@ -1116,7 +1116,7 @@ func (impl UserServiceImpl) GetUserByToken(context context.Context, token string return userInfo.Id, userInfo.UserType, nil } -func (impl UserServiceImpl) GetEmailFromToken(token string) (string, error) { +func (impl *UserServiceImpl) GetEmailFromToken(token string) (string, error) { if token == "" { impl.logger.Infow("no token provided") err := &util.ApiError{ @@ -1159,7 +1159,7 @@ func (impl UserServiceImpl) GetEmailFromToken(token string) (string, error) { return email, nil } -func (impl UserServiceImpl) GetByIds(ids []int32) ([]bean.UserInfo, error) { +func (impl *UserServiceImpl) GetByIds(ids []int32) ([]bean.UserInfo, error) { var beans []bean.UserInfo models, err := impl.userRepository.GetByIds(ids) if err != nil && err != pg.ErrNoRows { @@ -1174,7 +1174,7 @@ func (impl UserServiceImpl) GetByIds(ids []int32) ([]bean.UserInfo, error) { return beans, nil } -func (impl UserServiceImpl) DeleteUser(bean *bean.UserInfo) (bool, error) { +func (impl *UserServiceImpl) DeleteUser(bean *bean.UserInfo) (bool, error) { dbConnection := impl.roleGroupRepository.GetConnection() tx, err := dbConnection.Begin() @@ -1228,7 +1228,7 @@ func (impl UserServiceImpl) DeleteUser(bean *bean.UserInfo) (bool, error) { return true, nil } -func (impl UserServiceImpl) CheckUserRoles(id int32) ([]string, error) { +func (impl *UserServiceImpl) CheckUserRoles(id int32) ([]string, error) { model, err := impl.userRepository.GetByIdIncludeDeleted(id) if err != nil { impl.logger.Errorw("error while fetching user from db", "error", err) @@ -1244,7 +1244,7 @@ func (impl UserServiceImpl) CheckUserRoles(id int32) ([]string, error) { return groups, nil } -func (impl UserServiceImpl) SyncOrchestratorToCasbin() (bool, error) { +func (impl *UserServiceImpl) SyncOrchestratorToCasbin() (bool, error) { roles, err := impl.userAuthRepository.GetAllRole() if err != nil { impl.logger.Errorw("error while fetching roles from db", "error", err) @@ -1274,7 +1274,7 @@ func (impl UserServiceImpl) SyncOrchestratorToCasbin() (bool, error) { return true, nil } -func (impl UserServiceImpl) IsSuperAdmin(userId int) (bool, error) { +func (impl *UserServiceImpl) IsSuperAdmin(userId int) (bool, error) { //validating if action user is not admin and trying to update user who has super admin polices, return 403 isSuperAdmin := false userCasbinRoles, err := impl.CheckUserRoles(int32(userId)) @@ -1291,7 +1291,7 @@ func (impl UserServiceImpl) IsSuperAdmin(userId int) (bool, error) { return isSuperAdmin, nil } -func (impl UserServiceImpl) GetByIdIncludeDeleted(id int32) (*bean.UserInfo, error) { +func (impl *UserServiceImpl) GetByIdIncludeDeleted(id int32) (*bean.UserInfo, error) { model, err := impl.userRepository.GetByIdIncludeDeleted(id) if err != nil { impl.logger.Errorw("error while fetching user from db", "error", err) @@ -1304,7 +1304,7 @@ func (impl UserServiceImpl) GetByIdIncludeDeleted(id int32) (*bean.UserInfo, err return response, nil } -func (impl UserServiceImpl) UpdateTriggerPolicyForTerminalAccess() (err error) { +func (impl *UserServiceImpl) UpdateTriggerPolicyForTerminalAccess() (err error) { err = impl.userAuthRepository.UpdateTriggerPolicyForTerminalAccess() if err != nil { impl.logger.Errorw("error in updating policy for terminal access to trigger role", "err", err) @@ -1313,7 +1313,7 @@ func (impl UserServiceImpl) UpdateTriggerPolicyForTerminalAccess() (err error) { return nil } -func (impl UserServiceImpl) saveUserAudit(r *http.Request, userId int32) { +func (impl *UserServiceImpl) saveUserAudit(r *http.Request, userId int32) { clientIp := util2.GetClientIP(r) userAudit := &UserAudit{ UserId: userId, @@ -1323,7 +1323,7 @@ func (impl UserServiceImpl) saveUserAudit(r *http.Request, userId int32) { impl.userAuditService.Save(userAudit) } -func (impl UserServiceImpl) checkGroupAuth(groupName string, token string, managerAuth func(resource, token string, object string) bool, isActionUserSuperAdmin bool) bool { +func (impl *UserServiceImpl) checkGroupAuth(groupName string, token string, managerAuth func(resource, token string, object string) bool, isActionUserSuperAdmin bool) bool { //check permission for group which is going to add/eliminate roles, err := impl.roleGroupRepository.GetRolesByGroupCasbinName(groupName) if err != nil && err != pg.ErrNoRows { @@ -1353,7 +1353,7 @@ func (impl UserServiceImpl) checkGroupAuth(groupName string, token string, manag return hasAccessToGroup } -func (impl UserServiceImpl) GetRoleFiltersByGroupNames(groupNames []string) ([]bean.RoleFilter, error) { +func (impl *UserServiceImpl) GetRoleFiltersByGroupNames(groupNames []string) ([]bean.RoleFilter, error) { roles, err := impl.roleGroupRepository.GetRolesByGroupNames(groupNames) if err != nil && err != pg.ErrNoRows { impl.logger.Errorw("error in getting roles by group names", "err", err) diff --git a/pkg/user/mocks/UserService.go b/pkg/user/mocks/UserService.go new file mode 100644 index 00000000000..7ebaa91843b --- /dev/null +++ b/pkg/user/mocks/UserService.go @@ -0,0 +1,321 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: pkg/user/UserService.go + +// Package mock_user is a generated GoMock package. +package mock_user + +import ( + context "context" + http "net/http" + reflect "reflect" + + bean "github.com/devtron-labs/devtron/api/bean" + gomock "github.com/golang/mock/gomock" +) + +// MockUserService is a mock of UserService interface. +type MockUserService struct { + ctrl *gomock.Controller + recorder *MockUserServiceMockRecorder +} + +// MockUserServiceMockRecorder is the mock recorder for MockUserService. +type MockUserServiceMockRecorder struct { + mock *MockUserService +} + +// NewMockUserService creates a new mock instance. +func NewMockUserService(ctrl *gomock.Controller) *MockUserService { + mock := &MockUserService{ctrl: ctrl} + mock.recorder = &MockUserServiceMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockUserService) EXPECT() *MockUserServiceMockRecorder { + return m.recorder +} + +// CheckUserRoles mocks base method. +func (m *MockUserService) CheckUserRoles(id int32) ([]string, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "CheckUserRoles", id) + ret0, _ := ret[0].([]string) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// CheckUserRoles indicates an expected call of CheckUserRoles. +func (mr *MockUserServiceMockRecorder) CheckUserRoles(id interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CheckUserRoles", reflect.TypeOf((*MockUserService)(nil).CheckUserRoles), id) +} + +// CreateUser mocks base method. +func (m *MockUserService) CreateUser(userInfo *bean.UserInfo, token string, managerAuth func(string, string, string) bool) ([]*bean.UserInfo, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "CreateUser", userInfo, token, managerAuth) + ret0, _ := ret[0].([]*bean.UserInfo) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// CreateUser indicates an expected call of CreateUser. +func (mr *MockUserServiceMockRecorder) CreateUser(userInfo, token, managerAuth interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateUser", reflect.TypeOf((*MockUserService)(nil).CreateUser), userInfo, token, managerAuth) +} + +// DeleteUser mocks base method. +func (m *MockUserService) DeleteUser(userInfo *bean.UserInfo) (bool, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "DeleteUser", userInfo) + ret0, _ := ret[0].(bool) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// DeleteUser indicates an expected call of DeleteUser. +func (mr *MockUserServiceMockRecorder) DeleteUser(userInfo interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteUser", reflect.TypeOf((*MockUserService)(nil).DeleteUser), userInfo) +} + +// GetAll mocks base method. +func (m *MockUserService) GetAll() ([]bean.UserInfo, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetAll") + ret0, _ := ret[0].([]bean.UserInfo) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetAll indicates an expected call of GetAll. +func (mr *MockUserServiceMockRecorder) GetAll() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAll", reflect.TypeOf((*MockUserService)(nil).GetAll)) +} + +// GetAllDetailedUsers mocks base method. +func (m *MockUserService) GetAllDetailedUsers() ([]bean.UserInfo, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetAllDetailedUsers") + ret0, _ := ret[0].([]bean.UserInfo) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetAllDetailedUsers indicates an expected call of GetAllDetailedUsers. +func (mr *MockUserServiceMockRecorder) GetAllDetailedUsers() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAllDetailedUsers", reflect.TypeOf((*MockUserService)(nil).GetAllDetailedUsers)) +} + +// GetById mocks base method. +func (m *MockUserService) GetById(id int32) (*bean.UserInfo, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetById", id) + ret0, _ := ret[0].(*bean.UserInfo) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetById indicates an expected call of GetById. +func (mr *MockUserServiceMockRecorder) GetById(id interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetById", reflect.TypeOf((*MockUserService)(nil).GetById), id) +} + +// GetByIdIncludeDeleted mocks base method. +func (m *MockUserService) GetByIdIncludeDeleted(id int32) (*bean.UserInfo, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetByIdIncludeDeleted", id) + ret0, _ := ret[0].(*bean.UserInfo) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetByIdIncludeDeleted indicates an expected call of GetByIdIncludeDeleted. +func (mr *MockUserServiceMockRecorder) GetByIdIncludeDeleted(id interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByIdIncludeDeleted", reflect.TypeOf((*MockUserService)(nil).GetByIdIncludeDeleted), id) +} + +// GetByIds mocks base method. +func (m *MockUserService) GetByIds(ids []int32) ([]bean.UserInfo, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetByIds", ids) + ret0, _ := ret[0].([]bean.UserInfo) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetByIds indicates an expected call of GetByIds. +func (mr *MockUserServiceMockRecorder) GetByIds(ids interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByIds", reflect.TypeOf((*MockUserService)(nil).GetByIds), ids) +} + +// GetEmailFromToken mocks base method. +func (m *MockUserService) GetEmailFromToken(token string) (string, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetEmailFromToken", token) + ret0, _ := ret[0].(string) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetEmailFromToken indicates an expected call of GetEmailFromToken. +func (mr *MockUserServiceMockRecorder) GetEmailFromToken(token interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetEmailFromToken", reflect.TypeOf((*MockUserService)(nil).GetEmailFromToken), token) +} + +// GetLoggedInUser mocks base method. +func (m *MockUserService) GetLoggedInUser(r *http.Request) (int32, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetLoggedInUser", r) + ret0, _ := ret[0].(int32) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetLoggedInUser indicates an expected call of GetLoggedInUser. +func (mr *MockUserServiceMockRecorder) GetLoggedInUser(r interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetLoggedInUser", reflect.TypeOf((*MockUserService)(nil).GetLoggedInUser), r) +} + +// GetRoleFiltersByGroupNames mocks base method. +func (m *MockUserService) GetRoleFiltersByGroupNames(groupNames []string) ([]bean.RoleFilter, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetRoleFiltersByGroupNames", groupNames) + ret0, _ := ret[0].([]bean.RoleFilter) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetRoleFiltersByGroupNames indicates an expected call of GetRoleFiltersByGroupNames. +func (mr *MockUserServiceMockRecorder) GetRoleFiltersByGroupNames(groupNames interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRoleFiltersByGroupNames", reflect.TypeOf((*MockUserService)(nil).GetRoleFiltersByGroupNames), groupNames) +} + +// GetUserByToken mocks base method. +func (m *MockUserService) GetUserByToken(context context.Context, token string) (int32, string, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetUserByToken", context, token) + ret0, _ := ret[0].(int32) + ret1, _ := ret[1].(string) + ret2, _ := ret[2].(error) + return ret0, ret1, ret2 +} + +// GetUserByToken indicates an expected call of GetUserByToken. +func (mr *MockUserServiceMockRecorder) GetUserByToken(context, token interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUserByToken", reflect.TypeOf((*MockUserService)(nil).GetUserByToken), context, token) +} + +// IsSuperAdmin mocks base method. +func (m *MockUserService) IsSuperAdmin(userId int) (bool, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "IsSuperAdmin", userId) + ret0, _ := ret[0].(bool) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// IsSuperAdmin indicates an expected call of IsSuperAdmin. +func (mr *MockUserServiceMockRecorder) IsSuperAdmin(userId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsSuperAdmin", reflect.TypeOf((*MockUserService)(nil).IsSuperAdmin), userId) +} + +// SaveLoginAudit mocks base method. +func (m *MockUserService) SaveLoginAudit(emailId, clientIp string, id int32) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SaveLoginAudit", emailId, clientIp, id) +} + +// SaveLoginAudit indicates an expected call of SaveLoginAudit. +func (mr *MockUserServiceMockRecorder) SaveLoginAudit(emailId, clientIp, id interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SaveLoginAudit", reflect.TypeOf((*MockUserService)(nil).SaveLoginAudit), emailId, clientIp, id) +} + +// SelfRegisterUserIfNotExists mocks base method. +func (m *MockUserService) SelfRegisterUserIfNotExists(userInfo *bean.UserInfo) ([]*bean.UserInfo, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "SelfRegisterUserIfNotExists", userInfo) + ret0, _ := ret[0].([]*bean.UserInfo) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// SelfRegisterUserIfNotExists indicates an expected call of SelfRegisterUserIfNotExists. +func (mr *MockUserServiceMockRecorder) SelfRegisterUserIfNotExists(userInfo interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SelfRegisterUserIfNotExists", reflect.TypeOf((*MockUserService)(nil).SelfRegisterUserIfNotExists), userInfo) +} + +// SyncOrchestratorToCasbin mocks base method. +func (m *MockUserService) SyncOrchestratorToCasbin() (bool, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "SyncOrchestratorToCasbin") + ret0, _ := ret[0].(bool) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// SyncOrchestratorToCasbin indicates an expected call of SyncOrchestratorToCasbin. +func (mr *MockUserServiceMockRecorder) SyncOrchestratorToCasbin() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SyncOrchestratorToCasbin", reflect.TypeOf((*MockUserService)(nil).SyncOrchestratorToCasbin)) +} + +// UpdateTriggerPolicyForTerminalAccess mocks base method. +func (m *MockUserService) UpdateTriggerPolicyForTerminalAccess() error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "UpdateTriggerPolicyForTerminalAccess") + ret0, _ := ret[0].(error) + return ret0 +} + +// UpdateTriggerPolicyForTerminalAccess indicates an expected call of UpdateTriggerPolicyForTerminalAccess. +func (mr *MockUserServiceMockRecorder) UpdateTriggerPolicyForTerminalAccess() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateTriggerPolicyForTerminalAccess", reflect.TypeOf((*MockUserService)(nil).UpdateTriggerPolicyForTerminalAccess)) +} + +// UpdateUser mocks base method. +func (m *MockUserService) UpdateUser(userInfo *bean.UserInfo, token string, managerAuth func(string, string, string) bool) (*bean.UserInfo, bool, bool, []string, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "UpdateUser", userInfo, token, managerAuth) + ret0, _ := ret[0].(*bean.UserInfo) + ret1, _ := ret[1].(bool) + ret2, _ := ret[2].(bool) + ret3, _ := ret[3].([]string) + ret4, _ := ret[4].(error) + return ret0, ret1, ret2, ret3, ret4 +} + +// UpdateUser indicates an expected call of UpdateUser. +func (mr *MockUserServiceMockRecorder) UpdateUser(userInfo, token, managerAuth interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateUser", reflect.TypeOf((*MockUserService)(nil).UpdateUser), userInfo, token, managerAuth) +} + +// UserExists mocks base method. +func (m *MockUserService) UserExists(emailId string) bool { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "UserExists", emailId) + ret0, _ := ret[0].(bool) + return ret0 +} + +// UserExists indicates an expected call of UserExists. +func (mr *MockUserServiceMockRecorder) UserExists(emailId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UserExists", reflect.TypeOf((*MockUserService)(nil).UserExists), emailId) +} diff --git a/pkg/user/mocks/casbin/rbac.go b/pkg/user/mocks/casbin/rbac.go new file mode 100644 index 00000000000..aa8b77a6249 --- /dev/null +++ b/pkg/user/mocks/casbin/rbac.go @@ -0,0 +1,144 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: pkg/user/casbin/rbac.go + +// Package mock_casbin is a generated GoMock package. +package mock_casbin + +import ( + reflect "reflect" + + gomock "github.com/golang/mock/gomock" +) + +// MockEnforcer is a mock of Enforcer interface. +type MockEnforcer struct { + ctrl *gomock.Controller + recorder *MockEnforcerMockRecorder +} + +// MockEnforcerMockRecorder is the mock recorder for MockEnforcer. +type MockEnforcerMockRecorder struct { + mock *MockEnforcer +} + +// NewMockEnforcer creates a new mock instance. +func NewMockEnforcer(ctrl *gomock.Controller) *MockEnforcer { + mock := &MockEnforcer{ctrl: ctrl} + mock.recorder = &MockEnforcerMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockEnforcer) EXPECT() *MockEnforcerMockRecorder { + return m.recorder +} + +// Enforce mocks base method. +func (m *MockEnforcer) Enforce(emailId, resource, action, resourceItem string) bool { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Enforce", emailId, resource, action, resourceItem) + ret0, _ := ret[0].(bool) + return ret0 +} + +// Enforce indicates an expected call of Enforce. +func (mr *MockEnforcerMockRecorder) Enforce(emailId, resource, action, resourceItem interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Enforce", reflect.TypeOf((*MockEnforcer)(nil).Enforce), emailId, resource, action, resourceItem) +} + +// EnforceByEmail mocks base method. +func (m *MockEnforcer) EnforceByEmail(emailId, resource, action, resourceItem string) bool { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "EnforceByEmail", emailId, resource, action, resourceItem) + ret0, _ := ret[0].(bool) + return ret0 +} + +// EnforceByEmail indicates an expected call of EnforceByEmail. +func (mr *MockEnforcerMockRecorder) EnforceByEmail(emailId, resource, action, resourceItem interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EnforceByEmail", reflect.TypeOf((*MockEnforcer)(nil).EnforceByEmail), emailId, resource, action, resourceItem) +} + +// EnforceByEmailInBatch mocks base method. +func (m *MockEnforcer) EnforceByEmailInBatch(emailId, resource, action string, vals []string) map[string]bool { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "EnforceByEmailInBatch", emailId, resource, action, vals) + ret0, _ := ret[0].(map[string]bool) + return ret0 +} + +// EnforceByEmailInBatch indicates an expected call of EnforceByEmailInBatch. +func (mr *MockEnforcerMockRecorder) EnforceByEmailInBatch(emailId, resource, action, vals interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EnforceByEmailInBatch", reflect.TypeOf((*MockEnforcer)(nil).EnforceByEmailInBatch), emailId, resource, action, vals) +} + +// EnforceErr mocks base method. +func (m *MockEnforcer) EnforceErr(emailId, resource, action, resourceItem string) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "EnforceErr", emailId, resource, action, resourceItem) + ret0, _ := ret[0].(error) + return ret0 +} + +// EnforceErr indicates an expected call of EnforceErr. +func (mr *MockEnforcerMockRecorder) EnforceErr(emailId, resource, action, resourceItem interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EnforceErr", reflect.TypeOf((*MockEnforcer)(nil).EnforceErr), emailId, resource, action, resourceItem) +} + +// GetCacheDump mocks base method. +func (m *MockEnforcer) GetCacheDump() string { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetCacheDump") + ret0, _ := ret[0].(string) + return ret0 +} + +// GetCacheDump indicates an expected call of GetCacheDump. +func (mr *MockEnforcerMockRecorder) GetCacheDump() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCacheDump", reflect.TypeOf((*MockEnforcer)(nil).GetCacheDump)) +} + +// InvalidateCache mocks base method. +func (m *MockEnforcer) InvalidateCache(emailId string) bool { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "InvalidateCache", emailId) + ret0, _ := ret[0].(bool) + return ret0 +} + +// InvalidateCache indicates an expected call of InvalidateCache. +func (mr *MockEnforcerMockRecorder) InvalidateCache(emailId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InvalidateCache", reflect.TypeOf((*MockEnforcer)(nil).InvalidateCache), emailId) +} + +// InvalidateCompleteCache mocks base method. +func (m *MockEnforcer) InvalidateCompleteCache() { + m.ctrl.T.Helper() + m.ctrl.Call(m, "InvalidateCompleteCache") +} + +// InvalidateCompleteCache indicates an expected call of InvalidateCompleteCache. +func (mr *MockEnforcerMockRecorder) InvalidateCompleteCache() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InvalidateCompleteCache", reflect.TypeOf((*MockEnforcer)(nil).InvalidateCompleteCache)) +} + +// ReloadPolicy mocks base method. +func (m *MockEnforcer) ReloadPolicy() error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ReloadPolicy") + ret0, _ := ret[0].(error) + return ret0 +} + +// ReloadPolicy indicates an expected call of ReloadPolicy. +func (mr *MockEnforcerMockRecorder) ReloadPolicy() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReloadPolicy", reflect.TypeOf((*MockEnforcer)(nil).ReloadPolicy)) +} diff --git a/util/mocks/rbac/EnforcerUtil.go b/util/mocks/rbac/EnforcerUtil.go new file mode 100644 index 00000000000..344ba932542 --- /dev/null +++ b/util/mocks/rbac/EnforcerUtil.go @@ -0,0 +1,436 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: util/rbac/EnforcerUtil.go + +// Package mock_rbac is a generated GoMock package. +package mock_rbac + +import ( + reflect "reflect" + + application "github.com/devtron-labs/devtron/client/k8s/application" + pipelineConfig "github.com/devtron-labs/devtron/internal/sql/repository/pipelineConfig" + bean "github.com/devtron-labs/devtron/pkg/bean" + gomock "github.com/golang/mock/gomock" +) + +// MockEnforcerUtil is a mock of EnforcerUtil interface. +type MockEnforcerUtil struct { + ctrl *gomock.Controller + recorder *MockEnforcerUtilMockRecorder +} + +// MockEnforcerUtilMockRecorder is the mock recorder for MockEnforcerUtil. +type MockEnforcerUtilMockRecorder struct { + mock *MockEnforcerUtil +} + +// NewMockEnforcerUtil creates a new mock instance. +func NewMockEnforcerUtil(ctrl *gomock.Controller) *MockEnforcerUtil { + mock := &MockEnforcerUtil{ctrl: ctrl} + mock.recorder = &MockEnforcerUtilMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockEnforcerUtil) EXPECT() *MockEnforcerUtilMockRecorder { + return m.recorder +} + +// GetAllActiveTeamNames mocks base method. +func (m *MockEnforcerUtil) GetAllActiveTeamNames() ([]string, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetAllActiveTeamNames") + ret0, _ := ret[0].([]string) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetAllActiveTeamNames indicates an expected call of GetAllActiveTeamNames. +func (mr *MockEnforcerUtilMockRecorder) GetAllActiveTeamNames() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAllActiveTeamNames", reflect.TypeOf((*MockEnforcerUtil)(nil).GetAllActiveTeamNames)) +} + +// GetAppAndEnvObjectByDbPipeline mocks base method. +func (m *MockEnforcerUtil) GetAppAndEnvObjectByDbPipeline(cdPipelines []*pipelineConfig.Pipeline) map[int][]string { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetAppAndEnvObjectByDbPipeline", cdPipelines) + ret0, _ := ret[0].(map[int][]string) + return ret0 +} + +// GetAppAndEnvObjectByDbPipeline indicates an expected call of GetAppAndEnvObjectByDbPipeline. +func (mr *MockEnforcerUtilMockRecorder) GetAppAndEnvObjectByDbPipeline(cdPipelines interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAppAndEnvObjectByDbPipeline", reflect.TypeOf((*MockEnforcerUtil)(nil).GetAppAndEnvObjectByDbPipeline), cdPipelines) +} + +// GetAppAndEnvObjectByPipeline mocks base method. +func (m *MockEnforcerUtil) GetAppAndEnvObjectByPipeline(cdPipelines []*bean.CDPipelineConfigObject) map[int][]string { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetAppAndEnvObjectByPipeline", cdPipelines) + ret0, _ := ret[0].(map[int][]string) + return ret0 +} + +// GetAppAndEnvObjectByPipeline indicates an expected call of GetAppAndEnvObjectByPipeline. +func (mr *MockEnforcerUtilMockRecorder) GetAppAndEnvObjectByPipeline(cdPipelines interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAppAndEnvObjectByPipeline", reflect.TypeOf((*MockEnforcerUtil)(nil).GetAppAndEnvObjectByPipeline), cdPipelines) +} + +// GetAppAndEnvObjectByPipelineIds mocks base method. +func (m *MockEnforcerUtil) GetAppAndEnvObjectByPipelineIds(cdPipelineIds []int) map[int][]string { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetAppAndEnvObjectByPipelineIds", cdPipelineIds) + ret0, _ := ret[0].(map[int][]string) + return ret0 +} + +// GetAppAndEnvObjectByPipelineIds indicates an expected call of GetAppAndEnvObjectByPipelineIds. +func (mr *MockEnforcerUtilMockRecorder) GetAppAndEnvObjectByPipelineIds(cdPipelineIds interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAppAndEnvObjectByPipelineIds", reflect.TypeOf((*MockEnforcerUtil)(nil).GetAppAndEnvObjectByPipelineIds), cdPipelineIds) +} + +// GetAppObjectByCiPipelineIds mocks base method. +func (m *MockEnforcerUtil) GetAppObjectByCiPipelineIds(ciPipelineIds []int) map[int]string { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetAppObjectByCiPipelineIds", ciPipelineIds) + ret0, _ := ret[0].(map[int]string) + return ret0 +} + +// GetAppObjectByCiPipelineIds indicates an expected call of GetAppObjectByCiPipelineIds. +func (mr *MockEnforcerUtilMockRecorder) GetAppObjectByCiPipelineIds(ciPipelineIds interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAppObjectByCiPipelineIds", reflect.TypeOf((*MockEnforcerUtil)(nil).GetAppObjectByCiPipelineIds), ciPipelineIds) +} + +// GetAppRBACByAppIdAndPipelineId mocks base method. +func (m *MockEnforcerUtil) GetAppRBACByAppIdAndPipelineId(appId, pipelineId int) string { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetAppRBACByAppIdAndPipelineId", appId, pipelineId) + ret0, _ := ret[0].(string) + return ret0 +} + +// GetAppRBACByAppIdAndPipelineId indicates an expected call of GetAppRBACByAppIdAndPipelineId. +func (mr *MockEnforcerUtilMockRecorder) GetAppRBACByAppIdAndPipelineId(appId, pipelineId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAppRBACByAppIdAndPipelineId", reflect.TypeOf((*MockEnforcerUtil)(nil).GetAppRBACByAppIdAndPipelineId), appId, pipelineId) +} + +// GetAppRBACByAppNameAndEnvId mocks base method. +func (m *MockEnforcerUtil) GetAppRBACByAppNameAndEnvId(appName string, envId int) string { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetAppRBACByAppNameAndEnvId", appName, envId) + ret0, _ := ret[0].(string) + return ret0 +} + +// GetAppRBACByAppNameAndEnvId indicates an expected call of GetAppRBACByAppNameAndEnvId. +func (mr *MockEnforcerUtilMockRecorder) GetAppRBACByAppNameAndEnvId(appName, envId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAppRBACByAppNameAndEnvId", reflect.TypeOf((*MockEnforcerUtil)(nil).GetAppRBACByAppNameAndEnvId), appName, envId) +} + +// GetAppRBACName mocks base method. +func (m *MockEnforcerUtil) GetAppRBACName(appName string) string { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetAppRBACName", appName) + ret0, _ := ret[0].(string) + return ret0 +} + +// GetAppRBACName indicates an expected call of GetAppRBACName. +func (mr *MockEnforcerUtilMockRecorder) GetAppRBACName(appName interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAppRBACName", reflect.TypeOf((*MockEnforcerUtil)(nil).GetAppRBACName), appName) +} + +// GetAppRBACNameByAppId mocks base method. +func (m *MockEnforcerUtil) GetAppRBACNameByAppId(appId int) string { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetAppRBACNameByAppId", appId) + ret0, _ := ret[0].(string) + return ret0 +} + +// GetAppRBACNameByAppId indicates an expected call of GetAppRBACNameByAppId. +func (mr *MockEnforcerUtilMockRecorder) GetAppRBACNameByAppId(appId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAppRBACNameByAppId", reflect.TypeOf((*MockEnforcerUtil)(nil).GetAppRBACNameByAppId), appId) +} + +// GetAppRBACNameByTeamIdAndAppId mocks base method. +func (m *MockEnforcerUtil) GetAppRBACNameByTeamIdAndAppId(teamId, appId int) string { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetAppRBACNameByTeamIdAndAppId", teamId, appId) + ret0, _ := ret[0].(string) + return ret0 +} + +// GetAppRBACNameByTeamIdAndAppId indicates an expected call of GetAppRBACNameByTeamIdAndAppId. +func (mr *MockEnforcerUtilMockRecorder) GetAppRBACNameByTeamIdAndAppId(teamId, appId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAppRBACNameByTeamIdAndAppId", reflect.TypeOf((*MockEnforcerUtil)(nil).GetAppRBACNameByTeamIdAndAppId), teamId, appId) +} + +// GetEnvRBACArrayByAppId mocks base method. +func (m *MockEnforcerUtil) GetEnvRBACArrayByAppId(appId int) []string { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetEnvRBACArrayByAppId", appId) + ret0, _ := ret[0].([]string) + return ret0 +} + +// GetEnvRBACArrayByAppId indicates an expected call of GetEnvRBACArrayByAppId. +func (mr *MockEnforcerUtilMockRecorder) GetEnvRBACArrayByAppId(appId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetEnvRBACArrayByAppId", reflect.TypeOf((*MockEnforcerUtil)(nil).GetEnvRBACArrayByAppId), appId) +} + +// GetEnvRBACNameByAppId mocks base method. +func (m *MockEnforcerUtil) GetEnvRBACNameByAppId(appId, envId int) string { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetEnvRBACNameByAppId", appId, envId) + ret0, _ := ret[0].(string) + return ret0 +} + +// GetEnvRBACNameByAppId indicates an expected call of GetEnvRBACNameByAppId. +func (mr *MockEnforcerUtilMockRecorder) GetEnvRBACNameByAppId(appId, envId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetEnvRBACNameByAppId", reflect.TypeOf((*MockEnforcerUtil)(nil).GetEnvRBACNameByAppId), appId, envId) +} + +// GetEnvRBACNameByCdPipelineIdAndEnvId mocks base method. +func (m *MockEnforcerUtil) GetEnvRBACNameByCdPipelineIdAndEnvId(cdPipelineId int) string { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetEnvRBACNameByCdPipelineIdAndEnvId", cdPipelineId) + ret0, _ := ret[0].(string) + return ret0 +} + +// GetEnvRBACNameByCdPipelineIdAndEnvId indicates an expected call of GetEnvRBACNameByCdPipelineIdAndEnvId. +func (mr *MockEnforcerUtilMockRecorder) GetEnvRBACNameByCdPipelineIdAndEnvId(cdPipelineId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetEnvRBACNameByCdPipelineIdAndEnvId", reflect.TypeOf((*MockEnforcerUtil)(nil).GetEnvRBACNameByCdPipelineIdAndEnvId), cdPipelineId) +} + +// GetEnvRBACNameByCiPipelineIdAndEnvId mocks base method. +func (m *MockEnforcerUtil) GetEnvRBACNameByCiPipelineIdAndEnvId(ciPipelineId, envId int) string { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetEnvRBACNameByCiPipelineIdAndEnvId", ciPipelineId, envId) + ret0, _ := ret[0].(string) + return ret0 +} + +// GetEnvRBACNameByCiPipelineIdAndEnvId indicates an expected call of GetEnvRBACNameByCiPipelineIdAndEnvId. +func (mr *MockEnforcerUtilMockRecorder) GetEnvRBACNameByCiPipelineIdAndEnvId(ciPipelineId, envId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetEnvRBACNameByCiPipelineIdAndEnvId", reflect.TypeOf((*MockEnforcerUtil)(nil).GetEnvRBACNameByCiPipelineIdAndEnvId), ciPipelineId, envId) +} + +// GetHelmObject mocks base method. +func (m *MockEnforcerUtil) GetHelmObject(appId, envId int) (string, string) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetHelmObject", appId, envId) + ret0, _ := ret[0].(string) + ret1, _ := ret[1].(string) + return ret0, ret1 +} + +// GetHelmObject indicates an expected call of GetHelmObject. +func (mr *MockEnforcerUtilMockRecorder) GetHelmObject(appId, envId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetHelmObject", reflect.TypeOf((*MockEnforcerUtil)(nil).GetHelmObject), appId, envId) +} + +// GetHelmObjectByAppNameAndEnvId mocks base method. +func (m *MockEnforcerUtil) GetHelmObjectByAppNameAndEnvId(appName string, envId int) (string, string) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetHelmObjectByAppNameAndEnvId", appName, envId) + ret0, _ := ret[0].(string) + ret1, _ := ret[1].(string) + return ret0, ret1 +} + +// GetHelmObjectByAppNameAndEnvId indicates an expected call of GetHelmObjectByAppNameAndEnvId. +func (mr *MockEnforcerUtilMockRecorder) GetHelmObjectByAppNameAndEnvId(appName, envId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetHelmObjectByAppNameAndEnvId", reflect.TypeOf((*MockEnforcerUtil)(nil).GetHelmObjectByAppNameAndEnvId), appName, envId) +} + +// GetHelmObjectByProjectIdAndEnvId mocks base method. +func (m *MockEnforcerUtil) GetHelmObjectByProjectIdAndEnvId(teamId, envId int) (string, string) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetHelmObjectByProjectIdAndEnvId", teamId, envId) + ret0, _ := ret[0].(string) + ret1, _ := ret[1].(string) + return ret0, ret1 +} + +// GetHelmObjectByProjectIdAndEnvId indicates an expected call of GetHelmObjectByProjectIdAndEnvId. +func (mr *MockEnforcerUtilMockRecorder) GetHelmObjectByProjectIdAndEnvId(teamId, envId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetHelmObjectByProjectIdAndEnvId", reflect.TypeOf((*MockEnforcerUtil)(nil).GetHelmObjectByProjectIdAndEnvId), teamId, envId) +} + +// GetProjectAdminRBACNameBYAppName mocks base method. +func (m *MockEnforcerUtil) GetProjectAdminRBACNameBYAppName(appName string) string { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetProjectAdminRBACNameBYAppName", appName) + ret0, _ := ret[0].(string) + return ret0 +} + +// GetProjectAdminRBACNameBYAppName indicates an expected call of GetProjectAdminRBACNameBYAppName. +func (mr *MockEnforcerUtilMockRecorder) GetProjectAdminRBACNameBYAppName(appName interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetProjectAdminRBACNameBYAppName", reflect.TypeOf((*MockEnforcerUtil)(nil).GetProjectAdminRBACNameBYAppName), appName) +} + +// GetRBACNameForClusterEntity mocks base method. +func (m *MockEnforcerUtil) GetRBACNameForClusterEntity(clusterName string, resourceIdentifier application.ResourceIdentifier) (string, string) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetRBACNameForClusterEntity", clusterName, resourceIdentifier) + ret0, _ := ret[0].(string) + ret1, _ := ret[1].(string) + return ret0, ret1 +} + +// GetRBACNameForClusterEntity indicates an expected call of GetRBACNameForClusterEntity. +func (mr *MockEnforcerUtilMockRecorder) GetRBACNameForClusterEntity(clusterName, resourceIdentifier interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRBACNameForClusterEntity", reflect.TypeOf((*MockEnforcerUtil)(nil).GetRBACNameForClusterEntity), clusterName, resourceIdentifier) +} + +// GetRbacObjectsByAppIds mocks base method. +func (m *MockEnforcerUtil) GetRbacObjectsByAppIds(appIds []int) map[int]string { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetRbacObjectsByAppIds", appIds) + ret0, _ := ret[0].(map[int]string) + return ret0 +} + +// GetRbacObjectsByAppIds indicates an expected call of GetRbacObjectsByAppIds. +func (mr *MockEnforcerUtilMockRecorder) GetRbacObjectsByAppIds(appIds interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRbacObjectsByAppIds", reflect.TypeOf((*MockEnforcerUtil)(nil).GetRbacObjectsByAppIds), appIds) +} + +// GetRbacObjectsForAllApps mocks base method. +func (m *MockEnforcerUtil) GetRbacObjectsForAllApps() map[int]string { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetRbacObjectsForAllApps") + ret0, _ := ret[0].(map[int]string) + return ret0 +} + +// GetRbacObjectsForAllApps indicates an expected call of GetRbacObjectsForAllApps. +func (mr *MockEnforcerUtilMockRecorder) GetRbacObjectsForAllApps() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRbacObjectsForAllApps", reflect.TypeOf((*MockEnforcerUtil)(nil).GetRbacObjectsForAllApps)) +} + +// GetRbacObjectsForAllAppsAndEnvironments mocks base method. +func (m *MockEnforcerUtil) GetRbacObjectsForAllAppsAndEnvironments() (map[int]string, map[string]string) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetRbacObjectsForAllAppsAndEnvironments") + ret0, _ := ret[0].(map[int]string) + ret1, _ := ret[1].(map[string]string) + return ret0, ret1 +} + +// GetRbacObjectsForAllAppsAndEnvironments indicates an expected call of GetRbacObjectsForAllAppsAndEnvironments. +func (mr *MockEnforcerUtilMockRecorder) GetRbacObjectsForAllAppsAndEnvironments() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRbacObjectsForAllAppsAndEnvironments", reflect.TypeOf((*MockEnforcerUtil)(nil).GetRbacObjectsForAllAppsAndEnvironments)) +} + +// GetRbacObjectsForAllAppsWithMatchingAppName mocks base method. +func (m *MockEnforcerUtil) GetRbacObjectsForAllAppsWithMatchingAppName(appNameMatch string) map[int]string { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetRbacObjectsForAllAppsWithMatchingAppName", appNameMatch) + ret0, _ := ret[0].(map[int]string) + return ret0 +} + +// GetRbacObjectsForAllAppsWithMatchingAppName indicates an expected call of GetRbacObjectsForAllAppsWithMatchingAppName. +func (mr *MockEnforcerUtilMockRecorder) GetRbacObjectsForAllAppsWithMatchingAppName(appNameMatch interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRbacObjectsForAllAppsWithMatchingAppName", reflect.TypeOf((*MockEnforcerUtil)(nil).GetRbacObjectsForAllAppsWithMatchingAppName), appNameMatch) +} + +// GetRbacObjectsForAllAppsWithTeamID mocks base method. +func (m *MockEnforcerUtil) GetRbacObjectsForAllAppsWithTeamID(teamID int) map[int]string { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetRbacObjectsForAllAppsWithTeamID", teamID) + ret0, _ := ret[0].(map[int]string) + return ret0 +} + +// GetRbacObjectsForAllAppsWithTeamID indicates an expected call of GetRbacObjectsForAllAppsWithTeamID. +func (mr *MockEnforcerUtilMockRecorder) GetRbacObjectsForAllAppsWithTeamID(teamID interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRbacObjectsForAllAppsWithTeamID", reflect.TypeOf((*MockEnforcerUtil)(nil).GetRbacObjectsForAllAppsWithTeamID), teamID) +} + +// GetTeamAndEnvironmentRbacObjectByCDPipelineId mocks base method. +func (m *MockEnforcerUtil) GetTeamAndEnvironmentRbacObjectByCDPipelineId(pipelineId int) (string, string) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetTeamAndEnvironmentRbacObjectByCDPipelineId", pipelineId) + ret0, _ := ret[0].(string) + ret1, _ := ret[1].(string) + return ret0, ret1 +} + +// GetTeamAndEnvironmentRbacObjectByCDPipelineId indicates an expected call of GetTeamAndEnvironmentRbacObjectByCDPipelineId. +func (mr *MockEnforcerUtilMockRecorder) GetTeamAndEnvironmentRbacObjectByCDPipelineId(pipelineId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTeamAndEnvironmentRbacObjectByCDPipelineId", reflect.TypeOf((*MockEnforcerUtil)(nil).GetTeamAndEnvironmentRbacObjectByCDPipelineId), pipelineId) +} + +// GetTeamEnvRBACNameByAppId mocks base method. +func (m *MockEnforcerUtil) GetTeamEnvRBACNameByAppId(appId, envId int) string { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetTeamEnvRBACNameByAppId", appId, envId) + ret0, _ := ret[0].(string) + return ret0 +} + +// GetTeamEnvRBACNameByAppId indicates an expected call of GetTeamEnvRBACNameByAppId. +func (mr *MockEnforcerUtilMockRecorder) GetTeamEnvRBACNameByAppId(appId, envId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTeamEnvRBACNameByAppId", reflect.TypeOf((*MockEnforcerUtil)(nil).GetTeamEnvRBACNameByAppId), appId, envId) +} + +// GetTeamRBACByCiPipelineId mocks base method. +func (m *MockEnforcerUtil) GetTeamRBACByCiPipelineId(pipelineId int) string { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetTeamRBACByCiPipelineId", pipelineId) + ret0, _ := ret[0].(string) + return ret0 +} + +// GetTeamRBACByCiPipelineId indicates an expected call of GetTeamRBACByCiPipelineId. +func (mr *MockEnforcerUtilMockRecorder) GetTeamRBACByCiPipelineId(pipelineId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTeamRBACByCiPipelineId", reflect.TypeOf((*MockEnforcerUtil)(nil).GetTeamRBACByCiPipelineId), pipelineId) +} + +// GetTeamRbacObjectByCiPipelineId mocks base method. +func (m *MockEnforcerUtil) GetTeamRbacObjectByCiPipelineId(ciPipelineId int) string { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetTeamRbacObjectByCiPipelineId", ciPipelineId) + ret0, _ := ret[0].(string) + return ret0 +} + +// GetTeamRbacObjectByCiPipelineId indicates an expected call of GetTeamRbacObjectByCiPipelineId. +func (mr *MockEnforcerUtilMockRecorder) GetTeamRbacObjectByCiPipelineId(ciPipelineId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTeamRbacObjectByCiPipelineId", reflect.TypeOf((*MockEnforcerUtil)(nil).GetTeamRbacObjectByCiPipelineId), ciPipelineId) +} From 54e96da00b223c4d873be6ca39ef3eb8c46bd7e7 Mon Sep 17 00:00:00 2001 From: Avdhesh Kumar Date: Mon, 24 Jul 2023 11:25:35 +0530 Subject: [PATCH 4/9] Allow source change only in customApp --- .../app/BuildPipelineRestHandler.go | 23 ++++++++----------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/api/restHandler/app/BuildPipelineRestHandler.go b/api/restHandler/app/BuildPipelineRestHandler.go index 970ef6535bc..b85ee7acf95 100644 --- a/api/restHandler/app/BuildPipelineRestHandler.go +++ b/api/restHandler/app/BuildPipelineRestHandler.go @@ -251,11 +251,6 @@ func (handler PipelineConfigRestHandlerImpl) parseBranchChangeRequest(w http.Res } func (handler PipelineConfigRestHandlerImpl) authorizeSourceChangeRequest(w http.ResponseWriter, userId int32, patchRequest *bean.CiPipeline, token string) error { - isSuperAdmin, err := handler.userAuthService.IsSuperAdmin(int(userId)) - if err != nil { - common.WriteJsonResp(w, err, "failed to check if user is super admin", http.StatusInternalServerError) - return err - } handler.Logger.Debugw("update request ", "req", patchRequest) app, err := handler.pipelineBuilder.GetApp(patchRequest.AppId) if err != nil { @@ -263,16 +258,18 @@ func (handler PipelineConfigRestHandlerImpl) authorizeSourceChangeRequest(w http return err } - var ok bool - if app.AppType == helper.Job { - ok = isSuperAdmin - } else { - resourceName := handler.enforcerUtil.GetAppRBACName(app.AppName) - ok = handler.enforcer.Enforce(token, casbin.ResourceApplications, casbin.ActionCreate, resourceName) + if app.AppType != helper.CustomApp { + err = fmt.Errorf("only custom apps supported") + common.WriteJsonResp(w, err, nil, http.StatusBadRequest) + return err } + resourceName := handler.enforcerUtil.GetAppRBACName(app.AppName) + ok := handler.enforcer.Enforce(token, casbin.ResourceApplications, casbin.ActionCreate, resourceName) + if !ok { - common.WriteJsonResp(w, fmt.Errorf("unauthorized user"), "Unauthorized User", http.StatusForbidden) - return fmt.Errorf("unauthorized user") + err = fmt.Errorf("unauthorized user") + common.WriteJsonResp(w, err, "Unauthorized User", http.StatusForbidden) + return err } patchRequest.Name = app.AppName err = handler.validator.Struct(patchRequest) From 80c74ac0b210a36010085ef6fdad2f70581b486e Mon Sep 17 00:00:00 2001 From: Avdhesh Kumar Date: Mon, 24 Jul 2023 12:15:30 +0530 Subject: [PATCH 5/9] Refactor tests --- .../app/BuildPipelineRestHandler_test.go | 47 ++----------------- 1 file changed, 5 insertions(+), 42 deletions(-) diff --git a/api/restHandler/app/BuildPipelineRestHandler_test.go b/api/restHandler/app/BuildPipelineRestHandler_test.go index 7d8d391cfed..a165b3faa23 100644 --- a/api/restHandler/app/BuildPipelineRestHandler_test.go +++ b/api/restHandler/app/BuildPipelineRestHandler_test.go @@ -74,23 +74,6 @@ func TestPipelineConfigRestHandlerImpl_PatchCiMaterialSource(t *testing.T) { }, expectedStatusCode: http.StatusBadRequest, }, - { - name: "when super admin check fails, it should return internal server error", - fields: fields{ - validator: validator.New(), - }, - body: "{\"appId\":4, \"id\": 5 ,\"ciMaterial\":[{\"gitMaterialId\":4,\"id\":5,\"source\":{\"type\":\"SOURCE_TYPE_BRANCH_FIXED\",\"value\":\"main3\",\"regex\":\"\"}}]}", - setup: func(fields2 *fields) { - ctrl := gomock.NewController(t) - fields2.pipelineBuilder = mock_pipeline.NewMockPipelineBuilder(ctrl) - fields2.enforcer = mock_casbin.NewMockEnforcer(ctrl) - fields2.enforcerUtil = mocks_rbac.NewMockEnforcerUtil(ctrl) - fields2.userAuthService = mock_user.NewMockUserService(ctrl) - fields2.userAuthService.EXPECT().GetLoggedInUser(gomock.Any()).Return(int32(1), nil).Times(1) - fields2.userAuthService.EXPECT().IsSuperAdmin(1).Return(false, fmt.Errorf("not a super admin")).Times(1) - }, - expectedStatusCode: http.StatusInternalServerError, - }, { name: "when app is not found for the given appId, it should return bad request", fields: fields{ @@ -105,7 +88,7 @@ func TestPipelineConfigRestHandlerImpl_PatchCiMaterialSource(t *testing.T) { fields2.enforcerUtil = mocks_rbac.NewMockEnforcerUtil(ctrl) fields2.userAuthService = mock_user.NewMockUserService(ctrl) fields2.userAuthService.EXPECT().GetLoggedInUser(gomock.Any()).Return(int32(1), nil).Times(1) - fields2.userAuthService.EXPECT().IsSuperAdmin(1).Return(true, nil).Times(1) + //fields2.userAuthService.EXPECT().IsSuperAdmin(1).Return(true, nil).Times(1) }, expectedStatusCode: http.StatusBadRequest, }, @@ -127,31 +110,11 @@ func TestPipelineConfigRestHandlerImpl_PatchCiMaterialSource(t *testing.T) { //fields2.enforcerUtil.EXPECT().GetAppRBACName("Super App") fields2.userAuthService = mock_user.NewMockUserService(ctrl) fields2.userAuthService.EXPECT().GetLoggedInUser(gomock.Any()).Return(int32(1), nil).Times(1) - fields2.userAuthService.EXPECT().IsSuperAdmin(1).Return(true, nil).Times(1) + //fields2.userAuthService.EXPECT().IsSuperAdmin(1).Return(true, nil).Times(1) }, expectedStatusCode: http.StatusBadRequest, }, - { - name: "when user is not a super admin, it should return forbidden", - fields: fields{ - validator: validator.New(), - }, - body: "{\"appId\":4, \"id\": 5 ,\"ciMaterial\":[{\"gitMaterialId\":4,\"id\":5,\"source\":{\"type\":\"SOURCE_TYPE_BRANCH_FIXED\",\"value\":\"main3\",\"regex\":\"\"}}]}", - setup: func(fields2 *fields) { - ctrl := gomock.NewController(t) - fields2.pipelineBuilder = mock_pipeline.NewMockPipelineBuilder(ctrl) - fields2.pipelineBuilder.EXPECT().GetApp(4).Return(&bean.CreateAppDTO{AppName: "Super App", Id: 4, AppType: helper.Job}, nil).Times(1) - fields2.enforcer = mock_casbin.NewMockEnforcer(ctrl) - fields2.enforcerUtil = mocks_rbac.NewMockEnforcerUtil(ctrl) - //fields2.enforcerUtil.EXPECT().GetAppRBACName("Super App") - fields2.userAuthService = mock_user.NewMockUserService(ctrl) - fields2.userAuthService.EXPECT().GetLoggedInUser(gomock.Any()).Return(int32(1), nil).Times(1) - fields2.userAuthService.EXPECT().IsSuperAdmin(1).Return(false, nil).Times(1) - - }, - expectedStatusCode: http.StatusForbidden, - }, { name: "when app is not jobtype and enforce fails, it should return forbidden", fields: fields{ @@ -169,7 +132,7 @@ func TestPipelineConfigRestHandlerImpl_PatchCiMaterialSource(t *testing.T) { fields2.enforcerUtil.EXPECT().GetAppRBACName("Super App") fields2.userAuthService = mock_user.NewMockUserService(ctrl) fields2.userAuthService.EXPECT().GetLoggedInUser(gomock.Any()).Return(int32(1), nil).Times(1) - fields2.userAuthService.EXPECT().IsSuperAdmin(1).Return(false, nil).Times(1) + //fields2.userAuthService.EXPECT().IsSuperAdmin(1).Return(false, nil).Times(1) }, expectedStatusCode: http.StatusForbidden, @@ -194,7 +157,7 @@ func TestPipelineConfigRestHandlerImpl_PatchCiMaterialSource(t *testing.T) { fields2.enforcerUtil.EXPECT().GetAppRBACName("Super App") fields2.userAuthService = mock_user.NewMockUserService(ctrl) fields2.userAuthService.EXPECT().GetLoggedInUser(gomock.Any()).Return(int32(1), nil).Times(1) - fields2.userAuthService.EXPECT().IsSuperAdmin(1).Return(false, nil).Times(1) + //fields2.userAuthService.EXPECT().IsSuperAdmin(1).Return(false, nil).Times(1) }, expectedStatusCode: http.StatusInternalServerError, @@ -219,7 +182,7 @@ func TestPipelineConfigRestHandlerImpl_PatchCiMaterialSource(t *testing.T) { fields2.enforcerUtil.EXPECT().GetAppRBACName("Super App") fields2.userAuthService = mock_user.NewMockUserService(ctrl) fields2.userAuthService.EXPECT().GetLoggedInUser(gomock.Any()).Return(int32(1), nil).Times(1) - fields2.userAuthService.EXPECT().IsSuperAdmin(1).Return(false, nil).Times(1) + //fields2.userAuthService.EXPECT().IsSuperAdmin(1).Return(false, nil).Times(1) }, expectedStatusCode: http.StatusOK, From 55df29e89f0a9ebcf4c808f82a2bc970a09543d4 Mon Sep 17 00:00:00 2001 From: Avdhesh Kumar Date: Mon, 24 Jul 2023 12:30:07 +0530 Subject: [PATCH 6/9] Add logs --- api/restHandler/app/BuildPipelineRestHandler.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/api/restHandler/app/BuildPipelineRestHandler.go b/api/restHandler/app/BuildPipelineRestHandler.go index b85ee7acf95..3ba1f322e37 100644 --- a/api/restHandler/app/BuildPipelineRestHandler.go +++ b/api/restHandler/app/BuildPipelineRestHandler.go @@ -284,10 +284,12 @@ func (handler PipelineConfigRestHandlerImpl) authorizeSourceChangeRequest(w http func (handler PipelineConfigRestHandlerImpl) PatchCiMaterialSource(w http.ResponseWriter, r *http.Request) { patchRequest, userId, err := handler.parseBranchChangeRequest(w, r) if err != nil { + handler.Logger.Errorw("Parse error, PatchCiMaterialSource", "err", err, "PatchCiMaterialSource", patchRequest) return } token := r.Header.Get("token") if err = handler.authorizeSourceChangeRequest(w, userId, patchRequest, token); err != nil { + handler.Logger.Errorw("Authorization error, PatchCiMaterialSource", "err", err, "PatchCiMaterialSource", patchRequest) return } createResp, err := handler.pipelineBuilder.PatchCiMaterialSource(patchRequest, userId) From 6f0be57352e867a8832ccbe85d79c091f178de4f Mon Sep 17 00:00:00 2001 From: Avdhesh Kumar Date: Tue, 25 Jul 2023 15:28:54 +0530 Subject: [PATCH 7/9] Refactor API --- .../app/BuildPipelineRestHandler.go | 24 ++- .../app/BuildPipelineRestHandler_test.go | 10 +- api/router/PipelineConfigRouter.go | 2 +- pkg/bean/app.go | 7 + pkg/pipeline/CiCdPipelineOrchestrator.go | 55 +++--- pkg/pipeline/CiCdPipelineOrchestrator_test.go | 169 ------------------ pkg/pipeline/ImageTaggingService.go | 4 +- pkg/pipeline/PipelineBuilder.go | 4 +- pkg/pipeline/PipelineStageService.go | 4 +- pkg/pipeline/PipelineStageServiceIT_test.go | 6 +- pkg/pipeline/WorkflowDagExecutor.go | 2 +- pkg/pipeline/mock_pipeline/PipelineBuilder.go | 4 +- 12 files changed, 69 insertions(+), 222 deletions(-) diff --git a/api/restHandler/app/BuildPipelineRestHandler.go b/api/restHandler/app/BuildPipelineRestHandler.go index 3ba1f322e37..c42740e426b 100644 --- a/api/restHandler/app/BuildPipelineRestHandler.go +++ b/api/restHandler/app/BuildPipelineRestHandler.go @@ -43,7 +43,7 @@ type DevtronAppBuildRestHandler interface { GetExternalCi(w http.ResponseWriter, r *http.Request) GetExternalCiById(w http.ResponseWriter, r *http.Request) PatchCiPipelines(w http.ResponseWriter, r *http.Request) - PatchCiMaterialSource(w http.ResponseWriter, r *http.Request) + PatchCiMaterialSourceWithAppIdAndEnvironmentId(w http.ResponseWriter, r *http.Request) TriggerCiPipeline(w http.ResponseWriter, r *http.Request) GetCiPipelineMin(w http.ResponseWriter, r *http.Request) GetCIPipelineById(w http.ResponseWriter, r *http.Request) @@ -231,47 +231,42 @@ func (handler PipelineConfigRestHandlerImpl) UpdateBranchCiPipelinesWithRegex(w common.WriteJsonResp(w, err, resp, http.StatusOK) } -func (handler PipelineConfigRestHandlerImpl) parseBranchChangeRequest(w http.ResponseWriter, r *http.Request) (*bean.CiPipeline, int32, error) { +func (handler PipelineConfigRestHandlerImpl) parseSourceChangeRequest(w http.ResponseWriter, r *http.Request) (*bean.CiMaterialPatchRequest, int32, error) { decoder := json.NewDecoder(r.Body) userId, err := handler.userAuthService.GetLoggedInUser(r) if userId == 0 || err != nil { common.WriteJsonResp(w, err, "Unauthorized User", http.StatusUnauthorized) return nil, 0, err } - - var patchRequest bean.CiPipeline + var patchRequest bean.CiMaterialPatchRequest err = decoder.Decode(&patchRequest) if err != nil { - handler.Logger.Errorw("request err, PatchCiPipelines", "err", err, "PatchCiPipelines", patchRequest) + handler.Logger.Errorw("request err, PatchCiPipeline", "err", err, "PatchCiPipeline", patchRequest) common.WriteJsonResp(w, err, nil, http.StatusBadRequest) return nil, 0, err } return &patchRequest, userId, nil } -func (handler PipelineConfigRestHandlerImpl) authorizeSourceChangeRequest(w http.ResponseWriter, userId int32, patchRequest *bean.CiPipeline, token string) error { +func (handler PipelineConfigRestHandlerImpl) authorizeCiSourceChangeRequest(w http.ResponseWriter, patchRequest *bean.CiMaterialPatchRequest, token string) error { handler.Logger.Debugw("update request ", "req", patchRequest) app, err := handler.pipelineBuilder.GetApp(patchRequest.AppId) if err != nil { common.WriteJsonResp(w, err, nil, http.StatusBadRequest) return err } - if app.AppType != helper.CustomApp { err = fmt.Errorf("only custom apps supported") common.WriteJsonResp(w, err, nil, http.StatusBadRequest) return err } resourceName := handler.enforcerUtil.GetAppRBACName(app.AppName) - ok := handler.enforcer.Enforce(token, casbin.ResourceApplications, casbin.ActionCreate, resourceName) - - if !ok { + if ok := handler.enforcer.Enforce(token, casbin.ResourceApplications, casbin.ActionUpdate, resourceName); !ok { err = fmt.Errorf("unauthorized user") common.WriteJsonResp(w, err, "Unauthorized User", http.StatusForbidden) return err } - patchRequest.Name = app.AppName err = handler.validator.Struct(patchRequest) if err != nil { handler.Logger.Errorw("validation err", "err", err) @@ -281,17 +276,18 @@ func (handler PipelineConfigRestHandlerImpl) authorizeSourceChangeRequest(w http return nil } -func (handler PipelineConfigRestHandlerImpl) PatchCiMaterialSource(w http.ResponseWriter, r *http.Request) { - patchRequest, userId, err := handler.parseBranchChangeRequest(w, r) +func (handler PipelineConfigRestHandlerImpl) PatchCiMaterialSourceWithAppIdAndEnvironmentId(w http.ResponseWriter, r *http.Request) { + patchRequest, userId, err := handler.parseSourceChangeRequest(w, r) if err != nil { handler.Logger.Errorw("Parse error, PatchCiMaterialSource", "err", err, "PatchCiMaterialSource", patchRequest) return } token := r.Header.Get("token") - if err = handler.authorizeSourceChangeRequest(w, userId, patchRequest, token); err != nil { + if err = handler.authorizeCiSourceChangeRequest(w, patchRequest, token); err != nil { handler.Logger.Errorw("Authorization error, PatchCiMaterialSource", "err", err, "PatchCiMaterialSource", patchRequest) return } + createResp, err := handler.pipelineBuilder.PatchCiMaterialSource(patchRequest, userId) if err != nil { handler.Logger.Errorw("service err, PatchCiPipelines", "err", err, "PatchCiPipelines", patchRequest) diff --git a/api/restHandler/app/BuildPipelineRestHandler_test.go b/api/restHandler/app/BuildPipelineRestHandler_test.go index a165b3faa23..d2befef306e 100644 --- a/api/restHandler/app/BuildPipelineRestHandler_test.go +++ b/api/restHandler/app/BuildPipelineRestHandler_test.go @@ -47,7 +47,7 @@ func TestPipelineConfigRestHandlerImpl_PatchCiMaterialSource(t *testing.T) { fields: fields{ validator: validator.New(), }, - body: "{\"appId\":4, \"id\": 5 ,\"ci--Material\":[{\"gitMaterialId\":4,\"id\":5,\"source\":{\"type\":\"SOURCE_TYPE_BRANCH_FIXED\",\"value\":\"main3\",\"regex\":\"\"}}]}", + body: "{\"appId\":2, \"environmentId\": 1 ,\"source\":{\"type\":\"SOURCE_TYPE_BRANCH_FIXED\",\"value\":\"main10\",\"regex\":\"\"}}", setup: func(fields2 *fields) { ctrl := gomock.NewController(t) fields2.pipelineBuilder = mock_pipeline.NewMockPipelineBuilder(ctrl) @@ -142,7 +142,7 @@ func TestPipelineConfigRestHandlerImpl_PatchCiMaterialSource(t *testing.T) { fields: fields{ validator: validator.New(), }, - body: "{\"appId\":4, \"id\": 5 ,\"ciMaterial\":[{\"gitMaterialId\":4,\"id\":5,\"source\":{\"type\":\"SOURCE_TYPE_BRANCH_FIXED\",\"value\":\"main3\",\"regex\":\"\"}}]}", + body: "{\"appId\":4, \"environmentId\": 1 ,\"source\":{\"type\":\"SOURCE_TYPE_BRANCH_FIXED\",\"value\":\"main10\",\"regex\":\"\"}}", setup: func(fields2 *fields) { _ = fields2.validator.RegisterValidation("name-component", func(fl validator.FieldLevel) bool { return true @@ -167,7 +167,7 @@ func TestPipelineConfigRestHandlerImpl_PatchCiMaterialSource(t *testing.T) { fields: fields{ validator: validator.New(), }, - body: "{\"appId\":4, \"id\": 5 ,\"ciMaterial\":[{\"gitMaterialId\":4,\"id\":5,\"source\":{\"type\":\"SOURCE_TYPE_BRANCH_FIXED\",\"value\":\"main3\",\"regex\":\"\"}}]}", + body: "{\"appId\":4, \"environmentId\": 1 ,\"source\":{\"type\":\"SOURCE_TYPE_BRANCH_FIXED\",\"value\":\"main10\",\"regex\":\"\"}}", setup: func(fields2 *fields) { _ = fields2.validator.RegisterValidation("name-component", func(fl validator.FieldLevel) bool { return true @@ -175,7 +175,7 @@ func TestPipelineConfigRestHandlerImpl_PatchCiMaterialSource(t *testing.T) { ctrl := gomock.NewController(t) fields2.pipelineBuilder = mock_pipeline.NewMockPipelineBuilder(ctrl) fields2.pipelineBuilder.EXPECT().GetApp(4).Return(&bean.CreateAppDTO{AppName: "Super App", Id: 4, AppType: helper.CustomApp}, nil).Times(1) - fields2.pipelineBuilder.EXPECT().PatchCiMaterialSource(gomock.Any(), int32(1)).Return(&bean.CiPipeline{Id: 1}, nil) + fields2.pipelineBuilder.EXPECT().PatchCiMaterialSource(gomock.Any(), int32(1)).Return(&bean.CiMaterialPatchRequest{AppId: 2}, nil) fields2.enforcer = mock_casbin.NewMockEnforcer(ctrl) fields2.enforcer.EXPECT().Enforce(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(true).Times(1) fields2.enforcerUtil = mocks_rbac.NewMockEnforcerUtil(ctrl) @@ -206,7 +206,7 @@ func TestPipelineConfigRestHandlerImpl_PatchCiMaterialSource(t *testing.T) { } req.Header.Set("Content-Type", "application/json") rr := httptest.NewRecorder() - h := http.HandlerFunc(handler.PatchCiMaterialSource) + h := http.HandlerFunc(handler.PatchCiMaterialSourceWithAppIdAndEnvironmentId) h.ServeHTTP(rr, req) assert.Equal(t, rr.Code, tt.expectedStatusCode) }) diff --git a/api/router/PipelineConfigRouter.go b/api/router/PipelineConfigRouter.go index 938b1f60fbc..c5ea04951cd 100644 --- a/api/router/PipelineConfigRouter.go +++ b/api/router/PipelineConfigRouter.go @@ -85,7 +85,7 @@ func (router PipelineConfigRouterImpl) initPipelineConfigRouter(configRouter *mu configRouter.Path("/external-ci/{appId}/{externalCiId}").HandlerFunc(router.restHandler.GetExternalCiById).Methods("GET") configRouter.Path("/ci-pipeline/template/patch").HandlerFunc(router.restHandler.UpdateCiTemplate).Methods("POST") configRouter.Path("/ci-pipeline/patch").HandlerFunc(router.restHandler.PatchCiPipelines).Methods("POST") - configRouter.Path("/ci-pipeline/patch-branch").HandlerFunc(router.restHandler.PatchCiMaterialSource).Methods("PATCH") + configRouter.Path("/ci-pipeline/patch-source").HandlerFunc(router.restHandler.PatchCiMaterialSourceWithAppIdAndEnvironmentId).Methods("PATCH") configRouter.Path("/ci-pipeline/patch/regex").HandlerFunc(router.restHandler.UpdateBranchCiPipelinesWithRegex).Methods("POST") configRouter.Path("/cd-pipeline/{cd_pipeline_id}/material").HandlerFunc(router.restHandler.GetArtifactsByCDPipeline).Methods("GET") diff --git a/pkg/bean/app.go b/pkg/bean/app.go index 675dee88751..a37e266c9b8 100644 --- a/pkg/bean/app.go +++ b/pkg/bean/app.go @@ -211,6 +211,13 @@ func (a PatchAction) String() string { } // ---------------- + +type CiMaterialPatchRequest struct { + AppId int `json:"appId" validate:"required"` + EnvironmentId int `json:"environmentId" validate:"required"` + Source *SourceTypeConfig `json:"source" validate:"required"` +} + type CiPatchRequest struct { CiPipeline *CiPipeline `json:"ciPipeline"` AppId int `json:"appId,omitempty"` diff --git a/pkg/pipeline/CiCdPipelineOrchestrator.go b/pkg/pipeline/CiCdPipelineOrchestrator.go index 0f4b7ce4831..5d4827accc2 100644 --- a/pkg/pipeline/CiCdPipelineOrchestrator.go +++ b/pkg/pipeline/CiCdPipelineOrchestrator.go @@ -69,7 +69,7 @@ type CiCdPipelineOrchestrator interface { DeleteCiPipeline(pipeline *pipelineConfig.CiPipeline, request *bean.CiPatchRequest, tx *pg.Tx) error DeleteCdPipeline(pipelineId int, userId int32, tx *pg.Tx) error PatchMaterialValue(createRequest *bean.CiPipeline, userId int32, oldPipeline *pipelineConfig.CiPipeline) (*bean.CiPipeline, error) - PatchCiMaterialSource(ciPipeline *bean.CiPipeline, userId int32) (*bean.CiPipeline, error) + PatchCiMaterialSource(ciPipeline *bean.CiMaterialPatchRequest, userId int32) (*bean.CiMaterialPatchRequest, error) PipelineExists(name string) (bool, error) GetCdPipelinesForApp(appId int) (cdPipelines *bean.CdPipelines, err error) GetCdPipelinesForAppAndEnv(appId int, envId int) (cdPipelines *bean.CdPipelines, err error) @@ -161,33 +161,46 @@ func NewCiCdPipelineOrchestrator( const BEFORE_DOCKER_BUILD string = "BEFORE_DOCKER_BUILD" const AFTER_DOCKER_BUILD string = "AFTER_DOCKER_BUILD" -func (impl CiCdPipelineOrchestratorImpl) PatchCiMaterialSource(ciPipeline *bean.CiPipeline, userId int32) (*bean.CiPipeline, error) { - oldPipeline, err := impl.ciPipelineRepository.FindById(ciPipeline.Id) +func (impl CiCdPipelineOrchestratorImpl) PatchCiMaterialSource(patchRequest *bean.CiMaterialPatchRequest, userId int32) (*bean.CiMaterialPatchRequest, error) { + pipeline, err := impl.findUniquePipelineForAppIdAndEnvironmentId(patchRequest.AppId, patchRequest.EnvironmentId) if err != nil { return nil, err } - materialsUpdate := mapCiMaterialToPipelineMaterial(ciPipeline, userId, oldPipeline) - if err = impl.saveUpdatedMaterial(materialsUpdate); err != nil { + ciPipelineMaterial, err := impl.findUniqueCiPipelineMaterial(pipeline.CiPipelineId) + if err != nil { + return nil, err + } + ciPipelineMaterial.Type = patchRequest.Source.Type + ciPipelineMaterial.Value = patchRequest.Source.Value + ciPipelineMaterial.Regex = patchRequest.Source.Regex + ciPipelineMaterial.AuditLog.UpdatedBy = userId + ciPipelineMaterial.AuditLog.UpdatedOn = time.Now() + if err = impl.saveUpdatedMaterial([]*pipelineConfig.CiPipelineMaterial{ciPipelineMaterial}); err != nil { return nil, err } - return ciPipeline, nil + return patchRequest, nil } -func mapCiMaterialToPipelineMaterial(ciPipeline *bean.CiPipeline, userId int32, oldPipeline *pipelineConfig.CiPipeline) []*pipelineConfig.CiPipelineMaterial { - updatedMaterials := make([]*pipelineConfig.CiPipelineMaterial, 0) - oldPipelineMaterials := make(map[int]*pipelineConfig.CiPipelineMaterial) - for _, oldMaterial := range oldPipeline.CiPipelineMaterials { - oldPipelineMaterials[oldMaterial.Id] = oldMaterial +func (impl CiCdPipelineOrchestratorImpl) findUniquePipelineForAppIdAndEnvironmentId(appId, environmentId int) (*pipelineConfig.Pipeline, error) { + pipeline, err := impl.pipelineRepository.FindActiveByAppIdAndEnvironmentId(appId, environmentId) + if err != nil { + return nil, err + } + if len(pipeline) != 1 { + return nil, fmt.Errorf("unique pipeline was not found, for the given appId and environmentId") + } + return pipeline[0], nil +} + +func (impl CiCdPipelineOrchestratorImpl) findUniqueCiPipelineMaterial(ciPipelineId int) (*pipelineConfig.CiPipelineMaterial, error) { + ciPipelineMaterials, err := impl.ciPipelineMaterialRepository.FindByCiPipelineIdsIn([]int{ciPipelineId}) + if err != nil { + return nil, err } - for _, ciMaterial := range ciPipeline.CiMaterial { - pipelineMaterial := *oldPipelineMaterials[ciMaterial.Id] - pipelineMaterial.Type = ciMaterial.Source.Type - pipelineMaterial.Regex = ciMaterial.Source.Regex - pipelineMaterial.Value = ciMaterial.Source.Value - pipelineMaterial.AuditLog = sql.AuditLog{CreatedOn: oldPipelineMaterials[ciMaterial.Id].CreatedOn, CreatedBy: oldPipelineMaterials[ciMaterial.Id].CreatedBy, UpdatedOn: time.Now(), UpdatedBy: userId} - updatedMaterials = append(updatedMaterials, &pipelineMaterial) + if len(ciPipelineMaterials) != 1 { + return nil, fmt.Errorf("unique ciPipelineMaterial was not found, for the given appId and environmentId") } - return updatedMaterials + return ciPipelineMaterials[0], nil } func (impl CiCdPipelineOrchestratorImpl) saveUpdatedMaterial(materialsUpdate []*pipelineConfig.CiPipelineMaterial) error { @@ -586,7 +599,7 @@ func (impl CiCdPipelineOrchestratorImpl) DeleteCiPipeline(pipeline *pipelineConf CiPipelineId: request.CiPipeline.Id, DockerRegistryId: request.CiPipeline.DockerConfigOverride.DockerRegistry, DockerRepository: request.CiPipeline.DockerConfigOverride.DockerRepository, - //DockerfilePath: ciPipeline.DockerConfigOverride.DockerBuildConfig.DockerfilePath, + //DockerfilePath: ciPipelineRequest.DockerConfigOverride.DockerBuildConfig.DockerfilePath, GitMaterialId: request.CiPipeline.DockerConfigOverride.CiBuildConfig.GitMaterialId, Active: false, AuditLog: sql.AuditLog{ @@ -750,7 +763,7 @@ func (impl CiCdPipelineOrchestratorImpl) CreateCiConf(createRequest *bean.CiConf CiPipelineId: ciPipeline.Id, DockerRegistryId: ciPipeline.DockerConfigOverride.DockerRegistry, DockerRepository: ciPipeline.DockerConfigOverride.DockerRepository, - //DockerfilePath: ciPipeline.DockerConfigOverride.DockerBuildConfig.DockerfilePath, + //DockerfilePath: ciPipelineRequest.DockerConfigOverride.DockerBuildConfig.DockerfilePath, GitMaterialId: ciPipeline.DockerConfigOverride.CiBuildConfig.GitMaterialId, BuildContextGitMaterialId: ciPipeline.DockerConfigOverride.CiBuildConfig.BuildContextGitMaterialId, Active: true, diff --git a/pkg/pipeline/CiCdPipelineOrchestrator_test.go b/pkg/pipeline/CiCdPipelineOrchestrator_test.go index 774dca7b783..a7a97f3f159 100644 --- a/pkg/pipeline/CiCdPipelineOrchestrator_test.go +++ b/pkg/pipeline/CiCdPipelineOrchestrator_test.go @@ -10,7 +10,6 @@ import ( repository2 "github.com/devtron-labs/devtron/internal/sql/repository/dockerRegistry" "github.com/devtron-labs/devtron/internal/sql/repository/helper" "github.com/devtron-labs/devtron/internal/sql/repository/pipelineConfig" - "github.com/devtron-labs/devtron/internal/sql/repository/pipelineConfig/mocks" "github.com/devtron-labs/devtron/internal/util" app2 "github.com/devtron-labs/devtron/pkg/app" "github.com/devtron-labs/devtron/pkg/attributes" @@ -18,12 +17,10 @@ import ( repository3 "github.com/devtron-labs/devtron/pkg/cluster/repository" "github.com/devtron-labs/devtron/pkg/pipeline/history" repository4 "github.com/devtron-labs/devtron/pkg/pipeline/history/repository" - "github.com/devtron-labs/devtron/pkg/sql" "github.com/devtron-labs/devtron/pkg/user" "github.com/stretchr/testify/assert" "log" "testing" - "time" ) var ( @@ -159,25 +156,6 @@ func InitClusterNoteService() { ciCdPipelineOrchestrator = NewCiCdPipelineOrchestrator(appRepository, logger, materialRepository, pipelineRepository, ciPipelineRepository, ciPipelineMaterialRepository, GitSensorClient, ciConfig, appWorkflowRepository, envRepository, attributesService, appListingRepository, appLabelsService, userAuthService, prePostCdScriptHistoryService, prePostCiScriptHistoryService, pipelineStageService, ciTemplateOverrideRepository, gitMaterialHistoryService, ciPipelineHistoryService, ciTemplateService, dockerArtifactStoreRepository, configMapService) } -func TestPatchCiMaterialSourceWhenOldPipelineIsNotFoundItShouldReturnError(t *testing.T) { - //ctrl := gomock.NewController(t) - pipeline := &bean.CiPipeline{Id: 1} - userId := int32(10) - - mockedCiPipelineRepository := mocks.NewCiPipelineRepository(t) - mockedCiPipelineRepository.On("FindById", pipeline.Id).Return(nil, fmt.Errorf("dsfsdf")) - //mockedCiPipelineMaterialRepository := &mocks.MockCiPipelineMaterialRepository{} - //mockedGitSensor := &mock_gitSensor.MockClient{} - impl := CiCdPipelineOrchestratorImpl{ - ciPipelineRepository: mockedCiPipelineRepository, - //ciPipelineMaterialRepository: mockedCiPipelineMaterialRepository, - //GitSensorClient: mockedGitSensor, - } - res, err := impl.PatchCiMaterialSource(pipeline, userId) - assert.Error(t, err) - assert.Nil(t, res) -} - // func TestPatchCiMaterialSourceWhenOldPipelineExistsAndSaveUpdatedMaterialFailsItShouldReturnError(t *testing.T) { // //ctrl := gomock.NewController(t) // userId := int32(10) @@ -227,150 +205,3 @@ func TestPatchCiMaterialSourceWhenOldPipelineIsNotFoundItShouldReturnError(t *te // assert.Error(t, err) // assert.Nil(t, res) // } -func Test_mapCiMaterialToPipelineMaterial(t *testing.T) { - t1 := time.Now() - t2 := time.Now() - type args struct { - ciPipeline *bean.CiPipeline - userId int32 - oldPipeline *pipelineConfig.CiPipeline - } - tests := []struct { - name string - args args - want []*pipelineConfig.CiPipelineMaterial - }{ - { - name: "It should return []*pipelineConfig.CiPipelineMaterial with only source changed", - args: args{ - ciPipeline: &bean.CiPipeline{ - AppId: 0, - CiMaterial: []*bean.CiMaterial{ - { - Source: &bean.SourceTypeConfig{ - Type: "QWERTY", - Value: "masterrrrr", - Regex: "A@$%DS", - }, - Id: 2, - GitMaterialId: 2, - }, - }, - Id: 2, - }, - userId: 1, - oldPipeline: &pipelineConfig.CiPipeline{ - Id: 1, - AppId: 2, - App: nil, - CiTemplateId: 3, - DockerArgs: "abc", - Name: "def", - Version: "234", - Active: true, - Deleted: false, - IsManual: true, - IsExternal: false, - ParentCiPipeline: 0, - ScanEnabled: false, - IsDockerConfigOverridden: false, - AuditLog: sql.AuditLog{ - CreatedOn: t1, - CreatedBy: 2, - UpdatedOn: t2, - UpdatedBy: 1, - }, - CiPipelineMaterials: []*pipelineConfig.CiPipelineMaterial{ - { - Id: 2, - GitMaterialId: 2, - CiPipelineId: 2, - Path: "", - CheckoutPath: "", - Type: "ABC", - Value: "DEF", - ScmId: "", - ScmName: "", - ScmVersion: "", - Active: false, - Regex: "A$%", - GitTag: "", - CiPipeline: nil, - GitMaterial: nil, - AuditLog: sql.AuditLog{ - CreatedOn: t1, - CreatedBy: 2, - UpdatedOn: t1, - UpdatedBy: 2, - }, - }, - { - Id: 3, - GitMaterialId: 2, - CiPipelineId: 2, - Path: "", - CheckoutPath: "", - Type: "ABC123", - Value: "main", - ScmId: "", - ScmName: "", - ScmVersion: "", - Active: false, - Regex: "A$%a3e2", - GitTag: "sdf", - CiPipeline: nil, - GitMaterial: nil, - AuditLog: sql.AuditLog{ - CreatedOn: t1, - CreatedBy: 2, - UpdatedOn: t1, - UpdatedBy: 2, - }, - }, - }, - CiTemplate: nil, - }, - }, - want: []*pipelineConfig.CiPipelineMaterial{ - { - Id: 2, - GitMaterialId: 2, - CiPipelineId: 2, - Path: "", - CheckoutPath: "", - Type: "QWERTY", - Value: "masterrrrr", - Regex: "A@$%DS", - ScmId: "", - ScmName: "", - ScmVersion: "", - Active: false, - GitTag: "", - CiPipeline: nil, - GitMaterial: nil, - AuditLog: sql.AuditLog{ - CreatedOn: t1, - CreatedBy: 2, - UpdatedOn: t2, - UpdatedBy: 1, - }, - }, - }, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - res := mapCiMaterialToPipelineMaterial(tt.args.ciPipeline, tt.args.userId, tt.args.oldPipeline) - assert.Equal(t, len(res), 1) - assert.Equal(t, tt.want[0].Id, res[0].Id) - assert.Equal(t, tt.want[0].GitMaterialId, res[0].GitMaterialId) - assert.Equal(t, tt.want[0].CiPipelineId, res[0].CiPipelineId) - assert.Equal(t, tt.want[0].Type, res[0].Type) - assert.Equal(t, tt.want[0].Value, res[0].Value) - assert.Equal(t, tt.want[0].Regex, res[0].Regex) - assert.Equal(t, tt.want[0].AuditLog.CreatedBy, res[0].AuditLog.CreatedBy) - assert.Equal(t, tt.want[0].AuditLog.CreatedOn, res[0].AuditLog.CreatedOn) - assert.Equal(t, tt.want[0].AuditLog.UpdatedBy, res[0].AuditLog.UpdatedBy) - }) - } -} diff --git a/pkg/pipeline/ImageTaggingService.go b/pkg/pipeline/ImageTaggingService.go index a245cd2e454..57e074f4222 100644 --- a/pkg/pipeline/ImageTaggingService.go +++ b/pkg/pipeline/ImageTaggingService.go @@ -59,7 +59,7 @@ type ImageTaggingService interface { //ImageReleaseTags -> this will get the tags of the artifact, //AppReleaseTags -> all the tags of the given appId, //imageComment -> comment of the given artifactId, - // ProdEnvExists -> implies the existence of prod environment in any workflow of given ciPipelineId or its child ciPipeline's + // ProdEnvExists -> implies the existence of prod environment in any workflow of given ciPipelineId or its child ciPipelineRequest's GetTagsData(ciPipelineId, appId, artifactId int, externalCi bool) (*ImageTaggingResponseDTO, error) CreateOrUpdateImageTagging(ciPipelineId, appId, artifactId, userId int, imageTaggingRequest *ImageTaggingRequestDTO) (*ImageTaggingResponseDTO, error) GetProdEnvFromParentAndLinkedWorkflow(ciPipelineId int) (bool, error) @@ -114,7 +114,7 @@ func (impl ImageTaggingServiceImpl) GetImageTaggingServiceConfig() ImageTaggingS // ImageReleaseTags -> this will get the tags of the artifact, // AppReleaseTags -> all the tags of the given appId, // imageComment -> comment of the given artifactId, -// ProdEnvExists -> implies the existence of prod environment in any workflow of given ciPipelineId or its child ciPipeline's +// ProdEnvExists -> implies the existence of prod environment in any workflow of given ciPipelineId or its child ciPipelineRequest's func (impl ImageTaggingServiceImpl) GetTagsData(ciPipelineId, appId, artifactId int, externalCi bool) (*ImageTaggingResponseDTO, error) { resp := &ImageTaggingResponseDTO{} imageComment, err := impl.imageTaggingRepo.GetImageComment(artifactId) diff --git a/pkg/pipeline/PipelineBuilder.go b/pkg/pipeline/PipelineBuilder.go index 6cf066c9579..72377d1ef72 100644 --- a/pkg/pipeline/PipelineBuilder.go +++ b/pkg/pipeline/PipelineBuilder.go @@ -113,7 +113,7 @@ type PipelineBuilder interface { GetExternalCiById(appId int, externalCiId int) (ciConfig *bean.ExternalCiConfig, err error) UpdateCiTemplate(updateRequest *bean.CiConfigRequest) (*bean.CiConfigRequest, error) PatchCiPipeline(request *bean.CiPatchRequest) (ciConfig *bean.CiConfigRequest, err error) - PatchCiMaterialSource(ciPipeline *bean.CiPipeline, userId int32) (*bean.CiPipeline, error) + PatchCiMaterialSource(ciPipeline *bean.CiMaterialPatchRequest, userId int32) (*bean.CiMaterialPatchRequest, error) CreateCdPipelines(cdPipelines *bean.CdPipelines, ctx context.Context) (*bean.CdPipelines, error) GetApp(appId int) (application *bean.CreateAppDTO, err error) PatchCdPipelines(cdPipelines *bean.CDPatchRequest, ctx context.Context) (*bean.CdPipelines, error) @@ -1630,7 +1630,7 @@ func (impl *PipelineBuilderImpl) DeleteCiPipeline(request *bean.CiPatchRequest) } -func (impl *PipelineBuilderImpl) PatchCiMaterialSource(ciPipeline *bean.CiPipeline, userId int32) (*bean.CiPipeline, error) { +func (impl *PipelineBuilderImpl) PatchCiMaterialSource(ciPipeline *bean.CiMaterialPatchRequest, userId int32) (*bean.CiMaterialPatchRequest, error) { return impl.ciCdPipelineOrchestrator.PatchCiMaterialSource(ciPipeline, userId) } diff --git a/pkg/pipeline/PipelineStageService.go b/pkg/pipeline/PipelineStageService.go index 8de1a0be44c..36d63cd03e9 100644 --- a/pkg/pipeline/PipelineStageService.go +++ b/pkg/pipeline/PipelineStageService.go @@ -66,7 +66,7 @@ func (impl *PipelineStageServiceImpl) GetCiPipelineStageDataDeepCopy(ciPipelineI return nil, nil, err } } else { - impl.logger.Errorw("found improper stage mapped with ciPipeline", "ciPipelineId", ciPipelineId, "stage", ciStage) + impl.logger.Errorw("found improper stage mapped with ciPipelineRequest", "ciPipelineId", ciPipelineId, "stage", ciStage) } } return preCiStage, postCiStage, nil @@ -371,7 +371,7 @@ func (impl *PipelineStageServiceImpl) GetCiPipelineStageData(ciPipelineId int) ( return nil, nil, err } } else { - impl.logger.Errorw("found improper stage mapped with ciPipeline", "ciPipelineId", ciPipelineId, "stage", ciStage) + impl.logger.Errorw("found improper stage mapped with ciPipelineRequest", "ciPipelineId", ciPipelineId, "stage", ciStage) } } return preCiStage, postCiStage, nil diff --git a/pkg/pipeline/PipelineStageServiceIT_test.go b/pkg/pipeline/PipelineStageServiceIT_test.go index be7a9171441..f9be26ebc79 100644 --- a/pkg/pipeline/PipelineStageServiceIT_test.go +++ b/pkg/pipeline/PipelineStageServiceIT_test.go @@ -22,9 +22,9 @@ import ( "time" ) -const CiPipelineStageCreateReqJson = `{"appId":1,"appWorkflowId":0,"action":0,"ciPipeline":{"active":true,"ciMaterial":[{"gitMaterialId":1,"id":0,"source":{"type":"SOURCE_TYPE_BRANCH_FIXED","value":"main","regex":""}}],"dockerArgs":{},"externalCiConfig":{},"id":0,"isExternal":false,"isManual":false,"name":"ci-1-xyze","linkedCount":0,"scanEnabled":false,"preBuildStage":{"id":0,"steps":[{"id":1,"index":1,"name":"Task 1","description":"chbsdkhbc","stepType":"INLINE","directoryPath":"","inlineStepDetail":{"scriptType":"CONTAINER_IMAGE","script":"echo \"ifudsbvnv\"","conditionDetails":[],"inputVariables":[{"id":1,"name":"Hello","value":"","format":"STRING","description":"jnsdvbdvbsd","defaultValue":"","variableType":"GLOBAL","refVariableStepIndex":0,"refVariableName":"WORKING_DIRECTORY","refVariableStage":""}],"outputVariables":null,"commandArgsMap":[{"command":"echo","args":["\"HOSTNAME\"","\"PORT\""]}],"portMap":[{"portOnLocal":8080,"portOnContainer":9090}],"mountCodeToContainer":true,"mountDirectoryFromHost":true,"mountCodeToContainerPath":"/sourcecode","mountPathMap":[{"filePathOnDisk":"./test","filePathOnContainer":"./test_container"}],"containerImagePath":"python:latest","isMountCustomScript":true,"storeScriptAt":"./directory/script"},"outputDirectoryPath":["./test1"]},{"id":2,"index":2,"name":"K6 Load testing","description":"K6 is an open-source tool and cloud service that makes load testing easy for developers and QA engineers.","stepType":"REF_PLUGIN","directoryPath":"","pluginRefStepDetail":{"id":0,"pluginId":1,"conditionDetails":[{"id":0,"conditionOnVariable":"RelativePathToScript","conditionOperator":"==","conditionType":"TRIGGER","conditionalValue":"svfsv"},{"id":0,"conditionOnVariable":"PrometheusApiKey","conditionOperator":"==","conditionType":"TRIGGER","conditionalValue":"dfbeavafsv"}],"inputVariables":[{"id":1,"name":"RelativePathToScript","format":"STRING","description":"checkout path + script path along with script name","isExposed":true,"allowEmptyValue":false,"defaultValue":"/./script.js","variableType":"NEW","variableStepIndexInPlugin":1,"value":"dethdt","refVariableName":"","refVariableStage":""},{"id":2,"name":"PrometheusUsername","format":"STRING","description":"username of prometheus account","isExposed":true,"allowEmptyValue":true,"defaultValue":"","variableType":"NEW","variableStepIndexInPlugin":1,"value":"ghmfnbd","refVariableName":"","refVariableStage":""},{"id":3,"name":"PrometheusApiKey","format":"STRING","description":"api key of prometheus account","isExposed":true,"allowEmptyValue":true,"defaultValue":"","variableType":"NEW","variableStepIndexInPlugin":1,"value":"afegs","refVariableName":"","refVariableStage":""},{"id":4,"name":"PrometheusRemoteWriteEndpoint","format":"STRING","description":"remote write endpoint of prometheus account","isExposed":true,"allowEmptyValue":true,"defaultValue":"","variableType":"NEW","variableStepIndexInPlugin":1,"value":"aef","refVariableName":"","refVariableStage":""},{"id":5,"name":"OutputType","format":"STRING","description":"output type - LOG or PROMETHEUS","isExposed":true,"allowEmptyValue":false,"defaultValue":"LOG","variableType":"NEW","variableStepIndexInPlugin":1,"value":"fdgn","refVariableName":"","refVariableStage":""}]}},{"id":3,"index":3,"name":"Task 3","description":"sfdbvf","stepType":"INLINE","directoryPath":"","inlineStepDetail":{"scriptType":"SHELL","script":"#!/bin/sh \nset -eo pipefail \n#set -v ## uncomment this to debug the script \n","conditionDetails":[{"id":0,"conditionOnVariable":"Hello","conditionOperator":"==","conditionType":"PASS","conditionalValue":"aedfrwgwr"},{"id":0,"conditionOnVariable":"Hello","conditionOperator":"!=","conditionType":"PASS","conditionalValue":"tegegr"}],"inputVariables":[],"outputVariables":[{"id":1,"name":"Hello","value":"","format":"STRING","description":"dsuihvsuvhbdv","defaultValue":"","variableType":"NEW","refVariableStepIndex":0,"refVariableName":""}],"commandArgsMap":[{"command":"","args":[]}],"portMap":[],"mountCodeToContainer":false,"mountDirectoryFromHost":false},"outputDirectoryPath":["./test2"]}]},"postBuildStage":{},"dockerConfigOverride":{}}}` -const CiPipelineStageUpdateReqJson = `{"appId":1,"appWorkflowId":3,"action":1,"ciPipeline":{"isManual":false,"dockerArgs":{},"isExternal":false,"parentCiPipeline":0,"parentAppId":0,"appId":1,"externalCiConfig":{"id":0,"webhookUrl":"","payload":"","accessKey":"","payloadOption":null,"schema":null,"responses":null,"projectId":0,"projectName":"","environmentId":"","environmentName":"","environmentIdentifier":"","appId":0,"appName":"","role":""},"ciMaterial":[{"gitMaterialId":1,"id":3,"source":{"type":"SOURCE_TYPE_BRANCH_FIXED","value":"main","regex":""}}],"name":"ci-1-unov","id":3,"active":true,"linkedCount":0,"scanEnabled":false,"appWorkflowId":3,"preBuildStage":{"id":5,"type":"PRE_CI","steps":[{"id":9,"name":"K6 Load testing","description":"K6 is an open-source tool and cloud service that makes load testing easy for developers and QA engineers.","index":1,"stepType":"REF_PLUGIN","outputDirectoryPath":null,"inlineStepDetail":null,"pluginRefStepDetail":{"pluginId":1,"inputVariables":[{"id":44,"name":"RelativePathToScript","format":"STRING","description":"checkout path + script path along with script name","isExposed":true,"defaultValue":"/./script.js","value":"sfds","variableType":"NEW","variableStepIndexInPlugin":1,"refVariableStage":""},{"id":45,"name":"PrometheusUsername","format":"STRING","description":"username of prometheus account","isExposed":true,"allowEmptyValue":true,"value":"sdf","variableType":"NEW","variableStepIndexInPlugin":1,"refVariableStage":""},{"id":46,"name":"PrometheusApiKey","format":"STRING","description":"api key of prometheus account","isExposed":true,"allowEmptyValue":true,"value":"hter","variableType":"NEW","variableStepIndexInPlugin":1,"refVariableStage":""},{"id":47,"name":"PrometheusRemoteWriteEndpoint","format":"STRING","description":"remote write endpoint of prometheus account","isExposed":true,"allowEmptyValue":true,"value":"ewq","variableType":"NEW","variableStepIndexInPlugin":1,"refVariableStage":""},{"id":48,"name":"OutputType","format":"STRING","description":"output type - LOG or PROMETHEUS","isExposed":true,"defaultValue":"LOG","value":"erg","variableType":"NEW","variableStepIndexInPlugin":1,"refVariableStage":""}],"outputVariables":null,"conditionDetails":null},"triggerIfParentStageFail":false},{"id":10,"name":"Task 3","description":"","index":3,"stepType":"INLINE","outputDirectoryPath":["./asap"],"inlineStepDetail":{"scriptType":"CONTAINER_IMAGE","script":null,"storeScriptAt":null,"mountDirectoryFromHost":false,"containerImagePath":"alpine:latest","commandArgsMap":[{"command":"echo","args":["HOSTNAME"]}],"inputVariables":null,"outputVariables":null,"conditionDetails":null,"portMap":[],"mountCodeToContainerPath":null,"mountPathMap":null},"pluginRefStepDetail":null,"triggerIfParentStageFail":false},{"id":8,"name":"Task 1","description":"","index":2,"stepType":"INLINE","outputDirectoryPath":["./test"],"inlineStepDetail":{"scriptType":"SHELL","script":"#!/bin/sh \nset -eo pipefail \necho \"Hello from inside pre-build stage\"\n#set -v ## uncomment this to debug the script \n","storeScriptAt":"","mountDirectoryFromHost":false,"commandArgsMap":[{"command":"","args":null}],"inputVariables":null,"outputVariables":null,"conditionDetails":null},"pluginRefStepDetail":null,"triggerIfParentStageFail":false}]},"postBuildStage":{},"isDockerConfigOverridden":false,"dockerConfigOverride":{}}}` -const CiPipelineStageDeleteReqJson = `{"appId":1,"appWorkflowId":8,"action":2,"ciPipeline":{"isManual":false,"dockerArgs":{},"isExternal":false,"parentCiPipeline":0,"parentAppId":0,"appId":1,"externalCiConfig":{"id":0,"webhookUrl":"","payload":"","accessKey":"","payloadOption":null,"schema":null,"responses":null,"projectId":0,"projectName":"","environmentId":"","environmentName":"","environmentIdentifier":"","appId":0,"appName":"","role":""},"ciMaterial":[{"gitMaterialId":1,"id":8,"source":{"type":"SOURCE_TYPE_BRANCH_FIXED","value":"main","regex":""}}],"name":"ci-1-unjn","id":8,"active":true,"linkedCount":0,"scanEnabled":false,"appWorkflowId":8,"preBuildStage":{"id":7,"type":"PRE_CI","steps":[{"id":11,"name":"Task 1","description":"","index":1,"stepType":"INLINE","outputDirectoryPath":["./test"],"inlineStepDetail":{"scriptType":"SHELL","script":"#!/bin/sh \nset -eo pipefail \necho \"Prakash\"\n#set -v ## uncomment this to debug the script \n","storeScriptAt":"","mountDirectoryFromHost":false,"commandArgsMap":[{"command":"","args":null}],"inputVariables":null,"outputVariables":null,"conditionDetails":null},"pluginRefStepDetail":null,"triggerIfParentStageFail":false},{"id":12,"name":"K6 Load testing","description":"K6 is an open-source tool and cloud service that makes load testing easy for developers and QA engineers.","index":2,"stepType":"REF_PLUGIN","outputDirectoryPath":null,"inlineStepDetail":null,"pluginRefStepDetail":{"pluginId":1,"inputVariables":[{"id":49,"name":"RelativePathToScript","format":"STRING","description":"checkout path + script path along with script name","isExposed":true,"defaultValue":"/./script.js","value":"sfds","variableType":"NEW","variableStepIndexInPlugin":1,"refVariableStage":""},{"id":50,"name":"PrometheusUsername","format":"STRING","description":"username of prometheus account","isExposed":true,"allowEmptyValue":true,"value":"sdf","variableType":"NEW","variableStepIndexInPlugin":1,"refVariableStage":""},{"id":51,"name":"PrometheusApiKey","format":"STRING","description":"api key of prometheus account","isExposed":true,"allowEmptyValue":true,"value":"hter","variableType":"NEW","variableStepIndexInPlugin":1,"refVariableStage":""},{"id":52,"name":"PrometheusRemoteWriteEndpoint","format":"STRING","description":"remote write endpoint of prometheus account","isExposed":true,"allowEmptyValue":true,"value":"ewq","variableType":"NEW","variableStepIndexInPlugin":1,"refVariableStage":""},{"id":53,"name":"OutputType","format":"STRING","description":"output type - LOG or PROMETHEUS","isExposed":true,"defaultValue":"LOG","value":"erg","variableType":"NEW","variableStepIndexInPlugin":1,"refVariableStage":""}],"outputVariables":null,"conditionDetails":null},"triggerIfParentStageFail":false},{"id":13,"name":"Task 3","description":"","index":3,"stepType":"INLINE","outputDirectoryPath":["./asap"],"inlineStepDetail":{"scriptType":"CONTAINER_IMAGE","script":"","storeScriptAt":"","mountDirectoryFromHost":false,"containerImagePath":"alpine:latest","commandArgsMap":[{"command":"echo","args":["HOSTNAME"]}],"inputVariables":null,"outputVariables":null,"conditionDetails":null,"portMap":[]},"pluginRefStepDetail":null,"triggerIfParentStageFail":false}]},"isDockerConfigOverridden":false,"dockerConfigOverride":{},"postBuildStage":{}}}` +const CiPipelineStageCreateReqJson = `{"appId":1,"appWorkflowId":0,"action":0,"ciPipelineRequest":{"active":true,"ciMaterial":[{"gitMaterialId":1,"id":0,"source":{"type":"SOURCE_TYPE_BRANCH_FIXED","value":"main","regex":""}}],"dockerArgs":{},"externalCiConfig":{},"id":0,"isExternal":false,"isManual":false,"name":"ci-1-xyze","linkedCount":0,"scanEnabled":false,"preBuildStage":{"id":0,"steps":[{"id":1,"index":1,"name":"Task 1","description":"chbsdkhbc","stepType":"INLINE","directoryPath":"","inlineStepDetail":{"scriptType":"CONTAINER_IMAGE","script":"echo \"ifudsbvnv\"","conditionDetails":[],"inputVariables":[{"id":1,"name":"Hello","value":"","format":"STRING","description":"jnsdvbdvbsd","defaultValue":"","variableType":"GLOBAL","refVariableStepIndex":0,"refVariableName":"WORKING_DIRECTORY","refVariableStage":""}],"outputVariables":null,"commandArgsMap":[{"command":"echo","args":["\"HOSTNAME\"","\"PORT\""]}],"portMap":[{"portOnLocal":8080,"portOnContainer":9090}],"mountCodeToContainer":true,"mountDirectoryFromHost":true,"mountCodeToContainerPath":"/sourcecode","mountPathMap":[{"filePathOnDisk":"./test","filePathOnContainer":"./test_container"}],"containerImagePath":"python:latest","isMountCustomScript":true,"storeScriptAt":"./directory/script"},"outputDirectoryPath":["./test1"]},{"id":2,"index":2,"name":"K6 Load testing","description":"K6 is an open-source tool and cloud service that makes load testing easy for developers and QA engineers.","stepType":"REF_PLUGIN","directoryPath":"","pluginRefStepDetail":{"id":0,"pluginId":1,"conditionDetails":[{"id":0,"conditionOnVariable":"RelativePathToScript","conditionOperator":"==","conditionType":"TRIGGER","conditionalValue":"svfsv"},{"id":0,"conditionOnVariable":"PrometheusApiKey","conditionOperator":"==","conditionType":"TRIGGER","conditionalValue":"dfbeavafsv"}],"inputVariables":[{"id":1,"name":"RelativePathToScript","format":"STRING","description":"checkout path + script path along with script name","isExposed":true,"allowEmptyValue":false,"defaultValue":"/./script.js","variableType":"NEW","variableStepIndexInPlugin":1,"value":"dethdt","refVariableName":"","refVariableStage":""},{"id":2,"name":"PrometheusUsername","format":"STRING","description":"username of prometheus account","isExposed":true,"allowEmptyValue":true,"defaultValue":"","variableType":"NEW","variableStepIndexInPlugin":1,"value":"ghmfnbd","refVariableName":"","refVariableStage":""},{"id":3,"name":"PrometheusApiKey","format":"STRING","description":"api key of prometheus account","isExposed":true,"allowEmptyValue":true,"defaultValue":"","variableType":"NEW","variableStepIndexInPlugin":1,"value":"afegs","refVariableName":"","refVariableStage":""},{"id":4,"name":"PrometheusRemoteWriteEndpoint","format":"STRING","description":"remote write endpoint of prometheus account","isExposed":true,"allowEmptyValue":true,"defaultValue":"","variableType":"NEW","variableStepIndexInPlugin":1,"value":"aef","refVariableName":"","refVariableStage":""},{"id":5,"name":"OutputType","format":"STRING","description":"output type - LOG or PROMETHEUS","isExposed":true,"allowEmptyValue":false,"defaultValue":"LOG","variableType":"NEW","variableStepIndexInPlugin":1,"value":"fdgn","refVariableName":"","refVariableStage":""}]}},{"id":3,"index":3,"name":"Task 3","description":"sfdbvf","stepType":"INLINE","directoryPath":"","inlineStepDetail":{"scriptType":"SHELL","script":"#!/bin/sh \nset -eo pipefail \n#set -v ## uncomment this to debug the script \n","conditionDetails":[{"id":0,"conditionOnVariable":"Hello","conditionOperator":"==","conditionType":"PASS","conditionalValue":"aedfrwgwr"},{"id":0,"conditionOnVariable":"Hello","conditionOperator":"!=","conditionType":"PASS","conditionalValue":"tegegr"}],"inputVariables":[],"outputVariables":[{"id":1,"name":"Hello","value":"","format":"STRING","description":"dsuihvsuvhbdv","defaultValue":"","variableType":"NEW","refVariableStepIndex":0,"refVariableName":""}],"commandArgsMap":[{"command":"","args":[]}],"portMap":[],"mountCodeToContainer":false,"mountDirectoryFromHost":false},"outputDirectoryPath":["./test2"]}]},"postBuildStage":{},"dockerConfigOverride":{}}}` +const CiPipelineStageUpdateReqJson = `{"appId":1,"appWorkflowId":3,"action":1,"ciPipelineRequest":{"isManual":false,"dockerArgs":{},"isExternal":false,"parentCiPipeline":0,"parentAppId":0,"appId":1,"externalCiConfig":{"id":0,"webhookUrl":"","payload":"","accessKey":"","payloadOption":null,"schema":null,"responses":null,"projectId":0,"projectName":"","environmentId":"","environmentName":"","environmentIdentifier":"","appId":0,"appName":"","role":""},"ciMaterial":[{"gitMaterialId":1,"id":3,"source":{"type":"SOURCE_TYPE_BRANCH_FIXED","value":"main","regex":""}}],"name":"ci-1-unov","id":3,"active":true,"linkedCount":0,"scanEnabled":false,"appWorkflowId":3,"preBuildStage":{"id":5,"type":"PRE_CI","steps":[{"id":9,"name":"K6 Load testing","description":"K6 is an open-source tool and cloud service that makes load testing easy for developers and QA engineers.","index":1,"stepType":"REF_PLUGIN","outputDirectoryPath":null,"inlineStepDetail":null,"pluginRefStepDetail":{"pluginId":1,"inputVariables":[{"id":44,"name":"RelativePathToScript","format":"STRING","description":"checkout path + script path along with script name","isExposed":true,"defaultValue":"/./script.js","value":"sfds","variableType":"NEW","variableStepIndexInPlugin":1,"refVariableStage":""},{"id":45,"name":"PrometheusUsername","format":"STRING","description":"username of prometheus account","isExposed":true,"allowEmptyValue":true,"value":"sdf","variableType":"NEW","variableStepIndexInPlugin":1,"refVariableStage":""},{"id":46,"name":"PrometheusApiKey","format":"STRING","description":"api key of prometheus account","isExposed":true,"allowEmptyValue":true,"value":"hter","variableType":"NEW","variableStepIndexInPlugin":1,"refVariableStage":""},{"id":47,"name":"PrometheusRemoteWriteEndpoint","format":"STRING","description":"remote write endpoint of prometheus account","isExposed":true,"allowEmptyValue":true,"value":"ewq","variableType":"NEW","variableStepIndexInPlugin":1,"refVariableStage":""},{"id":48,"name":"OutputType","format":"STRING","description":"output type - LOG or PROMETHEUS","isExposed":true,"defaultValue":"LOG","value":"erg","variableType":"NEW","variableStepIndexInPlugin":1,"refVariableStage":""}],"outputVariables":null,"conditionDetails":null},"triggerIfParentStageFail":false},{"id":10,"name":"Task 3","description":"","index":3,"stepType":"INLINE","outputDirectoryPath":["./asap"],"inlineStepDetail":{"scriptType":"CONTAINER_IMAGE","script":null,"storeScriptAt":null,"mountDirectoryFromHost":false,"containerImagePath":"alpine:latest","commandArgsMap":[{"command":"echo","args":["HOSTNAME"]}],"inputVariables":null,"outputVariables":null,"conditionDetails":null,"portMap":[],"mountCodeToContainerPath":null,"mountPathMap":null},"pluginRefStepDetail":null,"triggerIfParentStageFail":false},{"id":8,"name":"Task 1","description":"","index":2,"stepType":"INLINE","outputDirectoryPath":["./test"],"inlineStepDetail":{"scriptType":"SHELL","script":"#!/bin/sh \nset -eo pipefail \necho \"Hello from inside pre-build stage\"\n#set -v ## uncomment this to debug the script \n","storeScriptAt":"","mountDirectoryFromHost":false,"commandArgsMap":[{"command":"","args":null}],"inputVariables":null,"outputVariables":null,"conditionDetails":null},"pluginRefStepDetail":null,"triggerIfParentStageFail":false}]},"postBuildStage":{},"isDockerConfigOverridden":false,"dockerConfigOverride":{}}}` +const CiPipelineStageDeleteReqJson = `{"appId":1,"appWorkflowId":8,"action":2,"ciPipelineRequest":{"isManual":false,"dockerArgs":{},"isExternal":false,"parentCiPipeline":0,"parentAppId":0,"appId":1,"externalCiConfig":{"id":0,"webhookUrl":"","payload":"","accessKey":"","payloadOption":null,"schema":null,"responses":null,"projectId":0,"projectName":"","environmentId":"","environmentName":"","environmentIdentifier":"","appId":0,"appName":"","role":""},"ciMaterial":[{"gitMaterialId":1,"id":8,"source":{"type":"SOURCE_TYPE_BRANCH_FIXED","value":"main","regex":""}}],"name":"ci-1-unjn","id":8,"active":true,"linkedCount":0,"scanEnabled":false,"appWorkflowId":8,"preBuildStage":{"id":7,"type":"PRE_CI","steps":[{"id":11,"name":"Task 1","description":"","index":1,"stepType":"INLINE","outputDirectoryPath":["./test"],"inlineStepDetail":{"scriptType":"SHELL","script":"#!/bin/sh \nset -eo pipefail \necho \"Prakash\"\n#set -v ## uncomment this to debug the script \n","storeScriptAt":"","mountDirectoryFromHost":false,"commandArgsMap":[{"command":"","args":null}],"inputVariables":null,"outputVariables":null,"conditionDetails":null},"pluginRefStepDetail":null,"triggerIfParentStageFail":false},{"id":12,"name":"K6 Load testing","description":"K6 is an open-source tool and cloud service that makes load testing easy for developers and QA engineers.","index":2,"stepType":"REF_PLUGIN","outputDirectoryPath":null,"inlineStepDetail":null,"pluginRefStepDetail":{"pluginId":1,"inputVariables":[{"id":49,"name":"RelativePathToScript","format":"STRING","description":"checkout path + script path along with script name","isExposed":true,"defaultValue":"/./script.js","value":"sfds","variableType":"NEW","variableStepIndexInPlugin":1,"refVariableStage":""},{"id":50,"name":"PrometheusUsername","format":"STRING","description":"username of prometheus account","isExposed":true,"allowEmptyValue":true,"value":"sdf","variableType":"NEW","variableStepIndexInPlugin":1,"refVariableStage":""},{"id":51,"name":"PrometheusApiKey","format":"STRING","description":"api key of prometheus account","isExposed":true,"allowEmptyValue":true,"value":"hter","variableType":"NEW","variableStepIndexInPlugin":1,"refVariableStage":""},{"id":52,"name":"PrometheusRemoteWriteEndpoint","format":"STRING","description":"remote write endpoint of prometheus account","isExposed":true,"allowEmptyValue":true,"value":"ewq","variableType":"NEW","variableStepIndexInPlugin":1,"refVariableStage":""},{"id":53,"name":"OutputType","format":"STRING","description":"output type - LOG or PROMETHEUS","isExposed":true,"defaultValue":"LOG","value":"erg","variableType":"NEW","variableStepIndexInPlugin":1,"refVariableStage":""}],"outputVariables":null,"conditionDetails":null},"triggerIfParentStageFail":false},{"id":13,"name":"Task 3","description":"","index":3,"stepType":"INLINE","outputDirectoryPath":["./asap"],"inlineStepDetail":{"scriptType":"CONTAINER_IMAGE","script":"","storeScriptAt":"","mountDirectoryFromHost":false,"containerImagePath":"alpine:latest","commandArgsMap":[{"command":"echo","args":["HOSTNAME"]}],"inputVariables":null,"outputVariables":null,"conditionDetails":null,"portMap":[]},"pluginRefStepDetail":null,"triggerIfParentStageFail":false}]},"isDockerConfigOverridden":false,"dockerConfigOverride":{},"postBuildStage":{}}}` var ciPipelineId int var cdPipelineId int diff --git a/pkg/pipeline/WorkflowDagExecutor.go b/pkg/pipeline/WorkflowDagExecutor.go index c33d753a065..b03527ec123 100644 --- a/pkg/pipeline/WorkflowDagExecutor.go +++ b/pkg/pipeline/WorkflowDagExecutor.go @@ -703,7 +703,7 @@ func (impl *WorkflowDagExecutorImpl) buildWFRequest(runner *pipelineConfig.CdWor if cdPipeline.CiPipelineId > 0 { ciPipeline, err = impl.ciPipelineRepository.FindById(cdPipeline.CiPipelineId) if err != nil && !util.IsErrNoRows(err) { - impl.logger.Errorw("cannot find ciPipeline", "err", err) + impl.logger.Errorw("cannot find ciPipelineRequest", "err", err) return nil, err } diff --git a/pkg/pipeline/mock_pipeline/PipelineBuilder.go b/pkg/pipeline/mock_pipeline/PipelineBuilder.go index fb9ab4a17ff..067acf2d3da 100644 --- a/pkg/pipeline/mock_pipeline/PipelineBuilder.go +++ b/pkg/pipeline/mock_pipeline/PipelineBuilder.go @@ -786,10 +786,10 @@ func (mr *MockPipelineBuilderMockRecorder) PatchCdPipelines(cdPipelines, ctx int } // PatchCiMaterialSource mocks base method. -func (m *MockPipelineBuilder) PatchCiMaterialSource(ciPipeline *bean0.CiPipeline, userId int32) (*bean0.CiPipeline, error) { +func (m *MockPipelineBuilder) PatchCiMaterialSource(ciPipeline *bean0.CiMaterialPatchRequest, userId int32) (*bean0.CiMaterialPatchRequest, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "PatchCiMaterialSource", ciPipeline, userId) - ret0, _ := ret[0].(*bean0.CiPipeline) + ret0, _ := ret[0].(*bean0.CiMaterialPatchRequest) ret1, _ := ret[1].(error) return ret0, ret1 } From 95c3391184449aacc33b8a559517b68b7f28a051 Mon Sep 17 00:00:00 2001 From: Avdhesh Kumar Date: Thu, 3 Aug 2023 13:51:12 +0530 Subject: [PATCH 8/9] Add source type check --- api/restHandler/app/BuildPipelineRestHandler.go | 7 +++++++ api/restHandler/app/BuildPipelineRestHandler_test.go | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/api/restHandler/app/BuildPipelineRestHandler.go b/api/restHandler/app/BuildPipelineRestHandler.go index c42740e426b..38e1e94bc93 100644 --- a/api/restHandler/app/BuildPipelineRestHandler.go +++ b/api/restHandler/app/BuildPipelineRestHandler.go @@ -280,11 +280,18 @@ func (handler PipelineConfigRestHandlerImpl) PatchCiMaterialSourceWithAppIdAndEn patchRequest, userId, err := handler.parseSourceChangeRequest(w, r) if err != nil { handler.Logger.Errorw("Parse error, PatchCiMaterialSource", "err", err, "PatchCiMaterialSource", patchRequest) + common.WriteJsonResp(w, err, nil, http.StatusBadRequest) + return + } + if !(patchRequest.Source.Type == pipelineConfig.SOURCE_TYPE_BRANCH_FIXED || patchRequest.Source.Type == pipelineConfig.SOURCE_TYPE_BRANCH_REGEX) { + handler.Logger.Errorw("Unsupported source type, PatchCiMaterialSource", "err", err, "PatchCiMaterialSource", patchRequest) + common.WriteJsonResp(w, err, "source.type not supported", http.StatusBadRequest) return } token := r.Header.Get("token") if err = handler.authorizeCiSourceChangeRequest(w, patchRequest, token); err != nil { handler.Logger.Errorw("Authorization error, PatchCiMaterialSource", "err", err, "PatchCiMaterialSource", patchRequest) + common.WriteJsonResp(w, err, nil, http.StatusUnauthorized) return } diff --git a/api/restHandler/app/BuildPipelineRestHandler_test.go b/api/restHandler/app/BuildPipelineRestHandler_test.go index d2befef306e..8425b73f053 100644 --- a/api/restHandler/app/BuildPipelineRestHandler_test.go +++ b/api/restHandler/app/BuildPipelineRestHandler_test.go @@ -79,7 +79,7 @@ func TestPipelineConfigRestHandlerImpl_PatchCiMaterialSource(t *testing.T) { fields: fields{ validator: validator.New(), }, - body: "{\"appId\":4, \"id\": 5 ,\"ciMaterial\":[{\"gitMaterialId\":4,\"id\":5,\"source\":{\"type\":\"SOURCE_TYPE_BRANCH_FIXED\",\"value\":\"main3\",\"regex\":\"\"}}]}", + body: "{\"appId\":4, \"id\": 5 ,\"source\":{\"type\":\"SOURCE_TYPE_BRANCH_FIXED\",\"value\":\"main3\",\"regex\":\"\"}}", setup: func(fields2 *fields) { ctrl := gomock.NewController(t) fields2.pipelineBuilder = mock_pipeline.NewMockPipelineBuilder(ctrl) From 56b472a71797b1dbba7b9be87dff568e45db330d Mon Sep 17 00:00:00 2001 From: Avdhesh Kumar Date: Thu, 3 Aug 2023 14:25:19 +0530 Subject: [PATCH 9/9] Add Spec for /orchestrator/app/ci-pipeline/patch-source --- .../ci-pipeline-change-source.yaml | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 specs/ci-pipeline/ci-pipeline-change-source.yaml diff --git a/specs/ci-pipeline/ci-pipeline-change-source.yaml b/specs/ci-pipeline/ci-pipeline-change-source.yaml new file mode 100644 index 00000000000..b1a7c7d5b66 --- /dev/null +++ b/specs/ci-pipeline/ci-pipeline-change-source.yaml @@ -0,0 +1,44 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: CiPipeline material change source +paths: + /orchestrator/app/ci-pipeline/patch-source: + patch: + description: update source of a ci-matrial + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/RequestBody" + responses: + "200": + description: Successfully fetched commit info. if CommitInfo is null, then commit is not found. + content: + application/json: + schema: + type: object + +#{"appId": 16, "environmentId": 1, "source": {"type":"SOURCE_TYPE_BRANCH_FIXED", "value": "main1", "regex":""}} +# Components +components: + schemas: + RequestBody: + type: object + properties: + appId: + type: integer + environmentId: + type: integer + source: + type: object + properties: + type: + type: string + description: "SOURCE_TYPE_BRANCH_FIXED / SOURCE_TYPE_BRANCH_REGEX" + value: + type: string + description: "name of the branch" + regex: + type: string + description: "regular expression when type is SOURCE_TYPE_BRANCH_REGEX" \ No newline at end of file