This repository has been archived by the owner on May 31, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
results.go
71 lines (57 loc) · 1.67 KB
/
results.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
/******************************************************************************
Cloud Resource Counter
File: results.go
Summary: Collects results (in the form of column names and column values) and
writes to a CSV file
******************************************************************************/
package main
import (
"encoding/csv"
"fmt"
"io"
)
// Results is a struct that collects rows of data and writes them to the supplied
// file in CSV format.
type Results struct {
Rows [][]string
StoreHeaders bool
Writer io.Writer
}
// Init performs one-time initialization on the results struct.
func (r *Results) Init() {
// Are storing column names in our rows?
if r.StoreHeaders {
// Create a new row to hold them
r.NewRow()
}
}
// NewRow creates a new row to receive results
func (r *Results) NewRow() {
r.Rows = append(r.Rows, []string{})
}
// Append the supplied column name and row value into our struct.
func (r *Results) Append(columnName string, rowValue interface{}) {
// Are we storing column names?
if r.StoreHeaders {
r.Rows[0] = append(r.Rows[0], columnName)
}
// Append our value to the last row
r.Rows[len(r.Rows)-1] = append(r.Rows[len(r.Rows)-1], fmt.Sprintf("%v", rowValue))
}
// Save the generated results to the supplied file
func (r *Results) Save(am ActivityMonitor) {
// If we don't have a Writer, then get out now...
if NilInterface(r.Writer) {
return
}
// Indicate activity
am.StartAction("Writing to file")
// Get the CSV Writer
writer := csv.NewWriter(r.Writer)
// Write all of the contents at once
err := writer.WriteAll(r.Rows)
// Check for Error
am.CheckError(err)
// Indicate success
am.EndAction("OK")
}