Last active
March 20, 2023 03:21
How to remove a file from a subdirectory using 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
#!/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