-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathcopy.ts
More file actions
182 lines (148 loc) · 5.98 KB
/
Copy pathcopy.ts
File metadata and controls
182 lines (148 loc) · 5.98 KB
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
/* eslint-disable import/no-dynamic-require */
import { execSync } from 'node:child_process';
import { copyFileSync, readFileSync, writeFileSync } from 'node:fs';
import { createRequire } from 'node:module';
import { resolve } from 'node:path';
const require = createRequire(import.meta.url);
const options = process.argv.slice(2).reduce((args, arg) => {
const [key, value] = arg.split('=');
args[key.substring(2)] = value ?? true;
return args;
}, {} as any);
function copy(filename: string, from: string, to: string): void {
copyFileSync(resolve(from, filename), resolve(to, filename));
}
function rewrite(path: string, replacer: (from: string) => string): void {
try {
const file = readFileSync(path).toString();
const replaced = replacer(file);
writeFileSync(path, replaced);
} catch {
// not found
}
}
let rootVersion: string;
function getRootVersion(bump = true): string {
if (rootVersion) {
return rootVersion;
}
const pkg = require(resolve(root, './lerna.json'));
rootVersion = pkg.version.replace(/^(\d+\.\d+\.\d+)-?.*$/, '$1');
if (bump) {
const parts = rootVersion.split('.');
const inc = bump ? 1 : 0;
const canary = String(options.canary).toLowerCase();
switch (canary) {
case 'major': {
parts[0] = `${+parts[0] + inc}`;
parts[1] = '0';
parts[2] = '0';
break;
}
case 'minor': {
parts[1] = `${+parts[0] + inc}`;
parts[2] = '0';
break;
}
case 'patch':
default:
parts[2] = `${+parts[2] + inc}`;
}
rootVersion = parts.join('.');
}
return rootVersion;
}
/**
* Checks next dev version number based on the `crawlee` meta package via `npm show`.
* We always use this package, so we ensure the version is the same for each package in the monorepo.
*/
function getNextVersion() {
const versions: string[] = [];
try {
const versionString = execSync(`npm show @crawlee/core versions --json`, { encoding: 'utf8', stdio: 'pipe' });
const parsed = JSON.parse(versionString) as string[];
versions.push(...parsed);
} catch {
// the package might not have been published yet
}
const version = getRootVersion();
if (versions.some((v) => v === version)) {
console.error(
`before-deploy: A release with version ${version} already exists. Please increment version accordingly.`,
);
process.exit(1);
}
const preid = options.preid ?? 'alpha';
const prereleaseNumbers = versions
.filter((v) => v.startsWith(`${version}-${preid}.`))
.map((v) => Number(v.match(/\.(\d+)$/)?.[1]));
const lastPrereleaseNumber = Math.max(-1, ...prereleaseNumbers);
return `${version}-${preid}.${lastPrereleaseNumber + 1}`;
}
// optionalDependencies too, otherwise `workspace:^` on @crawlee/impit-client publishes as a floating `^` range
function pinInternalDeps(pkgJson: any, version: string): void {
for (const deps of [pkgJson.dependencies, pkgJson.optionalDependencies]) {
for (const dep of Object.keys(deps ?? {})) {
if ((dep.startsWith('@crawlee/') && dep !== '@crawlee/fs-storage-native') || dep === 'crawlee') {
const prefix = deps[dep].startsWith('^') ? '^' : '';
deps[dep] = prefix + version;
}
}
}
}
// as we publish only the dist folder, we need to copy some meta files inside (readme/license/package.json)
// also changes paths inside the copied `package.json` (`dist/index.js` -> `index.js`)
const root = resolve(import.meta.dirname, '..');
const target = resolve(process.cwd(), 'dist');
const pkgPath = resolve(process.cwd(), 'package.json');
if (options.canary) {
const pkgJson = require(pkgPath);
const nextVersion = getNextVersion();
pkgJson.version = nextVersion;
pinInternalDeps(pkgJson, nextVersion);
console.info(`canary: setting version to ${nextVersion}`);
writeFileSync(pkgPath, `${JSON.stringify(pkgJson, null, 4)}\n`);
}
if (options['pin-versions']) {
const pkgJson = require(pkgPath);
const version = getRootVersion(false);
pinInternalDeps(pkgJson, version);
console.info(`pin-versions: version ${version}`, pkgJson.dependencies);
writeFileSync(pkgPath, `${JSON.stringify(pkgJson, null, 4)}\n`);
}
/**
* `catalog:` specifiers are a pnpm workspace feature; lerna publishes the manifest verbatim,
* so they have to be inlined with the versions from `pnpm-workspace.yaml` before publishing.
*/
function getCatalogVersions(): Record<string, string> {
const workspaceYaml = readFileSync(resolve(root, 'pnpm-workspace.yaml')).toString();
const catalogBlock = workspaceYaml.match(/^catalog:\n((?: {2}.+\n)+)/m)?.[1] ?? '';
const versions: Record<string, string> = {};
for (const line of catalogBlock.split('\n')) {
const match = line.match(/^ {2}["']?([^"':]+)["']?:\s*["']?(.+?)["']?\s*$/);
if (match) versions[match[1]] = match[2];
}
return versions;
}
copy('README.md', root, target);
copy('LICENSE.md', root, target);
copy('package.json', process.cwd(), target);
rewrite(resolve(target, 'package.json'), (pkg) => {
const catalog = getCatalogVersions();
const manifest = JSON.parse(pkg.replace(/dist\//g, '').replace(/src\/(.*)\.ts/g, '$1.js'));
for (const deps of [
manifest.dependencies,
manifest.devDependencies,
manifest.peerDependencies,
manifest.optionalDependencies,
]) {
for (const dep of Object.keys(deps ?? {})) {
if (deps[dep] === 'catalog:') {
if (!catalog[dep]) throw new Error(`Missing catalog entry for '${dep}' in pnpm-workspace.yaml`);
deps[dep] = catalog[dep];
}
}
}
return `${JSON.stringify(manifest, null, 4)}\n`;
});
rewrite(resolve(target, 'utils.js'), (pkg) => pkg.replace('../package.json', './package.json'));