1package repository
2
3import (
4 "fmt"
5 "strconv"
6 "strings"
7 "time"
8)
9
10var _ Config = &MemConfig{}
11
12type MemConfig struct {
13 config map[string]string
14}
15
16func NewMemConfig() *MemConfig {
17 return &MemConfig{
18 config: make(map[string]string),
19 }
20}
21
22func (mc *MemConfig) StoreString(key, value string) error {
23 mc.config[key] = value
24 return nil
25}
26
27func (mc *MemConfig) StoreBool(key string, value bool) error {
28 return mc.StoreString(key, strconv.FormatBool(value))
29}
30
31func (mc *MemConfig) StoreTimestamp(key string, value time.Time) error {
32 return mc.StoreString(key, strconv.Itoa(int(value.Unix())))
33}
34
35func (mc *MemConfig) ReadAll(keyPrefix string) (map[string]string, error) {
36 result := make(map[string]string)
37 for key, val := range mc.config {
38 if strings.HasPrefix(key, keyPrefix) {
39 result[key] = val
40 }
41 }
42 return result, nil
43}
44
45func (mc *MemConfig) ReadString(key string) (string, error) {
46 // unlike git, the mock can only store one value for the same key
47 val, ok := mc.config[key]
48 if !ok {
49 return "", ErrNoConfigEntry
50 }
51
52 return val, nil
53}
54
55func (mc *MemConfig) ReadBool(key string) (bool, error) {
56 // unlike git, the mock can only store one value for the same key
57 val, ok := mc.config[key]
58 if !ok {
59 return false, ErrNoConfigEntry
60 }
61
62 return strconv.ParseBool(val)
63}
64
65func (mc *MemConfig) ReadTimestamp(key string) (time.Time, error) {
66 value, err := mc.ReadString(key)
67 if err != nil {
68 return time.Time{}, err
69 }
70
71 timestamp, err := strconv.Atoi(value)
72 if err != nil {
73 return time.Time{}, err
74 }
75
76 return time.Unix(int64(timestamp), 0), nil
77}
78
79// RmConfigs remove all key/value pair matching the key prefix
80func (mc *MemConfig) RemoveAll(keyPrefix string) error {
81 found := false
82 for key := range mc.config {
83 if strings.HasPrefix(key, keyPrefix) {
84 delete(mc.config, key)
85 found = true
86 }
87 }
88
89 if !found {
90 return fmt.Errorf("section not found")
91 }
92
93 return nil
94}