simple.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. "strconv"
  9. "time"
  10. "github.com/syncthing/syncthing/lib/fs"
  11. )
  12. func init() {
  13. // Register the constructor for this type of versioner with the name "simple"
  14. Factories["simple"] = NewSimple
  15. }
  16. type Simple struct {
  17. keep int
  18. folderFs fs.Filesystem
  19. versionsFs fs.Filesystem
  20. }
  21. func NewSimple(folderID string, folderFs fs.Filesystem, params map[string]string) Versioner {
  22. keep, err := strconv.Atoi(params["keep"])
  23. if err != nil {
  24. keep = 5 // A reasonable default
  25. }
  26. s := Simple{
  27. keep: keep,
  28. folderFs: folderFs,
  29. versionsFs: fsFromParams(folderFs, params),
  30. }
  31. l.Debugf("instantiated %#v", s)
  32. return s
  33. }
  34. // Archive moves the named file away to a version archive. If this function
  35. // returns nil, the named file does not exist any more (has been archived).
  36. func (v Simple) Archive(filePath string) error {
  37. err := archiveFile(v.folderFs, v.versionsFs, filePath, TagFilename)
  38. if err != nil {
  39. return err
  40. }
  41. // Versions are sorted by timestamp in the file name, oldest first.
  42. versions := findAllVersions(v.versionsFs, filePath)
  43. if len(versions) > v.keep {
  44. for _, toRemove := range versions[:len(versions)-v.keep] {
  45. l.Debugln("cleaning out", toRemove)
  46. err = v.versionsFs.Remove(toRemove)
  47. if err != nil {
  48. l.Warnln("removing old version:", err)
  49. }
  50. }
  51. }
  52. return nil
  53. }
  54. func (v Simple) GetVersions() (map[string][]FileVersion, error) {
  55. return retrieveVersions(v.versionsFs)
  56. }
  57. func (v Simple) Restore(filepath string, versionTime time.Time) error {
  58. return restoreFile(v.versionsFs, v.folderFs, filepath, versionTime, TagFilename)
  59. }