1
0

empty_dir_tracker.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. "path/filepath"
  9. "slices"
  10. "strings"
  11. "github.com/syncthing/syncthing/lib/fs"
  12. )
  13. type emptyDirTracker map[string]struct{}
  14. func (t emptyDirTracker) addDir(path string) {
  15. if path == "." {
  16. return
  17. }
  18. t[path] = struct{}{}
  19. }
  20. // Remove all dirs from the path to the file
  21. func (t emptyDirTracker) addFile(path string) {
  22. dir := filepath.Dir(path)
  23. for dir != "." {
  24. delete(t, dir)
  25. dir = filepath.Dir(dir)
  26. }
  27. }
  28. func (t emptyDirTracker) emptyDirs() []string {
  29. var empty []string
  30. for dir := range t {
  31. empty = append(empty, dir)
  32. }
  33. slices.SortFunc(empty, func(a, b string) int {
  34. return strings.Compare(b, a)
  35. })
  36. return empty
  37. }
  38. func (t emptyDirTracker) deleteEmptyDirs(fs fs.Filesystem) {
  39. for _, path := range t.emptyDirs() {
  40. l.Debugln("Cleaner: deleting empty directory", path)
  41. err := fs.Remove(path)
  42. if err != nil {
  43. l.Warnln("Versioner: can't remove directory", path, err)
  44. }
  45. }
  46. }