diff options
author | Ryan Dahl <ry@tinyclouds.org> | 2018-12-19 13:50:48 -0500 |
---|---|---|
committer | GitHub <noreply@github.com> | 2018-12-19 13:50:48 -0500 |
commit | 3542f2de0cecdbcf07d3bea3de6439e6a87376df (patch) | |
tree | 53c39ae3456fa8d6a360485378e8d82949b09e9a /examples/gist.ts | |
parent | ecde6a4c503584aa712f40e70c8e1aa78959e110 (diff) |
Add examples/ directory (denoland/deno_std#28)
Previously https://github.com/denoland/deno_examples
Original: https://github.com/denoland/deno_std/commit/14be9a0e82d1b54d5b0f04291d9154d1d7da29f7
Diffstat (limited to 'examples/gist.ts')
-rwxr-xr-x | examples/gist.ts | 63 |
1 files changed, 63 insertions, 0 deletions
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(); |