UNPKG

8.68 kBJavaScriptView Raw
1"use strict";
2var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4 return new (P || (P = Promise))(function (resolve, reject) {
5 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8 step((generator = generator.apply(thisArg, _arguments || [])).next());
9 });
10};
11Object.defineProperty(exports, "__esModule", { value: true });
12exports.exit = exports.retrieveCols = exports.NewAction = void 0;
13const chalk = require("chalk");
14const child_process_1 = require("child_process");
15const fs = require("fs");
16const inquirer = require("inquirer");
17const path_1 = require("path");
18const util_1 = require("util");
19const defaults_1 = require("../lib/configuration/defaults");
20const package_managers_1 = require("../lib/package-managers");
21const questions_1 = require("../lib/questions/questions");
22const git_runner_1 = require("../lib/runners/git.runner");
23const schematics_1 = require("../lib/schematics");
24const ui_1 = require("../lib/ui");
25const formatting_1 = require("../lib/utils/formatting");
26const abstract_action_1 = require("./abstract.action");
27class NewAction extends abstract_action_1.AbstractAction {
28 handle(inputs, options) {
29 return __awaiter(this, void 0, void 0, function* () {
30 const directoryOption = options.find((option) => option.name === 'directory');
31 const dryRunOption = options.find((option) => option.name === 'dry-run');
32 const isDryRunEnabled = dryRunOption && dryRunOption.value;
33 yield askForMissingInformation(inputs);
34 yield generateApplicationFiles(inputs, options).catch(exports.exit);
35 const shouldSkipInstall = options.some((option) => option.name === 'skip-install' && option.value === true);
36 const shouldSkipGit = options.some((option) => option.name === 'skip-git' && option.value === true);
37 const projectDirectory = getProjectDirectory(getApplicationNameInput(inputs), directoryOption);
38 if (!shouldSkipInstall) {
39 yield installPackages(options, isDryRunEnabled, projectDirectory);
40 }
41 if (!isDryRunEnabled) {
42 if (!shouldSkipGit) {
43 yield initializeGitRepository(projectDirectory);
44 yield createGitIgnoreFile(projectDirectory);
45 }
46 printCollective();
47 }
48 process.exit(0);
49 });
50 }
51}
52exports.NewAction = NewAction;
53const getApplicationNameInput = (inputs) => inputs.find((input) => input.name === 'name');
54const getProjectDirectory = (applicationName, directoryOption) => {
55 return ((directoryOption && directoryOption.value) ||
56 (0, formatting_1.normalizeToKebabOrSnakeCase)(applicationName.value));
57};
58const askForMissingInformation = (inputs) => __awaiter(void 0, void 0, void 0, function* () {
59 console.info(ui_1.MESSAGES.PROJECT_INFORMATION_START);
60 console.info();
61 const prompt = inquirer.createPromptModule();
62 const nameInput = getApplicationNameInput(inputs);
63 if (!nameInput.value) {
64 const message = 'What name would you like to use for the new project?';
65 const questions = [(0, questions_1.generateInput)('name', message)('nest-app')];
66 const answers = yield prompt(questions);
67 replaceInputMissingInformation(inputs, answers);
68 }
69});
70const replaceInputMissingInformation = (inputs, answers) => {
71 return inputs.map((input) => (input.value =
72 input.value !== undefined ? input.value : answers[input.name]));
73};
74const generateApplicationFiles = (args, options) => __awaiter(void 0, void 0, void 0, function* () {
75 const collectionName = options.find((option) => option.name === 'collection' && option.value != null).value;
76 const collection = schematics_1.CollectionFactory.create(collectionName || schematics_1.Collection.NESTJS);
77 const schematicOptions = mapSchematicOptions(args.concat(options));
78 yield collection.execute('application', schematicOptions);
79 console.info();
80});
81const mapSchematicOptions = (options) => {
82 return options.reduce((schematicOptions, option) => {
83 if (option.name !== 'skip-install' &&
84 option.value !== 'package-manager') {
85 schematicOptions.push(new schematics_1.SchematicOption(option.name, option.value));
86 }
87 return schematicOptions;
88 }, []);
89};
90const installPackages = (options, dryRunMode, installDirectory) => __awaiter(void 0, void 0, void 0, function* () {
91 const inputPackageManager = options.find((option) => option.name === 'package-manager').value;
92 let packageManager;
93 if (dryRunMode) {
94 console.info();
95 console.info(chalk.green(ui_1.MESSAGES.DRY_RUN_MODE));
96 console.info();
97 return;
98 }
99 if (inputPackageManager !== undefined) {
100 try {
101 packageManager = package_managers_1.PackageManagerFactory.create(inputPackageManager);
102 yield packageManager.install(installDirectory, inputPackageManager);
103 }
104 catch (error) {
105 if (error && error.message) {
106 console.error(chalk.red(error.message));
107 }
108 }
109 }
110 else {
111 packageManager = yield selectPackageManager();
112 yield packageManager.install(installDirectory, packageManager.name.toLowerCase());
113 }
114});
115const selectPackageManager = () => __awaiter(void 0, void 0, void 0, function* () {
116 const answers = yield askForPackageManager();
117 return package_managers_1.PackageManagerFactory.create(answers['package-manager']);
118});
119const askForPackageManager = () => __awaiter(void 0, void 0, void 0, function* () {
120 const questions = [
121 (0, questions_1.generateSelect)('package-manager')(ui_1.MESSAGES.PACKAGE_MANAGER_QUESTION)([
122 package_managers_1.PackageManager.NPM,
123 package_managers_1.PackageManager.YARN,
124 package_managers_1.PackageManager.PNPM,
125 ]),
126 ];
127 const prompt = inquirer.createPromptModule();
128 return yield prompt(questions);
129});
130const initializeGitRepository = (dir) => __awaiter(void 0, void 0, void 0, function* () {
131 const runner = new git_runner_1.GitRunner();
132 yield runner.run('init', true, (0, path_1.join)(process.cwd(), dir)).catch(() => {
133 console.error(chalk.red(ui_1.MESSAGES.GIT_INITIALIZATION_ERROR));
134 });
135});
136/**
137 * Write a file `.gitignore` in the root of the newly created project.
138 * `.gitignore` available in `@nestjs/schematics` cannot be published to
139 * NPM (needs to be investigated).
140 *
141 * @param dir Relative path to the project.
142 * @param content (optional) Content written in the `.gitignore`.
143 *
144 * @return Resolves when succeeds, or rejects with any error from `fn.writeFile`.
145 */
146const createGitIgnoreFile = (dir, content) => {
147 const fileContent = content || defaults_1.defaultGitIgnore;
148 const filePath = (0, path_1.join)(process.cwd(), dir, '.gitignore');
149 return (0, util_1.promisify)(fs.writeFile)(filePath, fileContent);
150};
151const printCollective = () => {
152 const dim = print('dim');
153 const yellow = print('yellow');
154 const emptyLine = print();
155 emptyLine();
156 yellow(`Thanks for installing Nest ${ui_1.EMOJIS.PRAY}`);
157 dim('Please consider donating to our open collective');
158 dim('to help us maintain this package.');
159 emptyLine();
160 emptyLine();
161 print()(`${chalk.bold(`${ui_1.EMOJIS.WINE} Donate:`)} ${chalk.underline('https://opencollective.com/nest')}`);
162 emptyLine();
163};
164const print = (color = null) => (str = '') => {
165 const terminalCols = (0, exports.retrieveCols)();
166 const strLength = str.replace(/\u001b\[[0-9]{2}m/g, '').length;
167 const leftPaddingLength = Math.floor((terminalCols - strLength) / 2);
168 const leftPadding = ' '.repeat(Math.max(leftPaddingLength, 0));
169 if (color) {
170 str = chalk[color](str);
171 }
172 console.log(leftPadding, str);
173};
174const retrieveCols = () => {
175 const defaultCols = 80;
176 try {
177 const terminalCols = (0, child_process_1.execSync)('tput cols', {
178 stdio: ['pipe', 'pipe', 'ignore'],
179 });
180 return parseInt(terminalCols.toString(), 10) || defaultCols;
181 }
182 catch (_a) {
183 return defaultCols;
184 }
185};
186exports.retrieveCols = retrieveCols;
187const exit = () => process.exit(1);
188exports.exit = exit;