-
Notifications
You must be signed in to change notification settings - Fork 0
/
token.go
129 lines (110 loc) · 2.4 KB
/
token.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
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
126
127
128
129
package gogh
import "fmt"
type Token = string
type Host = string
type Owner = string
type TokenManager struct {
Hosts Map[Host, *TokenHost] `yaml:"hosts"`
DefaultHost Host `yaml:"default_host"`
}
type TokenHost struct {
Owners Map[Owner, Token] `yaml:"owners"`
DefaultOwner Owner `yaml:"default_owner"`
}
type Map[TKey comparable, TVal any] map[TKey]TVal
func (m *Map[TKey, TVal]) Set(key TKey, val TVal) {
if *m == nil {
*m = map[TKey]TVal{}
}
(*m)[key] = val
}
func (m *Map[TKey, TVal]) Delete(key TKey) {
if *m == nil {
return
}
delete(*m, key)
}
func (m *Map[TKey, TVal]) Has(key TKey) bool {
if *m == nil {
return false
}
_, ok := (*m)[key]
return ok
}
func (m *Map[TKey, TVal]) Get(key TKey) TVal {
var v TVal
return m.TryGet(key, v)
}
func (m *Map[TKey, TVal]) TryGet(key TKey, def TVal) TVal {
if *m == nil {
*m = map[TKey]TVal{
key: def,
}
return def
}
if v, ok := (*m)[key]; ok {
return v
}
(*m)[key] = def
return def
}
func (t TokenManager) GetDefaultKey() (Host, Owner) {
host := t.Hosts.Get(t.DefaultHost)
owner := ""
if host != nil {
owner = host.DefaultOwner
}
return t.DefaultHost, owner
}
func (t *TokenHost) GetDefaultToken() (Owner, Token) {
if t == nil {
return "", ""
}
return t.DefaultOwner, t.Owners.Get(t.DefaultOwner)
}
func (t TokenManager) Get(host, owner string) Token {
return t.Hosts.TryGet(host, &TokenHost{}).Owners.Get(owner)
}
func (t *TokenManager) Set(hostName, ownerName string, token Token) {
host := t.Hosts.TryGet(hostName, &TokenHost{})
if host.DefaultOwner == "" {
host.DefaultOwner = ownerName
}
host.Owners.Set(ownerName, token)
t.Hosts.Set(hostName, host)
}
func (t TokenManager) Delete(host, owner string) {
hosts := t.Hosts.Get(host)
if hosts == nil {
return
}
hosts.Owners.Delete(owner)
}
func (t TokenManager) Has(host, owner string) bool {
hosts := t.Hosts.Get(host)
if hosts == nil {
return false
}
return hosts.Owners.Has(owner)
}
type TokenEntry struct {
Host Host
Owner Owner
Token Token
}
func (e TokenEntry) String() string {
return fmt.Sprintf("%s/%s", e.Host, e.Owner)
}
func (t TokenManager) Entries() []TokenEntry {
var entries []TokenEntry
for hostName, hostEntry := range t.Hosts {
for owner, token := range hostEntry.Owners {
entries = append(entries, TokenEntry{
Host: hostName,
Owner: owner,
Token: token,
})
}
}
return entries
}