Skip to content

Instantly share code, notes, and snippets.

@RuiNtD
Created May 27, 2022 03:14
Show Gist options
  • Save RuiNtD/da4e7fab33f11b1efe12ecf499137d88 to your computer and use it in GitHub Desktop.
Save RuiNtD/da4e7fab33f11b1efe12ecf499137d88 to your computer and use it in GitHub Desktop.
Deno app that unpacks a file containing msgpack data into JSON
#!/usr/bin/env deno run
/**
Unpacks a file containing msgpack data into JSON.
@param filePath The path to the file to unpack.
@param outputPath The path to the file to write the output to.
@param pretty Whether to pretty-print the output.
*/
import * as msgpack from "https://unpkg.com/@msgpack/msgpack@2.7.2/mod.ts";
import { parse } from "https://deno.land/std@0.140.0/flags/mod.ts";
import { stripIndent } from "https://deno.land/x/deno_tags@1.8.0/tags/stripIndent.ts";
const args = parse(Deno.args, {
string: ["output"],
boolean: ["help", "pretty"],
alias: {
h: "help",
// "?": "help",
p: "pretty",
o: "output",
},
});
function errorExit(msg?: string): never {
if (msg) console.error(`%c${msg}`, "color: red");
Deno.exit(1);
}
const filename = args._[0];
if (args.help || typeof filename !== "string") {
console.log(stripIndent`
Usage:
msgunpack [OPTIONS] <FILE>
Options:
-h, --help
Show this help message.
-p, --pretty
Pretty-print the output.
-o, --output <FILE>
Write the output to a file.
`);
errorExit();
}
let file: Uint8Array;
try {
file = await Deno.readFile(filename);
} catch (e) {
if (e instanceof Deno.errors.NotFound)
errorExit(`File not found: ${filename}`);
else if (e instanceof Deno.errors.PermissionDenied)
errorExit("Permission denied to read file");
else throw e;
}
const data = msgpack.decode(file);
const space = args.pretty ? " " : "";
const results = JSON.stringify(data, null, space);
if (args.output) {
try {
await Deno.writeTextFile(args.output, results);
console.log("%cSaved to output", "color: green");
} catch (e) {
if (e instanceof Deno.errors.PermissionDenied)
errorExit("Permission denied to write output");
else throw e;
}
} else {
console.log(results);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment