versioner.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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 implements common interfaces for file versioning and a
  7. // simple default versioning scheme.
  8. package versioner
  9. import (
  10. "context"
  11. "errors"
  12. "fmt"
  13. "time"
  14. "github.com/syncthing/syncthing/lib/config"
  15. )
  16. type Versioner interface {
  17. Archive(filePath string) error
  18. GetVersions() (map[string][]FileVersion, error)
  19. Restore(filePath string, versionTime time.Time) error
  20. Clean(context.Context) error
  21. }
  22. type FileVersion struct {
  23. VersionTime time.Time `json:"versionTime"`
  24. ModTime time.Time `json:"modTime"`
  25. Size int64 `json:"size"`
  26. }
  27. type factory func(cfg config.FolderConfiguration) Versioner
  28. var factories = make(map[string]factory)
  29. var ErrRestorationNotSupported = errors.New("version restoration not supported with the current versioner")
  30. const (
  31. TimeFormat = "20060102-150405"
  32. timeGlob = "[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9][0-9][0-9]" // glob pattern matching TimeFormat
  33. )
  34. func New(cfg config.FolderConfiguration) (Versioner, error) {
  35. fac, ok := factories[cfg.Versioning.Type]
  36. if !ok {
  37. return nil, fmt.Errorf("requested versioning type %q does not exist", cfg.Versioning.Type)
  38. }
  39. return &versionerWithErrorContext{
  40. Versioner: fac(cfg),
  41. vtype: cfg.Versioning.Type,
  42. }, nil
  43. }
  44. type versionerWithErrorContext struct {
  45. Versioner
  46. vtype string
  47. }
  48. func (v *versionerWithErrorContext) wrapError(err error, op string) error {
  49. if err != nil {
  50. return fmt.Errorf("%s versioner: %v: %w", v.vtype, op, err)
  51. }
  52. return nil
  53. }
  54. func (v *versionerWithErrorContext) Archive(filePath string) error {
  55. return v.wrapError(v.Versioner.Archive(filePath), "archive")
  56. }
  57. func (v *versionerWithErrorContext) GetVersions() (map[string][]FileVersion, error) {
  58. versions, err := v.Versioner.GetVersions()
  59. return versions, v.wrapError(err, "get versions")
  60. }
  61. func (v *versionerWithErrorContext) Restore(filePath string, versionTime time.Time) error {
  62. return v.wrapError(v.Versioner.Restore(filePath, versionTime), "restore")
  63. }
  64. func (v *versionerWithErrorContext) Clean(ctx context.Context) error {
  65. return v.wrapError(v.Versioner.Clean(ctx), "clean")
  66. }