lukeonline - src/lib/repos.ts
import fs from 'node:fs'
import path from 'node:path'
const reposRoot = path.join(process.cwd(), 'src/content/repos')
export interface Repo {
name: string
head: string
defaultBranch: string
branches: string[]
tags: string[]
commitCount: number
}
export interface Commit {
sha: string
shortSha: string
parents: string[]
author: {
name: string
email: string
}
date: string
message: string
}
export interface RepoFile {
path: string
mode: string
type: string
sha: string
}
export function getCommits(name: string): Commit[] {
const file = path.join(reposRoot, name, 'commits.json')
return JSON.parse(fs.readFileSync(file, 'utf-8'))
}
export function getTree(name: string): RepoFile[] {
const file = path.join(reposRoot, name, 'tree.json')
return JSON.parse(fs.readFileSync(file, 'utf-8'))
}
export function getCommit(name: string, sha: string) {
const file = path.join(reposRoot, name, 'commits', `${sha}.json`)
return JSON.parse(fs.readFileSync(file, 'utf-8'))
}
export function getFile(name: string, encodedPath: string) {
const file = path.join(reposRoot, name, 'files', `${encodedPath}.json`)
return JSON.parse(fs.readFileSync(file, 'utf-8'))
}
export function getFileByPath(name: string, filePath: string) {
const encodedPath = Buffer.from(filePath, 'utf-8').toString('base64url')
return getFile(name, encodedPath)
}
export function getDirectoryChildren(tree: RepoFile[], directory: string) {
const prefix = directory ? `${directory}/` : ''
const directories = new Set<string>()
const files = new Set<string>()
for (const file of tree) {
if (!file.path.startsWith(prefix)) {
continue
}
const remaining = file.path.slice(prefix.length)
const child = remaining.split('/')[0]
if (remaining.includes('/')) {
directories.add(child)
} else {
files.add(child)
}
}
return {
directories: [...directories].sort(),
files: [...files].sort(),
}
}
export function encodeFilePath(filePath: string) {
return Buffer.from(filePath, 'utf-8').toString('base64url')
}
export function decodeFilePath(encodedPath: string) {
return Buffer.from(encodedPath, 'base64url').toString('utf-8')
}