-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparams.go
More file actions
98 lines (81 loc) · 2.77 KB
/
params.go
File metadata and controls
98 lines (81 loc) · 2.77 KB
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
package main
import (
"errors"
"os"
"github.com/joomcode/errorx"
"gopkg.in/yaml.v3"
)
var (
ErrParamsNamespace = errorx.NewNamespace("params")
ErrFailCreateDefaultParams = errorx.NewType(ErrParamsNamespace, "FailCreateDefaultParams")
ErrFailReadParams = errorx.NewType(ErrParamsNamespace, "FailReadParams")
)
const configFileName = "math-examples.yaml"
type AppParams struct {
Profiles map[string]ProfileParams
}
type ProfileParams struct {
ExamplesCount int `yaml:"examplesCount"`
MinBoundary int `yaml:"minBoundary"`
MaxBoundary int `yaml:"maxBoundary"`
OperandsCount int `yaml:"operandsCount"`
Parenthesis bool `yaml:"parenthesis"`
ShowCorrectAnswerAfter CorrectAnswerMode `yaml:"showCorrectAnswerAfter"`
AvailableOperands []string `yaml:"availableOperands"`
AvailableMultiplicationOperands []string `yaml:"availableMultiplicationOperands"`
AvailableOperationTypes []OperationType `yaml:"availableOperationTypes"`
}
type OperationType string
const (
PlusOperationType OperationType = "plus"
MinusOperationType OperationType = "minus"
MultiplyOperationType OperationType = "multiply"
DivideOperationType OperationType = "divide"
)
type CorrectAnswerMode string
const (
AfterEach CorrectAnswerMode = "each"
AfterAll CorrectAnswerMode = "all"
)
func ReadParams() (*AppParams, error) {
_, err := os.Stat(configFileName)
if errors.Is(err, os.ErrNotExist) {
defaultParams := AppParams{
Profiles: map[string]ProfileParams{
"Имя": {
ExamplesCount: 10,
MinBoundary: 0,
MaxBoundary: 100,
OperandsCount: 2,
ShowCorrectAnswerAfter: AfterEach,
AvailableOperationTypes: []OperationType{
PlusOperationType,
MinusOperationType,
MultiplyOperationType,
DivideOperationType,
},
AvailableOperands: []string{"1:100"},
AvailableMultiplicationOperands: []string{"1:9"},
},
},
}
bytes, err := yaml.Marshal(defaultParams)
if err != nil {
return nil, ErrFailCreateDefaultParams.Wrap(err, "failed to marshall default params")
}
err = os.WriteFile(configFileName, bytes, os.ModePerm)
if err != nil {
return nil, ErrFailCreateDefaultParams.Wrap(err, "failed to write default params to file")
}
}
bytes, err := os.ReadFile(configFileName)
if err != nil {
return nil, ErrFailReadParams.Wrap(err, "failed to read params from file")
}
var result AppParams
err = yaml.Unmarshal(bytes, &result)
if err != nil {
return nil, ErrFailReadParams.Wrap(err, "failed to unmarshall params")
}
return &result, nil
}