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.
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?
PS: I'd be using JavaScript to generate the HTML and for API calls. Also if there is a better method to achieve my goal I'm open to those too.
Use GitHub API v3 Repository Content endpoints
You need to take into account the following:
Here is a working example with Node.js with Octokit API using createOrUpdateFileContents method. 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 | View in 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}`);