1package main
2
3import (
4 "encoding/json"
5 "fmt"
6 "log"
7 "os"
8 "strings"
9
10 "github.com/spf13/pflag"
11 "gopkg.in/yaml.v3"
12)
13
14func importData(path string, structure *Invoice, flags *pflag.FlagSet) error {
15 fileText, err := os.ReadFile(path)
16 if err != nil {
17 return fmt.Errorf("unable to read file")
18 }
19
20 var b []byte
21 var byteBuffer [][]byte
22 flags.Visit(func(f *pflag.Flag) {
23 if f.Value.Type() != "string" {
24 b = []byte(fmt.Sprintf(`{"%s":%s}`, f.Name, f.Value))
25 } else {
26 b = []byte(fmt.Sprintf(`{"%s":"%s"}`, f.Name, f.Value))
27 }
28 byteBuffer = append(byteBuffer, b)
29 })
30
31 if strings.HasSuffix(path, ".json") {
32 err = importJson(fileText, structure)
33 } else if strings.HasSuffix(path, ".yaml") || strings.HasSuffix(path, ".yml") {
34 err = importYaml(fileText, structure)
35
36 } else {
37 return fmt.Errorf("unsupported file type")
38 }
39 if err != nil {
40 log.Fatal(err)
41 }
42
43 for _, bytes := range byteBuffer {
44 err = importJson(bytes, structure)
45 if err != nil {
46 log.Fatal(err)
47 }
48 }
49
50 return err
51}
52
53func importJson(text []byte, structure *Invoice) error {
54 if !json.Valid(text) {
55 return fmt.Errorf("json file not correctly formatted")
56 }
57
58 err := json.Unmarshal(text, structure)
59 if err != nil {
60 return fmt.Errorf("json file not correctly formatted")
61 }
62
63 return nil
64}
65
66func importYaml(text []byte, structure *Invoice) error {
67 err := yaml.Unmarshal(text, structure)
68 if err != nil {
69 return fmt.Errorf("yaml file not correctly formatted")
70 }
71
72 return nil
73}