-
-
Notifications
You must be signed in to change notification settings - Fork 82
/
import.go
73 lines (60 loc) · 1.44 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
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"strings"
"github.com/spf13/pflag"
"gopkg.in/yaml.v3"
)
func importData(path string, structure *Invoice, flags *pflag.FlagSet) error {
fileText, err := os.ReadFile(path)
if err != nil {
return fmt.Errorf("unable to read file")
}
var b []byte
var byteBuffer [][]byte
flags.Visit(func(f *pflag.Flag) {
if f.Value.Type() != "string" {
b = []byte(fmt.Sprintf(`{"%s":%s}`, f.Name, f.Value))
} else {
b = []byte(fmt.Sprintf(`{"%s":"%s"}`, f.Name, f.Value))
}
byteBuffer = append(byteBuffer, b)
})
if strings.HasSuffix(path, ".json") {
err = importJson(fileText, structure)
} else if strings.HasSuffix(path, ".yaml") || strings.HasSuffix(path, ".yml") {
err = importYaml(fileText, structure)
} else {
return fmt.Errorf("unsupported file type")
}
if err != nil {
log.Fatal(err)
}
for _, bytes := range byteBuffer {
err = importJson(bytes, structure)
if err != nil {
log.Fatal(err)
}
}
return err
}
func importJson(text []byte, structure *Invoice) error {
if !json.Valid(text) {
return fmt.Errorf("json file not correctly formatted")
}
err := json.Unmarshal(text, structure)
if err != nil {
return fmt.Errorf("json file not correctly formatted")
}
return nil
}
func importYaml(text []byte, structure *Invoice) error {
err := yaml.Unmarshal(text, structure)
if err != nil {
return fmt.Errorf("yaml file not correctly formatted")
}
return nil
}