create-rv-cli
Version:
## 简介 ---- 可用于自动化创建 vue 和 react 工程的命令工具
934 lines (922 loc) • 33.8 kB
JavaScript
#! /usr/bin/env node
import chalk from 'chalk';
import { Command } from 'commander';
import semver from 'semver';
import path from 'path';
import prompts from 'prompts';
import fs from 'fs-extra';
import { execSync, exec } from 'child_process';
import validateProjectName from 'validate-npm-package-name';
import ora from 'ora';
import fetch from 'node-fetch';
import __cjs_url__ from 'url';
import __cjs_path__ from 'path';
import __cjs_mod__ from 'module';
const __filename = __cjs_url__.fileURLToPath(import.meta.url);
const __dirname = __cjs_path__.dirname(__filename);
const require = __cjs_mod__.createRequire(import.meta.url);
// 处理程序退出
var handleExit = function handleExit() {
var exitStatus = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
console.error(chalk.red("Exiting without error.\n"));
process.exit(exitStatus);
};
// 处理打印错误信息
var handleError = function handleError(error) {
var exitStatus = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
console.log('');
error && console.error(chalk.red("ERROR! \n" + "".concat(error ? error.message || error : '')));
handleExit(exitStatus);
};
function _regeneratorRuntime() {
_regeneratorRuntime = function () {
return e;
};
var t,
e = {},
r = Object.prototype,
n = r.hasOwnProperty,
o = Object.defineProperty || function (t, e, r) {
t[e] = r.value;
},
i = "function" == typeof Symbol ? Symbol : {},
a = i.iterator || "@@iterator",
c = i.asyncIterator || "@@asyncIterator",
u = i.toStringTag || "@@toStringTag";
function define(t, e, r) {
return Object.defineProperty(t, e, {
value: r,
enumerable: !0,
configurable: !0,
writable: !0
}), t[e];
}
try {
define({}, "");
} catch (t) {
define = function (t, e, r) {
return t[e] = r;
};
}
function wrap(t, e, r, n) {
var i = e && e.prototype instanceof Generator ? e : Generator,
a = Object.create(i.prototype),
c = new Context(n || []);
return o(a, "_invoke", {
value: makeInvokeMethod(t, r, c)
}), a;
}
function tryCatch(t, e, r) {
try {
return {
type: "normal",
arg: t.call(e, r)
};
} catch (t) {
return {
type: "throw",
arg: t
};
}
}
e.wrap = wrap;
var h = "suspendedStart",
l = "suspendedYield",
f = "executing",
s = "completed",
y = {};
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
var p = {};
define(p, a, function () {
return this;
});
var d = Object.getPrototypeOf,
v = d && d(d(values([])));
v && v !== r && n.call(v, a) && (p = v);
var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p);
function defineIteratorMethods(t) {
["next", "throw", "return"].forEach(function (e) {
define(t, e, function (t) {
return this._invoke(e, t);
});
});
}
function AsyncIterator(t, e) {
function invoke(r, o, i, a) {
var c = tryCatch(t[r], t, o);
if ("throw" !== c.type) {
var u = c.arg,
h = u.value;
return h && "object" == typeof h && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) {
invoke("next", t, i, a);
}, function (t) {
invoke("throw", t, i, a);
}) : e.resolve(h).then(function (t) {
u.value = t, i(u);
}, function (t) {
return invoke("throw", t, i, a);
});
}
a(c.arg);
}
var r;
o(this, "_invoke", {
value: function (t, n) {
function callInvokeWithMethodAndArg() {
return new e(function (e, r) {
invoke(t, n, e, r);
});
}
return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
}
});
}
function makeInvokeMethod(e, r, n) {
var o = h;
return function (i, a) {
if (o === f) throw new Error("Generator is already running");
if (o === s) {
if ("throw" === i) throw a;
return {
value: t,
done: !0
};
}
for (n.method = i, n.arg = a;;) {
var c = n.delegate;
if (c) {
var u = maybeInvokeDelegate(c, n);
if (u) {
if (u === y) continue;
return u;
}
}
if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) {
if (o === h) throw o = s, n.arg;
n.dispatchException(n.arg);
} else "return" === n.method && n.abrupt("return", n.arg);
o = f;
var p = tryCatch(e, r, n);
if ("normal" === p.type) {
if (o = n.done ? s : l, p.arg === y) continue;
return {
value: p.arg,
done: n.done
};
}
"throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg);
}
};
}
function maybeInvokeDelegate(e, r) {
var n = r.method,
o = e.iterator[n];
if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y;
var i = tryCatch(o, e.iterator, r.arg);
if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y;
var a = i.arg;
return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y);
}
function pushTryEntry(t) {
var e = {
tryLoc: t[0]
};
1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e);
}
function resetTryEntry(t) {
var e = t.completion || {};
e.type = "normal", delete e.arg, t.completion = e;
}
function Context(t) {
this.tryEntries = [{
tryLoc: "root"
}], t.forEach(pushTryEntry, this), this.reset(!0);
}
function values(e) {
if (e || "" === e) {
var r = e[a];
if (r) return r.call(e);
if ("function" == typeof e.next) return e;
if (!isNaN(e.length)) {
var o = -1,
i = function next() {
for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next;
return next.value = t, next.done = !0, next;
};
return i.next = i;
}
}
throw new TypeError(typeof e + " is not iterable");
}
return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", {
value: GeneratorFunctionPrototype,
configurable: !0
}), o(GeneratorFunctionPrototype, "constructor", {
value: GeneratorFunction,
configurable: !0
}), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) {
var e = "function" == typeof t && t.constructor;
return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name));
}, e.mark = function (t) {
return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t;
}, e.awrap = function (t) {
return {
__await: t
};
}, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () {
return this;
}), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) {
void 0 === i && (i = Promise);
var a = new AsyncIterator(wrap(t, r, n, o), i);
return e.isGeneratorFunction(r) ? a : a.next().then(function (t) {
return t.done ? t.value : a.next();
});
}, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () {
return this;
}), define(g, "toString", function () {
return "[object Generator]";
}), e.keys = function (t) {
var e = Object(t),
r = [];
for (var n in e) r.push(n);
return r.reverse(), function next() {
for (; r.length;) {
var t = r.pop();
if (t in e) return next.value = t, next.done = !1, next;
}
return next.done = !0, next;
};
}, e.values = values, Context.prototype = {
constructor: Context,
reset: function (e) {
if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t);
},
stop: function () {
this.done = !0;
var t = this.tryEntries[0].completion;
if ("throw" === t.type) throw t.arg;
return this.rval;
},
dispatchException: function (e) {
if (this.done) throw e;
var r = this;
function handle(n, o) {
return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o;
}
for (var o = this.tryEntries.length - 1; o >= 0; --o) {
var i = this.tryEntries[o],
a = i.completion;
if ("root" === i.tryLoc) return handle("end");
if (i.tryLoc <= this.prev) {
var c = n.call(i, "catchLoc"),
u = n.call(i, "finallyLoc");
if (c && u) {
if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
} else if (c) {
if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
} else {
if (!u) throw new Error("try statement without catch or finally");
if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
}
}
}
},
abrupt: function (t, e) {
for (var r = this.tryEntries.length - 1; r >= 0; --r) {
var o = this.tryEntries[r];
if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) {
var i = o;
break;
}
}
i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null);
var a = i ? i.completion : {};
return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a);
},
complete: function (t, e) {
if ("throw" === t.type) throw t.arg;
return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y;
},
finish: function (t) {
for (var e = this.tryEntries.length - 1; e >= 0; --e) {
var r = this.tryEntries[e];
if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y;
}
},
catch: function (t) {
for (var e = this.tryEntries.length - 1; e >= 0; --e) {
var r = this.tryEntries[e];
if (r.tryLoc === t) {
var n = r.completion;
if ("throw" === n.type) {
var o = n.arg;
resetTryEntry(r);
}
return o;
}
}
throw new Error("illegal catch attempt");
},
delegateYield: function (e, r, n) {
return this.delegate = {
iterator: values(e),
resultName: r,
nextLoc: n
}, "next" === this.method && (this.arg = t), y;
}
}, e;
}
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
// const __filename = fileURLToPath(import.meta.url);
// const __dirname = dirname(__filename);
var PROJECT_PATH = process.cwd();
var PACKAGE = 'package.json';
var CURR_FILE_PATH = __dirname;
var PACKAGE_PATH = path.resolve(CURR_FILE_PATH, "../".concat(PACKAGE));
// webpack + react18 + redux
var REACT_WEBPACK_REPOSITORY_A_PATH = 'https://gitee.com/my_domain/rc-react-project.git';
// vite + react18 + redux
var REACT_VITE_REPOSITORY_A_PATH = 'https://gitee.com/my_domain/vite-react.git';
// webpack + vue2
var VUE_WEBPACK_REPOSITORY_PATH = 'https://gitee.com/my_domain/v-service-project.git';
var REGISTRY_URL = {
npm: 'https://registry.npmjs.org',
yarn: 'https://registry.yarnpkg.com',
taobao: 'https://registry.npmmirror.com'
};
var pathResolve = function pathResolve() {
var project = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : './';
var filePath = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : PROJECT_PATH;
var projectPath = path.resolve(filePath, project);
return projectPath;
};
var packageValues = [{
type: 'text',
name: 'name',
initial: 'project',
message: '项目名称?'
}, {
type: 'text',
name: 'author',
initial: '',
message: '项目作者?'
}, {
type: 'text',
name: 'description',
initial: '',
message: '项目描述?'
}, {
type: 'text',
name: 'license',
initial: 'none',
message: '项目许可证?'
}, {
type: 'toggle',
name: 'isPrivate',
initial: false,
message: '是否为私人项目?',
active: 'true',
inactive: 'false'
}];
var promptsProjectFrame = /*#__PURE__*/function () {
var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
var selectAnswer;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return prompts({
type: 'select',
name: 'frame',
message: '请选择使用开发框架?',
choices: [{
title: 'React',
value: 'react',
description: '使用React'
}, {
title: 'Vue',
value: 'vue',
description: '使用Vue'
}]
});
case 2:
selectAnswer = _context.sent;
if (!selectAnswer) {
process.exit(0);
}
return _context.abrupt("return", selectAnswer);
case 5:
case "end":
return _context.stop();
}
}, _callee);
}));
return function promptsProjectFrame() {
return _ref.apply(this, arguments);
};
}();
var promptsReactUseSchema = /*#__PURE__*/function () {
var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(_ref2) {
var appName, firstArr, mergeArr, selectAnswer;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
appName = _ref2.appName;
firstArr = [{
type: 'select',
name: 'schema',
message: '请选择使用架构?',
choices: [{
title: 'webpack',
value: 'webpack',
description: 'webpack + react18 + react-redux + react-dom + mocker-api + ts|js + scss|less'
}, {
title: 'vite',
value: 'vite',
description: 'webpack + react + react-redux + react-dom + vite-plugin-mock + ts|js + scss|less'
}]
}]; // @ts-ignore
mergeArr = firstArr.concat(packageValues);
mergeArr[1].initial = appName;
// @ts-ignore
_context2.next = 6;
return prompts(mergeArr);
case 6:
selectAnswer = _context2.sent;
if (!selectAnswer) {
process.exit(0);
}
return _context2.abrupt("return", selectAnswer);
case 9:
case "end":
return _context2.stop();
}
}, _callee2);
}));
return function promptsReactUseSchema(_x) {
return _ref3.apply(this, arguments);
};
}();
var promptsVueUseSchema = /*#__PURE__*/function () {
var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(_ref4) {
var appName, firstArr, mergeArr, selectAnswer;
return _regeneratorRuntime().wrap(function _callee3$(_context3) {
while (1) switch (_context3.prev = _context3.next) {
case 0:
appName = _ref4.appName;
firstArr = []; // @ts-ignore
mergeArr = firstArr.concat(packageValues);
mergeArr[0].initial = appName;
// @ts-ignore
_context3.next = 6;
return prompts(mergeArr);
case 6:
selectAnswer = _context3.sent;
if (!selectAnswer) {
process.exit(0);
}
return _context3.abrupt("return", selectAnswer);
case 9:
case "end":
return _context3.stop();
}
}, _callee3);
}));
return function promptsVueUseSchema(_x2) {
return _ref5.apply(this, arguments);
};
}();
function createSuccessTip(frame, appName) {
execSync("find ".concat(pathResolve("./".concat(appName)), " -name \".git\" | xargs rm -Rf"));
console.log();
console.log(chalk.green("".concat(frame, " \u5E94\u7528\u521B\u5EFA\u6210\u529F!")));
console.log();
console.log(chalk.green("\u8BF7\u6267\u884C\u547D\u4EE4".concat(chalk.cyan(" cd ".concat(pathResolve("./".concat(appName)), " ")), "\u8FDB\u5165\u9879\u76EE\u6839\u76EE\u5F55\u4E2D.")));
console.log();
console.log(chalk.green(" \u4F7F\u7528".concat(chalk.cyan(' npm install '), "\u4E0B\u8F7D\u9879\u76EE\u4F9D\u8D56.")));
console.log();
console.log(chalk.green(" \u4F9D\u8D56\u4E0B\u8F7D\u540E\u8BF7\u6267\u884C\u547D\u4EE4".concat(chalk.cyan(' npm run start '), "\u542F\u52A8\u9879\u76EE.")));
console.log();
console.log(chalk.green(" \u9879\u76EE\u5F00\u53D1\u5B8C\u540E\u6267\u884C\u547D\u4EE4".concat(chalk.cyan(' npm run build '), "\u6784\u5EFA\u9879\u76EE.")));
console.log();
}
// 检查项目目录是否符合规范
var checkAppName = function checkAppName(appName) {
var validationResult = validateProjectName(appName);
var isLegalName = true;
if (!validationResult.validForNewPackages) {
isLegalName = false;
var errors = [];
console.error(chalk.red("\u65E0\u6CD5\u521B\u5EFA\u540D\u4E3A ".concat(chalk.green("\"".concat(appName, "\"")), " \u56E0\u4E3A\u4E0D\u7B26\u5408\u547D\u540D\u89C4\u8303\u8BF7\u4FEE\u6539:\n")));
errors.concat(validationResult.errors || [], validationResult.warnings || []);
errors.forEach(function (error) {
console.error(chalk.red(" ## ".concat(error)));
});
}
return isLegalName;
};
// 检查文件或目录访问权限
function checkFileAccessPermission(filePath, createDirectory) {
try {
var accessDirectory = filePath;
if (filePath.endsWith(createDirectory)) accessDirectory = accessDirectory.replace(createDirectory, '');
fs.accessSync(accessDirectory, fs.constants.R_OK | fs.constants.W_OK);
} catch (error) {
handleError(error);
}
}
// 判断文件是否已经存在
function fileDirectoryIsExist(filePath, createDirectory) {
checkFileAccessPermission(filePath, createDirectory);
if (fs.existsSync(filePath)) return true;
return false;
}
// 修改json文件值
var modifyJson = function modifyJson(modifyValues, filePath) {
if (fileDirectoryIsExist(filePath)) {
var frame = modifyValues.frame,
appName = modifyValues.appName;
// 需要修改的项目字段
var modifyKeyValue = ['name', 'author', 'description', 'license', 'private'];
var packageObj = fs.readJsonSync(filePath);
var newModifyValues = modifyKeyValue.reduce(function (init, key) {
if (modifyValues) {
init[key] = modifyValues[key];
}
return init;
}, {});
var newPackageObj = Object.assign({}, packageObj, newModifyValues);
fs.writeJsonSync(filePath, newPackageObj, {
spaces: 4
});
createSuccessTip(frame, appName);
}
};
// 处理文件错误
var fileDirectoryRedoWarn = function fileDirectoryRedoWarn(filePath, createDirectory) {
if (fileDirectoryIsExist(filePath, createDirectory)) handleError("".concat(filePath, " \u76EE\u5F55\u5DF2\u7ECF\u5B58\u5728"));
};
// 获取package相关数据
var getPackageJson = function getPackageJson() {
var packageObj = fs.readJsonSync(PACKAGE_PATH);
return packageObj;
};
// 检查当前包是否事最新包
var getLatestVersion = /*#__PURE__*/function () {
var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
var command, packageJson, shell, res, spinners;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
command = 'npm'; // if (envIsIncludeYarn()) command = 'yarn';
packageJson = getPackageJson();
shell = "".concat(command, " info ").concat(packageJson.name, " --json");
_context.prev = 3;
_context.next = 6;
return fetch("".concat(REGISTRY_URL[command], "/").concat(packageJson.name, "/latest")).then(function (result) {
return result.json();
});
case 6:
res = _context.sent;
if (res.version) {
_context.next = 9;
break;
}
throw new Error('Not found');
case 9:
return _context.abrupt("return", res.version);
case 12:
_context.prev = 12;
_context.t0 = _context["catch"](3);
spinners = ora().start();
return _context.abrupt("return", new Promise(function (resolve) {
exec(shell, function (error, stdout) {
if (error) {
handleError("\u7248\u672C\u67E5\u8BE2: ".concat(error));
resolve(null);
} else if (!error && stdout) {
var stdoutJson = JSON.parse(stdout);
if (stdoutJson.data && stdoutJson.data.versions) {
var versions = stdoutJson.data.versions;
var lastVersion = versions[versions.length - 1];
resolve(lastVersion);
} else {
resolve(null);
}
} else {
resolve(null);
}
spinners.stop();
});
}));
case 16:
case "end":
return _context.stop();
}
}, _callee, null, [[3, 12]]);
}));
return function getLatestVersion() {
return _ref.apply(this, arguments);
};
}();
// 检查 是否有安装git
var envIsIncludeGit = function envIsIncludeGit() {
return new Promise(function (resolve, reject) {
exec('git --version', function (error) {
if (error) {
reject(false);
console.error(chalk.red("ERROR! \n" + "".concat(chalk.bold('Note: 没有找到git,请先下载git.'))));
return process.exit(1);
}
resolve(true);
});
});
};
// git 克隆下载仓库
var gitCloneRepository = function gitCloneRepository(repoPath) {
var assignDownloadPath = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
if (!repoPath) {
handleError("\u4ED3\u5E93\u5730\u5740\u4E0D\u80FD\u4E3A\u7A7A");
}
var spinners = ora('pull...').start();
return new Promise(function (resolve, reject) {
exec("git clone ".concat(repoPath, " ").concat(assignDownloadPath), function (error) {
spinners.stop();
if (error) {
reject(false);
handleError(error);
} else {
resolve(true);
}
});
});
};
var gitPull$1 = /*#__PURE__*/function () {
var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(projectDire, options) {
var schema, projectPath, result, projectDirePackagePath;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
schema = options.schema;
projectPath = '';
if (schema === 'vite') {
projectPath = REACT_VITE_REPOSITORY_A_PATH;
} else if (schema === 'webpack') {
projectPath = REACT_WEBPACK_REPOSITORY_A_PATH;
}
_context.next = 5;
return gitCloneRepository(projectPath, projectDire);
case 5:
result = _context.sent;
projectDirePackagePath = path.join(projectDire, PACKAGE);
if (result) {
modifyJson(options, projectDirePackagePath);
}
case 8:
case "end":
return _context.stop();
}
}, _callee);
}));
return function gitPull(_x, _x2) {
return _ref.apply(this, arguments);
};
}();
var pullReactProject = /*#__PURE__*/function () {
var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(projectDire, options) {
var appName, frame, result, _ref3, author, name, description, license, isPrivate, schema;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
appName = options.appName, frame = options.frame;
_context2.next = 3;
return promptsReactUseSchema({
appName: appName
});
case 3:
result = _context2.sent;
_ref3 = result || {}, author = _ref3.author, name = _ref3.name, description = _ref3.description, license = _ref3.license, isPrivate = _ref3.isPrivate, schema = _ref3.schema;
gitPull$1(projectDire, {
name: name,
author: author,
description: description,
license: license,
"private": isPrivate,
schema: schema,
frame: frame,
appName: appName
});
case 6:
case "end":
return _context2.stop();
}
}, _callee2);
}));
return function pullReactProject(_x3, _x4) {
return _ref2.apply(this, arguments);
};
}();
var gitPull = /*#__PURE__*/function () {
var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(projectDire, options) {
var result, projectDirePackagePath;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return gitCloneRepository(VUE_WEBPACK_REPOSITORY_PATH, projectDire);
case 2:
result = _context.sent;
projectDirePackagePath = path.join(projectDire, PACKAGE);
if (result) {
modifyJson(options, projectDirePackagePath);
}
case 5:
case "end":
return _context.stop();
}
}, _callee);
}));
return function gitPull(_x, _x2) {
return _ref.apply(this, arguments);
};
}();
var pullVueProject = /*#__PURE__*/function () {
var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(projectDire, options) {
var appName, frame, result, _ref3, author, name, description, license, isPrivate, schema;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
appName = options.appName, frame = options.frame;
_context2.next = 3;
return promptsVueUseSchema({
appName: appName
});
case 3:
result = _context2.sent;
_ref3 = result || {}, author = _ref3.author, name = _ref3.name, description = _ref3.description, license = _ref3.license, isPrivate = _ref3.isPrivate, schema = _ref3.schema;
gitPull(projectDire, {
name: name,
author: author,
description: description,
license: license,
"private": isPrivate,
schema: schema,
frame: frame,
appName: appName
});
case 6:
case "end":
return _context2.stop();
}
}, _callee2);
}));
return function pullVueProject(_x3, _x4) {
return _ref2.apply(this, arguments);
};
}();
// 检测node版本
var checkNodeVersion = function checkNodeVersion() {
var defaultNodeVersion = '12.17';
var currentNodeVersion = !semver.satisfies(
// @ts-ignore
process.version, ">=".concat(defaultNodeVersion));
if (currentNodeVersion) {
console.log();
console.log(chalk.red("\u5F53\u524D\u4F7F\u7528Node\u7248\u672C\u4E3A ".concat(process.version, " \u8BE5\u7248\u672C\u8FC7\u4F4E\u9700\u8981\u4F7F\u7528\u66F4\u9AD8Node\u7248\u672C.\n\n") + "\u8BF7\u66F4\u65B0\u5230Node ".concat(defaultNodeVersion, " \u6216\u8005\u66F4\u9AD8\uFF0C\u4EE5\u83B7\u5F97\u66F4\u597D\u7684\u3001\u5B8C\u5168\u652F\u6301\u7684\u4F53\u9A8C.\n")));
console.log();
process.exit(1);
}
};
// 创建项目
var createProject = /*#__PURE__*/function () {
var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(appName, options) {
var latestVersion, currentVersion, isLatestVersion, projectDire, frame, result;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
// 检查node环境
checkNodeVersion();
// 检查包版本
_context.next = 3;
return getLatestVersion();
case 3:
latestVersion = _context.sent;
currentVersion = getPackageJson();
isLatestVersion = semver.satisfies(
// @ts-ignore
latestVersion, ">".concat(currentVersion.version));
if (isLatestVersion) {
// 检查版本
console.log();
console.error(chalk.yellow("\u60A8\u6B63\u5728\u8FD0\u884C\u7684\u7248\u672C\u8FC7\u4F4E ".concat(currentVersion.name, "(").concat(currentVersion.version, "), \u6700\u65B0\u7248\u672C\u4E3A(").concat(latestVersion, ").\n\n") + "\u8BF7\u4F7F\u7528 ".concat(chalk.cyan("npm install -g ".concat(currentVersion.name, "@^").concat(latestVersion)), " \u66F4\u65B0\u5230\u6700\u65B0\u7248\u4E4B\u540E\u518D\u4F7F\u7528.")));
console.log();
process.exit(1);
}
// 检查项目名是否符合npm命名规范
checkAppName(appName);
// 需要依赖环境git命令
_context.next = 10;
return envIsIncludeGit();
case 10:
projectDire = path.join(PROJECT_PATH, appName);
fileDirectoryRedoWarn(projectDire, appName);
frame = options.by;
if (frame) {
_context.next = 18;
break;
}
_context.next = 16;
return promptsProjectFrame();
case 16:
result = _context.sent;
frame = result.frame;
case 18:
if (frame === 'react') {
pullReactProject(projectDire, {
appName: appName,
frame: frame
});
} else if (frame === 'vue') {
pullVueProject(projectDire, {
appName: appName,
frame: frame
});
} else {
frame && handleError("\u65E0\u6CD5\u521B\u5EFA\u6B64\u7C7B\u578B\u7684\u9879\u76EE: ".concat(frame));
}
case 19:
case "end":
return _context.stop();
}
}, _callee);
}));
return function createProject(_x, _x2) {
return _ref.apply(this, arguments);
};
}();
var create = function create(name, options) {
createProject(name, options)["catch"](function (err) {
console.error(chalk.red("Error\uFF1A\n ".concat(err.message || err)));
process.exit(1);
});
};
var program = new Command();
var packageJson = getPackageJson();
process.on('SIGINT', handleExit); // 终止监听
process.on('SIGTERM', handleExit); // 终止监听
process.on('uncaughtException', handleError); // 异常监听
process.on('unhandledRejection', handleError); // 异常监听
program.version(packageJson.version).usage('<command> [options]');
program.command('project <project-directory>').option('-b, --by <frame>', '使用技术栈').description("\u5FEB\u901F\u521B\u5EFA\u4E00\u4E2A\u65B0\u9879\u76EE. ".concat(chalk.bold(chalk.yellow('注意: 您需要先下载git')))).usage("".concat(chalk.green('<project-directory>'))).allowExcessArguments(false).action(function (name, options) {
create(name, options);
}).on('--help', function () {
console.log(" \u547D\u4EE4\u9879\u76EE\u53C2\u6570 ".concat(chalk.green('<project-directory>'), " \u662F\u5FC5\u9700\u7684."));
console.log();
});
program.command('info').description('查看当前设备及Node相关基本信息').action(function () {
console.log(chalk.bold(chalk.yellow('\n环境信息:')));
require('envinfo').run({
System: ['OS', 'CPU'],
Binaries: ['Node', 'npm', 'Yarn'],
Browsers: ['Chrome', 'Edge', 'Internet Explorer', 'Firefox', 'Safari']
}, {
showNotFound: true,
duplicates: true,
fullTree: true
}).then(function (info) {
return console.log(chalk.yellow(info));
});
});
program.parse(process.argv);