UNPKG

gh-emoji-cli

Version:

List and/or pick from valid github emojis

18 lines (16 loc) 14.3 kB
#!/usr/bin/env node import{EventEmitter as H}from"events";function j(n){return n==null?[]:Array.isArray(n)?n:[n]}function J(n,t,e,i){var o,s=n[t],r=~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?r:Array.isArray(s)?s.concat(r):[s,r]}function z(n,t){n=n||[],t=t||{};var e,i,o,s,r,h={_:[]},c=0,a=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=j(t.string),t.boolean=j(t.boolean),u)for(e in t.alias)for(i=t.alias[e]=j(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]]||[],a=i.length;a-- >0;)t.boolean.push(i[a]);for(c=t.string.length;c-- >0;)for(i=t.alias[t.string[c]]||[],a=i.length;a-- >0;)t.string.push(i[a]);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 E=d?Object.keys(t.alias):[];for(c=0;c<f;c++){if(o=n[c],o==="--"){h._=h._.concat(n.slice(++c));break}for(a=0;a<o.length&&o.charCodeAt(a)===45;a++);if(a===0)h._.push(o);else if(o.substring(a,a+3)==="no-"){if(s=o.substring(a+3),d&&!~E.indexOf(s))return t.unknown(o);h[s]=!1}else{for(m=a+1;m<o.length&&o.charCodeAt(m)!==61;m++);for(s=o.substring(a,m),r=o.substring(++m)||c+1===f||(""+n[c+1]).charCodeAt(0)===45||n[++c],i=a===2?[s]:s,m=0;m<i.length;m++){if(s=i[m],d&&!~E.indexOf(s))return t.unknown("-".repeat(a)+s);J(h,s,m+1<i.length||r,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 T=n=>n.replace(/[<[].+/,"").trim(),Y=n=>{let t=/<([^>]+)>/g,e=/\[([^\]]+)\]/g,i=[],o=h=>{let c=!1,a=h[1];return a.startsWith("...")&&(a=a.slice(3),c=!0),{required:h[0].startsWith("<"),value:a,variadic:c}},s;for(;s=t.exec(n);)i.push(o(s));let r;for(;r=e.exec(n);)i.push(o(r));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,r)=>r!==e&&s.names.some(h=>i.names.includes(h))&&typeof s.required=="boolean")||t.boolean.push(i.names[0]));return t},N=n=>n.sort((t,e)=>t.length>e.length?-1:1)[0],R=(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,r;for(;i<o;++i)r=s[t[i]],s=s[t[i]]=i===o-1?e:r??(~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]:""},_=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}},k=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(t).split(",").map(o=>{let s=o.trim().replace(/^-{1,2}/,"");return s.startsWith("no-")&&(this.negated=!0,s=s.replace(/^no-/,"")),_(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}`,C=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(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 k(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 O}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,r=[{body:`${t}${i?`/${i}`:""}`}];if(r.push({title:"Usage",body:` $ ${t} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&e.length>0){let a=N(e.map(m=>m.rawName));r.push({title:"Commands",body:e.map(m=>` ${R(m.rawName,a.length)} ${m.description}`).join(` `)}),r.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(a=>a.name!=="version")),c.length>0){let a=N(c.map(m=>m.rawName));r.push({title:"Options",body:c.map(m=>` ${R(m.rawName,a.length)} ${m.description} ${m.config.default===void 0?"":`(default: ${m.config.default})`}`).join(` `)})}this.examples.length>0&&r.push({title:"Examples",body:this.examples.map(a=>typeof a=="function"?a(t):a).join(` `)}),s&&(r=s(r)||r),console.log(r.map(a=>a.title?`${a.title}: ${a.body}`:a.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 r=i.some(h=>h.negated&&h.names.includes(o.name));if(s===!0||s===!1&&!r)throw new b(`option \`${o.rawName}\` value is missing`)}}}},O=class extends C{constructor(t){super("@@global@@","",{},t)}},y=Object.assign,x=class extends H{constructor(t=""){super(),this.name=t,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new O(this),this.globalCommand.usage("<command> [options]")}usage(t){return this.globalCommand.usage(t),this}command(t,e,i){let o=new C(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 r=this.mri(t.slice(2),s),h=r.args[0];if(s.isMatched(h)){i=!1;let c=y(y({},r),{args:r.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 r=this.mri(t.slice(2),s);this.setParsedInfo(r,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=[],r=t.indexOf("--");r>-1&&(s=t.slice(r+1),t=t.slice(0,r));let h=z(t,o);h=Object.keys(h).reduce((u,d)=>y(y({},u),{[_(d)]:h[d]}),{_:[]});let c=h._,a={"--":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)a[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(a,d,h[u]),Z(a,f)}return{args:c,options:a}}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,r)=>{s.variadic?o.push(t.slice(r)):o.push(t[r])}),o.push(e),i.commandAction.apply(this,o)}},S=(n="")=>new x(n);import dt from"node:assert";import I from"node:path";import $ from"node:fs/promises";import{spawn as ft}from"node:child_process";import{Readable as U}from"node:stream";import*as B 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"),rt=nt==="win32",V=g.TERM==="dumb",at=B&&B.isatty&&B.isatty(1)&&g.TERM&&!V,lt="CI"in g&&("GITHUB_ACTIONS"in g||"GITLAB_CI"in g||"CIRCLECI"in g),ct=!ot&&(st||rt&&!V||at||lt),G=(n,t,e,i,o=t.substring(0,n)+i,s=t.substring(n+e.length),r=s.indexOf(e))=>o+(r<0?s:G(r,s,e,i)),ht=(n,t,e,i,o)=>n<0?e+t+i:e+G(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:Bt,bold:$t,dim:w,italic:jt,underline:kt,inverse:xt,hidden:vt,strikethrough:It,black:At,red:Dt,green:Et,yellow:Nt,blue:Rt,magenta:L,cyan:Tt,white:_t,gray:St,bgBlack:Mt,bgRed:Pt,bgGreen:Vt,bgYellow:Gt,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:re}=ut();import gt from"node:os";import{createInterface as pt}from"node:readline";var p=S("gh-emoji");p.version("v1.2.0");p.help();var q=I.resolve(gt.homedir(),".cache/gh-emoji"),v=I.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 r=I.basename(new URL(s).pathname,".png");if(!i.has(r))try{let h=r.replace("-",",200d,").split(",").map(a=>parseInt(a,16)),c=String.fromCodePoint(...h);e.push({name:o,emoji:c,codePoints:h,code:r})}catch{}}return e}async function F(){let n=await bt();return await $.mkdir(q,{recursive:!0}),await $.writeFile(v,JSON.stringify(n)),n}async function A(){try{await $.stat(v)}catch(n){if(!(n instanceof Error&&"code"in n&&n.code==="ENOENT"))throw n;return await F()}return $.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 A();U.from(W(e,t)).pipe(process.stdout)});p.command("refresh","Refresh the icon cache").action(async()=>{await F(),process.stdout.write(`Icons updated! `)});p.command("get <emoji>","Get a icon").option("-e, --emoji","Just get the emoji").option("-t, --table","Print as table").action(async(n,t)=>{let e=await A(),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 A(),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 r=s.match(i)?.groups?.index;r&&(o=t[parseInt(r,10)])}o&&process.stdout.write(JSON.stringify(o,null,2)+` `)});p.parse(process.argv);