summaryrefslogtreecommitdiff
path: root/packages/core/src/services/gitService.ts
blob: 8cd6b887f2f7b24cbc92c51aa35b7a760afa5007 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import * as fs from 'fs/promises';
import * as path from 'path';
import { isNodeError } from '../utils/errors.js';
import { isGitRepository } from '../utils/gitUtils.js';
import { exec } from 'node:child_process';
import { simpleGit, SimpleGit, CheckRepoActions } from 'simple-git';

export const historyDirName = '.gemini_cli_history';

export class GitService {
  private projectRoot: string;

  constructor(projectRoot: string) {
    this.projectRoot = path.resolve(projectRoot);
  }

  async initialize(): Promise<void> {
    if (!isGitRepository(this.projectRoot)) {
      throw new Error('GitService requires a Git repository');
    }
    const gitAvailable = await this.verifyGitAvailability();
    if (!gitAvailable) {
      throw new Error('GitService requires Git to be installed');
    }
    this.setupHiddenGitRepository();
  }

  verifyGitAvailability(): Promise<boolean> {
    return new Promise((resolve) => {
      exec('git --version', (error) => {
        if (error) {
          resolve(false);
        } else {
          resolve(true);
        }
      });
    });
  }

  /**
   * Creates a hidden git repository in the project root.
   * The Git repository is used to support checkpointing.
   */
  async setupHiddenGitRepository() {
    const historyDir = path.join(this.projectRoot, historyDirName);
    const repoDir = path.join(historyDir, 'repository');

    await fs.mkdir(repoDir, { recursive: true });
    const repoInstance: SimpleGit = simpleGit(repoDir);
    const isRepoDefined = await repoInstance.checkIsRepo(
      CheckRepoActions.IS_REPO_ROOT,
    );
    if (!isRepoDefined) {
      await repoInstance.init();
      try {
        await repoInstance.raw([
          'worktree',
          'add',
          this.projectRoot,
          '--force',
        ]);
      } catch (error) {
        console.log('Failed to add worktree:', error);
      }
    }

    const visibileGitIgnorePath = path.join(this.projectRoot, '.gitignore');
    const hiddenGitIgnorePath = path.join(repoDir, '.gitignore');

    let visibileGitIgnoreContent = ``;
    try {
      visibileGitIgnoreContent = await fs.readFile(
        visibileGitIgnorePath,
        'utf-8',
      );
    } catch (error) {
      if (isNodeError(error) && error.code !== 'ENOENT') {
        throw error;
      }
    }

    await fs.writeFile(hiddenGitIgnorePath, visibileGitIgnoreContent);

    if (!visibileGitIgnoreContent.includes(historyDirName)) {
      const updatedContent = `${visibileGitIgnoreContent}\n# Gemini CLI history directory\n${historyDirName}\n`;
      await fs.writeFile(visibileGitIgnorePath, updatedContent);
    }

    const commit = await repoInstance.raw([
      'rev-list',
      '--all',
      '--max-count=1',
    ]);
    if (!commit) {
      await repoInstance.add(hiddenGitIgnorePath);

      await repoInstance.commit('Initial commit');
    }
  }

  private get hiddenGitRepository(): SimpleGit {
    const historyDir = path.join(this.projectRoot, historyDirName);
    const repoDir = path.join(historyDir, 'repository');
    return simpleGit(this.projectRoot).env({
      GIT_DIR: path.join(repoDir, '.git'),
      GIT_WORK_TREE: this.projectRoot,
    });
  }

  async getCurrentCommitHash(): Promise<string> {
    const hash = await this.hiddenGitRepository.raw('rev-parse', 'HEAD');
    return hash.trim();
  }

  async createFileSnapshot(message: string): Promise<string> {
    const repo = this.hiddenGitRepository;
    await repo.add('.');
    const commitResult = await repo.commit(message);
    return commitResult.commit;
  }

  async restoreProjectFromSnapshot(commitHash: string): Promise<void> {
    const repo = this.hiddenGitRepository;
    await repo.raw(['restore', '--source', commitHash, '.']);
  }
}