简体   繁体   English

通过REST API更新Github个文件

[英]Update Github files through the REST API

I'm working on a personal website builder.我正在开发个人网站构建器。 My goal is to be able to manipulate my page within the browser and then hit a 'Publish' button and have the new HTML file to be committed to the Github repository where my code is hosted.我的目标是能够在浏览器中操作我的页面,然后点击“发布”按钮并将新的 HTML 文件提交到托管我的代码的 Github 存储库。

I've been able to figure out everything up to generating the updated HTML. However, after going through the GitHub documentation I could not really understand how files should be processed prior or committed to the repository using the API. Could someone please help me out?我已经能够弄清楚生成更新的 HTML 之前的所有内容。但是,在阅读 GitHub 文档之后,我无法真正理解如何在使用 API 之前处理文件或将文件提交到存储库。有人可以帮我吗?

PS: I'd be using JavaScript to generate the HTML and for API calls. PS:我将使用JavaScript生成 HTML 和 API 调用。 Also if there is a better method to achieve my goal I'm open to those too.此外,如果有更好的方法来实现我的目标,我也愿意接受。

Use GitHub API v3 Repository Content endpoints使用GitHub API v3 存储库内容端点

You need to take into account the following:您需要考虑以下因素:

Here is a working example with Node.js with Octokit API using createOrUpdateFileContents method.这是一个使用createOrUpdateFileContents方法的 Node.js 和 Octokit API 的工作示例。 Read more about it here 在这里阅读更多相关信息

This endpoint will create a new commit with the new file content, you can even specify the committer and the author.此端点将使用新文件内容创建新提交,您甚至可以指定提交者和作者。

Update File Content in GitHub GitHub更新文件内容 View in Fusebit 在 Fusebit 中查看
// 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_sha = await getFileShaIfExists(octokit, owner, repo, path);
const fileContent = await octokit.rest.repos.createOrUpdateFileContents({
   owner,
   repo,
   path,
   sha: file_sha,
   message: 'This is the commit message generated via GitHub API',
   content,
   committer: {
     name: 'demo',
     email: 'demo@example.com'
   },
   author: {
     name: 'demo',
     email: 'demo@example.com'
   }
 });

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM