config_mem.go

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