-
Notifications
You must be signed in to change notification settings - Fork 40
/
repo.go
73 lines (61 loc) · 1.21 KB
/
repo.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
// Copyright 2017-2020 Square, Inc.
package cmd
import (
"log"
"sync"
)
// Repo is a thread-safe collection of Cmd used by an rce.Server.
type Repo interface {
// Add new command to repo, identified by Cmd.Id.
Add(*Cmd) error
// Remove command from repo.
Remove(id string) error
// Return command from repo, or nil if doesn't exist.
Get(id string) *Cmd
// Return list of all command IDs in repos. The list is a copy and can change
// between calls.
All() []string
}
type repo struct {
*sync.Mutex
all map[string]*Cmd // keyed on id
}
// NewRepo makes a new empty Repo.
func NewRepo() Repo {
return &repo{
Mutex: &sync.Mutex{},
all: map[string]*Cmd{},
}
}
func (r *repo) Add(cmd *Cmd) error {
r.Lock()
defer r.Unlock()
if c := r.all[cmd.Id]; c != nil {
return ErrDuplicateCommand
}
r.all[cmd.Id] = cmd
return nil
}
func (r *repo) Remove(id string) error {
r.Lock()
defer r.Unlock()
log.Printf("cmd=%s remove", id)
delete(r.all, id)
return nil
}
func (r *repo) Get(id string) *Cmd {
r.Lock()
defer r.Unlock()
return r.all[id]
}
func (r *repo) All() []string {
r.Lock()
defer r.Unlock()
all := make([]string, len(r.all))
i := 0
for id := range r.all {
all[i] = id
i++
}
return all
}