#!/usr/bin/env ruby if %w[-v --version].include? ARGV.first puts "Gistribute #{File.read(File.expand_path("../../VERSION", __FILE__)).strip}" exit 0 end require "json" require "fileutils" require "open-uri" require "nutella" print "Downloading data..." # The user can pass in either just the ID or the entire URL to the Gist. id = ARGV.first[/(^|\/)([[:xdigit:]]+)/, 2] begin gist = JSON.parse open("https://api.github.com/gists/#{id}").read rescue OpenURI::HTTPError => msg print <<-EOS.heredoc.red There was an error downloading the requested Gist. The error is as follows: EOS puts msg puts "The ID that was queried is:".red puts id exit -1 end # The JSON data contains a lot of information. The information that is # relevant to this program is as follows: # # { # "html_url" => "Link to the Gist", # "description" => "The description for the Gist", # # "user" => nil, # IF ANONYMOUS # "user" => { # IF TIED TO A USER # "login" => "username" # }, # # "files" => { # "filename of first file" => { # "content" => "entire contents of the file" # } # # Repeat the above for every file in the Gist. # } # } # Regular expression word wrap to keep lines less than 80 characters. Then # check to see if it's empty- if not, put newlines on each side so that it # will be padded when displayed in the output. desc = gist["description"].gsub(/(.{1,79})(\s+|\Z)/, "\\1\n").strip desc = "\n#{desc}\n" unless desc.empty? puts < "/", "~" => Dir.home # Default description is the name of the file. description = metadata.size == 1 ? File.basename(path) : metadata.first puts " #{"*".green} Installing #{description}..." # Handle directories that don't exist. FileUtils.mkdir_p File.dirname(path) File.write path, data["content"] end