-
Notifications
You must be signed in to change notification settings - Fork 0
/
update.go
99 lines (78 loc) · 1.94 KB
/
update.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package main
import (
"encoding/csv"
"flag"
"os"
gsheets "google.golang.org/api/sheets/v4"
"io.bytenix.com/gsheetcsv/sheets"
)
type (
// UpdateCommand represents a spreadsheet update command
UpdateCommand struct {
GSheetCommand
Flags struct {
Sheet string
Range string
TabSep bool
}
}
)
// Init initializes the UpdateCommand structure and flags
func (c *UpdateCommand) Init(f *flag.FlagSet) error {
if err := c.GSheetCommand.Init(); err != nil {
return err
}
f.StringVar(&c.Flags.Sheet, "sheet", "", "Google Sheet ID")
f.StringVar(&c.Flags.Range, "range", "", "Google Sheet Range")
f.BoolVar(&c.Flags.TabSep, "tab", false, "Use tab as fields delimiter")
return nil
}
// Execute executes the UpdateCommand business logic
func (c *UpdateCommand) Execute() error {
rng, err := sheets.RangeFromString(c.Flags.Range)
if err != nil {
return err
}
r := csv.NewReader(os.Stdin)
if c.Flags.TabSep {
r.Comma = '\t'
}
values, err := r.ReadAll()
if err != nil {
return err
}
rng.End.Row = rng.Start.Row + sheets.Row(len(values))
rng.End.Column = rng.Start.Column + sheets.Column(len(values[0])-1)
resp, err := GetSpreadsheetValues(c.OAuth2Client, c.Flags.Sheet, rng, true)
updates := []*gsheets.ValueRange{}
for i := range values {
for j := range values[i] {
if values[i][j] != resp[i][j] {
updates = append(updates, &gsheets.ValueRange{
Range: sheets.Range{
Sheet: rng.Sheet,
Start: sheets.Cell{
Column: rng.Start.Column + sheets.Column(j),
Row: rng.Start.Row + sheets.Row(i),
},
}.String(),
Values: [][]interface{}{
[]interface{}{values[i][j]},
},
})
}
}
}
s, err := gsheets.New(c.OAuth2Client)
if err != nil {
return err
}
_, err = s.Spreadsheets.Values.BatchUpdate(c.Flags.Sheet, &gsheets.BatchUpdateValuesRequest{
ValueInputOption: "USER_ENTERED",
Data: updates,
}).Do()
if err != nil {
return err
}
return nil
}