@jerryc05/hi-tools 0.0.10 → 0.0.12
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.
- package/dist/index.js +16 -16
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,25 +1,25 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
typeof globalThis.CustomEvent>"u"&&(globalThis.CustomEvent=class extends Event{constructor(t,n={}){super(t,n),this.detail=n.detail}});import{readFile as de}from"node:fs/promises";import{join as ue}from"node:path";var
|
|
3
|
-
Go to https://luban.bytedance.net/npm/publish and get your personal SCM username + password.`),process.exit(1));let{execa:m}=await import("execa");try{let c=m`git log -1 --pretty=%s`,a,
|
|
4
|
-
${a?`hash=${a}`:`brch=${
|
|
5
|
-
desc=${f.desc}`);let h=await fetch("https://scm.byted.org/api/v2/npm_versions/",{method:"POST",headers:{Authorization:`Basic ${Buffer.from(`${
|
|
6
|
-
\u274C ${
|
|
7
|
-
`).filter(o=>{if(o.includes("/node_modules/"))return!1;let
|
|
8
|
-
${await i.text()}`),process.exit(1));let r=await o();{let{count:c,blockingCount:a,runningCount:p}=r;a>0&&b(`Found ${a}/${c} blocking task(s)! Build may have failed?`),p>0&&b(`Found ${p}/${c} running task(s)! Still building?`)}let s=B(r.pipelineRuns);if(s.length)return s;let m=await ie(e,t,n);return await re(m,t,n)}async function ie(e,t,n){let{response:o,getJson:r}=await R({pipelineId:e,pageSize:10,withoutJob:!0},t,n);o.ok||(g(`[getRunInfoByPipelineID] failed: ${o.status} ${o.statusText}
|
|
9
|
-
${await o.text()}`),process.exit(1));let s=await r();s.pipelineRuns.length<=0&&(g(`\u6700\u8FD1 10 \u6B21 run \u67E5\u8BE2\u4E3A\u7A7A
|
|
10
|
-
${JSON.stringify(s,null,1)}`),process.exit(1)),ee("\u6700\u65B0\u4E00\u6B21 pipeline run \u53EF\u80FD\u672A\u7ED3\u675F\u3001\u5931\u8D25\uFF0C\u6216\u6CA1\u6709\u627E\u5230 Gecko \u4FE1\u606F\u3002\u8BF7\u9009\u62E9\u4E00\u4E2A\u5386\u53F2 run \u67E5\u770B\u3002","\u9700\u8981\u9009\u62E9\u5386\u53F2 run");let m=s.pipelineRuns.map(a=>{let p=`status=${a.runStatus}`,f=se(a),h=a.triggerInfo?.triggeredBy||a.createdBy||"?";return{value:a.runId,label:`#${a.runSeq} runId=${a.runId}`,hint:`${p} ${f} by=${h}`}}),c=await te({message:"\u8BF7\u9009\u62E9\u8981\u67E5\u770B\u7684 pipeline run",options:m});return Y(c)&&(Z("\u5DF2\u53D6\u6D88\u9009\u62E9 run"),process.exit(0)),c}async function re(e,t,n){let{response:i,getJson:o}=await j(e,t,n);i.ok||(g(`[getRunDetailByRunID] failed: ${i.status} ${i.statusText}
|
|
11
|
-
${await i.text()}`),process.exit(1));let r=await o();return B([r.pipelineRun])}function se(e){return e.completedAt?`completedAt=${w(e.completedAt)}`:e.startedAt?`startedAt=${w(e.startedAt)}`:e.createdAt?`createdAt=${w(e.createdAt)}`:"time=?"}async function ae({pipelineId:e,url:t,region:n}){let{jwtStr:i,jwtObj:o}=await O(),r=(()=>{if(e==null&&!t)throw new Error("pipelineId or url is required");return e??ne(t??"")})(),s=(await oe(r,i,o)).filter(c=>c.region?.includes(n??""));s.length<=0&&g(`No Gecko info found${n?` matching region [${n}]`:""} in latest run`);let{default:m}=await import("qrcode");for(let c=0;c<s.length;c++){let a=s[c];try{let p=await m.toString(a?.qrCodeScheme??"",{type:"terminal",small:!0,errorCorrectionLevel:"L"});console.log(`
|
|
2
|
+
typeof globalThis.CustomEvent>"u"&&(globalThis.CustomEvent=class extends Event{constructor(t,n={}){super(t,n),this.detail=n.detail}});import{readFile as de}from"node:fs/promises";import{join as ue}from"node:path";var C=[{cmd:{name:"bm <target>",desc:"[B]ranch [M]erge: merge current HEAD into target branch without switching"},action:async e=>{throw console.log(`\u{1F680} Starting silent merge: HEAD -> ${e}`),new Error("Not implemeted!")}}];import{networkInterfaces as W}from"node:os";var _=[{cmd:{name:"ips",desc:"Show current machine's IP addrs"},options:[{name:"-4, --onlyIpv4",desc:"IPv4 only"},{name:"-6, --onlyIpv6",desc:"IPv6 only"}],action:({onlyIpv4:e,onlyIpv6:t})=>{let n=W(),i={};for(let[o,s]of Object.entries(n))s=s?.filter(r=>e?r.family==="IPv4":t?r.family==="IPv6":!0),s?.length&&(i[o]=s.map(r=>r.address));console.log(i)}}];async function V({repoID:e,hash:t,branch:n}){let i="SCM_USERNAME",o="SCM_PASSWORD",s=process.env[i],r=process.env[o];(!s||!r)&&(console.log(`Missing ${s?o:i} in env var.
|
|
3
|
+
Go to https://luban.bytedance.net/npm/publish and get your personal SCM username + password.`),process.exit(1));let{execa:m}=await import("execa");try{let c=m`git log -1 --pretty=%s`,a,l;n?n===!0?l=(await m`git branch --show-current`).stdout.trim():l=n:t&&(t===!0?a=(await m`git rev-parse HEAD`).stdout.trim():a=t);let f={repos:e,create_user:s,pub_base:a?"commit_base":"branch_base",base_commit_hash:a??"",branch_name:l??"",desc:`[${d?.version}] ${(await c).stdout.trim()}`,has_version_stage:!1};console.log(`\u2139\uFE0F ${f.create_user} is publishing ${d?.name}@${d?.version} to repoID=${f.repos}
|
|
4
|
+
${a?`hash=${a}`:`brch=${l}`}
|
|
5
|
+
desc=${f.desc}`);let h=await fetch("https://scm.byted.org/api/v2/npm_versions/",{method:"POST",headers:{Authorization:`Basic ${Buffer.from(`${s}:${r}`).toString("base64")}`,Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(f)});if(!h.ok){let v=await h.text();console.log(`\u274C HTTP ${h.status} Error: ${v}`),process.exit(1)}let x=await h.json();console.log("\u{1F389} Successfully published:",x)}catch(c){console.error("\u274C Execution Failed:",c),process.exit(1)}}var k=[{cmd:{name:"tt-npm-pub <repoID>",desc:"[PUB]lish current hash of current repo to Luban"},options:[{name:"--hash [hash]",desc:"Publish pkg by hash (default)"},{name:"-b, --branch [branch]",desc:"Publish pkg by branch"}],action:V}];import{hostname as Q}from"node:os";var P=[{cmd:{name:"mdns",desc:"Show mdns hostname.local"},action:()=>{let e=Q();console.log(e.toLowerCase().endsWith(".local")?e:`${e}.local`)}}];import p from"picocolors";var y=e=>console.log(p.underline(p.blue(`\u23F3 ${e}`))),S=()=>console.log(p.bold(p.underline(p.green("\u{1F389} DONE!")))),g=e=>console.log(p.underline(`
|
|
6
|
+
\u274C ${p.bold(p.bgRed(e))}`)),D=e=>console.log(p.bold(p.underline(p.green(`\u2705 ${e}`)))),b=e=>console.log(p.underline(p.yellow(`\u{1F4AC} ${e}`))),H=e=>console.log(p.bold(p.underline(p.green(`\u{1F44B} ${e}`))));async function T(){let{execa:e}=await import("execa");try{let{stdout:t}=await e`git rev-parse --abbrev-ref --symbolic-full-name @{u}`;return t.split("/")[0]||"origin"}catch{return"origin"}}async function E(e){y(`${e?"Updating":"Fetching"} master...`);let{execa:t}=await import("execa");await t({stdio:"inherit",env:{GIT_TRACE:"1"}})`git fetch ${await T()} master${e?":master":""}`,y("Merging ..."),await t({stdio:"inherit",env:{GIT_TRACE:"1"}})`git merge ${await T()}/master --no-verify --no-edit`,S()}var U=[{cmd:{name:"mm",desc:"[M]erge [M]aster: Update local master to remote's, then merge into current branch"},action:()=>E(!0)},{cmd:{name:"mmm",desc:"[M]erge [M]aster (don't [M]odify local master): Merge remote's master into current branch, without updating local master"},action:()=>E(!1)}];var J=[{cmd:{name:"tschk",desc:"My ts-check rules"},action:async()=>{y("Running custom tsc type-check...");let e=["2322","2339","2551","6133","6192","18048"],{execa:t}=await import("execa");try{let{stdout:n}=await t({reject:!1,stderr:"ignore"})`npx tsc --noEmit --emitDeclarationOnly false`,i=n.split(`
|
|
7
|
+
`).filter(o=>{if(o.includes("/node_modules/"))return!1;let s=o.match(/error TS(\d+):/);return!(!s?.[1]||e.includes(s[1]))});i.length>0?(i.map(o=>console.log(o)),g("Type-check failed!"),process.exit(1)):D("Type-check passed!")}catch(n){g("Type-check: Unexpected err:"),console.error(n),process.exit(1)}}}];var A=[{cmd:{name:"tt-bam",desc:"Update BAM code-gen"},action:async()=>{let{execa:e}=await import("execa");await e({stdio:"inherit"})`pnpm dlx @byted-arch-fe/bam-code-generator update`}}];import{cancel as Z,isCancel as Y,note as ee,select as te}from"@clack/prompts";import I from"picocolors";var N="https://bits.bytedance.net";async function R(e,t,n,i){let o={...e,pageNum:e.pageNum??1},s=`${N}/api/v1/pipelines/runs?${new URLSearchParams(o).toString()}`,r=await fetch(s,{method:"GET",headers:{"Content-Type":"application/json","X-jwt-token":t,Username:n.username},signal:i??null});return{response:r,getJson:async()=>await r.json()}}async function j(e,t,n){let i=`${N}/api/v1/pipelines/runs/${e}`,o=await fetch(i,{method:"GET",headers:{"Content-Type":"application/json","X-jwt-token":t,Username:n.username}});return{response:o,getJson:async()=>await o.json()}}import{cac as X}from"cac";var u=X("hi");function w(e){return new Intl.DateTimeFormat("zh-CN",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",timeZoneName:"short"}).format(new Date(e))}import O from"picocolors";var $;async function B(){if(y("Logging in..."),!$){let{AIPaaSAuth:n}=await import("@byted/aipaas-auth");$=new n("cn")}let e=await $.getJwt(),t=await $.getUserInfo();return H(`Hi ${O.magenta(t.username)} from ${O.blue(`${t.scope} ${t.work_country}`)}`),b(` Login will expire on ${w(t.exp*1e3)}`),{jwtStr:e,jwtObj:t}}async function ne({pipelineId:e,url:t,region:n}){let{jwtStr:i,jwtObj:o}=await B(),s=(()=>{if(e==null&&!t)throw new Error("pipelineId or url is required");return e??ie(t??"")})(),r=(await oe(s,i,o)).filter(c=>c.region?.includes(n??""));r.length<=0&&g(`No Gecko info found${n?` matching region [${n}]`:""} in latest run`);let{default:m}=await import("qrcode");for(let c=0;c<r.length;c++){let a=r[c];try{let l=await m.toString(a?.qrCodeScheme??"",{type:"terminal",small:!0,errorCorrectionLevel:"L"});console.log(`
|
|
12
8
|
|
|
13
|
-
${
|
|
9
|
+
${l}`),console.dir(a),c<r.length-1&&console.log(`
|
|
14
10
|
|
|
15
11
|
-----------------
|
|
16
12
|
|
|
17
|
-
`)}catch(
|
|
18
|
-
|
|
19
|
-
|
|
13
|
+
`)}catch(l){console.error("Failed to generate QR:",l)}}}async function oe(e,t,n){let{response:i,getJson:o}=await R({pipelineId:e,pageSize:1,withoutJob:!1},t,n);i.ok||(g(`[getRunInfoByPipelineID] failed: ${i.status} ${i.statusText}
|
|
14
|
+
${await i.text()}`),process.exit(1));let s=await o();{let{count:c,blockingCount:a,runningCount:l}=s;a>0&&b(`Found ${a}/${c} blocking task(s)! Build may have failed?`),l>0&&b(`Found ${l}/${c} running task(s)! Still building?`)}let r=G(s.pipelineRuns);if(r.length)return r;let m=await se(e,t,n);return await re(m,t,n)}function ie(e){let t=/\bpipelineId=(\d+)\b/,n=e.match(t);if(n?.[1])return n[1];throw new Error(`Invalid URL. Expecting a url containing ${I.bold(I.yellow("pipelineId"))} query param. E.g. `+I.underline(I.gray(`https://b??.net/devops/??/develop/detail/??/flow?devops_space_type=server_fe&${I.bold(I.magenta("pipelineId=1139212901634"))}&stage=dev_gatekeeper_stage`)))}function G(e){return e.flatMap(t=>t.jobs.map(n=>{try{let i=n.jobAtom.output;if(!i)return null;let o=i.GECKO_packageInfo;if(!o)return null;let s=JSON.parse(o),{qrCodeScheme:r,candidatePackage:m,channel:c,updatedAt:a,creator:l,distributeRule:f}=s.package,{scmVersion:h}=m,x=w(Number.parseInt(a,10)*1e3),v=f.envLaneList.flatMap(z=>z.values);return{qrCodeScheme:r,region:i.GECKO_region,scmVersion:h,channel:c,updatedDate:x,creator:l,envs:v,runId:t.runId,runSeq:t.runSeq,pipelineRunUrl:t.pipelineRunUrl}}catch(i){return console.error(i),null}}).filter(n=>n!=null)).filter(t=>!!t)}async function se(e,t,n){let{response:o,getJson:s}=await R({pipelineId:e,pageSize:10,withoutJob:!0},t,n);o.ok||(g(`[getRunInfoByPipelineID] failed: ${o.status} ${o.statusText}
|
|
15
|
+
${await o.text()}`),process.exit(1));let r=await s();r.pipelineRuns.length<=0&&(g(`No pipeline runs found in the most recent 10 runs
|
|
16
|
+
${JSON.stringify(r,null,1)}`),process.exit(1)),ee("The latest pipeline run may still be running/failed. Please select a historical run to inspect.","Historical run selection required");let m=r.pipelineRuns.map(a=>{let l=`status=${a.runStatus}`,f=ae(a),h=a.triggerInfo?.triggeredBy||a.createdBy||"?";return{value:a.runId,label:`#${a.runSeq} runId=${a.runId} ${l}`,hint:`${f} by ${h}`}}),c=await te({message:"Please select the pipeline run to inspect",options:m});return Y(c)&&(Z("Run selection cancelled"),process.exit(0)),c}async function re(e,t,n){let{response:i,getJson:o}=await j(e,t,n);i.ok||(g(`[getRunDetailByRunID] failed: ${i.status} ${i.statusText}
|
|
17
|
+
${await i.text()}`),process.exit(1));let s=await o();return G([s.pipelineRun])}function ae(e){return e.completedAt?`completed @ ${w(e.completedAt)}`:e.startedAt?`started @ ${w(e.startedAt)}`:e.createdAt?`created @ ${w(e.createdAt)}`:"time=?"}var M=[{cmd:{name:"tt-gecko",desc:"Show gecko info by bits URL"},options:[{name:"-p,--pipelineId <pipelineId>",desc:"Pipeline ID (Overrides URL)"},{name:"-u,--url <url>",desc:"Bits URL"},{name:"-r,--region <region>",desc:"Region kw filter"}],examples:[`${u.name} tt-gecko -r us -u 'https://b??.net/devops/??/develop/detail/??/flow?devops_space_type=server_fe&pipelineId=1139212901634&stage=dev_gatekeeper_stage'`],action:ne}];import{access as ce,constants as me}from"node:fs/promises";var L=[{cmd:{name:"tt-i18n",desc:"I18n scan and sort"},action:async()=>{let e="starling.config.js",t="combine-lang.js";for(let o of[e,t])try{await ce(o,me.R_OK)}catch(s){console.error(`tt i18n: Failed to read ${o}
|
|
18
|
+
`,s),process.exit(1)}let{execa:n,execaNode:i}=await import("execa");await n({stdio:"inherit"})`pnpm dlx @ies/starling-cli scan -c ${e} --fallback --disable-browser`,await i({stdio:"inherit"})`${e}`,await n({stdio:"inherit"})`pnpm --package=json-sort-cli dlx sortjson ./src/lang`.catch(o=>console.error("tt i18n sortjson error:",o))}}];var q=[...A,...M,...L];async function le({npm:e,global:t}){let{execa:n}=await import("execa");await n({stdio:"inherit"})`${e?"npm":"pnpm"} add ${t?"-g":""} https://github.com/jerryc05/hi-tools.git`}var F=[{cmd:{name:"upgrade",desc:"Upgrade to latest version (default using pnpm)"},options:[{name:"--npm",desc:"Use npm instead of default"},{name:"-g,--global",desc:"Pass -g flag to pkg mgr"}],action:le}];var pe=e=>new Promise(t=>setTimeout(t,e)),K=[{cmd:{name:"wup",desc:"[W]ait for pkg publish, [U]pdate target repo, and [P]ush"},options:[{name:"-t, --target <path>",desc:"Target repository path"},{name:"-c, --cmdPrefix <prefix>",desc:"Pkg install command prefix",config:{default:"pnpm add"}},{name:"--timeout <limit>",desc:"Timeout limit in seconds",config:{default:300}}],examples:[`${u.name} wup -t "/tmp/otherRepoPath" -c "emo add"`,`${u.name} wup -t "/tmp/otherRepoPath" -c "rush add --make-consistent -p"`],action:async({target:e,cmdPrefix:t,timeout:n})=>{d||(console.log("\u274C Unable to parse package.json!"),process.exit(1)),e||(console.log("\u274C Missing target repo path"),process.exit(1));let i=d.version,o=`${d.name}@${i}`,s=1e4,r=[...t.split(" "),o];console.log(`\u{1F680} Monitoring ${o}...`),console.log(`\u{1F4C2} Target: ${e}`),console.log(`\u{1F6E0} Install cmd: ${r.join(" ")}`);let{execa:m}=await import("execa");try{console.log("\u{1F4E5} Pulling latest changes in target repo..."),await m({cwd:e,stdio:"inherit",env:{GIT_TRACE:"1"}})`git pull`;let c=Date.now();for(;;){let{exitCode:a}=await m({reject:!1,stdio:"inherit"})`npm view ${o} version`;if(a===0){console.log(`
|
|
19
|
+
\u2705 v${i} is live! Installing...`);try{await m({cwd:e,stdio:"inherit"})`${r}`,console.log(`
|
|
20
20
|
\u{1F389} [SUCCESS] ${o} installed!`);break}catch{console.log(`
|
|
21
21
|
\u26A0\uFE0F Registry updated but installation failed, retrying...`)}}else process.stdout.write(".");(Date.now()-c)/1e3>=n&&(console.error(`
|
|
22
|
-
\u274C [ERROR] Timed out after ${n}s.`),process.exit(1)),await
|
|
22
|
+
\u274C [ERROR] Timed out after ${n}s.`),process.exit(1)),await pe(s)}console.log("\u{1F4DD} Committing changes..."),await m({stdio:"inherit"})`git commit -am 'chore: upd ${o}`,console.log("\u{1F4E4} Pushing to remote..."),await m({stdio:"inherit"})`git push`,console.log("\u{1F389} DONE!")}catch(c){console.error(`
|
|
23
23
|
\u274C Task failed:`,c),process.exit(1)}}}];var d=JSON.parse(await de(ue(import.meta.dirname,"../package.json"),"utf8"));process.argv.includes("--quiet")&&process.exit(0);d&&(console.log(),b(`${d.name} v${d.version}
|
|
24
24
|
|
|
25
|
-
`));var ge=[...F,...
|
|
25
|
+
`));var ge=[...F,...U,...J,...K,..._,...P,...C,...k,...q];for(let{cmd:e,options:t,examples:n,action:i}of ge){let o=u.command(e.name,e.desc);for(let s of t??[])o=o.option(s.name,s.desc,s.config);for(let s of n??[])o=o.example(s);o.action(i)}u.version(d.version).help();u.command("","Print help message").option("--quiet","Silently quit").action(({quiet:e})=>{e||u.outputHelp()});u.parse();export{d as PKG_JSON_OBJ};
|