#!/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 "open-uri" require "colorize" require "nutella" print "Downloading data..." # The user can paste 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. # } # } puts <<-EOS.heredoc Finished downloading Gist from: #{gist["html_url"]} Gist uploaded by #{ gist["user"] ? "user #{gist["user"]["login"]}" : "an anonymous user" }. Beginning install... EOS gist["files"].each do |filename, data| lines = data["content"].lines.to_a # Parse out all metadata after %% on the first two lines, strip out # (lead|trail)ing whitespace while we're at it. metadata = lines[0..1].map { |line| line[/%%\s*(.*\S)\s*/, 1] } # Skip non-Gistribute files. next if metadata.first.nil? puts " #{"*".green} Installing #{metadata[1] || filename}..." # TODO: Is there a better way to handle ~? path = metadata.first.gsub "~", Dir.home # Handle directories that don't exist. FileUtils.mkdir_p File.dirname(path) File.open(path, "w") do |f| # Remove all lines with metadata- lines that don't match will return nil, # so compact it and drop that many off the top of the file. f << lines[metadata.compact.size..-1].join end end