gh-emoji-cli
Version:
List and/or pick from valid github emojis
18 lines (16 loc) • 14.5 kB
JavaScript
import{EventEmitter as H}from"events";function k(n){return n==null?[]:Array.isArray(n)?n:[n]}function J(n,t,e,i){var o,s=n[t],a=~i.string.indexOf(t)?e==null||e===!0?"":String(e):typeof e=="boolean"?e:~i.boolean.indexOf(t)?e==="false"?!1:e==="true"||(n._.push((o=+e,o*0===0?o:e)),!!e):(o=+e,o*0===0?o:e);n[t]=s==null?a:Array.isArray(s)?s.concat(a):[s,a]}function z(n,t){n=n||[],t=t||{};var e,i,o,s,a,h={_:[]},c=0,r=0,m=0,f=n.length;let u=t.alias!==void 0,d=t.unknown!==void 0,D=t.default!==void 0;if(t.alias=t.alias||{},t.string=k(t.string),t.boolean=k(t.boolean),u)for(e in t.alias)for(i=t.alias[e]=k(t.alias[e]),c=0;c<i.length;c++)(t.alias[i[c]]=i.concat(e)).splice(c,1);for(c=t.boolean.length;c-- >0;)for(i=t.alias[t.boolean[c]]||[],r=i.length;r-- >0;)t.boolean.push(i[r]);for(c=t.string.length;c-- >0;)for(i=t.alias[t.string[c]]||[],r=i.length;r-- >0;)t.string.push(i[r]);if(D){for(e in t.default)if(s=typeof t.default[e],i=t.alias[e]=t.alias[e]||[],t[s]!==void 0)for(t[s].push(e),c=0;c<i.length;c++)t[s].push(i[c])}let N=d?Object.keys(t.alias):[];for(c=0;c<f;c++){if(o=n[c],o==="--"){h._=h._.concat(n.slice(++c));break}for(r=0;r<o.length&&o.charCodeAt(r)===45;r++);if(r===0)h._.push(o);else if(o.substring(r,r+3)==="no-"){if(s=o.substring(r+3),d&&!~N.indexOf(s))return t.unknown(o);h[s]=!1}else{for(m=r+1;m<o.length&&o.charCodeAt(m)!==61;m++);for(s=o.substring(r,m),a=o.substring(++m)||c+1===f||(""+n[c+1]).charCodeAt(0)===45||n[++c],i=r===2?[s]:s,m=0;m<i.length;m++){if(s=i[m],d&&!~N.indexOf(s))return t.unknown("-".repeat(r)+s);J(h,s,m+1<i.length||a,t)}}}if(D)for(e in t.default)h[e]===void 0&&(h[e]=t.default[e]);if(u)for(e in h)for(i=t.alias[e]||[];i.length>0;)h[i.shift()]=h[e];return h}var _=n=>n.replace(/[<[].+/,"").trim(),Y=n=>{let t=/<([^>]+)>/g,e=/\[([^\]]+)\]/g,i=[],o=h=>{let c=!1,r=h[1];return r.startsWith("...")&&(r=r.slice(3),c=!0),{required:h[0].startsWith("<"),value:r,variadic:c}},s;for(;s=t.exec(n);)i.push(o(s));let a;for(;a=e.exec(n);)i.push(o(a));return i},K=n=>{let t={alias:{},boolean:[]};for(let[e,i]of n.entries())i.names.length>1&&(t.alias[i.names[0]]=i.names.slice(1)),i.isBoolean&&(i.negated&&n.some((s,a)=>a!==e&&s.names.some(h=>i.names.includes(h))&&typeof s.required=="boolean")||t.boolean.push(i.names[0]));return t},R=n=>n.sort((t,e)=>t.length>e.length?-1:1)[0],T=(n,t)=>n.length>=t?n:`${n}${" ".repeat(t-n.length)}`,Q=n=>n.replace(/([a-z])-([a-z])/g,(t,e,i)=>e+i.toUpperCase()),X=(n,t,e)=>{let i=0,o=t.length,s=n,a;for(;i<o;++i)a=s[t[i]],s=s[t[i]]=i===o-1?e:a??(~t[i+1].indexOf(".")||!(+t[i+1]>-1)?{}:[])},Z=(n,t)=>{for(let e of Object.keys(t)){let i=t[e];i.shouldTransform&&(n[e]=Array.prototype.concat.call([],n[e]),typeof i.transformFunction=="function"&&(n[e]=n[e].map(i.transformFunction)))}},tt=n=>{let t=/([^\\\/]+)$/.exec(n);return t?t[1]:""},I=n=>n.split(".").map((t,e)=>e===0?Q(t):t).join("."),b=class extends Error{constructor(t){super(t),this.name=this.constructor.name,typeof Error.captureStackTrace=="function"?Error.captureStackTrace(this,this.constructor):this.stack=new Error(t).stack}},x=class{constructor(t,e,i){this.rawName=t,this.description=e,this.config=Object.assign({},i),t=t.replace(/\.\*/g,""),this.negated=!1,this.names=_(t).split(",").map(o=>{let s=o.trim().replace(/^-{1,2}/,"");return s.startsWith("no-")&&(this.negated=!0,s=s.replace(/^no-/,"")),I(s)}).sort((o,s)=>o.length>s.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null&&(this.config.default=!0),t.includes("<")?this.required=!0:t.includes("[")?this.required=!1:this.isBoolean=!0}},et=process.argv,it=`${process.platform}-${process.arch} node-${process.version}`,j=class{constructor(t,e,i={},o){this.rawName=t,this.description=e,this.config=i,this.cli=o,this.options=[],this.aliasNames=[],this.name=_(t),this.args=Y(t),this.examples=[]}usage(t){return this.usageText=t,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version(t,e="-v, --version"){return this.versionNumber=t,this.option(e,"Display version number"),this}example(t){return this.examples.push(t),this}option(t,e,i){let o=new x(t,e,i);return this.options.push(o),this}alias(t){return this.aliasNames.push(t),this}action(t){return this.commandAction=t,this}isMatched(t){return this.name===t||this.aliasNames.includes(t)}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof C}hasOption(t){return t=t.split(".")[0],this.options.find(e=>e.names.includes(t))}outputHelp(){let{name:t,commands:e}=this.cli,{versionNumber:i,options:o,helpCallback:s}=this.cli.globalCommand,a=[{body:`${t}${i?`/${i}`:""}`}];if(a.push({title:"Usage",body:` $ ${t} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&e.length>0){let r=R(e.map(m=>m.rawName));a.push({title:"Commands",body:e.map(m=>` ${T(m.rawName,r.length)} ${m.description}`).join(`
`)}),a.push({title:"For more info, run any command with the `--help` flag",body:e.map(m=>` $ ${t}${m.name===""?"":` ${m.name}`} --help`).join(`
`)})}let c=this.isGlobalCommand?o:[...this.options,...o||[]];if(!this.isGlobalCommand&&!this.isDefaultCommand&&(c=c.filter(r=>r.name!=="version")),c.length>0){let r=R(c.map(m=>m.rawName));a.push({title:"Options",body:c.map(m=>` ${T(m.rawName,r.length)} ${m.description} ${m.config.default===void 0?"":`(default: ${m.config.default})`}`).join(`
`)})}this.examples.length>0&&a.push({title:"Examples",body:this.examples.map(r=>typeof r=="function"?r(t):r).join(`
`)}),s&&(a=s(a)||a),console.log(a.map(r=>r.title?`${r.title}:
${r.body}`:r.body).join(`
`))}outputVersion(){let{name:t}=this.cli,{versionNumber:e}=this.cli.globalCommand;e&&console.log(`${t}/${e} ${it}`)}checkRequiredArgs(){let t=this.args.filter(e=>e.required).length;if(this.cli.args.length<t)throw new b(`missing required args for command \`${this.rawName}\``)}checkUnknownOptions(){let{options:t,globalCommand:e}=this.cli;if(!this.config.allowUnknownOptions){for(let i of Object.keys(t))if(i!=="--"&&!this.hasOption(i)&&!e.hasOption(i))throw new b(`Unknown option \`${i.length>1?`--${i}`:`-${i}`}\``)}}checkOptionValue(){let{options:t,globalCommand:e}=this.cli,i=[...e.options,...this.options];for(let o of i){let s=t[o.name.split(".")[0]];if(o.required){let a=i.some(h=>h.negated&&h.names.includes(o.name));if(s===!0||s===!1&&!a)throw new b(`option \`${o.rawName}\` value is missing`)}}}},C=class extends j{constructor(t){super("@@global@@","",{},t)}},y=Object.assign,E=class extends H{constructor(t=""){super(),this.name=t,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new C(this),this.globalCommand.usage("<command> [options]")}usage(t){return this.globalCommand.usage(t),this}command(t,e,i){let o=new j(t,e||"",i,this);return o.globalCommand=this.globalCommand,this.commands.push(o),o}option(t,e,i){return this.globalCommand.option(t,e,i),this}help(t){return this.globalCommand.option("-h, --help","Display this message"),this.globalCommand.helpCallback=t,this.showHelpOnExit=!0,this}version(t,e="-v, --version"){return this.globalCommand.version(t,e),this.showVersionOnExit=!0,this}example(t){return this.globalCommand.example(t),this}outputHelp(){this.matchedCommand?this.matchedCommand.outputHelp():this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:t,options:e},i,o){return this.args=t,this.options=e,i&&(this.matchedCommand=i),o&&(this.matchedCommandName=o),this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}parse(t=et,{run:e=!0}={}){this.rawArgs=t,this.name||(this.name=t[1]?tt(t[1]):"cli");let i=!0;for(let s of this.commands){let a=this.mri(t.slice(2),s),h=a.args[0];if(s.isMatched(h)){i=!1;let c=y(y({},a),{args:a.args.slice(1)});this.setParsedInfo(c,s,h),this.emit(`command:${h}`,s)}}if(i){for(let s of this.commands)if(s.name===""){i=!1;let a=this.mri(t.slice(2),s);this.setParsedInfo(a,s),this.emit("command:!",s)}}if(i){let s=this.mri(t.slice(2));this.setParsedInfo(s)}this.options.help&&this.showHelpOnExit&&(this.outputHelp(),e=!1,this.unsetMatchedCommand()),this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null&&(this.outputVersion(),e=!1,this.unsetMatchedCommand());let o={args:this.args,options:this.options};return e&&this.runMatchedCommand(),!this.matchedCommand&&this.args[0]&&this.emit("command:*"),o}mri(t,e){let i=[...this.globalCommand.options,...e?e.options:[]],o=K(i),s=[],a=t.indexOf("--");a>-1&&(s=t.slice(a+1),t=t.slice(0,a));let h=z(t,o);h=Object.keys(h).reduce((u,d)=>y(y({},u),{[I(d)]:h[d]}),{_:[]});let c=h._,r={"--":s},m=e&&e.config.ignoreOptionDefaultValue?e.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,f=Object.create(null);for(let u of i){if(!m&&u.config.default!==void 0)for(let d of u.names)r[d]=u.config.default;Array.isArray(u.config.type)&&f[u.name]===void 0&&(f[u.name]=Object.create(null),f[u.name].shouldTransform=!0,f[u.name].transformFunction=u.config.type[0])}for(let u of Object.keys(h))if(u!=="_"){let d=u.split(".");X(r,d,h[u]),Z(r,f)}return{args:c,options:r}}runMatchedCommand(){let{args:t,options:e,matchedCommand:i}=this;if(!i||!i.commandAction)return;i.checkUnknownOptions(),i.checkOptionValue(),i.checkRequiredArgs();let o=[];return i.args.forEach((s,a)=>{s.variadic?o.push(t.slice(a)):o.push(t[a])}),o.push(e),i.commandAction.apply(this,o)}},S=(n="")=>new E(n);import dt from"node:assert";import A from"node:path";import B from"node:fs/promises";import{spawn as ft}from"node:child_process";import{Readable as U}from"node:stream";import*as O from"tty";var{env:g={},argv:P=[],platform:nt=""}=typeof process>"u"?{}:process,ot="NO_COLOR"in g||P.includes("--no-color"),st="FORCE_COLOR"in g||P.includes("--color"),at=nt==="win32",G=g.TERM==="dumb",rt=O&&O.isatty&&O.isatty(1)&&g.TERM&&!G,lt="CI"in g&&("GITHUB_ACTIONS"in g||"GITLAB_CI"in g||"CIRCLECI"in g),ct=!ot&&(st||at&&!G||rt||lt),V=(n,t,e,i,o=t.substring(0,n)+i,s=t.substring(n+e.length),a=s.indexOf(e))=>o+(a<0?s:V(a,s,e,i)),ht=(n,t,e,i,o)=>n<0?e+t+i:e+V(n,t,i,o)+i,mt=(n,t,e=n,i=n.length+1)=>o=>o||!(o===""||o===void 0)?ht((""+o).indexOf(t,i),o,n,t,e):"",l=(n,t,e)=>mt(`\x1B[${n}m`,`\x1B[${t}m`,e),M={reset:l(0,0),bold:l(1,22,"\x1B[22m\x1B[1m"),dim:l(2,22,"\x1B[22m\x1B[2m"),italic:l(3,23),underline:l(4,24),inverse:l(7,27),hidden:l(8,28),strikethrough:l(9,29),black:l(30,39),red:l(31,39),green:l(32,39),yellow:l(33,39),blue:l(34,39),magenta:l(35,39),cyan:l(36,39),white:l(37,39),gray:l(90,39),bgBlack:l(40,49),bgRed:l(41,49),bgGreen:l(42,49),bgYellow:l(43,49),bgBlue:l(44,49),bgMagenta:l(45,49),bgCyan:l(46,49),bgWhite:l(47,49),blackBright:l(90,39),redBright:l(91,39),greenBright:l(92,39),yellowBright:l(93,39),blueBright:l(94,39),magentaBright:l(95,39),cyanBright:l(96,39),whiteBright:l(97,39),bgBlackBright:l(100,49),bgRedBright:l(101,49),bgGreenBright:l(102,49),bgYellowBright:l(103,49),bgBlueBright:l(104,49),bgMagentaBright:l(105,49),bgCyanBright:l(106,49),bgWhiteBright:l(107,49)},ut=({useColor:n=ct}={})=>n?M:Object.keys(M).reduce((t,e)=>({...t,[e]:String}),{}),{reset:Ot,bold:Bt,dim:w,italic:$t,underline:kt,inverse:xt,hidden:Et,strikethrough:vt,black:At,red:Dt,green:Nt,yellow:Rt,blue:Tt,magenta:L,cyan:_t,white:It,gray:St,bgBlack:Mt,bgRed:Pt,bgGreen:Gt,bgYellow:Vt,bgBlue:Lt,bgMagenta:Ut,bgCyan:qt,bgWhite:Ft,blackBright:Wt,redBright:Ht,greenBright:Jt,yellowBright:zt,blueBright:Yt,magentaBright:Kt,cyanBright:Qt,whiteBright:Xt,bgBlackBright:Zt,bgRedBright:te,bgGreenBright:ee,bgYellowBright:ie,bgBlueBright:ne,bgMagentaBright:oe,bgCyanBright:se,bgWhiteBright:ae}=ut();import gt from"node:os";import{createInterface as pt}from"node:readline";var p=S("gh-emoji");p.version("v1.3.0");p.help();var q=A.resolve(gt.homedir(),".cache/gh-emoji"),v=A.resolve(q,"emojis.json");async function bt(){let n=await fetch("https://api.github.com/emojis",{headers:{Accept:"application/json"}});dt(n.ok);let t=await n.json(),e=[],i=new Set(["atom","accessibility"]);for(let[o,s]of Object.entries(t)){let a=A.basename(new URL(s).pathname,".png");if(!i.has(a))try{let h=a.replace("-",",200d,").split(",").map(r=>parseInt(r,16)),c=String.fromCodePoint(...h);e.push({name:o,emoji:c,codePoints:h,code:a})}catch{}}return e}async function F(){let n=await bt();return await B.mkdir(q,{recursive:!0}),await B.writeFile(v,JSON.stringify(n)),n}async function $(){try{await B.stat(v)}catch(n){if(!(n instanceof Error&&"code"in n&&n.code==="ENOENT"))throw n;return await F()}return B.readFile(v,"utf-8").then(n=>JSON.parse(n))}function*wt(n){let t=0;for(let e of n)yield[t++,e]}function yt(n,t){for(;t.startsWith(":");)t=t.substring(1,t.length-1);return n.find(e=>e.name===t)}async function*W(n,t){let e=Math.ceil(Math.log10(n.length));for(let[i,o]of wt(n))t.color?yield`${L(String(i).padStart(e," "))}. ${t.emoji?`${o.emoji} `:""}${w(`:${o.name}:`)}
`:yield`${String(i).padStart(e," ")}. ${t.emoji?`${o.emoji} `:""}:${o.name}:
`}p.command("[list]","List all emojis").option("-c, --color","Print with colors",{default:!0}).option("-e, --emoji","Print emoji",{default:!0}).action(async(n,t)=>{let e=await $();U.from(W(e,t)).pipe(process.stdout)});p.command("json","Get emoji data as json").action(async()=>{let n=await $();process.stdout.write(JSON.stringify(n))});p.command("refresh","Refresh the emoji cache").action(async()=>{await F(),process.stdout.write(`Emojis updated!
`)});p.command("get <emoji>","Get a emoji").option("-e, --emoji","Just get the emoji").option("-t, --table","Print as table").action(async(n,t)=>{let e=await $(),i=yt(e,n);i||process.exit(1),t.emoji?process.stdout.write(`${i.emoji}
`):t.table?process.stdout.write([`${w("Emoji \u2502")} ${i.emoji}`,` ${w("Name \u2502")} :${i.name}:`,` ${w("Code \u2502")} ${i.codePoints.join(", ")}`].join(`
`)+`
`):process.stdout.write(JSON.stringify(i,null,2)+`
`)});p.command("pick","Pick emoji with fzf").option("-p, --preview","Preview",{default:!0}).action(async n=>{let t=await $(),e=ft("fzf",["--no-multi","--cycle","--ansi"].concat(n.preview?["--preview",`${process.argv[1]} --table get {-1}`]:[]),{stdio:["pipe","pipe","inherit"],shell:!1});U.from(W(t,{color:!0,emoji:!n.preview})).pipe(e.stdin);let i=/^\s*(?<index>\d+)\./,o=null;for await(let s of pt({input:e.stdout})){let a=s.match(i)?.groups?.index;a&&(o=t[parseInt(a,10)])}o&&process.stdout.write(JSON.stringify(o,null,2)+`
`)});p.parse(process.argv);