Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:bug: Show tagged snapshots in document snapshot history https://github.com/siyuan-note/siyuan/issues/19916

Daniel2f690e670adc
diff --git a/app/src/assets/scss/business/_history.scss b/app/src/assets/scss/business/_history.scss
index d7661d3200..795fb12684 100644
--- a/app/src/assets/scss/business/_history.scss
+++ b/app/src/assets/scss/business/_history.scss
@@ -43,6 +43,11 @@
flex-direction: column;
}
+ &__snapshot-detail-status {
+ padding: 12px 16px;
+ overflow-wrap: anywhere;
+ }
+
&__snapshot-detail-meta {
padding: 12px 16px;
max-height: 25vh;
diff --git a/app/src/history/doc.ts b/app/src/history/doc.ts
index b2c9856108..4a8dc0d38c 100644
--- a/app/src/history/doc.ts
+++ b/app/src/history/doc.ts
@@ -9,6 +9,7 @@ import * as dayjs from "dayjs";
import {fetchPost, fetchSyncPost} from "../util/fetch";
import {isMobile} from "../util/functions";
import type {App} from "../index";
+import type {APIPOSTRoutes, APITransportError} from "../types/api";
import {resizeSide} from "./resizeSide";
import {escapeHtml} from "../util/escape";
import {renderRepoFile, renderRepoFileList, rollbackRepoFile, saveRepoFile} from "./repoFile";
@@ -96,6 +97,7 @@ const renderRepo = async (element: HTMLElement, currentPage: number, id: string)
if (element.getAttribute("data-loading") === "true") {
return;
}
+ getDocHistorySnapshots(element)?.reset();
const previousElement = element.querySelector('[data-type="snapshotprevious"]');
const nextElement = element.querySelector('[data-type="snapshotnext"]');
const pageNumElement = element.querySelector('[data-type="jumpSnapshotPage"]');
@@ -115,19 +117,25 @@ const renderRepo = async (element: HTMLElement, currentPage: number, id: string)
nextElement.setAttribute("disabled", "disabled");
listElement.innerHTML = '<li style="position: relative;height: 100%;"><div class="fn__loading"><img width="64px" src="/stage/loading-pure.svg"></div></li>';
- let response: IWebSocketData;
+ let response: APIPOSTRoutes["/api/repo/getRepoDocHistory"]["response"] | APITransportError;
try {
response = await fetchSyncPost("/api/repo/getRepoDocHistory", {
id,
page: currentPage
});
} catch (e) {
+ if (!element.isConnected) {
+ return;
+ }
console.warn("get repo doc history failed", e);
element.removeAttribute("data-loading");
listElement.innerHTML = `${genCurrentVersionItem()}<li class="b3-list--empty">${window.siyuan.languages.emptyContent}</li>`;
element.dispatchEvent(new CustomEvent("versionListRendered"));
return;
}
+ if (!element.isConnected) {
+ return;
+ }
if (response.code !== 0) {
element.removeAttribute("data-loading");
listElement.innerHTML = `${genCurrentVersionItem()}<li class="b3-list--empty">${window.siyuan.languages.emptyContent}</li>`;
@@ -146,11 +154,14 @@ const renderRepo = async (element: HTMLElement, currentPage: number, id: string)
}
pageNumElement.setAttribute("data-totalpage", Math.max(pageCount, 1).toString());
pageInfoElement.textContent = window.siyuan.languages.pageCountAndSnapshotCount
- .replace("${x}", pageCount)
- .replace("${y}", response.data.totalCount);
+ .replace("${x}", String(pageCount))
+ .replace("${y}", String(response.data.totalCount));
pageInfoElement.classList.remove("fn__none");
renderRepoFileList(response.data.files, listElement, false, true);
listElement.insertAdjacentHTML("afterbegin", genCurrentVersionItem());
+ getDocHistorySnapshots(element)?.setEntries(response.data.files.map(file => ({
+ created: file.fileID, historyPath: "", snapshots: file.snapshots || []
+ })));
element.dispatchEvent(new CustomEvent("versionListRendered"));
};
@@ -257,6 +268,7 @@ export const openDocHistory = (options: {
destroyCallback() {
forgetNotebookHistoryDialog(dialog);
getDocHistorySnapshots(fileElement)?.destroy();
+ getDocHistorySnapshots(repoElement)?.destroy();
historyEditor?.destroy();
historyEditor = undefined;
repoHistoryEditors.get(repoElement)?.destroy();
@@ -307,6 +319,7 @@ export const openDocHistory = (options: {
const fileElement = dialog.element.querySelector('#docHistoryContainer [data-type="doc"]') as HTMLElement;
const historySnapshots = new DocHistorySnapshots(options.app, fileElement, options.id);
const repoElement = dialog.element.querySelector('#docHistoryContainer [data-type="repo"]') as HTMLElement;
+ const repoSnapshots = new DocHistorySnapshots(options.app, repoElement, options.id, options.notebookId);
fileElement.addEventListener("versionListRendered", syncVersionSelection);
repoElement.addEventListener("versionListRendered", syncVersionSelection);
const opElement = fileElement.querySelector(".b3-select") as HTMLSelectElement;
@@ -336,6 +349,7 @@ export const openDocHistory = (options: {
const pageNumElement = fileElement.querySelector('[data-type="jumpRepoPage"]');
const titleElement = fileElement.querySelector(".protyle-title__input");
const previewRepoFile = (element: Element) => {
+ repoSnapshots.select(element.getAttribute("data-id"));
repoHistoryEditors.get(repoElement)?.destroy();
repoHistoryEditors.delete(repoElement);
repoTitleElement.textContent = element.getAttribute("data-title") ||
@@ -428,6 +442,7 @@ export const openDocHistory = (options: {
break;
} else if (target.classList.contains("b3-list-item") && type === "currentVersionItem") {
historySnapshots.select("");
+ repoSnapshots.select("");
toggleVersionSelection(currentVersion);
event.stopPropagation();
event.preventDefault();
diff --git a/app/src/history/docSnapshots.test.ts b/app/src/history/docSnapshots.test.ts
index b56194c177..67786bfe10 100644
--- a/app/src/history/docSnapshots.test.ts
+++ b/app/src/history/docSnapshots.test.ts
@@ -5,7 +5,7 @@ import {join} from "node:path";
import {ScriptTarget, transpileModule} from "typescript";
import {escapeAttr, escapeHtml} from "../util/escape";
-const setup = () => {
+const setup = (notebook = "") => {
const source = readFileSync(join(__dirname, "docSnapshots.ts"), "utf8");
const code = source.slice(source.indexOf("const views =")).replace(/export /g, "");
const panel = {innerHTML: "", textContent: "", classList: {toggle() {}, add() {}}, setAttribute() {}, querySelector: (): HTMLElement | null => null};
@@ -21,6 +21,7 @@ const setup = () => {
const pending: ((response: unknown) => void)[] = [];
const signals: AbortSignal[] = [];
const opened: unknown[] = [];
+ const notebooks: string[] = [];
const dependencies = {
document: {createElement: () => panel},
window: {siyuan: {languages: {loading: "loading", historySnapshots: "snapshots", historySnapshotsError: "failed", retry: "retry"}}},
@@ -28,18 +29,33 @@ const setup = () => {
signals.push(signal);
return new Promise(resolve => pending.push(resolve));
},
- openSnapshotDetail: (_app: unknown, snapshot: unknown) => opened.push(snapshot),
+ openSnapshotDetail: (_app: unknown, snapshot: unknown, notebook: string) => { opened.push(snapshot); notebooks.push(notebook); },
escapeAttr, escapeHtml, dayjs: () => ({format: () => "date"}),
};
const View = new Function(...Object.keys(dependencies), transpileModule(code, {
compilerOptions: {target: ScriptTarget.ES2021},
}).outputText + "\nreturn DocHistorySnapshots;")(...Object.values(dependencies));
- return {view: new View({}, element, "doc"), panel, summary, pending, signals, opened, listeners, element};
+ return {view: new View({}, element, "doc", notebook), panel, summary, pending, signals, opened, notebooks, listeners, element};
};
const snapshot = (id: string) => ({id, fileID: "file", tags: ["<tag>"], memo: "<script>alert(1)</script>\nline", created: 1});
const response = (ids: string[]) => ({code: 0, data: {histories: [{created: "1", historyPath: "history/path", snapshots: ids.map(snapshot)}]}});
+it("renders repository version associations without querying file history and retains notebook context", () => {
+ const {view, panel, summary, pending, opened, notebooks, listeners} = setup("notebook");
+ view.setEntries([{created: "1", historyPath: "", snapshots: [snapshot("first"), snapshot("second")]}]);
+ view.select("1");
+ assert.equal(pending.length, 0);
+ assert.match(summary.innerHTML, /\+1/);
+ assert.match(panel.innerHTML, /snapshots \(2\)/);
+ listeners.click({target: {closest: () => ({hasAttribute: () => false, dataset: {historyCreated: "1", historySnapshot: "second"}})}, stopPropagation() {}});
+ assert.deepEqual(opened, [snapshot("second")]);
+ assert.deepEqual(notebooks, ["notebook"]);
+ view.reset();
+ view.setEntries([{created: "1", historyPath: "", snapshots: []}]);
+ assert.equal(summary.innerHTML, "");
+});
+
it("keeps all matching snapshots, escapes notes and opens the clicked snapshot", async () => {
const {view, panel, summary, pending, opened, listeners} = setup();
const loading = view.load(["1"], "all");
diff --git a/app/src/history/docSnapshots.ts b/app/src/history/docSnapshots.ts
index 4cdbe0c55a..796469f474 100644
--- a/app/src/history/docSnapshots.ts
+++ b/app/src/history/docSnapshots.ts
@@ -20,7 +20,7 @@ export class DocHistorySnapshots {
private abort?: AbortController;
private panel: HTMLElement;
- constructor(private app: App, private element: HTMLElement, private id: string) {
+ constructor(private app: App, private element: HTMLElement, private id: string, private notebook = "") {
views.set(element, this);
this.panel = document.createElement("section");
this.panel.className = "history__associations fn__none";
@@ -40,7 +40,7 @@ export class DocHistorySnapshots {
const entry = this.entries.get(target.dataset.historyCreated);
const snapshot = entry?.snapshots.find(item => item.id === target.dataset.historySnapshot);
if (snapshot) {
- void openSnapshotDetail(this.app, snapshot, entry.historyPath.split("/").filter(Boolean)[2]);
+ void openSnapshotDetail(this.app, snapshot, this.notebook || entry.historyPath.split("/").filter(Boolean)[2]);
}
});
}
@@ -66,6 +66,14 @@ export class DocHistorySnapshots {
this.renderPanel();
}
+ setEntries(entries: DocHistorySnapshotEntry[]) {
+ this.entries = new Map(entries.map(entry => [entry.created, entry]));
+ this.error = "";
+ this.loading = false;
+ this.renderSummaries();
+ this.renderPanel();
+ }
+
async load(created: string[], op: string) {
this.abort?.abort();
this.abort = new AbortController();
@@ -99,6 +107,11 @@ export class DocHistorySnapshots {
this.error = error instanceof Error ? error.message : String(error);
}
this.loading = false;
+ this.renderSummaries();
+ this.renderPanel();
+ }
+
+ private renderSummaries() {
this.element.querySelectorAll<HTMLElement>("[data-history-tags]").forEach(summary => {
const created = summary.dataset.historyTags;
const snapshots = this.entries.get(created)?.snapshots || [];
@@ -111,7 +124,6 @@ export class DocHistorySnapshots {
summary.innerHTML = "";
}
});
- this.renderPanel();
}
private renderPanel() {
diff --git a/app/src/history/repoFile.ts b/app/src/history/repoFile.ts
index 9e569f2670..daf7d7337f 100644
--- a/app/src/history/repoFile.ts
+++ b/app/src/history/repoFile.ts
@@ -32,7 +32,7 @@ export const renderRepoFileList = (files: IRepoFile[], element: Element, showPat
files.forEach((item) => {
if (showCompare) {
html += `<li class="b3-list-item b3-list-item--hide-action" data-type="searchFileItem" data-id="${item.fileID}" data-snapshot="${item.indexID}" data-created="${item.updated}" data-title="${escapeAttr(escapeHtml(item.title))}">
- <span class="b3-list-item__text">${dayjs(item.updated).format("YYYY-MM-DD HH:mm:ss")}</span>
+ <div class="fn__flex-1 fn__flex-column"><span class="b3-list-item__text">${dayjs(item.updated).format("YYYY-MM-DD HH:mm:ss")}</span><span data-history-tags="${escapeAttr(item.fileID)}"></span></div>
<span class="fn__space"></span>
<span class="b3-list-item__action b3-tooltips b3-tooltips__w" data-type="rollback" aria-label="${window.siyuan.languages.rollback}">
<svg><use xlink:href="#iconUndo"></use></svg>
diff --git a/app/src/history/snapshotDetail.ts b/app/src/history/snapshotDetail.ts
index 84fa38b4b4..4520c350ec 100644
--- a/app/src/history/snapshotDetail.ts
+++ b/app/src/history/snapshotDetail.ts
@@ -15,7 +15,7 @@ export const openSnapshotDetail = async (app: App, reference: DocHistorySnapshot
const abort = new AbortController();
const dialog = new Dialog({
title: escapeHtml(reference.tags.join(" / ")),
- content: `<div class="history__snapshot-detail"><div data-detail-status>${lang.loading}</div><div class="history__snapshot-detail-content fn__none"><div class="history__snapshot-detail-meta"></div><div class="history__snapshot-detail-panels"><ul class="b3-list b3-list--background history__snapshot-detail-files"></ul><div class="history__snapshot-detail-preview"></div></div></div></div>`,
+ content: `<div class="history__snapshot-detail"><div class="history__snapshot-detail-status" data-detail-status role="status">${lang.loading}</div><div class="history__snapshot-detail-content fn__none"><div class="history__snapshot-detail-meta"></div><div class="history__snapshot-detail-panels"><ul class="b3-list b3-list--background history__snapshot-detail-files"></ul><div class="history__snapshot-detail-preview"></div></div></div></div>`,
width: isMobile() ? "100vw" : "85vw",
height: isMobile() ? "100dvh" : "80vh",
containerClassName: "b3-dialog__container--theme",
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.ts
index 6dc5ff9d58..e796c632d4 100644
--- a/app/src/types/api/index.d.ts
+++ b/app/src/types/api/index.d.ts
@@ -1600,7 +1600,7 @@ export type RepoDiffFile = { "fileID": string; "hPath"?: string; "hSize": string
export type RepoDiffIndex = { "created": number; "id": string; };
-export type RepoDocHistory = { "fileID": string; "hSize": string; "indexID": string; "title": string; "updated": number; };
+export type RepoDocHistory = { "fileID": string; "hSize": string; "indexID": string; "snapshots": Array<DocHistorySnapshot | null> | null; "title": string; "updated": number; };
export type RepoDocHistoryData = { "files": Array<RepoDocHistory | null> | null; "pageCount": number; "totalCount": number; };
diff --git a/app/tests/historySnapshots.test.js b/app/tests/historySnapshots.test.js
index 60b4def6ca..faa4ea6aea 100644
--- a/app/tests/historySnapshots.test.js
+++ b/app/tests/historySnapshots.test.js
@@ -78,9 +78,16 @@ const runCases = async (sources, css, mobile, dark) => {
const history = new Dialog({title: "项目计划 - 文件历史", width: mobile ? "100vw" : "90vw", height: mobile ? "100dvh" : "80vh",
content: '<div class="history__repo fn__block" style="height:100%"><div class="fn__flex fn__flex-1 history__panel"><ul class="b3-list b3-list--background history__side" style="width:240px"><li class="b3-list-item b3-list-item--focus"><div class="fn__flex-1 fn__flex-column"><span class="b3-list-item__text">2026-09-28 09:00:00</span><span data-history-tags="1"></span></div></li></ul><div class="fn__flex-1 fn__flex-column"><div class="protyle-title__input">项目计划</div><textarea class="history__text fn__flex-1" readonly>原文件历史预览</textarea></div></div></div>'});
const root = history.element.querySelector(".history__repo");
- const view = new DocHistorySnapshots({}, root, "doc");
- await view.load(["1"], "all");
- view.select("1");
+ const view = new DocHistorySnapshots({}, root, "doc", "notebook");
+ if (dark) {
+ load("history/repoFile").renderRepoFileList([{fileID: "doc-file", indexID: snapshots[0].id, title: "项目计划", updated: 1790557200000, hSize: "1 KB"}], root.querySelector(".history__side"), false, true);
+ view.setEntries([{created: "doc-file", historyPath: "", snapshots}]);
+ view.select("doc-file");
+ assert.match(root.querySelector("[data-history-tags]").textContent, /发布版本/);
+ } else {
+ await view.load(["1"], "all");
+ view.select("1");
+ }
await tick();
const links = root.querySelectorAll(".history__association button");
assert.equal(links.length, 2);
@@ -126,6 +133,9 @@ const runCases = async (sources, css, mobile, dark) => {
responseMode = "pending";
links[0].click();
await tick();
+ const loading = window.siyuan.dialogs.at(-1).element.querySelector("[data-detail-status]");
+ assert.ok(parseFloat(getComputedStyle(loading).paddingLeft) >= 16, "loading status needs horizontal spacing");
+ assert.ok(parseFloat(getComputedStyle(loading).paddingTop) >= 12, "loading status needs vertical spacing");
closeNotebookHistoryDialogs("notebook");
await tick();
assert.ok(signal.aborted);
diff --git a/kernel/api/contract_history_snapshots_test.go b/kernel/api/contract_history_snapshots_test.go
index e200e1af74..9a7c49b743 100644
--- a/kernel/api/contract_history_snapshots_test.go
+++ b/kernel/api/contract_history_snapshots_test.go
@@ -87,6 +87,7 @@ func TestAPIContractDocHistorySnapshots(t *testing.T) {
const endpoint = "/api/history/getDocHistorySnapshots"
engine.POST(endpoint, getDocHistorySnapshots)
engine.POST("/api/repo/getRepoSnapshots", getRepoSnapshots)
+ engine.POST("/api/repo/getRepoDocHistory", getRepoDocHistory)
for _, include := range []bool{false, true} {
body, _ := json.Marshal(map[string]interface{}{"id": index.ID, "page": 1, "includeFiles": include})
recorder := httptest.NewRecorder()
@@ -136,4 +137,28 @@ func TestAPIContractDocHistorySnapshots(t *testing.T) {
}
}
}
+ for _, tagged := range []bool{true, false} {
+ if !tagged {
+ if err = repo.RemoveTag("release"); err != nil {
+ t.Fatal(err)
+ }
+ }
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", "/api/repo/getRepoDocHistory", strings.NewReader(`{"id":"`+id+`","page":1}`)))
+ requireAPIContract(t, "POST", "/api/repo/getRepoDocHistory", recorder)
+ var response struct {
+ Code int `json:"code"`
+ Data apicontract.RepoDocHistoryData `json:"data"`
+ }
+ if err = json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || response.Code != 0 || len(response.Data.Files) != 1 {
+ t.Fatalf("repository document history: %s, %v", recorder.Body.String(), err)
+ }
+ associations := response.Data.Files[0].Snapshots
+ if associations == nil || (len(associations) == 1) != tagged {
+ t.Fatalf("repository associations: %s", recorder.Body.String())
+ }
+ if tagged && (associations[0].ID != index.ID || associations[0].FileID != response.Data.Files[0].FileID || associations[0].Memo != "memo\nline" || associations[0].Tags[0] != "release") {
+ t.Fatalf("repository association metadata: %s", recorder.Body.String())
+ }
+ }
}
diff --git a/kernel/api/history_snapshots.go b/kernel/api/history_snapshots.go
index 9f376b0130..233bb81c6d 100644
--- a/kernel/api/history_snapshots.go
+++ b/kernel/api/history_snapshots.go
@@ -34,13 +34,18 @@ var getDocHistorySnapshots = contractHandler(apicontract.GetDocHistorySnapshots,
}
data := apicontract.DocHistorySnapshotsData{Histories: make([]*apicontract.DocHistorySnapshotEntry, 0, len(histories))}
for _, history := range histories {
- entry := &apicontract.DocHistorySnapshotEntry{Created: history.Created, HistoryPath: history.HistoryPath, Snapshots: []*apicontract.DocHistorySnapshot{}}
- for _, snapshot := range history.Snapshots {
- entry.Snapshots = append(entry.Snapshots, &apicontract.DocHistorySnapshot{
- ID: snapshot.ID, FileID: snapshot.FileID, Tags: snapshot.Tags, Memo: snapshot.Memo, Created: snapshot.Created,
- })
- }
+ entry := &apicontract.DocHistorySnapshotEntry{Created: history.Created, HistoryPath: history.HistoryPath, Snapshots: docHistorySnapshots(history.Snapshots)}
data.Histories = append(data.Histories, entry)
}
return apicontract.Success(data)
})
+
+func docHistorySnapshots(values []*model.DocHistorySnapshot) []*apicontract.DocHistorySnapshot {
+ ret := make([]*apicontract.DocHistorySnapshot, 0, len(values))
+ for _, snapshot := range values {
+ ret = append(ret, &apicontract.DocHistorySnapshot{
+ ID: snapshot.ID, FileID: snapshot.FileID, Tags: snapshot.Tags, Memo: snapshot.Memo, Created: snapshot.Created,
+ })
+ }
+ return ret
+}
diff --git a/kernel/api/repo.go b/kernel/api/repo.go
index 025ba897aa..4e8c8b6c50 100644
--- a/kernel/api/repo.go
+++ b/kernel/api/repo.go
@@ -399,7 +399,13 @@ func repoDocHistories(values []*model.RepoDocHistory) []*apicontract.RepoDocHist
}
ret := make([]*apicontract.RepoDocHistory, len(values))
for i, value := range values {
- ret[i] = (*apicontract.RepoDocHistory)(value)
+ if value == nil {
+ continue
+ }
+ ret[i] = &apicontract.RepoDocHistory{
+ FileID: value.FileID, IndexID: value.IndexID, Title: value.Title, HSize: value.HSize, Updated: value.Updated,
+ Snapshots: docHistorySnapshots(value.Snapshots),
+ }
}
return ret
}
diff --git a/kernel/apicontract/repo.go b/kernel/apicontract/repo.go
index 85ea824a15..a4383d6e7a 100644
--- a/kernel/apicontract/repo.go
+++ b/kernel/apicontract/repo.go
@@ -167,6 +167,9 @@ type RepoDocHistory struct {
Title string `json:"title"`
HSize string `json:"hSize"`
Updated int64 `json:"updated"`
+ // Snapshots 包含引用此文件版本的全部本地标记快照,按快照时间倒序排列;同一快照的标记合并。
+ // 以仓库文件 ID 匹配,不只查询 IndexID;仅返回标记、备注等元数据,不读取文件正文。
+ Snapshots []*DocHistorySnapshot `json:"snapshots"`
}
type RepoTypeCount struct {
Type string `json:"type"`
diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.json
index 43d0a0899d..bc21456f3c 100644
--- a/kernel/apicontract/schema.json
+++ b/kernel/apicontract/schema.json
@@ -34980,6 +34980,26 @@
"indexID": {
"type": "string"
},
+ "snapshots": {
+ "anyOf": [
+ {
+ "type": "array",
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/DocHistorySnapshot"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
"title": {
"type": "string"
},
@@ -34991,6 +35011,7 @@
"fileID",
"hSize",
"indexID",
+ "snapshots",
"title",
"updated"
],
diff --git a/kernel/model/history_snapshots.go b/kernel/model/history_snapshots.go
index 5fec6fa457..baf8230dea 100644
--- a/kernel/model/history_snapshots.go
+++ b/kernel/model/history_snapshots.go
@@ -15,6 +15,7 @@ import (
"strings"
"github.com/88250/lute/ast"
+ "github.com/siyuan-note/dejavu"
"github.com/siyuan-note/dejavu/entity"
"github.com/siyuan-note/siyuan/kernel/treenode"
)
@@ -99,42 +100,10 @@ func GetDocHistorySnapshots(ctx context.Context, id string, histories []*DocHist
if err != nil {
return err
}
- // 只读取标记引用与索引,避免为每个标记重复展开整个快照的文件列表。
- tags, err := os.ReadDir(filepath.Join(repo.Path, "refs", "tags"))
- if os.IsNotExist(err) {
- return nil
- }
+ indexes, indexTags, err := localTaggedSnapshotIndexes(ctx, repo)
if err != nil {
return err
}
- indexes := map[string]*entity.Index{}
- indexTags := map[string][]string{}
- for _, tag := range tags {
- if err := ctx.Err(); err != nil {
- return err
- }
- if tag.IsDir() {
- continue
- }
- indexID, readErr := repo.GetTag(tag.Name())
- if readErr != nil {
- return readErr
- }
- if _, readErr = hex.DecodeString(indexID); len(indexID) != 40 || readErr != nil {
- return errors.New("invalid tagged snapshot ID")
- }
- if indexes[indexID] == nil {
- index, readErr := repo.GetIndex(indexID)
- if readErr != nil {
- return readErr
- }
- if index.ID != indexID || !index.VerifyAESKey(Conf.Repo.Key) {
- return errors.New("invalid tagged snapshot index")
- }
- indexes[indexID] = index
- }
- indexTags[indexID] = append(indexTags[indexID], tag.Name())
- }
fileMatches := map[string][]*DocHistorySnapshotEntry{}
for indexID, index := range indexes {
seen := map[*DocHistorySnapshotEntry]bool{}
@@ -214,3 +183,82 @@ func docHistorySnapshotDigest(data []byte, id string) ([sha256.Size]byte, error)
}
return sha256.Sum256(data), nil
}
+
+// attachRepoDocHistorySnapshots 按文件版本关联所有标记索引,避免去重列表的单个 IndexID 丢失关联。
+func attachRepoDocHistorySnapshots(repo *dejavu.Repo, histories []*RepoDocHistory) error {
+ if len(histories) == 0 {
+ return nil
+ }
+ files := map[string]*RepoDocHistory{}
+ for _, history := range histories {
+ history.Snapshots = []*DocHistorySnapshot{}
+ files[history.FileID] = history
+ }
+ indexes, tags, err := localTaggedSnapshotIndexes(context.Background(), repo)
+ if err != nil {
+ return err
+ }
+ for id, index := range indexes {
+ seen := map[string]bool{}
+ for _, fileID := range index.Files {
+ history := files[fileID]
+ if history == nil || seen[fileID] {
+ continue
+ }
+ seen[fileID] = true
+ history.Snapshots = append(history.Snapshots, &DocHistorySnapshot{
+ ID: id, FileID: fileID, Tags: tags[id], Memo: index.Memo, Created: index.Created,
+ })
+ }
+ }
+ for _, history := range histories {
+ sort.Slice(history.Snapshots, func(i, j int) bool {
+ a, b := history.Snapshots[i], history.Snapshots[j]
+ if a.Created == b.Created {
+ return a.ID < b.ID
+ }
+ return a.Created > b.Created
+ })
+ }
+ return nil
+}
+
+func localTaggedSnapshotIndexes(ctx context.Context, repo *dejavu.Repo) (map[string]*entity.Index, map[string][]string, error) {
+ // 只读取标记引用与索引,避免为每个标记重复展开整个快照的文件列表。
+ tags, err := os.ReadDir(filepath.Join(repo.Path, "refs", "tags"))
+ if os.IsNotExist(err) {
+ return map[string]*entity.Index{}, map[string][]string{}, nil
+ }
+ if err != nil {
+ return nil, nil, err
+ }
+ indexes := map[string]*entity.Index{}
+ indexTags := map[string][]string{}
+ for _, tag := range tags {
+ if err := ctx.Err(); err != nil {
+ return nil, nil, err
+ }
+ if tag.IsDir() {
+ continue
+ }
+ indexID, readErr := repo.GetTag(tag.Name())
+ if readErr != nil {
+ return nil, nil, readErr
+ }
+ if _, readErr = hex.DecodeString(indexID); len(indexID) != 40 || readErr != nil {
+ return nil, nil, errors.New("invalid tagged snapshot ID")
+ }
+ if indexes[indexID] == nil {
+ index, readErr := repo.GetIndex(indexID)
+ if readErr != nil {
+ return nil, nil, readErr
+ }
+ if index.ID != indexID || !index.VerifyAESKey(Conf.Repo.Key) {
+ return nil, nil, errors.New("invalid tagged snapshot index")
+ }
+ indexes[indexID] = index
+ }
+ indexTags[indexID] = append(indexTags[indexID], tag.Name())
+ }
+ return indexes, indexTags, nil
+}
diff --git a/kernel/model/history_snapshots_test.go b/kernel/model/history_snapshots_test.go
index bd02188d50..eef7c9abf1 100644
--- a/kernel/model/history_snapshots_test.go
+++ b/kernel/model/history_snapshots_test.go
@@ -82,6 +82,18 @@ func TestDocHistorySnapshotsMatching(t *testing.T) {
entry.Snapshots[0].FileID == "" {
t.Fatalf("unexpected snapshot associations: %+v", entry.Snapshots)
}
+ versions, _, _, err := GetRepoDocHistory(historySnapshotDocID, 1)
+ if err != nil || len(versions) != 1 || len(versions[0].Snapshots) != 2 {
+ t.Fatalf("deduplicated repository version lost associations: %+v %v", versions, err)
+ }
+ if versions[0].Snapshots[0].ID != second.ID || versions[0].Snapshots[1].ID != first.ID ||
+ strings.Join(versions[0].Snapshots[1].Tags, ",") != "alias,first" || versions[0].Snapshots[0].Memo != "second\nline" {
+ t.Fatalf("repository snapshot metadata lost: %+v", versions[0].Snapshots)
+ }
+ unmatched := &RepoDocHistory{FileID: strings.Repeat("f", 40)}
+ if err := attachRepoDocHistorySnapshots(repo, []*RepoDocHistory{unmatched}); err != nil || unmatched.Snapshots == nil || len(unmatched.Snapshots) != 0 {
+ t.Fatalf("unmatched repository version must have an empty list: %+v %v", unmatched, err)
+ }
if len(query(historySnapshotData("different")).Snapshots) != 0 {
t.Fatal("different document data matched")
}
@@ -95,6 +107,10 @@ func TestDocHistorySnapshotsMatching(t *testing.T) {
if len(entry.Snapshots) != 1 || entry.Snapshots[0].Memo != "edited" {
t.Fatal("tag deletion or memo edit was hidden by stale associations")
}
+ versions, _, _, err = GetRepoDocHistory(historySnapshotDocID, 1)
+ if err != nil || len(versions) != 1 || len(versions[0].Snapshots) != 1 || versions[0].Snapshots[0].Memo != "edited" {
+ t.Fatalf("repository history retained stale tags or memo: %+v %v", versions, err)
+ }
ctx, cancel := context.WithCancel(context.Background())
cancel()
if err = GetDocHistorySnapshots(ctx, historySnapshotDocID, []*DocHistorySnapshotEntry{entry}); err != context.Canceled {
@@ -106,6 +122,9 @@ func TestDocHistorySnapshotsMatching(t *testing.T) {
if err = GetDocHistorySnapshots(context.Background(), historySnapshotDocID, []*DocHistorySnapshotEntry{entry}); err == nil {
t.Fatal("corrupt tag was treated as no match")
}
+ if _, _, _, err = GetRepoDocHistory(historySnapshotDocID, 1); err == nil {
+ t.Fatal("repository history ignored a corrupt tag")
+ }
if actual, err := os.ReadFile(tagPath); err != nil || !bytes.Equal(actual, corrupt) {
t.Fatal("corrupt tag was modified")
}
diff --git a/kernel/model/repository.go b/kernel/model/repository.go
index da0109165e..ff04fe8c84 100644
--- a/kernel/model/repository.go
+++ b/kernel/model/repository.go
@@ -558,11 +558,12 @@ type DiffFile struct {
}
type RepoDocHistory struct {
- FileID string `json:"fileID"`
- IndexID string `json:"indexID"`
- Title string `json:"title"`
- HSize string `json:"hSize"`
- Updated int64 `json:"updated"`
+ FileID string `json:"fileID"`
+ IndexID string `json:"indexID"`
+ Title string `json:"title"`
+ HSize string `json:"hSize"`
+ Updated int64 `json:"updated"`
+ Snapshots []*DocHistorySnapshot `json:"snapshots"`
}
type DiffIndex struct {
@@ -853,6 +854,7 @@ func GetRepoDocHistory(id string, page int) (ret []*RepoDocHistory, pageCount, t
Updated: file.Updated,
})
}
+ err = attachRepoDocHistorySnapshots(repo, ret)
return
}