From 3542f2de0cecdbcf07d3bea3de6439e6a87376df Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Wed, 19 Dec 2018 13:50:48 -0500 Subject: Add examples/ directory (denoland/deno_std#28) Previously https://github.com/denoland/deno_examples Original: https://github.com/denoland/deno_std/commit/14be9a0e82d1b54d5b0f04291d9154d1d7da29f7 --- examples/gist.ts | 63 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100755 examples/gist.ts (limited to 'examples/gist.ts') diff --git a/examples/gist.ts b/examples/gist.ts new file mode 100755 index 000000000..04a123560 --- /dev/null +++ b/examples/gist.ts @@ -0,0 +1,63 @@ +#!/usr/bin/env deno --allow-net --allow-env + +import { args, env, exit, readFile } from "deno"; +import parseArgs from "https://deno.land/x/parseargs/index.ts"; + +function pathBase(p: string): string { + const parts = p.split("/"); + return parts[parts.length - 1]; +} + +async function main() { + const token = env()["GIST_TOKEN"]; + if (!token) { + console.error("GIST_TOKEN environmental variable not set."); + console.error("Get a token here: https://github.com/settings/tokens"); + exit(1); + } + + const parsedArgs = parseArgs(args.slice(1)); + + if (parsedArgs._.length === 0) { + console.error( + "Usage: gist.ts --allow-env --allow-net [-t|--title Example] some_file [next_file]" + ); + exit(1); + } + + const files = {}; + for (const filename of parsedArgs._) { + const base = pathBase(filename); + const content = await readFile(filename); + const contentStr = new TextDecoder().decode(content); + files[base] = { content: contentStr }; + } + + const content = { + description: parsedArgs.title || parsedArgs.t || "Example", + public: false, + files: files + }; + const body = JSON.stringify(content); + + const res = await fetch("https://api.github.com/gists", { + method: "POST", + headers: [ + ["Content-Type", "application/json"], + ["User-Agent", "Deno-Gist"], + ["Authorization", "token " + token] + ], + body + }); + + if (res.ok) { + let resObj = await res.json(); + console.log("Success"); + console.log(resObj["html_url"]); + } else { + let err = await res.text(); + console.error("Failure to POST", err); + } +} + +main(); -- cgit v1.2.3