Created
September 22, 2011 23:31
-
-
Save testcollab/1236348 to your computer and use it in GitHub Desktop.
Editing a File via the GitHub API v3
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 'editor.rb' | |
ed = Editor.new('testcollab/rails-test') | |
if ed.update_file('README.txt', 'my message', 'my new content') | |
ed.set_author('Scott', 'schacon@gmail.com') | |
ed.update_file('README.2.txt', 'my message', 'my new content') | |
end |
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 'rubygems' | |
require 'httparty' | |
require 'json' | |
class Editor | |
include HTTParty | |
attr_accessor :repo, :branch, :author | |
base_uri 'https://api.github.com' | |
basic_auth USER, PASS | |
default_params :output => 'json' | |
format :json | |
def initialize(repo, branch = 'master') | |
@repo = repo | |
@branch = branch | |
@author = false | |
end | |
def set_author(name, email) | |
@author = {'name' => name, 'email' => email} | |
end | |
def update_file(file, message, content) | |
last_commit_sha = last_commit # get last commit | |
last_tree = tree_for(last_commit_sha) # get base tree | |
tree_sha = create_tree(file, content, last_tree) # create new tree | |
new_commit_sha = create_commit(message, tree_sha, last_commit_sha) # create new commit | |
update_branch(new_commit_sha) # update reference | |
end | |
private | |
def last_commit | |
Editor.get("/repos/#{@repo}/git/refs/heads/#{@branch}").parsed_response['object']['sha'] | |
end | |
def tree_for(commit_sha) | |
Editor.get("/repos/#{@repo}/git/commits/#{commit_sha}").parsed_response['tree']['sha'] | |
end | |
def create_tree(file, content, last_tree) | |
new_tree = { | |
"base_tree" => last_tree, | |
"tree" => [{"path" => file, "mode" => "100644", "type" => "blob", "content" => content}] | |
} | |
Editor.post("/repos/#{@repo}/git/trees", :body => new_tree.to_json).parsed_response['sha'] | |
end | |
def create_commit(message, tree_sha, parent) | |
commit = { 'message' => message, 'parents' => [parent], 'tree' => tree_sha } | |
if @author | |
commit['author'] = @author | |
end | |
Editor.post("/repos/#{@repo}/git/commits", :body => commit.to_json).parsed_response['sha'] | |
end | |
def update_branch(new) | |
ref = {'sha' => new} | |
post = Editor.post("/repos/#{@repo}/git/refs/heads/#{@branch}", :body => ref.to_json) | |
post.headers['status'] == '200 OK' | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment