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