返回 oh-my-ppt
html-editor-git.ts
根目录 / src / main / html-editor / html-editor-git.ts
1 import fs from 'fs'
2 import path from 'path'
3 import * as git from 'isomorphic-git'
4
5 const AUTHOR = { name: 'Oh My PPT HTML Editor', email: 'html-editor@oh-my-ppt.local' }
6
7 /** 确保 dir 下有 git 仓库(内容版本由 git 管理)。 */
8 export async function ensureHtmlRepo(dir: string): Promise<void> {
9 await fs.promises.mkdir(dir, { recursive: true })
10 const gitDir = path.join(dir, '.git')
11 if (!fs.existsSync(gitDir)) {
12 await git.init({ fs, dir, defaultBranch: 'main' })
13 await git.setConfig({ fs, dir, path: 'user.name', value: AUTHOR.name })
14 await git.setConfig({ fs, dir, path: 'user.email', value: AUTHOR.email })
15 }
16 }
17
18 export async function getHtmlRepoHead(dir: string): Promise<string> {
19 return git.resolveRef({ fs, dir, ref: 'HEAD' })
20 }
21
22 export async function restoreHtmlRepoHead(dir: string, commitSha: string): Promise<void> {
23 const currentBranchRef = await git.currentBranch({ fs, dir, fullname: true })
24 await git.writeRef({
25 fs,
26 dir,
27 ref: currentBranchRef || 'HEAD',
28 value: commitSha,
29 force: true
30 })
31 }
32
33 export async function restoreHtmlFileAtCommit(
34 dir: string,
35 filepath: string,
36 commitSha: string
37 ): Promise<void> {
38 await git.checkout({
39 fs,
40 dir,
41 ref: commitSha,
42 filepaths: [filepath],
43 noUpdateHead: true,
44 force: true
45 })
46 }
47
48 /** 提交 dir 下 filepath(相对路径)的当前内容,返回 commit sha。 */
49 export async function commitHtmlFile(
50 dir: string,
51 filepath: string,
52 message: string
53 ): Promise<string> {
54 await git.add({ fs, dir, filepath })
55 return git.commit({ fs, dir, message, author: AUTHOR })
56 }
57
58 /** 读取某 commit 下 filepath 的内容(用于恢复版本)。 */
59 export async function readHtmlAtCommit(
60 dir: string,
61 filepath: string,
62 oid: string
63 ): Promise<string> {
64 const { blob } = await git.readBlob({ fs, dir, oid, filepath })
65 return Buffer.from(blob).toString('utf-8')
66 }
67
67 lines TYPESCRIPT