An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Unify and cache sync ignore rules safely https://github.com/siyuan-note/siyuan/issues/19397
Danielf781da1ceb90
diff --git a/kernel/go.mod b/kernel/go.modindex 40dfa5191c..ed4a1e1921 100644--- a/kernel/go.mod+++ b/kernel/go.mod@@ -72,7 +72,7 @@ require (github.com/sashabaranov/go-openai v1.42.0github.com/shirou/gopsutil/v4 v4.26.7github.com/siyuan-note/dataparser v0.0.0-20260115084335-b57cb8bc7c17- github.com/siyuan-note/dejavu v0.0.0-20260912132557-f037a610f501+ github.com/siyuan-note/dejavu v0.0.0-20260913022125-a81c0754dcb7github.com/siyuan-note/encryption v0.0.0-20260715062728-9cb8e9548044github.com/siyuan-note/eventbus v0.0.0-20260530125927-d77c74260dcegithub.com/siyuan-note/filelock v0.0.0-20260831011452-393425122aaadiff --git a/kernel/go.sum b/kernel/go.sumindex c61a97f2a1..cbb8c5b2c4 100644--- a/kernel/go.sum+++ b/kernel/go.sum@@ -484,6 +484,8 @@ github.com/siyuan-note/dejavu v0.0.0-20260912093153-963dde2c2a50 h1:0aLHzjW+sZixgithub.com/siyuan-note/dejavu v0.0.0-20260912093153-963dde2c2a50/go.mod h1:ixj6rxm+wkjoV8pBDGbuCyfMiPQh3MlxBwHG5OvtEQU=github.com/siyuan-note/dejavu v0.0.0-20260912132557-f037a610f501 h1:5BXH9LrqIVGvT+q7FNKXo5Z5+JkPiA0SWgVwo6opEpY=github.com/siyuan-note/dejavu v0.0.0-20260912132557-f037a610f501/go.mod h1:ixj6rxm+wkjoV8pBDGbuCyfMiPQh3MlxBwHG5OvtEQU=+github.com/siyuan-note/dejavu v0.0.0-20260913022125-a81c0754dcb7 h1:+NSzydozQJsqkx+wSznWNMicK+ByibKr+aAmm6OXVXA=+github.com/siyuan-note/dejavu v0.0.0-20260913022125-a81c0754dcb7/go.mod h1:ixj6rxm+wkjoV8pBDGbuCyfMiPQh3MlxBwHG5OvtEQU=github.com/siyuan-note/encryption v0.0.0-20260715062728-9cb8e9548044 h1:b1/Q4DSREDvGh1/NbzR9873EKrjakdoUtsNlghWxUOI=github.com/siyuan-note/encryption v0.0.0-20260715062728-9cb8e9548044/go.mod h1:t6jXpJdrXzRsdQF+XGaw35f16JVZcDyIkk5/6//ywnY=github.com/siyuan-note/eventbus v0.0.0-20260530125927-d77c74260dce h1:356bfC3pucxXuYpZIwaQ3viVCbq5RbRuvBhb4xtoBR0=diff --git a/kernel/model/inline_style_test.go b/kernel/model/inline_style_test.goindex aa7e43c3a5..3cbb12b74f 100644--- a/kernel/model/inline_style_test.go+++ b/kernel/model/inline_style_test.go@@ -659,7 +659,7 @@ func TestInlineStylesRepoPath(t *testing.T) {t.Fatalf("unexpected inline styles repository path match: %s", filePath)}}- if ignore.CompileIgnoreLines(getSyncIgnoreLines()...).MatchesPath(inlineStylesRepoPath) {+ if ignore.CompileIgnoreLines(mustSyncIgnoreLines(t)...).MatchesPath(inlineStylesRepoPath) {t.Fatal("inline styles file is ignored by data synchronization")}}diff --git a/kernel/model/mount.go b/kernel/model/mount.goindex 696495551c..a768c86365 100644--- a/kernel/model/mount.go+++ b/kernel/model/mount.go@@ -21,6 +21,7 @@ import ("fmt""os""path/filepath"+ "slices""sort""strings""sync"@@ -573,18 +574,15 @@ func mountBox(boxID string) (alreadyMount bool, err error) {return false, nil}+var userGuideIDs = []string{"20210808180117-6v0mkxr", "20210808180117-czj9bvb", "20211226090932-5lcq56f", "20240530133126-axarxgx"}+func IsUserGuide(boxID string) bool {- return "20210808180117-czj9bvb" == boxID || "20210808180117-6v0mkxr" == boxID || "20211226090932-5lcq56f" == boxID || "20240530133126-axarxgx" == boxID+ return slices.Contains(userGuideIDs, boxID)}func getUserGuideAVJSONFiles(boxID string) (ret []string, err error) {guideAVDirPath := filepath.Join(util.WorkingDir, "guide", boxID, "storage", "av")- if !filelock.IsExist(guideAVDirPath) {- logging.LogErrorf("guide av dir [%s] not exist", guideAVDirPath)- return- }-- avEntries, err := os.ReadDir(guideAVDirPath)+ avEntries, err := readUserGuideDirectory(guideAVDirPath)if nil != err {logging.LogErrorf("read guide av dir [%s] failed: %s", guideAVDirPath, err)return@@ -600,9 +598,9 @@ func getUserGuideAVJSONFiles(boxID string) (ret []string, err error) {return}-func getAllUserGuideAVJSONFiles() (ret []string) {+func getAllUserGuideAVJSONFiles() (ret []string, err error) {guideDirPath := filepath.Join(util.WorkingDir, "guide")- guideEntries, err := os.ReadDir(guideDirPath)+ guideEntries, err := readUserGuideDirectory(guideDirPath)if nil != err {return}@@ -615,9 +613,23 @@ func getAllUserGuideAVJSONFiles() (ret []string) {avFiles, err := getUserGuideAVJSONFiles(boxID)if nil != err {- continue+ return nil, err}ret = append(ret, avFiles...)}return}++func readUserGuideDirectory(dir string) ([]os.DirEntry, error) {+ info, err := os.Stat(dir)+ if os.IsNotExist(err) {+ return nil, nil+ }+ if err != nil {+ return nil, err+ }+ if !info.IsDir() {+ return nil, fmt.Errorf("user guide path is not a directory: %s", dir)+ }+ return os.ReadDir(dir)+}diff --git a/kernel/model/repository.go b/kernel/model/repository.goindex 642ff01bfd..f901e4bbb5 100644--- a/kernel/model/repository.go+++ b/kernel/model/repository.go@@ -2982,8 +2982,20 @@ func newRepositoryWithAssetSourceLocked() (ret *dejavu.Repo, err error) {return}- ignoreLines := getSyncIgnoreLines()- ret, err = dejavu.NewRepo(util.DataDir, util.RepoDir, util.HistoryDir, util.TempDir, Conf.System.ID, Conf.System.Name, Conf.System.OS, Conf.Repo.Key, ignoreLines, cloudRepo)+ ignoreLines, err := getSyncIgnoreLines()+ if err != nil {+ return nil, err+ }+ dataDir := util.DataDir+ ret, err = dejavu.NewRepoWithOptions(dejavu.Options{+ DataPath: util.DataDir, RepoPath: util.RepoDir, HistoryPath: util.HistoryDir, TempPath: util.TempDir,+ DeviceID: Conf.System.ID, DeviceName: Conf.System.Name, DeviceOS: Conf.System.OS,+ AESKey: Conf.Repo.Key, IgnoreLines: ignoreLines, Cloud: cloudRepo,+ IgnoreRulePath: syncIgnoreRulePath, HiddenDirectoryNames: []string{".siyuan"},+ PathFilter: func(info os.FileInfo, absPath string) (bool, error) {+ return syncPathFilter(dataDir, info, absPath)+ },+ })if err != nil {logging.LogErrorf("init data repo failed: %s", err)returndiff --git a/kernel/model/sync.go b/kernel/model/sync.goindex 8413c59636..1e1fed3d8c 100644--- a/kernel/model/sync.go+++ b/kernel/model/sync.go@@ -944,23 +944,26 @@ func bootSyncRepoWithDNSRetry() (err error) {return}-func getSyncIgnoreLines() (ret []string) {+func loadSyncIgnoreLines() (ret []string, err error) {// 忽略旧版同步配置,读取用户规则失败时仍需保留此规则。defer func() {ret = append(ret, "/.siyuan/conf.json")}()ignore := filepath.Join(util.DataDir, ".siyuan", "syncignore")- err := os.MkdirAll(filepath.Dir(ignore), 0755)+ err = os.MkdirAll(filepath.Dir(ignore), 0755)if err != nil {return}- if !gulu.File.IsExist(ignore) {- if err = gulu.File.WriteFileSafer(ignore, nil, 0644); err != nil {- logging.LogErrorf("create syncignore [%s] failed: %s", ignore, err)- return+ data, err := os.ReadFile(ignore)+ if os.IsNotExist(err) {+ var file *os.File+ file, err = os.OpenFile(ignore, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)+ if err == nil {+ err = file.Close()+ } else if os.IsExist(err) {+ data, err = os.ReadFile(ignore)}}- data, err := os.ReadFile(ignore)if err != nil {logging.LogErrorf("read syncignore [%s] failed: %s", ignore, err)return@@ -970,15 +973,18 @@ func getSyncIgnoreLines() (ret []string) {ret = strings.Split(dataStr, "\n")// 忽略用户指南- ret = append(ret, "20210808180117-6v0mkxr/**/*")- ret = append(ret, "20210808180117-czj9bvb/**/*")- ret = append(ret, "20211226090932-5lcq56f/**/*")- ret = append(ret, "20240530133126-axarxgx/**/*")+ for _, id := range userGuideIDs {+ ret = append(ret, id+"/**/*")+ }// 视图状态仅在当前设备使用,不参与数据同步。ret = append(ret, "/storage/view-state.json")ret = append(ret, "/storage/view-state-corrupted-*.json")// 忽略用户指南的数据库 JSON 文件- for _, avName := range getAllUserGuideAVJSONFiles() {+ avNames, err := getAllUserGuideAVJSONFiles()+ if err != nil {+ return nil, err+ }+ for _, avName := range avNames {ret = append(ret, "/storage/av/"+avName)}diff --git a/kernel/model/sync_ignore.go b/kernel/model/sync_ignore.gonew file mode 100644index 0000000000..8860dff044--- /dev/null+++ b/kernel/model/sync_ignore.go@@ -0,0 +1,133 @@+package model++import (+ "os"+ "path/filepath"+ "slices"+ "strings"+ "sync"+ "time"++ ignore "github.com/sabhiram/go-gitignore"+ "github.com/siyuan-note/dejavu"+ "github.com/siyuan-note/siyuan/kernel/util"+)++const syncIgnoreRulePath = ".siyuan/syncignore"++type syncMissingDirectory struct{ name string }++func (d syncMissingDirectory) Name() string { return d.name }+func (d syncMissingDirectory) Size() int64 { return 0 }+func (d syncMissingDirectory) Mode() os.FileMode { return os.ModeDir }+func (d syncMissingDirectory) ModTime() time.Time { return time.Time{} }+func (d syncMissingDirectory) IsDir() bool { return true }+func (d syncMissingDirectory) Sys() any { return nil }++type syncIgnoreStamp struct {+ path string+ size int64+ modified time.Time+ mode os.FileMode+}++var syncIgnoreCache struct {+ sync.Mutex+ stamps []syncIgnoreStamp+ lines []string+ matcher *ignore.GitIgnore+}++func syncIgnoreStamps() (ret []syncIgnoreStamp, valid bool) {+ paths := []string{filepath.Join(util.DataDir, syncIgnoreRulePath), filepath.Join(util.WorkingDir, "guide")}+ for _, id := range userGuideIDs {+ paths = append(paths, filepath.Join(util.WorkingDir, "guide", id, "storage", "av"))+ }+ valid = true+ for _, path := range paths {+ stamp := syncIgnoreStamp{path: path}+ info, err := os.Stat(path)+ if err == nil {+ stamp.size, stamp.modified, stamp.mode = info.Size(), info.ModTime(), info.Mode()+ } else if !os.IsNotExist(err) {+ valid = false+ }+ ret = append(ret, stamp)+ }+ return+}++func getSyncIgnoreRules() ([]string, *ignore.GitIgnore, error) {+ syncIgnoreCache.Lock()+ defer syncIgnoreCache.Unlock()+ stamps, valid := syncIgnoreStamps()+ if valid && syncIgnoreCache.matcher != nil && slices.Equal(stamps, syncIgnoreCache.stamps) {+ return slices.Clone(syncIgnoreCache.lines), syncIgnoreCache.matcher, nil+ }+ lines, err := loadSyncIgnoreLines()+ if err != nil {+ syncIgnoreCache.matcher = nil+ return nil, nil, err+ }+ matcher := ignore.CompileIgnoreLines(lines...)+ // 读取期间发生变化时不缓存,下一次调用重新读取规则。+ after, afterValid := syncIgnoreStamps()+ if valid && afterValid && slices.Equal(stamps, after) {+ syncIgnoreCache.lines, syncIgnoreCache.matcher, syncIgnoreCache.stamps = slices.Clone(lines), matcher, after+ } else {+ syncIgnoreCache.matcher = nil+ }+ return lines, matcher, nil+}++func getSyncIgnoreLines() ([]string, error) {+ lines, _, err := getSyncIgnoreRules()+ return lines, err+}++func invalidateSyncIgnoreRules(absPaths ...string) {+ var resolved []string+ for _, absPath := range absPaths {+ resolved = append(resolved, util.ResolveLongestExistingParent(absPath))+ }+ invalidateResolvedSyncIgnoreRules(util.ResolveLongestExistingParent(util.DataDir), resolved...)+}++func invalidateResolvedSyncIgnoreRules(dataDir string, absPaths ...string) {+ rulePath := filepath.Join(dataDir, syncIgnoreRulePath)+ for _, absPath := range absPaths {+ if _, contains := dataRelativePath(absPath, rulePath); contains {+ syncIgnoreCache.Lock()+ syncIgnoreCache.matcher = nil+ syncIgnoreCache.Unlock()+ return+ }+ }+}++// syncPathFilter 统一索引、签出与同步计划的文件系统及应用层忽略判定。+func syncPathFilter(dataDir string, info os.FileInfo, absPath string) (bool, error) {+ rel, ok := dataRelativePath(dataDir, absPath)+ if !ok {+ return true, nil+ }+ if ignored, err := dejavu.IgnorePath(info, absPath, rel, syncIgnoreRulePath, ".siyuan"); ignored || err != nil {+ return ignored, err+ }+ if info != nil && info.IsDir() {+ if info.Name() == "filesys_status_check" {+ return true, filepath.SkipDir+ }+ return true, nil+ }+ for _, name := range []string{"local.json", "recent-doc.json", "ref-used.json"} {+ if rel == "/storage/"+name {+ return true, nil+ }+ // 保留已发布版本对嵌套路径的排除,避免历史签出删除原本被忽略的文件。+ if strings.HasSuffix(rel, "data/storage/"+name) {+ return true, nil+ }+ }+ return false, nil+}diff --git a/kernel/model/sync_ignore_test.go b/kernel/model/sync_ignore_test.gonew file mode 100644index 0000000000..7aee529e83--- /dev/null+++ b/kernel/model/sync_ignore_test.go@@ -0,0 +1,259 @@+package model++import (+ "os"+ "path/filepath"+ "reflect"+ "sort"+ "testing"++ ignore "github.com/sabhiram/go-gitignore"+ "github.com/siyuan-note/dejavu"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func mustSyncIgnoreRules(t testing.TB) ([]string, *ignore.GitIgnore) {+ t.Helper()+ lines, matcher, err := getSyncIgnoreRules()+ if err != nil {+ t.Fatal(err)+ }+ return lines, matcher+}++func mustSyncIgnoreLines(t testing.TB) []string {+ t.Helper()+ lines, _ := mustSyncIgnoreRules(t)+ return lines+}++func TestSyncIgnoreGuideReadFailureRecovers(t *testing.T) {+ oldData, oldWorking := util.DataDir, util.WorkingDir+ util.DataDir, util.WorkingDir = t.TempDir(), t.TempDir()+ t.Cleanup(func() { util.DataDir, util.WorkingDir = oldData, oldWorking })+ guide := filepath.Join(util.WorkingDir, "guide")+ writeSyncPathTestFile(t, guide)+ if _, matcher, err := getSyncIgnoreRules(); err == nil || matcher != nil {+ t.Fatal("guide read failure must not produce usable rules")+ }+ if err := os.Remove(guide); err != nil {+ t.Fatal(err)+ }+ mustSyncIgnoreRules(t)+}++func TestSyncIgnoreRepositoryRejectsUnreadableRules(t *testing.T) {+ prepareAssetDownloadRepoTest(t)+ p := filepath.Join(util.DataDir, syncIgnoreRulePath)+ if err := os.Remove(p); err != nil && !os.IsNotExist(err) {+ t.Fatal(err)+ }+ if err := os.MkdirAll(p, 0755); err != nil {+ t.Fatal(err)+ }+ if repo, err := newRepository(); err == nil || repo != nil {+ t.Fatal("repository creation continued with unreadable rules")+ }+ if err := os.Remove(p); err != nil {+ t.Fatal(err)+ }+ if _, err := newRepository(); err != nil {+ t.Fatalf("repository creation did not recover: %v", err)+ }+}++func TestSyncPathFilterUsesBoundRoot(t *testing.T) {+ oldData := util.DataDir+ util.DataDir = t.TempDir()+ t.Cleanup(func() { util.DataDir = oldData })+ root := t.TempDir()+ for _, tc := range []struct {+ path string+ ignored bool+ }{{"assets/tracked.txt", false}, {"storage/local.json", true}} {+ p := filepath.Join(root, tc.path)+ writeSyncPathTestFile(t, p)+ info, err := os.Stat(p)+ if err != nil {+ t.Fatal(err)+ }+ if ignored, err := syncPathFilter(root, info, p); err != nil || ignored != tc.ignored {+ t.Fatalf("bound root was not used for %s: %v %v", tc.path, ignored, err)+ }+ }+}++func TestPathsAffectSyncLinkedDataRoot(t *testing.T) {+ oldData := util.DataDir+ t.Cleanup(func() { util.DataDir = oldData })+ root := t.TempDir()+ util.DataDir = filepath.Join(t.TempDir(), "data")+ if err := os.Symlink(root, util.DataDir); err != nil {+ t.Skipf("symlinks unavailable: %v", err)+ }+ p := filepath.Join(util.DataDir, "assets", "tracked.txt")+ writeSyncPathTestFile(t, p)+ if !PathsAffectSync(p) {+ t.Fatal("linked data root lost a tracked change")+ }+}++func TestSyncIgnoreCache(t *testing.T) {+ oldData, oldWorking := util.DataDir, util.WorkingDir+ util.DataDir, util.WorkingDir = t.TempDir(), t.TempDir()+ t.Cleanup(func() { util.DataDir, util.WorkingDir = oldData, oldWorking })+ rule := filepath.Join(util.DataDir, syncIgnoreRulePath)+ writeSyncPathTestFile(t, rule)+ if err := os.WriteFile(rule, []byte("/one.txt"), 0644); err != nil {+ t.Fatal(err)+ }+ lines, first := mustSyncIgnoreRules(t)+ lines[0] = "/wrong.txt"+ _, second := mustSyncIgnoreRules(t)+ if first != second || !second.MatchesPath("/one.txt") {+ t.Fatal("unchanged rules were not reused")+ }+ info, err := os.Stat(rule)+ if err != nil {+ t.Fatal(err)+ }+ if err = os.WriteFile(rule, []byte("/two.txt"), 0644); err != nil {+ t.Fatal(err)+ }+ if err = os.Chtimes(rule, info.ModTime(), info.ModTime()); err != nil {+ t.Fatal(err)+ }+ invalidateSyncIgnoreRules(rule)+ _, third := mustSyncIgnoreRules(t)+ if third == second || !third.MatchesPath("/two.txt") || third.MatchesPath("/one.txt") {+ t.Fatal("explicit invalidation did not reload same-size rules")+ }+ if err = os.WriteFile(rule, []byte("/external.txt"), 0644); err != nil {+ t.Fatal(err)+ }+ _, fourth := mustSyncIgnoreRules(t)+ if !fourth.MatchesPath("/external.txt") {+ t.Fatal("external change was not detected")+ }+ avName := "20260913123456-abcdefg.json"+ avPath := filepath.Join(util.WorkingDir, "guide", "20210808180117-6v0mkxr", "storage", "av", avName)+ writeSyncPathTestFile(t, avPath)+ _, fifth := mustSyncIgnoreRules(t)+ if !fifth.MatchesPath("/storage/av/" + avName) {+ t.Fatal("guide directory change was not detected")+ }+ if err = os.Remove(avPath); err != nil {+ t.Fatal(err)+ }+ _, sixth := mustSyncIgnoreRules(t)+ if sixth.MatchesPath("/storage/av/" + avName) {+ t.Fatal("removed guide file remains ignored")+ }+}++func BenchmarkSyncIgnoreRules(b *testing.B) {+ oldData, oldWorking := util.DataDir, util.WorkingDir+ util.DataDir, util.WorkingDir = b.TempDir(), b.TempDir()+ b.Cleanup(func() { util.DataDir, util.WorkingDir = oldData, oldWorking })+ getSyncIgnoreRules()+ getSyncIgnoreRules()+ b.Run("cached", func(b *testing.B) {+ for b.Loop() {+ getSyncIgnoreRules()+ }+ })+ b.Run("uncached", func(b *testing.B) {+ for b.Loop() {+ lines, err := loadSyncIgnoreLines()+ if err != nil {+ b.Fatal(err)+ }+ ignore.CompileIgnoreLines(lines...)+ }+ })+}++func TestSyncIgnoreRepoCompatibility(t *testing.T) {+ oldConf := Conf+ Conf = &AppConf{Lang: "en"}+ t.Cleanup(func() { Conf = oldConf })+ oldData := util.DataDir+ base := t.TempDir()+ util.DataDir = filepath.Join(base, "data")+ t.Cleanup(func() { util.DataDir = oldData })+ paths := []string{+ ".siyuan/searchignore", ".siyuan/embeddingignore", ".siyuan/indexignore", ".siyuan/refsearchignore",+ ".siyuan/data-crypto-backup.json", ".siyuan/conf.json", "box/.siyuan/conf.json",+ ".hidden/file", "box/.hidden/file", "assets/file.tmp", "assets/tracked.txt",+ "storage/local.json", "storage/recent-doc.json", "storage/ref-used.json", "storage/view-state.json",+ "storage/view-state-corrupted-20260913000000.json", "nested/data/storage/local.json",+ "filesys_status_check/file", "nested/filesys_status_check/file", "20210808180117-6v0mkxr/file.sy",+ }+ for _, path := range paths {+ writeSyncPathTestFile(t, filepath.Join(util.DataDir, path))+ if err := os.WriteFile(filepath.Join(util.DataDir, path), []byte(path), 0644); err != nil {+ t.Fatal(err)+ }+ }+ key := []byte("0123456789abcdef0123456789abcdef")+ lines := mustSyncIgnoreLines(t)+ legacy, err := dejavu.NewRepo(util.DataDir, filepath.Join(base, "repo"), filepath.Join(base, "history"), filepath.Join(base, "temp"), "device", "device", "windows", key, lines, nil)+ if err != nil {+ t.Fatal(err)+ }+ before, err := legacy.Index("legacy", false, nil)+ if err != nil {+ t.Fatal(err)+ }+ previous, err := legacy.GetFiles(before)+ if err != nil {+ t.Fatal(err)+ }+ repo, err := dejavu.NewRepoWithOptions(dejavu.Options{+ DataPath: util.DataDir, RepoPath: filepath.Join(base, "repo"), HistoryPath: filepath.Join(base, "history"), TempPath: filepath.Join(base, "temp"),+ DeviceID: "device", DeviceName: "device", DeviceOS: "windows", AESKey: key,+ IgnoreLines: lines, IgnoreRulePath: syncIgnoreRulePath, HiddenDirectoryNames: []string{".siyuan"},+ PathFilter: func(info os.FileInfo, absPath string) (bool, error) {+ return syncPathFilter(util.DataDir, info, absPath)+ },+ })+ if err != nil {+ t.Fatal(err)+ }+ after, err := repo.Index("options", false, nil)+ if err != nil {+ t.Fatal(err)+ }+ current, err := repo.GetFiles(after)+ if err != nil {+ t.Fatal(err)+ }+ var oldPaths, newPaths []string+ tracked := map[string]bool{}+ for _, file := range previous {+ oldPaths = append(oldPaths, file.Path)+ }+ for _, file := range current {+ newPaths = append(newPaths, file.Path)+ tracked[file.Path] = true+ }+ sort.Strings(oldPaths)+ sort.Strings(newPaths)+ if !reflect.DeepEqual(oldPaths, newPaths) {+ t.Fatalf("index changed: %v -> %v", oldPaths, newPaths)+ }+ for _, path := range paths {+ if got := PathsAffectSync(filepath.Join(util.DataDir, path)); got != tracked["/"+path] {+ t.Fatalf("scheduling differs from index: %s", path)+ }+ }+ if _, _, err = repo.Checkout(before.ID, nil); err != nil {+ t.Fatal(err)+ }+ for _, path := range paths {+ data, readErr := os.ReadFile(filepath.Join(util.DataDir, path))+ if readErr != nil || string(data) != path {+ t.Fatalf("checkout changed %s: %q %v", path, data, readErr)+ }+ }+}diff --git a/kernel/model/sync_ignore_windows_test.go b/kernel/model/sync_ignore_windows_test.gonew file mode 100644index 0000000000..54457a95e7--- /dev/null+++ b/kernel/model/sync_ignore_windows_test.go@@ -0,0 +1,53 @@+package model++import (+ "os"+ "path/filepath"+ "syscall"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestSyncIgnoreReadFailureRecovers(t *testing.T) {+ oldData, oldWorking := util.DataDir, util.WorkingDir+ util.DataDir, util.WorkingDir = t.TempDir(), t.TempDir()+ t.Cleanup(func() { util.DataDir, util.WorkingDir = oldData, oldWorking })+ p := filepath.Join(util.DataDir, syncIgnoreRulePath)+ writeSyncPathTestFile(t, p)+ if err := os.WriteFile(p, []byte("/private/**/*"), 0644); err != nil {+ t.Fatal(err)+ }+ ptr, err := syscall.UTF16PtrFromString(p)+ if err != nil {+ t.Fatal(err)+ }+ h, err := syscall.CreateFile(ptr, syscall.GENERIC_READ, syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_DELETE,+ nil, syscall.OPEN_EXISTING, syscall.FILE_ATTRIBUTE_NORMAL, 0)+ if err != nil {+ t.Fatal(err)+ }+ closed := false+ defer func() {+ if !closed {+ syscall.CloseHandle(h)+ }+ }()+ if _, err = os.Stat(p); err != nil {+ t.Fatal(err)+ }+ if _, matcher, loadErr := getSyncIgnoreRules(); loadErr == nil || matcher != nil {+ t.Fatal("unreadable rules must return an error without a matcher")+ }+ if !PathsAffectSync(filepath.Join(util.DataDir, "private", "secret.txt")) {+ t.Fatal("read failure must conservatively schedule sync")+ }+ if err = syscall.CloseHandle(h); err != nil {+ t.Fatal(err)+ }+ closed = true+ _, matcher := mustSyncIgnoreRules(t)+ if !matcher.MatchesPath("/private/secret.txt") {+ t.Fatal("rules did not recover after the sharing violation ended")+ }+}diff --git a/kernel/model/sync_path.go b/kernel/model/sync_path.goindex 9e965961b0..9a20ba853a 100644--- a/kernel/model/sync_path.go+++ b/kernel/model/sync_path.go@@ -22,13 +22,16 @@ import ("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 {+ return pathsAffectSync(false, absPaths...)+}++func pathsAffectSync(invalidate bool, absPaths ...string) bool {if 0 == len(absPaths) {return false}@@ -43,8 +46,14 @@ func PathsAffectSync(absPaths ...string) bool {if 0 == len(dataPaths) {return false}+ if invalidate {+ invalidateResolvedSyncIgnoreRules(dataDir, dataPaths...)+ }- matcher := ignore.CompileIgnoreLines(getSyncIgnoreLines()...)+ _, matcher, err := getSyncIgnoreRules()+ if err != nil {+ return true+ }for _, absPath := range dataPaths {if pathAffectsSync(dataDir, absPath, matcher) {return true@@ -55,7 +64,7 @@ func PathsAffectSync(absPaths ...string) bool {// IncSyncIfNeeded 在指定路径的变更会影响数据同步仓库时重新计划同步。func IncSyncIfNeeded(absPaths ...string) {- if PathsAffectSync(absPaths...) {+ if pathsAffectSync(true, absPaths...) {IncSync()}}@@ -73,7 +82,7 @@ func pathAffectsSync(dataDir, absPath string, matcher *ignore.GitIgnore) bool {info, err := os.Stat(absPath)if nil != err || !info.IsDir() {- return syncFilePathIncluded(absPath, relPath, info, matcher)+ return syncFilePathIncluded(dataDir, absPath, relPath, info, matcher)}syncIgnorePath := filepath.Join(dataDir, ".siyuan", "syncignore")@@ -82,7 +91,10 @@ func pathAffectsSync(dataDir, absPath string, matcher *ignore.GitIgnore) bool {return true}}- if syncPathHasSkippedDir(relPath, true) {+ if syncPathHasSkippedDir(dataDir, relPath, true) {+ return false+ }+ if _, filterErr := syncPathFilter(dataDir, info, absPath); filterErr != nil {return false}affects := false@@ -96,9 +108,16 @@ func pathAffectsSync(dataDir, absPath string, matcher *ignore.GitIgnore) bool {return nil}if entry.IsDir() {- if path != absPath && syncPathHasSkippedDir(rel, true) {+ if path != absPath && syncPathHasSkippedDir(dataDir, rel, true) {return filepath.SkipDir}+ info, infoErr := entry.Info()+ if infoErr != nil {+ return infoErr+ }+ if _, filterErr := syncPathFilter(dataDir, info, path); filterErr != nil {+ return filterErr+ }return nil}entryInfo, infoErr := entry.Info()@@ -106,7 +125,7 @@ func pathAffectsSync(dataDir, absPath string, matcher *ignore.GitIgnore) bool {affects = truereturn fs.SkipAll}- if syncFilePathIncluded(path, rel, entryInfo, matcher) {+ if syncFilePathIncluded(dataDir, path, rel, entryInfo, matcher) {affects = truereturn fs.SkipAll}@@ -126,30 +145,28 @@ func dataRelativePath(dataDir, absPath string) (string, bool) {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") {+func syncFilePathIncluded(dataDir, absPath, relPath string, info os.FileInfo, matcher *ignore.GitIgnore) bool {+ if syncPathHasSkippedDir(dataDir, relPath, false) {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)) {+ if ignored, err := syncPathFilter(dataDir, info, absPath); ignored || err != nil {return false}return !matcher.MatchesPath(relPath)}-func syncPathHasSkippedDir(relPath string, includeLast bool) bool {+func syncPathHasSkippedDir(dataDir, relPath string, includeLast bool) bool {parts := strings.Split(strings.TrimPrefix(filepath.ToSlash(relPath), "/"), "/")if !includeLast && 0 < len(parts) {parts = parts[:len(parts)-1]}+ absPath := dataDirfor _, part := range parts {- if (strings.HasPrefix(part, ".") && ".siyuan" != part) || "filesys_status_check" == part {+ if part == "" {+ continue+ }+ absPath = filepath.Join(absPath, part)+ if _, err := syncPathFilter(dataDir, syncMissingDirectory{name: part}, absPath); err != nil {return true}}diff --git a/kernel/model/sync_path_test.go b/kernel/model/sync_path_test.goindex fc9a2fc0c8..0116dfb9c3 100644--- a/kernel/model/sync_path_test.go+++ b/kernel/model/sync_path_test.go@@ -140,7 +140,7 @@ func TestPathsAffectSyncMetadata(t *testing.T) {metadataDir := filepath.Join(util.DataDir, ".siyuan")writeSyncPathTestFile(t, filepath.Join(metadataDir, "data-crypto-backup.json"))- matcher := ignore.CompileIgnoreLines(getSyncIgnoreLines()...)+ matcher := ignore.CompileIgnoreLines(mustSyncIgnoreLines(t)...)if err := os.Remove(filepath.Join(metadataDir, "syncignore")); nil != err {t.Fatal(err)}@@ -160,9 +160,8 @@ func TestSyncIgnoreLegacyConfReadFailure(t *testing.T) {util.DataDir = oldDataDir})writeSyncPathTestFile(t, filepath.Join(util.DataDir, ".siyuan"))- matcher := ignore.CompileIgnoreLines(getSyncIgnoreLines()...)- if !matcher.MatchesPath("/.siyuan/conf.json") {- t.Fatal("legacy sync configuration must remain ignored when rules cannot be read")+ if _, _, err := getSyncIgnoreRules(); err == nil {+ t.Fatal("unreadable rules must prevent repository creation")}}diff --git a/kernel/model/view_state_test.go b/kernel/model/view_state_test.goindex e36584e235..5296d31caa 100644--- a/kernel/model/view_state_test.go+++ b/kernel/model/view_state_test.go@@ -377,7 +377,7 @@ func TestViewStateIsIgnoredBySync(t *testing.T) {util.DataDir = oldDataDir})- ignoreLines := getSyncIgnoreLines()+ ignoreLines := mustSyncIgnoreLines(t)lines := map[string]bool{}for _, line := range ignoreLines {lines[line] = true