Last active
November 24, 2017 17:06
-
-
Save ismasan/f8c7662a7adb2a4402544e734f9c15b3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'typhoeus' | |
require 'json' | |
require 'base64' | |
require 'fileutils' | |
# theme = GithubTheme.new( | |
# repo_url: "https://api.github.com/repos/bootic/theme_gallery/contents/snap", | |
# credentials: "user:token" | |
# ) | |
# puts 'TEMPLATES' | |
# theme.templates.each do |f| | |
# puts f.file_name | |
# end | |
# puts 'ASSETS' | |
# theme.assets.each do |f| | |
# puts f.file_name | |
# File.open("./foo/#{f.file_name}", "w") do |w| | |
# w.write f.file.read | |
# end | |
# end | |
# | |
class GithubTheme | |
class GFile | |
attr_reader :file_name | |
def initialize(path, data) | |
@file_name, @data = File.basename(path), data | |
end | |
def body | |
@body ||= Base64.decode64(@data) | |
end | |
def file | |
@file ||= StringIO.new(body) | |
end | |
end | |
class GDir | |
attr_reader :path, :contents | |
def initialize(path, contents) | |
@path, @contents = path, contents | |
end | |
def files | |
contents.find_all do |node| | |
node.is_a?(GFile) | |
end | |
end | |
def dirs | |
contents.find_all do |node| | |
node.is_a?(GDir) | |
end | |
end | |
end | |
def initialize(repo_url:, credentials:) | |
@repo_url, @credentials = repo_url, credentials | |
end | |
def title | |
File.basename(repo_url) | |
end | |
def settings | |
{} | |
end | |
def templates | |
@templates ||= root.files | |
end | |
def assets | |
@assets ||= assets_dir ? assets_dir.files : [] | |
end | |
private | |
attr_reader :repo_url, :credentials | |
def root | |
@root ||= build_dir({ | |
'path' => './', | |
'_links' => { | |
'self' => repo_url | |
} | |
}) | |
end | |
def assets_dir | |
@assets_dir ||= root.dirs.find do |node| | |
node.path =~ /assets/ | |
end | |
end | |
def get_json(url) | |
resp = Typhoeus::Request.get(url, userpwd: credentials, headers: {'Accept' => 'application/vnd.github.v3+json'}) | |
raise "nope" unless resp.success? | |
JSON.parse(resp.body) | |
end | |
def build_file(node) | |
node = get_json(node['_links']['self']) | |
GFile.new(node['path'], node['content']) | |
end | |
def build_dir(node) | |
contents = get_json(node['_links']['self']) | |
GDir.new(node['path'], build(contents)) | |
end | |
def build(list) | |
list.map do |node| | |
case node['type'] | |
when 'file' | |
build_file(node) | |
when 'dir' | |
build_dir(node) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment