An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Correct kernel CLI document operations https://github.com/siyuan-note/siyuan/issues/18381
Daniele93abf903cf3
diff --git a/kernel/cli/cmd/block.go b/kernel/cli/cmd/block.goindex a82e2a04d5..a0cf2cdc8f 100644--- a/kernel/cli/cmd/block.go+++ b/kernel/cli/cmd/block.go@@ -399,6 +399,10 @@ var blockMoveCmd = &cobra.Command{return fmt.Errorf("--id and --parent are required")}+ if err := validateBlockMove(id, parentID, previousID); err != nil {+ return err+ }+if dryRun {fmt.Printf("[dry-run] Would move block %s to parent %s\n", id, parentID)if previousID != "" {@@ -407,26 +411,17 @@ var blockMoveCmd = &cobra.Command{return nil}- // 仅靠 parentID 定位目标时(无 previousID),目标必须是容器块,否则非法嵌套- if previousID == "" {- if err := treenode.CheckListItemNesting(parentID, id); err != nil {- return err- }- if err := treenode.CheckContainerParent(parentID); err != nil {- return err- }- }-- transactions := []*model.Transaction{{+ transaction := &model.Transaction{DoOperations: []*model.Operation{{Action: "move",ID: id,ParentID: parentID,PreviousID: previousID,}},- }}- model.PerformTransactions(&transactions)- model.FlushTxQueue()+ }+ if err := model.PerformTxSync(transaction); err != nil {+ return err+ }if bt := treenode.GetBlockTree(id); bt != nil {model.AppendPushReloadProtyleEntry(bt.RootID)}@@ -435,6 +430,31 @@ var blockMoveCmd = &cobra.Command{},}+func validateBlockMove(id, parentID, previousID string) error {+ bt := treenode.GetBlockTree(id)+ if nil == bt {+ return fmt.Errorf("block not found: %s", id)+ }+ if "d" == bt.Type {+ return fmt.Errorf("document block [%s] cannot be moved with block move; use document move instead", id)+ }++ if "" != previousID {+ previousBt := treenode.GetBlockTree(previousID)+ if nil == previousBt {+ return fmt.Errorf("previous block not found: %s", previousID)+ }+ if "d" == previousBt.Type {+ return fmt.Errorf("document block [%s] cannot be used as a previous sibling; use it as --parent instead", previousID)+ }+ return nil+ }+ if err := treenode.CheckListItemNesting(parentID, id); err != nil {+ return err+ }+ return treenode.CheckContainerParent(parentID)+}+var blockBatchGetCmd = &cobra.Command{Use: "batch-get --ids id1,id2,...",Short: "Batch get block info",diff --git a/kernel/cli/cmd/display_test.go b/kernel/cli/cmd/display_test.goindex ac67a94fc9..f36a1123ee 100644--- a/kernel/cli/cmd/display_test.go+++ b/kernel/cli/cmd/display_test.go@@ -10,6 +10,112 @@ package cmdimport "testing"+func TestResolveDocumentMovePath(t *testing.T) {+ paths := map[string]string{+ "/parent": "/20260726000000-parent1.sy",+ "/grand/parent": "/20260726000000-grand01/20260726000001-parent1.sy",+ "/existing/child": "/20260726000002-existin/20260726000003-child01.sy",+ }+ lookup := func(hPath string) (string, bool) {+ p, found := paths[hPath]+ return p, found+ }+ tests := []struct {+ name string+ userPath string+ hPath string+ sourceHPath string+ want string+ wantErr bool+ }{+ {+ name: "explicit internal path",+ userPath: "/20260726000000-parent1.sy",+ hPath: "/missing",+ sourceHPath: "/child",+ want: "/20260726000000-parent1.sy",+ },+ {name: "default root", sourceHPath: "/child", want: "/"},+ {name: "root hpath", hPath: "/", sourceHPath: "/child", want: "/"},+ {+ name: "parent hpath",+ hPath: "/parent",+ sourceHPath: "/child",+ want: "/20260726000000-parent1.sy",+ },+ {+ name: "parent hpath with trailing slash",+ hPath: "/parent/",+ sourceHPath: "/child",+ want: "/20260726000000-parent1.sy",+ },+ {+ name: "full destination hpath",+ hPath: "/parent/child",+ sourceHPath: "/child",+ want: "/20260726000000-parent1.sy",+ },+ {+ name: "nested full destination hpath",+ hPath: "/grand/parent/child",+ sourceHPath: "/child",+ want: "/20260726000000-grand01/20260726000001-parent1.sy",+ },+ {+ name: "existing target with different source title",+ hPath: "/existing/child",+ sourceHPath: "/source",+ want: "/20260726000002-existin/20260726000003-child01.sy",+ },+ {name: "missing target", hPath: "/missing", sourceHPath: "/child", wantErr: true},+ {name: "missing destination parent", hPath: "/missing/child", sourceHPath: "/child", wantErr: true},+ }++ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ got, err := resolveDocumentMovePathWithLookup(test.userPath, test.hPath, test.sourceHPath, lookup)+ if test.wantErr {+ if nil == err {+ t.Fatalf("expected an error, got path %q", got)+ }+ return+ }+ if nil != err {+ t.Fatalf("resolve document move path failed: %v", err)+ }+ if got != test.want {+ t.Fatalf("unexpected document move path: got %q, want %q", got, test.want)+ }+ })+ }+}++func TestNormalizeDocumentCreateParentPath(t *testing.T) {+ tests := []struct {+ name string+ path string+ want string+ }{+ {name: "default root", path: "", want: "/"},+ {name: "root", path: "/", want: "/"},+ {name: "document directory", path: "/20260726000000-abcdefg", want: "/20260726000000-abcdefg"},+ {name: "document file", path: "/20260726000000-abcdefg.sy", want: "/20260726000000-abcdefg"},+ {+ name: "nested document file",+ path: "/20260726000000-abcdefg/20260726000001-abcdefg.sy",+ want: "/20260726000000-abcdefg/20260726000001-abcdefg",+ },+ }++ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ if got := normalizeDocumentCreateParentPath(test.path); got != test.want {+ t.Fatalf("normalizeDocumentCreateParentPath(%q) = %q, want %q", test.path, got, test.want)+ }+ })+ }+}+func TestDocumentSearchDisplayFields(t *testing.T) {tests := []struct {name stringdiff --git a/kernel/cli/cmd/document.go b/kernel/cli/cmd/document.goindex 110af652db..65d0e883ea 100644--- a/kernel/cli/cmd/document.go+++ b/kernel/cli/cmd/document.go@@ -75,8 +75,11 @@ var documentCreateCmd = &cobra.Command{if title == "" {return fmt.Errorf("--title is required")}- if dir == "" {- dir = "/"+ dir = normalizeDocumentCreateParentPath(dir)+ id := ast.NewNodeID()+ docPath := path.Join(dir, id+".sy")+ if err := model.ValidateCreateDoc(notebook, docPath, title); err != nil {+ return err}if dryRun {@@ -84,8 +87,6 @@ var documentCreateCmd = &cobra.Command{return nil}- id := ast.NewNodeID()- docPath := path.Join(dir, id+".sy")_, err := model.CreateDocByMd(notebook, docPath, title, markdown, nil, nil)if err != nil {return err@@ -96,6 +97,13 @@ var documentCreateCmd = &cobra.Command{},}+func normalizeDocumentCreateParentPath(parentPath string) string {+ if "" == parentPath {+ return "/"+ }+ return strings.TrimSuffix(path.Clean(parentPath), ".sy")+}+var documentGetCmd = &cobra.Command{Use: "get --id <id>",Short: "Get document info",@@ -209,16 +217,21 @@ var documentMoveCmd = &cobra.Command{return fmt.Errorf("--id and --notebook are required")}+ tree, err := model.LoadTreeByBlockID(id)+ if err != nil {+ return err+ }+ targetPath, err := resolveDocumentMovePath(toNotebook, toPath, hpath, tree.HPath)+ if err != nil {+ return err+ }+if dryRun {fmt.Printf("[dry-run] Would move document %s to notebook %s\n", id, toNotebook)return nil}- tree, err := model.LoadTreeByBlockID(id)- if err != nil {- return err- }- if err := model.MoveDocs([]string{tree.Path}, toNotebook, resolvePath(toNotebook, toPath, hpath), nil); err != nil {+ if err := model.MoveDocs([]string{tree.Path}, toNotebook, targetPath, nil); err != nil {return err}model.AppendPushReloadFiletreeEntry()@@ -291,6 +304,46 @@ func resolvePath(boxID, userPath, hpath string) string {return "/"}+func resolveDocumentMovePath(boxID, userPath, hpath, sourceHPath string) (string, error) {+ return resolveDocumentMovePathWithLookup(userPath, hpath, sourceHPath, func(targetHPath string) (string, bool) {+ bt := treenode.GetBlockTreeRootByHPath(boxID, targetHPath)+ if nil == bt {+ return "", false+ }+ return bt.Path, true+ })+}++func resolveDocumentMovePathWithLookup(+ userPath, hpath, sourceHPath string,+ lookup func(string) (string, bool),+) (string, error) {+ if "" != userPath {+ return userPath, nil+ }+ if "" == hpath {+ return "/", nil+ }++ targetHPath := path.Clean("/" + strings.TrimPrefix(hpath, "/"))+ if "/" == targetHPath {+ return "/", nil+ }++ sourceTitle := path.Base(path.Clean(sourceHPath))+ if sourceTitle == path.Base(targetHPath) {+ targetHPath = path.Dir(targetHPath)+ if "/" == targetHPath {+ return "/", nil+ }+ }++ if targetPath, found := lookup(targetHPath); found {+ return targetPath, nil+ }+ return "", fmt.Errorf("target human-readable path not found: %s", targetHPath)+}+var documentSearchCmd = &cobra.Command{Use: "search <keyword>",Short: "Search documents by keyword",diff --git a/kernel/model/file.go b/kernel/model/file.goindex f4a0f1b7e4..66687dc591 100644--- a/kernel/model/file.go+++ b/kernel/model/file.go@@ -1982,25 +1982,24 @@ func removeDoc(box *Box, p string, luteEngine *lute.Lute) (ret *parse.Tree, errtreenode.RemoveBlockTreesByPathPrefix(box.ID, childrenDir)cache.RemoveDocIAL(ret.Path)cache.RemoveTreeData(ret.ID)+ sql.RemoveTreePathQueue(ret.Box, childrenDir)evt := util.NewCmdResult("removeDoc", 0, util.PushModeBroadcast)evt.Data = map[string]any{"ids": removeIDs,}util.PushEvent(evt)- task.AppendTask(task.DatabaseIndex, removeDoc0, ret, childrenDir)+ task.AppendTask(task.DatabaseIndex, removeDoc0, ret)return}-func removeDoc0(tree *parse.Tree, childrenDir string) {+func removeDoc0(tree *parse.Tree) {// 收集引用的定义块 IDrefDefIDs := getRefDefIDs(tree.Root)// 推送定义节点引用计数for _, defID := range refDefIDs {task.AppendAsyncTaskWithDelay(task.SetDefRefCount, util.SQLFlushInterval, refreshRefCount, defID)}-- sql.RemoveTreePathQueue(tree.Box, childrenDir)}func RenameDoc(boxID, p, title string) (err error) {@@ -2108,15 +2107,31 @@ func renameDoc0(boxID, p, title string) (err error) {return}-func createDoc(boxID, p, title, dom string, titleEmpty bool) (tree *parse.Tree, err error) {+type createDocValidation struct {+ box *Box+ path string+ title string+ hPath string+ id string+ folder string+ isEmpty bool+}++// ValidateCreateDoc 校验文档创建参数,不写入文件或索引。+func ValidateCreateDoc(boxID, p, title string) error {+ _, err := validateCreateDoc(boxID, p, title, false)+ return err+}++func validateCreateDoc(boxID, p, title string, titleEmpty bool) (ret *createDocValidation, err error) {p = normalizeBoxDocPath(boxID, p)title = normalizeDocTitle(title)if 512 < utf8.RuneCountInString(title) {// 限制笔记本名和文档名最大长度为 `512` https://github.com/siyuan-note/siyuan/issues/6299- err = errors.New(Conf.Language(106))- return+ return nil, errors.New(Conf.Language(106))}- var isEmpty bool++ isEmpty := falseif "" == title {title = Conf.Language(16)isEmpty = true@@ -2126,64 +2141,80 @@ func createDoc(boxID, p, title, dom string, titleEmpty bool) (tree *parse.Tree,baseName := strings.TrimSpace(path.Base(p))if "" == util.GetTreeID(baseName) {- err = errors.New(Conf.Language(16))- return+ return nil, errors.New(Conf.Language(16))}-if strings.HasPrefix(baseName, ".") {- err = errors.New(Conf.Language(13))- return+ return nil, errors.New(Conf.Language(13))}box := Conf.Box(boxID)if nil == box {- err = errors.New(Conf.Language(0))- return+ return nil, errors.New(Conf.Language(0))}- id := util.GetTreeID(p)- var hPath stringfolder := path.Dir(p)+ hPath := "/" + titleif "/" != folder {parentID := path.Base(folder)parentTree, loadErr := LoadTreeByBlockID(parentID)if nil != loadErr {logging.LogErrorf("get parent tree [%s] failed", parentID)- err = ErrBlockNotFound- return+ return nil, ErrBlockNotFound+ }+ parentPath := strings.TrimSuffix(parentTree.Path, ".sy")+ if parentTree.Box != boxID || cleanBoxDocDir(parentPath) != cleanBoxDocDir(folder) {+ logging.LogErrorf("parent tree [%s] does not match box [%s] and folder [%s]", parentID, boxID, folder)+ return nil, ErrBlockNotFound}hPath = path.Join(parentTree.HPath, title)- } else {- hPath = "/" + title}if depth := strings.Count(p, "/"); 7 < depth && !Conf.FileTree.AllowCreateDeeper {- err = errors.New(Conf.Language(118))- return+ return nil, errors.New(Conf.Language(118))+ }+ if box.Exist(p) {+ return nil, errors.New(Conf.Language(1))}- if !box.Exist(folder) {- if err = box.MkdirAll(folder); err != nil {- return- }+ ret = &createDocValidation{+ box: box,+ path: p,+ title: title,+ hPath: hPath,+ id: util.GetTreeID(p),+ folder: folder,+ isEmpty: isEmpty,}+ return+}- if box.Exist(p) {- err = errors.New(Conf.Language(1))+func cleanBoxDocDir(p string) string {+ return path.Clean("/" + strings.TrimPrefix(p, "/"))+}++func createDoc(boxID, p, title, dom string, titleEmpty bool) (tree *parse.Tree, err error) {+ validation, err := validateCreateDoc(boxID, p, title, titleEmpty)+ if nil != err {return}+ if !validation.box.Exist(validation.folder) {+ if err = validation.box.MkdirAll(validation.folder); err != nil {+ return+ }+ }+luteEngine := util.NewLute()tree = luteEngine.BlockDOM2Tree(dom)tree.Box = boxID- tree.Path = p- tree.HPath = hPath- tree.ID = id- tree.Root.ID = id+ tree.Path = validation.path+ tree.HPath = validation.hPath+ tree.ID = validation.id+ tree.Root.ID = validation.idtree.Root.Spec = treenode.CurrentSpec- updated := util.TimeFromID(id)- tree.Root.KramdownIAL = [][]string{{"id", id}, {"title", html.EscapeAttrVal(title)}, {"updated", updated}}- if isEmpty {+ updated := util.TimeFromID(validation.id)+ tree.Root.KramdownIAL = [][]string{{"id", validation.id}, {"title", html.EscapeAttrVal(validation.title)}, {"updated", updated}}+ if validation.isEmpty {tree.Root.SetIALAttr(NodeAttrTitleEmpty, "true")}if nil == tree.Root.FirstChild {diff --git a/kernel/model/file_index_test.go b/kernel/model/file_index_test.gonew file mode 100644index 0000000000..27411bb6df--- /dev/null+++ b/kernel/model/file_index_test.go@@ -0,0 +1,105 @@+// SiYuan - Refactor your thinking+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++//go:build fts5++package model++import (+ "os"+ "os/exec"+ "path/filepath"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/sql"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++const removeDocSQLTestEnv = "SIYUAN_TEST_REMOVE_DOC_SQL"++func TestRemoveDocFlushesDatabaseIndex(t *testing.T) {+ if "1" != os.Getenv(removeDocSQLTestEnv) {+ cmd := exec.Command(os.Args[0], "-test.run=^TestRemoveDocFlushesDatabaseIndex$", "-test.v")+ cmd.Env = append(os.Environ(), removeDocSQLTestEnv+"=1")+ output, err := cmd.CombinedOutput()+ if nil != err {+ t.Fatalf("remove document SQL subprocess failed: %v\n%s", err, output)+ }+ return+ }++ workspaceDir := t.TempDir()+ util.WorkspaceDir = workspaceDir+ util.ConfDir = filepath.Join(workspaceDir, "conf")+ util.DataDir = filepath.Join(workspaceDir, "data")+ util.HistoryDir = filepath.Join(workspaceDir, "history")+ util.TempDir = filepath.Join(workspaceDir, "temp")+ util.QueueDir = filepath.Join(util.TempDir, "queue")+ util.DBPath = filepath.Join(util.TempDir, util.DBName)+ util.HistoryDBPath = filepath.Join(util.TempDir, "history.db")+ util.AssetContentDBPath = filepath.Join(util.TempDir, "asset_content.db")+ util.BlockTreeDBPath = filepath.Join(util.TempDir, "blocktree.db")+ for _, dir := range []string{util.ConfDir, util.DataDir, util.HistoryDir, util.TempDir, util.QueueDir} {+ if err := os.MkdirAll(dir, 0755); err != nil {+ t.Fatalf("create test directory [%s] failed: %v", dir, err)+ }+ }++ Conf = NewAppConf()+ Conf.FileTree = conf.NewFileTree()+ Conf.NotebookCrypto = conf.NewNotebookCrypto()+ Conf.Sync = conf.NewSync()++ box := &Box{ID: "20260726000000-abcdefg"}+ boxConf := conf.NewBoxConf()+ boxConf.Name = "Remove document SQL test"+ boxConf.Closed = false+ if err := box.SaveConf(boxConf); err != nil {+ t.Fatalf("save test notebook conf failed: %v", err)+ }++ sql.InitDatabase(true)+ sql.InitHistoryDatabase(true)+ sql.InitAssetContentDatabase(true)+ t.Cleanup(sql.CloseDatabase)++ tree := treenode.NewTree(box.ID, "/20260726000001-abcdefg.sy", "/Delete target", "Delete target")+ if err := indexWriteTreeIndexQueue(tree); err != nil {+ t.Fatalf("write and index test document failed: %v", err)+ }+ sql.FlushQueue()+ assertDatabaseBlockExists(t, tree.ID, true)++ if err := RemoveDoc(box.ID, tree.Path); err != nil {+ t.Fatalf("remove test document failed: %v", err)+ }+ sql.FlushQueue()+ assertDatabaseBlockExists(t, tree.ID, false)+}++func assertDatabaseBlockExists(t *testing.T, id string, expected bool) {+ t.Helper()++ rows, err := sql.Query("SELECT id FROM blocks WHERE id = '"+id+"'", 1)+ if nil != err {+ t.Fatalf("query block [%s] failed: %v", id, err)+ }+ if actual := 0 < len(rows); actual != expected {+ t.Fatalf("unexpected database block existence for [%s]: got %t, want %t", id, actual, expected)+ }+}diff --git a/kernel/model/file_test.go b/kernel/model/file_test.goindex 0fe6db440a..40df2b9ed5 100644--- a/kernel/model/file_test.go+++ b/kernel/model/file_test.go@@ -102,6 +102,49 @@ func TestRemoveDocRejectsInvalidPath(t *testing.T) {}}+func TestValidateCreateDocDoesNotWrite(t *testing.T) {+ fixture := setupFileOperationTest(t)+ newID := "20260718000003-abcdefg"++ rootPath := "/" + newID + ".sy"+ if err := ValidateCreateDoc(fixture.box.ID, rootPath, "Root document"); err != nil {+ t.Fatalf("validate root document failed: %v", err)+ }+ if fixture.box.Exist(rootPath) {+ t.Fatalf("validation created root document [%s]", rootPath)+ }++ childPath := path.Join(strings.TrimSuffix(fixture.targetPath, ".sy"), newID+".sy")+ if err := ValidateCreateDoc(fixture.box.ID, childPath, "Child document"); err != nil {+ t.Fatalf("validate child document failed: %v", err)+ }+ if fixture.box.Exist(childPath) {+ t.Fatalf("validation created child document [%s]", childPath)+ }++ invalidChildPath := path.Join(fixture.targetPath, newID+".sy")+ if err := ValidateCreateDoc(fixture.box.ID, invalidChildPath, "Invalid child"); !errors.Is(err, ErrBlockNotFound) {+ t.Fatalf("expected parent path with .sy suffix to return ErrBlockNotFound, got [%v]", err)+ }++ wrongParentPath := path.Join(strings.TrimSuffix(fixture.sourcePath, ".sy"), strings.TrimSuffix(fixture.targetPath, ".sy"), newID+".sy")+ if err := ValidateCreateDoc(fixture.box.ID, wrongParentPath, "Wrong parent"); !errors.Is(err, ErrBlockNotFound) {+ t.Fatalf("expected mismatched parent path to return ErrBlockNotFound, got [%v]", err)+ }++ otherBox := &Box{ID: "20260718000004-abcdefg"}+ otherBoxConf := conf.NewBoxConf()+ otherBoxConf.Name = "Other file operation test"+ otherBoxConf.Closed = false+ if err := otherBox.SaveConf(otherBoxConf); err != nil {+ t.Fatalf("save other test notebook conf failed: %v", err)+ }+ crossBoxPath := path.Join(strings.TrimSuffix(fixture.targetPath, ".sy"), newID+".sy")+ if err := ValidateCreateDoc(otherBox.ID, crossBoxPath, "Cross notebook"); !errors.Is(err, ErrBlockNotFound) {+ t.Fatalf("expected cross-notebook parent to return ErrBlockNotFound, got [%v]", err)+ }+}+func TestGetBoxesByPathsStrictRejectsInvalidPaths(t *testing.T) {fixture := setupFileOperationTest(t)tests := []struct {@@ -128,6 +171,81 @@ func TestGetBoxesByPathsStrictRejectsInvalidPaths(t *testing.T) {}}+func TestBlockTransactionRejectsDocumentMove(t *testing.T) {+ fixture := setupFileOperationTest(t)+ before := treenode.GetBlockTree(fixture.sourceID)+ if nil == before {+ t.Fatalf("source document block tree [%s] not found", fixture.sourceID)+ }++ tx := &Transaction{DoOperations: []*Operation{{+ Action: "move",+ ID: fixture.sourceID,+ ParentID: strings.TrimSuffix(path.Base(fixture.targetPath), ".sy"),+ }}}+ err := PerformTxSync(tx)+ if nil == err {+ t.Fatal("expected document move transaction to be rejected")+ }+ var txErr *TxErr+ if !errors.As(err, &txErr) {+ t.Fatalf("expected transaction error, got [%T] %v", err, err)+ }+ if TxErrCodePushMsg != txErr.Code() {+ t.Fatalf("unexpected transaction error code: got %d, want %d", txErr.Code(), TxErrCodePushMsg)+ }++ after := treenode.GetBlockTree(fixture.sourceID)+ if nil == after {+ t.Fatalf("source document block tree [%s] was removed", fixture.sourceID)+ }+ if before.RootID != after.RootID || before.ParentID != after.ParentID || before.BoxID != after.BoxID ||+ before.Path != after.Path || before.HPath != after.HPath || before.Type != after.Type {+ t.Fatalf("source document block tree changed: before [%+v], after [%+v]", before, after)+ }+ if !fixture.box.Exist(fixture.sourcePath) || !fixture.box.Exist(fixture.targetPath) {+ t.Fatal("document move transaction changed files on disk")+ }+}++func TestBlockTransactionRejectsDocumentPreviousSibling(t *testing.T) {+ fixture := setupFileOperationTest(t)+ before := treenode.GetBlockTree(fixture.childID)+ if nil == before {+ t.Fatalf("source block tree [%s] not found", fixture.childID)+ }++ tx := &Transaction{DoOperations: []*Operation{{+ Action: "move",+ ID: fixture.childID,+ ParentID: fixture.sourceID,+ PreviousID: strings.TrimSuffix(path.Base(fixture.targetPath), ".sy"),+ }}}+ err := PerformTxSync(tx)+ if nil == err {+ t.Fatal("expected document previous sibling to be rejected")+ }+ var txErr *TxErr+ if !errors.As(err, &txErr) {+ t.Fatalf("expected transaction error, got [%T] %v", err, err)+ }+ if TxErrCodePushMsg != txErr.Code() {+ t.Fatalf("unexpected transaction error code: got %d, want %d", txErr.Code(), TxErrCodePushMsg)+ }++ after := treenode.GetBlockTree(fixture.childID)+ if nil == after {+ t.Fatalf("source block tree [%s] was removed", fixture.childID)+ }+ if before.RootID != after.RootID || before.ParentID != after.ParentID || before.BoxID != after.BoxID ||+ before.Path != after.Path || before.HPath != after.HPath || before.Type != after.Type {+ t.Fatalf("source block tree changed: before [%+v], after [%+v]", before, after)+ }+ if !fixture.box.Exist(fixture.sourcePath) || !fixture.box.Exist(fixture.targetPath) {+ t.Fatal("document previous sibling transaction changed files on disk")+ }+}+func TestMoveDocsRejectsInvalidPathsBeforeMoving(t *testing.T) {fixture := setupFileOperationTest(t)newPath := path.Join(strings.TrimSuffix(fixture.targetPath, ".sy"), fixture.sourceID+".sy")diff --git a/kernel/model/transaction.go b/kernel/model/transaction.goindex c4b5ffacde..f0b0fc5ed6 100644--- a/kernel/model/transaction.go+++ b/kernel/model/transaction.go@@ -520,6 +520,19 @@ func (tx *Transaction) doMove(operation *Operation) (ret *TxErr) {logging.LogErrorf("get node [%s] in tree [%s] failed", id, srcTree.Root.ID)return &TxErr{code: TxErrCodeBlockNotFound, id: id}}+ if ast.NodeDocument == srcNode.Type {+ msg := "document blocks cannot be moved with block transactions"+ logging.LogWarnf("%s [%s]", msg, id)+ return &TxErr{code: TxErrCodePushMsg, msg: msg, id: id}+ }+ if targetPreviousID := operation.PreviousID; "" != targetPreviousID {+ if targetBlockTree := treenode.GetBlockTree(targetPreviousID); nil != targetBlockTree &&+ treenode.TypeAbbr(ast.NodeDocument.String()) == targetBlockTree.Type {+ msg := "document blocks cannot be used as previous siblings"+ logging.LogWarnf("%s [%s]", msg, targetPreviousID)+ return &TxErr{code: TxErrCodePushMsg, msg: msg, id: targetPreviousID}+ }+ }// 生成文档历史 https://github.com/siyuan-note/siyuan/issues/14359generateOpTypeHistory(srcTree, HistoryOpUpdate)@@ -567,6 +580,11 @@ func (tx *Transaction) doMove(operation *Operation) (ret *TxErr) {logging.LogErrorf("get node [%s] in tree [%s] failed", targetPreviousID, targetTree.Root.ID)return &TxErr{code: TxErrCodeBlockNotFound, id: targetPreviousID}}+ if ast.NodeDocument == targetNode.Type {+ msg := "document blocks cannot be used as previous siblings"+ logging.LogWarnf("%s [%s]", msg, targetPreviousID)+ return &TxErr{code: TxErrCodePushMsg, msg: msg, id: targetPreviousID}+ }if ast.NodeHeading == targetNode.Type && treenode.IsSelfFolded(targetNode) {targetChildren := treenode.HeadingChildren(targetNode)