UNPKG

2.7 kBJavaScriptView Raw
1"use strict";
2
3const { promisifyAll } = require('bluebird');
4const fse = require('fs-extra');
5const exec = promisifyAll(require('child_process')).execAsync;
6const path = require('path');
7const validateNpmPackageName = require("validate-npm-package-name");
8const ArgError = require('../errors.js').ArgError;
9
10module.exports.init = async function init(name) {
11 const ora = require('ora');
12 const prompts = require('prompts');
13
14 if (typeof name !== 'string' || !name.trim()) {
15 const response = await prompts({
16 type: 'text',
17 name: 'project',
18 message: 'Please enter Project name',
19 validate: value => String(value).length > 3
20 });
21 name = response.project;
22 }
23
24 const fullpath = path.resolve(name);
25
26 if (fse.existsSync(fullpath) && fse.readdirSync(fullpath).length !== 0) {
27 console.log(`${fullpath} is not empty. Quiting...`);
28 process.exit(1);
29 }
30
31 const packageName = fullpath.substr(Math.max(fullpath.lastIndexOf('/'), fullpath.lastIndexOf('\\')) + 1);
32
33 const nameValidity = validateNpmPackageName(packageName);
34
35 if (!nameValidity.validForNewPackages) {
36 if (nameValidity.errors) nameValidity.errors.forEach((e) => console.log(e));
37 if (nameValidity.warnings) nameValidity.warnings.forEach((e) => console.log(e));
38
39 throw new ArgError("Package name is not valid");
40 }
41
42 const response = await prompts({
43 type: 'toggle',
44 name: 'isJs',
45 message: 'Add support for TypeScript?',
46 initial: true,
47 active: 'no',
48 inactive: 'yes'
49 });
50
51 const sourceFolder = response.isJs ? 'template.js' : 'template.ts';
52
53 const source = path.join(__dirname, sourceFolder);
54 const dest = path.join(process.cwd(), name);
55
56 let spinner = ora(`Creating new test project in ${dest}`).start();
57
58 await fse.copy(source, dest);
59
60 const sourcePackageJson = path.join(__dirname, sourceFolder, 'package.json');
61 const destPackageJson = path.join(process.cwd(), name, 'package.json');
62
63 const packageContents = await fse.readFile(sourcePackageJson);
64
65 const newPackageJson = packageContents.toString().replace('~testim-codeful-test-project~', packageName);
66
67 await fse.writeFile(destPackageJson, newPackageJson);
68
69 const gitIgnore = 'node_modules';
70 const gitIgnoreFilePath = path.join(process.cwd(), name, '.gitignore');
71 await fse.writeFile(gitIgnoreFilePath, gitIgnore);
72
73 spinner.succeed();
74 spinner = ora('Installing dependencies').start();
75 await exec('npm install', { cwd: dest });
76
77 spinner.succeed();
78
79 console.log(`Testim Dev Kit project folder successfully created in ${dest}.`);
80
81};