|
| 1 | +import * as childProcess from "child_process"; |
| 2 | +import * as fs from "fs"; |
| 3 | +import * as path from "path"; |
| 4 | + |
| 5 | +const FILE_HISTORY_AUTHOR_NAME = "DeepCode Checkpoint"; |
| 6 | +const FILE_HISTORY_AUTHOR_EMAIL = "deepcode-checkpoint@localhost"; |
| 7 | + |
| 8 | +export class GitFileHistory { |
| 9 | + constructor( |
| 10 | + private readonly projectRoot: string, |
| 11 | + private readonly gitDir: string |
| 12 | + ) {} |
| 13 | + |
| 14 | + ensureSession(sessionId: string): string | undefined { |
| 15 | + const branchRef = this.getSessionBranchRef(sessionId); |
| 16 | + if (!branchRef) { |
| 17 | + return undefined; |
| 18 | + } |
| 19 | + |
| 20 | + try { |
| 21 | + if (!fs.existsSync(this.gitDir)) { |
| 22 | + fs.mkdirSync(path.dirname(this.gitDir), { recursive: true }); |
| 23 | + this.runGit(["init"], { includeWorkTree: true }); |
| 24 | + } |
| 25 | + |
| 26 | + const current = this.getCurrentCheckpointHash(sessionId); |
| 27 | + if (current) { |
| 28 | + return current; |
| 29 | + } |
| 30 | + |
| 31 | + const emptyTree = this.runGit(["mktree"], { includeWorkTree: false, input: "" }).trim(); |
| 32 | + const commitHash = this.createCommit(emptyTree, null, "Initial checkpoint"); |
| 33 | + this.runGit(["update-ref", branchRef, commitHash], { includeWorkTree: false }); |
| 34 | + return commitHash; |
| 35 | + } catch { |
| 36 | + return undefined; |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + getCurrentCheckpointHash(sessionId: string): string | undefined { |
| 41 | + const branchRef = this.getSessionBranchRef(sessionId); |
| 42 | + if (!branchRef || !fs.existsSync(this.gitDir)) { |
| 43 | + return undefined; |
| 44 | + } |
| 45 | + |
| 46 | + try { |
| 47 | + const hash = this.runGit(["rev-parse", "--verify", `${branchRef}^{commit}`], { |
| 48 | + includeWorkTree: false, |
| 49 | + }).trim(); |
| 50 | + return isCommitHash(hash) ? hash : undefined; |
| 51 | + } catch { |
| 52 | + return undefined; |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + recordCheckpoint(sessionId: string, filePaths: string[], message: string): string | undefined { |
| 57 | + const branchRef = this.getSessionBranchRef(sessionId); |
| 58 | + if (!branchRef) { |
| 59 | + return undefined; |
| 60 | + } |
| 61 | + |
| 62 | + const relativePaths = filePaths |
| 63 | + .map((filePath) => this.toProjectRelativeGitPath(filePath)) |
| 64 | + .filter((filePath): filePath is string => Boolean(filePath)); |
| 65 | + if (relativePaths.length === 0) { |
| 66 | + return this.getCurrentCheckpointHash(sessionId); |
| 67 | + } |
| 68 | + |
| 69 | + try { |
| 70 | + const parentHash = this.ensureSession(sessionId); |
| 71 | + if (!parentHash) { |
| 72 | + return undefined; |
| 73 | + } |
| 74 | + this.runGit(["read-tree", "--reset", branchRef], { includeWorkTree: true }); |
| 75 | + this.runGit(["add", "-f", "-A", "--", ...relativePaths], { includeWorkTree: true }); |
| 76 | + const treeHash = this.runGit(["write-tree"], { includeWorkTree: false }).trim(); |
| 77 | + const parentTreeHash = this.runGit(["rev-parse", `${parentHash}^{tree}`], { |
| 78 | + includeWorkTree: false, |
| 79 | + }).trim(); |
| 80 | + if (treeHash === parentTreeHash) { |
| 81 | + return parentHash; |
| 82 | + } |
| 83 | + |
| 84 | + const commitHash = this.createCommit(treeHash, parentHash, message); |
| 85 | + this.runGit(["update-ref", branchRef, commitHash, parentHash], { includeWorkTree: false }); |
| 86 | + return commitHash; |
| 87 | + } catch { |
| 88 | + return undefined; |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + canRestore(sessionId: string, checkpointHash: string): boolean { |
| 93 | + if (!isCommitHash(checkpointHash)) { |
| 94 | + return false; |
| 95 | + } |
| 96 | + if (!this.getSessionBranchRef(sessionId)) { |
| 97 | + return false; |
| 98 | + } |
| 99 | + if (!fs.existsSync(this.gitDir)) { |
| 100 | + return false; |
| 101 | + } |
| 102 | + |
| 103 | + try { |
| 104 | + this.runGit(["cat-file", "-e", `${checkpointHash}^{commit}`], { includeWorkTree: false }); |
| 105 | + return true; |
| 106 | + } catch { |
| 107 | + return false; |
| 108 | + } |
| 109 | + } |
| 110 | + |
| 111 | + restore(sessionId: string, checkpointHash: string): void { |
| 112 | + if (!isCommitHash(checkpointHash)) { |
| 113 | + throw new Error("Invalid checkpoint hash."); |
| 114 | + } |
| 115 | + const branchRef = this.getSessionBranchRef(sessionId); |
| 116 | + if (!branchRef || !fs.existsSync(this.gitDir)) { |
| 117 | + throw new Error("File history Git repository was not found for this project."); |
| 118 | + } |
| 119 | + this.runGit(["cat-file", "-e", `${checkpointHash}^{commit}`], { includeWorkTree: false }); |
| 120 | + |
| 121 | + try { |
| 122 | + this.runGit(["read-tree", "--reset", branchRef], { includeWorkTree: true }); |
| 123 | + } catch { |
| 124 | + // If the session branch is missing, fall back to the target tree only. |
| 125 | + // The target checkpoint has already been validated above. |
| 126 | + } |
| 127 | + this.runGit(["read-tree", "--reset", "-u", checkpointHash], { includeWorkTree: true }); |
| 128 | + this.runGit(["update-ref", branchRef, checkpointHash], { includeWorkTree: false }); |
| 129 | + } |
| 130 | + |
| 131 | + private getSessionBranchRef(sessionId: string): string | null { |
| 132 | + if (!/^[A-Za-z0-9._-]+$/.test(sessionId)) { |
| 133 | + return null; |
| 134 | + } |
| 135 | + return `refs/heads/${sessionId}`; |
| 136 | + } |
| 137 | + |
| 138 | + private createCommit(treeHash: string, parentHash: string | null, message: string): string { |
| 139 | + const args = ["commit-tree", treeHash]; |
| 140 | + if (parentHash) { |
| 141 | + args.push("-p", parentHash); |
| 142 | + } |
| 143 | + args.push("-m", message); |
| 144 | + return this.runGit(args, { |
| 145 | + includeWorkTree: false, |
| 146 | + env: getFileHistoryGitEnv(), |
| 147 | + }).trim(); |
| 148 | + } |
| 149 | + |
| 150 | + private toProjectRelativeGitPath(filePath: string): string | null { |
| 151 | + const absolutePath = path.resolve(filePath); |
| 152 | + const relativePath = path.relative(this.projectRoot, absolutePath); |
| 153 | + if (!relativePath || relativePath.startsWith("..") || path.isAbsolute(relativePath)) { |
| 154 | + return null; |
| 155 | + } |
| 156 | + return relativePath.split(path.sep).join("/"); |
| 157 | + } |
| 158 | + |
| 159 | + private runGit( |
| 160 | + args: string[], |
| 161 | + options: { includeWorkTree: boolean; input?: string; env?: NodeJS.ProcessEnv } |
| 162 | + ): string { |
| 163 | + const gitArgs = ["-c", "core.autocrlf=false", "-c", "core.eol=lf", `--git-dir=${this.gitDir}`]; |
| 164 | + if (options.includeWorkTree) { |
| 165 | + gitArgs.push(`--work-tree=${this.projectRoot}`); |
| 166 | + } |
| 167 | + gitArgs.push(...args); |
| 168 | + const result = childProcess.spawnSync("git", gitArgs, { |
| 169 | + encoding: "utf8", |
| 170 | + input: options.input, |
| 171 | + env: options.env, |
| 172 | + stdio: ["pipe", "pipe", "pipe"], |
| 173 | + }); |
| 174 | + if (result.status !== 0) { |
| 175 | + const detail = (result.stderr || result.stdout || "").trim(); |
| 176 | + throw new Error(detail || `git ${args.join(" ")} failed`); |
| 177 | + } |
| 178 | + return result.stdout ?? ""; |
| 179 | + } |
| 180 | +} |
| 181 | + |
| 182 | +function getFileHistoryGitEnv(): NodeJS.ProcessEnv { |
| 183 | + return { |
| 184 | + ...process.env, |
| 185 | + GIT_AUTHOR_NAME: process.env.GIT_AUTHOR_NAME || FILE_HISTORY_AUTHOR_NAME, |
| 186 | + GIT_AUTHOR_EMAIL: process.env.GIT_AUTHOR_EMAIL || FILE_HISTORY_AUTHOR_EMAIL, |
| 187 | + GIT_COMMITTER_NAME: process.env.GIT_COMMITTER_NAME || FILE_HISTORY_AUTHOR_NAME, |
| 188 | + GIT_COMMITTER_EMAIL: process.env.GIT_COMMITTER_EMAIL || FILE_HISTORY_AUTHOR_EMAIL, |
| 189 | + }; |
| 190 | +} |
| 191 | + |
| 192 | +function isCommitHash(value: string): boolean { |
| 193 | + return /^[0-9a-f]{40}$/i.test(value); |
| 194 | +} |
0 commit comments