-
Notifications
You must be signed in to change notification settings - Fork 4
/
source.go
78 lines (63 loc) · 1.67 KB
/
source.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package source
import (
"context"
"fmt"
"reflect"
validation "github.com/go-ozzo/ozzo-validation/v4"
)
// SourceEntry is an entry that has been discovered in a source, with the contents of the
// source file and an Origin that explains where the entry came from, specific to the type
// of source that produced it.
type SourceEntry struct {
Origin string
Content []byte
}
func (e SourceEntry) Parse() ([]Entry, error) {
entries := Parse(e.Content)
if len(entries) == 0 {
return entries, fmt.Errorf("failed to parse any entries")
}
return entries, nil
}
// Source is instantiated from configuration and represents a source of catalog files.
type Source struct {
Local *SourceLocal `json:"local,omitempty"`
Inline *SourceInline `json:"inline,omitempty"`
Exec *SourceExec `json:"exec,omitempty"`
}
func (s Source) Validate() error {
err := validation.Validate("source", validation.By(func(value any) error {
if reflect.ValueOf(s).IsZero() {
return ErrInvalidSourceEmpty
}
return nil
}))
if err != nil {
return err
}
return validation.ValidateStruct(&s)
}
type SourceBackend interface {
String() string
Load(ctx context.Context) ([]*SourceEntry, error)
}
func (s Source) Backend() (SourceBackend, error) {
if s.Local != nil {
return s.Local, nil
}
if s.Inline != nil {
return s.Inline, nil
}
if s.Exec != nil {
return s.Exec, nil
}
return nil, ErrInvalidSourceEmpty
}
var ErrInvalidSourceEmpty = fmt.Errorf("invalid source, must specify at least one type of source configuration")
func (s Source) Load(ctx context.Context) ([]*SourceEntry, error) {
source, err := s.Backend()
if err != nil {
return nil, err
}
return source.Load(ctx)
}