Elffuss BraidHub

kikocis/continue public

3ff29c567dd0 · 1.9 KiBRawPermalink
1import { IDE } from "../..";
2
3type GetDiffFn = () => Promise<string[]>;
4
5export class GitDiffCache {
6 private static instance: GitDiffCache | null = null;
7 private cachedDiff: string[] | undefined = undefined;
8 private lastFetchTime: number = 0;
9 private pendingRequest: Promise<string[]> | null = null;
10 private getDiffFn: GetDiffFn;
11 private cacheTimeMs: number;
12
13 private constructor(getDiffFn: GetDiffFn, cacheTimeSeconds: number = 60) {
14 this.getDiffFn = getDiffFn;
15 this.cacheTimeMs = cacheTimeSeconds * 1000;
16 }
17
18 public static getInstance(
19 getDiffFn: GetDiffFn,
20 cacheTimeSeconds?: number,
21 ): GitDiffCache {
22 if (!GitDiffCache.instance) {
23 GitDiffCache.instance = new GitDiffCache(getDiffFn, cacheTimeSeconds);
24 }
25 return GitDiffCache.instance;
26 }
27
28 private async getDiffPromise(): Promise<string[]> {
29 try {
30 const diff = await this.getDiffFn();
31 this.cachedDiff = diff;
32 this.lastFetchTime = Date.now();
33 return this.cachedDiff;
34 } catch (e) {
35 console.error("Error fetching git diff:", e);
36 return [];
37 } finally {
38 this.pendingRequest = null;
39 }
40 }
41
42 public async get(): Promise<string[]> {
43 if (
44 this.cachedDiff !== undefined &&
45 Date.now() - this.lastFetchTime < this.cacheTimeMs
46 ) {
47 return this.cachedDiff;
48 }
49
50 // If there's already a request in progress, return that instead of starting a new one
51 if (this.pendingRequest) {
52 return this.pendingRequest;
53 }
54
55 this.pendingRequest = this.getDiffPromise();
56 return this.pendingRequest;
57 }
58
59 public invalidate(): void {
60 this.cachedDiff = undefined;
61 this.pendingRequest = null;
62 }
63}
64
65// factory to make diff cache more testable
66export function getDiffFn(ide: IDE): GetDiffFn {
67 return () => ide.getDiff(true);
68}
69
70export async function getDiffsFromCache(ide: IDE): Promise<string[]> {
71 const diffCache = GitDiffCache.getInstance(getDiffFn(ide));
72 return await diffCache.get();
73}