Passed
Push — master ( 7456e0...8eb6db )
by Stanislav
01:27
created

config.GetConfig   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
package config
2
3
import (
4
	"fmt"
5
	"github.com/jinzhu/configor"
6
	"reflect"
7
	"strings"
8
	"gopkg.in/yaml.v2"
9
	"os"
10
	"io/ioutil"
11
	"time"
12
)
13
14
// Config - структура с конфигом приложения
15
type Config struct {
16
	SMTPHost                   string `env:"SMTP_HOST" yaml:"smtpHost"`
17
	SMTPPort                   int    `env:"SMTP_PORT" yaml:"smtpPort"`
18
	SMTPSecure                 bool   `env:"SMTP_SECURE" yaml:"smtpSecure"`
19
	PlanfixAccount             string `env:"PLANFIX_ACCOUNT" yaml:"planfixAccount"`
20
	SendInterval               int    `env:"SEND_INTERVAL" yaml:"sendInterval"`
21
	LogFile                    string `env:"LOG_FILE" yaml:"logFile"`
22
	NoConsole                  bool   `env:"NO_CONSOLE" yaml:"noConsole"`
23
	TogglAPIToken              string `env:"TOGGL_API_TOKEN" yaml:"togglApiToken"`
24
	TogglWorkspaceID           int    `env:"TOGGL_WORKSPACE_ID" yaml:"togglWorkspaceId"`
25
	TogglUserID                int    `env:"TOGGL_USER_ID" yaml:"togglUserId"` // will get in runtime
26
	TogglSentTag               string `env:"TOGGL_SENT_TAG" yaml:"togglSentTag"`
27
	SMTPLogin                  string `env:"SMTP_LOGIN" yaml:"smtpLogin"`
28
	SMTPPassword               string `env:"SMTP_PASSWORD" yaml:"smtpPassword"`
29
	SMTPEmailFrom              string `env:"SMTP_EMAIL_FROM" yaml:"smtpEmailFrom"`
30
	PlanfixAuthorName          string `env:"PLANFIX_AUTHOR_NAME" yaml:"planfixAuthorName"`
31
	Debug                      bool   `env:"DEBUG" yaml:"debug"`
32
	DryRun                     bool   `env:"DRY_RUN" yaml:"dryRun"`
33
	PlanfixAPIKey              string `env:"PLANFIX_API_KEY" yaml:"planfixApiKey"`
34
	PlanfixAPIUrl              string `env:"PLANFIX_API_URL" yaml:"planfixApiUrl"`
35
	PlanfixUserName            string `env:"PLANFIX_USER_NAME" yaml:"planfixUserName"`
36
	PlanfixUserPassword        string `env:"PLANFIX_USER_PASSWORD" yaml:"planfixUserPassword"`
37
	PlanfixUserID              int    `env:"PLANFIX_USER_ID" yaml:"planfixUserId"` // will get in runtime
38
	PlanfixAnaliticName        string `env:"PLANFIX_ANALITIC_NAME" yaml:"planfixAnaliticName"`
39
	PlanfixAnaliticTypeName    string `env:"PLANFIX_ANALITIC_TYPE_NAME" yaml:"planfixAnaliticTypeName"`
40
	PlanfixAnaliticTypeValue   string `env:"PLANFIX_ANALITIC_TYPE_VALUE" yaml:"planfixAnaliticTypeValue"`
41
	PlanfixAnaliticCountName   string `env:"PLANFIX_ANALITIC_COUNT_NAME" yaml:"planfixAnaliticCountName"`
42
	PlanfixAnaliticCommentName string `env:"PLANFIX_ANALITIC_COMMENT_NAME" yaml:"planfixAnaliticCommentName"`
43
	PlanfixAnaliticDateName    string `env:"PLANFIX_ANALITIC_DATE_NAME" yaml:"planfixAnaliticDateName"`
44
	PlanfixAnaliticUsersName   string `env:"PLANFIX_ANALITIC_USERS_NAME" yaml:"planfixAnaliticUsersName"`
45
}
46
47
// - GetConfig читает конфиг из файлов и возвращает структуру
0 ignored issues
show
introduced by
comment on exported function GetConfig should be of the form "GetConfig ..."
Loading history...
48
func GetConfig() (cfg Config) {
49
	configor.Load(&cfg, "config.yml", "config.default.yml")
50
	return cfg
51
}
52
53
// - SaveConfig пишет конфиг в файл
0 ignored issues
show
introduced by
comment on exported method Config.SaveConfig should be of the form "SaveConfig ..."
Loading history...
54
func (c *Config) SaveConfig() (cfg *Config, err error) {
55
	cfgString, err := yaml.Marshal(c)
56
	if err != nil {
57
		return cfg, err
58
	}
59
	if _, err := os.Stat("config.yml"); err == nil {
60
		os.Rename("config.yml", fmt.Sprintf("config-%s.yml", time.Now().Format("2006-02-01 15_04_05")));
61
		ioutil.WriteFile("config.yml", cfgString, 0644)
62
	}
63
	return c, nil
64
}
65
66
func (c *Config) Validate() (errors []string, isValid bool) {
0 ignored issues
show
introduced by
exported method Config.Validate should have comment or be unexported
Loading history...
67
	emptyFields := c.filterNotEmpty(c.GetFields())
68
	if len(emptyFields) > 0 {
69
		msg := fmt.Sprintf("поля %s пустые",
70
			strings.Join(emptyFields, ", "),
71
		)
72
		errors = append(errors, msg)
73
	}
74
75
	err := c.isGroupInvalid([]string{
76
		"TogglAPIToken",
77
		"TogglWorkspaceID",
78
	})
79
	if err != nil {
80
		errors = append(errors, "настройки Toggl неправильные")
81
	}
82
83
	err = c.isGroupInvalid([]string{
84
		"PlanfixAccount",
85
		"PlanfixApiKey",
86
		"PlanfixUserName",
87
		"PlanfixUserPassword",
88
	})
89
	if err != nil {
90
		errors = append(errors, "настройки подключения к Планфиксу неправильные")
91
	}
92
93
	err = c.isGroupInvalid([]string{
94
		"PlanfixAnaliticName",
95
		"PlanfixAnaliticTypeName",
96
		"PlanfixAnaliticTypeValue",
97
		"PlanfixAnaliticCountName",
98
		"PlanfixAnaliticCommentName",
99
		"PlanfixAnaliticDateName",
100
		"PlanfixAnaliticUsersName",
101
	})
102
	if err != nil {
103
		errors = append(errors, "настройки аналитики, отправляемой в Планфикс, неправильные")
104
	}
105
106
	if c.SMTPSecure {
107
		errors = append(errors, "Secure SMTP не поддерживается")
108
	}
109
110
	isValid = len(errors) == 0
111
	return errors, isValid
112
}
113
114
func isEmpty(s string) bool {
115
	return s == ""
116
}
117
118
func (c *Config) isGroupInvalid(fields []string) error {
119
	emptyFields := c.filterNotEmpty(fields)
120
	if len(emptyFields) == 0 {
121
		return nil
122
	}
123
124
	return fmt.Errorf("поля %s неправильные",
125
		strings.Join(emptyFields, ", "),
126
	)
127
}
128
129
func (c *Config) filterNotEmpty(fields []string) (emptyFields []string) {
130
	for _, fieldName := range fields {
131
		if isEmpty(c.getFieldByName(fieldName)) {
132
			emptyFields = append(emptyFields, fieldName)
133
		}
134
	}
135
	return emptyFields
136
}
137
138
func (c *Config) getFieldByName(field string) string {
139
	r := reflect.ValueOf(c)
140
	v := reflect.Indirect(r)
141
	f := v.FieldByName(field)
142
	return f.String()
143
}
144
145
func (c *Config) GetFields() (emptyFields []string) {
0 ignored issues
show
introduced by
exported method Config.GetFields should have comment or be unexported
Loading history...
146
	s := reflect.ValueOf(c).Elem()
147
	typeOfT := s.Type()
148
149
	for i := 0; i < s.NumField(); i++ {
150
		emptyFields = append(emptyFields, typeOfT.Field(i).Name)
151
	}
152
153
	return emptyFields
154
}
155
156
/*func (c *Config) GetEmptyFields (emptyFields []string){
157
	r := reflect.ValueOf(c)
158
159
	fields := r.MapKeys()
160
	for _, field := range(fields){
161
		fieldValue := field.String()
162
	}
163
}*/
164