Skip to content

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

:art: Improve doc sort placement when importing .sy.zip https://github.com/siyuan-note/siyuan/issues/19074

Danielf33859a94e72
diff --git a/kernel/model/import.go b/kernel/model/import.go
index e5ca4bf0dc..22c4e9d166 100644
--- a/kernel/model/import.go
+++ b/kernel/model/import.go
@@ -29,6 +29,7 @@ import (
"io"
"io/fs"
"maps"
+ "math"
"net/url"
"os"
"path"
@@ -176,6 +177,103 @@ func isSYNotebookExport(hasBoxConf, hasBoxDocMeta bool) bool {
return hasBoxConf || hasBoxDocMeta
}
+type importedSYSortDoc struct {
+ oldID string
+ newID string
+ sourcePath string
+ hidden bool
+}
+
+func buildImportedSYSortValues(importedDocs []*importedSYSortDoc, sourceSortIDs map[string]int,
+ existingRootIDs []string, createDocAtTop bool) map[string]int {
+ groups := map[string][]*importedSYSortDoc{}
+ for _, doc := range importedDocs {
+ if nil == doc || doc.hidden {
+ continue
+ }
+ parentPath := path.Dir(doc.sourcePath)
+ groups[parentPath] = append(groups[parentPath], doc)
+ }
+
+ for _, docs := range groups {
+ sort.Slice(docs, func(i, j int) bool {
+ leftSort, rightSort := sourceSortIDs[docs[i].oldID], sourceSortIDs[docs[j].oldID]
+ if leftSort != rightSort {
+ return leftSort < rightSort
+ }
+ leftCreated, rightCreated := util.TimeFromID(docs[i].oldID), util.TimeFromID(docs[j].oldID)
+ if leftCreated != rightCreated {
+ return leftCreated > rightCreated
+ }
+ return docs[i].oldID < docs[j].oldID
+ })
+ }
+
+ sortValues := map[string]int{}
+ for _, docs := range groups {
+ for sortValue, doc := range docs {
+ sortValues[doc.newID] = sortValue
+ }
+ }
+
+ rootDocs := groups["/"]
+ rootIDs := make([]string, 0, len(rootDocs))
+ for _, doc := range rootDocs {
+ rootIDs = append(rootIDs, doc.newID)
+ }
+ orderedRootIDs := make([]string, 0, len(rootIDs)+len(existingRootIDs))
+ if createDocAtTop {
+ orderedRootIDs = append(orderedRootIDs, rootIDs...)
+ orderedRootIDs = append(orderedRootIDs, existingRootIDs...)
+ } else {
+ orderedRootIDs = append(orderedRootIDs, existingRootIDs...)
+ orderedRootIDs = append(orderedRootIDs, rootIDs...)
+ }
+ for sortValue, id := range orderedRootIDs {
+ sortValues[id] = sortValue
+ }
+ return sortValues
+}
+
+func applyImportedSYSort(boxID, targetPath string, importedDocs []*importedSYSortDoc, sourceSortIDs map[string]int) error {
+ if 1 > len(importedDocs) {
+ return nil
+ }
+
+ fileTreeSortLock.Lock()
+ defer fileTreeSortLock.Unlock()
+
+ docs, _, err := ListDocTree(boxID, targetPath, util.SortModeCustom, false, false, math.MaxInt)
+ if nil != err {
+ return err
+ }
+ importedIDs := map[string]struct{}{}
+ for _, doc := range importedDocs {
+ if nil != doc {
+ importedIDs[doc.newID] = struct{}{}
+ }
+ }
+ existingRootIDs := make([]string, 0, len(docs))
+ for _, doc := range docs {
+ if _, imported := importedIDs[doc.ID]; !imported {
+ existingRootIDs = append(existingRootIDs, doc.ID)
+ }
+ }
+
+ createDocAtTop := nil != Conf.FileTree.CreateDocAtTop && *Conf.FileTree.CreateDocAtTop
+ sortValues := buildImportedSYSortValues(importedDocs, sourceSortIDs, existingRootIDs, createDocAtTop)
+ if 1 > len(sortValues) {
+ return nil
+ }
+ confPath := filepath.Join(util.DataDir, boxID, ".siyuan", "sort.json")
+ fullSortIDs, err := readSortConfMap(confPath)
+ if nil != err {
+ return err
+ }
+ maps.Copy(fullSortIDs, sortValues)
+ return writeSortConfMap(confPath, fullSortIDs)
+}
+
func importSY(zipPath, boxID, toPath string, createNotebook, autoDetect bool) (createdBoxID string, err error) {
return importSY0(zipPath, boxID, toPath, createNotebook, autoDetect, nil, false)
}
@@ -352,6 +450,7 @@ func importSY0(zipPath, boxID, toPath string, createNotebook, autoDetect bool, s
blockIDs = map[string]string{}
}
trees := map[string]*parse.Tree{}
+ var importedSortDocs []*importedSYSortDoc
importedBoxDoc := false
containsFlashcardAttrs := false
@@ -410,6 +509,12 @@ func importSY0(zipPath, boxID, toPath string, createNotebook, autoDetect bool, s
} else if oldRootID == importedBoxDocID {
removeBoxDocHiddenAttr(tree)
}
+ importedSortDocs = append(importedSortDocs, &importedSYSortDoc{
+ oldID: oldRootID,
+ newID: tree.ID,
+ sourcePath: tree.Path,
+ hidden: createNotebook && oldRootID == importedBoxDocID,
+ })
trees[tree.ID] = tree
util.PushEndlessProgress(Conf.language(73) + " " + fmt.Sprintf(Conf.language(70), fmt.Sprintf("%d/%d", i+1, len(syPaths))))
}
@@ -690,48 +795,15 @@ func importSY0(zipPath, boxID, toPath string, createNotebook, autoDetect bool, s
tree.Path = finalRelPath
}
- // 合并 sort.json
- fullSortIDs := map[string]int{}
- sortIDs := map[string]int{}
- var sortData []byte
+ // 读取包内自定义排序,复制成功后根据目标位置重新编号
+ sourceSortIDs := map[string]int{}
var sortErr error
sortPath := filepath.Join(unzipRootPath, ".siyuan", "sort.json")
if filelock.IsExist(sortPath) {
- sortData, sortErr = filelock.ReadFile(sortPath)
+ sourceSortIDs, sortErr = readSortConfMap(sortPath)
if nil != sortErr {
logging.LogErrorf("read import sort conf failed: %s", sortErr)
- }
-
- if sortErr = gulu.JSON.UnmarshalJSON(sortData, &sortIDs); nil != sortErr {
- logging.LogErrorf("unmarshal sort conf failed: %s", sortErr)
- }
-
- boxSortPath := filepath.Join(util.DataDir, boxID, ".siyuan", "sort.json")
- if filelock.IsExist(boxSortPath) {
- sortData, sortErr = filelock.ReadFile(boxSortPath)
- if nil != sortErr {
- logging.LogErrorf("read box sort conf failed: %s", sortErr)
- }
-
- if sortErr = gulu.JSON.UnmarshalJSON(sortData, &fullSortIDs); nil != sortErr {
- logging.LogErrorf("unmarshal box sort conf failed: %s", sortErr)
- }
- }
-
- for oldID, sort := range sortIDs {
- if newID := blockIDs[oldID]; "" != newID {
- fullSortIDs[newID] = sort
- }
- }
-
- sortData, sortErr = gulu.JSON.MarshalJSON(fullSortIDs)
- if nil != sortErr {
- logging.LogErrorf("marshal box full sort conf failed: %s", sortErr)
- } else {
- sortErr = filelock.WriteFile(boxSortPath, sortData)
- if nil != sortErr {
- logging.LogErrorf("write box full sort conf failed: %s", sortErr)
- }
+ sourceSortIDs = map[string]int{}
}
if removeErr := os.RemoveAll(sortPath); nil != removeErr {
logging.LogErrorf("remove temp sort conf failed: %s", removeErr)
@@ -938,6 +1010,9 @@ func importSY0(zipPath, boxID, toPath string, createNotebook, autoDetect bool, s
sql.IndexTreeQueue(tree)
util.PushEndlessProgress(Conf.language(73) + " " + fmt.Sprintf(Conf.language(70), tree.Root.IALAttr("title")))
}
+ if sortErr = applyImportedSYSort(boxID, baseTargetPath, importedSortDocs, sourceSortIDs); nil != sortErr {
+ logging.LogErrorf("apply imported document sort failed: %s", sortErr)
+ }
IncSync()
diff --git a/kernel/model/import_test.go b/kernel/model/import_test.go
index 534b19168d..2bc26ebce7 100644
--- a/kernel/model/import_test.go
+++ b/kernel/model/import_test.go
@@ -55,6 +55,78 @@ func TestIsSYNotebookExport(t *testing.T) {
}
}
+func TestBuildImportedSYSortValues(t *testing.T) {
+ first := &importedSYSortDoc{
+ oldID: "20260801000001-aaaaaaa", newID: "20260801000001-newaaaa", sourcePath: "/20260801000001-aaaaaaa.sy"}
+ second := &importedSYSortDoc{
+ oldID: "20260801000002-bbbbbbb", newID: "20260801000002-newbbbb", sourcePath: "/20260801000002-bbbbbbb.sy"}
+ childOld := &importedSYSortDoc{
+ oldID: "20260801000003-ccccccc", newID: "20260801000003-newcccc",
+ sourcePath: "/20260801000001-aaaaaaa/20260801000003-ccccccc.sy"}
+ childNew := &importedSYSortDoc{
+ oldID: "20260801000004-ddddddd", newID: "20260801000004-newdddd",
+ sourcePath: "/20260801000001-aaaaaaa/20260801000004-ddddddd.sy"}
+ hidden := &importedSYSortDoc{
+ oldID: "20260801000005-eeeeeee", newID: "20260801000005-neweeee",
+ sourcePath: "/20260801000005-eeeeeee.sy", hidden: true}
+ importedDocs := []*importedSYSortDoc{first, second, childOld, childNew, hidden}
+ sourceSortIDs := map[string]int{first.oldID: 20, second.oldID: 10}
+ existingRootIDs := []string{"existing-first", "existing-second"}
+
+ tests := []struct {
+ name string
+ createDocAtTop bool
+ want map[string]int
+ }{
+ {
+ name: "prepend batch",
+ createDocAtTop: true,
+ want: map[string]int{
+ second.newID: 0, first.newID: 1, "existing-first": 2, "existing-second": 3,
+ childNew.newID: 0, childOld.newID: 1,
+ },
+ },
+ {
+ name: "append batch",
+ want: map[string]int{
+ "existing-first": 0, "existing-second": 1, second.newID: 2, first.newID: 3,
+ childNew.newID: 0, childOld.newID: 1,
+ },
+ },
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ got := buildImportedSYSortValues(importedDocs, sourceSortIDs, existingRootIDs, test.createDocAtTop)
+ assertImportedSYSortValues(t, got, test.want)
+ if _, ok := got[hidden.newID]; ok {
+ t.Fatalf("hidden notebook document received a sort value")
+ }
+ })
+ }
+}
+
+func TestBuildImportedSYSortValuesWithoutSourceSort(t *testing.T) {
+ older := &importedSYSortDoc{
+ oldID: "20260801000001-aaaaaaa", newID: "20260801000001-newaaaa", sourcePath: "/20260801000001-aaaaaaa.sy"}
+ newer := &importedSYSortDoc{
+ oldID: "20260801000002-bbbbbbb", newID: "20260801000002-newbbbb", sourcePath: "/20260801000002-bbbbbbb.sy"}
+
+ got := buildImportedSYSortValues([]*importedSYSortDoc{older, newer}, nil, []string{"existing"}, true)
+ assertImportedSYSortValues(t, got, map[string]int{newer.newID: 0, older.newID: 1, "existing": 2})
+}
+
+func assertImportedSYSortValues(t *testing.T, got, want map[string]int) {
+ t.Helper()
+ if len(got) != len(want) {
+ t.Fatalf("sort value count = %d, want %d: got=%v", len(got), len(want), got)
+ }
+ for id, wantValue := range want {
+ if gotValue, ok := got[id]; !ok || gotValue != wantValue {
+ t.Fatalf("sort value for [%s] = %d, want %d: got=%v", id, gotValue, wantValue, got)
+ }
+ }
+}
+
func TestImportFromLocalPathRejectsClosedNotebookBeforeWriting(t *testing.T) {
fixture := setupFileOperationTest(t)
boxConf := fixture.box.GetConf()