/
migrate.go
43 lines (40 loc) · 1.05 KB
/
migrate.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
package config
import (
"encoding/json"
"io/ioutil"
"os"
"path/filepath"
"github.com/adrg/xdg"
"github.com/claudiodangelis/qrcp/application"
"gopkg.in/yaml.v2"
)
// Migrate function will look for an existing legacy configuration file
// and will migrate it to the new format
func Migrate(app application.App) (bool, error) {
oldConfigFile := filepath.Join(xdg.ConfigHome, "qrcp", "config.json")
newConfigFile := filepath.Join(xdg.ConfigHome, "qrcp", "config.yml")
// Check if old configuration file exists
if _, err := os.Stat(oldConfigFile); os.IsNotExist(err) {
return false, nil
}
oldConfigFileBytes, err := ioutil.ReadFile(oldConfigFile)
if err != nil {
panic(err)
}
var cfg Config
if err := json.Unmarshal(oldConfigFileBytes, &cfg); err != nil {
panic(err)
}
newConfigFileBytes, err := yaml.Marshal(cfg)
if err != nil {
panic(err)
}
if err := ioutil.WriteFile(newConfigFile, newConfigFileBytes, 0644); err != nil {
panic(err)
}
// Delete old file
if err := os.Remove(oldConfigFile); err != nil {
panic(err)
}
return true, nil
}