origin.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. // MarshalJSONV2 implements [jsonv2.MarshalerV2].
  43. func (s Origin) MarshalJSONV2(out *jsontext.Encoder, opts jsonv2.Options) error {
  44. return jsonv2.MarshalEncode(out, &s.data, opts)
  45. }
  46. // UnmarshalJSONV2 implements [jsonv2.UnmarshalerV2].
  47. func (s *Origin) UnmarshalJSONV2(in *jsontext.Decoder, opts jsonv2.Options) error {
  48. return jsonv2.UnmarshalDecode(in, &s.data, opts)
  49. }
  50. // MarshalJSON implements [json.Marshaler].
  51. func (s Origin) MarshalJSON() ([]byte, error) {
  52. return jsonv2.Marshal(s) // uses MarshalJSONV2
  53. }
  54. // UnmarshalJSON implements [json.Unmarshaler].
  55. func (s *Origin) UnmarshalJSON(b []byte) error {
  56. return jsonv2.Unmarshal(b, s) // uses UnmarshalJSONV2
  57. }