@r5n/sisyphus 0.8.1 → 0.8.2
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/README.md
CHANGED
package/dist/cli.js
CHANGED
|
@@ -87,7 +87,7 @@ ${a}
|
|
|
87
87
|
`).trimEnd()}command(e,t){let n=[],r=t??this.metadata.bin,i=`${r} ${e.name}`,s=`${w.cmd(r)} ${w.cmd(e.name)}`;n.push(w.name(i)),n.push(w.desc(e.description)),n.push(""),n.push(w.header("Usage:"));let o=this.formatPositionalUsage(e.positionals);if(e.hasSubcommands())n.push(` ${s} ${w.placeholder("<subcommand>")} ${w.placeholder("[options]")}`);else{let p=[s];if(o)p.push(o);p.push(w.placeholder("[options]")),n.push(` ${p.join(" ")}`)}if(e.prompts&&Object.keys(e.positionals).length>0)n.push(` ${w.hint("Omit positional arguments to run interactively.")}`);if(n.push(""),e.hasSubcommands()){n.push(w.header("Subcommands:"));let p=e.getSubcommands().map((u)=>[` ${w.cmd(u.name)}`,w.desc(u.description)]);n.push(...this.formatColumns(p)),n.push("")}if(Object.entries(e.positionals).length>0)n.push(w.header("Arguments:")),n.push(...this.formatPositionalDefs(e.positionals)),n.push("");if(Object.entries(e.args).length>0)n.push(w.header("Options:")),n.push(...this.formatArgDefs(e.args));return n.join(`
|
|
88
88
|
`).trimEnd()}formatPositionalUsage(e){return Object.entries(e).map(([t,n])=>{let r=n.variadic?`${t}...`:t;return n.required?w.arg(`<${r}>`):w.arg(`[${r}]`)}).join(" ")}formatPositionalDefs(e){let t=Object.entries(e).map(([n,r])=>{let i=r.variadic?`${n}...`:n,s=w.desc(r.description??""),o=r.required?"":w.hint(" (optional)");return[` ${w.arg(i)}`,`${s}${o}`]});return this.formatColumns(t)}formatArgDefs(e){let t=[];for(let[n,r]of Object.entries(e)){let i=r.alias?`${w.flag(`-${r.alias}`)}, `:" ",s=r.type==="boolean"?"":` ${w.placeholder(`<${r.type==="number"?"number":"value"}>`)}`,o=`${i}${w.flag(`--${Ht(n)}`)}${s}`,a=w.desc(r.description??""),g=this.formatDefault(r),p=g===void 0?"":` (default: ${w.default(g)})`;t.push([` ${o}`,`${a}${p}`])}return this.formatColumns(t)}formatDefault(e){if(typeof e.displayDefault==="string")return e.displayDefault;if(e.default===void 0)return;if(e.type==="boolean"&&e.default===!1)return;if(e.type==="string")return`"${e.default}"`;return String(e.default)}formatColumns(e){if(e.length===0)return[];let t=Math.max(...e.map(([r])=>this.stripAnsi(r).length)),n=2;return e.map(([r,i])=>{let s=t-this.stripAnsi(r).length+n;return`${r}${" ".repeat(s)}${i}`})}stripAnsi(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}}var ge=new Uint32Array(65536),ds=(e,t)=>{let n=e.length,r=t.length,i=1<<n-1,s=-1,o=0,a=n,g=n;while(g--)ge[e.charCodeAt(g)]|=1<<g;for(g=0;g<r;g++){let p=ge[t.charCodeAt(g)],u=p|o;if(p|=(p&s)+s^s,o|=~(p|s),s&=p,o&i)a++;if(s&i)a--;o=o<<1|1,s=s<<1|~(u|o),o&=u}g=n;while(g--)ge[e.charCodeAt(g)]=0;return a},ys=(e,t)=>{let n=t.length,r=e.length,i=[],s=[],o=Math.ceil(n/32),a=Math.ceil(r/32);for(let h=0;h<o;h++)s[h]=-1,i[h]=0;let g=0;for(;g<a-1;g++){let h=0,P=-1,j=g*32,x=Math.min(32,r)+j;for(let k=j;k<x;k++)ge[e.charCodeAt(k)]|=1<<k;for(let k=0;k<n;k++){let H=ge[t.charCodeAt(k)],L=s[k/32|0]>>>k&1,C=i[k/32|0]>>>k&1,G=H|h,O=((H|C)&P)+P^P|H|C,E=h|~(O|P),U=P&O;if(E>>>31^L)s[k/32|0]^=1<<k;if(U>>>31^C)i[k/32|0]^=1<<k;E=E<<1|L,U=U<<1|C,P=U|~(G|E),h=E&G}for(let k=j;k<x;k++)ge[e.charCodeAt(k)]=0}let p=0,u=-1,d=g*32,y=Math.min(32,r-d)+d;for(let h=d;h<y;h++)ge[e.charCodeAt(h)]|=1<<h;let b=r;for(let h=0;h<n;h++){let P=ge[t.charCodeAt(h)],j=s[h/32|0]>>>h&1,x=i[h/32|0]>>>h&1,k=P|p,H=((P|x)&u)+u^u|P|x,L=p|~(H|u),C=u&H;if(b+=L>>>r-1&1,b-=C>>>r-1&1,L>>>31^j)s[h/32|0]^=1<<h;if(C>>>31^x)i[h/32|0]^=1<<h;L=L<<1|j,C=C<<1|x,u=C|~(k|L),p=L&k}for(let h=d;h<y;h++)ge[e.charCodeAt(h)]=0;return b},bs=(e,t)=>{if(e.length<t.length){let n=t;t=e,e=n}if(t.length===0)return e.length;if(e.length<=32)return ds(e,t);return ys(e,t)},br=(e,t)=>{let n=1/0,r=0;for(let i=0;i<t.length;i++){let s=bs(e,t[i]);if(s<n)n=s,r=i}return t[r]};function pt(e,t,n,r){let i=br(t,n);if(console.error(c.red(`Unknown ${e}: ${t}`)),i)console.error(c.yellow(`Did you mean "${i}"?`));console.error(`
|
|
89
89
|
Run "${r} --help" for usage.`),process.exit(1)}function be(e,t){let n=(i)=>i&&typeof i==="object";if(!n(e)||!n(t))return t;let r={...e};for(let i of Object.keys(t)){let s=r[i],o=t[i];if(Array.isArray(s)&&Array.isArray(o))r[i]=[...o];else if(n(s)&&n(o))r[i]=be(s,o);else r[i]=o}return r}var zt="__exit__";class Re{command;env;prefix;options;constructor(e,t,n,r={}){this.command=e;this.env=t;this.prefix=n;this.options=r}get commandPath(){return this.prefix?`${this.prefix} ${this.command.name}`:this.command.name}async route(e,t){if(t)await this.routeInteractive();else await this.routeDirect(e)}async routeDirect(e){let[t,...n]=e;if(t&&this.command.hasSubcommands()){let r=this.command.getSubcommand(t);if(r){await this.handleSubcommandRoute(r,n);return}if(!t.startsWith("-")){this.handleUnknownSubcommand(t);return}}await this.executeCommand(e)}handleUnknownSubcommand(e){let t=this.command.getSubcommands().map((n)=>n.name);pt("subcommand",e,t,this.commandPath)}async handleSubcommandRoute(e,t){await new Re(e,this.env,this.commandPath).route(t,!1)}async executeCommand(e){if(this.isHelpRequest(e)){this.printHelp(this.command);return}if(this.command.hasSubcommands()&&!this.command.execute){this.printHelp(this.command);return}if(!this.command.execute)return;let{args:n,rawPositionals:r}=Wt(e,this.command.args),i=Vt(r,this.command.positionals),s=yr(i,this.command.positionals);if(s)l.error(s),console.error(`
|
|
90
|
-
Run "${this.commandPath} --help" for usage.`),process.exit(1);let o=this.command.prompts&&r.length===0,a=this.buildContext(i,n,o);await this.command.execute(a)}async routeInteractive(){if(!this.command.hasSubcommands()){await this.executeInteractive();return}await this.runSubcommandMenu()}async executeInteractive(){let{args:e}=Wt([],this.command.args),t=Vt([],this.command.positionals),n=this.buildContext(t,e,!0);await this.command.execute?.(n)}async runSubcommandMenu(){while(!0){let e=await this.promptSubcommandSelectionOrBack();if(e===null)return;if(e===zt){this.options.onExit?.();return}let t=this.command.getSubcommand(e);if(t)await this.executeSubcommand(t)}}async promptSubcommandSelectionOrBack(){try{return await this.promptSubcommandSelection()}catch(e){if(e instanceof te){if(this.options.isRoot)this.options.onExit?.();return null}throw e}}async executeSubcommand(e){try{await new Re(e,this.env,this.commandPath).route([],!0)}catch(t){if(t instanceof te)return;if(t instanceof f){if(l.warn(c.yellow(t.message)),t.hint)l.info(c.dim(t.hint));return}throw t}}promptSubcommandSelection(){let{isRoot:e}=this.options,t=e?{hint:this.env.cli.exitHint,label:this.env.cli.exitLabel??"Exit",value:zt}:{hint:"Return to previous menu",label:"Back",value:zt};return ye({message:e?this.env.cli.promptMessage??"Select:":`${this.command.name}:`,options:[...this.command.getSubcommands().map((n)=>({hint:n.description,label:n.name,value:n.name})),t]})}buildContext(e,t,n){return{...this.env,args:t,interactive:n,positionals:e}}isHelpRequest(e){return e.includes("--help")||e.includes("-h")}printHelp(e){let t=e===this.command?this.prefix:this.commandPath;console.log(this.env.formatHelp(e,t))}}var Ps={clearOnStart:!0,exitHint:"Close the CLI",exitLabel:"Exit",goodbyeMessage:"Goodbye!",name:"CLI",promptMessage:"What would you like to do?"};class Kt{commands=new Map;metadata;configManager;help;bin;globalArgs={help:{alias:"h",description:"Show help",type:"boolean"},interactive:{alias:"i",description:"Open interactive mode",type:"boolean"},version:{alias:"v",description:"Show version",type:"boolean"}};constructor(e,t){this.configManager=e,this.metadata={...Ps,...t},this.bin=this.metadata.bin??this.metadata.name,this.init(),this.help=new Jt({bin:this.bin,description:this.metadata.description,name:this.metadata.name,version:this.metadata.version},this.commands,this.globalArgs)}registerCommands(e){for(let t of e)t.init?.(),this.commands.set(t.name,t)}async run(e=process.argv.slice(2)){let{command:t,flags:n,restArgs:r}=dr(e,this.globalArgs);if(n.version&&!t)return console.log(this.help.version());if(n.interactive&&!t)return this.runInteractive();if(!t)return console.log(this.help.global());if(t==="help")return this.printHelpFor(r[0]);await this.runDirect(t,r,!!n.help)}printHelpFor(e){if(!e)return console.log(this.help.global());let t=this.commands.get(e);if(!t)return this.handleUnknownCommand(e);console.log(this.help.command(t))}async runInteractive(){this.showIntro();let e=this.createVirtualRootCommand(),t={cli:this.metadata,config:this.configManager,formatHelp:this.help.command.bind(this.help)},n=new Re(e,t,this.bin,{isRoot:!0,onExit:()=>this.exit()});try{await n.route([],!0)}catch(r){this.handleError(r)}}createVirtualRootCommand(){return{description:this.metadata.description,getSubcommand:(e)=>this.commands.get(e),getSubcommands:()=>Array.from(this.commands.values()),hasSubcommands:()=>!0,name:this.metadata.name}}exit(){it(this.metadata.goodbyeMessage),process.exit(0)}async runDirect(e,t,n){let r=this.commands.get(e);if(!r)return this.handleUnknownCommand(e);let i=t.length>0&&!t[0]?.startsWith("-");if(n&&!i)return console.log(this.help.command(r));try{let s={cli:this.metadata,config:this.configManager,formatHelp:this.help.command.bind(this.help)};await new Re(r,s,this.bin).route(t,!1)}catch(s){this.handleError(s)}}showIntro(){if(this.metadata.clearOnStart)console.clear();let e=this.metadata.version?` v${this.metadata.version}`:"";rt(`${c.bgCyan(c.black(` ${this.metadata.name}${e} `))}`)}handleUnknownCommand(e){let t=Array.from(this.commands.keys());pt("command",e,t,this.bin)}handleError(e){if(this.metadata.onError?.(e))return;if(e instanceof te)process.exit(0);if(e instanceof f){if(l.warn(c.yellow(e.message)),e.hint)l.info(c.dim(e.hint));process.exit(0)}if(e instanceof Error)l.error(c.red(e.message)),process.exit(1);console.error(c.red("Error:"),e),process.exit(1)}}class Ue{args={};positionals={};prompts=!1;subcommands=new Map;registerSubcommands(e){for(let t of e)t.init?.(),this.subcommands.set(t.name,t)}hasSubcommands(){return this.subcommands.size>0}getSubcommand(e){return this.subcommands.get(e)}getSubcommands(){return Array.from(this.subcommands.values())}}function F(e){return e}function Q(e){return e}import Se from"fs";import Pr from"path";class Yt{config;configPath;defaultConfig;constructor(e,t){this.configPath=Pr.resolve(e),this.defaultConfig=t,this.config=this.loadConfig()}get(e){return this.config[e]}set(e,t){this.config[e]=t,this.save()}delete(e){delete this.config[e],this.save()}exists(){return Se.existsSync(this.configPath)}getAll(){return be({},this.config)}save(e){if(e)this.config={...e};this.ensureDirectoryExists();try{Se.writeFileSync(this.configPath,JSON.stringify(this.config,null,2))}catch(t){console.error(`Failed to save config to ${this.configPath}:`,t)}}ensureDirectoryExists(){let e=Pr.dirname(this.configPath);if(!Se.existsSync(e))try{Se.mkdirSync(e,{recursive:!0})}catch(t){console.error(`Failed to create config directory at ${e}:`,t)}}loadConfig(){if(!Se.existsSync(this.configPath))return{...this.defaultConfig};try{let e=Se.readFileSync(this.configPath,"utf-8"),t=JSON.parse(e);return be({...this.defaultConfig},t)}catch{return console.warn(`Config file corrupted at ${this.configPath}. Using defaults.`),{...this.defaultConfig}}}}var wr="0.8.1";class I extends Ue{}import{existsSync as Ls}from"fs";import{mkdir as Os,writeFile as As}from"fs/promises";import{dirname as Ns}from"path";class fe{owner;repo;constructor(e){this.owner=e.owner,this.repo=e.repo}}class mt extends fe{name="bitbucket";notImplemented(){throw new f("Bitbucket is not supported yet","Bitbucket support is coming soon")}async ensureAvailable(){this.notImplemented()}async getDefaultBranch(){this.notImplemented()}async findPr(e){this.notImplemented()}async createPr(e){this.notImplemented()}async updatePr(e,t){this.notImplemented()}async getPr(e){this.notImplemented()}async getPrFromCurrentBranch(){this.notImplemented()}async getPrCommits(e){this.notImplemented()}async getPrFiles(e){this.notImplemented()}async ensureLabelExists(e,t){this.notImplemented()}async createRelease(e){this.notImplemented()}async deleteRelease(e){this.notImplemented()}}var A="sis",Tt="\uD83E\uDEA8",de="other",Me={build:23,chore:25,ci:24,docs:20,feat:10,"feat!":0,fix:11,"fix!":1,perf:12,refactor:13,style:21,test:22,["other"]:100},Ie=50,lt=".sisyphus",vr="stones",kr="released",ut=7,Cr="unknown",Ge="unknown",$r="0.0.0",Rr="latest",pe="main",Sr=4,Mr=8,Ir="config.json";var De={$schema:"https://raw.githubusercontent.com/r5n-labs/clis/refs/heads/develop/packages/sisyphus/schema.json",changelog:{append:!0,filename:"CHANGELOG.md",generate:!0,packageHeader:"{emoji} {version} ({date})",root:!1,rootHeader:"{date} - {packages}",sections:{breaking:"Breaking changes",build:"Build",chore:"Chores",ci:"CI",dependencies:"Dependency updates",docs:"Documentation",feat:"Features",fix:"Bug fixes",other:"Other changes",perf:"Performance",refactor:"Refactoring",style:"Styling",test:"Tests"}},commit:{author:"r5n-bot",message:"chore(release): {message}"},commits:{skip:{authors:["r5n-bot[bot]"],messagePatterns:["^chore\\(release\\):","^chore: add stone"]}},ignore:[],lastStone:{commit:"",date:""},plugins:[],pr:{labelMapping:{breaking:"major","breaking-change":"major",bug:"patch",chore:"patch",docs:"patch",enhancement:"minor",feature:"minor",fix:"patch"},skip:{authors:["r5n-bot[bot]"],labels:["sisyphus-release","skip-stone"],titlePatterns:["^chore\\(release\\):"]}},release:{createRelease:!1,npm:!1,push:!1,tags:!1},scripts:{post:{},pre:{}},single:!1,sisyphusDir:".sisyphus",stones:[],tag:"latest"};class ht extends fe{name="github";get apiPath(){return`repos/${encodeURIComponent(this.owner)}/${encodeURIComponent(this.repo)}`}async ensureAvailable(){try{await Bun.$`which gh`.quiet()}catch{throw new f("GitHub CLI (gh) is not installed","Install from https://cli.github.com and run: gh auth login")}try{await Bun.$`gh auth status`.quiet()}catch{throw new f("GitHub CLI (gh) is not authenticated","Run: gh auth login")}}async getDefaultBranch(){try{return(await Bun.$`gh repo view --json defaultBranchRef --jq .defaultBranchRef.name`.quiet()).stdout.toString().trim()||pe}catch{return pe}}async findPr(e){try{let t=[];if(e.head)t.push("--head",e.head);if(e.label)t.push("--label",e.label);let n=await Bun.$`gh pr list --json number,url,title,body,labels,author,headRefName,baseRefName,mergeCommit,state --limit 1 ${t}`.quiet(),r=JSON.parse(n.stdout.toString());if(!r[0])return null;return this.mapPrResponse(r[0])}catch{return null}}async createPr(e){let t=await Bun.$`gh api ${this.apiPath}/pulls --method POST -f head=${e.head} -f base=${e.base} -f title=${e.title} -f body=${e.body}`,r=JSON.parse(t.stdout.toString()).number;if(e.labels&&e.labels.length>0){let i=e.labels.flatMap((s)=>["-f",`labels[]=${s}`]);await Bun.$`gh api ${this.apiPath}/issues/${r}/labels --method POST ${i}`}return this.getPr(r)}async updatePr(e,t){let n=[];if(t.title)n.push("--title",t.title);if(t.body)n.push("--body",t.body);await Bun.$`gh pr edit ${e} ${n}`}async getPr(e){try{let t=await Bun.$`gh api ${this.apiPath}/pulls/${e}`.quiet(),n=JSON.parse(t.stdout.toString());return this.mapRestApiResponse(n)}catch{throw new f(`Failed to fetch PR #${e}`,"Make sure the PR exists and you have access")}}async getPrFromCurrentBranch(){try{let e=await Bun.$`gh pr view --json number,title,body,labels,author,headRefName,baseRefName,url,mergeCommit,state`.quiet(),t=JSON.parse(e.stdout.toString());return this.mapPrResponse(t)}catch{throw new f("No PR found for current branch","Make sure you have an open PR or provide a URL with --url")}}async getPrCommits(e){try{return(await Bun.$`gh api ${this.apiPath}/pulls/${e}/commits --jq '.[].sha'`.quiet()).stdout.toString().trim().split(`
|
|
90
|
+
Run "${this.commandPath} --help" for usage.`),process.exit(1);let o=this.command.prompts&&r.length===0,a=this.buildContext(i,n,o);await this.command.execute(a)}async routeInteractive(){if(!this.command.hasSubcommands()){await this.executeInteractive();return}await this.runSubcommandMenu()}async executeInteractive(){let{args:e}=Wt([],this.command.args),t=Vt([],this.command.positionals),n=this.buildContext(t,e,!0);await this.command.execute?.(n)}async runSubcommandMenu(){while(!0){let e=await this.promptSubcommandSelectionOrBack();if(e===null)return;if(e===zt){this.options.onExit?.();return}let t=this.command.getSubcommand(e);if(t)await this.executeSubcommand(t)}}async promptSubcommandSelectionOrBack(){try{return await this.promptSubcommandSelection()}catch(e){if(e instanceof te){if(this.options.isRoot)this.options.onExit?.();return null}throw e}}async executeSubcommand(e){try{await new Re(e,this.env,this.commandPath).route([],!0)}catch(t){if(t instanceof te)return;if(t instanceof f){if(l.warn(c.yellow(t.message)),t.hint)l.info(c.dim(t.hint));return}throw t}}promptSubcommandSelection(){let{isRoot:e}=this.options,t=e?{hint:this.env.cli.exitHint,label:this.env.cli.exitLabel??"Exit",value:zt}:{hint:"Return to previous menu",label:"Back",value:zt};return ye({message:e?this.env.cli.promptMessage??"Select:":`${this.command.name}:`,options:[...this.command.getSubcommands().map((n)=>({hint:n.description,label:n.name,value:n.name})),t]})}buildContext(e,t,n){return{...this.env,args:t,interactive:n,positionals:e}}isHelpRequest(e){return e.includes("--help")||e.includes("-h")}printHelp(e){let t=e===this.command?this.prefix:this.commandPath;console.log(this.env.formatHelp(e,t))}}var Ps={clearOnStart:!0,exitHint:"Close the CLI",exitLabel:"Exit",goodbyeMessage:"Goodbye!",name:"CLI",promptMessage:"What would you like to do?"};class Kt{commands=new Map;metadata;configManager;help;bin;globalArgs={help:{alias:"h",description:"Show help",type:"boolean"},interactive:{alias:"i",description:"Open interactive mode",type:"boolean"},version:{alias:"v",description:"Show version",type:"boolean"}};constructor(e,t){this.configManager=e,this.metadata={...Ps,...t},this.bin=this.metadata.bin??this.metadata.name,this.init(),this.help=new Jt({bin:this.bin,description:this.metadata.description,name:this.metadata.name,version:this.metadata.version},this.commands,this.globalArgs)}registerCommands(e){for(let t of e)t.init?.(),this.commands.set(t.name,t)}async run(e=process.argv.slice(2)){let{command:t,flags:n,restArgs:r}=dr(e,this.globalArgs);if(n.version&&!t)return console.log(this.help.version());if(n.interactive&&!t)return this.runInteractive();if(!t)return console.log(this.help.global());if(t==="help")return this.printHelpFor(r[0]);await this.runDirect(t,r,!!n.help)}printHelpFor(e){if(!e)return console.log(this.help.global());let t=this.commands.get(e);if(!t)return this.handleUnknownCommand(e);console.log(this.help.command(t))}async runInteractive(){this.showIntro();let e=this.createVirtualRootCommand(),t={cli:this.metadata,config:this.configManager,formatHelp:this.help.command.bind(this.help)},n=new Re(e,t,this.bin,{isRoot:!0,onExit:()=>this.exit()});try{await n.route([],!0)}catch(r){this.handleError(r)}}createVirtualRootCommand(){return{description:this.metadata.description,getSubcommand:(e)=>this.commands.get(e),getSubcommands:()=>Array.from(this.commands.values()),hasSubcommands:()=>!0,name:this.metadata.name}}exit(){it(this.metadata.goodbyeMessage),process.exit(0)}async runDirect(e,t,n){let r=this.commands.get(e);if(!r)return this.handleUnknownCommand(e);let i=t.length>0&&!t[0]?.startsWith("-");if(n&&!i)return console.log(this.help.command(r));try{let s={cli:this.metadata,config:this.configManager,formatHelp:this.help.command.bind(this.help)};await new Re(r,s,this.bin).route(t,!1)}catch(s){this.handleError(s)}}showIntro(){if(this.metadata.clearOnStart)console.clear();let e=this.metadata.version?` v${this.metadata.version}`:"";rt(`${c.bgCyan(c.black(` ${this.metadata.name}${e} `))}`)}handleUnknownCommand(e){let t=Array.from(this.commands.keys());pt("command",e,t,this.bin)}handleError(e){if(this.metadata.onError?.(e))return;if(e instanceof te)process.exit(0);if(e instanceof f){if(l.warn(c.yellow(e.message)),e.hint)l.info(c.dim(e.hint));process.exit(0)}if(e instanceof Error)l.error(c.red(e.message)),process.exit(1);console.error(c.red("Error:"),e),process.exit(1)}}class Ue{args={};positionals={};prompts=!1;subcommands=new Map;registerSubcommands(e){for(let t of e)t.init?.(),this.subcommands.set(t.name,t)}hasSubcommands(){return this.subcommands.size>0}getSubcommand(e){return this.subcommands.get(e)}getSubcommands(){return Array.from(this.subcommands.values())}}function F(e){return e}function Q(e){return e}import Se from"fs";import Pr from"path";class Yt{config;configPath;defaultConfig;constructor(e,t){this.configPath=Pr.resolve(e),this.defaultConfig=t,this.config=this.loadConfig()}get(e){return this.config[e]}set(e,t){this.config[e]=t,this.save()}delete(e){delete this.config[e],this.save()}exists(){return Se.existsSync(this.configPath)}getAll(){return be({},this.config)}save(e){if(e)this.config={...e};this.ensureDirectoryExists();try{Se.writeFileSync(this.configPath,JSON.stringify(this.config,null,2))}catch(t){console.error(`Failed to save config to ${this.configPath}:`,t)}}ensureDirectoryExists(){let e=Pr.dirname(this.configPath);if(!Se.existsSync(e))try{Se.mkdirSync(e,{recursive:!0})}catch(t){console.error(`Failed to create config directory at ${e}:`,t)}}loadConfig(){if(!Se.existsSync(this.configPath))return{...this.defaultConfig};try{let e=Se.readFileSync(this.configPath,"utf-8"),t=JSON.parse(e);return be({...this.defaultConfig},t)}catch{return console.warn(`Config file corrupted at ${this.configPath}. Using defaults.`),{...this.defaultConfig}}}}var wr="0.8.2";class I extends Ue{}import{existsSync as Ls}from"fs";import{mkdir as Os,writeFile as As}from"fs/promises";import{dirname as Ns}from"path";class fe{owner;repo;constructor(e){this.owner=e.owner,this.repo=e.repo}}class mt extends fe{name="bitbucket";notImplemented(){throw new f("Bitbucket is not supported yet","Bitbucket support is coming soon")}async ensureAvailable(){this.notImplemented()}async getDefaultBranch(){this.notImplemented()}async findPr(e){this.notImplemented()}async createPr(e){this.notImplemented()}async updatePr(e,t){this.notImplemented()}async getPr(e){this.notImplemented()}async getPrFromCurrentBranch(){this.notImplemented()}async getPrCommits(e){this.notImplemented()}async getPrFiles(e){this.notImplemented()}async ensureLabelExists(e,t){this.notImplemented()}async createRelease(e){this.notImplemented()}async deleteRelease(e){this.notImplemented()}}var A="sis",Tt="\uD83E\uDEA8",de="other",Me={build:23,chore:25,ci:24,docs:20,feat:10,"feat!":0,fix:11,"fix!":1,perf:12,refactor:13,style:21,test:22,["other"]:100},Ie=50,lt=".sisyphus",vr="stones",kr="released",ut=7,Cr="unknown",Ge="unknown",$r="0.0.0",Rr="latest",pe="main",Sr=4,Mr=8,Ir="config.json";var De={$schema:"https://raw.githubusercontent.com/r5n-labs/clis/refs/heads/develop/packages/sisyphus/schema.json",changelog:{append:!0,filename:"CHANGELOG.md",generate:!0,packageHeader:"{emoji} {version} ({date})",root:!1,rootHeader:"{date} - {packages}",sections:{breaking:"Breaking changes",build:"Build",chore:"Chores",ci:"CI",dependencies:"Dependency updates",docs:"Documentation",feat:"Features",fix:"Bug fixes",other:"Other changes",perf:"Performance",refactor:"Refactoring",style:"Styling",test:"Tests"}},commit:{author:"r5n-bot",message:"chore(release): {message}"},commits:{skip:{authors:["r5n-bot[bot]"],messagePatterns:["^chore\\(release\\):","^chore: add stone"]}},ignore:[],lastStone:{commit:"",date:""},plugins:[],pr:{labelMapping:{breaking:"major","breaking-change":"major",bug:"patch",chore:"patch",docs:"patch",enhancement:"minor",feature:"minor",fix:"patch"},skip:{authors:["r5n-bot[bot]"],labels:["sisyphus-release","skip-stone"],titlePatterns:["^chore\\(release\\):"]}},release:{createRelease:!1,npm:!1,push:!1,tags:!1},scripts:{post:{},pre:{}},single:!1,sisyphusDir:".sisyphus",stones:[],tag:"latest"};class ht extends fe{name="github";get apiPath(){return`repos/${encodeURIComponent(this.owner)}/${encodeURIComponent(this.repo)}`}async ensureAvailable(){try{await Bun.$`which gh`.quiet()}catch{throw new f("GitHub CLI (gh) is not installed","Install from https://cli.github.com and run: gh auth login")}try{await Bun.$`gh auth status`.quiet()}catch{throw new f("GitHub CLI (gh) is not authenticated","Run: gh auth login")}}async getDefaultBranch(){try{return(await Bun.$`gh repo view --json defaultBranchRef --jq .defaultBranchRef.name`.quiet()).stdout.toString().trim()||pe}catch{return pe}}async findPr(e){try{let t=[];if(e.head)t.push("--head",e.head);if(e.label)t.push("--label",e.label);let n=await Bun.$`gh pr list --json number,url,title,body,labels,author,headRefName,baseRefName,mergeCommit,state --limit 1 ${t}`.quiet(),r=JSON.parse(n.stdout.toString());if(!r[0])return null;return this.mapPrResponse(r[0])}catch{return null}}async createPr(e){let t=await Bun.$`gh api ${this.apiPath}/pulls --method POST -f head=${e.head} -f base=${e.base} -f title=${e.title} -f body=${e.body}`,r=JSON.parse(t.stdout.toString()).number;if(e.labels&&e.labels.length>0){let i=e.labels.flatMap((s)=>["-f",`labels[]=${s}`]);await Bun.$`gh api ${this.apiPath}/issues/${r}/labels --method POST ${i}`}return this.getPr(r)}async updatePr(e,t){let n=[];if(t.title)n.push("--title",t.title);if(t.body)n.push("--body",t.body);await Bun.$`gh pr edit ${e} ${n}`}async getPr(e){try{let t=await Bun.$`gh api ${this.apiPath}/pulls/${e}`.quiet(),n=JSON.parse(t.stdout.toString());return this.mapRestApiResponse(n)}catch{throw new f(`Failed to fetch PR #${e}`,"Make sure the PR exists and you have access")}}async getPrFromCurrentBranch(){try{let e=await Bun.$`gh pr view --json number,title,body,labels,author,headRefName,baseRefName,url,mergeCommit,state`.quiet(),t=JSON.parse(e.stdout.toString());return this.mapPrResponse(t)}catch{throw new f("No PR found for current branch","Make sure you have an open PR or provide a URL with --url")}}async getPrCommits(e){try{return(await Bun.$`gh api ${this.apiPath}/pulls/${e}/commits --jq '.[].sha'`.quiet()).stdout.toString().trim().split(`
|
|
91
91
|
`).filter(Boolean)}catch{return[]}}async getPrFiles(e){try{return(await Bun.$`gh api ${this.apiPath}/pulls/${e}/files --jq '.[].filename'`.quiet()).stdout.toString().trim().split(`
|
|
92
92
|
`).filter(Boolean)}catch{return[]}}async ensureLabelExists(e,t){try{let n=t?.description??"",r=t?.color?["--color",t.color]:[];await Bun.$`gh label create ${e} --description ${n} ${r} --force`.quiet()}catch{}}async createRelease(e){await Bun.$`gh release create ${e.tag} --title ${e.title} --notes ${e.notes}`}async deleteRelease(e){try{await Bun.$`gh release delete ${e} --yes`.quiet()}catch{}}mapRestApiResponse(e){return{author:e.user?.login??Ge,baseBranch:e.base?.ref??pe,body:e.body??"",headBranch:e.head?.ref??"",labels:e.labels?.map((t)=>t.name)??[],mergeCommitSha:e.merge_commit_sha,merged:e.merged,number:e.number,title:e.title,url:e.html_url}}mapPrResponse(e){return{author:e.author?.login??Ge,baseBranch:e.baseRefName??pe,body:e.body??"",headBranch:e.headRefName??"",labels:e.labels?.map((t)=>t.name)??[],mergeCommitSha:e.mergeCommit?.oid??null,merged:e.state==="MERGED",number:e.number,title:e.title,url:e.url}}}var vs="https://gitlab.com/api/v4";class ft extends fe{name="gitlab";authHeader={};apiUrl;projectPath;constructor(e){super(e);this.apiUrl=process.env.CI_API_V4_URL??vs,this.projectPath=encodeURIComponent(`${this.owner}/${this.repo}`)}async ensureAvailable(){this.authHeader=await this.resolveAuth()}async getDefaultBranch(){try{return(await this.api(`/projects/${this.projectPath}`)).default_branch||pe}catch{return pe}}async findPr(e){try{let t=new URLSearchParams({per_page:"1",state:"opened"});if(e.head)t.set("source_branch",e.head);if(e.label)t.set("labels",e.label);let n=await this.api(`/projects/${this.projectPath}/merge_requests?${t}`);if(!n[0])return null;return this.mapMrResponse(n[0])}catch{return null}}async createPr(e){let t={description:e.body,source_branch:e.head,target_branch:e.base,title:e.title};if(e.labels?.length)t.labels=e.labels.join(",");let n=await this.api(`/projects/${this.projectPath}/merge_requests`,{body:JSON.stringify(t),method:"POST"});return this.mapMrResponse(n)}async updatePr(e,t){let n={};if(t.title)n.title=t.title;if(t.body)n.description=t.body;await this.api(`/projects/${this.projectPath}/merge_requests/${e}`,{body:JSON.stringify(n),method:"PUT"})}async getPr(e){try{let t=await this.api(`/projects/${this.projectPath}/merge_requests/${e}`);return this.mapMrResponse(t)}catch{throw new f(`Failed to fetch MR !${e}`,"Make sure the MR exists and you have access")}}async getPrFromCurrentBranch(){try{let t=(await Bun.$`git rev-parse --abbrev-ref HEAD`.quiet()).stdout.toString().trim(),n=new URLSearchParams({per_page:"1",source_branch:t,state:"opened"}),r=await this.api(`/projects/${this.projectPath}/merge_requests?${n}`);if(!r[0])throw Error("No MR found");return this.mapMrResponse(r[0])}catch{throw new f("No MR found for current branch","Make sure you have an open MR or provide a URL with --url")}}async getPrCommits(e){try{return(await this.api(`/projects/${this.projectPath}/merge_requests/${e}/commits`)).map((n)=>n.id)}catch{return[]}}async getPrFiles(e){try{return(await this.api(`/projects/${this.projectPath}/merge_requests/${e}/changes`)).changes?.map((n)=>n.new_path)??[]}catch{return[]}}async ensureLabelExists(e,t){try{let n={name:e};if(t?.description)n.description=t.description;if(t?.color)n.color=`#${t.color}`;await this.api(`/projects/${this.projectPath}/labels`,{body:JSON.stringify(n),method:"POST"})}catch{}}async createRelease(e){await this.api(`/projects/${this.projectPath}/releases`,{body:JSON.stringify({description:e.notes,name:e.title,tag_name:e.tag}),method:"POST"})}async deleteRelease(e){try{await this.api(`/projects/${this.projectPath}/releases/${encodeURIComponent(e)}`,{method:"DELETE"})}catch{}}async resolveAuth(){if(process.env.GITLAB_TOKEN)return{"PRIVATE-TOKEN":process.env.GITLAB_TOKEN};if(process.env.CI_JOB_TOKEN)return{"JOB-TOKEN":process.env.CI_JOB_TOKEN};try{let e=await Bun.$`glab auth status --show-token`.quiet(),n=(e.stdout.toString()+e.stderr.toString()).match(/Token found:\s*(\S+)/);if(n?.[1])return{Authorization:`Bearer ${n[1]}`}}catch{}throw new f("GitLab token not found","Set GITLAB_TOKEN environment variable or install glab CLI and run: glab auth login")}async api(e,t){let n=await fetch(`${this.apiUrl}${e}`,{...t,headers:{"Content-Type":"application/json",...this.authHeader,...t?.headers}});if(!n.ok){let r=await n.text().catch(()=>"");throw Error(`GitLab API error: ${n.status} ${n.statusText}${r?` \u2014 ${r}`:""}`)}return n.json()}mapMrResponse(e){return{author:e.author?.username??Ge,baseBranch:e.target_branch??pe,body:e.description??"",headBranch:e.source_branch??"",labels:e.labels??[],mergeCommitSha:e.merge_commit_sha,merged:e.state==="merged",number:e.iid,title:e.title,url:e.web_url}}}var ks=/github\.com[:/]([^/]+)\/([^/.]+)/,Cs=/gitlab\.com[:/]([^/]+)\/([^/.]+)/,$s=/bitbucket\.org[:/]([^/]+)\/([^/.]+)/,Rs=/github\.com\/([^/]+)\/([^/]+)\/pull\/(\d+)/,Ss=/gitlab\.com\/([^/]+)\/([^/]+)\/-\/merge_requests\/(\d+)/,Ms=/bitbucket\.org\/([^/]+)\/([^/]+)\/pull-requests\/(\d+)/;async function Fe(){let e=await Dr();if(!e)throw new f("Could not detect git provider","Make sure you have a git remote configured (origin)");let t=Is(e);return await t.ensureAvailable(),t}function Is(e){switch(e.provider){case"github":return new ht(e);case"gitlab":return new ft(e);case"bitbucket":return new mt(e);default:throw new f(`Unsupported provider: ${e.provider}`)}}async function Dr(){let e=await _t();if(!e)return null;return Zt(e)}async function Fr(){let e=await Dr();if(!e)throw new f("Could not detect git provider","Make sure you have a git remote configured (origin)");return e.provider}async function _t(){try{return(await Bun.$`git remote get-url origin`.quiet()).stdout.toString().trim()||null}catch{return null}}function Zt(e){let t=[[ks,"github"],[Cs,"gitlab"],[$s,"bitbucket"]];for(let[n,r]of t){let i=e.match(n);if(!i)continue;let[,s,o]=i;if(s&&o)return{owner:s,provider:r,repo:o}}return null}function Qt(e){let t=[[Rs,"github"],[Ss,"gitlab"],[Ms,"bitbucket"]];for(let[n,r]of t){let i=e.match(n);if(!i)continue;let[,s,o,a]=i;if(s&&o&&a)return{number:Number.parseInt(a,10),owner:s,provider:r,repo:o}}return null}import{existsSync as jr}from"fs";import{readFile as Ds}from"fs/promises";import{dirname as Fs,join as Xt}from"path";import{fileURLToPath as js}from"url";var dt={"create-stone":{description:"When a PR is merged, create stone and update release PR",name:"Handle PR merge (stone + release PR)"},release:{description:"When the release PR is merged, publish packages",name:"Publish release"}},Es=Xt(Fs(js(import.meta.url)),"templates"),Er={"create-stone":"sis-create-stone.yml",release:"sis-release.yml"};class en{async generate(e){let t=[];for(let n of e){let r=await this.readTemplate(n),i=this.getOutputPath(n);t.push({content:r,path:i})}return t}getExistingFiles(e){return e.map((t)=>this.getOutputPath(t)).filter((t)=>jr(t))}async readTemplate(e){let t=Xt(Es,this.provider,Er[e]);return Ds(t,"utf-8")}}class yt extends en{provider="github";outputDir=".github/workflows";getOutputPath(e){return Xt(this.outputDir,Er[e])}}var qe=".gitlab-ci-sisyphus.yml";class bt extends en{provider="gitlab";outputDir=".";async generate(e){let t=[];t.push(`stages:
|
|
93
93
|
- sisyphus
|
|
@@ -19,7 +19,7 @@ jobs:
|
|
|
19
19
|
contents: write
|
|
20
20
|
pull-requests: write
|
|
21
21
|
steps:
|
|
22
|
-
- uses: actions/checkout@
|
|
22
|
+
- uses: actions/checkout@v7
|
|
23
23
|
with:
|
|
24
24
|
fetch-depth: 0
|
|
25
25
|
|
|
@@ -68,7 +68,7 @@ jobs:
|
|
|
68
68
|
contents: write
|
|
69
69
|
pull-requests: write
|
|
70
70
|
steps:
|
|
71
|
-
- uses: actions/checkout@
|
|
71
|
+
- uses: actions/checkout@v7
|
|
72
72
|
with:
|
|
73
73
|
fetch-depth: 0
|
|
74
74
|
|
package/package.json
CHANGED