-
Notifications
You must be signed in to change notification settings - Fork 0
/
formatters.go
80 lines (69 loc) · 2.1 KB
/
formatters.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
// Copyright 2017 The LUCI Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package format
import (
"fmt"
"sync"
"github.com/TriggerMail/luci-go/common/errors"
)
// registry is a registry of Resolver key mapped to the Formatter to use to
// format that key.
var registry struct {
sync.RWMutex
r map[string]Formatter
}
// Formatter applies a transformation to the data's cached representation.
//
// The Formatter is supplied with the content to format along with the
// formatter-specific metadata, fd.
//
// Formatter operates on a config.Config's Content via the "format" Backend.
type Formatter interface {
FormatItem(c, fd string) (string, error)
}
// Register registers a Formatter implementation for given format.
//
// If the supplied key is already registered, Register will panic.
func Register(rk string, f Formatter) {
if rk == "" {
panic("cannot register empty key")
}
registry.Lock()
defer registry.Unlock()
if _, ok := registry.r[rk]; ok {
panic(fmt.Errorf("key %q is already registered", rk))
}
if registry.r == nil {
registry.r = map[string]Formatter{}
}
registry.r[rk] = f
}
// ClearRegistry removes all registered formatters.
//
// Useful in tests that call Register to setup initial state.
func ClearRegistry() {
registry.Lock()
defer registry.Unlock()
registry.r = nil
}
// getFormatter returns the Formatter associated with the provided Format.
func getFormatter(f string) (Formatter, error) {
registry.RLock()
defer registry.RUnlock()
formatter := registry.r[f]
if formatter == nil {
return nil, errors.Reason("unknown formatter: %q", f).Err()
}
return formatter, nil
}