summaryrefslogtreecommitdiff
path: root/io_helpers.go
blob: 3bf96001d21eb367ec9cedd958c1ea563cf1be6a (plain)
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
package main

import (
	"bufio"
	"encoding/csv"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
)

func readLines(filepath string) []string {
	file, err := os.Open(filepath)
	if err != nil {
		panic(err)
	}
	defer file.Close()

	resp := []string{}
	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		resp = append(resp, scanner.Text())
	}

	if err := scanner.Err(); err != nil {
		panic(err)
	}
	return resp
}

// writeLines writes the lines to the given file.
func writeLines(lines []string, path string) error {
	file, err := os.Create(path)
	if err != nil {
		return err
	}
	defer file.Close()

	w := bufio.NewWriter(file)
	for _, line := range lines {
		fmt.Fprintln(w, line)
	}
	return w.Flush()
}

func readJson(filepath string) map[string]string {
	data := make(map[string]string)
	plan, err := ioutil.ReadFile(filepath)
	if err != nil {
		return data
	}
	err = json.Unmarshal(plan, &data)
	if err != nil {
		panic(err)
	}
	return data
}

func writeJson(data map[string]string) {
	metadataJson, _ := json.MarshalIndent(data, "", "  ")
	err := ioutil.WriteFile(metadataPath, metadataJson, 0644)
	if err != nil {
		panic(err)
	}
}

func writeCSV(data [][]string) {
	f, err := os.Create(metadataPathCSV)
	defer f.Close()

	if err != nil {
		panic(err)
	}

	w := csv.NewWriter(f)
	w.Comma = '\t'
	defer w.Flush()

	if err := w.WriteAll(data); err != nil {
		panic(err)
	}
}