Skip to content

Instantly share code, notes, and snippets.

@gjtorikian
Last active March 20, 2023 03:21
Show Gist options
  • Save gjtorikian/5208350 to your computer and use it in GitHub Desktop.
Save gjtorikian/5208350 to your computer and use it in GitHub Desktop.
How to remove a file from a subdirectory using the GitHub API v3
#!/usr/bin/env ruby
require 'octokit'
# !!! DO NOT EVER USE HARD-CODED VALUES IN A REAL APP !!!
login = ENV['GH_LOGIN']
password = ENV['GH_LOGIN_PASSWORD']
repo = "gjtorikian/crud-test"
master = client.ref(repo, "heads/master")
root_tree = client.tree(repo, master.object.sha)
subdir_name = "test"
# grab blob with matching subdir name
subdir_blob = root_tree.tree.detect { |blob| blob["path"] == subdir_name }
subdir_sha = subdir_blob.sha
# remove the requested file from that subdir's tree
removed_tree = client.tree(repo, subdir_sha).tree.reject {|blob| blob.path == "test.txt" }
# create a new subdir blob with the file removed
new_tree = client.create_tree(repo, removed_tree)
# with the magic of pass by reference, replace
# the root tree's subdir_blob sha with the newly created one
subdir_blob.sha = new_tree.sha
# create a new root tree (since we changed the subdir_blob)
new_root_tree = client.create_tree(repo, root_tree.tree)
# commit against master
new_commit = client.create_commit(repo, "Removing file from subdir", new_root_tree.sha, master.object.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