-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsteamSummaryCSV.go
80 lines (75 loc) · 1.61 KB
/
steamSummaryCSV.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
74
75
76
77
78
79
80
package main
import (
"encoding/csv"
"errors"
"fmt"
"os"
"os/user"
"path/filepath"
"reflect"
"strings"
)
type SteamSummaryCSV struct {
Heading []string
Values []string
}
func NewSteamSummaryCSV(s *SteamGameSummary) SteamSummaryCSV {
r := reflect.ValueOf(s).Elem()
t := r.Type()
var (
headings []string
values []string
)
for i := 0; i < r.NumField(); i++ {
var v string
headings = append(headings, t.Field(i).Name)
x := r.Field(i).Interface()
switch x.(type) {
case []string:
v = strings.Join(x.([]string), ",")
default:
v = fmt.Sprintf("%v", x)
}
values = append(values, v)
}
return SteamSummaryCSV{
Heading: headings,
Values: values}
}
func writeSteamSummaryCSV(fullpath string, name string, s *[]SteamSummaryCSV) error {
if len(*s) == 0 {
return errors.New("s cannot be empty")
}
err := os.MkdirAll(fullpath, os.ModePerm)
if err != nil {
return err
}
if ok := strings.HasSuffix(name, ".csv"); ok != true {
name = fmt.Sprintf("%s.csv", name)
}
file, err := os.Create(filepath.Join(fullpath, name))
defer file.Close()
if err != nil {
return err
}
writer := csv.NewWriter(file)
defer writer.Flush()
if err := writer.Write((*s)[0].Heading); err != nil {
return err
}
for _, steamSummaryCSV := range *s {
if err := writer.Write(steamSummaryCSV.Values); err != nil {
return err
}
}
return nil
}
func writeSteamSummaryCSVDefault(name string, s *[]SteamSummaryCSV) error {
user, err := user.Current()
if err != nil {
panic(err)
}
fullpath := filepath.Join(user.HomeDir, "Desktop", "steambot")
err = writeSteamSummaryCSV(fullpath, name, s)
return err
}