/
make.ts
344 lines (306 loc) · 12.5 KB
/
make.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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
import path from 'path';
import { getElectronVersion } from '@electron-forge/core-utils';
import { MakerBase } from '@electron-forge/maker-base';
import {
ForgeArch,
ForgeConfigMaker,
ForgeListrTaskFn,
ForgeMakeResult,
ForgePlatform,
IForgeResolvableMaker,
ResolvedForgeConfig,
} from '@electron-forge/shared-types';
import { autoTrace, delayTraceTillSignal } from '@electron-forge/tracer';
import { getHostArch } from '@electron/get';
import chalk from 'chalk';
import filenamify from 'filenamify';
import fs from 'fs-extra';
import { Listr } from 'listr2';
import logSymbols from 'log-symbols';
import getForgeConfig from '../util/forge-config';
import { getHookListrTasks, runMutatingHook } from '../util/hook';
import getCurrentOutDir from '../util/out-dir';
import parseArchs from '../util/parse-archs';
import { readMutatedPackageJson } from '../util/read-package-json';
import requireSearch from '../util/require-search';
import resolveDir from '../util/resolve-dir';
import { listrPackage } from './package';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
class MakerImpl extends MakerBase<any> {
name = 'impl';
defaultPlatforms = [];
}
type MakeTargets = ForgeConfigMaker[] | string[];
function generateTargets(forgeConfig: ResolvedForgeConfig, overrideTargets?: MakeTargets) {
if (overrideTargets) {
return overrideTargets.map((target) => {
if (typeof target === 'string') {
return forgeConfig.makers.find((maker) => (maker as IForgeResolvableMaker).name === target) || ({ name: target } as IForgeResolvableMaker);
}
return target;
});
}
return forgeConfig.makers;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function isElectronForgeMaker(target: MakerBase<any> | unknown): target is MakerBase<any> {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return (target as MakerBase<any>).__isElectronForgeMaker;
}
type MakeContext = {
dir: string;
forgeConfig: ResolvedForgeConfig;
actualOutDir: string;
makers: Array<() => MakerBase<unknown>>;
outputs: ForgeMakeResult[];
};
export interface MakeOptions {
/**
* The path to the app from which distrubutables are generated
*/
dir?: string;
/**
* Whether to use sensible defaults or prompt the user visually
*/
interactive?: boolean;
/**
* Whether to skip the pre-make packaging step
*/
skipPackage?: boolean;
/**
* An array of make targets to override your forge config
*/
overrideTargets?: MakeTargets;
/**
* The target architecture
*/
arch?: ForgeArch;
/**
* The target platform
*/
platform?: ForgePlatform;
/**
* The path to the directory containing generated distributables
*/
outDir?: string;
}
export const listrMake = (
childTrace: typeof autoTrace,
{
dir: providedDir = process.cwd(),
interactive = false,
skipPackage = false,
arch = getHostArch() as ForgeArch,
platform = process.platform as ForgePlatform,
overrideTargets,
outDir,
}: MakeOptions,
receiveMakeResults?: (results: ForgeMakeResult[]) => void
) => {
const listrOptions = {
concurrent: false,
rendererOptions: {
collapse: false,
collapseErrors: false,
},
rendererSilent: !interactive,
rendererFallback: Boolean(process.env.DEBUG),
};
const runner = new Listr<MakeContext>(
[
{
title: 'Loading configuration',
task: childTrace<Parameters<ForgeListrTaskFn<MakeContext>>>({ name: 'load-forge-config', category: '@electron-forge/core' }, async (_, ctx) => {
const resolvedDir = await resolveDir(providedDir);
if (!resolvedDir) {
throw new Error('Failed to locate startable Electron application');
}
ctx.dir = resolvedDir;
ctx.forgeConfig = await getForgeConfig(resolvedDir);
}),
},
{
title: 'Resolving make targets',
task: childTrace<Parameters<ForgeListrTaskFn<MakeContext>>>(
{ name: 'resolve-make-targets', category: '@electron-forge/core' },
async (_, ctx, task) => {
const { dir, forgeConfig } = ctx;
ctx.actualOutDir = outDir || getCurrentOutDir(dir, forgeConfig);
if (!['darwin', 'win32', 'linux', 'mas'].includes(platform)) {
throw new Error(`'${platform}' is an invalid platform. Choices are 'darwin', 'mas', 'win32' or 'linux'.`);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const makers: Array<() => MakerBase<any>> = [];
const possibleMakers = generateTargets(forgeConfig, overrideTargets);
for (const possibleMaker of possibleMakers) {
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
let maker: MakerBase<any>;
if (isElectronForgeMaker(possibleMaker)) {
maker = possibleMaker;
if (!maker.platforms.includes(platform)) continue;
} else {
const resolvableTarget = possibleMaker as IForgeResolvableMaker;
// non-false falsy values should be 'true'
if (resolvableTarget.enabled === false) continue;
if (!resolvableTarget.name) {
throw new Error(`The following maker config is missing a maker name: ${JSON.stringify(resolvableTarget)}`);
} else if (typeof resolvableTarget.name !== 'string') {
throw new Error(`The following maker config has a maker name that is not a string: ${JSON.stringify(resolvableTarget)}`);
}
const MakerClass = requireSearch<typeof MakerImpl>(dir, [resolvableTarget.name]);
if (!MakerClass) {
throw new Error(
`Could not find module with name '${resolvableTarget.name}'. If this is a package from NPM, make sure it's listed in the devDependencies of your package.json. If this is a local module, make sure you have the correct path to its entry point. Try using the DEBUG="electron-forge:require-search" environment variable for more information.`
);
}
maker = new MakerClass(resolvableTarget.config, resolvableTarget.platforms || undefined);
if (!maker.platforms.includes(platform)) continue;
}
if (!maker.isSupportedOnCurrentPlatform) {
throw new Error(
[
`Maker for target ${maker.name} is incompatible with this version of `,
'Electron Forge, please upgrade or contact the maintainer ',
"(needs to implement 'isSupportedOnCurrentPlatform)')",
].join('')
);
}
if (!maker.isSupportedOnCurrentPlatform()) {
throw new Error(`Cannot make for ${platform} and target ${maker.name}: the maker declared that it cannot run on ${process.platform}.`);
}
maker.ensureExternalBinariesExist();
makers.push(() => maker.clone());
}
if (makers.length === 0) {
throw new Error(`Could not find any make targets configured for the "${platform}" platform.`);
}
ctx.makers = makers;
task.output = `Making for the following targets: ${chalk.magenta(`${makers.map((maker) => maker.name).join(', ')}`)}`;
}
),
options: {
persistentOutput: true,
},
},
{
title: `Running ${chalk.yellow('package')} command`,
task: childTrace<Parameters<ForgeListrTaskFn<MakeContext>>>({ name: 'package()', category: '@electron-forge/core' }, async (childTrace, ctx, task) => {
if (!skipPackage) {
return delayTraceTillSignal(
childTrace,
listrPackage(childTrace, {
dir: ctx.dir,
interactive,
arch,
outDir: ctx.actualOutDir,
platform,
}),
'run'
);
} else {
task.output = chalk.yellow(`${logSymbols.warning} Skipping could result in an out of date build`);
task.skip();
}
}),
options: {
persistentOutput: true,
},
},
{
title: `Running ${chalk.yellow('preMake')} hook`,
task: childTrace<Parameters<ForgeListrTaskFn<MakeContext>>>(
{ name: 'run-preMake-hook', category: '@electron-forge/core' },
async (childTrace, ctx, task) => {
return delayTraceTillSignal(childTrace, task.newListr(await getHookListrTasks(childTrace, ctx.forgeConfig, 'preMake')), 'run');
}
),
},
{
title: 'Making distributables',
task: childTrace<Parameters<ForgeListrTaskFn<MakeContext>>>(
{ name: 'make-distributables', category: '@electron-forge/core' },
async (childTrace, ctx, task) => {
const { actualOutDir, dir, forgeConfig, makers } = ctx;
const packageJSON = await readMutatedPackageJson(dir, forgeConfig);
const appName = filenamify(forgeConfig.packagerConfig.name || packageJSON.productName || packageJSON.name, { replacement: '-' });
const outputs: ForgeMakeResult[] = [];
ctx.outputs = outputs;
const subRunner = task.newListr([], {
...listrOptions,
concurrent: true,
rendererOptions: {
collapse: false,
collapseErrors: false,
},
});
for (const targetArch of parseArchs(platform, arch, await getElectronVersion(dir, packageJSON))) {
const packageDir = path.resolve(actualOutDir, `${appName}-${platform}-${targetArch}`);
if (!(await fs.pathExists(packageDir))) {
throw new Error(`Couldn't find packaged app at: ${packageDir}`);
}
for (const maker of makers) {
const uniqMaker = maker();
subRunner.add({
title: `Making a ${chalk.magenta(uniqMaker.name)} distributable for ${chalk.cyan(`${platform}/${targetArch}`)}`,
task: childTrace<[]>({ name: `make-${maker.name}`, category: '@electron-forge/core', newRoot: true }, async () => {
try {
await Promise.resolve(uniqMaker.prepareConfig(targetArch));
const artifacts = await uniqMaker.make({
appName,
forgeConfig,
packageJSON,
targetArch,
dir: packageDir,
makeDir: path.resolve(actualOutDir, 'make'),
targetPlatform: platform,
});
outputs.push({
artifacts,
packageJSON,
platform,
arch: targetArch,
});
} catch (err) {
if (err) {
throw err;
} else {
throw new Error(`An unknown error occurred while making for target: ${uniqMaker.name}`);
}
}
}),
options: {
showTimer: true,
},
});
}
}
return delayTraceTillSignal(childTrace, subRunner, 'run');
}
),
},
{
title: `Running ${chalk.yellow('postMake')} hook`,
task: childTrace<Parameters<ForgeListrTaskFn<MakeContext>>>({ name: 'run-postMake-hook', category: '@electron-forge/core' }, async (_, ctx, task) => {
// If the postMake hooks modifies the locations / names of the outputs it must return
// the new locations so that the publish step knows where to look
ctx.outputs = await runMutatingHook(ctx.forgeConfig, 'postMake', ctx.outputs);
receiveMakeResults?.(ctx.outputs);
task.output = `Artifacts available at: ${chalk.green(path.resolve(ctx.actualOutDir, 'make'))}`;
}),
options: {
persistentOutput: true,
},
},
],
{
...listrOptions,
ctx: {} as MakeContext,
}
);
return runner;
};
export default autoTrace({ name: 'make()', category: '@electron-forge/core' }, async (childTrace, opts: MakeOptions): Promise<ForgeMakeResult[]> => {
const runner = listrMake(childTrace, opts);
await runner.run();
return runner.ctx.outputs;
});