/
new.action.ts
261 lines (233 loc) · 7.53 KB
/
new.action.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
import * as chalk from 'chalk';
import { execSync } from 'child_process';
import * as fs from 'fs';
import * as inquirer from 'inquirer';
import { Answers, Question } from 'inquirer';
import { join } from 'path';
import { Input } from '../commands';
import { defaultGitIgnore } from '../lib/configuration/defaults';
import {
AbstractPackageManager,
PackageManager,
PackageManagerFactory,
} from '../lib/package-managers';
import { generateInput, generateSelect } from '../lib/questions/questions';
import { GitRunner } from '../lib/runners/git.runner';
import {
AbstractCollection,
Collection,
CollectionFactory,
SchematicOption,
} from '../lib/schematics';
import { EMOJIS, MESSAGES } from '../lib/ui';
import { normalizeToKebabOrSnakeCase } from '../lib/utils/formatting';
import { AbstractAction } from './abstract.action';
export class NewAction extends AbstractAction {
public async handle(inputs: Input[], options: Input[]) {
const directoryOption = options.find(
(option) => option.name === 'directory',
);
const dryRunOption = options.find((option) => option.name === 'dry-run');
const isDryRunEnabled = dryRunOption && dryRunOption.value;
await askForMissingInformation(inputs, options);
await generateApplicationFiles(inputs, options).catch(exit);
const shouldSkipInstall = options.some(
(option) => option.name === 'skip-install' && option.value === true,
);
const shouldSkipGit = options.some(
(option) => option.name === 'skip-git' && option.value === true,
);
const projectDirectory = getProjectDirectory(
getApplicationNameInput(inputs)!,
directoryOption,
);
if (!shouldSkipInstall) {
await installPackages(
options,
isDryRunEnabled as boolean,
projectDirectory,
);
}
if (!isDryRunEnabled) {
if (!shouldSkipGit) {
await initializeGitRepository(projectDirectory);
await createGitIgnoreFile(projectDirectory);
}
printCollective();
}
process.exit(0);
}
}
const getApplicationNameInput = (inputs: Input[]) =>
inputs.find((input) => input.name === 'name');
const getPackageManagerInput = (inputs: Input[]) =>
inputs.find((options) => options.name === 'packageManager');
const getProjectDirectory = (
applicationName: Input,
directoryOption?: Input,
): string => {
return (
(directoryOption && (directoryOption.value as string)) ||
normalizeToKebabOrSnakeCase(applicationName.value as string)
);
};
const askForMissingInformation = async (inputs: Input[], options: Input[]) => {
console.info(MESSAGES.PROJECT_INFORMATION_START);
console.info();
const prompt: inquirer.PromptModule = inquirer.createPromptModule();
const nameInput = getApplicationNameInput(inputs);
if (!nameInput!.value) {
const message = 'What name would you like to use for the new project?';
const questions = [generateInput('name', message)('nest-app')];
const answers: Answers = await prompt(questions as ReadonlyArray<Question>);
replaceInputMissingInformation(inputs, answers);
}
const packageManagerInput = getPackageManagerInput(options);
if (!packageManagerInput!.value) {
const answers = await askForPackageManager();
replaceInputMissingInformation(options, answers);
}
};
const replaceInputMissingInformation = (
inputs: Input[],
answers: Answers,
): Input[] => {
return inputs.map(
(input) =>
(input.value =
input.value !== undefined ? input.value : answers[input.name]),
);
};
const generateApplicationFiles = async (args: Input[], options: Input[]) => {
const collectionName = options.find(
(option) => option.name === 'collection' && option.value != null,
)!.value;
const collection: AbstractCollection = CollectionFactory.create(
(collectionName as Collection) || Collection.NESTJS,
);
const schematicOptions: SchematicOption[] = mapSchematicOptions(
args.concat(options),
);
await collection.execute('application', schematicOptions);
console.info();
};
const mapSchematicOptions = (options: Input[]): SchematicOption[] => {
return options.reduce(
(schematicOptions: SchematicOption[], option: Input) => {
if (option.name !== 'skip-install') {
schematicOptions.push(new SchematicOption(option.name, option.value));
}
return schematicOptions;
},
[],
);
};
const installPackages = async (
options: Input[],
dryRunMode: boolean,
installDirectory: string,
) => {
const inputPackageManager = getPackageManagerInput(options)!.value as string;
let packageManager: AbstractPackageManager;
if (dryRunMode) {
console.info();
console.info(chalk.green(MESSAGES.DRY_RUN_MODE));
console.info();
return;
}
try {
packageManager = PackageManagerFactory.create(inputPackageManager);
await packageManager.install(installDirectory, inputPackageManager);
} catch (error) {
if (error && error.message) {
console.error(chalk.red(error.message));
}
}
};
const askForPackageManager = async (): Promise<Answers> => {
const questions: Question[] = [
generateSelect('packageManager')(MESSAGES.PACKAGE_MANAGER_QUESTION)([
PackageManager.NPM,
PackageManager.YARN,
PackageManager.PNPM,
]),
];
const prompt = inquirer.createPromptModule();
return await prompt(questions);
};
const initializeGitRepository = async (dir: string) => {
const runner = new GitRunner();
await runner.run('init', true, join(process.cwd(), dir)).catch(() => {
console.error(chalk.red(MESSAGES.GIT_INITIALIZATION_ERROR));
});
};
/**
* Write a file `.gitignore` in the root of the newly created project.
* `.gitignore` available in `@nestjs/schematics` cannot be published to
* NPM (needs to be investigated).
*
* @param dir Relative path to the project.
* @param content (optional) Content written in the `.gitignore`.
*
* @return Resolves when succeeds, or rejects with any error from `fn.writeFile`.
*/
const createGitIgnoreFile = (dir: string, content?: string) => {
const fileContent = content || defaultGitIgnore;
const filePath = join(process.cwd(), dir, '.gitignore');
if (fileExists(filePath)) {
return;
}
return fs.promises.writeFile(filePath, fileContent);
};
const printCollective = () => {
const dim = print('dim');
const yellow = print('yellow');
const emptyLine = print();
emptyLine();
yellow(`Thanks for installing Nest ${EMOJIS.PRAY}`);
dim('Please consider donating to our open collective');
dim('to help us maintain this package.');
emptyLine();
emptyLine();
print()(
`${chalk.bold(`${EMOJIS.WINE} Donate:`)} ${chalk.underline(
'https://opencollective.com/nest',
)}`,
);
emptyLine();
};
const print =
(color: string | null = null) =>
(str = '') => {
const terminalCols = retrieveCols();
const strLength = str.replace(/\u001b\[[0-9]{2}m/g, '').length;
const leftPaddingLength = Math.floor((terminalCols - strLength) / 2);
const leftPadding = ' '.repeat(Math.max(leftPaddingLength, 0));
if (color) {
str = (chalk as any)[color](str);
}
console.log(leftPadding, str);
};
export const retrieveCols = () => {
const defaultCols = 80;
try {
const terminalCols = execSync('tput cols', {
stdio: ['pipe', 'pipe', 'ignore'],
});
return parseInt(terminalCols.toString(), 10) || defaultCols;
} catch {
return defaultCols;
}
};
const fileExists = (path: string) => {
try {
fs.accessSync(path);
return true;
} catch (err: any) {
if (err.code === 'ENOENT') {
return false;
}
throw err;
}
};
export const exit = () => process.exit(1);