empty_dir_tracker.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright (C) 2017 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package versioner
  7. import (
  8. "log/slog"
  9. "path/filepath"
  10. "slices"
  11. "strings"
  12. "github.com/syncthing/syncthing/internal/slogutil"
  13. "github.com/syncthing/syncthing/lib/fs"
  14. )
  15. type emptyDirTracker map[string]struct{}
  16. func (t emptyDirTracker) addDir(path string) {
  17. if path == "." {
  18. return
  19. }
  20. t[path] = struct{}{}
  21. }
  22. // Remove all dirs from the path to the file
  23. func (t emptyDirTracker) addFile(path string) {
  24. dir := filepath.Dir(path)
  25. for dir != "." {
  26. delete(t, dir)
  27. dir = filepath.Dir(dir)
  28. }
  29. }
  30. func (t emptyDirTracker) emptyDirs() []string {
  31. var empty []string
  32. for dir := range t {
  33. empty = append(empty, dir)
  34. }
  35. slices.SortFunc(empty, func(a, b string) int {
  36. return strings.Compare(b, a)
  37. })
  38. return empty
  39. }
  40. func (t emptyDirTracker) deleteEmptyDirs(fs fs.Filesystem) {
  41. for _, path := range t.emptyDirs() {
  42. l.Debugln("Cleaner: deleting empty directory", path)
  43. err := fs.Remove(path)
  44. if err != nil {
  45. slog.Warn("Failed to remove versioned directory", slogutil.FilePath(path), slogutil.Error(err))
  46. }
  47. }
  48. }