ts-shasum
Version:
Compute and check SHA256 message digest.
18 lines (14 loc) • 11.7 kB
JavaScript
/**
* Version: 1.2.0
*
* Copyright (c) 2024 kjxbyz. All rights reserved.
*/
"use strict";var A=require("events");function w(n){return n==null?[]:Array.isArray(n)?n:[n]}function P(n,e,s,t){var i,o=n[e],r=~t.string.indexOf(e)?s==null||s===!0?"":String(s):typeof s=="boolean"?s:~t.boolean.indexOf(e)?s==="false"?!1:s==="true"||(n._.push((i=+s,i*0===0?i:s)),!!s):(i=+s,i*0===0?i:s);n[e]=o==null?r:Array.isArray(o)?o.concat(r):[o,r]}function I(n,e){n=n||[],e=e||{};var s,t,i,o,r,h={_:[]},a=0,l=0,c=0,p=n.length;let m=e.alias!==void 0,u=e.unknown!==void 0,v=e.default!==void 0;if(e.alias=e.alias||{},e.string=w(e.string),e.boolean=w(e.boolean),m)for(s in e.alias)for(t=e.alias[s]=w(e.alias[s]),a=0;a<t.length;a++)(e.alias[t[a]]=t.concat(s)).splice(a,1);for(a=e.boolean.length;a-- >0;)for(t=e.alias[e.boolean[a]]||[],l=t.length;l-- >0;)e.boolean.push(t[l]);for(a=e.string.length;a-- >0;)for(t=e.alias[e.string[a]]||[],l=t.length;l-- >0;)e.string.push(t[l]);if(v){for(s in e.default)if(o=typeof e.default[s],t=e.alias[s]=e.alias[s]||[],e[o]!==void 0)for(e[o].push(s),a=0;a<t.length;a++)e[o].push(t[a])}let $=u?Object.keys(e.alias):[];for(a=0;a<p;a++){if(i=n[a],i==="--"){h._=h._.concat(n.slice(++a));break}for(l=0;l<i.length&&i.charCodeAt(l)===45;l++);if(l===0)h._.push(i);else if(i.substring(l,l+3)==="no-"){if(o=i.substring(l+3),u&&!~$.indexOf(o))return e.unknown(i);h[o]=!1}else{for(c=l+1;c<i.length&&i.charCodeAt(c)!==61;c++);for(o=i.substring(l,c),r=i.substring(++c)||a+1===p||(""+n[a+1]).charCodeAt(0)===45||n[++a],t=l===2?[o]:o,c=0;c<t.length;c++){if(o=t[c],u&&!~$.indexOf(o))return e.unknown("-".repeat(l)+o);P(h,o,c+1<t.length||r,e)}}}if(v)for(s in e.default)h[s]===void 0&&(h[s]=e.default[s]);if(m)for(s in h)for(t=e.alias[s]||[];t.length>0;)h[t.shift()]=h[s];return h}var T=n=>n.replace(/[<[].+/,"").trim(),L=n=>{let e=/<([^>]+)>/g,s=/\[([^\]]+)\]/g,t=[],i=h=>{let a=!1,l=h[1];return l.startsWith("...")&&(l=l.slice(3),a=!0),{required:h[0].startsWith("<"),value:l,variadic:a}},o;for(;o=e.exec(n);)t.push(i(o));let r;for(;r=s.exec(n);)t.push(i(r));return t},q=n=>{let e={alias:{},boolean:[]};for(let[s,t]of n.entries())t.names.length>1&&(e.alias[t.names[0]]=t.names.slice(1)),t.isBoolean&&(t.negated&&n.some((o,r)=>r!==s&&o.names.some(h=>t.names.includes(h))&&typeof o.required=="boolean")||e.boolean.push(t.names[0]));return e},F=n=>n.sort((e,s)=>e.length>s.length?-1:1)[0],j=(n,e)=>n.length>=e?n:`${n}${" ".repeat(e-n.length)}`,M=n=>n.replace(/([a-z])-([a-z])/g,(e,s,t)=>s+t.toUpperCase()),G=(n,e,s)=>{let t=0,i=e.length,o=n,r;for(;t<i;++t)r=o[e[t]],o=o[e[t]]=t===i-1?s:r??(~e[t+1].indexOf(".")||!(+e[t+1]>-1)?{}:[])},R=(n,e)=>{for(let s of Object.keys(e)){let t=e[s];t.shouldTransform&&(n[s]=Array.prototype.concat.call([],n[s]),typeof t.transformFunction=="function"&&(n[s]=n[s].map(t.transformFunction)))}},U=n=>{let e=/([^\\\/]+)$/.exec(n);return e?e[1]:""},H=n=>n.split(".").map((e,s)=>s===0?M(e):e).join("."),f=class extends Error{constructor(e){super(e),this.name=this.constructor.name,typeof Error.captureStackTrace=="function"?Error.captureStackTrace(this,this.constructor):this.stack=new Error(e).stack}},C=class{constructor(e,s,t){this.rawName=e,this.description=s,this.config=Object.assign({},t),e=e.replace(/\.\*/g,""),this.negated=!1,this.names=T(e).split(",").map(i=>{let o=i.trim().replace(/^-{1,2}/,"");return o.startsWith("no-")&&(this.negated=!0,o=o.replace(/^no-/,"")),H(o)}).sort((i,o)=>i.length>o.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null&&(this.config.default=!0),e.includes("<")?this.required=!0:e.includes("[")?this.required=!1:this.isBoolean=!0}},z=process.argv,W=`${process.platform}-${process.arch} node-${process.version}`,y=class{constructor(e,s,t={},i){this.rawName=e,this.description=s,this.config=t,this.cli=i,this.options=[],this.aliasNames=[],this.name=T(e),this.args=L(e),this.examples=[]}usage(e){return this.usageText=e,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version(e,s="-v, --version"){return this.versionNumber=e,this.option(s,"Display version number"),this}example(e){return this.examples.push(e),this}option(e,s,t){let i=new C(e,s,t);return this.options.push(i),this}alias(e){return this.aliasNames.push(e),this}action(e){return this.commandAction=e,this}isMatched(e){return this.name===e||this.aliasNames.includes(e)}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof O}hasOption(e){return e=e.split(".")[0],this.options.find(s=>s.names.includes(e))}outputHelp(){let{name:e,commands:s}=this.cli,{versionNumber:t,options:i,helpCallback:o}=this.cli.globalCommand,r=[{body:`${e}${t?`/${t}`:""}`}];if(r.push({title:"Usage",body:` $ ${e} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&s.length>0){let l=F(s.map(c=>c.rawName));r.push({title:"Commands",body:s.map(c=>` ${j(c.rawName,l.length)} ${c.description}`).join(`
`)}),r.push({title:"For more info, run any command with the `--help` flag",body:s.map(c=>` $ ${e}${c.name===""?"":` ${c.name}`} --help`).join(`
`)})}let a=this.isGlobalCommand?i:[...this.options,...i||[]];if(!this.isGlobalCommand&&!this.isDefaultCommand&&(a=a.filter(l=>l.name!=="version")),a.length>0){let l=F(a.map(c=>c.rawName));r.push({title:"Options",body:a.map(c=>` ${j(c.rawName,l.length)} ${c.description} ${c.config.default===void 0?"":`(default: ${c.config.default})`}`).join(`
`)})}this.examples.length>0&&r.push({title:"Examples",body:this.examples.map(l=>typeof l=="function"?l(e):l).join(`
`)}),o&&(r=o(r)||r),console.log(r.map(l=>l.title?`${l.title}:
${l.body}`:l.body).join(`
`))}outputVersion(){let{name:e}=this.cli,{versionNumber:s}=this.cli.globalCommand;s&&console.log(`${e}/${s} ${W}`)}checkRequiredArgs(){let e=this.args.filter(s=>s.required).length;if(this.cli.args.length<e)throw new f(`missing required args for command \`${this.rawName}\``)}checkUnknownOptions(){let{options:e,globalCommand:s}=this.cli;if(!this.config.allowUnknownOptions){for(let t of Object.keys(e))if(t!=="--"&&!this.hasOption(t)&&!s.hasOption(t))throw new f(`Unknown option \`${t.length>1?`--${t}`:`-${t}`}\``)}}checkOptionValue(){let{options:e,globalCommand:s}=this.cli,t=[...s.options,...this.options];for(let i of t){let o=e[i.name.split(".")[0]];if(i.required){let r=t.some(h=>h.negated&&h.names.includes(i.name));if(o===!0||o===!1&&!r)throw new f(`option \`${i.rawName}\` value is missing`)}}}},O=class extends y{constructor(e){super("@@global@@","",{},e)}},b=Object.assign,x=class extends A.EventEmitter{constructor(e=""){super(),this.name=e,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new O(this),this.globalCommand.usage("<command> [options]")}usage(e){return this.globalCommand.usage(e),this}command(e,s,t){let i=new y(e,s||"",t,this);return i.globalCommand=this.globalCommand,this.commands.push(i),i}option(e,s,t){return this.globalCommand.option(e,s,t),this}help(e){return this.globalCommand.option("-h, --help","Display this message"),this.globalCommand.helpCallback=e,this.showHelpOnExit=!0,this}version(e,s="-v, --version"){return this.globalCommand.version(e,s),this.showVersionOnExit=!0,this}example(e){return this.globalCommand.example(e),this}outputHelp(){this.matchedCommand?this.matchedCommand.outputHelp():this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:e,options:s},t,i){return this.args=e,this.options=s,t&&(this.matchedCommand=t),i&&(this.matchedCommandName=i),this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}parse(e=z,{run:s=!0}={}){this.rawArgs=e,this.name||(this.name=e[1]?U(e[1]):"cli");let t=!0;for(let o of this.commands){let r=this.mri(e.slice(2),o),h=r.args[0];if(o.isMatched(h)){t=!1;let a=b(b({},r),{args:r.args.slice(1)});this.setParsedInfo(a,o,h),this.emit(`command:${h}`,o)}}if(t){for(let o of this.commands)if(o.name===""){t=!1;let r=this.mri(e.slice(2),o);this.setParsedInfo(r,o),this.emit("command:!",o)}}if(t){let o=this.mri(e.slice(2));this.setParsedInfo(o)}this.options.help&&this.showHelpOnExit&&(this.outputHelp(),s=!1,this.unsetMatchedCommand()),this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null&&(this.outputVersion(),s=!1,this.unsetMatchedCommand());let i={args:this.args,options:this.options};return s&&this.runMatchedCommand(),!this.matchedCommand&&this.args[0]&&this.emit("command:*"),i}mri(e,s){let t=[...this.globalCommand.options,...s?s.options:[]],i=q(t),o=[],r=e.indexOf("--");r>-1&&(o=e.slice(r+1),e=e.slice(0,r));let h=I(e,i);h=Object.keys(h).reduce((m,u)=>b(b({},m),{[H(u)]:h[u]}),{_:[]});let a=h._,l={"--":o},c=s&&s.config.ignoreOptionDefaultValue?s.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,p=Object.create(null);for(let m of t){if(!c&&m.config.default!==void 0)for(let u of m.names)l[u]=m.config.default;Array.isArray(m.config.type)&&p[m.name]===void 0&&(p[m.name]=Object.create(null),p[m.name].shouldTransform=!0,p[m.name].transformFunction=m.config.type[0])}for(let m of Object.keys(h))if(m!=="_"){let u=m.split(".");G(l,u,h[m]),R(l,p)}return{args:a,options:l}}runMatchedCommand(){let{args:e,options:s,matchedCommand:t}=this;if(!t||!t.commandAction)return;t.checkUnknownOptions(),t.checkOptionValue(),t.checkRequiredArgs();let i=[];return t.args.forEach((o,r)=>{o.variadic?i.push(e.slice(r)):i.push(e[r])}),i.push(s),t.commandAction.apply(this,i)}},E=(n="")=>new x(n);var S=require("glob"),D=require("crypto"),d=require("fs");async function V(n,e,s="sha256",t,i){let o=Object.fromEntries((await k(n,s,t,i)).map(([r,h])=>[h,r]));return e.reduce((r,[h,a])=>(r.push([a,h==o[a]]),r),[])}async function k(n,e="sha256",s,t){return await Promise.all((await Q(n)).map(async i=>[await K(i,e,s,t),i]))}function N(n,e,s){let t=e.map(([i,o])=>`${i} ${o}`);(0,d.writeFileSync)(n,t.join(`
`),s)}function _(n,e,s){let t=(0,d.readFileSync)(n,e);return Buffer.isBuffer(t)&&(t=t.toString(s)),t?.split(`
`)?.reduce((i,o)=>(i.push(o.split(" ")),i),[])||[]}function K(n,e,s,t){return new Promise(function(i,o){let r=(0,D.createHash)(e,s),h=(0,d.createReadStream)(n,t);h.on("readable",()=>{let a=h.read();a?r.update(a):i(r.digest("hex"))}),h.on("error",a=>{o(a)})})}function Q(n){return new Promise(function(e,s){try{let t=(0,S.globSync)(n,{});e(t)}catch(t){s(t)}})}var B="1.2.0";var g=E("shasum");g.command("create <entry> [...files]","Compute SHA256 message digest.").option("--algorithm <algorithm>","The `algorithm` is dependent on the available algorithms supported by the version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. On recent releases of OpenSSL, `openssl list -digest-algorithms` will display the available digest algorithms. (default: sha256) ",{default:"sha256"}).action(async(n,e,s)=>{console.debug(e,s);try{let t=await k(e,s.algorithm);console.warn(t),N(n,t),console.log("Saved successfully")}catch(t){console.error(t),process.exit(1)}});g.command("verify <entry> [...files]","Check SHA256 message digest.").option("--algorithm <algorithm>","The `algorithm` is dependent on the available algorithms supported by the version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. On recent releases of OpenSSL, `openssl list -digest-algorithms` will display the available digest algorithms. (default: sha256) ",{default:"sha256"}).action(async(n,e,s)=>{console.debug(n,e,s);try{let t=_(n),i=await V(e,t,s.algorithm);console.warn(i)}catch(t){console.error(t),process.exit(1)}});g.help();g.version(B);g.parse();