empty_dir_tracker.go 1.1 KB

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