origin.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. package setting
  4. import (
  5. "fmt"
  6. jsonv2 "github.com/go-json-experiment/json"
  7. "github.com/go-json-experiment/json/jsontext"
  8. )
  9. // Origin describes where a policy or a policy setting is configured.
  10. type Origin struct {
  11. data settingOrigin
  12. }
  13. // settingOrigin is the marshallable data of an [Origin].
  14. type settingOrigin struct {
  15. Name string `json:",omitzero"`
  16. Scope PolicyScope
  17. }
  18. // NewOrigin returns a new [Origin] with the specified scope.
  19. func NewOrigin(scope PolicyScope) *Origin {
  20. return NewNamedOrigin("", scope)
  21. }
  22. // NewNamedOrigin returns a new [Origin] with the specified scope and name.
  23. func NewNamedOrigin(name string, scope PolicyScope) *Origin {
  24. return &Origin{settingOrigin{name, scope}}
  25. }
  26. // Scope reports the policy [PolicyScope] where the setting is configured.
  27. func (s Origin) Scope() PolicyScope {
  28. return s.data.Scope
  29. }
  30. // Name returns the name of the policy source where the setting is configured,
  31. // or "" if not available.
  32. func (s Origin) Name() string {
  33. return s.data.Name
  34. }
  35. // String implements [fmt.Stringer].
  36. func (s Origin) String() string {
  37. if s.Name() != "" {
  38. return fmt.Sprintf("%s (%v)", s.Name(), s.Scope())
  39. }
  40. return s.Scope().String()
  41. }
  42. var (
  43. _ jsonv2.MarshalerTo = (*Origin)(nil)
  44. _ jsonv2.UnmarshalerFrom = (*Origin)(nil)
  45. )
  46. // MarshalJSONTo implements [jsonv2.MarshalerTo].
  47. func (s Origin) MarshalJSONTo(out *jsontext.Encoder) error {
  48. return jsonv2.MarshalEncode(out, &s.data)
  49. }
  50. // UnmarshalJSONFrom implements [jsonv2.UnmarshalerFrom].
  51. func (s *Origin) UnmarshalJSONFrom(in *jsontext.Decoder) error {
  52. return jsonv2.UnmarshalDecode(in, &s.data)
  53. }
  54. // MarshalJSON implements [json.Marshaler].
  55. func (s Origin) MarshalJSON() ([]byte, error) {
  56. return jsonv2.Marshal(s) // uses MarshalJSONTo
  57. }
  58. // UnmarshalJSON implements [json.Unmarshaler].
  59. func (s *Origin) UnmarshalJSON(b []byte) error {
  60. return jsonv2.Unmarshal(b, s) // uses UnmarshalJSONFrom
  61. }