UNPKG

@beisen/bscpm

Version:
389 lines (342 loc) 12.9 kB
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs); var _yeomanGenerator = require('yeoman-generator'); var _yeomanGenerator2 = _interopRequireDefault(_yeomanGenerator); var _requestPromise = require('request-promise'); var _requestPromise2 = _interopRequireDefault(_requestPromise); var _execa = require('execa'); var _execa2 = _interopRequireDefault(_execa); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } exports.default = class extends _yeomanGenerator2.default { prompting() { var _this = this; return _asyncToGenerator(function* () { const { CMP_SERVER_HOST, GITLAB_HOST } = process.env; const schemaApiHost = `http://10.129.6.88:5009`; let { username } = _this.options; _this.selectGroupName; _this.selectSchema; // 请求可使用的分组 _this.groupNames = []; _this.groupNameCNMaps = {}; _this.schemaMap = {}; _this.schemas = []; _this.schemaVersions = []; try { let groups = yield _requestPromise2.default.get(`${CMP_SERVER_HOST}/api/v2/groups`); JSON.parse(groups).forEach(function (group) { let shownNameCN = `${group.nameCN} (${group.name})`; _this.groupNames.push(shownNameCN); _this.groupNameCNMaps[shownNameCN] = group.name; }); } catch (e) {} // throw new Error('应用信息获取失败,请检查网络连接是否正确') // 获取Schema类型 try { yield _requestPromise2.default.get({ 'uri': `${schemaApiHost}/v1/schemas`, 'qs': { 'type': '1' }, 'headers': { 'Content-Type': 'application/json' }, 'json': true }).then(function (res) { for (let i = 0; i < res.Data.length; i++) { _this.schemaMap[res.Data[i]._name] = res.Data[i]; _this.schemas.push(res.Data[i]._name); } }); } catch (e) {} // throw new Error('应用信息获取失败,请检查网络连接是否正确') // 提供开发者输入其他应用 _this.groupNames.push('其它应用'); // 如果为传递用户名,则自动获取,用于给Gitlab项目添加权限 if (!username) { try { const { stdout } = _execa2.default.sync('git', ['config', 'user.name']); username = `${stdout}`.replace(/^\s+|\s+$/, ''); } catch (err) {} } if (!username) { console.log(`未通过 'git config user.name' 获取到用户名,无法在Gitlab项目中添加开发者权限`); console.log(`解决方案:`); console.log(` 1. 通过 'git config user.name' 命令设置与Gitlab相同的用户名`); console.log(` 2. 使用 '--username' 参数,例如:'bscpm create --username guojia6'`); return; } yield _this.prompt([{ 'type': 'input', 'name': 'projectName', 'message': '项目名称(Gitlab项目名称):', 'validate': function (value) { if (!value.match(/^[a-zA-Z\-\d]+?$/)) { return '项目名式不正确, 只能包含大小写字母、数字、中划线'; } return true; } }, { 'type': 'input', 'name': 'moduleName', 'message': '组件名 (package.json 中的 name):', 'validate': function (value) { if (!value.match(/^[@\/a-z\-\d]+?$/)) { return '组件名称格式不正确, 只能包含小写英文、数字、中划线'; } return true; } }, { 'type': 'input', 'name': 'nameCN', 'message': '组件中文名:' }, { 'type': 'list', 'name': 'reactVersion', 'message': 'React版本:', 'choices': ['16', '15'] }, { 'type': 'confirm', 'name': 'useTypescript', 'message': '是否使用 typescript:', 'default': true }, { 'type': 'list', 'name': 'cssLanguage', 'message': '使用的 CSS 语言:', 'choices': ['css', 'sass', 'less', 'style-components'] }, { 'type': 'list', 'name': 'cmpType', 'message': '组件类型:', 'choices': ['UIComponent', 'ThunderPage'] }, { 'type': 'confirm', 'name': 'isSyncGitlab', 'message': '是否在Gitlab创建项目', 'default': true // 'when': answers => { // return answers.cmpType == 'UIComponent' // } }, { 'type': 'input', 'name': 'description', 'message': '项目描述:' }, { 'type': 'input', 'name': 'group', 'message': '项目所在Gitlab的分组:', 'default': 'ux-share-platform', 'when': function (answers) { return answers.isSyncGitlab; // || answers.cmpType == 'ThunderPage' } }, { 'type': 'list', 'name': 'category', 'message': 'UI组件类型:', 'choices': ['Common', 'Text', 'Form', 'List', 'Chart', 'Layout', 'Table', 'Tree'], 'when': function (answers) { return answers.cmpType == 'UIComponent'; } }, { 'type': 'list', 'name': 'team', 'message': '所属应用:', 'choices': _this.groupNames, 'pageSize': 20, 'when': function (answers) { return _this.groupNames.length > 0; }, 'validate': function (value) { _this.selectGroupName = value; // 用于判断是否让开发者输入分组 return true; }, 'transformer': function (value) { _this.selectGroupName = value; // 用于判断是否让开发者输入分组 return value; }, 'filter': function (value) { _this.selectGroupName = value; // 用于判断是否让开发者输入分组 return value; } }, { 'type': 'input', 'name': 'otherGroup', 'message': '其他应用编码:', 'when': function (answers) { return _this.selectGroupName == '其它应用'; } }, { 'type': 'list', 'name': 'device', 'message': '适配的设备:', 'choices': ['pc', 'mobile'] }, { 'type': 'confirm', 'name': 'hasSchema', 'message': '是否配置Schema:', 'default': true }, { 'type': 'list', 'name': 'schemaName', 'message': 'Schema:', 'choices': _this.schemas, 'pageSize': 20, 'when': function (answers) { return answers.hasSchema; } }]).then(function (promptes) { let { projectName, moduleName, nameCN, description, group, category, team = '', device, reactVersion, cmpType, useTypescript, cssLanguage, otherGroup, schemaName, schemaVersion } = promptes; _this.promptes = promptes; // 开发者未提供中文名、项目名,默认使用组件名 if (!nameCN) { nameCN = moduleName; } if (!projectName) { projectName = moduleName; } _this.promptes.projectName = projectName; _this.promptes.nameCN = nameCN; _this.promptes.cmpType = cmpType; _this.promptes.username = username; _this.promptes.useTypescript = useTypescript; _this.promptes.cssLanguage = cssLanguage; _this.promptes.repository = ''; // 页面模版默认创建Gitlab项目和默认类型 if (cmpType == 'ThunderPage') { // this.promptes.isSyncGitlab = true _this.promptes.category = 'ThunderPage'; } if (otherGroup) { _this.promptes.team = otherGroup; } else { _this.promptes.team = _this.groupNameCNMaps[team]; // 获取真正的APP_NAME } }); // 获取schema版本 yield _requestPromise2.default.get({ 'uri': `${schemaApiHost}/v1/schemas`, 'qs': { 'name': _this.promptes.schemaName }, 'headers': { 'Content-Type': 'application/json' }, 'json': true }).then(function (res) { for (let i = 0; i < res.Data.length; i++) { _this.schemaVersions.push(res.Data[i]._ver); } }); return _this.prompt([{ 'type': 'list', 'name': 'schemaVersion', 'message': 'Schema版本:', 'choices': function () { return _this.schemaVersions; }, 'when': function (answers) { return _this.promptes.hasSchema; } }]).then(function (promptes) { Object.assign(_this.promptes, { 'schemaVersion': promptes.schemaVersion }); }); })(); } writing() { var _this2 = this; return _asyncToGenerator(function* () { const { CMP_SERVER_HOST, GITLAB_HOST } = process.env; let { projectName, username, isSyncGitlab, group } = _this2.promptes; if (!isSyncGitlab) { // 创建目录 if (!_fs2.default.existsSync(projectName)) { _fs2.default.mkdirSync(projectName); } else { // 文件夹中有文件,提示错误 let files = _fs2.default.readdirSync(projectName).filter(function (filename) { return filename !== '.git'; }); if (files.length) { return console.log(`fatal: destination path '${projectName}' already exists and is not an empty directory.\n`); } } // 创建、安装 _this2._copyTemplateFiles(); return; } yield _requestPromise2.default.post({ 'url': `${CMP_SERVER_HOST}/api/v1/projects`, 'form': { 'project': projectName, 'username': username, 'group': group, 'hook': `${CMP_SERVER_HOST}/webhooks/push` } }).then(function (body) { const { code, message, data = {} } = JSON.parse(body); // 如果接口中返回非200,异常,则提示错误 if (code !== 200) { let msg = `${message}, 可能是username缺失,如果没有配置 git user.name,可使用 --username 添加Gitlab用户名`; return console.log(msg); } // 项目地址 _this2.promptes.repository = `git@${GITLAB_HOST}:${group}/${projectName}.git`; _this2._copyTemplateFiles(); }).catch(function (err) { console.log(err.message); }); })(); } conflicts() { // init .git set remote const cwd = `${this.options.contextRoot}/${this.promptes.projectName}`; _execa2.default.sync('git', ['init'], { cwd }); _execa2.default.sync('git', ['remote', 'add', 'origin', this.promptes.repository], { cwd }); } install() { process.chdir(`${this.promptes.projectName}`); this.npmInstall(); } /* * 封装copy(API),减少代码量 * 28原则:百分之20%的代码解决80%的功能 * 函数名前面添加下滑线,告知Yeoman不自定执行改函数 */ _copyTemplateFiles() { var _this3 = this; return _asyncToGenerator(function* () { let { reactVersion, cmpType } = _this3.promptes; let copies = [['gitignore', '.gitignore'], // npm publish,会忽略 .gitignore 文件 ['index.js', 'src/index.js'], [`package-react-${reactVersion}.json`, 'package.json'], // 根据不同的 React 版本选择 package.json ['npmignore', '.npmignore'], ['bscpmrc.json', '.bscpmrc'], ['README.md']]; _this3._private_copies(copies); })(); } _private_copies(copyJobs = []) { copyJobs.forEach(([tplFilePath, destFilePath]) => { if (!destFilePath) { destFilePath = tplFilePath; } if (!tplFilePath) throw new Error('tplFilePath is none'); if (!destFilePath) throw new Error('destFilePath is none'); // 改变路径为项目目录下 // if (this.promptes.isSyncGitlab) { destFilePath = `${this.promptes.projectName}/${destFilePath}`; // } this.fs.copyTpl(this.templatePath(tplFilePath), this.destinationPath(`${this.options.contextRoot}/${destFilePath}`), this.promptes); }); } }; module.exports = exports['default'];