versioningconfiguration.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. // internalVersioningConfiguration is used in XML serialization
  14. type internalVersioningConfiguration struct {
  15. Type string `xml:"type,attr,omitempty"`
  16. Params []internalParam `xml:"param"`
  17. CleanupIntervalS int `xml:"cleanupIntervalS" default:"3600"`
  18. }
  19. type internalParam struct {
  20. Key string `xml:"key,attr"`
  21. Val string `xml:"val,attr"`
  22. }
  23. func (c VersioningConfiguration) Copy() VersioningConfiguration {
  24. cp := c
  25. cp.Params = make(map[string]string, len(c.Params))
  26. for k, v := range c.Params {
  27. cp.Params[k] = v
  28. }
  29. return cp
  30. }
  31. func (c *VersioningConfiguration) UnmarshalJSON(data []byte) error {
  32. util.SetDefaults(c)
  33. type noCustomUnmarshal VersioningConfiguration
  34. ptr := (*noCustomUnmarshal)(c)
  35. return json.Unmarshal(data, ptr)
  36. }
  37. func (c *VersioningConfiguration) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
  38. var intCfg internalVersioningConfiguration
  39. util.SetDefaults(&intCfg)
  40. if err := d.DecodeElement(&intCfg, &start); err != nil {
  41. return err
  42. }
  43. c.fromInternal(intCfg)
  44. return nil
  45. }
  46. func (c *VersioningConfiguration) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
  47. // Using EncodeElement instead of plain Encode ensures that we use the
  48. // outer tag name from the VersioningConfiguration (i.e.,
  49. // `<versioning>`) rather than whatever the internal representation
  50. // would otherwise be.
  51. return e.EncodeElement(c.toInternal(), start)
  52. }
  53. func (c *VersioningConfiguration) toInternal() internalVersioningConfiguration {
  54. var tmp internalVersioningConfiguration
  55. tmp.Type = c.Type
  56. tmp.CleanupIntervalS = c.CleanupIntervalS
  57. for k, v := range c.Params {
  58. tmp.Params = append(tmp.Params, internalParam{k, v})
  59. }
  60. sort.Slice(tmp.Params, func(a, b int) bool {
  61. return tmp.Params[a].Key < tmp.Params[b].Key
  62. })
  63. return tmp
  64. }
  65. func (c *VersioningConfiguration) fromInternal(intCfg internalVersioningConfiguration) {
  66. c.Type = intCfg.Type
  67. c.CleanupIntervalS = intCfg.CleanupIntervalS
  68. c.Params = make(map[string]string, len(intCfg.Params))
  69. for _, p := range intCfg.Params {
  70. c.Params[p.Key] = p.Val
  71. }
  72. }