使用 github api 重命名文件?

Rename a file with github api?

我认为 Github API 的 update file 方法可用于重命名文件(通过提供新路径作为参数)但它似乎不起作用.

重命名的唯一方法是删除文件并使用新名称创建一个类似的文件吗?

I thought that the update file method of the Github API could be used to rename a file (by providing the new path as parameter) but it does not seem to work.

无法通过 API 的单个请求重命名文件。

The only way to rename is to delete the file and to create a similar one with the new name?

这是一种方式,但缺点是您会在历史记录中获得两次提交(一次用于删除,一次用于创建)。

另一种方法是使用低级 Git API:

https://developer.github.com/v3/git/

有了它,您可以修改包含 blob 的树条目以将其列在不同的名称下,然后为该树创建一个新提交,最后更新分支以指向该新提交。整个过程需要更多 API 个请求,但您只获得一次重命名提交。

在以下文章的帮助下,我弄清楚了如何使用 Github API.

重命名文件

首先,找到并存储最新提交的树。

# Gem octokir.rb 4.2.0 and Github API v3
api = Octokit::Client.new(access_token: "")
ref = 'heads/master'
repo = 'repo/name'
master_ref = api.ref repo, ref
last_commit = api.commit(repo, master_ref[:object][:sha])
last_tree = api.tree(repo, last_commit[:sha], recursive: true)

使用文章中描述的更难的方法使用 GitHub API 创建一棵新树。然后,像 nodeJs 版本会根据以下更改创建新树。

changed_tree = last_tree[:tree].map(&:to_hash).reject { |blob| blob[:type] == 'tree' }
changed_tree.each { |blob| blob[:path] = new_name if blob[:path] == old_name }
changed_tree.each { |blob| blob.delete(:url) && blob.delete(:size) }
new_tree = api.create_tree(repo, changed_tree)

创建一个新提交然后将 HEAD 指向它。

new_commit = api.create_commit(repo, "Rename #{File.basename(old_name)} to #{File.basename(new_name)}", new_tree[:sha], last_commit[:sha])
api.update_ref(repo, ref, new_commit.sha)

就这些了。

对于那些最终在这里寻找更多选择的人来说,有一个更好的方法来重命名 file/folder。请参考以下link: Rename a file using GitHub api

也适用于文件夹重命名。在那里,您需要使用与上面 link.

示例请求中相同的有效负载结构来指定新旧文件夹路径