versioningconfiguration.go 2.5 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 config
  7. import (
  8. "encoding/json"
  9. "encoding/xml"
  10. "sort"
  11. "github.com/syncthing/syncthing/lib/util"
  12. )
  13. // VersioningConfiguration is used in the code and for JSON serialization
  14. type VersioningConfiguration struct {
  15. Type string `json:"type"`
  16. Params map[string]string `json:"params"`
  17. CleanupIntervalS int `json:"cleanupIntervalS" default:"3600"`
  18. }
  19. // internalVersioningConfiguration is used in XML serialization
  20. type internalVersioningConfiguration struct {
  21. Type string `xml:"type,attr,omitempty"`
  22. Params []internalParam `xml:"param"`
  23. CleanupIntervalS int `xml:"cleanupIntervalS" default:"3600"`
  24. }
  25. type internalParam struct {
  26. Key string `xml:"key,attr"`
  27. Val string `xml:"val,attr"`
  28. }
  29. func (c VersioningConfiguration) Copy() VersioningConfiguration {
  30. cp := c
  31. cp.Params = make(map[string]string, len(c.Params))
  32. for k, v := range c.Params {
  33. cp.Params[k] = v
  34. }
  35. return cp
  36. }
  37. func (c *VersioningConfiguration) UnmarshalJSON(data []byte) error {
  38. util.SetDefaults(c)
  39. type noCustomUnmarshal VersioningConfiguration
  40. ptr := (*noCustomUnmarshal)(c)
  41. return json.Unmarshal(data, ptr)
  42. }
  43. func (c *VersioningConfiguration) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
  44. var intCfg internalVersioningConfiguration
  45. util.SetDefaults(&intCfg)
  46. if err := d.DecodeElement(&intCfg, &start); err != nil {
  47. return err
  48. }
  49. c.fromInternal(intCfg)
  50. return nil
  51. }
  52. func (c *VersioningConfiguration) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
  53. return e.Encode(c.toInternal())
  54. }
  55. func (c *VersioningConfiguration) toInternal() internalVersioningConfiguration {
  56. var tmp internalVersioningConfiguration
  57. tmp.Type = c.Type
  58. tmp.CleanupIntervalS = c.CleanupIntervalS
  59. for k, v := range c.Params {
  60. tmp.Params = append(tmp.Params, internalParam{k, v})
  61. }
  62. sort.Slice(tmp.Params, func(a, b int) bool {
  63. return tmp.Params[a].Key < tmp.Params[b].Key
  64. })
  65. return tmp
  66. }
  67. func (c *VersioningConfiguration) fromInternal(intCfg internalVersioningConfiguration) {
  68. c.Type = intCfg.Type
  69. c.CleanupIntervalS = intCfg.CleanupIntervalS
  70. c.Params = make(map[string]string, len(intCfg.Params))
  71. for _, p := range intCfg.Params {
  72. c.Params[p.Key] = p.Val
  73. }
  74. }