staticql
Version:
Type-safe query engine for static content including Markdown, YAML, JSON, and more.
52 lines (51 loc) • 1.73 kB
JavaScript
export class GitHubDiffProvider {
constructor(options) {
this.repo = options.repo;
this.token = options.token;
}
get headers() {
const headers = {
Accept: "application/vnd.github.v3+json",
};
if (this.token) {
headers.Authorization = `token ${this.token}`;
}
return headers;
}
async diffLines(baseRef, headRef) {
const url = `https://api.github.com/repos/${this.repo}/compare/${baseRef}...${headRef}`;
const res = await fetch(url, { headers: this.headers });
const data = await res.json();
if (!res.ok) {
throw new Error(`GitHub API error fetching diff compare: ${(data && data.message) || res.status}`);
}
if (!Array.isArray(data.files)) {
return [];
}
const statusMap = {
added: "A",
removed: "D",
modified: "M",
};
return data.files
.filter((file) => ["added", "removed", "modified"].includes(file.status))
.map((file) => ({
status: statusMap[file.status],
path: file.filename,
}));
}
async gitShow(rev, filePath) {
const url = `https://api.github.com/repos/${this.repo}/contents/${filePath}?ref=${rev}`;
const headers = {
Accept: "application/vnd.github.v3.raw",
};
if (this.token) {
headers.Authorization = `token ${this.token}`;
}
const res = await fetch(url, { headers });
if (!res.ok) {
throw new Error(`GitHub API error fetching file ${filePath}@${rev}: ${res.status}`);
}
return await res.text();
}
}