This repository has been archived by the owner on Jun 22, 2020. It is now read-only.
/
Artifact.ts
184 lines (169 loc) · 6.64 KB
/
Artifact.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
/*
* Copyright © 2019 Atomist, 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.
*/
import {
EventFired,
GraphQL,
HandlerContext,
HandlerResult,
logger,
Success,
} from "@atomist/automation-client";
import { generateHash } from "@atomist/automation-client/lib/internal/util/string";
import {
addressChannelsFor,
ArtifactListenerInvocation,
ArtifactListenerRegisterable,
DefaultGoalNameGenerator,
fetchGoalsForCommit,
FulfillableGoalDetails,
FulfillableGoalWithRegistrations,
getGoalDefinitionFrom,
Goal,
goalCorrespondsToSdmGoal,
IndependentOfEnvironment,
PushListenerInvocation,
resolveCredentialsPromise,
SdmGoalState,
SideEffect,
SoftwareDeliveryMachine,
toArtifactListenerRegistration,
updateGoal,
} from "@atomist/sdm";
import * as _ from "lodash";
import { OnImageLinked } from "./typings/types";
export interface ArtifactRegistration {
listeners?: ArtifactListenerRegisterable[];
}
/**
* This goal is fulfilled by an OnImageLinked event subscription. The Build goal will
* cause such an event to be emitted, but external CI systems can trigger the goal
* fulfillment as well. On fulfillment, the external URL for the artifact will be
* put on the goal instance and shown in the client.
*
* You can register listeners on this event to trigger when a new artifact is available
* through this goal.
*/
export class Artifact extends FulfillableGoalWithRegistrations<ArtifactRegistration> {
constructor(goalDetailsOrUniqueName: FulfillableGoalDetails | string
= DefaultGoalNameGenerator.generateName("artifact"),
...dependsOn: Goal[]) {
super({
...ArtifactGoal.definition,
...getGoalDefinitionFrom(goalDetailsOrUniqueName, DefaultGoalNameGenerator.generateName("artifact")),
displayName: "artifact",
}, ...dependsOn);
const fulfillment: SideEffect = { name: "build" };
this.addFulfillment(fulfillment);
}
public register(sdm: SoftwareDeliveryMachine): void {
super.register(sdm);
sdm.addEvent({
name: `OnImageLinkedHandler${generateHash(this.definition.uniqueName)}`,
description: `Handle image link events for goal ${this.definition.uniqueName}`,
subscription: GraphQL.subscription("OnImageLinked"),
listener: (event, context) => this.handle(event, context, this),
});
}
private async handle(event: EventFired<OnImageLinked.Subscription>,
context: HandlerContext,
goal: Artifact): Promise<HandlerResult> {
const imageLinked = event.data.ImageLinked[0];
const commit = imageLinked.commit;
const image = imageLinked.image;
const id = goal.sdm.configuration.sdm.repoRefResolver.toRemoteRepoRef(
commit.repo,
{
sha: commit.sha,
branch: commit.pushes[0].branch,
});
const goals = await fetchGoalsForCommit(
context,
id,
commit.repo.org.provider.providerId);
if (!goals) {
return Success;
}
if (goal.registrations.length > 0) {
const credentials = await resolveCredentialsPromise(
goal.sdm.configuration.sdm.credentialsResolver.eventHandlerCredentials(context, id));
logger.info("Scanning artifact for %j", id);
const deployableArtifact = await goal.sdm.configuration.sdm.artifactStore.checkout(
image.imageName,
id,
credentials);
const addressChannels = addressChannelsFor(commit.repo, context);
const preferences = goal.sdm.configuration.sdm.preferenceStoreFactory(context);
const configuration = goal.sdm.configuration;
await goal.sdm.configuration.sdm.projectLoader.doWithProject({
credentials,
id,
context,
readOnly: true,
}, async project => {
// TODO only handles first push
const pli: PushListenerInvocation = {
id,
context,
credentials,
addressChannels,
preferences,
push: commit.pushes[0],
project,
configuration,
} as any;
const ai: ArtifactListenerInvocation = {
id,
context,
addressChannels,
preferences,
deployableArtifact,
credentials,
configuration,
};
if (!!goal.registrations) {
const listeners = goal.registrations.length > 0 ?
_.flatten(goal.registrations.map(r => !!r.listeners ? r.listeners : [])) :
[];
logger.info("About to invoke %d ArtifactListener registrations", listeners.length);
await Promise.all(
listeners
.map(toArtifactListenerRegistration)
.filter(async arl => !arl.pushTest || !!(await arl.pushTest.mapping(pli)))
.map(l => l.action(ai)));
}
});
}
const artifactGoals = goals.filter(g => goalCorrespondsToSdmGoal(goal, g));
for (const artifactGoal of artifactGoals) {
await updateGoal(context, artifactGoal, {
state: SdmGoalState.success,
description: goal.successDescription,
externalUrls: [{
label: "Image",
url: image.imageName,
}],
});
logger.info("Updated artifact goal '%s' of goalSet '%s'", artifactGoal.name, artifactGoal.goalSetId);
}
return Success;
}
}
const ArtifactGoal = new Goal({
uniqueName: "artifact",
environment: IndependentOfEnvironment,
displayName: "store artifact",
completedDescription: "Stored artifact",
});