gpt4 book ai didi

javascript - 通过 REST API 更新 Github 文件

转载 作者:行者123 更新时间:2023-12-03 08:10:16 27 4
gpt4 key购买 nike

我正在开发个人网站构建器。 我的目标是能够在浏览器中操作我的页面,然后点击“发布”按钮并将新的 HTML 文件提交到托管我的代码的 Github 存储库。

我已经能够弄清楚生成更新的 HTML 之前的所有事情。然而,在浏览完 GitHub 文档后,我无法真正理解如何使用 API 在存储库之前处理文件或将文件提交到存储库。有人可以帮我吗?

PS:我将使用 JavaScript 生成 HTML 并进行 API 调用。 此外,如果有更好的方法来实现我的目标,我也愿意接受。

最佳答案

使用GitHub API v3 Repository Content endpoints

您需要考虑以下因素:

  • 文件内容应采用 Base64 编码。
  • 如果文件已经存在,您需要提供该文件的blob SHA,您可以通过 Get repository content endpoint 获取.

这是一个使用 Node.js 和 Octokit API 使用 createOrUpdateFileContents 方法的工作示例。了解更多相关信息here

此端点将使用新文件内容创建一个新的提交,您甚至可以指定提交者和作者。

<表类=“s-表”><标题>更新 GitHub 中的文件内容                                                                                  View in Runme
// The content of the file should be base64
const content = Buffer.from(`Hello world at ${new Date().toUTCString()}`, 'utf8').toString('base64');

// If the file already exists, you need to provide the sha in order to update the file content.
const file = await octokit.rest.repos.getContent({
owner: owner,
repo: repo,
path: path,
branch: branch,
});
const { sha } = file.data;
const fileContent = await octokit.rest.repos.createOrUpdateFileContents({
owner,
repo,
path,
sha: sha,
message: 'This is the commit message generated via GitHub API',
content,
committer: {
name: 'demo',
email: '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ce8e9e1e3cce9f4ede1fce0e9a2efe3e1" rel="noreferrer noopener nofollow">[email protected]</a>'
},
author: {
name: 'demo',
email: '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="197d7c7476597c61787469757c377a7674" rel="noreferrer noopener nofollow">[email protected]</a>'
}
});

const { commit: { html_url } } = fileContent.data;

console.log(`Content updated, see changes at ${html_url}`);

关于javascript - 通过 REST API 更新 Github 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71054940/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com