Skip to content

Commit 070f95e

Browse files
authored
fix(api,ui): resync as code when application is not ascode (#5093)
1 parent b83d05d commit 070f95e

File tree

7 files changed

+55
-48
lines changed

7 files changed

+55
-48
lines changed

engine/api/ascode.go

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -214,28 +214,25 @@ func (api *API) postResyncPRAsCodeHandler() service.Handler {
214214
if errP != nil {
215215
return sdk.WrapError(errP, "unable to load project")
216216
}
217-
var app *sdk.Application
218-
if fromRepo != "" {
219-
apps, err := application.LoadAsCode(api.mustDB(), api.Cache, key, fromRepo)
217+
var app sdk.Application
218+
switch {
219+
case appName != "":
220+
appP, err := application.LoadByName(api.mustDB(), api.Cache, key, appName)
220221
if err != nil {
221222
return err
222223
}
223-
if len(apps) == 0 {
224-
return sdk.WrapError(sdk.ErrApplicationNotFound, "unable to load application as code key:%s fromRepo:%s", key, fromRepo)
225-
}
226-
app = &apps[0]
227-
} else {
228-
var err error
229-
app, err = application.LoadByName(api.mustDB(), api.Cache, key, appName)
224+
app = *appP
225+
case fromRepo != "":
226+
wkf, err := workflow.LoadByRepo(ctx, api.Cache, api.mustDB(), *proj, fromRepo)
230227
if err != nil {
231228
return err
232229
}
233-
if app == nil {
234-
return sdk.WrapError(sdk.ErrApplicationNotFound, "unable to load application %s", appName)
235-
}
230+
app = wkf.Applications[wkf.WorkflowData.Node.Context.ApplicationID]
231+
default:
232+
return sdk.WrapError(sdk.ErrWrongRequest, "Missing appName or repo query parameter")
236233
}
237234

238-
if _, _, err := sync.SyncAsCodeEvent(ctx, api.mustDB(), api.Cache, *proj, *app, getAPIConsumer(ctx).AuthentifiedUser); err != nil {
235+
if _, _, err := sync.SyncAsCodeEvent(ctx, api.mustDB(), api.Cache, *proj, app, getAPIConsumer(ctx).AuthentifiedUser); err != nil {
239236
return err
240237
}
241238
return nil

engine/api/ascode_test.go

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -310,12 +310,14 @@ func Test_postResyncPRAsCodeHandler(t *testing.T) {
310310
api, db, _, end := newTestAPI(t)
311311
defer end()
312312

313+
repoURL := sdk.RandomString(10)
314+
313315
u, pass := assets.InsertAdminUser(t, db)
314316
pkey := sdk.RandomString(10)
315317
p := assets.InsertTestProject(t, db, api.Cache, pkey, pkey)
316318

317319
// Clean as code event
318-
as, err := ascode.LoadAsCodeEventByRepo(context.TODO(), db, "urltomyrepo")
320+
as, err := ascode.LoadAsCodeEventByRepo(context.TODO(), db, repoURL)
319321
assert.NoError(t, err)
320322
for _, a := range as {
321323
assert.NoError(t, ascode.DeleteAsCodeEvent(db, a))
@@ -341,7 +343,7 @@ vcs_ssh_key: proj-blabla
341343
app, _, globalError := application.ParseAndImport(context.Background(), db, api.Cache, *p, eapp, application.ImportOptions{Force: true}, nil, u)
342344
assert.NoError(t, globalError)
343345

344-
app.FromRepository = "urltomyrepo"
346+
app.FromRepository = repoURL
345347
assert.NoError(t, application.Update(db, api.Cache, app))
346348

347349
//First pipeline
@@ -353,20 +355,21 @@ vcs_ssh_key: proj-blabla
353355
test.NoError(t, pipeline.InsertPipeline(db, &pip))
354356

355357
wf := sdk.Workflow{
356-
Name: sdk.RandomString(10),
357-
ProjectID: p.ID,
358-
ProjectKey: p.Key,
358+
Name: sdk.RandomString(10),
359+
ProjectID: p.ID,
360+
ProjectKey: p.Key,
361+
FromRepository: repoURL,
359362
WorkflowData: sdk.WorkflowData{
360363
Node: sdk.Node{
361364
Name: "root",
362365
Type: sdk.NodeTypePipeline,
363366
Context: &sdk.NodeContext{
364-
PipelineID: pip.ID,
367+
PipelineID: pip.ID,
368+
ApplicationID: app.ID,
365369
},
366370
},
367371
},
368372
}
369-
370373
proj2, errP := project.Load(api.mustDB(), api.Cache, p.Key, project.LoadOptions.WithPipelines, project.LoadOptions.WithGroups, project.LoadOptions.WithIntegrations)
371374
require.NoError(t, errP)
372375
require.NoError(t, workflow.Insert(context.TODO(), db, api.Cache, *proj2, &wf))
@@ -416,7 +419,7 @@ vcs_ssh_key: proj-blabla
416419
asCodeEvent := sdk.AsCodeEvent{
417420
Username: u.GetUsername(),
418421
CreateDate: time.Now(),
419-
FromRepo: "urltomyrepo",
422+
FromRepo: repoURL,
420423
Migrate: true,
421424
PullRequestID: 666,
422425
PullRequestURL: "urltomypr",
@@ -438,7 +441,7 @@ vcs_ssh_key: proj-blabla
438441
"key": pkey,
439442
})
440443

441-
uri = fmt.Sprintf("%s?appName=blabla&repo=urltomyrepo", uri)
444+
uri = fmt.Sprintf("%s?repo=%s", uri, repoURL)
442445
req, err := http.NewRequest("POST", uri, nil)
443446
test.NoError(t, err)
444447
assets.AuthentifyRequest(t, req, u, pass)
@@ -450,12 +453,12 @@ vcs_ssh_key: proj-blabla
450453
t.Logf(w.Body.String())
451454

452455
// Check there is no more events in db
453-
assDB, err := ascode.LoadAsCodeEventByRepo(context.TODO(), db, "urltomyrepo")
456+
assDB, err := ascode.LoadAsCodeEventByRepo(context.TODO(), db, repoURL)
454457
assert.NoError(t, err)
455458
assert.Equal(t, 0, len(assDB))
456459

457460
// Check workflow has been migrated
458461
wUpdated, err := workflow.Load(context.TODO(), db, api.Cache, *p, wf.Name, workflow.LoadOptions{})
459462
assert.NoError(t, err)
460-
assert.Equal(t, "urltomyrepo", wUpdated.FromRepository)
463+
assert.Equal(t, repoURL, wUpdated.FromRepository)
461464
}

engine/api/workflow/dao.go

Lines changed: 13 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -99,26 +99,21 @@ func Exists(db gorp.SqlExecutor, key string, name string) (bool, error) {
9999
return count > 0, nil
100100
}
101101

102-
// CountVariableInWorkflow counts how many time the given variable is used on all workflows of the given project
103-
func CountVariableInWorkflow(db gorp.SqlExecutor, projectKey string, varName string) ([]CountVarInWorkflowData, error) {
102+
func LoadByRepo(ctx context.Context, store cache.Store, db gorp.SqlExecutor, proj sdk.Project, repo string) (*sdk.Workflow, error) {
104103
query := `
105-
SELECT DISTINCT workflow.name as workflow_name, w_node.name as node_name
106-
FROM workflow
107-
JOIN project ON project.id = workflow.project_id
108-
JOIN w_node ON w_node.workflow_id = workflow.id
109-
JOIN w_node_context ON w_node_context.node_id = w_node.id
110-
WHERE project.projectkey = $1
111-
AND (
112-
w_node_context.default_pipeline_parameters::TEXT LIKE $2
113-
OR
114-
w_node_context.default_payload::TEXT LIKE $2
115-
);
116-
`
117-
var datas []CountVarInWorkflowData
118-
if _, err := db.Select(&datas, query, projectKey, fmt.Sprintf("%%%s%%", varName)); err != nil {
119-
return nil, sdk.WrapError(err, "Unable to count var in workflow")
104+
SELECT workflow.*
105+
FROM workflow
106+
JOIN project ON project.id = workflow.project_id
107+
WHERE project.projectkey = $1 AND workflow.from_repository = $2
108+
LIMIT 1`
109+
w, err := load(ctx, db, proj, LoadOptions{}, query, proj.Key, repo)
110+
if err != nil {
111+
return nil, err
120112
}
121-
return datas, nil
113+
if err := IsValid(ctx, store, db, w, proj, LoadOptions{}); err != nil {
114+
return nil, sdk.WrapError(err, "Unable to valid workflow")
115+
}
116+
return w, nil
122117
}
123118

124119
// UpdateIcon update the icon of a workflow

ui/src/app/shared/diff/diff.ts

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,8 @@ export function calculateWorkflowTemplateDiff(before: WorkflowTemplate, after: W
4141
}
4242
];
4343

44-
let pipelinesLength = Math.max(before && before.pipelines ? before.pipelines.length : 0, after && after.pipelines ? after.pipelines.length : 0);
44+
let pipelinesLength = Math.max(before && before.pipelines ?
45+
before.pipelines.length : 0, after && after.pipelines ? after.pipelines.length : 0);
4546
for (let i = 0; i < pipelinesLength; i++) {
4647
diffItems.push(
4748
<Item>{
@@ -62,7 +63,8 @@ export function calculateWorkflowTemplateDiff(before: WorkflowTemplate, after: W
6263
<Item>{
6364
translate: 'workflow_template_diff_application',
6465
translateData: { number: applicationsLength > 1 ? i : '' },
65-
before: before && before.applications && before.applications[i] ? Base64.b64DecodeUnicode(before.applications[i].value) : null,
66+
before: before && before.applications && before.applications[i] ?
67+
Base64.b64DecodeUnicode(before.applications[i].value) : null,
6668
after: after && after.applications && after.applications[i] ? Base64.b64DecodeUnicode(after.applications[i].value) : null,
6769
type: 'text/x-yaml'
6870
})
@@ -77,7 +79,8 @@ export function calculateWorkflowTemplateDiff(before: WorkflowTemplate, after: W
7779
<Item>{
7880
translate: 'workflow_template_diff_environment',
7981
translateData: { number: environmentsLength > 1 ? i : '' },
80-
before: before && before.environments && before.environments[i] ? Base64.b64DecodeUnicode(before.environments[i].value) : null,
82+
before: before && before.environments && before.environments[i] ?
83+
Base64.b64DecodeUnicode(before.environments[i].value) : null,
8184
after: after && after.environments && after.environments[i] ? Base64.b64DecodeUnicode(after.environments[i].value) : null,
8285
type: 'text/x-yaml'
8386
})

ui/src/app/store/pipelines.state.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { Job } from 'app/model/job.model';
44
import { Parameter } from 'app/model/parameter.model';
55
import { Pipeline, PipelineAudit } from 'app/model/pipeline.model';
66
import { PipelineService } from 'app/service/pipeline/pipeline.service';
7+
import * as actionAsCode from 'app/store/ascode.action';
78
import { cloneDeep } from 'lodash-es';
89
import { tap } from 'rxjs/operators';
910
import * as actionPipeline from './pipelines.action';
@@ -581,4 +582,12 @@ export class PipelinesState {
581582
editMode: editMode,
582583
});
583584
}
585+
586+
@Action(actionAsCode.ResyncEvents)
587+
refreshAsCodeEvents(ctx: StateContext<PipelinesStateModel>, _) {
588+
const state = ctx.getState();
589+
if (state.pipeline) {
590+
ctx.dispatch(new actionPipeline.ResyncPipeline({projectKey: state.currentProjectKey, pipelineName: state.pipeline.name}));
591+
}
592+
}
584593
}

ui/src/app/views/pipeline/show/pipeline.show.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
[remote]="remote" [branch]="branch">
77
<div class="right floated labelFeature" [title]="'workflow_from_repository_btn' | translate">
88
<a class="ui label small basic"
9-
[class.green]="pipeline && pipeline.from_repository && !pipeline.ascode_events"
9+
[class.green]="pipeline && pipeline.from_repository && (!pipeline.ascode_events || pipeline.ascode_events.length ===0)"
1010
[class.orange]="pipeline && pipeline.from_repository && pipeline?.ascode_events?.length > 0"
1111
suiPopup
1212
[popupTemplate]="popupFromRepository" popupPlacement="bottom right" popupTrigger="outsideClick"

ui/src/app/views/workflow/workflow.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
<ng-container
2020
*ngIf="workflow && (workflow.from_repository || (workflow.as_code_events && workflow.as_code_events.length > 0))">
2121
<app-ascode-event [events]="workflow.as_code_events" [repo]="workflow.from_repository"
22-
[appName]="workflow.applications[workflow.workflow_data.node.context.application_id].name"
22+
[appName]="workflow.applications[workflow.workflow_data.node.context.application_id]?.name"
2323
[project]="project"></app-ascode-event>
2424
</ng-container>
2525
<ng-container

0 commit comments

Comments
 (0)