-
Notifications
You must be signed in to change notification settings - Fork 542
/
initHandler.ts
100 lines (84 loc) · 2.57 KB
/
initHandler.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
import pathUtils from 'path';
import { promises as fs } from 'fs';
import {
NpmSnapFileNames,
SnapManifest,
readJsonFile,
satisfiesVersionRange,
NpmSnapPackageJson,
} from '@metamask/snaps-utils';
import { YargsArgs } from '../../types/yargs';
import {
cloneTemplate,
gitInit,
isGitInstalled,
isInGitRepository,
prepareWorkingDirectory,
SNAP_LOCATION,
yarnInstall,
} from './initUtils';
const SATISFIED_VERSION = '>=16';
/**
* Creates a new snap package, based on one of the provided templates. This
* creates all the necessary files, like `package.json`, `snap.config.js`, etc.
* to start developing a snap.
*
* @param argv - The Yargs arguments object.
* @returns The Yargs arguments augmented with the new `dist`, `outfileName` and
* `src` properties.
* @throws If initialization of the snap package failed.
*/
export async function initHandler(argv: YargsArgs) {
const { directory } = argv;
const isVersionSupported = satisfiesVersionRange(
process.version,
SATISFIED_VERSION,
);
if (!isVersionSupported) {
throw new Error(
`Init Error: You are using an outdated version of Node (${process.version}). Please update to Node ${SATISFIED_VERSION}.`,
);
}
const gitExists = isGitInstalled();
if (!gitExists) {
throw new Error(
`Init Error: git is not installed. Please install git to continue.`,
);
}
const directoryToUse = directory
? pathUtils.join(process.cwd(), directory)
: process.cwd();
console.log(`Preparing ${directoryToUse}...`);
await prepareWorkingDirectory(directoryToUse);
try {
console.log(`Cloning template...`);
await cloneTemplate(directoryToUse);
fs.rm(pathUtils.join(directoryToUse, '.git'), {
force: true,
recursive: true,
});
} catch (err) {
throw new Error('Init Error: Failed to create template.');
}
console.log('Installing dependencies...');
await yarnInstall(directoryToUse);
if (!isInGitRepository(directoryToUse)) {
console.log('Initializing git repository...');
await gitInit(directoryToUse);
}
const snapLocation = pathUtils.join(directoryToUse, SNAP_LOCATION);
const manifest: SnapManifest = await readJsonFile(
pathUtils.join(snapLocation, NpmSnapFileNames.Manifest),
);
const packageJson: NpmSnapPackageJson = await readJsonFile(
pathUtils.join(snapLocation, NpmSnapFileNames.PackageJson),
);
const distPath = manifest.source.location.npm.filePath.split('/');
return {
...argv,
dist: distPath[0],
outfileName: distPath[1],
src: packageJson.main || 'src/index.js',
snapLocation,
};
}