UNPKG

@dovenv/repo

Version:

Repository tools for any runtime

47 lines (39 loc) 35.5 kB
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});const utils=require("@dovenv/core/utils"),u=require("husky"),node_child_process=require("node:child_process"),core=require("@dovenv/core");function _interopDefaultCompat(k){return k&&typeof k=="object"&&"default"in k?k.default:k}const u__default=_interopDefaultCompat(u),homepage="https://dovenv.pigeonposse.com/guide/plugin/repo";class Repo{utils;opts;constructor({opts:s,utils:o}){this.opts=s,this.utils=o,this.utils.helpURL=homepage,this.utils.title="repo",this.onInit()}onInit(){this.opts||(this.opts={}),!this.opts?.homepageURL&&this.utils.pkg?.homepage&&(this.opts.homepageURL=this.utils.pkg.homepage),!this.opts?.tags&&this.utils.pkg?.keywords&&(this.opts.tags=this.utils.pkg.keywords),!this.opts?.desc&&this.utils.pkg?.description&&(this.opts.desc=this.utils.pkg.description),!this.opts?.workflowsDir&&this.utils.wsDir&&(this.opts.workflowsDir=utils.joinPath(this.utils.wsDir,".github","workflows")),this.opts?.defaultBranch||(this.opts.defaultBranch="main"),!this.opts?.URL&&this.utils.pkg&&(this.opts.URL=utils.getPackageRepoUrlFromContent(this.utils.pkg)),!this.opts?.ID&&this.utils.pkg?.extra&&this.utils.pkg.extra.repoID&&(this.opts.ID=this.utils.pkg.extra.repoID),!this.opts?.ID&&this.utils.pkg?.extra&&this.utils.pkg.extra.repoId&&(this.opts.ID=this.utils.pkg.extra.repoId),!this.opts?.userID&&this.utils.pkg?.extra&&this.utils.pkg.extra.userID&&(this.opts.userID=this.utils.pkg.extra.userID),!this.opts?.URL&&this.opts?.ID&&this.opts?.userID&&(this.opts.URL=`https://github.com/${this.opts.userID}/${this.opts.ID}`),!this.opts?.ID&&this.opts.URL&&(this.opts.ID=this.opts.URL.split("/").pop()),!this.opts?.userID&&this.opts.URL&&(this.opts.userID=this.opts.URL.split("/").slice(-2,-1)[0])}async _existsLocalGit(){return await utils.existsLocalBin("git")}async initGH(){if(!await utils.existsLocalBin("gh")){console.warn("You must install gh binary for use `gh` commands. See: https://cli.github.com/");return}if(!await utils.isGitHubAuthenticated()){console.warn("You must login to GitHub for use gh commands. Use `gh auth login`.See: https://cli.github.com/manual/gh_auth_login");return}}async init(){if(!await this._existsLocalGit()){console.warn(`Git is not installed or not detected. Git is required to run this command. Please Install git and try again`);return}}}class GitSuper extends Repo{async getGitRemoteURL(){return this.opts?.URL||(await utils.execChild("git remote get-url origin")).stdout||void 0}}class GitAdd extends GitSuper{async ask(s="."){const o=await this.utils.prompt.text({message:"What paths do you want to add?",placeholder:".",initialValue:s});return this.utils.prompt.isCancel(o)&&await this.utils.onCancel(),o}async exec(s){const o=`git add ${s}`,[a,h]=await utils.catchExecOutput(`git add ${s}`);a?console.error(this.utils.style.error.msg(a.message)):h&&h!==""&&(console.log(this.utils.style.info.hr(o)),console.log(this.utils.style.success.p(h)),console.log(this.utils.style.info.hr()))}async run(){await this.init();const s=await this.ask();this.exec(s)}}class GitBranch extends GitSuper{async askSelectBranch(s,o=!0){const a=await this.getAll(o),h=await this.utils.prompt.select({message:"Select branch of the repository",options:a.map(r=>({value:r,label:r})),initialValue:s&&a.includes(s)?s:void 0});if(this.utils.prompt.isCancel(h))await this.utils.onCancel();else if(!h||typeof h!="string")throw new Error("Unexpected error: No branch selected");return h}async#t(){const s=await this.utils.prompt.text({message:"Set new branch name"});if(this.utils.prompt.isCancel(s))await this.utils.onCancel();else if(!s||typeof s!="string")throw new Error("Unexpected error: No branch selected");return s}async getCurrent(){const{stdout:s}=await utils.execChild("git branch --show-current");return s}async showCurrent(){const s=await this.getCurrent();this.utils.prompt.note(this.utils.style.info.lk(s),"Current branch"),this.utils.prompt.log.step("")}async getAll(s=!0){const o=s?"git branch -a":"git branch",{stdout:a}=await utils.execChild(o);return a.split(` `).map(h=>h.replace(/[*\s]/g,"").trim()).filter(h=>h.length>0)}async showAll(s=!0){const o=(await this.getAll(s)).map(a=>this.utils.style.info.lk(a)).join(` `);this.utils.prompt.note(o,"All branches"),this.utils.prompt.log.step("")}async change(s,o=!1){const a=s||await this.askSelectBranch(),h=o?`git checkout -f ${a}`:`git checkout ${a}`,{stdout:r,stderr:g}=await utils.execChild(h);if(g)throw new Error(`Error changing branch: ${g}`);this.utils.prompt.log.success(`Switched to branch: ${r.trim()}`)}async switch(s){const o=s||await this.askSelectBranch(),{stderr:a}=await utils.execChild(`git switch ${o}`);if(a)throw new Error(`Error switching to branch: ${a}`);this.utils.prompt.log.success(`Switched to branch: ${o}`)}async create(s){const o=s||await this.#t(),{stderr:a}=await utils.execChild(`git branch ${o}`);if(a)throw new Error(`Error creating branch: ${a}`);this.utils.prompt.log.success(`Created branch: ${o}`)}async createAndSwitch(s){const o=s||await this.#t(),{stderr:a}=await utils.execChild(`git checkout -b ${o}`);if(a)throw new Error(`Error creating and switching to branch: ${a}`);this.utils.prompt.log.success(`Created and switched to branch: ${o}`)}async delete(s,o=!1){const a=s||await this.askSelectBranch(),h=o?`git branch -D ${a}`:`git branch -d ${a}`,{stderr:r}=await utils.execChild(h);if(r)throw new Error(`Error deleting branch: ${r}`);this.utils.prompt.log.success(`Deleted branch: ${a}`)}}class GitCommit extends GitSuper{types=[{value:":sparkles: feat",title:"\u2728 feat",desc:"Adding a new feature"},{value:":bug: fix",title:"\u{1F41B} fix",desc:"Fixing a bug"},{value:":memo: docs",title:"\u{1F4DD} docs",desc:"Add or update documentation"},{value:":lipstick: style",title:"\u{1F484} style",desc:"Add or update styles, UI, or UX"},{value:":recycle: refactor",title:"\u267B\uFE0F refactor",desc:"Code change that neither fixes a bug nor adds a feature"},{value:":zap: perf",title:"\u26A1\uFE0F perf",desc:"Code change that improves performance"},{value:":white_check_mark: test",title:"\u2705 test",desc:"Adding test cases"},{value:":truck: chore",title:"\u{1F69A} chore",desc:"Changes to the build process or auxiliary tools and libraries (e.g., documentation generation)"},{value:":rewind: revert",title:"\u23EA\uFE0F revert",desc:"Revert to a previous commit"},{value:":construction: wip",title:"\u{1F6A7} wip",desc:"Work in progress"},{value:":construction_worker: build",title:"\u{1F477} build",desc:"Add or update related to build process"},{value:":green_heart: ci",title:"\u{1F49A} ci",desc:"Add or update related to CI process"}];scopes=[{value:"core",desc:"Core functionality of the application"},{value:"env",desc:"Reference for workspace environment"},{value:"all",desc:"Reference all changes affecting multiple scopes"}];async getStagedFiles(){const{stdout:s}=await utils.execChild("git status --short");return s.trim().split(` `).map(o=>o.trim()).join(` `)}async getStagedFilesList(){return(await this.getStagedFiles()).split(` `)}async getLastCommit(){const{stdout:s}=await utils.execChild("git log -1 --pretty=%B");return s.trim()}async isStageEmpty(){const{stdout:s}=await utils.execChild("git diff --cached");return s===""}async exec(s){const o=`git commit -m "${s}"`;console.log(this.utils.style.info.hr("git commit")),await utils.exec(o),console.log(this.utils.style.info.hr())}async ask(s=!0){const o=this.opts?.commit?.types||this.types,a=this.opts?.commit?.scopes||this.scopes,h={type:"type",scope:"scope",msg:"message"},r={[h.type]:void 0,[h.scope]:void 0,[h.msg]:""},g=await this.utils.cache("commit",r),b=await g.get(),m=await this.utils.promptGroup({onCancel:async()=>this.utils.onCancel(),list:async d=>{const S={[h.type]:async()=>{const v=o?await d.select({message:"Select type of commit",options:o.map(x=>({value:x.value,label:x.title||x.value,hint:x.desc})),initialValue:o.some(x=>x.value===b[h.type])?b[h.type]:void 0}):void 0;return await g.set({[h.type]:v}),v},[h.scope]:async()=>{const v=a?await d.select({message:"Select scope of commit",options:a.map(x=>({value:x.value,label:x.title||x.value,hint:x.desc})),initialValue:a.some(x=>x.value===b[h.scope])?b[h.scope]:void 0}):void 0;return await g.set({[h.scope]:v}),v},[h.msg]:async()=>{const v=await d.text({message:"Commit message",placeholder:await g.get(h.msg),validate:x=>{if(!x.trim())return"Commit message is required"}});return await g.set({[h.msg]:v}),v}};return{desc:()=>d.log.info(this.utils.style.p("Prompt for commit message")),...S,commit:async({results:v})=>{const x=v.message,R=v.scope,$=v.type,P=()=>{if(x)return!R&&!$?x:R?$?`${$}(${R}): ${x}`:`${R}: ${x}`:`${$}: ${x}`};try{const D=P();if(!D){console.warn("Unexpected: Commit message is not defined");return}return d.log.info(this.utils.style.info.msg("Total message",D)),s&&await this.exec(D),D}catch(D){D instanceof Error?d.log.error(D.message):console.error(D),await this.utils.onCancel()}}}}});return console.debug({"commit-results":m}),m.commit}async run(){if(await this.init(),!await this.isStageEmpty())return await this.ask();console.warn(`Nothing to commit. Stage your changes executing: ${this.utils.style.badge("dovenv git push")} Or stage your changes manually using ${this.utils.style.badge("git add")} and executing again: ${this.utils.style.badge("dovenv git commit")}`)}}class Husky extends GitSuper{async#t(s){const o=utils.joinPath(s,"_"),a=await utils.existsDir(o);if(console.debug({path:s,exist:a}),a)return!0;await this.init();const h=await u__default(s);if(h)throw new Error(h);return!1}async run(){const s=this.opts?.husky?.path??utils.joinPath(this.utils.wsDir,".dovenv/husky"),[o,a]=await utils.catchError((async()=>this.#t(s))());if(o)return console.log(this.utils.style.error.msg(o.message));console.log(a?this.utils.style.success.msg("Husky exists in:",s):this.utils.style.success.msg("Husky folder is now in",s)),console.log(this.utils.style.success.p(` Add now you Git hooks! More info: ${this.utils.style.a("https://typicode.github.io/husky")}`))}}class GitInit extends GitSuper{async isInit(){return await utils.existsDir(utils.joinPath(this.utils.wsDir,".git"))}async#t(){const s=this.utils.pkg?.extra.repoId||this.utils.pkg?.repoID||this.utils.pkg?.name,o=this.utils.pkg?.extra.collective.id,a=s&&o?`https://github.com/${o}/${s}.git`:this.utils.pkg?.reppsitory.url;if(!a)throw new Error("Invalid repository url: "+a);const h=await this.utils.prompt.text({message:"Write your origin git url",placeholder:a,initialValue:a});return this.utils.prompt.isCancel(h)&&await this.utils.onCancel(),h}async#s(){const s=await this.utils.prompt.confirm({message:"Do you want to execute the command?"});return this.utils.prompt.isCancel(s)&&await this.utils.onCancel(),s}async#e(){const s="main",o=await this.utils.prompt.text({message:"Write your init branch",placeholder:s,initialValue:s});return this.utils.prompt.isCancel(o)&&await this.utils.onCancel(),o}async run(s=!1){if(await this.isInit()){if(s)return;this.utils.prompt.log.success(this.utils.style.success.msg("Git is initialized \u2728")),this.utils.prompt.log.step("");return}this.utils.prompt.log.info(this.utils.style.p("Init your repository"));const o=new GitAdd({opts:this.opts,utils:this.utils}),a=new GitCommit({opts:this.opts,utils:this.utils}),h=await o.ask(),r=await a.ask(!1),g=await this.#e(),b=await this.#t(),m=`git init && git add ${h} && git commit -m "${r}" && git branch -M ${g} && git remote add origin ${b} && git push -u origin ${g}`;this.utils.prompt.note(`Command to be executed: ${m}`),await this.#s()?(console.log(this.utils.style.info.hr("git init")),await node_child_process.exec(m),console.log(this.utils.style.info.hr()),this.utils.prompt.log.success(this.utils.style.success.msg("Git is initialized \u2728"))):this.utils.prompt.log.success(this.utils.style.success.msg("Git init skipped from execution \u2728")),this.utils.prompt.log.step("")}}class GitPull extends GitSuper{async#t(s,o,a="main",h=!1){try{const r=await utils.execChild(`gh pr create --title "${s}" --body "${o}" --base ${a}${h?" --web":""}`);if(r.stderr&&r.stderr.trim()!=="")throw new Error(r.stderr);return this.utils.prompt.log.success(r.stdout),!0}catch(r){this.utils.prompt.log.step("");const g=r?.stderr||r?.message;return this.utils.prompt.cancel(`Error creating pull request: `+g),!1}}async run(){await this.init(),await this.initGH();const s=this.opts?.defaultBranch,o=new GitBranch({opts:this.opts,utils:this.utils}),a={title:"title",body:"body",base:"base",open:"open"},h={[a.title]:"",[a.body]:"",[a.base]:s,[a.open]:!1},r=await this.utils.cache("pull",h),g=await r.get();console.debug("cached data",g),await this.utils.promptGroup({outro:`Finished ${this.utils.style.badge("pull")} process \u{1F308}`,onCancel:async()=>this.utils.onCancel(),list:async b=>({desc:()=>b.log.info(this.utils.style.p("Create a pull request on GitHub.")),[a.title]:async()=>{const m=await b.text({message:"Title of pull request",placeholder:g[a.title],initialValue:g[a.title],validate:d=>{if(d.length===0)return"Body can not be empty."}});return await r.set({[a.title]:m}),m},[a.body]:async()=>{const m=await b.text({message:"Body of pull request",placeholder:g[a.body],initialValue:g[a.body],validate:d=>{if(d.length===0)return"Body can not be empty.";if(d.length>50)return"Body can not be longer than 50 characters."}});return await r.set({[a.body]:m}),m},[a.base]:async()=>{const m=await o.askSelectBranch(g[a.base]||s);return await r.set({[a.base]:m}),m},[a.open]:async()=>{const m=await b.confirm({message:"Open pull request in browser?",initialValue:g[a.open]});return await r.set({[a.open]:m}),m},run:async({results:m})=>{await this.#t(m[a.title],m[a.body],m[a.base],m[a.open])||this.utils.process.exit(0)}})})}}class GHSuper extends Repo{async getRepoList(s){const{archived:o,fork:a,visibility:h}=s||{},r=[];await this.init(),await this.initGH(),o===!0?r.push("--archived"):o===!1&&r.push("--no-archived"),a===!0?r.push("--fork"):a===!1&&r.push("--source"),h&&r.push(`--visibility ${h}`);const g=`gh repo list ${this.opts?.userID||""} --json url,name,owner,homepageUrl,description,repositoryTopics`,{stdout:b,stderr:m}=await utils.execChild(r.length?`${g} ${r.join(" ")}`:g);if(m)throw new Error(`Error getting repo list: ${m}`);return JSON.parse(b.trim()).map(d=>({desc:d.description?.trim()===""?void 0:d.description,homepage:d.homepageUrl?.trim()===""?void 0:d.homepageUrl,name:d.name,owner:d.owner.login,topics:d.repositoryTopics?.map(S=>S.name),url:d.url}))}}class GitHubWorkflow extends GHSuper{async list(){const{workflowsDir:s,URL:o}=this.opts||{};if(!s)return console.warn("No workflows dir provided. You need to provide a workflows dir");console.debug({workflowsDir:s});const a=await utils.getPaths([s+"/*.yml"],{onlyFiles:!0}),h=this.utils.style,r=utils.relativePath(this.utils.process.cwd(),s),g=h.info.b(r)+` `+(a&&a.length?await utils.getDirTree({input:s}):h.warn.p("No workflows found it!")).split(` `).map(b=>" "+b).join(` `)+` `+h.info.li("PATH:",r)+(o?` `+h.info.li("URL:",h.info.a(o)):"");console.log(utils.box(g,{padding:1,borderStyle:"none"}))}async run(){await this.init(),await this.initGH();const{workflowDefaultInputs:s,workflowsDir:o,URL:a}=this.opts||{};if(!(o&&await utils.existsDir(o))||!o){this.utils.prompt.log.warn(this.utils.style.warn.msg("Does not exist workflows directory:",o));return}const h=await utils.getFilteredFileNames({path:o,extensions:[".yml"]});if(!h.length){this.utils.prompt.log.warn(this.utils.style.warn.msg("No local workflows found in",o));return}const r={file:"file",inputs:"inputs"},g={[r.file]:h[0],[r.inputs]:s||""},b=await this.utils.cache("workflow",g),m=await b.get();await this.utils.promptGroup({onCancel:this.utils.onCancel,list:async d=>({desc:()=>d.log.info(this.utils.style.p("Prompt for run workflow")),[r.file]:async()=>d.select({message:"Select a workflow:",options:h.map(S=>({value:S,label:S})),initialValue:m[r.file]}),[r.inputs]:async()=>d.text({initialValue:m[r.inputs],message:`Set inputs for workflow in comma separed. ${this.utils.style.color.dim("(Leave empty to not use any input)")}`}),fn:async({results:S})=>{try{const v=S;let x="";if(v.inputs&&v.inputs.trim()!=="")try{x=v.inputs.split(",").map($=>$.trim()).map($=>{const[P,D]=$.split("=");return`-f ${P}=${D}`}).join(" ")}catch{x=""}if(await b.set({[r.file]:v.file,[r.inputs]:v.inputs||""}),(await utils.execChild(`gh workflow run ${v.file}.yml ${x}`)).stderr)throw Error("Error creating workflow");const R=await utils.execChild("echo $(gh run list --limit 1 --json databaseId,url --jq '.[0].url')");R.stdout&&R.stdout.trim()!==""&&d.log.info("GitHub action url: "+this.utils.style.p(R.stdout)),d.log.success(a?this.utils.style.success.msg("See action progress:",this.utils.style.a(utils.joinUrl(a,"actions"))):this.utils.style.success.msg("Succesfully finished \u{1F308}"))}catch(v){const x=v instanceof Error?v.message:v&&typeof v=="object"&&"stderr"in v?`${v.stderr}`:typeof v=="object"?JSON.stringify(v):`${v}`;d.log.error(this.utils.style.error.msg(`Workflow error `,x))}}})})}}const y=new utils.LazyLoader({sizium:()=>import("@sizium/core")});class Packages extends Repo{async#t(s){try{utils.deprecatedAlerts().hide(),await this.utils.execPkgBin("@changesets/cli",s)}catch(o){o instanceof Error&&await this.utils.onCancel()}}async init(){await this.#t(["init"])}async publish(s){return console.log(this.utils.style.info.hr("Publish packages")),s&&typeof s=="string"&&await utils.exec(s),await this.#t(["publish"])}async version(){return console.log(this.utils.style.info.hr("Update package version")),await this.#t(["version"])}async prepare(){return console.log(this.utils.style.info.hr("Prepare update")),await this.#t()}async getPkgVersion(s=!0,o=!0){const a=await this.utils.getPkgPaths();return(await Promise.all(a.map(async h=>{const r=await utils.getObjectFromFile(h),g=!!r.private&&r.private!=="false";if(g&&!o||!r.name||!r.version)return null;const[b,m]=s&&!g?await utils.catchError(utils.getPackageVersion(r.name)):[void 0,void 0];return{name:r.name,version:r.version,npm:m,private:g}}))).filter(h=>!!h)}async showPackageVersion(s=!0){const o=this.utils.prompt,a=o.spinner();try{a.start("Getting package(s) version info");const h=await this.getPkgVersion(s);a.stop("Getted pscakge(s) version info"),o.log.step(""),await o.box({value:`Your package version(s): ${h.map(r=>this.utils.style.section.li(r.name,`local: ${r.version}`+(s?` | npm: ${r.npm||"none"}`:"")+(r.private?" | private":""))).join(` `)} `,opts:{borderStyle:"none",padding:0}})}catch(h){h instanceof Error?o.log.error(h.message):o.log.error(h?h.toString():"Unknown error"),a.stop("Error getting package version")}}async ask(){const s={publish:"publish",run:"run",none:"none"},o={publishOrRun:"publish-or-run",prepare:"prepare",version:"version",command:"command"},a={[o.publishOrRun]:Object.values(s)[0],[o.prepare]:!0,[o.version]:!0,[o.command]:""},h=await this.utils.cache("pkg-ask",a),r=await h.get();return console.debug("cached data",r),await this.utils.promptGroup({onCancel:async()=>await this.utils.onCancel(),list:async g=>({prepare:async()=>{const b=await g.confirm({message:"Prepare new version(s)?",initialValue:r[o.prepare]});if(g.isCancel(b))return await this.utils.onCancel();if(await h.set({[o.prepare]:b}),!b)return b;await this.prepare(),console.log(this.utils.style.info.hr())},[o.version]:async()=>{const b=await g.confirm({message:"Update the version of the package(s) with the new prepared versions?",initialValue:r[o.version]});return g.isCancel(b)?await this.utils.onCancel():(await h.set({[o.version]:b}),b&&(await this.version(),console.log(this.utils.style.info.hr()),await this.showPackageVersion(!1),b))},publish:async({results:b})=>{let m=[];o.version in b&&m.push("Update the version of the package(s)"),m=[...m,"Build your package(s), if necessary","Run the tests to make sure everything works as expected"],await g.box({value:`Best practices before publishing: ${m.map(S=>this.utils.style.section.lk(S)).join(` `)} `,opts:{borderStyle:"none",padding:0}});const d=await g.select({message:"Publish the package now?",options:[{value:s.publish,label:"Publish package"},{value:s.run,label:"Run a command first"},{value:s.none,label:"Skip"}],initialValue:r[o.publishOrRun]});if(g.isCancel(d))return await this.utils.onCancel();if(await h.set({[o.publishOrRun]:d}),d===s.publish)await this.publish(),console.log(this.utils.style.info.hr());else if(d===s.run){const S=await g.text({message:"What command do you want to run?",initialValue:r[o.command]});if(g.isCancel(S))return await this.utils.onCancel();await h.set({[o.command]:S}),await this.publish(S),console.log(this.utils.style.info.hr())}else d!==s.none&&console.error(this.utils.style.error.msg("Unexpected error","No publish or run selected"))}})})}async release(){try{await this.prepare(),await this.version(),await this.publish()}catch(s){s instanceof Error?console.error("Release failed:",s.message):console.error("Release failed:",s)}}async getSizeData(s="./"){const{Sizium:o}=await y.get("sizium"),a=new o(s);return{data:await a.get(),inputType:a.inputType}}async getSize(s="./"){const o=await this.getSizeData(s),a=o.inputType,{packageNum:h,size:r,id:g,packages:b}=o.data,m=a!=="string",d=v=>`${(v/(1024*1024)).toFixed(2)}mb (${(v/1024).toFixed(2)}kb)`;let S=this.utils.style.table([["Name",this.utils.style.info.b(g)],["Packages Installed",this.utils.style.p(h)],["Local package",this.utils.style.p(m)],["",""],["Unpacked size",this.utils.style.p(d(b[0].unpackedSize))],["Total size",this.utils.style.success.p(d(r))],["",""]],{chars:{top:"","top-mid":"","top-left":"","top-right":"",bottom:"","bottom-mid":"","bottom-left":"","bottom-right":"",left:"","left-mid":"",mid:"","mid-mid":"",right:"","right-mid":"",middle:""}});return m||(S+=` `+this.utils.style.p(` View more details in ${this.utils.style.a(`https://sizium.pigeonposse.com/?s=${s}`)} `)),this.utils.prompt.log.message(S),o}}class GitPush extends GitSuper{async exec(s){const o=`git push -f origin ${s}`;console.log(this.utils.style.info.hr(o)),await utils.exec(o),console.log(this.utils.style.info.hr())}async run(s){await this.init();const o=this.opts?.defaultBranch,a={opts:this.opts,utils:this.utils},h=new GitBranch(a),r=new GitCommit(a),g=new GitAdd(a),b=new GitInit(a),m=new Packages(a);await b.run(!0);const d={staged:"staged",view:"view",update:"update",add:"add",origin:"origin",workflow:"workflow"},S={[d.staged]:!1,[d.view]:!0,[d.update]:!1,[d.add]:".",[d.origin]:o,[d.workflow]:!1},v=await this.utils.cache("push",S),x=await v.get();console.debug("cached data",x),await this.utils.promptGroup({outro:`Finished ${this.utils.style.badge("push")} process \u{1F308}`,onCancel:async()=>await this.utils.onCancel(),list:async R=>({desc:async()=>R.log.info(this.utils.style.p("Push your repository")),...s?.skipUpdate?{}:{[d.staged]:async()=>{const $=await R.confirm({message:"View staged files?",initialValue:x[d.staged]});if(R.isCancel($))return await this.utils.onCancel();if(await v.set({[d.staged]:$}),!$)return;const P=await r.getStagedFiles();return R.log.message(this.utils.style.p(P)),$},[d.view]:async()=>{const $=await R.confirm({message:"View package version(s)?",initialValue:x[d.view]});return R.isCancel($)?await this.utils.onCancel():(await v.set({[d.view]:$}),$&&await m.showPackageVersion(),$)},[d.update]:async()=>{const $=await R.confirm({message:"Update the version(s)?",initialValue:x[d.update]});return R.isCancel($)?await this.utils.onCancel():(await v.set({[d.update]:$}),$)},"update-res":async({results:$})=>{$[d.update]&&await m.ask()}},"desc-add":async()=>R.log.info(this.utils.style.p("Prompt for add to repository")),[d.add]:async()=>await g.ask(x[d.add]),[d.origin]:async()=>await h.askSelectBranch(x[d.origin]||o),"add-res":async({results:$})=>{const P=$,D={[d.add]:P[d.add],[d.origin]:P[d.origin]};if(await v.set(D),D[d.add]&&D[d.origin])try{console.log(),await g.exec(D[d.add]),await r.run(),await this.exec(D[d.origin]),console.log(),R.log.success(this.utils.style.success.h("Successfully pushed to")+" "+this.utils.style.success.p(`${this.utils.style.a(await this.getGitRemoteURL()||"[no repoURL provided]")} `))}catch(E){E instanceof Error&&R.log.error(E.message),await this.utils.onCancel()}},...s?.skipWorkflow?{}:{[d.workflow]:async()=>{const $=await R.confirm({message:"Run GitHub workflow?",initialValue:x[d.workflow]});return R.isCancel($)?await this.utils.onCancel():(await v.set({[d.workflow]:$}),$)},"workflow-res":async({results:$})=>{$[d.workflow]&&await new GitHubWorkflow({opts:this.opts,utils:this.utils}).run()}}})})}}class w extends Repo{add;branch;commit;husky;pull;push;initialize;constructor(s){super(s),this.add=new GitAdd(s),this.branch=new GitBranch(s),this.commit=new GitCommit(s),this.husky=new Husky(s),this.pull=new GitPull(s),this.push=new GitPush(s),this.initialize=new GitInit(s)}}const n={list:"list",current:"current",change:"change",create:"create",delete:"delete",switch:"switch",createSwitch:"create-switch"},i$1={add:"add",commit:"commit",branch:"branch",push:"push",pull:"pr",husky:"husky",init:"init"},C=k=>({custom:{git:{desc:"Git commands (add, commit, branch, pull, push...)",cmds:{[i$1.init]:{desc:"Initialize git project"},[i$1.add]:{desc:"Add files to git"},[i$1.commit]:{desc:"Commit configuration"},[i$1.branch]:{desc:"branch configuration",opts:{[n.list]:{desc:"List branches",type:"boolean"},[n.current]:{desc:"Show current branch",type:"boolean"},[n.change]:{desc:"Change branch",type:"string"},[n.create]:{desc:"Create branch",type:"string"},[n.delete]:{desc:"Delete branch",type:"string"},[n.switch]:{desc:"Switch branch",type:"string"},[n.createSwitch]:{desc:"Create and switch branch",type:"string"}}},[i$1.pull]:{desc:"Pull request configuration"},[i$1.push]:{desc:"Push your code to a branch",opts:{"skip-update":{desc:"Skip update",type:"boolean"},"skip-wf":{desc:"Skip workflow",type:"boolean"}}},[i$1.husky]:{desc:"Husky configuration"}},fn:async({cmds:s,utils:o,opts:a,showHelp:h})=>{const r=b=>Object.values(b).map(m=>utils.color.gray.dim.italic(m)).join(", "),g=new w({opts:k,utils:o});s?.includes(i$1.commit)?await g.commit.run():s?.includes(i$1.init)?await g.initialize.run():s?.includes(i$1.add)?await g.add.run():s?.includes(i$1.pull)?await g.pull.run():s?.includes(i$1.branch)?a?.list?await g.branch.showAll():a?.current?await g.branch.showCurrent():a?.change||a?.change===""?await g.branch.change(a.change):a?.create||a?.create===""?await g.branch.create(a.create):a?.delete||a?.delete===""?await g.branch.delete(a.delete):a?.switch||a?.switch===""?await g.branch.switch(a.switch):a?.[n.createSwitch]||a?.[n.createSwitch]===""?await g.branch.createAndSwitch(a.createAndSwitch):console.warn(`No option provided. Use: ${r(n)}`):s?.includes(i$1.push)?await g.push.run({skipUpdate:a?.["skip-update"],skipWorkflow:a?.skipWorkflow}):s?.includes(i$1.husky)?await g.husky.run():h()}}}});class GitHubCreate extends GHSuper{async run(){await this.init(),await this.initGH(),console.log(this.utils.style.info.hr("Publish packages")),await utils.exec("gh repo create")}}class GitHubInfo extends GHSuper{async viewAll(){const s=await this.getRepoList();s&&s.length>0?console.dir(s,{depth:1/0}):console.error("No data found")}async view(){const s=(await this.getRepoList()).filter(o=>o.name===this.opts?.ID)[0];s?console.dir(s,{depth:1/0}):console.error("No data found")}async update(){try{await this.init(),await this.initGH();const{URL:s,homepageURL:o,tags:a,desc:h}=this.opts||{};if(!s)return this.utils.prompt.log.warn(this.utils.style.warn.msg("No repo url provided","You need to provide a repo url"));const r=o?`--homepage "${o}"`:"",g=a?`--add-topic "${a}"`:"",b=h?`-d "${h}"`:"",m=[["homepage",o||"none"],["topics",a?.join(", ")||"none"],["description",h||"none"]];if(await this.utils.prompt.box({value:`Repo info to update: ${m.map(d=>this.utils.style.info.li(...d)).join(` `)} `,opts:{borderStyle:"none",padding:0},type:"info"}),r||g||b){const{stderr:d}=await utils.execChild(`gh repo edit "${s}" ${r} ${g} ${b}`);if(d)return this.utils.prompt.log.errorWithExit(this.utils.style.error.msg("Error updating repo info",d));this.utils.prompt.log.success(this.utils.style.success.h("Updated repo info in")+" "+this.utils.style.success.p(`${this.utils.style.a(s)}`))}else this.utils.prompt.log.errorWithExit(this.utils.style.error.msg("Nothing to update."));this.utils.prompt.log.step("")}catch(s){console.error("Unexpected error",s)}}}const i={DOWNLOAD:"download",WORKFLOW:"workflow",INFO:"info",CREATE:"create"},p={WORKFLOW:"wf"};class l{info;workflow;create;opts;utils;constructor({opts:s,utils:o}){this.opts=s,this.utils=o,this.info=new GitHubInfo({opts:s,utils:o}),this.workflow=new GitHubWorkflow({opts:s,utils:o}),this.create=new GitHubCreate({opts:s,utils:o})}async download(s,o){return await utils.downloadGitHubPath({input:s,output:o})}}const c$1=k=>({custom:{gh:{desc:"GitHub Repo commands and configuration",cmds:{[i.DOWNLOAD]:{desc:"Download a repository or a part of it",opts:{input:{type:"string",desc:"Repository or Repository path to download",alias:"i"},output:{type:"string",desc:"Output directory",alias:"o"}}},[i.CREATE]:{desc:"Create a new repo"},[i.WORKFLOW]:{desc:"Run or list a workflow",opts:{list:{desc:"List workflows",alias:"l"}}},[i.INFO]:{desc:"Repo information",cmds:{update:{desc:"Update repo info"},view:{desc:"View repo info",opts:{all:{desc:"Show repo info for all repositories"}}}}}},fn:async({cmds:s,opts:o,utils:a,showHelp:h})=>{const r=new l({opts:k,utils:a});s?.includes(i.DOWNLOAD)&&o?.input&&o?.output?await r.download(o.input,o.output):s?.includes(i.WORKFLOW)||s?.includes(p.WORKFLOW)?o?.list?await r.workflow.list():await r.workflow.run():s?.includes(i.CREATE)?await r.create.run():s?.includes(i.INFO)&&(s?.includes("update")||s?.includes("up"))?await r.info.update():s?.includes(i.INFO)&&s?.includes("view")?o?.all?await r.info.viewAll():await r.info.view():h()}}}}),e={release:"release",publish:"publish",init:"init",version:"version",prepare:"prepare",ask:"ask",showVersion:"show-version",size:"size"},c=k=>({custom:{pkg:{desc:"Packages commands: update, publish...",cmds:{[e.init]:{desc:"Init package(s)"},[e.ask]:{desc:"Ask for changes"},[e.prepare]:{desc:"Preprare version changelog"},[e.version]:{desc:"Update version of package(s)"},[e.publish]:{desc:"Publish package(s)"},[e.release]:{desc:"Update version and publish package(s)"},[e.showVersion]:{desc:"Show version of package(s). (Local and NPM)",opts:{local:{desc:"show Local version only",type:"boolean"}}},[e.size]:{desc:"Get package size of package. (Local and NPM)",opts:{input:{alias:"i",desc:"Local path package directory/file or npm package name",type:"string"}}}},fn:async({utils:s,cmds:o,showHelp:a,opts:h})=>{const r=new Packages({opts:k,utils:s});o?.includes(e.release)?await r.release():o?.includes(e.publish)?await r.publish():o?.includes(e.prepare)?await r.prepare():o?.includes(e.init)?await r.init():o?.includes(e.version)?await r.version():o?.includes(e.ask)?await r.ask():o?.includes(e.size)?await r.getSize(h?.input):o?.includes(e.showVersion)?await r.showPackageVersion(!h?.local):a()},examples:[{cmd:`$0 pkg ${e.release}`,desc:"Directly update version and publish packages"}]}}}),CONTRIBUTOR_ROLE={author:{name:"Author",emoji:"\u{1F451}",desc:"Author of the project."},developer:{name:"Developer",emoji:"\u{1F4BB}",desc:"Contributor for the development of the project. Code, docs, etc."},contributor:{name:"Contributor",emoji:"\u{1F4BB}",desc:"Contributor for the development of the project. Code, docs, etc."},mantainer:{name:"Mantainer",emoji:"\u{1F6A7}",desc:"Maintainer of the project. Code, docs, etc."},designer:{name:"Designer",emoji:"\u{1F484}",desc:"Contributor for the design of the project. Images, icons, etc."},organization:{name:"Organization",emoji:"\u{1F3E2}",desc:"Organization of the project."},sponsor:{name:"Sponsor",emoji:"\u{1F91D}",desc:"Sponsor of the project."},translator:{name:"Translator",emoji:"\u{1F30F}",desc:"Translator for the project."}},f=k=>{if(k.includes("github.com")){const s=k.match(/github\.com\/([^/]+)/);return s?s[1]:"unknown"}return k.split("@")[0]||"unknown"},package2Contributors=(k,s)=>{if(!k)throw new Error("No package provided");const o=s?.member||[],a={author:CONTRIBUTOR_ROLE.author,contributor:CONTRIBUTOR_ROLE.contributor,mantainer:CONTRIBUTOR_ROLE.mantainer,...s?.role||{}},h={contributors:k.contributors||[],author:k.author?[k.author]:[],maintainers:k.maintainers||[]};for(const[r,g]of Object.entries(h))for(const b of g)if(typeof b=="string")o.push({role:r,ghUsername:b,name:b});else{const{name:m,url:d,email:S}=b,v=f(d||S||"");o.push({role:r,ghUsername:v,name:m||v,url:d})}return o.length?{role:a,member:o}:void 0};class Contributors{opts;utils;constructor(s){this.utils=s?.utils,!s?.opts||!s?.opts.role||!s?.opts.member?this.utils?.pkg&&(this.opts=package2Contributors(this.utils.pkg)):this.opts=s?.opts}async filterByRole(s){if(!this.opts?.member||!this.opts?.role)throw new Error("Missing role or member");return s.length?{role:Object.fromEntries(Object.entries(this.opts.role).filter(([o])=>s.includes(o))),member:this.opts.member.filter(o=>s.includes(o.role))}:void 0}async filterByRolePattern(s){if(!this.opts?.role)throw new Error("Missing role");const o=utils.getMatch(Object.keys(this.opts.role),s);return await this.filterByRole(o)}async getMarkdownContent(s){const o=s?.role||this.opts?.role,a=s?.member||this.opts?.member;if(!a||!o)throw new Error("Missing role or member");const h=s?.content?.name??!0,r=s?.content?.image??!0,g=s?.role!==void 0?s.role:!0,b=[],m=[];r&&(b.push(" "),m.push("-----")),h&&(b.push("Name"),m.push("----")),g&&(b.push("Role"),m.push("----"));const d=`| ${b.join(" | ")} |`,S=`| ${m.join(" | ")} |`,v=a.map(x=>{const R=x.url||`https://github.com/${x.ghUsername}`,$=x.avatar||`https://github.com/${x.ghUsername}.png?size=72`,P=o[x.role],D=[];if(r&&D.push(`![${x.name}](${$})`),h&&D.push(`[${x.name}](${R})`),g){const E=`${P?.emoji??""} ${P?.name??""}`.trim();D.push(E)}return`| ${D.join(" | ")} |`});return["## Contributors","",d,S,...v].join(` `).trim()}async getHtmlContent(s){return utils.md2html(await this.getMarkdownContent(s))}async getTerminalContent(s){return await utils.md2terminal(await this.getMarkdownContent(s))}async showTerminalOutput(s){console.log(await this.getTerminalContent(s))}}const contributorsPlugin=k=>({const:k?{contributors:k}:void 0,custom:{contributors:{desc:"Toolkit for workspace contributors",cmds:{list:{desc:"List workspace contributors",opts:{role:{type:"array",desc:"Contributor role pattern"}}}},fn:async({cmds:s,showHelp:o,opts:a,utils:h})=>{const r=new Contributors({opts:k,utils:h});if(s?.includes("list"))if(a?.role){const g=await r.filterByRolePattern(a.role);await r.showTerminalOutput({...g,content:{image:!1}})}else await r.showTerminalOutput({content:{image:!1}});else o()}}}}),t=k=>{const{contributors:s,...o}=k||{};return core.defineConfig([contributorsPlugin(s),c$1(o),C(o),c(o)])};exports.CONTRIBUTOR_ROLE=CONTRIBUTOR_ROLE,exports.Contributors=Contributors,exports.Git=w,exports.GitAdd=GitAdd,exports.GitBranch=GitBranch,exports.GitCommit=GitCommit,exports.GitHub=l,exports.GitHubInfo=GitHubInfo,exports.GitHubWorkflow=GitHubWorkflow,exports.GitInit=GitInit,exports.GitPull=GitPull,exports.GitPush=GitPush,exports.Husky=Husky,exports.Packages=Packages,exports.contributorsPlugin=contributorsPlugin,exports.default=t,exports.ghPlugin=c$1,exports.gitPlugin=C,exports.package2Contributors=package2Contributors,exports.pkgPlugin=c,exports.repoPlugin=t;