forked from novuhq/novu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpnpm-context.mjs
253 lines (222 loc) · 6.53 KB
/
pnpm-context.mjs
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
#!/usr/bin/env node
/*
* Beware this script fails when run directly from shell, it must be run via package.json.
* I believe this is a bug, see https://github.com/pnpm/pnpm/issues/3726 for details.
*/
import meow from 'meow';
import os from 'os';
import { basename, dirname, join, relative, resolve } from 'path';
import { create as createTar } from 'tar';
import { globby } from 'globby';
import { parsePackageSelector, readProjects } from '@pnpm/filter-workspace-packages';
import { pipe as rawPipe } from 'mississippi';
import { promises as fs } from 'fs';
import { promisify } from 'util';
const pipe = promisify(rawPipe);
const SCRIPT_PATH = basename(process.argv[1]);
const cli = meow(
`
Usage
$ ${SCRIPT_PATH} [--patterns=regex]... [--list-files] <Dockerfile-path>
Options
--list-files, -l Don't generate tar, just list files. Useful for debugging.
--patterns, -p Additional .gitignore-like patterns used to find/exclude files (can be specified multiple times).
--root Path to the root of the monorepository. Defaults to current working directory.
Examples
$ ${SCRIPT_PATH} packages/app/Dockerfile
`,
{
allowUnknownFlags: false,
autoHelp: false,
description: `./${SCRIPT_PATH}`,
flags: {
help: { type: 'boolean', alias: 'h' },
listFiles: { type: 'boolean', alias: 'l' },
patterns: { type: 'string', alias: 'p', isMultiple: true },
root: { type: 'string', default: process.cwd() },
},
importMeta: import.meta,
}
);
if (cli.flags.help) {
cli.showHelp(0);
}
/**
* @typedef ParsedCLI
* @type {object}
* @property {boolean} listFiles
* @property {string[]} extraPatterns
* @property {string} dockerFile
* @property {string} root
*/
/**
* @param {ParsedCLI} cli
*/
async function main(cli) {
const projectPath = dirname(cli.dockerFile);
const [dependencyFiles, packageFiles, metaFiles] = await Promise.all([
getFilesFromPnpmSelector(`{${projectPath}}^...`, cli.root, {
extraPatterns: cli.extraPatterns,
}),
getFilesFromPnpmSelector(`{${projectPath}}`, cli.root, {
extraPatterns: cli.extraPatterns.concat([`!${cli.dockerFile}`]),
}),
getMetafilesFromPnpmSelector(`{${projectPath}}...`, cli.root, {
extraPatterns: cli.extraPatterns,
}),
]);
await withTmpdir(async (tmpdir) => {
await Promise.all([
fs.copyFile(cli.dockerFile, join(tmpdir, 'Dockerfile')),
// ↑ Copy target-Dockerfile to context root so Docker can find it by default
copyFiles(dependencyFiles, join(tmpdir, 'deps')),
copyFiles(metaFiles, join(tmpdir, 'meta')),
copyFiles(packageFiles, join(tmpdir, 'pkg')),
]);
const files = await getFiles(tmpdir);
if (cli.listFiles) {
for await (const path of files) console.log(path);
} else {
await pipe(createTar({ gzip: true, cwd: tmpdir }, files), process.stdout);
}
});
}
await parseCli(cli)
.then(main)
.catch((err) => {
throw err;
});
/**
* @param {string} path
* @returns {Promise<boolean>}
*/
async function fileExists(path) {
try {
await fs.stat(path);
} catch (err) {
return false;
}
return true;
}
/**
* @param {string} selector
* @param {string} cwd
* @param {object=} options
* @param {string[]=} options.extraPatterns
* @returns {Promise<string[]>}
*/
async function getFilesFromPnpmSelector(selector, cwd, options = {}) {
const projectPaths = await getPackagePathsFromPnpmSelector(selector, cwd);
const patterns = projectPaths.concat(options.extraPatterns || []);
return globby(patterns, { cwd, dot: true, gitignore: true });
}
/**
* @param {string} selector
* @param {string} cwd
* @param {object=} options
* @param {string[]=} options.extraPatterns
* @returns {Promise<string[]>}
*/
async function getMetafilesFromPnpmSelector(selector, cwd, options = {}) {
const [rootMetas, projectMetas] = await Promise.all([
globby(
[
'package.json',
'pnpm-lock.yaml',
'pnpm-workspace.yaml',
'nx.json',
'tsconfig.json',
'tsconfig.base.json',
'tsconfig.build.json',
'.npmrc',
'lerna.json',
'.npmrc-cloud',
],
{ cwd, dot: true, gitignore: true }
),
getPackagePathsFromPnpmSelector(selector, cwd).then((paths) => {
const patterns = paths.map((p) => `${p}/**/package.json`).concat(options.extraPatterns || []);
return globby(patterns, { cwd, dot: true, gitignore: true });
}),
]);
return rootMetas.concat(projectMetas);
}
/**
* @param {string} selector
* @param {string} cwd
* @returns {Promise<string[]>}
*/
async function getPackagePathsFromPnpmSelector(selector, cwd) {
const projects = await readProjects(cwd, [parsePackageSelector(selector, cwd)]);
return Object.keys(projects.selectedProjectsGraph).map((p) => relative(cwd, p).replace(/\\/g, '/'));
}
/**
* @param {string[]} input
* @param {object} flags
* @returns {Promise<ParsedCLI>}
*/
async function parseCli({ input, flags }) {
const dockerFile = input.shift();
if (!dockerFile) throw new Error('Must specify path to Dockerfile');
if (!(await fileExists(dockerFile))) throw new Error(`Dockerfile not found: ${dockerFile}`);
return {
dockerFile,
extraPatterns: flags.patterns,
listFiles: flags.listFiles,
root: flags.root,
};
}
/**
* Call `callable` with a temporary directory that's cleaned up after running
*
* @param {function(string):Promise<void>} callable
*/
async function withTmpdir(callable) {
const tmpdir = await fs.mkdtemp(join(os.tmpdir(), SCRIPT_PATH));
let result;
try {
result = await callable(tmpdir);
} finally {
await fs.rm(tmpdir, { recursive: true });
}
return result;
}
/**
* Get relative files recursively from `dir`
*
* @param {string} dir
* @returns {Promise<string[]>}
*/
async function getFiles(dir) {
async function* yieldFiles(dirPath) {
const paths = await fs.readdir(dirPath, { withFileTypes: true });
for (const path of paths) {
const res = resolve(dirPath, path.name);
if (path.isDirectory()) {
yield* yieldFiles(res);
} else {
yield res;
}
}
}
const files = [];
for await (const f of yieldFiles(dir)) {
files.push(relative(dir, f));
}
return files;
}
/**
* Copy array of `files` to `dstDir`
*
* @param {string[]} files
* @param {string} dstDir
* @returns {Promise<void>}
*/
async function copyFiles(files, dstDir) {
return Promise.all(
files.map((f) => {
const dst = join(dstDir, f);
return fs.mkdir(dirname(dst), { recursive: true }).then(() => fs.copyFile(f, dst));
})
);
}