UNPKG

8.53 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 strings_1 = require("@angular-devkit/core/src/utils/strings");
14const chalk = require("chalk");
15const child_process_1 = require("child_process");
16const fs = require("fs");
17const inquirer = require("inquirer");
18const path_1 = require("path");
19const util_1 = require("util");
20const defaults_1 = require("../lib/configuration/defaults");
21const package_managers_1 = require("../lib/package-managers");
22const questions_1 = require("../lib/questions/questions");
23const git_runner_1 = require("../lib/runners/git.runner");
24const schematics_1 = require("../lib/schematics");
25const ui_1 = require("../lib/ui");
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 strings_1.dasherize(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 = [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 questions_1.generateSelect('package-manager')(ui_1.MESSAGES.PACKAGE_MANAGER_QUESTION)([
122 package_managers_1.PackageManager.NPM,
123 package_managers_1.PackageManager.YARN,
124 ]),
125 ];
126 const prompt = inquirer.createPromptModule();
127 return yield prompt(questions);
128});
129const initializeGitRepository = (dir) => __awaiter(void 0, void 0, void 0, function* () {
130 const runner = new git_runner_1.GitRunner();
131 yield runner.run('init', true, path_1.join(process.cwd(), dir)).catch(() => {
132 console.error(chalk.red(ui_1.MESSAGES.GIT_INITIALIZATION_ERROR));
133 });
134});
135/**
136 * Write a file `.gitignore` in the root of the newly created project.
137 * `.gitignore` available in `@nestjs/schematics` cannot be published to
138 * NPM (needs to be investigated).
139 *
140 * @param dir Relative path to the project.
141 * @param content (optional) Content written in the `.gitignore`.
142 *
143 * @return Resolves when succeeds, or rejects with any error from `fn.writeFile`.
144 */
145const createGitIgnoreFile = (dir, content) => {
146 const fileContent = content || defaults_1.defaultGitIgnore;
147 const filePath = path_1.join(process.cwd(), dir, '.gitignore');
148 return util_1.promisify(fs.writeFile)(filePath, fileContent);
149};
150const printCollective = () => {
151 const dim = print('dim');
152 const yellow = print('yellow');
153 const emptyLine = print();
154 emptyLine();
155 yellow(`Thanks for installing Nest ${ui_1.EMOJIS.PRAY}`);
156 dim('Please consider donating to our open collective');
157 dim('to help us maintain this package.');
158 emptyLine();
159 emptyLine();
160 print()(`${chalk.bold(`${ui_1.EMOJIS.WINE} Donate:`)} ${chalk.underline('https://opencollective.com/nest')}`);
161 emptyLine();
162};
163const print = (color = null) => (str = '') => {
164 const terminalCols = exports.retrieveCols();
165 const strLength = str.replace(/\u001b\[[0-9]{2}m/g, '').length;
166 const leftPaddingLength = Math.floor((terminalCols - strLength) / 2);
167 const leftPadding = ' '.repeat(Math.max(leftPaddingLength, 0));
168 if (color) {
169 str = chalk[color](str);
170 }
171 console.log(leftPadding, str);
172};
173exports.retrieveCols = () => {
174 const defaultCols = 80;
175 try {
176 const terminalCols = child_process_1.execSync('tput cols', {
177 stdio: ['pipe', 'pipe', 'ignore'],
178 });
179 return parseInt(terminalCols.toString(), 10) || defaultCols;
180 }
181 catch (_a) {
182 return defaultCols;
183 }
184};
185exports.exit = () => process.exit(1);