simple.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // Copyright (C) 2014 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. "context"
  9. "strconv"
  10. "time"
  11. "github.com/syncthing/syncthing/lib/config"
  12. "github.com/syncthing/syncthing/lib/fs"
  13. )
  14. func init() {
  15. // Register the constructor for this type of versioner with the name "simple"
  16. factories["simple"] = newSimple
  17. }
  18. type simple struct {
  19. keep int
  20. cleanoutDays int
  21. folderFs fs.Filesystem
  22. versionsFs fs.Filesystem
  23. copyRangeMethod fs.CopyRangeMethod
  24. }
  25. func newSimple(cfg config.FolderConfiguration) Versioner {
  26. var keep, err = strconv.Atoi(cfg.Versioning.Params["keep"])
  27. cleanoutDays, _ := strconv.Atoi(cfg.Versioning.Params["cleanoutDays"])
  28. // On error we default to 0, "do not clean out the trash can"
  29. if err != nil {
  30. keep = 5 // A reasonable default
  31. }
  32. s := simple{
  33. keep: keep,
  34. cleanoutDays: cleanoutDays,
  35. folderFs: cfg.Filesystem(),
  36. versionsFs: versionerFsFromFolderCfg(cfg),
  37. copyRangeMethod: cfg.CopyRangeMethod,
  38. }
  39. l.Debugf("instantiated %#v", s)
  40. return s
  41. }
  42. // Archive moves the named file away to a version archive. If this function
  43. // returns nil, the named file does not exist any more (has been archived).
  44. func (v simple) Archive(filePath string) error {
  45. err := archiveFile(v.copyRangeMethod, v.folderFs, v.versionsFs, filePath, TagFilename)
  46. if err != nil {
  47. return err
  48. }
  49. // Versions are sorted by timestamp in the file name, oldest first.
  50. versions := findAllVersions(v.versionsFs, filePath)
  51. if len(versions) > v.keep {
  52. for _, toRemove := range versions[:len(versions)-v.keep] {
  53. l.Debugln("cleaning out", toRemove)
  54. err = v.versionsFs.Remove(toRemove)
  55. if err != nil {
  56. l.Warnln("removing old version:", err)
  57. }
  58. }
  59. }
  60. return nil
  61. }
  62. func (v simple) GetVersions() (map[string][]FileVersion, error) {
  63. return retrieveVersions(v.versionsFs)
  64. }
  65. func (v simple) Restore(filepath string, versionTime time.Time) error {
  66. return restoreFile(v.copyRangeMethod, v.versionsFs, v.folderFs, filepath, versionTime, TagFilename)
  67. }
  68. func (v simple) Clean(ctx context.Context) error {
  69. return cleanByDay(ctx, v.versionsFs, v.cleanoutDays)
  70. }