Skip to content

Commit

Permalink
expose the error utility as a method (issue lukeed#54)
Browse files Browse the repository at this point in the history
  • Loading branch information
paulovieira committed Jul 11, 2022
1 parent 1cdf3e4 commit cd26309
Show file tree
Hide file tree
Showing 5 changed files with 23 additions and 11 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@ node_modules
*.lock
*.log

/lib
#/lib
1 change: 1 addition & 0 deletions lib/index.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions lib/index.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import e from"mri";const t="__all__",i="__default__",s="\n";function r(e){if(!e.length)return"";let t=function(e){let t=0,i=0,s=0,r=e.length;if(r)for(;r--;)i=e[r].length,i>t&&(s=r,t=i);return e[s].length}(e.map(e=>e[0]))+4;return e.map(e=>e[0]+" ".repeat(t-e[0].length)+e[1]+(null==e[2]?"":` (default ${e[2]})`))}function n(e){return e}function l(e,t,i){if(!t||!t.length)return"";let r=0,n="";for(n+="\n "+e;r<t.length;r++)n+="\n "+i(t[r]);return n+s}class a{constructor(e,s){let[r,...n]=e.split(/\s+/);s=s||n.length>0,this.bin=r,this.ver="0.0.0",this.default="",this.tree={},this.command(t),this.command([i].concat(s?n:"<command>").join(" ")),this.single=s,this.curr=""}command(e,t,i={}){if(this.single)throw new Error('Disable "single" mode to add commands');let s=[],r=[],n=/(\[|<)/;if(e.split(/\s+/).forEach(e=>{(n.test(e.charAt(0))?r:s).push(e)}),s=s.join(" "),s in this.tree)throw new Error("Command already exists: "+s);return s.includes("__")||r.unshift(s),r=r.join(" "),this.curr=s,i.default&&(this.default=s),this.tree[s]={usage:r,alibi:[],options:[],alias:{},default:{},examples:[]},i.alias&&this.alias(i.alias),t&&this.describe(t),this}describe(e){return this.tree[this.curr||i].describe=Array.isArray(e)?e:function(e){return(e||"").replace(/([.?!])\s*(?=[A-Z])/g,"$1|").split("|")}(e),this}alias(...e){if(this.single)throw new Error('Cannot call `alias()` in "single" mode');if(!this.curr)throw new Error("Cannot call `alias()` before defining a command");return(this.tree[this.curr].alibi=this.tree[this.curr].alibi.concat(...e)).forEach(e=>this.tree[e]=this.curr),this}option(e,i,s){let r=this.tree[this.curr||t],[n,l]=function(e){return(e||"").split(/^-{1,2}|,|\s+-{1,2}|\s+/).filter(Boolean)}(e);if(l&&l.length>1&&([n,l]=[l,n]),e="--"+n,l&&l.length>0){e=`-${l}, ${e}`;let t=r.alias[l];r.alias[l]=(t||[]).concat(n)}let a=[e,i||""];return void 0!==s?(a.push(s),r.default[n]=s):l||(r.default[n]=void 0),r.options.push(a),this}action(e){return this.tree[this.curr||i].handler=e,this}example(e){return this.tree[this.curr||i].examples.push(e),this}version(e){return this.ver=e,this}parse(s,r={}){s=s.slice();let n,l,a,o,h=2,u=e(s.slice(h),{alias:{h:"help",v:"version"}}),f=this.single,c=this.bin,p="";if(f)o=this.tree[i];else{let e,t=1,i=u._.length+1;for(;t<i;t++)if(n=u._.slice(0,t).join(" "),e=this.tree[n],"string"==typeof e)l=(p=e).split(" "),s.splice(s.indexOf(u._[0]),t,...l),t+=l.length-t;else if(e)p=n;else if(p)break;if(o=this.tree[p],a=void 0===o,a)if(this.default)p=this.default,o=this.tree[p],s.unshift(p),h++;else if(n)return this.error(c,"Invalid command: "+n)}if(u.help)return this.help(!f&&!a&&p);if(u.version)return this._version();if(!f&&void 0===o)return this.error(c,"No command specified.");let d=this.tree[t];r.alias=Object.assign(d.alias,o.alias,r.alias),r.default=Object.assign(d.default,o.default,r.default),n=p.split(" "),l=s.indexOf(n[0],2),~l&&s.splice(l,n.length);let g=e(s.slice(h),r);if(!g||"string"==typeof g)return this.error(c,g||"Parsed unknown option flag(s)!");let m=o.usage.split(/\s+/),b=m.filter(e=>"<"===e.charAt(0)),_=g._.splice(0,b.length);if(_.length<b.length)return p&&(c+=" "+p),this.error(c,"Insufficient arguments!");m.filter(e=>"["===e.charAt(0)).forEach(e=>{_.push(g._.shift())}),_.push(g);let v=o.handler;return r.lazy?{args:_,name:p,handler:v}:v.apply(null,_)}help(e){console.log(function(e,a,o,h){let u="",f=a[o],c="$ "+e,p=a[t],d=e=>`${c} ${e}`.replace(/\s+/g," "),g=[["-h, --help","Displays this message"]];if(o===i&&g.unshift(["-v, --version","Displays current version"]),f.options=(f.options||[]).concat(p.options,g),f.options.length>0&&(f.usage+=" [options]"),u+=l("Description",f.describe,n),u+=l("Usage",[f.usage],d),h||o!==i)h||o===i||(u+=l("Aliases",f.alibi,d));else{let e,t=/^__/,i="",o=[];for(e in a)"string"==typeof a[e]||t.test(e)||o.push([e,(a[e].describe||[""])[0]])<3&&(i+=`\n ${c} ${e} --help`);u+=l("Available Commands",r(o),n),u+="\n For more info, run any command with the `--help` flag"+i+s}return u+=l("Options",r(f.options),n),u+=l("Examples",f.examples.map(d),n),u}(this.bin,this.tree,e||i,this.single))}_version(){console.log(`${this.bin}, ${this.ver}`)}error(e,t,i=1){let s=l("ERROR",[t],n);s+=`\n Run \`$ ${e} --help\` for more info.\n`,console.error(s),"number"==typeof i&&process.exit(i)}}export default(e,t)=>new a(e,t);
18 changes: 14 additions & 4 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ class Sade {
arr.unshift(name);
offset++;
} else if (tmp) {
return $.error(bin, `Invalid command: ${tmp}`);
return this.error(bin, `Invalid command: ${tmp}`);
} //=> else: cmd not specified, wait for now...
}
}
Expand All @@ -152,7 +152,7 @@ class Sade {
if (argv.version) return this._version();

if (!isSingle && cmd === void 0) {
return $.error(bin, 'No command specified.');
return this.error(bin, 'No command specified.');
}

let all = this.tree[ALL];
Expand All @@ -166,7 +166,7 @@ class Sade {

let vals = mri(arr.slice(offset), opts);
if (!vals || typeof vals === 'string') {
return $.error(bin, vals || 'Parsed unknown option flag(s)!');
return this.error(bin, vals || 'Parsed unknown option flag(s)!');
}

let segs = cmd.usage.split(/\s+/);
Expand All @@ -175,7 +175,7 @@ class Sade {

if (args.length < reqs.length) {
if (name) bin += ` ${name}`; // for help text
return $.error(bin, 'Insufficient arguments!');
return this.error(bin, 'Insufficient arguments!');
}

segs.filter(x => x.charAt(0)==='[').forEach(_ => {
Expand All @@ -196,6 +196,16 @@ class Sade {
_version() {
console.log(`${this.bin}, ${this.ver}`);
}

error(bin, str, num=1) {
let out = $.section('ERROR', [str], $.noop);
out += ($.NL + $.__ + `Run \`$ ${bin} --help\` for more info.` + $.NL);
console.error(out);

if (typeof num == 'number') {
process.exit(num);
}
}
}

export default (str, isOne) => new Sade(str, isOne);
12 changes: 6 additions & 6 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,12 +76,12 @@ export function help(bin, tree, key, single) {
return out;
}

export function error(bin, str, num=1) {
let out = section('ERROR', [str], noop);
out += (NL + __ + `Run \`$ ${bin} --help\` for more info.` + NL);
console.error(out);
process.exit(num);
}
// export function error(bin, str, num=1) {
// let out = section('ERROR', [str], noop);
// out += (NL + __ + `Run \`$ ${bin} --help\` for more info.` + NL);
// console.error(out);
// process.exit(num);
// }

// Strips leading `-|--` & extra space(s)
export function parse(str) {
Expand Down

0 comments on commit cd26309

Please sign in to comment.