-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathupdate-stats-sheet
executable file
·83 lines (65 loc) · 2.96 KB
/
update-stats-sheet
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
#!/usr/bin/env python3
"""
Update the analytics stats spreadsheet from data passed via stdin.
"""
import argparse
import json
import sys
import gspread
from gspread import WorksheetNotFound
from gspread.utils import ValueInputOption
def create_sheet(args):
"""Create the spreadsheet"""
gc = gspread.service_account(filename=args.credentials, scopes=['https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive'])
sheet = gc.create(args.create)
sheet.share(args.share_with, perm_type='user', role='writer')
print(sheet.id)
def delete_sheet(args):
"""Delete the spreadsheet"""
gc = gspread.service_account(filename=args.credentials, scopes=['https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive'])
gc.del_spreadsheet(args.id)
def import_stats(args):
"""Import the stats data from the given JSON file"""
gc = gspread.service_account(filename=args.credentials, scopes=['https://www.googleapis.com/auth/spreadsheets'])
sheet = gc.open_by_key(args.id)
data = json.load(sys.stdin)
for i, name in enumerate(data):
site_data = data[name]
num_cols = max([len(r) for r in site_data])
num_rows = len(site_data)
try:
wks = sheet.worksheet(name)
except WorksheetNotFound:
wks = sheet.add_worksheet(name, cols=max(num_cols, 50), rows=max(num_rows, 1000), index=i + 2)
wks.freeze(1)
wks.format('1:1', {
'textFormat': {
'bold': True
}
})
if num_cols > wks.col_count:
wks.add_cols(num_cols - wks.col_count)
wks.update('A1', data[name], value_input_option=ValueInputOption.user_entered)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Update the analytics stats spreadsheet from data passed via stdin.')
parser.add_argument('--id', help='The ID of the spreadsheet to update')
parser.add_argument('--credentials', required=True,
help='The path to the Google service account credentials JSON file')
parser.add_argument('--create', help='Create a new spreadsheet with the given name')
parser.add_argument('--share-with', help='Share the created spreadsheet with the given email address')
parser.add_argument('--delete', action='store_true', help='Delete the given spreadsheet')
args = parser.parse_args()
if args.create:
if not args.share_with:
parser.error("Must specify --share-with address when creating a new spreadsheet")
create_sheet(args)
elif args.delete:
if not args.id:
parser.error("Must specify --id when deleting a spreadsheet")
delete_sheet(args)
else:
if not args.id:
parser.error("Must specify either --id or --create")
import_stats(args)