-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
release-publish.impl.ts
271 lines (244 loc) · 8.16 KB
/
release-publish.impl.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
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
import { ExecutorContext, readJsonFile } from '@nx/devkit';
import { execSync } from 'child_process';
import { env as appendLocalEnv } from 'npm-run-path';
import { join } from 'path';
import { parseRegistryOptions } from '../../utils/npm-config';
import { logTar } from './log-tar';
import { PublishExecutorSchema } from './schema';
import chalk = require('chalk');
const LARGE_BUFFER = 1024 * 1000000;
function processEnv(color: boolean) {
const env = {
...process.env,
...appendLocalEnv(),
};
if (color) {
env.FORCE_COLOR = `${color}`;
}
return env;
}
export default async function runExecutor(
options: PublishExecutorSchema,
context: ExecutorContext
) {
/**
* We need to check both the env var and the option because the executor may have been triggered
* indirectly via dependsOn, in which case the env var will be set, but the option will not.
*/
const isDryRun = process.env.NX_DRY_RUN === 'true' || options.dryRun || false;
const projectConfig =
context.projectsConfigurations!.projects[context.projectName!]!;
const packageRoot = join(
context.root,
options.packageRoot ?? projectConfig.root
);
const packageJsonPath = join(packageRoot, 'package.json');
const packageJson = readJsonFile(packageJsonPath);
const packageName = packageJson.name;
// If package and project name match, we can make log messages terser
let packageTxt =
packageName === context.projectName
? `package "${packageName}"`
: `package "${packageName}" from project "${context.projectName}"`;
if (packageJson.private === true) {
console.warn(
`Skipped ${packageTxt}, because it has \`"private": true\` in ${packageJsonPath}`
);
return {
success: true,
};
}
const warnFn = (message: string) => {
console.log(chalk.keyword('orange')(message));
};
const { registry, tag, registryConfigKey } = await parseRegistryOptions(
context.root,
{
packageRoot,
packageJson,
},
{
registry: options.registry,
tag: options.tag,
},
warnFn
);
const npmViewCommandSegments = [
`npm view ${packageName} versions dist-tags --json --"${registryConfigKey}=${registry}"`,
];
const npmDistTagAddCommandSegments = [
`npm dist-tag add ${packageName}@${packageJson.version} ${tag} --"${registryConfigKey}=${registry}"`,
];
/**
* In a dry-run scenario, it is most likely that all commands are being run with dry-run, therefore
* the most up to date/relevant version might not exist on disk for us to read and make the npm view
* request with.
*
* Therefore, so as to not produce misleading output in dry around dist-tags being altered, we do not
* perform the npm view step, and just show npm publish's dry-run output.
*/
if (!isDryRun && !options.firstRelease) {
const currentVersion = packageJson.version;
try {
const result = execSync(npmViewCommandSegments.join(' '), {
env: processEnv(true),
cwd: context.root,
stdio: ['ignore', 'pipe', 'pipe'],
});
const resultJson = JSON.parse(result.toString());
const distTags = resultJson['dist-tags'] || {};
if (distTags[tag] === currentVersion) {
console.warn(
`Skipped ${packageTxt} because v${currentVersion} already exists in ${registry} with tag "${tag}"`
);
return {
success: true,
};
}
if (resultJson.versions.includes(currentVersion)) {
try {
if (!isDryRun) {
execSync(npmDistTagAddCommandSegments.join(' '), {
env: processEnv(true),
cwd: context.root,
stdio: 'ignore',
});
console.log(
`Added the dist-tag ${tag} to v${currentVersion} for registry ${registry}.\n`
);
} else {
console.log(
`Would add the dist-tag ${tag} to v${currentVersion} for registry ${registry}, but ${chalk.keyword(
'orange'
)('[dry-run]')} was set.\n`
);
}
return {
success: true,
};
} catch (err) {
try {
const stdoutData = JSON.parse(err.stdout?.toString() || '{}');
// If the error is that the package doesn't exist, then we can ignore it because we will be publishing it for the first time in the next step
if (
!(
stdoutData.error?.code?.includes('E404') &&
stdoutData.error?.summary?.includes('no such package available')
) &&
!(
err.stderr?.toString().includes('E404') &&
err.stderr?.toString().includes('no such package available')
)
) {
console.error('npm dist-tag add error:');
if (stdoutData.error.summary) {
console.error(stdoutData.error.summary);
}
if (stdoutData.error.detail) {
console.error(stdoutData.error.detail);
}
if (context.isVerbose) {
console.error('npm dist-tag add stdout:');
console.error(JSON.stringify(stdoutData, null, 2));
}
return {
success: false,
};
}
} catch (err) {
console.error(
'Something unexpected went wrong when processing the npm dist-tag add output\n',
err
);
return {
success: false,
};
}
}
}
} catch (err) {
const stdoutData = JSON.parse(err.stdout?.toString() || '{}');
// If the error is that the package doesn't exist, then we can ignore it because we will be publishing it for the first time in the next step
if (
!(
stdoutData.error?.code?.includes('E404') &&
stdoutData.error?.summary?.toLowerCase().includes('not found')
) &&
!(
err.stderr?.toString().includes('E404') &&
err.stderr?.toString().toLowerCase().includes('not found')
)
) {
console.error(
`Something unexpected went wrong when checking for existing dist-tags.\n`,
err
);
return {
success: false,
};
}
}
}
if (options.firstRelease && context.isVerbose) {
console.log('Skipped npm view because --first-release was set');
}
const npmPublishCommandSegments = [
`npm publish ${packageRoot} --json --"${registryConfigKey}=${registry}" --tag=${tag}`,
];
if (options.otp) {
npmPublishCommandSegments.push(`--otp=${options.otp}`);
}
if (isDryRun) {
npmPublishCommandSegments.push(`--dry-run`);
}
try {
const output = execSync(npmPublishCommandSegments.join(' '), {
maxBuffer: LARGE_BUFFER,
env: processEnv(true),
cwd: context.root,
stdio: ['ignore', 'pipe', 'pipe'],
});
const stdoutData = JSON.parse(output.toString());
// If npm workspaces are in use, the publish output will nest the data under the package name, so we normalize it first
const normalizedStdoutData = stdoutData[packageName] ?? stdoutData;
logTar(normalizedStdoutData);
if (isDryRun) {
console.log(
`Would publish to ${registry} with tag "${tag}", but ${chalk.keyword(
'orange'
)('[dry-run]')} was set`
);
} else {
console.log(`Published to ${registry} with tag "${tag}"`);
}
return {
success: true,
};
} catch (err) {
try {
const stdoutData = JSON.parse(err.stdout?.toString() || '{}');
console.error('npm publish error:');
if (stdoutData.error.summary) {
console.error(stdoutData.error.summary);
}
if (stdoutData.error.detail) {
console.error(stdoutData.error.detail);
}
if (context.isVerbose) {
console.error('npm publish stdout:');
console.error(JSON.stringify(stdoutData, null, 2));
}
return {
success: false,
};
} catch (err) {
console.error(
'Something unexpected went wrong when processing the npm publish output\n',
err
);
return {
success: false,
};
}
}
}