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: Avoid sync after writing ignored files https://github.com/siyuan-note/siyuan/issues/19130
Daniel5707b825db61
diff --git a/kernel/api/file.go b/kernel/api/file.goindex 7b42c8e9ad..d62b0ac8e8 100644--- a/kernel/api/file.go+++ b/kernel/api/file.go@@ -104,6 +104,10 @@ func getUniqueFilename(c *gin.Context) {func globalCopyFiles(c *gin.Context) {ret := gulu.Ret.NewResult()defer c.JSON(http.StatusOK, ret)+ var changedPaths []string+ defer func() {+ model.IncSyncIfNeeded(changedPaths...)+ }()arg, ok := util.JsonArg(c, ret)if !ok {@@ -215,14 +219,17 @@ func globalCopyFiles(c *gin.Context) {ret.Msg = err.Error()return}+ changedPaths = append(changedPaths, dest)}-- model.IncSync()}func workspaceCopyFiles(c *gin.Context) {ret := gulu.Ret.NewResult()defer c.JSON(http.StatusOK, ret)+ var changedPaths []string+ defer func() {+ model.IncSyncIfNeeded(changedPaths...)+ }()arg, ok := util.JsonArg(c, ret)if !ok {@@ -334,9 +341,8 @@ func workspaceCopyFiles(c *gin.Context) {ret.Msg = err.Error()return}+ changedPaths = append(changedPaths, dest)}-- model.IncSync()}func copyFile(c *gin.Context) {@@ -429,7 +435,7 @@ func copyFile(c *gin.Context) {return}- model.IncSync()+ model.IncSyncIfNeeded(dest)}func getFile(c *gin.Context) {@@ -719,6 +725,7 @@ func renameFile(c *gin.Context) {ret.Msg = "Field [newPath]: cannot rename a directory into its own subdirectory"return}+ affectsSync := model.PathsAffectSync(srcAbsPath)destParent := filepath.Dir(destAbsPath)if filelock.IsExist(destParent) {@@ -750,7 +757,9 @@ func renameFile(c *gin.Context) {return}- model.IncSync()+ if affectsSync || model.PathsAffectSync(destAbsPath) {+ model.IncSync()+ }}func removeFile(c *gin.Context) {@@ -794,6 +803,7 @@ func removeFile(c *gin.Context) {ret.Msg = http.StatusText(http.StatusInternalServerError) + errMsgSeeKernelLogreturn}+ affectsSync := model.PathsAffectSync(fileAbsPath)if err = filelock.RemoveWithoutFatal(fileAbsPath); err != nil {logging.LogErrorf("remove [%s] failed: %s", fileAbsPath, err)@@ -802,7 +812,9 @@ func removeFile(c *gin.Context) {return}- model.IncSync()+ if affectsSync {+ model.IncSync()+ }}func putFile(c *gin.Context) {@@ -924,7 +936,9 @@ func putFile(c *gin.Context) {return}- model.IncSync()+ if !isDir {+ model.IncSyncIfNeeded(fileAbsPath)+ }}func millisecond2Time(t int64) time.Time {diff --git a/kernel/model/sync_path.go b/kernel/model/sync_path.gonew file mode 100644index 0000000000..264135fbe5--- /dev/null+++ b/kernel/model/sync_path.go@@ -0,0 +1,158 @@+// SiYuan - From thought to insight, with agents+// 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/>.++package model++import (+ "io/fs"+ "os"+ "path/filepath"+ "strings"++ "github.com/88250/gulu"+ ignore "github.com/sabhiram/go-gitignore"+ "github.com/siyuan-note/siyuan/kernel/util"+)++// PathsAffectSync 判断指定路径的变更是否会影响数据同步仓库。+func PathsAffectSync(absPaths ...string) bool {+ if 0 == len(absPaths) {+ return false+ }+ dataDir := util.ResolveLongestExistingParent(util.DataDir)+ var dataPaths []string+ for _, absPath := range absPaths {+ resolved := util.ResolveLongestExistingParent(absPath)+ if _, ok := dataRelativePath(dataDir, resolved); ok {+ dataPaths = append(dataPaths, resolved)+ }+ }+ if 0 == len(dataPaths) {+ return false+ }++ matcher := ignore.CompileIgnoreLines(getSyncIgnoreLines()...)+ for _, absPath := range dataPaths {+ if pathAffectsSync(dataDir, absPath, matcher) {+ return true+ }+ }+ return false+}++// IncSyncIfNeeded 在指定路径的变更会影响数据同步仓库时重新计划同步。+func IncSyncIfNeeded(absPaths ...string) {+ if PathsAffectSync(absPaths...) {+ IncSync()+ }+}++func pathAffectsSync(dataDir, absPath string, matcher *ignore.GitIgnore) bool {+ absPath = util.ResolveLongestExistingParent(absPath)+ relPath, ok := dataRelativePath(dataDir, absPath)+ if !ok {+ return false+ }++ // 修改同步忽略规则会改变仓库内容,规则文件本身虽然不参与同步也需要重新计划同步。+ if "/.siyuan/syncignore" == relPath {+ return true+ }++ info, err := os.Stat(absPath)+ if nil != err || !info.IsDir() {+ return syncFilePathIncluded(absPath, relPath, info, matcher)+ }++ syncIgnorePath := filepath.Join(dataDir, ".siyuan", "syncignore")+ if _, containsSyncIgnore := dataRelativePath(absPath, syncIgnorePath); containsSyncIgnore {+ if _, statErr := os.Stat(syncIgnorePath); nil == statErr {+ return true+ }+ }+ if syncPathHasSkippedDir(relPath, true) {+ return false+ }+ affects := false+ err = filepath.WalkDir(absPath, func(path string, entry fs.DirEntry, walkErr error) error {+ if nil != walkErr {+ affects = true+ return fs.SkipAll+ }+ rel, included := dataRelativePath(dataDir, path)+ if !included {+ return nil+ }+ if entry.IsDir() {+ if path != absPath && syncPathHasSkippedDir(rel, true) {+ return filepath.SkipDir+ }+ return nil+ }+ entryInfo, infoErr := entry.Info()+ if nil != infoErr {+ affects = true+ return fs.SkipAll+ }+ if syncFilePathIncluded(path, rel, entryInfo, matcher) {+ affects = true+ return fs.SkipAll+ }+ return nil+ })+ return affects || nil != err+}++func dataRelativePath(dataDir, absPath string) (string, bool) {+ relPath, err := filepath.Rel(dataDir, absPath)+ if nil != err || filepath.IsAbs(relPath) || ".." == relPath || strings.HasPrefix(relPath, ".."+string(os.PathSeparator)) {+ return "", false+ }+ if "." == relPath {+ return "/", true+ }+ return "/" + filepath.ToSlash(relPath), true+}++func syncFilePathIncluded(absPath, relPath string, info os.FileInfo, matcher *ignore.GitIgnore) bool {+ if syncPathHasSkippedDir(relPath, false) {+ return false+ }+ name := filepath.Base(absPath)+ if strings.HasPrefix(name, ".") || strings.HasSuffix(name, ".tmp") {+ return false+ }+ if "/storage/local.json" == relPath || "/storage/recent-doc.json" == relPath || "/storage/ref-used.json" == relPath {+ return false+ }+ if nil != info && (!info.Mode().IsRegular() || gulu.File.IsHidden(absPath)) {+ return false+ }+ return !matcher.MatchesPath(relPath)+}++func syncPathHasSkippedDir(relPath string, includeLast bool) bool {+ parts := strings.Split(strings.TrimPrefix(filepath.ToSlash(relPath), "/"), "/")+ if !includeLast && 0 < len(parts) {+ parts = parts[:len(parts)-1]+ }+ for _, part := range parts {+ if strings.HasPrefix(part, ".") || "filesys_status_check" == part {+ return true+ }+ }+ return false+}diff --git a/kernel/model/sync_path_test.go b/kernel/model/sync_path_test.gonew file mode 100644index 0000000000..962a500685--- /dev/null+++ b/kernel/model/sync_path_test.go@@ -0,0 +1,141 @@+// SiYuan - From thought to insight, with agents+// 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/>.++package model++import (+ "os"+ "path/filepath"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestPathsAffectSync(t *testing.T) {+ oldDataDir := util.DataDir+ util.DataDir = t.TempDir()+ t.Cleanup(func() {+ util.DataDir = oldDataDir+ })++ outsideDir := t.TempDir()+ outsideFile := filepath.Join(outsideDir, "export.zip")+ writeSyncPathTestFile(t, outsideFile)+ if PathsAffectSync(outsideFile) {+ t.Fatal("workspace path outside data should not affect sync")+ }+ if _, err := os.Stat(filepath.Join(util.DataDir, ".siyuan", "syncignore")); !os.IsNotExist(err) {+ t.Fatal("checking a path outside data should not create syncignore")+ }++ syncIgnorePath := filepath.Join(util.DataDir, ".siyuan", "syncignore")+ if err := os.MkdirAll(filepath.Dir(syncIgnorePath), 0755); nil != err {+ t.Fatal(err)+ }+ ignoreData := []byte("/ignored/**/*\n!/ignored/keep.txt\n/ignored-only/**/*\n")+ if err := os.WriteFile(syncIgnorePath, ignoreData, 0644); nil != err {+ t.Fatal(err)+ }++ trackedFile := filepath.Join(util.DataDir, "assets", "tracked.txt")+ writeSyncPathTestFile(t, trackedFile)+ if !PathsAffectSync(trackedFile) {+ t.Fatal("tracked data file should affect sync")+ }++ ignoredFile := filepath.Join(util.DataDir, "ignored", "drop.txt")+ writeSyncPathTestFile(t, ignoredFile)+ if PathsAffectSync(ignoredFile) {+ t.Fatal("syncignore path should not affect sync")+ }++ unignoredFile := filepath.Join(util.DataDir, "ignored", "keep.txt")+ writeSyncPathTestFile(t, unignoredFile)+ if !PathsAffectSync(unignoredFile) {+ t.Fatal("negated syncignore path should affect sync")+ }++ ignoredDir := filepath.Join(util.DataDir, "ignored-only")+ writeSyncPathTestFile(t, filepath.Join(ignoredDir, "drop.txt"))+ if PathsAffectSync(ignoredDir) {+ t.Fatal("directory containing only ignored files should not affect sync")+ }+ if !PathsAffectSync(filepath.Join(util.DataDir, "ignored")) {+ t.Fatal("directory containing an unignored file should affect sync")+ }++ if !PathsAffectSync(syncIgnorePath) {+ t.Fatal("syncignore changes should affect sync")+ }+ if !PathsAffectSync(filepath.Dir(syncIgnorePath)) {+ t.Fatal("directory containing syncignore should affect sync")+ }+ for _, ignored := range []string{+ filepath.Join(util.DataDir, ".hidden", "file.txt"),+ filepath.Join(util.DataDir, "assets", "upload.tmp"),+ filepath.Join(util.DataDir, "filesys_status_check", "status"),+ filepath.Join(util.DataDir, "storage", "local.json"),+ filepath.Join(util.DataDir, "storage", "recent-doc.json"),+ filepath.Join(util.DataDir, "storage", "ref-used.json"),+ filepath.Join(util.DataDir, "storage", "view-state.json"),+ } {+ writeSyncPathTestFile(t, ignored)+ if PathsAffectSync(ignored) {+ t.Fatalf("repository ignored path should not affect sync: %s", ignored)+ }+ }+}++func TestPathsAffectSyncResolvesSymlinks(t *testing.T) {+ oldDataDir := util.DataDir+ util.DataDir = t.TempDir()+ t.Cleanup(func() {+ util.DataDir = oldDataDir+ })++ trackedDir := filepath.Join(util.DataDir, "assets")+ trackedFile := filepath.Join(trackedDir, "tracked.txt")+ writeSyncPathTestFile(t, trackedFile)+ outsideDir := t.TempDir()+ incomingLink := filepath.Join(outsideDir, "data-link")+ if err := os.Symlink(trackedDir, incomingLink); nil != err {+ t.Skipf("create symlink failed: %s", err)+ }+ if !PathsAffectSync(filepath.Join(incomingLink, "tracked.txt")) {+ t.Fatal("path resolving into data should affect sync")+ }++ externalTargetDir := t.TempDir()+ externalTarget := filepath.Join(externalTargetDir, "external.txt")+ writeSyncPathTestFile(t, externalTarget)+ outgoingLink := filepath.Join(util.DataDir, "external-link")+ if err := os.Symlink(externalTargetDir, outgoingLink); nil != err {+ t.Skipf("create symlink failed: %s", err)+ }+ if PathsAffectSync(filepath.Join(outgoingLink, "external.txt")) {+ t.Fatal("path resolving outside data should not affect sync")+ }+}++func writeSyncPathTestFile(t *testing.T, path string) {+ t.Helper()+ if err := os.MkdirAll(filepath.Dir(path), 0755); nil != err {+ t.Fatal(err)+ }+ if err := os.WriteFile(path, []byte("test"), 0644); nil != err {+ t.Fatal(err)+ }+}