-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfetch.go
More file actions
125 lines (103 loc) · 2.45 KB
/
fetch.go
File metadata and controls
125 lines (103 loc) · 2.45 KB
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package fetch
import (
"context"
"encoding/json"
"io"
"iter"
"github.com/aserto-dev/ds-load/plugins/google/pkg/googleclient"
"github.com/aserto-dev/ds-load/sdk/common"
"github.com/aserto-dev/ds-load/sdk/common/js"
"github.com/aserto-dev/ds-load/sdk/fetcher"
)
type Fetcher struct {
gClient *googleclient.GoogleClient
Groups bool
}
func New(client *googleclient.GoogleClient) (*Fetcher, error) {
return &Fetcher{
gClient: client,
}, nil
}
func (f *Fetcher) WithGroups(groups bool) *Fetcher {
f.Groups = groups
return f
}
func (f *Fetcher) Fetch(ctx context.Context, outputWriter, errorWriter io.Writer) error {
writer := js.NewJSONArrayWriter(outputWriter)
defer writer.Close()
for user, err := range f.fetchUsers() {
if err != nil {
common.WriteErrorWithExitCode(errorWriter, err, 1)
continue
}
if err := writer.Write(user); err != nil {
_, _ = errorWriter.Write([]byte(err.Error()))
}
}
if f.Groups {
for group, err := range f.fetchGroups() {
if err != nil {
common.WriteErrorWithExitCode(errorWriter, err, 1)
continue
}
if err := writer.Write(group); err != nil {
_, _ = errorWriter.Write([]byte(err.Error()))
}
}
}
return nil
}
func (f *Fetcher) fetchUsers() iter.Seq2[map[string]any, error] {
users, err := f.gClient.ListUsers()
if err != nil {
return fetcher.YieldError(err)
}
return fetcher.YieldMap(users, json.Marshal)
}
func (f *Fetcher) fetchGroups() iter.Seq2[map[string]any, error] {
groups, err := f.gClient.ListGroups()
if err != nil {
return fetcher.YieldError(err)
}
return func(yield func(map[string]any, error) bool) {
for _, group := range groups {
groupBytes, err := json.Marshal(group)
if err != nil {
if !yield(nil, err) {
return
}
}
var obj map[string]any
if err := json.Unmarshal(groupBytes, &obj); err != nil {
if !yield(nil, err) {
return
}
}
users, err := f.fetchUsersInGroup(group.Id)
if err != nil {
if !yield(nil, err) {
return
}
}
obj["users"] = users
if !(yield(obj, nil)) {
return
}
}
}
}
func (f *Fetcher) fetchUsersInGroup(groupId string) ([]map[string]any, error) {
usersInGroup, err := f.gClient.GetUsersInGroup(groupId)
if err != nil {
return nil, err
}
usersInGroupBytes, err := json.Marshal(usersInGroup)
if err != nil {
return nil, err
}
var users []map[string]any
if err := json.Unmarshal(usersInGroupBytes, &users); err != nil {
return nil, err
}
return users, nil
}