y-undertree
7/4/2015 - 3:25 AM

gist to dash

gist to dash

#!/usr/bin/env ruby

if ARGV[0].nil? || ARGV[0].match(/-h/)
  puts "Usage : #{$0} 0: github_username, 1: dash_sqlite_db, 2: keyword prefix, 3: [no_comments]"
  exit
end

require 'net/http'
require 'open-uri'
#require 'awesome_print'
require 'uri'
require 'json'
require 'sqlite3'
require 'openssl'

#############
# Variables
#############

url =  "https://api.github.com/users/#{ARGV[0]}/gists"

############
# Functions
############

def getHttpsContent(url)
  uri = URI.parse(url)
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE
  request = Net::HTTP::Get.new(uri.request_uri)
  # private
  # request.basic_auth 'user-name', 'password'
  http.request(request).body
end

#############
# We get all the public gists
#############

puts "\nFetching #{url}...\n"
gists = []
i     = 1
max   = 20
# max page loop
while i <  max
  response = JSON.parse getHttpsContent(url + "?page=#{i}")
  if response.length >= 1
    gists += response
    i = i + 1
  else
    break;
  end
end

#ap gists

#############
# We list the gists and detect those we'll update
#############

gists_to_update = []
puts "Gists are :\n"
gists.each do |gist|
  puts "\t#{gist['description']}\n"

    unless (shortcut = gist['description'].to_s).empty?

    #gist['files'].each {|f| ap f}
    files = []
    gist['files'].each {|f| files << {:filename => f[0], :url => f[1]['raw_url']}}

    gists_to_update << {
      :shortcut => shortcut,
      :files => files
    }
  end
end

puts "\n\nThose Dash snippets will be updated :\n"
gists_to_update.each {|x| puts "\t#{ARGV[2]}#{x[:shortcut]}"}

#############
# We update the database
#############

db = SQLite3::Database.new(ARGV[1])
#db.execute2 'SELECT * FROM snippets;' do |row|
#  ap row
#end

gists_to_update.each do |gist|
  content = ""
  gist[:files].each do |f|
    content << "\n\n### #{f[:filename]}\n\n" if ARGV[3].nil?
    open(f[:url]) {|c|
      c.each_line {|line| content << line}
    }
  end

  snippet_id = db.get_first_row( "SELECT sid FROM snippets WHERE title = ?","#{ARGV[2]}#{gist[:shortcut]}")
  if snippet_id.nil?
    db.execute( "INSERT INTO snippets VALUES (null, ?, ?, 'Standard', 0)",
    "#{ARGV[2]}#{gist[:shortcut]}",
    content )
  else
    db.execute( "UPDATE snippets SET body = ? WHERE sid = ?",
    content,
    snippet_id )
  end
  puts "\n#{ARGV[2]}#{gist[:shortcut]} has been updated"
end

source

  • dropbox管理すれば、使い回せる
# my setting
./gists_to_dash.rb y-undertree /Users/kinoshityasunori/Dropbox/Develop/my-gists.dash "gists:" no_comments