hunk summaries are now fetched from the api with local storage cache based on hunk hash

This commit is contained in:
Kiril Videlov 2023-06-20 12:48:58 +02:00 committed by Kiril Videlov
parent ade9bc6de0
commit a4f2d4604d
2 changed files with 43 additions and 1 deletions

39
src/lib/summaries.ts Normal file
View File

@ -0,0 +1,39 @@
import { get, writable } from '@square/svelte-store';
import { browser } from '$app/environment';
import { CloudApi } from '$lib/api';
const cloud = CloudApi();
export const store = writable<Map<string, string>>(
(browser && new Map(Object.entries(JSON.parse(localStorage.getItem('hunkSummaries') || '{}')))) ||
new Map<string, string>()
);
store.subscribe((val: Map<string, string>) => {
if (browser) {
localStorage.setItem('hunkSummaries', JSON.stringify(Object.fromEntries(val)));
}
});
export async function summarizeHunk(diff: string): Promise<string> {
const cache = get(store);
const diffHash = hash(diff);
if (cache.has(diffHash)) {
return cache.get(diffHash) as string;
}
const rsp = await cloud.summarize.hunk({ hunk: diff });
cache.set(diffHash, rsp.message);
store.set(cache);
return rsp.message;
}
function hash(s: string) {
let h = 0;
let i = s.length;
while (i > 0) {
h = ((h << 5) - h + s.charCodeAt(--i)) | 0;
}
return h.toString();
}

View File

@ -5,6 +5,7 @@
import type { DndEvent } from 'svelte-dnd-action/typings';
import type { Hunk } from './types';
import HunkDiffViewer from './HunkDiffViewer.svelte';
import { summarizeHunk } from '$lib/summaries';
export let filepath: string;
export let hunks: Hunk[];
@ -86,7 +87,9 @@
class="changed-hunk flex w-full flex-col gap-1 rounded-sm border border-light-500 dark:border-dark-500"
>
<div class="w-full text-ellipsis p-2">
{hunk.name}
{#await summarizeHunk(hunk.diff) then description}
{description}
{/await}
</div>
<div
class="cursor-pointer border-t border-b border-light-700 text-sm dark:border-dark-800"