Skip to content

Instantly share code, notes, and snippets.

@yaodong
Last active November 24, 2015 16:56
Show Gist options
  • Save yaodong/213fd4b30d78c45d13b6 to your computer and use it in GitHub Desktop.
Save yaodong/213fd4b30d78c45d13b6 to your computer and use it in GitHub Desktop.
Rename file use Github API
master_ref = client.ref(repo, 'heads/master')
last_commit = client.commit(repo, master_ref[:object][:sha])
last_tree = client.tree(repo, last_commit[:sha], recursive: true)
changed_tree = last_tree[:tree].map(&:to_hash).reject { |blob| blob[:type] == 'tree' }
changed_tree.each { |blob| blob[:path] = 'History.markdown-2' if blob[:path] == 'History.markdown' }
changed_tree.each { |blob| blob.delete(:url) && blob.delete(:size) }
new_tree = client.create_tree(repo, changed_tree)
new_commit = client.create_commit(repo, 'move file test', new_tree[:sha], last_commit[:sha])
client.update_ref(repo, 'heads/master', new_commit.sha)
# References:
#
# http://www.levibotelho.com/development/commit-a-file-with-the-github-api/
# https://github.com/michael/github/blob/fac19118d73193e8dd1a66f8d8d11af4eda2fd71/github.js
master_ref = client.ref(repo, 'heads/master')
last_commit = client.commit(repo, master_ref[:object][:sha])
last_tree = client.tree(repo, last_commit[:sha], recursive: true)
changed_tree = last_tree[:tree].map(&:to_hash).reject { |blob| blob[:type] == 'tree' }
changed_tree.each { |blob| blob[:path] = 'History.markdown-5' if blob[:path] == 'History.markdown-4' }
changed_tree.each { |blob| blob.delete(:url) && blob.delete(:size) }
tree_for_rename = client.create_tree(repo, changed_tree)
blob_sha = client.create_blob(repo, Base64.encode64('## HEAD'), 'base64')
mod_tree = client.create_tree(repo, [ { :path => 'History.markdown-5', :mode => "100644", :type => "blob", :sha => blob_sha } ], {:base_tree => tree_for_rename[:sha] })
new_commit = client.create_commit(repo, 'move file test', mod_tree[:sha], last_commit[:sha])
client.update_ref(repo, 'heads/master', new_commit.sha)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment