forked from NateScarlet/holiday-cn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupdate.py
executable file
·181 lines (146 loc) · 4.51 KB
/
update.py
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
#!/usr/bin/env python3
"""Script for updating data. """
import argparse
import json
import os
import re
import subprocess
from datetime import datetime, timedelta, tzinfo
from tempfile import mkstemp
from typing import Iterator
from zipfile import ZipFile
from tqdm import tqdm
from fetch_holidays import CustomJSONEncoder, fetch_holiday
from generate_ics import generate_ics
class ChinaTimezone(tzinfo):
"""Timezone of china."""
def tzname(self, dt):
return "UTC+8"
def utcoffset(self, dt):
return timedelta(hours=8)
def dst(self, dt):
return timedelta()
__dirname__ = os.path.abspath(os.path.dirname(__file__))
def _file_path(*other):
return os.path.join(__dirname__, *other)
def update_data(year: int) -> Iterator[str]:
"""Update and store data for a year."""
json_filename = _file_path(f"{year}.json")
ics_filename = _file_path(f"{year}.ics")
with open(json_filename, "w", encoding="utf-8", newline="\n") as f:
data = fetch_holiday(year)
json.dump(
dict(
(
(
"$schema",
"https://raw.githubusercontent.com/NateScarlet/holiday-cn/master/schema.json",
),
(
"$id",
f"https://raw.githubusercontent.com/NateScarlet/holiday-cn/master/{year}.json",
),
*data.items(),
)
),
f,
indent=4,
ensure_ascii=False,
cls=CustomJSONEncoder,
)
yield json_filename
generate_ics(data["days"], ics_filename)
yield ics_filename
def update_main_ics(fr_year, to_year):
all_days = []
for year in range(fr_year, to_year + 1):
filename = _file_path(f"{year}.json")
if not os.path.isfile(filename):
continue
with open(filename, "r", encoding="utf8") as inf:
data = json.loads(inf.read())
all_days.extend(data.get("days"))
filename = _file_path("holiday-cn.ics")
generate_ics(
all_days,
filename,
)
return filename
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"--all",
action="store_true",
help="Update all years since 2007, default is this year and next year",
)
parser.add_argument(
"--release",
action="store_true",
help="create new release if repository data is not up to date",
)
args = parser.parse_args()
now = datetime.now(ChinaTimezone())
is_release = args.release
filenames = []
progress = tqdm(range(2007 if args.all else now.year, now.year + 2))
for i in progress:
progress.set_description(f"Updating {i} data")
filenames += list(update_data(i))
progress.set_description("Updating holiday-cn.ics")
filenames.append(update_main_ics(now.year - 4, now.year + 1))
print("")
subprocess.run(["hub", "add", *filenames], check=True)
diff = subprocess.run(
["hub", "diff", "--stat", "--cached", "*.json", "*.ics"],
check=True,
stdout=subprocess.PIPE,
encoding="utf-8",
).stdout
if not diff:
print("Already up to date.")
return
if not is_release:
print("Updated repository data, skip release since not specified `--release`")
return
subprocess.run(
[
"hub",
"commit",
"-m",
"chore(release): update holiday data",
"-m",
"[skip ci]",
],
check=True,
)
subprocess.run(["hub", "push"], check=True)
tag = now.strftime("%Y.%m.%d")
temp_note_fd, temp_note_name = mkstemp()
with open(temp_note_fd, "w", encoding="utf-8") as f:
f.write(tag + "\n\n```diff\n" + diff + "\n```\n")
os.makedirs(_file_path("dist"), exist_ok=True)
zip_path = _file_path("dist", f"holiday-cn-{tag}.zip")
pack_data(zip_path)
subprocess.run(
[
"hub",
"release",
"create",
"-F",
temp_note_name,
"-a",
f"{zip_path}#JSON数据",
tag,
],
check=True,
)
os.unlink(temp_note_name)
def pack_data(file):
"""Pack data json in zip file."""
zip_file = ZipFile(file, "w")
for i in os.listdir(__dirname__):
if not re.match(r"\d+\.json", i):
continue
zip_file.write(_file_path(i), i)
if __name__ == "__main__":
main()