-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
init.ts
266 lines (218 loc) Β· 9.21 KB
/
init.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
import {BaseCommand} from '@yarnpkg/cli';
import {Configuration, Manifest, miscUtils, Project, YarnVersion} from '@yarnpkg/core';
import {execUtils, scriptUtils, structUtils} from '@yarnpkg/core';
import {xfs, ppath, Filename} from '@yarnpkg/fslib';
import {Command, Option, Usage, UsageError} from 'clipanion';
// eslint-disable-next-line arca/no-default-export
export default class InitCommand extends BaseCommand {
static paths = [
[`init`],
];
static usage: Usage = Command.Usage({
description: `create a new package`,
details: `
This command will setup a new package in your local directory.
If the \`-p,--private\` or \`-w,--workspace\` options are set, the package will be private by default.
If the \`-w,--workspace\` option is set, the package will be configured to accept a set of workspaces in the \`packages/\` directory.
If the \`-i,--install\` option is given a value, Yarn will first download it using \`yarn set version\` and only then forward the init call to the newly downloaded bundle. Without arguments, the downloaded bundle will be \`latest\`.
The initial settings of the manifest can be changed by using the \`initScope\` and \`initFields\` configuration values. Additionally, Yarn will generate an EditorConfig file whose rules can be altered via \`initEditorConfig\`, and will initialize a Git repository in the current directory.
`,
examples: [[
`Create a new package in the local directory`,
`yarn init`,
], [
`Create a new private package in the local directory`,
`yarn init -p`,
], [
`Create a new package and store the Yarn release inside`,
`yarn init -i=latest`,
], [
`Create a new private package and defines it as a workspace root`,
`yarn init -w`,
]],
});
private = Option.Boolean(`-p,--private`, false, {
description: `Initialize a private package`,
});
workspace = Option.Boolean(`-w,--workspace`, false, {
description: `Initialize a workspace root with a \`packages/\` directory`,
});
install = Option.String(`-i,--install`, false, {
tolerateBoolean: true,
description: `Initialize a package with a specific bundle that will be locked in the project`,
});
name = Option.String(`-n,--name`, {
description: `Initialize a package with the given name`,
});
// Options that only mattered on v1
usev2 = Option.Boolean(`-2`, false, {hidden: true});
yes = Option.Boolean(`-y,--yes`, {hidden: true});
async execute() {
const configuration = await Configuration.find(this.context.cwd, this.context.plugins);
const install = typeof this.install === `string`
? this.install
: this.usev2 || this.install === true
? `latest`
: null;
if (install !== null) {
return await this.executeProxy(configuration, install);
} else {
return await this.executeRegular(configuration);
}
}
async executeProxy(configuration: Configuration, version: string) {
if (configuration.projectCwd !== null && configuration.projectCwd !== this.context.cwd)
throw new UsageError(`Cannot use the --install flag from within a project subdirectory`);
if (!xfs.existsSync(this.context.cwd))
await xfs.mkdirPromise(this.context.cwd, {recursive: true});
const lockfilePath = ppath.join(this.context.cwd, Filename.lockfile);
if (!xfs.existsSync(lockfilePath))
await xfs.writeFilePromise(lockfilePath, ``);
const versionExitCode = await this.cli.run([`set`, `version`, version], {quiet: true});
if (versionExitCode !== 0)
return versionExitCode;
const args: Array<string> = [];
if (this.private)
args.push(`-p`);
if (this.workspace)
args.push(`-w`);
if (this.name)
args.push(`-n=${this.name}`);
if (this.yes)
args.push(`-y`);
return await xfs.mktempPromise(async binFolder => {
const {code} = await execUtils.pipevp(`yarn`, [`init`, ...args], {
cwd: this.context.cwd,
stdin: this.context.stdin,
stdout: this.context.stdout,
stderr: this.context.stderr,
env: await scriptUtils.makeScriptEnv({binFolder}),
});
return code;
});
}
async executeRegular(configuration: Configuration) {
let existingProject: Project | null = null;
try {
existingProject = (await Project.find(configuration, this.context.cwd)).project;
} catch {
existingProject = null;
}
if (!xfs.existsSync(this.context.cwd))
await xfs.mkdirPromise(this.context.cwd, {recursive: true});
const original = await Manifest.tryFind(this.context.cwd);
const manifest = original ?? new Manifest();
const fields = Object.fromEntries(configuration.get(`initFields`).entries());
manifest.load(fields);
manifest.name = manifest.name
?? structUtils.makeIdent(configuration.get(`initScope`), this.name ?? ppath.basename(this.context.cwd));
manifest.packageManager = YarnVersion && miscUtils.isTaggedYarnVersion(YarnVersion)
? `yarn@${YarnVersion}`
: null;
if ((!original && this.workspace) || this.private)
manifest.private = true;
if (this.workspace && manifest.workspaceDefinitions.length === 0) {
await xfs.mkdirPromise(ppath.join(this.context.cwd, `packages`), {recursive: true});
manifest.workspaceDefinitions = [{
pattern: `packages/*`,
}];
}
const serialized: any = {};
manifest.exportTo(serialized);
const manifestPath = ppath.join(this.context.cwd, Manifest.fileName);
await xfs.changeFilePromise(manifestPath, `${JSON.stringify(serialized, null, 2)}\n`, {
automaticNewlines: true,
});
const changedPaths = [
manifestPath,
];
const readmePath = ppath.join(this.context.cwd, `README.md`);
if (!xfs.existsSync(readmePath)) {
await xfs.writeFilePromise(readmePath, `# ${structUtils.stringifyIdent(manifest.name)}\n`);
changedPaths.push(readmePath);
}
if (!existingProject || existingProject.cwd === this.context.cwd) {
const lockfilePath = ppath.join(this.context.cwd, Filename.lockfile);
if (!xfs.existsSync(lockfilePath)) {
await xfs.writeFilePromise(lockfilePath, ``);
changedPaths.push(lockfilePath);
}
const gitignoreLines = [
`.yarn/*`,
`!.yarn/patches`,
`!.yarn/plugins`,
`!.yarn/releases`,
`!.yarn/sdks`,
`!.yarn/versions`,
``,
`# Swap the comments on the following lines if you wish to use zero-installs`,
`# In that case, don't forget to run \`yarn config set enableGlobalCache false\`!`,
`# Documentation here: https://yarnpkg.com/features/caching#zero-installs`,
``,
`#!.yarn/cache`,
`.pnp.*`,
];
const gitignoreBody = gitignoreLines.map(line => {
return `${line}\n`;
}).join(``);
const gitignorePath = ppath.join(this.context.cwd, `.gitignore`);
if (!xfs.existsSync(gitignorePath)) {
await xfs.writeFilePromise(gitignorePath, gitignoreBody);
changedPaths.push(gitignorePath);
}
const gitattributesLines = [
`/.yarn/** linguist-vendored`,
`/.yarn/releases/* binary`,
`/.yarn/plugins/**/* binary`,
`/.pnp.* binary linguist-generated`,
];
const gitattributesBody = gitattributesLines.map(line => {
return `${line}\n`;
}).join(``);
const gitattributesPath = ppath.join(this.context.cwd, `.gitattributes`);
if (!xfs.existsSync(gitattributesPath)) {
await xfs.writeFilePromise(gitattributesPath, gitattributesBody);
changedPaths.push(gitattributesPath);
}
const editorConfigProperties = {
[`*`]: {
endOfLine: `lf`,
insertFinalNewline: true,
},
[`*.{js,json,yml}`]: {
charset: `utf-8`,
indentStyle: `space`,
indentSize: 2,
},
};
miscUtils.mergeIntoTarget(editorConfigProperties, configuration.get(`initEditorConfig`));
let editorConfigBody = `root = true\n`;
for (const [selector, props] of Object.entries(editorConfigProperties)) {
editorConfigBody += `\n[${selector}]\n`;
for (const [propName, propValue] of Object.entries(props)) {
const snakeCaseName = propName.replace(/[A-Z]/g, $0 => `_${$0.toLowerCase()}`);
editorConfigBody += `${snakeCaseName} = ${propValue}\n`;
}
}
const editorConfigPath = ppath.join(this.context.cwd, `.editorconfig`);
if (!xfs.existsSync(editorConfigPath)) {
await xfs.writeFilePromise(editorConfigPath, editorConfigBody);
changedPaths.push(editorConfigPath);
}
await this.cli.run([`install`], {
quiet: true,
});
if (!xfs.existsSync(ppath.join(this.context.cwd, `.git`))) {
await execUtils.execvp(`git`, [`init`], {
cwd: this.context.cwd,
});
await execUtils.execvp(`git`, [`add`, `--`, ...changedPaths], {
cwd: this.context.cwd,
});
await execUtils.execvp(`git`, [`commit`, `--allow-empty`, `-m`, `First commit`], {
cwd: this.context.cwd,
});
}
}
}
}