-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
105 lines (86 loc) · 2.14 KB
/
config.go
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
package libdotfilesync
import (
"errors"
"fmt"
"os"
"time"
"github.com/jochemste/dotfile_sync/utils"
"github.com/pelletier/go-toml/v2"
)
// Configuration that is managed by the user
type UserConfig struct {
Origin string
Files []string
AccessToken string
Mode string
}
// Information that is used and adjusted automatically
type DontChangeConfig struct {
LastCheck time.Time
NrSync int
Store string
File string
}
// Configuration struct
type Config struct {
UserSettings UserConfig
DoNotChange DontChangeConfig
}
// Write the Config object to a file
func (config *Config) ToFile(file ...string) error {
var fp string
if len(file) == 0 {
fp = config.DoNotChange.File
} else {
fp = file[0]
}
fd, err := os.Create(fp)
if err != nil {
return errors.New("Could not create file " + fp)
}
if err := toml.NewEncoder(fd).Encode(config); err != nil {
return err
}
if err := fd.Close(); err != nil {
return err
}
return nil
}
// Set a Config from a toml file, if the file exists
func (config *Config) FromFile(file string) error {
if !utils.FileExists(file) {
return errors.New("File " + file + " does not exist")
}
content, err := utils.GetFileContent(file)
if err != nil {
return err
}
if err := toml.Unmarshal([]byte(content), &config); err != nil {
return err
}
config.DoNotChange.File = file
writable := utils.IsWritable(file)
if writable != true {
return errors.New("File " + file + " is not writable for the current user")
}
return nil
}
func (config *Config) IsWritable() bool {
return utils.IsWritable(config.DoNotChange.File)
}
func (config *Config) Print() {
fmt.Printf("Configuration:\n")
fmt.Printf("\tLocation: %s\n", config.DoNotChange.File)
fmt.Printf("\tOrigin: %s\n", config.UserSettings.Origin)
fmt.Printf("\tMode: %s\n", config.UserSettings.Mode)
fmt.Printf("\tFiles:\n")
for _, file := range config.UserSettings.Files {
fmt.Printf("\t\t%s\n", file)
}
fmt.Printf("\tNr Synchronisations: %d\n", config.DoNotChange.NrSync)
fmt.Printf("\tLastCheck: %s\n", config.DoNotChange.LastCheck)
}
// Get a new Config object
func NewConfig() *Config {
return &Config{}
}