From 6c2d00026c57299b7bec3b2bee04edf04fffec0a Mon Sep 17 00:00:00 2001 From: Ben Balter Date: Mon, 30 Nov 2015 16:29:45 -0500 Subject: [PATCH 01/12] use octokit to fetch gists when token present --- jekyll-gist.gemspec | 1 + lib/jekyll-gist/gist_tag.rb | 42 +++++++++++++++++++++++++++---------- spec/gist_tag_spec.rb | 34 ++++++++++++++++++++++-------- 3 files changed, 57 insertions(+), 20 deletions(-) diff --git a/jekyll-gist.gemspec b/jekyll-gist.gemspec index b4f3ece..8b62a2a 100644 --- a/jekyll-gist.gemspec +++ b/jekyll-gist.gemspec @@ -19,6 +19,7 @@ Gem::Specification.new do |spec| spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] + spec.add_dependency "octokit", "~> 4.2" spec.add_development_dependency "bundler", "~> 1.6" spec.add_development_dependency "rake" spec.add_development_dependency "rspec" diff --git a/lib/jekyll-gist/gist_tag.rb b/lib/jekyll-gist/gist_tag.rb index 3e9b844..aad50a2 100644 --- a/lib/jekyll-gist/gist_tag.rb +++ b/lib/jekyll-gist/gist_tag.rb @@ -62,20 +62,40 @@ def gist_noscript_tag(gist_id, filename = nil) end def fetch_raw_code(gist_id, filename = nil) + content = code_from_api(gist_id, filename) + return content if content + url = "https://gist.githubusercontent.com/#{gist_id}/raw" url = "#{url}/#{filename}" unless filename.empty? - begin - uri = URI(url) - Net::HTTP.start(uri.host, uri.port, - use_ssl: uri.scheme == 'https', - read_timeout: 3, open_timeout: 3) do |http| - request = Net::HTTP::Get.new uri.to_s - response = http.request(request) - response.body - end - rescue SocketError, Net::HTTPError, Net::OpenTimeout, Net::ReadTimeout, TimeoutError - nil + uri = URI(url) + Net::HTTP.start(uri.host, uri.port, + use_ssl: uri.scheme == 'https', + read_timeout: 3, open_timeout: 3) do |http| + request = Net::HTTP::Get.new uri.to_s + response = http.request(request) + response.body end + rescue SocketError, Net::HTTPError, Net::OpenTimeout, Net::ReadTimeout, TimeoutError + nil + end + + private + + def code_from_api(gist_id, filename = nil) + return unless ENV["JEKYLL_GITHUB_TOKEN"] + + client = Octokit::Client.new :access_token => ENV["JEKYLL_GITHUB_TOKEN"] + gist = client.gist gist_id + + file = if filename && gist.files[filename] + gist.files.filename + else + files.first + end + + file.content unless file.truncated + rescue Octokit => e + nil end end end diff --git a/spec/gist_tag_spec.rb b/spec/gist_tag_spec.rb index e10b177..7c15361 100644 --- a/spec/gist_tag_spec.rb +++ b/spec/gist_tag_spec.rb @@ -9,6 +9,7 @@ doc.output = Jekyll::Renderer.new(doc.site, doc).run end + before_each { ENV["JEKYLL_GITHUB_TOKEN"] = nil } context "valid gist" do context "with user prefix" do @@ -18,7 +19,7 @@ it "produces the correct script tag" do expect(output).to match(/