Files
blitzkit/src/core/blitzkrieg/commitMultipleFiles.ts
T

100 lines
2.1 KiB
TypeScript
Raw Normal View History

2023-07-15 01:21:59 +00:00
import { Octokit } from '@octokit/rest';
2023-11-27 17:50:02 -06:00
const TIME_PER_BLOB = 2 ** 4 * 1000;
2023-11-27 16:52:38 -06:00
export interface FileChange {
path: string;
content: string;
encoding: 'utf-8' | 'base64';
}
export default async function commitMultipleFiles(
2023-07-15 01:21:59 +00:00
octokit: Octokit,
owner: string,
repo: string,
branch: string,
message: string,
2023-11-27 16:52:38 -06:00
changes: FileChange[],
2023-12-05 19:14:53 -06:00
verbose = false,
) {
2023-11-27 17:50:02 -06:00
const latestCommitSha = (
await octokit.git.getRef({
owner,
repo,
ref: `heads/${branch}`,
})
).data.object.sha;
const treeSha = (
await octokit.git.getCommit({
owner,
repo,
commit_sha: latestCommitSha,
})
).data.tree.sha;
const blobs: {
sha: string;
path: string;
mode: '100644';
type: 'blob';
}[] = [];
2023-07-15 01:21:59 +00:00
2023-11-27 17:50:02 -06:00
for (const changeIndexString in changes) {
const changeIndex = parseInt(changeIndexString);
const change = changes[changeIndex];
let done = false;
while (!done) {
try {
const { sha } = (
await octokit.git.createBlob({
owner,
repo,
content: change.content,
encoding: change.encoding,
})
).data;
blobs.push({ sha, path: change.path, mode: '100644', type: 'blob' });
done = true;
} catch (error) {
console.warn(
`Failed blob ${changeIndex + 1} / ${
changes.length
}; retrying in ${TIME_PER_BLOB}ms...`,
2023-12-05 19:14:53 -06:00
error,
2023-11-27 17:50:02 -06:00
);
await new Promise((resolve) => setTimeout(resolve, TIME_PER_BLOB));
}
}
2023-12-05 19:14:53 -06:00
if (verbose) {
2023-11-27 17:50:02 -06:00
console.log(
`Created blob ${changeIndex + 1} / ${changes.length} (${(
(100 * (changeIndex + 1)) /
changes.length
).toFixed(2)}%)`,
);
}
}
const { data: treeData } = await octokit.git.createTree({
owner,
repo,
base_tree: treeSha,
tree: blobs,
});
const { data: newCommitData } = await octokit.git.createCommit({
owner,
repo,
message,
tree: treeData.sha,
parents: [latestCommitSha],
});
await octokit.git.updateRef({
owner,
repo,
ref: `heads/${branch}`,
sha: newCommitData.sha,
});
}