forked from pascalgn/npm-publish-action
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
executable file
·243 lines (202 loc) · 6.2 KB
/
index.js
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
#!/usr/bin/env node
const process = require("process");
const { join, dirname } = require("path");
const { spawn } = require("child_process");
const { readFile } = require("fs");
var glob = require("glob");
async function main() {
const dir = getEnv("WORKSPACE");
if (!dir) {
throw new Error(
"Missing workspace for your monorepo packages - usually set to ./packages"
);
}
const eventFile =
process.env.GITHUB_EVENT_PATH || "/github/workflow/event.json";
const eventObj = await readJson(eventFile);
const commitPattern =
getEnv("COMMIT_PATTERN") || "^(?:Release|Version) (\\S+)";
const versionFrom = getEnv("VERSION_FROM") || ".";
const createTagFlag = getEnv("CREATE_TAG") !== "false";
const publishCommand = getEnv("PUBLISH_COMMAND") || "yarn";
const publishArgs = arrayEnv("PUBLISH_ARGS");
const { name, email } = eventObj.repository.owner;
const packagesVersion = await getVersion(versionFrom);
const config = {
commitPattern,
createTag: createTagFlag,
tagName: placeholderEnv("TAG_NAME", "v%s"),
tagMessage: placeholderEnv("TAG_MESSAGE", "v%s"),
tagAuthor: { name, email },
publishCommand,
publishArgs,
packagesVersion
};
console.log("Init release with config", config);
const foundCommit = checkCommit(config, eventObj.commits);
console.log("Publish all packages in folder");
const files = glob.sync(join(dir, "/**/package.json"));
if (files.length == 0) {
return console.error("Invalid workspace: " + dir);
}
for (const file of files) {
console.log("Publishing " + dirname(file));
await publishPackage(dirname(file), config, config.packagesVersion);
console.log("Publishing current package done");
}
if (config.createTag) {
console.log("Creating tag: " + packagesVersion);
await createTag(dir, config, packagesVersion);
}
setOutput("changed", "true");
setOutput("version", packagesVersion);
setOutput("commit", foundCommit.sha);
}
function getEnv(name) {
return process.env[name] || process.env[`INPUT_${name}`];
}
function placeholderEnv(name, defaultValue) {
const str = getEnv(name);
if (!str) {
return defaultValue;
} else if (!str.includes("%s")) {
throw new Error(`missing placeholder in variable: ${name}`);
} else {
return str;
}
}
function arrayEnv(name) {
const str = getEnv(name);
return str ? str.split(" ") : [];
}
async function getVersion(dir) {
const packageFile = join(dir, "package.json");
const packageObj = await readJson(packageFile).catch(() =>
Promise.reject(
new NeutralExitError(`package file not found: ${packageFile}`)
)
);
if (packageObj == null || packageObj.version == null) {
throw new Error("missing version field!");
}
const { version } = packageObj;
return version;
}
function checkCommit(config, commits) {
for (const commit of commits) {
const match = commit.message.match(config.commitPattern);
if (match && match[1]) {
console.log(`Found release commit: ${commit.message}`);
if (match[1] === config.packagesVersion) {
return commit;
} else {
console.log(
`Release commit doesn't match current version:
${match[1]} != ${config.packagesVersion}`
);
}
}
}
console.log(`No release commit found in : ${JSON.stringify(commits)}`);
throw new NeutralExitError(
`No commit found for version: ${config.packagesVersion}`
);
}
async function readJson(file) {
const data = await new Promise((resolve, reject) =>
readFile(file, "utf8", (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
})
);
return JSON.parse(data);
}
async function createTag(dir, config, version) {
const tagName = config.tagName.replace(/%s/g, version);
const tagMessage = config.tagMessage.replace(/%s/g, version);
const tagExists = await run(
dir,
"git",
"rev-parse",
"-q",
"--verify",
`refs/tags/${tagName}`
).catch(e =>
e instanceof ExitError && e.code === 1 ? false : Promise.reject(e)
);
if (tagExists) {
console.log(`Tag already exists: ${tagName}`);
throw new NeutralExitError();
}
const { name, email } = config.tagAuthor;
await run(dir, "git", "config", "user.name", name);
await run(dir, "git", "config", "user.email", email);
await run(dir, "git", "tag", "-a", "-m", tagMessage, tagName);
await run(dir, "git", "push", "origin", `refs/tags/${tagName}`);
console.log("Tag has been created successfully:", tagName);
}
async function publishPackage(dir, config, version) {
const { publishArgs } = config;
const cmd = [
"yarn",
"publish",
"--non-interactive",
"--new-version",
version
];
await run(dir, ...cmd, ...publishArgs);
console.log("Version has been published successfully:", version, dir);
}
function setOutput(name, value = "") {
const out = `name=${encodeURIComponent(name)}::${encodeURIComponent(value)}`;
console.log(`::set-output ${out}`);
}
function run(cwd, command, ...args) {
console.log("Executing:", command, args.join(" "));
return new Promise((resolve, reject) => {
const proc = spawn(command, args, {
cwd,
stdio: ["ignore", "ignore", "pipe"]
});
const buffers = [];
proc.stderr.on("data", data => buffers.push(data));
proc.on("error", () => {
reject(new Error(`command failed: ${command}`));
});
proc.on("exit", code => {
if (code === 0) {
resolve(true);
} else {
const stderr = Buffer.concat(buffers).toString("utf8").trim();
if (stderr) {
console.log(`command failed with code ${code}`);
console.log(stderr);
}
reject(new ExitError(code));
}
});
});
}
class ExitError extends Error {
constructor(code) {
super(`command failed with code ${code}`);
this.code = code;
}
}
class NeutralExitError extends Error {}
if (require.main === module) {
main().catch(e => {
setOutput("changed", false);
if (e instanceof NeutralExitError) {
// GitHub removed support for neutral exit code:
// https://twitter.com/ethomson/status/1163899559279497217
process.exitCode = 0;
} else {
process.exitCode = 1;
console.log(e.message || e);
}
});
}