-
Notifications
You must be signed in to change notification settings - Fork 73
/
import.go
100 lines (86 loc) · 2.34 KB
/
import.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
package main
import (
"bytes"
"fmt"
"io"
"os"
"gopkg.in/yaml.v3"
"github.com/mbrt/gmailctl/cmd/gmailctl-config-migrate/v1alpha1"
"github.com/mbrt/gmailctl/cmd/gmailctl-config-migrate/v1alpha2"
"github.com/mbrt/gmailctl/cmd/gmailctl-config-migrate/v1alpha3"
"github.com/mbrt/gmailctl/internal/engine/rimport"
)
const header = `// This file is generated by gmailctl-config-migrate.
//
// WARNING: This functionality is experimental. Before making any
// changes, check that no diff is detected with the remote filters by
// using the 'gmailctl diff' command.
`
func importConfig(path string, out io.Writer) error {
cfg, err := readConfig(path)
if err != nil {
return err
}
err = rimport.MarshalJsonnet(cfg, out, header)
if err != nil {
return fmt.Errorf("converting to Jsonnet: %w", err)
}
return nil
}
func readConfig(path string) (v1alpha3.Config, error) {
/* #nosec */
buf, err := os.ReadFile(path)
if err != nil {
return v1alpha3.Config{}, err
}
return readYaml(buf)
}
func readYaml(buf []byte) (v1alpha3.Config, error) {
var res v1alpha3.Config
version, err := readYamlVersion(buf)
if err != nil {
return res, fmt.Errorf("parsing the config version: %w", err)
}
dec := yaml.NewDecoder(bytes.NewReader(buf))
dec.KnownFields(true)
switch version {
case v1alpha3.Version:
var v3 v1alpha3.Config
if err := dec.Decode(&v3); err != nil {
return res, fmt.Errorf("parsing the v1alpha3 config: %w", err)
}
return v3, nil
case v1alpha2.Version:
var v2 v1alpha2.Config
if err := dec.Decode(&v2); err != nil {
return res, fmt.Errorf("parsing v1alpha2 config: %w", err)
}
return importFromV2(v2)
case v1alpha1.Version:
var v1 v1alpha1.Config
if err := dec.Decode(&v1); err != nil {
return res, fmt.Errorf("parsing v1alpha1 config: %w", err)
}
return importFromV1(v1)
default:
return res, fmt.Errorf("unsupported config version: %s", version)
}
}
func importFromV1(v1 v1alpha1.Config) (v1alpha3.Config, error) {
v2, err := v1alpha2.Import(v1)
if err != nil {
return v1alpha3.Config{}, err
}
return importFromV2(v2)
}
func importFromV2(v2 v1alpha2.Config) (v1alpha3.Config, error) {
return v1alpha3.Import(v2)
}
func readYamlVersion(buf []byte) (string, error) {
// Try to unmarshal only the version
v := struct {
Version string `yaml:"version"`
}{}
err := yaml.Unmarshal(buf, &v)
return v.Version, err
}