-
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathutils.ts
More file actions
185 lines (149 loc) · 4.54 KB
/
utils.ts
File metadata and controls
185 lines (149 loc) · 4.54 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
183
184
185
import fs from 'node:fs/promises';
import os from 'node:os';
import assert from 'node:assert';
import path from 'node:path';
import { $ } from 'execa';
import { fileURLToPath } from 'node:url';
import { globby } from 'globby';
import { execa, type Options } from 'execa';
const DEBUG = process.env.DEBUG === 'true';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
// repo-root
const blueprintPath = path.join(__dirname, '../..');
const defaultTryPath = path.join(blueprintPath, 'files/.try.mjs');
export const SUPPORTED_PACKAGE_MANAGERS = ['npm', 'pnpm'] as const;
export async function getTryScenarios(filePath = defaultTryPath) {
let scenarioInfo = await import(filePath);
return scenarioInfo.default?.scenarios ?? [];
}
export async function applyTryScenario(
tryName: string,
options: { cwd: string; filePath?: string },
) {
let { filePath = defaultTryPath, cwd } = options;
assert(cwd, 'applyTryScenario cwd is required');
let scenarios = await getTryScenarios(filePath);
let validNames = scenarios.map((x: { name: string }) => x.name);
assert(
validNames.includes(tryName),
`Invalid try scenario name: ${tryName}. Valid names: ${validNames.join(', ')}`,
);
return await $({ cwd })`pnpm dlx @embroider/try apply ${tryName}`;
}
export async function createTmp() {
let prefix = 'v2-addon-blueprint--';
let prefixPath = path.join(os.tmpdir(), prefix);
let tmpDirPath = await fs.mkdtemp(prefixPath);
return tmpDirPath;
}
/**
* Returns a copy of the current process env with EMBER_, VITE_, and NODE_
* prefixed vars removed.
*
* Useful when spawning child processes with `extendEnv: false` so that
* vitest's NODE_ENV=test (and similar) doesn't leak into the child and
* interfere with the build-time / runtime macro mode detection.
*/
export function safeExecaEnv(): Record<string, string | undefined> {
let env = { ...process.env };
for (let key of Object.keys(env)) {
if (key.startsWith('EMBER_') || key.startsWith('VITE_') || key.startsWith('NODE_')) {
delete env[key];
}
}
return env;
}
/**
* Abstraction for install, as the blueprint supports multiple package managers
*/
export async function install({
cwd,
packageManager,
skipPrepare,
}: {
cwd: string;
packageManager: string;
skipPrepare?: boolean;
}) {
if (packageManager === 'yarn') {
await execa('yarn', ['install', '--non-interactive'], { cwd });
} else {
let installOptions = [];
if (packageManager === 'pnpm') {
installOptions.push('--no-frozen-lockfile');
}
await execa(packageManager, ['install', '--ignore-scripts', ...installOptions], { cwd });
}
const pkg = await packageJsonAt(cwd);
// in order to test prepare, we need to have ignore-scripts=false
// which is a security risk so we'll manually invoke install + prepare
if (pkg.scripts?.prepare && !skipPrepare) {
await execa(packageManager, ['run', 'prepare'], { cwd });
}
}
/**
* Abstraction for install, as the blueprint supports multiple package managers
*/
export async function runScript({
cwd,
script,
packageManager,
}: {
cwd: string;
script: string;
packageManager: string;
}) {
// all package managers allow a more verbose <packageManager> run <script> way of running scripts
let promise = execa(packageManager, ['run', script], { cwd });
try {
await promise;
return promise;
} catch (e) {
console.error(e);
return promise;
}
}
export async function filesMatching(glob: string, dirPath: string) {
try {
let files = await globby(glob, { cwd: dirPath });
return files.sort();
} catch (e) {
console.error('error', e);
return [];
}
}
export async function dirContents(dirPath: string) {
try {
let files = await fs.readdir(dirPath);
return files;
} catch (e) {
console.error('error', e);
return [];
}
}
export async function packageJsonAt(dirPath: string) {
let buffer = await fs.readFile(path.join(dirPath, 'package.json'));
let str = buffer.toString();
return JSON.parse(str);
}
export async function createAddon({
name = 'my-addon',
args = [],
options = {},
}: {
name?: string;
args?: string[];
options?: Options;
}) {
let emberCliArgs = ['addon', name, '-b', blueprintPath, '--skip-npm', '--skip-git', ...args];
if (DEBUG) {
console.debug(`Running ember-cli in ${options.cwd}`);
console.debug(`\tember ${emberCliArgs.join(' ')}`);
}
let localEmberCli = require.resolve('ember-cli/bin/ember');
let result = await execa(localEmberCli, emberCliArgs, {
...options,
preferLocal: true,
});
return { result, name };
}