UNPKG

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