This repository has been archived by the owner on Jul 13, 2020. It is now read-only.
/
tryToUpdateDependency.ts
207 lines (178 loc) · 6.52 KB
/
tryToUpdateDependency.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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
/*
* 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 {
automationClientInstance,
EditMode,
GitProject,
guid,
MessageOptions,
Parameter,
Parameters,
} from "@atomist/automation-client";
import {
CodeTransform,
CodeTransformRegistration,
formatDate,
spawnLog,
StringCapturingProgressLog,
} from "@atomist/sdm";
import { BuildAwareMarker } from "@atomist/sdm-pack-build";
import {
codeLine,
SlackMessage,
} from "@atomist/slack-messages";
export const AutoMergeCheckSuccessLabel = "auto-merge:on-check-success";
export const AutoMergeCheckSuccessTag = `[${AutoMergeCheckSuccessLabel}]`;
@Parameters()
export class UpdateDependencyParameters {
@Parameter({
displayName: "Desired NPM dist tag to update to",
description: "The desired NPM dist tag to update dependencies to",
pattern: /^.+$/,
required: false,
})
public tag: string = "latest";
@Parameter({
displayName: "NPM package to update",
description: "The NPM package to update",
pattern: /^.+$/,
required: true,
})
public package: string;
public commitMessage: string;
}
export const UpdateDependencyTransform: CodeTransform<UpdateDependencyParameters> =
async (p, ctx, params) => {
const tag = params.tag;
const range = (tag === "latest" ? "^" : "");
const pjFile = await p.getFile("package.json");
const pj = JSON.parse(await pjFile.getContent());
const versions = [];
const message: SlackMessage = {
text: `Updating ${codeLine(params.package)} NPM dependency of ${codeLine(pj.name)}`,
attachments: [{
text: "",
fallback: "Versions",
}],
};
const opts: MessageOptions = {
id: guid(),
};
const sendMessage = async (msg?: string) => {
if (msg) {
message.attachments[0].text = `${message.attachments[0].text}${msg}`;
message.attachments[0].footer =
`${automationClientInstance().configuration.name}:${automationClientInstance().configuration.version}`;
}
await ctx.context.messageClient.respond(message, opts);
};
await sendMessage();
if (pj.dependencies) {
await updateDependencies(pj.dependencies, params.package, tag, range, versions, sendMessage);
}
if (pj.devDependencies) {
await updateDependencies(pj.devDependencies, params.package, tag, range, versions, sendMessage);
}
await pjFile.setContent(`${JSON.stringify(pj, undefined, 2)}\n`);
if (!(await (p as GitProject).isClean())) {
await sendMessage(`\nVersion updated. Running ${codeLine("npm install")}`);
// NPM doesn't like to go back to older versions; hence we delete the lock file here to force the
// dependencies in
p.deleteFileSync("package-lock.json");
const result = await spawnLog(
"npm",
["i"],
{
cwd: (p as GitProject).baseDir,
env: {
...process.env,
NODE_ENV: "development",
},
log: new StringCapturingProgressLog(),
},
);
await sendMessage(result.code === 0 ?
`\n:atomist_build_passed: ${codeLine("npm install")} completed successfully` :
`\n:atomist_build_failed: ${codeLine("npm install")} failed`);
// Exit if npm install failed
if (result.code !== 0) {
return {
edited: false,
target: p,
success: false,
};
}
}
params.commitMessage = `Update ${params.package} dependency to tag ${params.tag}
${versions.join("\n")}
${BuildAwareMarker} ${AutoMergeCheckSuccessTag}`;
return p;
};
async function updateDependencies(deps: any,
pkg: string,
tag: string,
range: string,
versions: string[],
sendMessage: (msg?: string) => Promise<void>): Promise<void> {
for (const k in deps) {
if (deps.hasOwnProperty(k)) {
if (k === pkg) {
const oldVersion = deps[k];
const version = `${range}${await latestVersion(`${k}@${tag}`)}`;
if (version && oldVersion !== version) {
deps[k] = version;
versions.push(`${k} ${oldVersion} > ${version}`);
await sendMessage(
`:atomist_build_passed: Updated ${codeLine(k)} from ${codeLine(oldVersion)} to ${codeLine(version)}\n`);
}
}
}
}
}
async function latestVersion(module: string): Promise<string | undefined> {
const log = new StringCapturingProgressLog();
const result = await spawnLog(
"npm",
["show", module, "version"],
{
logCommand: false,
log,
});
if (result.code === 0) {
return log.log.trim();
}
return undefined;
}
export const TryToUpdateDependency: CodeTransformRegistration<UpdateDependencyParameters> = {
transform: UpdateDependencyTransform,
paramsMaker: UpdateDependencyParameters,
name: "UpdateDependency",
description: `Update NPM dependency`,
intent: ["update dependency", "update dep"],
transformPresentation: ci => {
return new BranchCommit(ci.parameters);
},
};
class BranchCommit implements EditMode {
constructor(private readonly params: UpdateDependencyParameters) {
}
get message(): string {
return this.params.commitMessage || "Update NPM dependency";
}
get branch(): string {
return `atomist-update-${this.params.tag}-${formatDate()}`;
}
}