/
import.js
227 lines (187 loc) · 9.01 KB
/
import.js
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
import debug from 'debug';
import fs from 'fs-promise';
import inquirer from 'inquirer';
import path from 'path';
import { spawn as yarnOrNPMSpawn, hasYarn } from 'yarn-or-npm';
import initGit from '../init/init-git';
import { deps, devDeps } from '../init/init-npm';
import asyncOra from '../util/ora-handler';
import installDepList from '../util/install-dependencies';
import readPackageJSON from '../util/read-package-json';
import confirmIfInteractive from '../util/confirm-if-interactive';
const d = debug('electron-forge:import');
/**
* @typedef {Object} ImportOptions
* @property {string} [dir=process.cwd()] The path to the app to be imported
* @property {boolean} [interactive=false] Whether to use sensible defaults or prompt the user visually
* @property {boolean} [updateScripts=true] Whether to update the modules package.json scripts to be electron-forge commands
*/
/**
* Attempt to import a given module directory to the Electron Forge standard.
*
* - Replaces the prebuilt electron package with the one that integrates with `electron-compile`
* - Sets up `git` and the correct NPM dependencies
* - Adds a template forge config to `package.json`
*
* @param {ImportOptions} providedOptions - Options for the import method
* @return {Promise} Will resolve when the import process is complete
*/
export default async (providedOptions = {}) => {
const { dir, interactive, updateScripts } = Object.assign({
dir: process.cwd(),
interactive: false,
updateScripts: true,
}, providedOptions);
asyncOra.interactive = interactive;
d(`Attempting to import project in: ${dir}`);
if (!await fs.exists(dir) || !await fs.exists(path.resolve(dir, 'package.json'))) {
throw `We couldn't find a project in: ${dir}`;
}
// eslint-disable-next-line max-len
const confirm = await confirmIfInteractive(interactive, `WARNING: We will now attempt to import: "${dir}". This will involve modifying some files, are you sure you want to continue?`);
if (!confirm) {
process.exit(0);
}
await initGit(dir);
let packageJSON = await readPackageJSON(dir);
if (packageJSON.config && packageJSON.config.forge) {
if (interactive) console.warn('It looks like this project is already configured for "electron-forge"'.green);
const shouldContinue = await confirmIfInteractive(interactive, 'Are you sure you want to continue?');
if (!shouldContinue) {
process.exit(0);
}
}
// eslint-disable-next-line max-len
const shouldChangeMain = await confirmIfInteractive(interactive, 'Do you want us to change the "main" attribute of your package.json? If you are currently using babel and pointing to a "build" directory say yes.', false);
if (shouldChangeMain) {
const { newMain } = await inquirer.createPromptModule()({
type: 'input',
name: 'newMain',
default: packageJSON.main,
message: 'Enter the relative path to your uncompiled main file',
});
packageJSON.main = newMain;
}
packageJSON.dependencies = packageJSON.dependencies || {};
packageJSON.devDependencies = packageJSON.devDependencies || {};
const keys = Object.keys(packageJSON.dependencies).concat(Object.keys(packageJSON.devDependencies));
const buildToolPackages = {
'electron-builder': 'provides mostly equivalent functionality',
'electron-download': 'already uses this module as a transitive dependency',
'electron-installer-debian': 'already uses this module as a transitive dependency',
'electron-installer-dmg': 'already uses this module as a transitive dependency',
'electron-installer-flatpak': 'already uses this module as a transitive dependency',
'electron-installer-redhat': 'already uses this module as a transitive dependency',
'electron-osx-sign': 'already uses this module as a transitive dependency',
'electron-packager': 'already uses this module as a transitive dependency',
'electron-winstaller': 'already uses this module as a transitive dependency',
};
let electronName;
for (const key of keys) {
if (key === 'electron' || key === 'electron-prebuilt') {
delete packageJSON.dependencies[key];
delete packageJSON.devDependencies[key];
electronName = key;
} else if (buildToolPackages[key]) {
const explanation = buildToolPackages[key];
// eslint-disable-next-line max-len
const shouldRemoveDependency = await confirmIfInteractive(interactive, `Do you want us to remove the "${key}" dependency in package.json? Electron Forge ${explanation}.`, updateScripts);
if (shouldRemoveDependency) {
delete packageJSON.dependencies[key];
delete packageJSON.devDependencies[key];
}
}
}
packageJSON.scripts = packageJSON.scripts || {};
d('reading current scripts object:', packageJSON.scripts);
const updatePackageScript = async (scriptName, newValue) => {
if (packageJSON.scripts[scriptName] !== newValue) {
// eslint-disable-next-line max-len
const shouldUpdate = await confirmIfInteractive(interactive, `Do you want us to update the "${scriptName}" script to instead call the electron-forge task "${newValue}"`);
if (shouldUpdate) {
packageJSON.scripts[scriptName] = newValue;
}
}
};
await updatePackageScript('start', 'electron-forge start');
await updatePackageScript('package', 'electron-forge package');
await updatePackageScript('make', 'electron-forge make');
d('forgified scripts object:', packageJSON.scripts);
const writeChanges = async () => {
await asyncOra('Writing modified package.json file', async () => {
await fs.writeFile(path.resolve(dir, 'package.json'), `${JSON.stringify(packageJSON, null, 2)}\n`);
});
};
let electronVersion;
if (electronName) {
const electronPackageJSON = await readPackageJSON(path.resolve(dir, 'node_modules', electronName));
electronVersion = electronPackageJSON.version;
packageJSON.devDependencies['electron-prebuilt-compile'] = electronVersion;
}
await writeChanges();
if (electronName) {
await asyncOra('Pruning deleted modules', async () => {
await new Promise((resolve) => {
d('attempting to prune node_modules in:', dir);
const child = yarnOrNPMSpawn(hasYarn() ? [] : ['prune'], {
cwd: dir,
stdio: 'ignore',
});
child.on('exit', () => resolve());
});
});
}
await asyncOra('Installing dependencies', async () => {
d('deleting old dependencies forcefully');
await fs.remove(path.resolve(dir, 'node_modules/.bin/electron'));
await fs.remove(path.resolve(dir, 'node_modules/.bin/electron.cmd'));
await fs.remove(path.resolve(dir, 'node_modules', electronName));
d('installing dependencies');
await installDepList(dir, deps);
d('installing devDependencies');
await installDepList(dir, devDeps, true);
d('installing electron-prebuilt-compile');
await installDepList(dir, [`electron-prebuilt-compile@${electronVersion || 'latest'}`], false, true);
});
packageJSON = await readPackageJSON(dir);
packageJSON.config = packageJSON.config || {};
const templatePackageJSON = await readPackageJSON(path.resolve(__dirname, '../../tmpl'));
packageJSON.config.forge = templatePackageJSON.config.forge;
await writeChanges();
await asyncOra('Fixing .gitignore', async () => {
if (await fs.exists(path.resolve(dir, '.gitignore'))) {
const gitignore = await fs.readFile(path.resolve(dir, '.gitignore'));
if (!gitignore.includes('out')) {
await fs.writeFile(path.resolve(dir, '.gitignore'), `${gitignore}\nout/`);
}
}
});
let babelConfig = packageJSON.babel;
const babelPath = path.resolve(dir, '.babelrc');
if (!babelConfig && await fs.exists(babelPath)) {
babelConfig = JSON.parse(await fs.readFile(babelPath, 'utf8'));
}
if (babelConfig) {
await asyncOra('Porting original babel config', async () => {
let compileConfig = {};
const compilePath = path.resolve(dir, '.compilerc');
if (await fs.exists(compilePath)) {
compileConfig = JSON.parse(await fs.readFile(compilePath, 'utf8'));
}
await fs.writeFile(compilePath, JSON.stringify(Object.assign(compileConfig, {
'application/javascript': babelConfig,
}), null, 2));
});
if (interactive) console.info('NOTE: You might be able to remove your `.compilerc` file completely if you are only using the `es2015` and `react` presets'.yellow); // eslint-disable-line max-len
}
if (interactive) {
console.info(`
We have ATTEMPTED to convert your app to be in a format that electron-forge understands.
Nothing much will have changed but we added the ${'"electron-prebuilt-compile"'.cyan} dependency. This is \
the dependency you must version bump to get newer versions of Electron.
We also tried to import any build tooling you already had but we can't get everything. You might need to convert any CLI/gulp/grunt tasks yourself.
Also please note if you are using \`preload\` scripts you need to follow the steps outlined \
at https://github.com/electron-userland/electron-forge/wiki/Using-%27preload%27-scripts
Thanks for using ${'"electron-forge"'.green}!!!`);
}
};