cli-z-develop 0.0.14 → 0.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +1 -1
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{program as e}from"commander";import t from"chalk";import i from"shelljs";import n from"fs-extra";import o from"minimist";import s from"node:fs";import r from"node:path";import a from"node:os";import c,{AxiosError as l}from"axios";import u from"dayjs";import d from"inquirer";import m from"inquirer/lib/prompts/base.js";import p from"inquirer/lib/utils/paginator.js";import f from"inquirer/lib/utils/events.js";import"inquirer/lib/objects/choices.js";import{map as h,takeUntil as g,filter as y}from"rxjs";import v from"figures";import b from"ora";import j from"child_process";import w from"lint-staged";var $={name:"cli-z-develop",version:"0.0.14",description:"前端本地开发命令行工具",main:"dist/index.js",bin:{z:"./bin/z.js","z-develop":"./bin/z.js"},scripts:{prepare:"husky",dev:"rollup -c -w --environment DEBUG:true",build:"rollup -c",eslint:"eslint '**/*.{ts,js}' --fix",prettier:"prettier -wu .",upload:"npm version patch && npm run build && npm publish --access public --registry https://registry.npmjs.org/"},type:"module",repository:{type:"git",url:"http://git.cxlqd.com/fe-base/cli-z-develop.git"},author:"z",devDependencies:{"@commitlint/cli":"^19.3.0","@commitlint/config-conventional":"^19.2.2","@rollup/plugin-json":"^6.1.0","@rollup/plugin-node-resolve":"^15.2.3","@rollup/plugin-replace":"^5.0.5","@rollup/plugin-terser":"^0.4.4","@types/fs-extra":"^11.0.4","@types/inquirer":"^9.0.7","@types/minimist":"^1.2.5","@types/node":"^20.12.12","@types/shelljs":"^0.8.15","@types/tough-cookie":"^4.0.5","@typescript-eslint/eslint-plugin":"^7.9.0","@typescript-eslint/parser":"^7.9.0",eslint:"^8.57.0","eslint-config-alloy":"^5.1.2","eslint-config-prettier":"^9.1.0",husky:"^9.0.11",prettier:"^3.2.5",rollup:"^4.17.2","rollup-plugin-typescript2":"^0.36.0",tslib:"^2.6.2",typescript:"^5.4.5"},dependencies:{axios:"^1.7.1",chalk:"^5.3.0",commander:"^12.1.0",dayjs:"^1.11.11",figures:"^6.1.0","fs-extra":"^11.2.0",inquirer:"^9.2.22",minimist:"^1.2.8",ora:"^8.0.1",rxjs:"^7.8.1",shelljs:"^0.8.5","lint-staged":"^15.2.2"}};function k(e,t,i,n){return new(i||(i=Promise))((function(o,s){function r(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(r,a)}c((n=n.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const x='{\n "printWidth": 120,\n "tabWidth": 2,\n "useTabs": false,\n "semi": true,\n "singleQuote": false,\n "quoteProps": "as-needed",\n "jsxSingleQuote": false,\n "trailingComma": "all",\n "bracketSpacing": true,\n "bracketSameLine": false,\n "arrowParens": "always",\n "requirePragma": false,\n "insertPragma": false,\n "proseWrap": "preserve",\n "htmlWhitespaceSensitivity": "css",\n "vueIndentScriptAndStyle": false,\n "endOfLine": "lf",\n "embeddedLanguageFormatting": "auto",\n "singleAttributePerLine": false\n}\n',S="# 系统 信息文件\n.DS_Store/\nThumbs.db\n\n# 编辑器配置文件\n.idea/\n.vscode/\n\n# 输出目录\ndist/\n\n# Log files\n*.log\n\n# 本地配置文件\n*.local\n\n# 缓存文件\n*.cache\n\n# 垃圾文件\n.Trashes\n",z={Java:{"**/*.{java}":"./run.sh pmd -d ../../../src/main/java/ -f text -R rulesets/java/quickstart.xml"},JavaScript:{"**/*.{vue,js,jsx,cjs,mjs,ts,tsx,cts,mts}":"eslint --fix","*":"prettier -wu"}},O=[{name:"开发环境 - dev",value:"dev"},{name:"测试环境 - test",value:"test"},{name:"预发环境 - release",value:"release"},{name:"正式环境 - production",value:"production"}],E=[{name:"网页 - h5",value:"h5"},{name:"支付宝小程序 - alipay",value:"alipay"},{name:"微信小程序 - weapp",value:"weapp"},{name:"node module - npm",value:"npm"}],N=["main","master"],q=["dev","test","release"],D=["fix","feat","refactor"],T={1:"研发",2:"测试",3:"产品",4:"设计",5:"运营",6:"销售",7:"行政",8:"财务",9:"其他"},C="http://git.cxlqd.com",I="fe-tpl";function P(e){if(!e)return"不能为空";if(!/^[a-z0-9-]+$/.test(e))return"格式为小写字母、中横线(可选)、数字(不推荐)。如apple, apple-tree";return!V().includes(e)||"当前目录下已存在同名文件夹,请先处理。"}function L(e){return!!e||"不能为空"}function J(e){return e?!!/^[a-zA-Z0-9]+$/.test(e)||"格式为大小写字母、数字,小驼峰命名。如userInfo、systemRouter3":"不能为空"}function _(e){if(!e)return"目录名称不能为空";if(!/^[a-z][a-z0-9\-\/]+$/.test(e))return"支持小写字母、数字,连字符(-)命名,小写字母开头,多层目录使用/隔开。如user、modules-3、setting/profile";if(e.includes("/")){const t=e.split("/");for(const e of t){if(!e)return"子级目录名称不能为空";if(!/^[a-z][a-z0-9\-]+$/.test(e))return"支持小写字母、数字,连字符(-)命名,小写字母开头。如user、modules-3"}}return!0}const{red:A,green:B,blue:U,magenta:W}=t;function R(...e){console.log(B(...e))}function K(e,t=!1){let i=e;e instanceof Error?(i=e.message,c.isAxiosError(e)&&(i=`请求失败:${e.message}`),console.log(A(i)),console.log(W(e.stack))):console.log(A(e)),t||process.exit(1)}function F(e){return!!s.existsSync(e)&&s.lstatSync(e).isDirectory()}function V(e=process.cwd()){if(F(e)){return s.readdirSync(e).filter((t=>F(r.resolve(e,t))))}return[]}function M(){return r.resolve(a.homedir(),".z")}function H(){return r.resolve(M(),"develop-config.json")}function G(){return s.existsSync(M())&&s.existsSync(H())}function Q(e){return k(this,arguments,void 0,(function*(e,t={removeTailLinkBreak:!0,silent:!0}){let n=yield new Promise(((n,o)=>{try{n(i.exec(e,{silent:t.silent}))}catch(e){o(e)}}));return n=n.toString(),t.removeTailLinkBreak&&(n=n.replace(/\n$/,"")),n}))}function Z(){return u(Date.now()).format("YYMMDD")}function Y(){s.existsSync(r.resolve(".z"))||K("当前不在项目根目录。请切换到项目根目录")}function X(){s.existsSync(r.resolve(".git"))||K("当前不是git项目根目录,请先执行git init,或切换到根目录")}function ee(){return k(this,void 0,void 0,(function*(){""!==(yield Q("git status -s"))&&K("请先提交代码变动,再进行操作")}))}const te={profile:{ldapAccount:"",ldapPassword:"",gitToken:"",gitUserId:0,gitName:"",gitEnglishName:"",gitEmail:"",weWorkName:"",weWorkUserId:"",jobType:"fe",zenTaoToken:""},main:{version:$.version,latestCheckVersionTimestamp:0,versionCheckDuring:3,weWorkListCache:[]},constants:{ZenTaoDomain:"",FEServerDomain:"",jenkinsDomain:"",jenkinsUsername:"",jenkinsPassword:"",OSSEndpoint:"",OSSAccessKeyID:"",OSSAccessKeySecret:"",OSSBucketName:""}};function ie(e,t){void 0!==t?te.profile[e]=t:te.profile=Object.assign(Object.assign({},te.profile),e)}function ne(e,t){te.constants=Object.assign(Object.assign({},te.constants),e)}function oe(e,t){void 0!==t?te.main[e]=t:te.main=Object.assign(Object.assign({},te.main),e)}function se(e){return e?te.profile[e]:te.profile}function re(e){return e?te.main[e]:te.main}function ae(e){return e?te.constants[e]:te.constants}let ce=null,le=null;function ue(){if(ce)return ce;const e=r.resolve("package.json");try{ce=n.readJsonSync(e)}catch(t){K(`当前目录(${i.pwd()})不存在${e}文件,请在项目根目录执行该命令。`)}return ce}function de(){if(le)return le;const e=r.resolve(".z/project.json");try{le=n.readJsonSync(e)}catch(t){K(`当前目录(${i.pwd()})不存在${e}文件,请在项目根目录执行该命令,或者初始化项目(z init .)。`)}return le}function me(e){le=le?Object.assign(Object.assign({},le),e):e,n.writeJSONSync(r.resolve(".z/project.json"),le,{spaces:2})}const pe={id:0,name:"",group:"",sourceBranch:"",mergeRequestUrl:""};function fe(){return k(this,void 0,void 0,(function*(){if(!pe.name){const e=ue();pe.name=e.name}if(!pe.id)try{const[t]=yield(e=pe.name,je({url:`${xe()}/projects`,data:{search:e}}));pe.mergeRequestUrl=t.web_url+"/merge_requests",pe.id=t.id,pe.group=t.namespace.path}catch(e){K(e)}var e;return pe.sourceBranch||(pe.sourceBranch=yield Q("git branch --show-current")),pe}))}function he(){n.writeJSONSync(H(),{main:re(),profile:se(),constants:ae()},{spaces:2})}function ge(e,t){const i=[];t.forEach((t=>{e.includes(t.value)&&i.push(t)}));const n=re("weWorkListCache"),o=n.map((e=>e.value));i.forEach((e=>{const t=o.indexOf(e.value);t>-1?n[t].usageCount+=1:n.push(Object.assign(Object.assign({},e),{usageCount:1}))})),oe({weWorkListCache:n.sort(((e,t)=>t.usageCount-e.usageCount))}),he()}function ye(){return k(this,void 0,void 0,(function*(){const{data:e}=yield ke({url:"/user/list"}),t=e.filter((e=>[1,2,3].includes(e.title))).map((e=>({name:`${e.nick} - ${T[e.title]}`,value:e.weWorkUserId}))),i=re("weWorkListCache"),n=i.map((e=>e.value)),o=[];return t.forEach((e=>{const t=n.indexOf(e.value);o.push(Object.assign(Object.assign({},e),{usageCount:t>-1?i[t].usageCount:0}))})),o.sort(((e,t)=>t.usageCount-e.usageCount))}))}function ve(e){return k(this,void 0,void 0,(function*(){var i;const n=e.method||"get",o=e.headers||{},s=e.data||{},r=e.dataKey||["GET","get"].includes(n)?"params":"data",a=e.auth||void 0;try{const i={url:e.url,method:n,[r]:s,headers:o,auth:a};t.magenta(i.method.toUpperCase()),t.yellow(i.url),JSON.stringify(i.headers),JSON.stringify(i.auth||{}),t.gray(JSON.stringify(i[r],null,2));const l=yield c(i);return t.green("Response"),t.grey(JSON.stringify(l.data,null,2)),Promise.resolve(l.data)}catch(e){return e instanceof l&&(t.red("Error"),t.grey(JSON.stringify(null===(i=null==e?void 0:e.response)||void 0===i?void 0:i.data))),Promise.reject(e)}}))}function be(){return k(this,void 0,void 0,(function*(){const e=se("gitToken");if(e)return e;{const{access_token:e}=yield ve({url:`${C}/oauth/token`,method:"post",data:{grant_type:"password",username:se("ldapAccount"),password:se("ldapPassword")}}),t=`Bearer ${e}`;return ie("gitToken",t),he(),t}}))}function je(e){return k(this,void 0,void 0,(function*(){return ve(Object.assign(Object.assign({},e),{headers:{Authorization:yield be()}}))}))}function we(){return k(this,void 0,void 0,(function*(){const e=se("zenTaoToken");if(e)return e;{const{token:e}=yield ve({url:`${ae("ZenTaoDomain")}/api.php/v1/tokens`,method:"post",data:{account:se("ldapAccount"),password:se("ldapPassword")}});return ie("zenTaoToken",e),he(),e}}))}function $e(e){return k(this,void 0,void 0,(function*(){const t=yield ve(Object.assign(Object.assign({},e),{headers:{Token:yield we()}}));if("string"==typeof t){const e=JSON.parse(t.slice(0,t.indexOf("<script>")));return JSON.parse(e.data)}if("object"==typeof t)return"Unauthorized"===t.error||t.data.indexOf("<script>")<0?(ie("zenTaoToken",""),$e(Object.assign({},e))):t}))}function ke(e){return k(this,void 0,void 0,(function*(){const t=`${ae("FEServerDomain")}/api`,{data:i}=yield ve({url:`${t}/auth/z-develop/login`,method:"post"});return ve({url:t+e.url,headers:{Authorization:`Bearer ${i}`},data:e.data,method:e.method||"post"})}))}const xe=()=>`${C}/api/v4`,Se=e=>xe()+"/projects/100/repository/files/"+encodeURIComponent(e)+"/raw?ref=master";function ze(){return je({url:Se("src/data/z-develop-config.json")})}function Oe(e){return je({url:`${xe()}/projects/${e}/repository/branches`})}const Ee=e=>`${ae("ZenTaoDomain")}${e}`;function Ne(e,i){let n="";return e.forEach(((e,o)=>{if(e.disabled)n=`${n} - ${e.name} (Disabled)`;else{n+=o===i?t.cyan(v.pointer)+" ":" ",n+=(e.checked||!1?t.green(v.radioOn):v.radioOff)+" "+e.name}n+="\n"})),n.replace(/\n$/,"")}class qe extends m{constructor(e,t,i){super(e,t,i),this.pointer=0,this.opt.choices||this.throwParamError("choices"),this.opt.choices.forEach(((e,t)=>{const i=e;i.checked=!1,i.id=t}));if(this.opt.choices.find((e=>"separator"===e.type)))throw new Error("Separator is not allowed in choices.");Array.isArray(this.opt.default)&&this.opt.choices.forEach((e=>{"separator"!==e.type&&this.opt.default.includes(e.value)&&(e.checked=!0)})),this.pointer=0,this.selection=[],this.done=e=>{console.log(e)},this.opt.default=null,this.paginator=new p(this.screen,{isInfinite:!0}),this.filterList=this.allList=this.opt.choices.choices}_run(e){this.done=e;const t=f(this.rl),i=this.handleSubmitEvents(t.line.pipe(h(this.getCurrentValue.bind(this))));i.success.forEach(this.onEnd.bind(this)),i.error.forEach(this.onError.bind(this)),t.normalizedUpKey.pipe(g(i.success)).forEach(this.onUpKey.bind(this)),t.normalizedDownKey.pipe(g(i.success)).forEach(this.onDownKey.bind(this)),t.spaceKey.pipe(g(i.success)).forEach(this.onSpaceKey.bind(this));const n=["up","down","space"];return t.keypress.pipe(y((e=>!e.key.ctrl&&!n.includes(e.key.name||"")))).pipe(g(i.success)).forEach(this.onKeyPress.bind(this)),this.render(),this}render(e){let i=this.getQuestion(),n="";if(this.getCurrentValue(),"answered"===this.status)i+=t.cyan(this.selection.join(","));else{this.selection.length?i+=t.magenta(`[已选: ${this.selection.join(",")}]`):i+="("+t.blue.bold("空格键")+"选择,"+t.blue.bold("回车键")+"提交,"+t.blue.bold("输入中文")+"搜索)",i+=t.bgYellowBright(t.black(this.rl.line));const e=Ne(this.filterList,this.pointer);n=this.paginator.paginate(e,this.pointer,this.opt.pageSize)}e&&(n=t.red(">> ")+e),this.screen.render(i,n)}getCurrentValue(){const e=this.allList.filter((e=>e.checked&&!e.disabled));return this.selection=e.map((e=>e.short)),e.map((e=>e.value))}toggleChoice(e){const t=this.filterList[e];t&&(this.allList[t.id].checked=!t.checked)}filterChoices(){this.filterList=this.allList.filter((e=>{var t;return null===(t=e.name)||void 0===t?void 0:t.includes(this.rl.line.trim())}))}onSpaceKey(){this.toggleChoice(this.pointer),this.render(),this.rl.resume()}onDownKey(){const e=this.filterList.length;this.pointer=this.pointer<e-1?this.pointer+1:0,this.render()}onUpKey(){const e=this.filterList.length;this.pointer=this.pointer>0?this.pointer-1:e-1,this.render()}onKeyPress(){this.pointer=0,this.filterChoices(),this.render()}onEnd(e){this.status="answered",this.render(),this.screen.done(),this.done(e.value)}onError(e){this.render(e.isValid)}}function De(){return k(this,void 0,void 0,(function*(){const e=o(process.argv.slice(2));if(!["init","i"].includes(e._[0]))if(G()){const e=n.readJSONSync(H());ie(e.profile),oe(e.main),ne(e.constants),yield function(){return k(this,void 0,void 0,(function*(){const e=re("latestCheckVersionTimestamp"),i=re("versionCheckDuring");if(Date.now()-Number(e)>24*Number(i)*3600*1e3){ne(yield ze());const e=yield Q(`npm view ${$.name} version`);if(e!==$.version){console.log(`${t.blue($.name)}本地版本为${$.version},低于线上版本${e},开始升级`);try{yield Q(`npm i -g ${$.name}`),oe("latestCheckVersionTimestamp",Date.now()),he(),console.log(t.green("升级完成!")),process.exit(0)}catch(e){console.log("升级出错!请重试,或者手动升级"),K(e)}}}}))}()}else e.h||e.help||e.v||e.version||K("请先初始化z-develop(执行 z i)。更多见https://zxf-fe.yuque.com/org-wiki-zxf-fe-ex4bve/qi89vg/us8lgdb5cq4kf3aa#PJK7q")}))}function Te(){return k(this,void 0,void 0,(function*(){try{if(G()){const{isRemove:e}=yield d.prompt([{type:"confirm",name:"isRemove",message:"系统中已存在z的配置文件,确认重新配置?"}]);e?i.rm("-rf",H()):process.exit(0)}s.mkdirSync(M(),{recursive:!0});const{jobType:e,account:t,password:n}=yield d.prompt([{type:"list",name:"jobType",message:"请选择你要创建的类型",choices:[{name:"前端",value:"fe"},{name:"后端",value:"be"}]},{type:"input",name:"account",message:"请输入LDAP账号:"},{type:"input",name:"password",message:"请输入LDAP密码:"}]);ie("jobType",e),ie("ldapAccount",t),ie("ldapPassword",n);ne(yield ze());const o=yield ye(),{weWork:r}=yield d.prompt([{type:"search-checkbox",name:"weWork",message:"请选择你自己(用于企微通知):",choices:o,validate:e=>e.length>1?"只能选一个":!(e.length<1)||"请选一个"}]),{name:a,value:c}=o.find((e=>e.value===r[0]));ie({weWorkName:a,weWorkUserId:c})}catch(e){K(e)}const e=b("配置信息初始化中").start();try{const t=yield je({url:`${xe()}/user`});ie({gitUserId:t.id,gitName:t.name,gitEnglishName:t.username,gitEmail:t.email}),oe("latestCheckVersionTimestamp",Date.now()),he(),e.succeed("配置信息初始化完成")}catch(t){e.fail("配置信息初始化失败"),c.isAxiosError(t)&&K("请检查你的域名及令牌配置"),K(t)}}))}const Ce=".z",Ie=(e="")=>r.join(Ce,e);let Pe;function Le(){return k(this,void 0,void 0,(function*(){if(s.existsSync(Ie())){const{isRemove:e}=yield d.prompt([{type:"confirm",name:"isRemove",message:`当前项目中已存在配置文件夹${Ce},确认重新配置?`}]);e?i.rm("-rf",".z"):process.exit(0)}s.mkdirSync(Ie(),{recursive:!0}),yield function(){return k(this,void 0,void 0,(function*(){const e=yield Q("git remote get-url --push origin");e||K("获取项目远程地址失败,请配置后重试");const{language:t}=yield d.prompt([{type:"list",name:"language",message:"请选择项目语言",choices:[{name:"JavaScript",value:"JavaScript"},{name:"Java",value:"Java"}]}]);Pe=b("项目初始化中").start(),me({language:t,"lint-staged":z[t],repository:{url:e}})}))}(),yield function(){return k(this,void 0,void 0,(function*(){j.spawnSync("git",["config","core.hooksPath",Ce]),s.writeFileSync(Ie(".commit-msg-tpl"),"",{mode:493}),j.spawnSync("git",["config","commit.template",r.join(Ce,".commit-msg-tpl")]),s.writeFileSync(Ie("commit-msg"),"z lint commit-msg",{mode:493}),s.writeFileSync(Ie("pre-commit"),"z lint commit-files",{mode:493}),s.writeFileSync(Ie(".prettierrc.json"),x,{mode:493}),s.writeFileSync(Ie(".prettierignore"),S,{mode:493}),s.writeFileSync(Ie(".gitignore"),".commit-msg-tpl\n")}))}(),null==Pe||Pe.succeed("初始化完成。")}))}function Je(){return k(this,void 0,void 0,(function*(){try{const s={},a=()=>k(this,void 0,void 0,(function*(){const e=V(),{projects:t}=yield je({url:Se("src/data/template-projects.json")}),i=t.map((t=>{const i={name:`${t.name} [${t.desc}]`,value:t.name,short:t.name,disabled:!1};return e.includes(t.name)&&(i.disabled="目录下已存在同名文件夹"),i})),{project:n}=yield d.prompt([{type:"list",name:"project",message:"请选择一个项目模板",choices:i}]),o=t.find((e=>e.name===n));s.tplName=o.name,s.tplUrl=o.url})),c=()=>k(this,void 0,void 0,(function*(){const e=yield je({url:`${xe()}/groups`}),{list:t}=yield je({url:Se("src/data/project-groups.json")}),{group:i}=yield d.prompt([{type:"list",name:"group",message:"请选择一个分组",choices:t.map((e=>({name:`${e.name} [${e.desc}]`,value:e.name,short:e.name,disabled:!1})))}]),n=(o=i,e.find((e=>e.name===o)));var o;s.group=i,s.groupId=n.id})),l=()=>k(this,void 0,void 0,(function*(){const{name:e,desc:t}=yield d.prompt([{type:"input",name:"name",message:"请输入项目名称",validate:P},{type:"input",name:"desc",message:"请输入项目描述",validate:L}]);s.projectName=e,s.projectDesc=t}));yield a(),yield c(),yield l();const u=`${C}/${s.group}/${s.projectName}.git`,m=b("模版初始化中").start();yield Q(`git clone --depth=1 ${s.tplUrl}`),i.mv(s.tplName,s.projectName),i.cd(s.projectName),i.rm("-rf",".git"),yield Q("git init --initial-branch=master"),yield Q(`git remote add origin ${u}`),yield Q(`git config user.name ${se("gitName")}`),yield Q(`git config user.email ${se("gitEmail")}`),o=Object.assign(Object.assign({},ue()),{name:s.projectName,description:s.projectDesc}),ce=ce?Object.assign(Object.assign({},ce),o):o,n.writeJSONSync(r.resolve("package.json"),ce,{spaces:2}),me({language:"JavaScript","lint-staged":z.JavaScript,repository:{url:u}}),j.spawnSync("git",["config","core.hooksPath",Ce]),j.spawnSync("git",["config","commit.template",r.join(Ce,".commit-msg-tpl")]),yield n.writeFile(r.resolve("README.md"),function(e="项目中文名",t="项目描述"){return`\n# ${e}\n${t}\n\n## 快速开始\n### 安装依赖\n\`\`\`bash\n npm i\n\`\`\`\n\n### 本地开发\n\`\`\`bash\n npm run dev:{environment}:{platform}\n\`\`\`\n\n> 查看更多关于 [platform](https://zxf-fe.yuque.com/org-wiki-zxf-fe-ex4bve/qi89vg/nttvbeif4a62gtpz#faWqt) 和 [environment](https://zxf-fe.yuque.com/org-wiki-zxf-fe-ex4bve/qi89vg/nttvbeif4a62gtpz#faWqt)\n\n### 打包代码\n\`\`\`bash\n npm run build:{environment}:{platform}\n\`\`\`\n\n### 格式化、修复代码语法\n\`\`\`bash\n z lint prettier\n\`\`\`\n\n> [ESLint相关规范](https://zxf-fe.yuque.com/org-wiki-zxf-fe-ex4bve/qi89vg/ul914hdkqz8fr02g#AkvQ4)\n\n### 格式化文档\n\`\`\`bash\n z lint prettier\n\`\`\`\n\n> [Prettier相关规范](https://zxf-fe.yuque.com/org-wiki-zxf-fe-ex4bve/qi89vg/ul914hdkqz8fr02g#ojpwI)\n\n## 常见问题\n列出开发中常见的问题和解决方案\n\n## 了解更多\n在此处放入语雀文档链接。请在[前端团队-项目手册](https://zxf-fe.yuque.com/org-wiki-zxf-fe-ex4bve/qi89vg/bfrcicwzosoyaifg)中按照分类新建文档。\n`}(s.projectName,s.projectDesc)),m.succeed("模版初始化完成");const p=b("依赖安装中").start();yield Q("npm install"),p.succeed("依赖安装完成");const f=b("远程项目创建中").start(),h=yield(e={name:s.projectName,description:s.projectDesc,path:s.projectName,visibility:"private",namespace_id:s.groupId},je({url:`${xe()}/projects`,method:"post",data:e}));f.succeed("远程项目创建成功");const g=b("项目推送中").start();yield Q('git add . && git commit -m "chore: init"'),yield Q("git push -u origin master"),g.succeed(`项目已推送到远程,地址: ${t.blue(u)}`);const y=b("初始化分支中").start(),v=`feat_init_${Z()}`,w=s.group===I?[v]:[...q,v],$=yield Promise.allSettled(w.map((e=>function(e){return je({url:`${xe()}/projects/${e.id}/repository/branches`,method:"post",data:e})}({id:h.id,branch:e,ref:"master"})))),x=[];$.forEach((({status:e},t)=>{"fulfilled"===e&&x.push(w[t])})),yield Q("git fetch origin"),x.includes(v)?(yield Q(`git checkout -b ${v} origin/${v}`),y.succeed(`项目已切换到初始分支: ${t.blue(v)}`)):y.warn("开发分支检出失败!项目当前在主分支,请自行检出开发分支。");const S=`cd ${s.projectName} && z start`;console.log(`输入 ${t.green(S)} 开始开发吧~`)}catch(e){K(e)}var e,o}))}function _e(e){return 0!==e.length||"请选择项"}function Ae(){return k(this,void 0,void 0,(function*(){const{type:e}=yield d.prompt({type:"list",name:"type",message:"请选择你要创建的模板类型",choices:[{name:"feat - 业务需求开发",value:"feat"},{name:"fix - bug修复",value:"fix"},{name:"refactor - 技术内部需求",value:"refactor"},{name:"chore - 其他",value:"chore"}]});if(["feat","refactor"].includes(e)){const e=yield function(){return k(this,void 0,void 0,(function*(){const e=yield $e({url:Ee("/my-work-task.json?tid=mrrferp8"),method:"get"});return null==e?void 0:e.tasks.map((({id:e,name:t})=>({value:{name:t,value:e},name:t})))}))}(),{tasks:t}=yield d.prompt({type:"checkbox",name:"tasks",message:"请关联开发任务(可多选):",validate:_e,choices:e.map((e=>Object.assign(Object.assign({},e),{name:`[${e.value.value}]: ${e.name}`})))});Be("feat",t)}else if("fix"===e){const e=yield function(){return k(this,void 0,void 0,(function*(){const e=yield $e({url:Ee("/my-work-bug.json?tid=mrrferp8"),method:"get"});return null==e?void 0:e.bugs.map((({id:e,title:t})=>({name:t,value:{name:t,value:e}})))}))}(),{bugs:t}=yield d.prompt({type:"checkbox",name:"bugs",message:"请关联Bug(可多选):",validate:_e,choices:e.map((e=>Object.assign(Object.assign({},e),{name:`[${e.value.value}]: ${e.name}`})))});Be("fix",t)}else if("chore"===e){const{msg:e}=yield d.prompt({type:"input",name:"msg",message:"请输入commit msg:",validate:e=>0!==e.length||"请输入commit msg"});Be("chore",[e])}}))}function Be(e,i){let n="";if(["feat","refactor","fix"].includes(e)){n=`${e}(${i.map((e=>e.value)).join(",")}): ${i.map((e=>e.name)).join(";")}`}"chore"===e&&(n=`${e}: ${i[0]}`),s.writeFileSync(r.resolve(".z/.commit-msg-tpl"),n,"utf-8"),console.log(t.yellow(n)),R("commit msg模板写入成功,可以进行提交了")}function Ue(){return k(this,void 0,void 0,(function*(){s.mkdirSync(r.resolve("src/pages"),{recursive:!0});const{dirName:e}=yield d.prompt([{name:"dirName",type:"input",message:"请输入页面目录名称(已存在则跳过创建)",validate:_}]);s.mkdirSync(r.resolve("src/pages",e),{recursive:!0});const t=function(e=process.cwd()){if(F(e))return s.readdirSync(e).filter((t=>!F(r.resolve(e,t))));return[]}(r.resolve("src/pages",e)),{pageName:i}=yield d.prompt([{name:"pageName",type:"input",message:"请输入页面名称",validate:e=>function(e,t){return e?/^[a-z][a-z0-9\-]+$/.test(e)?!t.includes(e)||"页面已存在":"支持小写字母、数字,连字符(-)命名,小写字母开头。如user、modules-3":"页面名称不能为空"}(e,t)}]);console.log(i)}))}function We(e,t){return k(this,void 0,void 0,(function*(){const i=function(e){const{pathname:t}=new URL(e),i=t.match(/\/(.+)\.git/);if(i)return i[1];K("GitLab URL有误")}(e),{originBranch:n,environment:o,platform:s,notify:r,processId:a}=t;var c;yield(c={params:{command:"build",params:JSON.stringify({originBranch:n,environment:o,platform:s,profile:{weWorkName:se("weWorkName"),weWorkUserId:se("weWorkUserId")}}),options:JSON.stringify({processId:a,notify:r||[]})},jobName:i},ve({url:`${ae("jenkinsDomain")}/job/${c.jobName}/buildWithParameters`,method:"post",dataKey:"params",data:c.params,auth:{username:ae("jenkinsUsername"),password:ae("jenkinsPassword")}}))}))}function Re(e){return k(this,void 0,void 0,(function*(){try{const{originBranch:t,environment:i,platform:n,notify:o,processId:s}=e,r=de();!function(e,t){var i,n,o,s,r;const a=ue(),c=de();(null===(i=null==c?void 0:c.repository)||void 0===i?void 0:i.url)||K("项目package.json文件中缺少repository.url");const l=`build:${e}:${t}`;(null==a?void 0:a.scripts[l])||K(`项目package.json文件scripts不存在命令${l}。`),["alipay","weapp"].includes(t)&&(a.mini||K("请在package.json配置mini字段"),"alipay"===t&&((null===(o=null===(n=a.mini)||void 0===n?void 0:n.alipay)||void 0===o?void 0:o.appid)||K("请在package.json配置mini.alipay.appid字段")),"weapp"===t&&((null===(r=null===(s=a.mini)||void 0===s?void 0:s.weapp)||void 0===r?void 0:r.appid)||K("请在package.json配置mini.weapp.appid字段")))}(i,n),yield Q("git fetch origin"),yield function(e,t){return k(this,void 0,void 0,(function*(){const i=de(),n=yield Q(`git remote show ${i.repository.url}`),[,o]=n.match(/HEAD branch: (.+)\n/),s=yield Q(`git log -b origin/${o} -1 --format=%H`),r=`origin/${e}`;if((yield Q(`git branch --contains ${s} -r ${r}`))||K(`请先将最新的主分支(${o})代码合并到${r},再进行部署。`),"production"!==t)return;const a=yield Q(`git log -b origin/${e} -1 --format=%H`),c=(yield Q(`git log ${s}...${a} -b ${r}`)).split("\n");c.length||K(`分支${e}上没有要发布的commit`);const l=yield Q("git log -b origin/test -1 --format=%H");(function(e,t){for(let i of t)if(!e.includes(i))return!1;return!0})((yield Q(`git log ${s}...${l} -b origin/test`)).split("\n"),c)||K("请先在测试环境发布要部署的代码")}))}(t,i),yield We(r.repository.url,{originBranch:t,environment:i,platform:n,notify:o,processId:s})}catch(e){K(e)}}))}function Ke(){if(s.existsSync(r.resolve(".z/project.json"))){const e=n.readJsonSync(r.resolve(".z/project.json"));if(e["lint-staged"])return e["lint-staged"];throw new Error("未找到lint配置")}throw new Error("请先初始化项目(z i .)。")}e.command("init").alias("i").argument("[type]","非必填。可选值:.。不传为初始化工具配置;传 . 为初始化当前项目。").description("初始化工具配置、项目配置").action((function(e){return k(this,void 0,void 0,(function*(){e?"."===e?(X(),yield Le()):K("参数错误。执行 z init -h 查看帮助。"):yield Te()}))})),e.command("create").alias("c").argument("[type]","可选值为project|p, branch|b, commit-msg|cm。传 p 为创建项目;传 b 为创建分支;传 cm 为创建提交信息").description("创建项目/分支/提交信息").action((function(e){return k(this,void 0,void 0,(function*(){let t;if(e)["project","pr"].includes(e)?t="project":["branch","b"].includes(e)?t="branch":["page","pa"].includes(e)?t="page":["commit-msg","cm"].includes(e)?t="commit-msg":K("参数输入错误");else{t=(yield d.prompt({type:"list",name:"type",message:"请选择你要创建的类型",choices:[{name:"提交信息",value:"commit-msg"},{name:"分支",value:"branch"},{name:"页面",value:"page"},{name:"项目",value:"project"}]})).type}"project"===t?yield Je():"branch"===t?(Y(),X(),yield ee(),yield function(){return k(this,void 0,void 0,(function*(){const{type:e,purpose:t}=yield d.prompt([{name:"type",type:"list",message:"请选择创建分支的类型",choices:[{name:"开发新功能(feat)",value:"feat"},{name:"修复BUG(fix)",value:"fix"},{name:"重构/优化代码(refactor)",value:"refactor"}]},{name:"purpose",type:"input",message:"请输入创建分支的目的(大小写字母、数字,小驼峰式命名。如userInfo)",validate:J}]),i=`${e}_${t}_${Z()}`,n=de(),o=yield Q(`git remote show ${n.repository.url}`),[,s]=o.match(/HEAD branch: (.+)\n/);yield Q("git fetch origin"),yield Q(`git checkout -b ${i} origin/${s}`)}))}()):"commit-msg"===t?(Y(),X(),yield Ae()):"page"===t&&(Y(),X(),yield Ue())}))})),e.command("merge").alias("m").description("合并当前分支到指定远程分支,并部署。").action((function(){return k(this,void 0,void 0,(function*(){var e;Y(),X(),yield ee();const i=yield fe(),n=yield Oe(i.id),o=[...q],s=i.group===I,r=n.filter((e=>s?![i.sourceBranch].includes(e.name):![...N,i.sourceBranch].includes(e.name))).map((e=>{let i=e.name;return!s&&o.includes(i)&&(i=t.bold.blue(i)),{name:i,value:e.name}})),{target:a}=yield d.prompt([{type:"list",name:"target",message:"请选择要合并到的目标分支:",choices:r}]),l=o.includes(a);let u="h5",m=[];if(l){const e=yield ye(),t=yield d.prompt([{type:"list",name:"platform",message:"请选择平台",choices:[{name:"网页 - h5",value:"h5"},{name:"支付宝小程序 - alipay",value:"alipay"},{name:"微信小程序 - weapp",value:"weapp"}]},{type:"search-checkbox",name:"notify",message:"请选择部署成功要通知的人员:",choices:e,validate:e=>!(e.length<1)||"至少选一个"}]);ge(m,e),u=t.platform,m=t.notify}yield Q("git fetch origin"),yield Q(`git push -u origin ${i.sourceBranch}`);let p=0;try{const{iid:e}=yield(f={title:"MR by z-develop",id:i.id,source_branch:i.sourceBranch,target_branch:a,remove_source_branch:s&&N.includes(a)},je({url:`${xe()}/projects/${f.id}/merge_requests`,method:"post",data:f}));p=e}catch(t){if(c.isAxiosError(t)){409===(null===(e=null==t?void 0:t.response)||void 0===e?void 0:e.status)&&K(`存在重复的合并请求,前往查看${i.mergeRequestUrl}`)}K(t)}var f;const h=()=>k(this,void 0,void 0,(function*(){var e;try{yield new Promise((e=>{setTimeout(e,5e3)})),yield function(e){return je({url:`${xe()}/projects/${e.id}/merge_requests/${e.iid}/merge`,method:"put"})}({id:i.id,iid:p})}catch(t){if(c.isAxiosError(t)){406===(null===(e=null==t?void 0:t.response)||void 0===e?void 0:e.status)?yield h():(yield function(e){return je({url:`${xe()}/projects/${e.id}/merge_requests/${e.iid}`,method:"put",data:e})}({id:i.id,iid:p,state_event:"close"}),K("合并过程中出现冲突,MR已关闭。建议在本地完成合并。"))}else K(t)}}));yield h(),l&&(yield Re({originBranch:a,environment:a,platform:u,notify:m,processId:""}))}))})),e.command("deploy").alias("d").description("发布指定远程分支").action((function(){return k(this,void 0,void 0,(function*(){const e=yield ye(),{environment:t,platform:i,notify:n}=yield d.prompt([{type:"list",name:"environment",message:"请选择部署环境",choices:O},{type:"list",name:"platform",message:"请选择平台",choices:E},{type:"search-checkbox",name:"notify",message:"请选择部署成功要通知的人员:",choices:e,validate:e=>!(e.length<1)||"至少选一个"}]);ge(n,e);let o=t,s="";if("production"===t){const e=yield fe(),t=(yield Oe(e.id)).filter((e=>![...N,...q].includes(e.name))).map((e=>({name:e.name,value:e.name}))),n=yield d.prompt([{type:"list",name:"branchName",message:"请输入要部署的分支:",choices:t},{type:"input",name:"processId",message:"请输入本次部署的企微审批编号"}]);o=n.branchName,s=n.processId,function(e){const t=e.split("_");if(4!==t.length)return!1;const[i,n,o]=t;return!!D.includes(i)&&!0===J(n)&&8===o.length&&!isNaN(Number(o))}(o)||K("分支命名不符合规范,参见https://zhongshitech.yuque.com/nx4ugr/guide/mg8t44#bQhu4");const{data:{state:a,content:c}}=yield(r={businessId:s},ke({url:"/approval/findByBusinessId",data:r}));1===a&&K("当前审批流程状态为审批中,审批通过才能进行发布。"),3===a&&K("当前审批流程状态为已驳回,请重新提交审批。"),4===a&&K("当前审批流程状态为已发布,如需再次发布,请重新提交审批。");const{formComponentValues:l}=JSON.parse(c),u={};l.forEach((e=>{u[e.name]=e.value})),u["申请人"]!==se("weWorkName")&&K("发布审批申请人与当前发布人不一致!"),u["项目名称"]!==ue().name&&K("发布审批项目名称与当前发布项目名称不一致!"),u["发布分支"]!==o&&K("发布审批发布分支与当前发布分支不一致!"),u["发布平台"]!==i&&K("发布审批发布平台与当前发布平台不一致!")}var r;yield Re({originBranch:o,environment:t,platform:i,notify:n,processId:s})}))})),e.command("start").alias("s").description("启动本地开发环境").action((function(){return k(this,void 0,void 0,(function*(){const e=ue(),{environment:t}=yield d.prompt([{type:"list",name:"environment",message:"请选择环境",choices:O}]),n=`dev:${t}`;if(e.scripts[n])try{i.exec(`npm run ${n}`,{silent:!1})}catch(e){K(e)}else K(`项目中(package.josn > scripts)不存在命令${n},请先添加!`)}))})),e.command("lint").alias("l").argument("[type]","非必填。可选值为commit-msg|cm, commit-files|cf, prettier|p, eslint|e。传 cm 为执行 lint commit-msg;传 cf 为执行 lint commit-files;传 p 为全部文件执行prettier;传 e 为全部文件执行eslint。cm 和 cf属于内部命令,会在git hooks中自动执行。").description("执行 lint 脚本。包含 lint staged 、 lint commit message、 prettier、 eslint。").action((function(e){return k(this,void 0,void 0,(function*(){let t;if(Y(),X(),e)["commit-msg","cm"].includes(e)?t="commit-msg":["commit-files","cf"].includes(e)?t="commit-files":["prettier","p"].includes(e)?t="prettier":["eslint","e"].includes(e)?t="eslint":K("参数输入错误");else{t=(yield d.prompt({type:"list",name:"type",message:"请选择你要执行的操作",choices:[{name:"全局执行 prettier",value:"prettier"},{name:"全局执行 eslint",value:"eslint"}]})).type}if("commit-msg"===t)yield function(){return k(this,void 0,void 0,(function*(){const e=function(e){const t=s.readFileSync(r.resolve(".git/COMMIT_EDITMSG"),"utf-8").split(": ");if(1===t.length)return"body前缺少「:」";{const e=t[0];return/^(feat|fix|refactor)/.test(e)?!!/\(\d+(?:,\d+)*\)/.test(e)||"ID缺少或者格式不正确。":/^chore/.test(e)?"chore"===e||"chore类型无需填写ID。":"不存在的提交类型。"}}();!0===e?R("commit msg validate success."):K(`commit msg格式错误。${e}`)}))}();else if("commit-files"===t)yield function(){return k(this,void 0,void 0,(function*(){(yield w({concurrent:!1,debug:void 0,config:Ke()}))?R("代码风格检测通过!"):K("代码风格检测未通过!")}))}();else if("prettier"===t){s.existsSync(r.resolve("node_modules/.bin/prettier"))||K("该项目未安装prettier,请安装后重试");try{yield Q("prettier --write . --config .z/.prettierrc.json --ignore-path .z/.prettierignore --ignore-unknown --no-error-on-unmatched-pattern",{silent:!1}),R("prettier执行成功")}catch(e){K("prettier校验出错")}}else if("eslint"===t){console.log(r.resolve("node_modules/.bin/eslint")),s.existsSync(r.resolve("node_modules/.bin/eslint"))||K("该项目未安装eslint,请安装后重试");try{yield Q("eslint '**/*.{vue,js,jsx,cjs,mjs,ts,tsx,cts,mts}' --fix",{silent:!1}),R("eslint执行成功")}catch(e){K("eslint校验出错")}}}))})),function(){k(this,void 0,void 0,(function*(){process.on("unhandledRejection",(e=>{})),process.on("uncaughtException",(e=>{})),i.config.fatal=!0,i.config.silent=!0,i.config.verbose=!1,yield De(),d.registerPrompt("search-checkbox",qe)}))}(),e.name("z-develop").alias("z").description(`z-develop, 开发流程管理工具。\n了解更多: ${t.blue("https://zxf-fe.yuque.com/org-wiki-zxf-fe-ex4bve/qi89vg/us8lgdb5cq4kf3aa")}`).usage("<command> [options]").version($.version,"-v, --version","当前版本号").helpOption("-h, --help","帮助").showHelpAfterError("可以使用z -h查看帮助。"),e.parse();
1
+ import{program as e}from"commander";import t from"chalk";import i from"shelljs";import n from"fs-extra";import o from"minimist";import s from"node:fs";import r from"node:path";import a from"node:os";import c,{AxiosError as l}from"axios";import u from"dayjs";import d from"inquirer";import m from"inquirer/lib/prompts/base.js";import p from"inquirer/lib/utils/paginator.js";import f from"inquirer/lib/utils/events.js";import"inquirer/lib/objects/choices.js";import{map as h,takeUntil as g,filter as y}from"rxjs";import v from"figures";import b from"ora";import j from"child_process";import w from"lint-staged";var $={name:"cli-z-develop",version:"0.0.15",description:"前端本地开发命令行工具",main:"dist/index.js",bin:{z:"./bin/z.js","z-develop":"./bin/z.js"},scripts:{prepare:"husky",dev:"rollup -c -w --environment DEBUG:true",build:"rollup -c",eslint:"eslint '**/*.{ts,js}' --fix",prettier:"prettier -wu .",upload:"npm version patch && npm run build && npm publish --access public --registry https://registry.npmjs.org/"},type:"module",repository:{type:"git",url:"http://git.cxlqd.com/fe-base/cli-z-develop.git"},author:"z",devDependencies:{"@commitlint/cli":"^19.3.0","@commitlint/config-conventional":"^19.2.2","@rollup/plugin-json":"^6.1.0","@rollup/plugin-node-resolve":"^15.2.3","@rollup/plugin-replace":"^5.0.5","@rollup/plugin-terser":"^0.4.4","@types/fs-extra":"^11.0.4","@types/inquirer":"^9.0.7","@types/minimist":"^1.2.5","@types/node":"^20.12.12","@types/shelljs":"^0.8.15","@types/tough-cookie":"^4.0.5","@typescript-eslint/eslint-plugin":"^7.9.0","@typescript-eslint/parser":"^7.9.0",eslint:"^8.57.0","eslint-config-alloy":"^5.1.2","eslint-config-prettier":"^9.1.0",husky:"^9.0.11",prettier:"^3.2.5",rollup:"^4.17.2","rollup-plugin-typescript2":"^0.36.0",tslib:"^2.6.2",typescript:"^5.4.5"},dependencies:{axios:"^1.7.1",chalk:"^5.3.0",commander:"^12.1.0",dayjs:"^1.11.11",figures:"^6.1.0","fs-extra":"^11.2.0",inquirer:"^9.2.22",minimist:"^1.2.8",ora:"^8.0.1",rxjs:"^7.8.1",shelljs:"^0.8.5","lint-staged":"^15.2.2"}};function k(e,t,i,n){return new(i||(i=Promise))((function(o,s){function r(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(r,a)}c((n=n.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const S='{\n "printWidth": 120,\n "tabWidth": 2,\n "useTabs": false,\n "semi": true,\n "singleQuote": false,\n "quoteProps": "as-needed",\n "jsxSingleQuote": false,\n "trailingComma": "all",\n "bracketSpacing": true,\n "bracketSameLine": false,\n "arrowParens": "always",\n "requirePragma": false,\n "insertPragma": false,\n "proseWrap": "preserve",\n "htmlWhitespaceSensitivity": "css",\n "vueIndentScriptAndStyle": false,\n "endOfLine": "lf",\n "embeddedLanguageFormatting": "auto",\n "singleAttributePerLine": false\n}\n',x="# 系统 信息文件\n.DS_Store/\nThumbs.db\n\n# 编辑器配置文件\n.idea/\n.vscode/\n\n# 输出目录\ndist/\n\n# Log files\n*.log\n\n# 本地配置文件\n*.local\n\n# 缓存文件\n*.cache\n\n# 垃圾文件\n.Trashes\n",z={Java:{"**/*.{java}":"./run.sh pmd -d ../../../src/main/java/ -f text -R rulesets/java/quickstart.xml"},JavaScript:{"**/*.{vue,js,jsx,cjs,mjs,ts,tsx,cts,mts}":"eslint --fix","*":"prettier -wu"}},O=[{name:"开发环境 - dev",value:"dev"},{name:"测试环境 - test",value:"test"},{name:"预发环境 - release",value:"release"},{name:"正式环境 - production",value:"production"}],E=[{name:"网页 - h5",value:"h5"},{name:"支付宝小程序 - alipay",value:"alipay"},{name:"微信小程序 - weapp",value:"weapp"},{name:"node module - npm",value:"npm"}],N=["main","master"],q=["dev","test","release"],D=["fix","feat","refactor"],T={1:"研发",2:"测试",3:"产品",4:"设计",5:"运营",6:"销售",7:"行政",8:"财务",9:"其他"},C="http://git.cxlqd.com",I="fe-tpl";function P(e){if(!e)return"不能为空";if(!/^[a-z0-9-]+$/.test(e))return"格式为小写字母、中横线(可选)、数字(不推荐)。如apple, apple-tree";return!V().includes(e)||"当前目录下已存在同名文件夹,请先处理。"}function L(e){return!!e||"不能为空"}function J(e){return e?!!/^[a-zA-Z0-9]+$/.test(e)||"格式为大小写字母、数字,小驼峰命名。如userInfo、systemRouter3":"不能为空"}function _(e){if(!e)return"目录名称不能为空";if(!/^[a-z][a-z0-9\-\/]+$/.test(e))return"支持小写字母、数字,连字符(-)命名,小写字母开头,多层目录使用/隔开。如user、modules-3、setting/profile";if(e.includes("/")){const t=e.split("/");for(const e of t){if(!e)return"子级目录名称不能为空";if(!/^[a-z][a-z0-9\-]+$/.test(e))return"支持小写字母、数字,连字符(-)命名,小写字母开头。如user、modules-3"}}return!0}const{red:A,green:B,blue:U,magenta:W}=t;function R(...e){console.log(B(...e))}function K(e,t=!1){let i=e;e instanceof Error?(i=e.message,c.isAxiosError(e)&&(i=`请求失败:${e.message}`),console.log(A(i)),console.log(W(e.stack))):console.log(A(e)),t||process.exit(1)}function F(e){return!!s.existsSync(e)&&s.lstatSync(e).isDirectory()}function V(e=process.cwd()){if(F(e)){return s.readdirSync(e).filter((t=>F(r.resolve(e,t))))}return[]}function M(e=process.cwd()){if(F(e)){return s.readdirSync(e).filter((t=>!F(r.resolve(e,t))))}return[]}function H(){return r.resolve(a.homedir(),".z")}function G(){return r.resolve(H(),"develop-config.json")}function Q(){return s.existsSync(H())&&s.existsSync(G())}function Z(e){return k(this,arguments,void 0,(function*(e,t={removeTailLinkBreak:!0,silent:!0}){let n=yield new Promise(((n,o)=>{try{n(i.exec(e,{silent:t.silent}))}catch(e){o(e)}}));return n=n.toString(),t.removeTailLinkBreak&&(n=n.replace(/\n$/,"")),n}))}function Y(){return u(Date.now()).format("YYMMDD")}function X(){s.existsSync(r.resolve(".z"))||K("当前不在项目根目录。请切换到项目根目录")}function ee(){s.existsSync(r.resolve(".git"))||K("当前不是git项目根目录,请先执行git init,或切换到根目录")}function te(){return k(this,void 0,void 0,(function*(){""!==(yield Z("git status -s"))&&K("请先提交代码变动,再进行操作")}))}const ie={profile:{ldapAccount:"",ldapPassword:"",gitToken:"",gitUserId:0,gitName:"",gitEnglishName:"",gitEmail:"",weWorkName:"",weWorkUserId:"",jobType:"fe",zenTaoToken:""},main:{version:$.version,latestCheckVersionTimestamp:0,versionCheckDuring:3,weWorkListCache:[]},constants:{ZenTaoDomain:"",FEServerDomain:"",jenkinsDomain:"",jenkinsUsername:"",jenkinsPassword:"",OSSEndpoint:"",OSSAccessKeyID:"",OSSAccessKeySecret:"",OSSBucketName:""}};function ne(e,t){void 0!==t?ie.profile[e]=t:ie.profile=Object.assign(Object.assign({},ie.profile),e)}function oe(e,t){ie.constants=Object.assign(Object.assign({},ie.constants),e)}function se(e,t){void 0!==t?ie.main[e]=t:ie.main=Object.assign(Object.assign({},ie.main),e)}function re(e){return e?ie.profile[e]:ie.profile}function ae(e){return e?ie.main[e]:ie.main}function ce(e){return e?ie.constants[e]:ie.constants}let le=null,ue=null;function de(){if(le)return le;const e=r.resolve("package.json");try{le=n.readJsonSync(e)}catch(t){K(`当前目录(${i.pwd()})不存在${e}文件,请在项目根目录执行该命令。`)}return le}function me(){if(ue)return ue;const e=r.resolve(".z","project.json");try{ue=n.readJsonSync(e)}catch(t){K(`当前目录(${i.pwd()})不存在${e}文件,请在项目根目录执行该命令,或者初始化项目(z init .)。`)}return ue}function pe(e){ue=ue?Object.assign(Object.assign({},ue),e):e,n.writeJSONSync(r.resolve(".z","project.json"),ue,{spaces:2})}const fe={id:0,name:"",group:"",sourceBranch:"",mergeRequestUrl:""};function he(){return k(this,void 0,void 0,(function*(){if(!fe.name){const e=de();fe.name=e.name}if(!fe.id)try{const[t]=yield(e=fe.name,we({url:`${xe()}/projects`,data:{search:e}}));fe.mergeRequestUrl=t.web_url+"/merge_requests",fe.id=t.id,fe.group=t.namespace.path}catch(e){K(e)}var e;return fe.sourceBranch||(fe.sourceBranch=yield Z("git branch --show-current")),fe}))}function ge(){n.writeJSONSync(G(),{main:ae(),profile:re(),constants:ce()},{spaces:2})}function ye(e,t){const i=[];t.forEach((t=>{e.includes(t.value)&&i.push(t)}));const n=ae("weWorkListCache"),o=n.map((e=>e.value));i.forEach((e=>{const t=o.indexOf(e.value);t>-1?n[t].usageCount+=1:n.push(Object.assign(Object.assign({},e),{usageCount:1}))})),se({weWorkListCache:n.sort(((e,t)=>t.usageCount-e.usageCount))}),ge()}function ve(){return k(this,void 0,void 0,(function*(){const{data:e}=yield Se({url:"/user/list"}),t=e.filter((e=>[1,2,3].includes(e.title))).map((e=>({name:`${e.nick} - ${T[e.title]}`,value:e.weWorkUserId}))),i=ae("weWorkListCache"),n=i.map((e=>e.value)),o=[];return t.forEach((e=>{const t=n.indexOf(e.value);o.push(Object.assign(Object.assign({},e),{usageCount:t>-1?i[t].usageCount:0}))})),o.sort(((e,t)=>t.usageCount-e.usageCount))}))}function be(e){return k(this,void 0,void 0,(function*(){var i;const n=e.method||"get",o=e.headers||{},s=e.data||{},r=e.dataKey||["GET","get"].includes(n)?"params":"data",a=e.auth||void 0;try{const i={url:e.url,method:n,[r]:s,headers:o,auth:a};t.magenta(i.method.toUpperCase()),t.yellow(i.url),JSON.stringify(i.headers),JSON.stringify(i.auth||{}),t.gray(JSON.stringify(i[r],null,2));const l=yield c(i);return t.green("Response"),t.grey(JSON.stringify(l.data,null,2)),Promise.resolve(l.data)}catch(e){return e instanceof l&&(t.red("Error"),t.grey(JSON.stringify(null===(i=null==e?void 0:e.response)||void 0===i?void 0:i.data))),Promise.reject(e)}}))}function je(){return k(this,void 0,void 0,(function*(){const e=re("gitToken");if(e)return e;{const{access_token:e}=yield be({url:`${C}/oauth/token`,method:"post",data:{grant_type:"password",username:re("ldapAccount"),password:re("ldapPassword")}}),t=`Bearer ${e}`;return ne("gitToken",t),ge(),t}}))}function we(e){return k(this,void 0,void 0,(function*(){return be(Object.assign(Object.assign({},e),{headers:{Authorization:yield je()}}))}))}function $e(){return k(this,void 0,void 0,(function*(){const e=re("zenTaoToken");if(e)return e;{const{token:e}=yield be({url:`${ce("ZenTaoDomain")}/api.php/v1/tokens`,method:"post",data:{account:re("ldapAccount"),password:re("ldapPassword")}});return ne("zenTaoToken",e),ge(),e}}))}function ke(e){return k(this,void 0,void 0,(function*(){const t=yield be(Object.assign(Object.assign({},e),{headers:{Token:yield $e()}}));if("string"==typeof t){const e=JSON.parse(t.slice(0,t.indexOf("<script>")));return JSON.parse(e.data)}if("object"==typeof t)return"Unauthorized"===t.error||t.data.indexOf("<script>")<0?(ne("zenTaoToken",""),ke(Object.assign({},e))):t}))}function Se(e){return k(this,void 0,void 0,(function*(){const t=`${ce("FEServerDomain")}/api`,{data:i}=yield be({url:`${t}/auth/z-develop/login`,method:"post"});return be({url:t+e.url,headers:{Authorization:`Bearer ${i}`},data:e.data,method:e.method||"post"})}))}const xe=()=>`${C}/api/v4`,ze=e=>xe()+"/projects/100/repository/files/"+encodeURIComponent(e)+"/raw?ref=master";function Oe(){return we({url:ze("src/data/z-develop-config.json")})}function Ee(e){return we({url:`${xe()}/projects/${e}/repository/branches`})}const Ne=e=>`${ce("ZenTaoDomain")}${e}`;function qe(e,i){let n="";return e.forEach(((e,o)=>{if(e.disabled)n=`${n} - ${e.name} (Disabled)`;else{n+=o===i?t.cyan(v.pointer)+" ":" ",n+=(e.checked||!1?t.green(v.radioOn):v.radioOff)+" "+e.name}n+="\n"})),n.replace(/\n$/,"")}class De extends m{constructor(e,t,i){super(e,t,i),this.pointer=0,this.opt.choices||this.throwParamError("choices"),this.opt.choices.forEach(((e,t)=>{const i=e;i.checked=!1,i.id=t}));if(this.opt.choices.find((e=>"separator"===e.type)))throw new Error("Separator is not allowed in choices.");Array.isArray(this.opt.default)&&this.opt.choices.forEach((e=>{"separator"!==e.type&&this.opt.default.includes(e.value)&&(e.checked=!0)})),this.pointer=0,this.selection=[],this.done=e=>{console.log(e)},this.opt.default=null,this.paginator=new p(this.screen,{isInfinite:!0}),this.filterList=this.allList=this.opt.choices.choices}_run(e){this.done=e;const t=f(this.rl),i=this.handleSubmitEvents(t.line.pipe(h(this.getCurrentValue.bind(this))));i.success.forEach(this.onEnd.bind(this)),i.error.forEach(this.onError.bind(this)),t.normalizedUpKey.pipe(g(i.success)).forEach(this.onUpKey.bind(this)),t.normalizedDownKey.pipe(g(i.success)).forEach(this.onDownKey.bind(this)),t.spaceKey.pipe(g(i.success)).forEach(this.onSpaceKey.bind(this));const n=["up","down","space"];return t.keypress.pipe(y((e=>!e.key.ctrl&&!n.includes(e.key.name||"")))).pipe(g(i.success)).forEach(this.onKeyPress.bind(this)),this.render(),this}render(e){let i=this.getQuestion(),n="";if(this.getCurrentValue(),"answered"===this.status)i+=t.cyan(this.selection.join(","));else{this.selection.length?i+=t.magenta(`[已选: ${this.selection.join(",")}]`):i+="("+t.blue.bold("空格键")+"选择,"+t.blue.bold("回车键")+"提交,"+t.blue.bold("输入中文")+"搜索)",i+=t.bgYellowBright(t.black(this.rl.line));const e=qe(this.filterList,this.pointer);n=this.paginator.paginate(e,this.pointer,this.opt.pageSize)}e&&(n=t.red(">> ")+e),this.screen.render(i,n)}getCurrentValue(){const e=this.allList.filter((e=>e.checked&&!e.disabled));return this.selection=e.map((e=>e.short)),e.map((e=>e.value))}toggleChoice(e){const t=this.filterList[e];t&&(this.allList[t.id].checked=!t.checked)}filterChoices(){this.filterList=this.allList.filter((e=>{var t;return null===(t=e.name)||void 0===t?void 0:t.includes(this.rl.line.trim())}))}onSpaceKey(){this.toggleChoice(this.pointer),this.render(),this.rl.resume()}onDownKey(){const e=this.filterList.length;this.pointer=this.pointer<e-1?this.pointer+1:0,this.render()}onUpKey(){const e=this.filterList.length;this.pointer=this.pointer>0?this.pointer-1:e-1,this.render()}onKeyPress(){this.pointer=0,this.filterChoices(),this.render()}onEnd(e){this.status="answered",this.render(),this.screen.done(),this.done(e.value)}onError(e){this.render(e.isValid)}}function Te(){return k(this,void 0,void 0,(function*(){const e=o(process.argv.slice(2));if(!["init","i"].includes(e._[0]))if(Q()){const e=n.readJSONSync(G());ne(e.profile),se(e.main),oe(e.constants),yield function(){return k(this,void 0,void 0,(function*(){const e=ae("latestCheckVersionTimestamp"),i=ae("versionCheckDuring");if(Date.now()-Number(e)>24*Number(i)*3600*1e3){oe(yield Oe());const e=yield Z(`npm view ${$.name} version`);if(e!==$.version){console.log(`${t.blue($.name)}本地版本为${$.version},低于线上版本${e},开始升级`);try{yield Z(`npm i -g ${$.name}`),se("latestCheckVersionTimestamp",Date.now()),ge(),console.log(t.green("升级完成!")),process.exit(0)}catch(e){console.log("升级出错!请重试,或者手动升级"),K(e)}}}}))}()}else e.h||e.help||e.v||e.version||K("请先初始化z-develop(执行 z i)。更多见https://zxf-fe.yuque.com/org-wiki-zxf-fe-ex4bve/qi89vg/us8lgdb5cq4kf3aa#PJK7q")}))}function Ce(){return k(this,void 0,void 0,(function*(){try{if(Q()){const{isRemove:e}=yield d.prompt([{type:"confirm",name:"isRemove",message:"系统中已存在z的配置文件,确认重新配置?"}]);e?i.rm("-rf",G()):process.exit(0)}s.mkdirSync(H(),{recursive:!0});const{jobType:e,account:t,password:n}=yield d.prompt([{type:"list",name:"jobType",message:"请选择岗位类型",choices:[{name:"前端",value:"fe"},{name:"后端",value:"be"}]},{type:"input",name:"account",message:"请输入LDAP账号:"},{type:"input",name:"password",message:"请输入LDAP密码:"}]);ne("jobType",e),ne("ldapAccount",t),ne("ldapPassword",n);oe(yield Oe());const o=yield ve(),{weWork:r}=yield d.prompt([{type:"search-checkbox",name:"weWork",message:"请选择你自己(用于企微通知):",choices:o,validate:e=>e.length>1?"只能选一个":!(e.length<1)||"请选一个"}]),{name:a,value:c}=o.find((e=>e.value===r[0]));ne({weWorkName:a,weWorkUserId:c})}catch(e){K(e)}const e=b("配置信息初始化中").start();try{const t=yield we({url:`${xe()}/user`});ne({gitUserId:t.id,gitName:t.name,gitEnglishName:t.username,gitEmail:t.email}),se("latestCheckVersionTimestamp",Date.now()),ge(),e.succeed("配置信息初始化完成")}catch(t){e.fail("配置信息初始化失败"),c.isAxiosError(t)&&K("请检查你的域名及令牌配置"),K(t)}}))}const Ie=".z",Pe=(e="")=>r.join(Ie,e);let Le;function Je(){return k(this,void 0,void 0,(function*(){if(s.existsSync(Pe())){const{isRemove:e}=yield d.prompt([{type:"confirm",name:"isRemove",message:`当前项目中已存在配置文件夹${Ie},确认重新配置?`}]);e?i.rm("-rf",".z"):process.exit(0)}s.mkdirSync(Pe(),{recursive:!0}),yield function(){return k(this,void 0,void 0,(function*(){const e=yield Z("git remote get-url --push origin");e||K("获取项目远程地址失败,请配置后重试");const{language:t}=yield d.prompt([{type:"list",name:"language",message:"请选择项目语言",choices:[{name:"JavaScript",value:"JavaScript"},{name:"Java",value:"Java"}]}]);Le=b("项目初始化中").start(),pe({language:t,"lint-staged":z[t],repository:{url:e}})}))}(),yield function(){return k(this,void 0,void 0,(function*(){j.spawnSync("git",["config","core.hooksPath",Ie]),s.writeFileSync(Pe(".commit-msg-tpl"),"",{mode:493}),j.spawnSync("git",["config","commit.template",r.join(Ie,".commit-msg-tpl")]),s.writeFileSync(Pe("commit-msg"),"z lint commit-msg",{mode:493}),s.writeFileSync(Pe("pre-commit"),"z lint commit-files",{mode:493}),s.writeFileSync(Pe(".prettierrc.json"),S,{mode:493}),s.writeFileSync(Pe(".prettierignore"),x,{mode:493}),s.writeFileSync(Pe(".gitignore"),".commit-msg-tpl\n",{mode:493})}))}(),null==Le||Le.succeed("初始化完成。")}))}function _e(){return k(this,void 0,void 0,(function*(){try{const a={},c=()=>k(this,void 0,void 0,(function*(){const e=V(),{projects:t}=yield we({url:ze("src/data/template-projects.json")}),i=t.map((t=>{const i={name:`${t.name} [${t.desc}]`,value:t.name,short:t.name,disabled:!1};return e.includes(t.name)&&(i.disabled="目录下已存在同名文件夹"),i})),{project:n}=yield d.prompt([{type:"list",name:"project",message:"请选择一个项目模板",choices:i}]),o=t.find((e=>e.name===n));a.tplName=o.name,a.tplUrl=o.url})),l=()=>k(this,void 0,void 0,(function*(){const e=yield we({url:`${xe()}/groups`}),{list:t}=yield we({url:ze("src/data/project-groups.json")}),{group:i}=yield d.prompt([{type:"list",name:"group",message:"请选择一个分组",choices:t.map((e=>({name:`${e.name} [${e.desc}]`,value:e.name,short:e.name,disabled:!1})))}]),n=(o=i,e.find((e=>e.name===o)));var o;a.group=i,a.groupId=n.id})),u=()=>k(this,void 0,void 0,(function*(){const{name:e,desc:t}=yield d.prompt([{type:"input",name:"name",message:"请输入项目名称",validate:P},{type:"input",name:"desc",message:"请输入项目描述",validate:L}]);a.projectName=e,a.projectDesc=t}));yield c(),yield l(),yield u();const m=`${C}/${a.group}/${a.projectName}.git`,p=b("模版初始化中").start();yield Z(`git clone --depth=1 ${a.tplUrl}`),i.mv(a.tplName,a.projectName),i.cd(a.projectName),i.rm("-rf",".git"),yield Z("git init --initial-branch=master"),yield Z(`git remote add origin ${m}`),yield Z(`git config user.name ${re("gitName")}`),yield Z(`git config user.email ${re("gitEmail")}`),o=Object.assign(Object.assign({},de()),{name:a.projectName,description:a.projectDesc}),le=le?Object.assign(Object.assign({},le),o):o,n.writeJSONSync(r.resolve("package.json"),le,{spaces:2}),pe({language:"JavaScript","lint-staged":z.JavaScript,repository:{url:m}}),j.spawnSync("git",["config","core.hooksPath",Ie]),j.spawnSync("git",["config","commit.template",r.join(Ie,".commit-msg-tpl")]),M(r.resolve(".z")).forEach((e=>{s.chmodSync(r.resolve(".z",e),493)})),yield n.writeFile(r.resolve("README.md"),function(e="项目中文名",t="项目描述"){return`\n# ${e}\n${t}\n\n## 快速开始\n### 安装依赖\n\`\`\`bash\n npm i\n\`\`\`\n\n### 本地开发\n\`\`\`bash\n npm run dev:{environment}:{platform}\n\`\`\`\n\n> 查看更多关于 [platform](https://zxf-fe.yuque.com/org-wiki-zxf-fe-ex4bve/qi89vg/nttvbeif4a62gtpz#faWqt) 和 [environment](https://zxf-fe.yuque.com/org-wiki-zxf-fe-ex4bve/qi89vg/nttvbeif4a62gtpz#faWqt)\n\n### 打包代码\n\`\`\`bash\n npm run build:{environment}:{platform}\n\`\`\`\n\n### 格式化、修复代码语法\n\`\`\`bash\n z lint prettier\n\`\`\`\n\n> [ESLint相关规范](https://zxf-fe.yuque.com/org-wiki-zxf-fe-ex4bve/qi89vg/ul914hdkqz8fr02g#AkvQ4)\n\n### 格式化文档\n\`\`\`bash\n z lint prettier\n\`\`\`\n\n> [Prettier相关规范](https://zxf-fe.yuque.com/org-wiki-zxf-fe-ex4bve/qi89vg/ul914hdkqz8fr02g#ojpwI)\n\n## 常见问题\n列出开发中常见的问题和解决方案\n\n## 了解更多\n在此处放入语雀文档链接。请在[前端团队-项目手册](https://zxf-fe.yuque.com/org-wiki-zxf-fe-ex4bve/qi89vg/bfrcicwzosoyaifg)中按照分类新建文档。\n`}(a.projectName,a.projectDesc)),p.succeed("模版初始化完成");const f=b("依赖安装中").start();yield Z("npm install"),f.succeed("依赖安装完成");const h=b("远程项目创建中").start(),g=yield(e={name:a.projectName,description:a.projectDesc,path:a.projectName,visibility:"private",namespace_id:a.groupId},we({url:`${xe()}/projects`,method:"post",data:e}));h.succeed("远程项目创建成功");const y=b("项目推送中").start();yield Z('git add . && git commit -m "chore: init"'),yield Z("git push -u origin master"),y.succeed(`项目已推送到远程,地址: ${t.blue(m)}`);const v=b("初始化分支中").start(),w=`feat_init_${Y()}`,$=a.group===I?[w]:[...q,w],S=yield Promise.allSettled($.map((e=>function(e){return we({url:`${xe()}/projects/${e.id}/repository/branches`,method:"post",data:e})}({id:g.id,branch:e,ref:"master"})))),x=[];S.forEach((({status:e},t)=>{"fulfilled"===e&&x.push($[t])})),yield Z("git fetch origin"),x.includes(w)?(yield Z(`git checkout -b ${w} origin/${w}`),v.succeed(`项目已切换到初始分支: ${t.blue(w)}`)):v.warn("开发分支检出失败!项目当前在主分支,请自行检出开发分支。");const O=`cd ${a.projectName} && z start`;console.log(`输入 ${t.green(O)} 开始开发吧~`)}catch(e){K(e)}var e,o}))}function Ae(e){return 0!==e.length||"请选择项"}function Be(){return k(this,void 0,void 0,(function*(){const{type:e}=yield d.prompt({type:"list",name:"type",message:"请选择你要创建的模板类型",choices:[{name:"feat - 业务需求开发",value:"feat"},{name:"fix - bug修复",value:"fix"},{name:"refactor - 技术内部需求",value:"refactor"},{name:"chore - 其他",value:"chore"}]});if(["feat","refactor"].includes(e)){const e=yield function(){return k(this,void 0,void 0,(function*(){const e=yield ke({url:Ne("/my-work-task.json?tid=mrrferp8"),method:"get"});return null==e?void 0:e.tasks.map((({id:e,name:t})=>({value:{name:t,value:e},name:t})))}))}(),{tasks:t}=yield d.prompt({type:"checkbox",name:"tasks",message:"请关联开发任务(可多选):",validate:Ae,choices:e.map((e=>Object.assign(Object.assign({},e),{name:`[${e.value.value}]: ${e.name}`})))});Ue("feat",t)}else if("fix"===e){const e=yield function(){return k(this,void 0,void 0,(function*(){const e=yield ke({url:Ne("/my-work-bug.json?tid=mrrferp8"),method:"get"});return null==e?void 0:e.bugs.map((({id:e,title:t})=>({name:t,value:{name:t,value:e}})))}))}(),{bugs:t}=yield d.prompt({type:"checkbox",name:"bugs",message:"请关联Bug(可多选):",validate:Ae,choices:e.map((e=>Object.assign(Object.assign({},e),{name:`[${e.value.value}]: ${e.name}`})))});Ue("fix",t)}else if("chore"===e){const{msg:e}=yield d.prompt({type:"input",name:"msg",message:"请输入commit msg:",validate:e=>0!==e.length||"请输入commit msg"});Ue("chore",[e])}}))}function Ue(e,i){let n="";if(["feat","refactor","fix"].includes(e)){n=`${e}(${i.map((e=>e.value)).join(",")}): ${i.map((e=>e.name)).join(";")}`}"chore"===e&&(n=`${e}: ${i[0]}`),s.writeFileSync(r.resolve(".z",".commit-msg-tpl"),n,"utf-8"),console.log(t.yellow(n)),R("commit msg模板写入成功,可以进行提交了")}function We(e,t){return k(this,void 0,void 0,(function*(){const i=function(e){const{pathname:t}=new URL(e),i=t.match(/\/(.+)\.git/);if(i)return i[1];K("GitLab URL有误")}(e),{originBranch:n,environment:o,platform:s,notify:r,processId:a}=t;var c;yield(c={params:{command:"build",params:JSON.stringify({originBranch:n,environment:o,platform:s,profile:{weWorkName:re("weWorkName"),weWorkUserId:re("weWorkUserId")}}),options:JSON.stringify({processId:a,notify:r||[]})},jobName:i},be({url:`${ce("jenkinsDomain")}/job/${c.jobName}/buildWithParameters`,method:"post",dataKey:"params",data:c.params,auth:{username:ce("jenkinsUsername"),password:ce("jenkinsPassword")}}))}))}function Re(e){return k(this,void 0,void 0,(function*(){try{const{originBranch:t,environment:i,platform:n,notify:o,processId:s}=e,r=me();!function(e,t){var i,n,o,s,r;const a=de(),c=me();(null===(i=null==c?void 0:c.repository)||void 0===i?void 0:i.url)||K("项目package.json文件中缺少repository.url");const l=`build:${e}:${t}`;(null==a?void 0:a.scripts[l])||K(`项目package.json文件scripts不存在命令${l}。`),["alipay","weapp"].includes(t)&&(a.mini||K("请在package.json配置mini字段"),"alipay"===t&&((null===(o=null===(n=a.mini)||void 0===n?void 0:n.alipay)||void 0===o?void 0:o.appid)||K("请在package.json配置mini.alipay.appid字段")),"weapp"===t&&((null===(r=null===(s=a.mini)||void 0===s?void 0:s.weapp)||void 0===r?void 0:r.appid)||K("请在package.json配置mini.weapp.appid字段")))}(i,n),yield Z("git fetch origin"),yield function(e,t){return k(this,void 0,void 0,(function*(){const i=me(),n=yield Z(`git remote show ${i.repository.url}`),[,o]=n.match(/HEAD branch: (.+)\n/),s=yield Z(`git log -b origin/${o} -1 --format=%H`),r=`origin/${e}`;if((yield Z(`git branch --contains ${s} -r ${r}`))||K(`请先将最新的主分支(${o})代码合并到${r},再进行部署。`),"production"!==t)return;const a=yield Z(`git log -b origin/${e} -1 --format=%H`),c=(yield Z(`git log ${s}...${a} -b ${r}`)).split("\n");c.length||K(`分支${e}上没有要发布的commit`);const l=yield Z("git log -b origin/test -1 --format=%H");(function(e,t){for(let i of t)if(!e.includes(i))return!1;return!0})((yield Z(`git log ${s}...${l} -b origin/test`)).split("\n"),c)||K("请先在测试环境发布要部署的代码")}))}(t,i),yield We(r.repository.url,{originBranch:t,environment:i,platform:n,notify:o,processId:s})}catch(e){K(e)}}))}function Ke(){if(s.existsSync(r.resolve(".z","project.json"))){const e=n.readJsonSync(r.resolve(".z","project.json"));if(e["lint-staged"])return e["lint-staged"];throw new Error("未找到lint配置")}throw new Error("请先初始化项目(z i .)。")}e.command("init").alias("i").argument("[type]","非必填。可选值:.。不传为初始化工具配置;传 . 为初始化当前项目。").description("初始化工具配置、项目配置").action((function(e){return k(this,void 0,void 0,(function*(){e?"."===e?(ee(),yield Je()):K("参数错误。执行 z init -h 查看帮助。"):yield Ce()}))})),e.command("create").alias("c").argument("[type]","可选值为project|p, branch|b, commit-msg|cm。传 p 为创建项目;传 b 为创建分支;传 cm 为创建提交信息").description("创建项目/分支/提交信息").action((function(e){return k(this,void 0,void 0,(function*(){let t;if(e)["project","pr"].includes(e)?t="project":["branch","b"].includes(e)?t="branch":["page","pa"].includes(e)?t="page":["commit-msg","cm"].includes(e)?t="commit-msg":K("参数输入错误");else{t=(yield d.prompt({type:"list",name:"type",message:"请选择你要创建的类型",choices:[{name:"提交信息",value:"commit-msg"},{name:"分支",value:"branch"},{name:"页面",value:"page"},{name:"项目",value:"project"}]})).type}"project"===t?yield _e():"branch"===t?(X(),ee(),yield te(),yield function(){return k(this,void 0,void 0,(function*(){const{type:e,purpose:t}=yield d.prompt([{name:"type",type:"list",message:"请选择创建分支的类型",choices:[{name:"开发新功能(feat)",value:"feat"},{name:"修复BUG(fix)",value:"fix"},{name:"重构/优化代码(refactor)",value:"refactor"}]},{name:"purpose",type:"input",message:"请输入创建分支的目的(大小写字母、数字,小驼峰式命名。如userInfo)",validate:J}]),i=`${e}_${t}_${Y()}`,n=me(),o=yield Z(`git remote show ${n.repository.url}`),[,s]=o.match(/HEAD branch: (.+)\n/);yield Z("git fetch origin"),yield Z(`git checkout -b ${i} origin/${s}`)}))}()):"commit-msg"===t?(X(),ee(),yield Be()):"page"===t&&(X(),ee(),yield function(){return k(this,void 0,void 0,(function*(){s.mkdirSync(r.resolve("src","pages"),{recursive:!0});const{dirName:e}=yield d.prompt([{name:"dirName",type:"input",message:"请输入页面目录名称(已存在则跳过创建)",validate:_}]);s.mkdirSync(r.resolve("src","pages",e),{recursive:!0});const t=M(r.resolve("src","pages",e)),{pageName:i}=yield d.prompt([{name:"pageName",type:"input",message:"请输入页面名称",validate:e=>function(e,t){return e?/^[a-z][a-z0-9\-]+$/.test(e)?!t.includes(e)||"页面已存在":"支持小写字母、数字,连字符(-)命名,小写字母开头。如user、modules-3":"页面名称不能为空"}(e,t)}]);console.log(i)}))}())}))})),e.command("merge").alias("m").description("合并当前分支到指定远程分支,并部署。").action((function(){return k(this,void 0,void 0,(function*(){var e;X(),ee(),yield te();const i=yield he(),n=yield Ee(i.id),o=[...q],s=i.group===I,r=n.filter((e=>s?![i.sourceBranch].includes(e.name):![...N,i.sourceBranch].includes(e.name))).map((e=>{let i=e.name;return!s&&o.includes(i)&&(i=t.bold.blue(i)),{name:i,value:e.name}})),{target:a}=yield d.prompt([{type:"list",name:"target",message:"请选择要合并到的目标分支:",choices:r}]),l=o.includes(a);let u="h5",m=[];if(l){const e=yield ve(),t=yield d.prompt([{type:"list",name:"platform",message:"请选择平台",choices:[{name:"网页 - h5",value:"h5"},{name:"支付宝小程序 - alipay",value:"alipay"},{name:"微信小程序 - weapp",value:"weapp"}]},{type:"search-checkbox",name:"notify",message:"请选择部署成功要通知的人员:",choices:e,validate:e=>!(e.length<1)||"至少选一个"}]);ye(m,e),u=t.platform,m=t.notify}yield Z("git fetch origin"),yield Z(`git push -u origin ${i.sourceBranch}`);let p=0;try{const{iid:e}=yield(f={title:"MR by z-develop",id:i.id,source_branch:i.sourceBranch,target_branch:a,remove_source_branch:s&&N.includes(a)},we({url:`${xe()}/projects/${f.id}/merge_requests`,method:"post",data:f}));p=e}catch(t){if(c.isAxiosError(t)){409===(null===(e=null==t?void 0:t.response)||void 0===e?void 0:e.status)&&K(`存在重复的合并请求,前往查看${i.mergeRequestUrl}`)}K(t)}var f;const h=()=>k(this,void 0,void 0,(function*(){var e;try{yield new Promise((e=>{setTimeout(e,5e3)})),yield function(e){return we({url:`${xe()}/projects/${e.id}/merge_requests/${e.iid}/merge`,method:"put"})}({id:i.id,iid:p})}catch(t){if(c.isAxiosError(t)){406===(null===(e=null==t?void 0:t.response)||void 0===e?void 0:e.status)?yield h():(yield function(e){return we({url:`${xe()}/projects/${e.id}/merge_requests/${e.iid}`,method:"put",data:e})}({id:i.id,iid:p,state_event:"close"}),K("合并过程中出现冲突,MR已关闭。建议在本地完成合并。"))}else K(t)}}));yield h(),l&&(yield Re({originBranch:a,environment:a,platform:u,notify:m,processId:""}))}))})),e.command("deploy").alias("d").description("发布指定远程分支").action((function(){return k(this,void 0,void 0,(function*(){const e=yield ve(),{environment:t,platform:i,notify:n}=yield d.prompt([{type:"list",name:"environment",message:"请选择部署环境",choices:O},{type:"list",name:"platform",message:"请选择平台",choices:E},{type:"search-checkbox",name:"notify",message:"请选择部署成功要通知的人员:",choices:e,validate:e=>!(e.length<1)||"至少选一个"}]);ye(n,e);let o=t,s="";if("production"===t){const e=yield he(),t=(yield Ee(e.id)).filter((e=>![...N,...q].includes(e.name))).map((e=>({name:e.name,value:e.name}))),n=yield d.prompt([{type:"list",name:"branchName",message:"请输入要部署的分支:",choices:t},{type:"input",name:"processId",message:"请输入本次部署的企微审批编号"}]);o=n.branchName,s=n.processId,function(e){const t=e.split("_");if(4!==t.length)return!1;const[i,n,o]=t;return!!D.includes(i)&&!0===J(n)&&8===o.length&&!isNaN(Number(o))}(o)||K("分支命名不符合规范,参见https://zhongshitech.yuque.com/nx4ugr/guide/mg8t44#bQhu4");const{data:{state:a,content:c}}=yield(r={businessId:s},Se({url:"/approval/findByBusinessId",data:r}));1===a&&K("当前审批流程状态为审批中,审批通过才能进行发布。"),3===a&&K("当前审批流程状态为已驳回,请重新提交审批。"),4===a&&K("当前审批流程状态为已发布,如需再次发布,请重新提交审批。");const{formComponentValues:l}=JSON.parse(c),u={};l.forEach((e=>{u[e.name]=e.value})),u["申请人"]!==re("weWorkName")&&K("发布审批申请人与当前发布人不一致!"),u["项目名称"]!==de().name&&K("发布审批项目名称与当前发布项目名称不一致!"),u["发布分支"]!==o&&K("发布审批发布分支与当前发布分支不一致!"),u["发布平台"]!==i&&K("发布审批发布平台与当前发布平台不一致!")}var r;yield Re({originBranch:o,environment:t,platform:i,notify:n,processId:s})}))})),e.command("start").alias("s").description("启动本地开发环境").action((function(){return k(this,void 0,void 0,(function*(){const e=de(),{environment:t}=yield d.prompt([{type:"list",name:"environment",message:"请选择环境",choices:O}]),n=`dev:${t}`;if(e.scripts[n])try{i.exec(`npm run ${n}`,{silent:!1})}catch(e){K(e)}else K(`项目中(package.josn > scripts)不存在命令${n},请先添加!`)}))})),e.command("lint").alias("l").argument("[type]","非必填。可选值为commit-msg|cm, commit-files|cf, prettier|p, eslint|e。传 cm 为执行 lint commit-msg;传 cf 为执行 lint commit-files;传 p 为全部文件执行prettier;传 e 为全部文件执行eslint。cm 和 cf属于内部命令,会在git hooks中自动执行。").description("执行 lint 脚本。包含 lint staged 、 lint commit message、 prettier、 eslint。").action((function(e){return k(this,void 0,void 0,(function*(){let t;if(X(),ee(),e)["commit-msg","cm"].includes(e)?t="commit-msg":["commit-files","cf"].includes(e)?t="commit-files":["prettier","p"].includes(e)?t="prettier":["eslint","e"].includes(e)?t="eslint":K("参数输入错误");else{t=(yield d.prompt({type:"list",name:"type",message:"请选择你要执行的操作",choices:[{name:"全局执行 prettier",value:"prettier"},{name:"全局执行 eslint",value:"eslint"}]})).type}if("commit-msg"===t)yield function(){return k(this,void 0,void 0,(function*(){const e=function(e){const t=s.readFileSync(r.resolve(".git","COMMIT_EDITMSG"),"utf-8").split(": ");if(1===t.length)return"body前缺少「:」";{const e=t[0];return/^(feat|fix|refactor)/.test(e)?!!/\(\d+(?:,\d+)*\)/.test(e)||"ID缺少或者格式不正确。":/^chore/.test(e)?"chore"===e||"chore类型无需填写ID。":"不存在的提交类型。"}}();!0===e?R("commit msg validate success."):K(`commit msg格式错误。${e}`)}))}();else if("commit-files"===t)yield function(){return k(this,void 0,void 0,(function*(){(yield w({concurrent:!1,debug:void 0,config:Ke()}))?R("代码风格检测通过!"):K("代码风格检测未通过!")}))}();else if("prettier"===t){s.existsSync(r.resolve("node_modules",".bin","prettier"))||K("该项目未安装prettier,请安装后重试");try{yield Z("prettier --write . --config .z/.prettierrc.json --ignore-path .z/.prettierignore --ignore-unknown --no-error-on-unmatched-pattern",{silent:!1}),R("prettier执行成功")}catch(e){K("prettier校验出错")}}else if("eslint"===t){console.log(r.resolve("node_modules",".bin","eslint")),s.existsSync(r.resolve("node_modules",".bin","eslint"))||K("该项目未安装eslint,请安装后重试");try{yield Z("eslint '**/*.{vue,js,jsx,cjs,mjs,ts,tsx,cts,mts}' --fix",{silent:!1}),R("eslint执行成功")}catch(e){K("eslint校验出错")}}}))})),function(){k(this,void 0,void 0,(function*(){process.on("unhandledRejection",(e=>{})),process.on("uncaughtException",(e=>{})),i.config.fatal=!0,i.config.silent=!0,i.config.verbose=!1,yield Te(),d.registerPrompt("search-checkbox",De)}))}(),e.name("z-develop").alias("z").description(`z-develop, 开发流程管理工具。\n了解更多: ${t.blue("https://zxf-fe.yuque.com/org-wiki-zxf-fe-ex4bve/qi89vg/us8lgdb5cq4kf3aa")}`).usage("<command> [options]").version($.version,"-v, --version","当前版本号").helpOption("-h, --help","帮助").showHelpAfterError("可以使用z -h查看帮助。"),e.parse();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cli-z-develop",
3
- "version": "0.0.14",
3
+ "version": "0.0.15",
4
4
  "description": "前端本地开发命令行工具",
5
5
  "main": "dist/index.js",
6
6
  "bin": {