-
Notifications
You must be signed in to change notification settings - Fork 0
/
csv.go
62 lines (52 loc) · 1.26 KB
/
csv.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
package formats
import (
"encoding/csv"
"fmt"
"github.com/dazfuller/azcosts/internal/model"
"os"
)
type CsvFormatter struct {
useStdOut bool
outputPath string
}
func MakeCsvFormatter(useStdOut bool, outputPath string) (CsvFormatter, error) {
if err := validateOptions(useStdOut, outputPath); err != nil {
return CsvFormatter{}, err
}
return CsvFormatter{useStdOut: useStdOut, outputPath: outputPath}, nil
}
func (cf CsvFormatter) Generate(costs []model.ResourceGroupSummary) error {
var writer *csv.Writer
if cf.useStdOut {
writer = csv.NewWriter(os.Stdout)
} else {
file, err := os.Create(cf.outputPath)
if err != nil {
return err
}
writer = csv.NewWriter(file)
}
// Write header
header := []string{"Name", "Subscription Name"}
for _, cost := range costs[0].Costs {
header = append(header, cost.Period)
}
header = append(header, "Total Costs")
err := writer.Write(header)
if err != nil {
return err
}
for _, rg := range costs {
record := []string{rg.Name, rg.SubscriptionName}
for _, cost := range rg.Costs {
record = append(record, fmt.Sprintf("%.2f", cost.Total))
}
record = append(record, fmt.Sprintf("%.2f", rg.TotalCost))
err := writer.Write(record)
if err != nil {
return err
}
}
writer.Flush()
return nil
}