aboutsummaryrefslogtreecommitdiffstats
path: root/repository/config_mem.go
blob: d9126f39fe5bdd4a9c98231364f4079146cec518 (plain) (blame)
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package repository

import (
	"fmt"
	"strconv"
	"strings"
	"time"
)

var _ Config = &MemConfig{}

type MemConfig struct {
	config map[string]string
}

func NewMemConfig() *MemConfig {
	return &MemConfig{
		config: make(map[string]string),
	}
}

func (mc *MemConfig) StoreString(key, value string) error {
	key = normalizeKey(key)
	mc.config[key] = value
	return nil
}

func (mc *MemConfig) StoreBool(key string, value bool) error {
	return mc.StoreString(key, strconv.FormatBool(value))
}

func (mc *MemConfig) StoreTimestamp(key string, value time.Time) error {
	return mc.StoreString(key, strconv.Itoa(int(value.Unix())))
}

func (mc *MemConfig) ReadAll(keyPrefix string) (map[string]string, error) {
	keyPrefix = normalizeKey(keyPrefix)
	result := make(map[string]string)
	for key, val := range mc.config {
		if strings.HasPrefix(key, keyPrefix) {
			result[key] = val
		}
	}
	return result, nil
}

func (mc *MemConfig) ReadString(key string) (string, error) {
	// unlike git, the mock can only store one value for the same key
	key = normalizeKey(key)
	val, ok := mc.config[key]
	if !ok {
		return "", newErrNoConfigEntry(key)
	}

	return val, nil
}

func (mc *MemConfig) ReadBool(key string) (bool, error) {
	// unlike git, the mock can only store one value for the same key
	val, err := mc.ReadString(key)
	if err != nil {
		return false, err
	}

	return strconv.ParseBool(val)
}

func (mc *MemConfig) ReadTimestamp(key string) (time.Time, error) {
	value, err := mc.ReadString(key)
	if err != nil {
		return time.Time{}, err
	}

	timestamp, err := strconv.Atoi(value)
	if err != nil {
		return time.Time{}, err
	}

	return time.Unix(int64(timestamp), 0), nil
}

// RemoveAll remove all key/value pair matching the key prefix
func (mc *MemConfig) RemoveAll(keyPrefix string) error {
	keyPrefix = normalizeKey(keyPrefix)
	found := false
	for key := range mc.config {
		if strings.HasPrefix(key, keyPrefix) {
			delete(mc.config, key)
			found = true
		}
	}

	if !found {
		return fmt.Errorf("section not found")
	}

	return nil
}

func normalizeKey(key string) string {
	// this feels so wrong, but that's apparently how git behave.
	// only section and final segment are case insensitive, subsection in between are not.
	s := strings.Split(key, ".")
	s[0] = strings.ToLower(s[0])
	s[len(s)-1] = strings.ToLower(s[len(s)-1])
	return strings.Join(s, ".")
}