Skip to content

Instantly share code, notes, and snippets.

@sgolemon
Created June 17, 2020 13:39
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sgolemon/af0ef6daeea5bab558484687aad4c8e7 to your computer and use it in GitHub Desktop.
Save sgolemon/af0ef6daeea5bab558484687aad4c8e7 to your computer and use it in GitHub Desktop.
Command-line gist writer
#!/usr/local/bin/php
<?php
// Get a key from Github > Settings > Developer Settings > Personal Access Tokens
// Create a token with only the 'gist' permission.
const GISTKEY = '';
const GISTUSER = ''; // Put your github username here. Duh.
const GISTPOST = 'https://api.github.com/gists';
$headers = [
'Authorization: token ' . GISTKEY,
'Content-type: text/json',
'User-agent: sgolemon\'s gist writer',
];
// Make a hard(or sym) link version of this script called `git-gist-public`
// and that version will automatically make public gists.
// Default for any other name is secret.
$cmd = array_shift($_SERVER['argv']);
$public = basename($cmd) === 'git-gist-public';
if (count($_SERVER['argv']) < 1) {
fprintf(STDERR, "Usage: $cmd filename [description...]\n");
exit(1);
}
$filename = array_shift($_SERVER['argv']);
$description = implode(' ', $_SERVER['argv']) ?: $filename;
$contents = stream_get_contents(STDIN);
if (empty($filename) || empty($contents)) {
fwrite(STDERR, "Nothing to post\n");
exit(1);
}
$query = [
'files' => [ $filename => [ 'content' => $contents ] ],
'public' => $public,
'description' => $description,
];
$ch = curl_init(GISTPOST);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($query));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$url = json_decode($result)->html_url ?? null;
if (!isset($url)) {
fwrite(STDERR, "$result\n");
} else {
echo $url, PHP_EOL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment