-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcompile.py
195 lines (163 loc) · 6.04 KB
/
compile.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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
# MIT License
#
# Copyright (c) 2024-2025 Yegor Bugayenko
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# flake8: noqa: WPS202
import datetime
import sys
from pathlib import Path
from typing import Literal, TypeAlias, TypedDict
from copy import deepcopy
import httpx
import yaml
class InvalidUrlError(Exception):
"""Exception throwed on fail ping url."""
class ExpiredCfpError(Exception):
"""Exception throwed on call for papers date expired."""
DateAsStrT: TypeAlias = str
RawDateT: TypeAlias = DateAsStrT | Literal["closed"]
class ConfInfoDict(TypedDict):
name: str
year: str
url: str
publisher: str
rank: str
core: str
scope: str
short: str
full: str
format: str
cfp: str
country: str
def build_name(conf_name: str, conf_info: ConfInfoDict) -> str:
"""Build name.
>>> build_name('ABC', {'year': '2099', 'url': 'https://google.com', 'later': False})
"[ABC'99](<https://google.com>)"
>>> build_name('ABC', {'year': 2099, 'url': 'https://google.com', 'later': False})
"[ABC'99](<https://google.com>)"
"""
year_last_two_digit = str(conf_info["year"])[-2:]
return "[{0}'{1}](<{2}>)".format(
conf_name,
year_last_two_digit,
validate_url(conf_info["url"]) if not conf_info["later"] else conf_info["url"],
)
def date_actual(date: datetime.date) -> datetime.date:
today = datetime.datetime.now(tz=datetime.UTC).date()
if date > today:
return date
raise ExpiredCfpError("{0} expired for today {1}".format(date, today))
def render_date(raw_date: RawDateT | None):
"""Render date.
>>> render_date("2090-01-01")
'90-Jan'
>>> render_date("closed")
'closed'
>>> render_date(None)
''
"""
if not raw_date:
return ""
if raw_date == "closed":
return "closed"
parsed_date = datetime.datetime.strptime(raw_date, "%Y-%m-%d").date()
return parsed_date.strftime("%y-%b")
def build_row(conf_name: str, conf_info: list[dict], markdown_table_row_template: str):
return markdown_table_row_template.format(
name=build_name(conf_name, conf_info),
publisher=conf_info["publisher"] or "",
rank="[{0}](<{1}>)".format(
conf_info["rank"],
validate_url(conf_info["core"]) if not conf_info["later"] else conf_info["url"],
),
scope=conf_info["scope"],
short=conf_info["short"] or "",
full=conf_info["full"] or "",
format=conf_info["format"] or "",
cfp=render_date(conf_info["cfp"]),
country=conf_info["country"],
)
def md_rows(yaml_as_dict: dict[str, ConfInfoDict], markdown_table_row_template: str):
sorting_dict = {char: idx for idx, char in enumerate(["A*", "A", "B", "C", "D", "E", "F"])}
return [
build_row(conf_name, conf_info, markdown_table_row_template)
for conf_name, conf_info in sorted(
yaml_as_dict.items(),
key=lambda x: sorting_dict[x[1]["rank"]]
)
]
def validate_url(url: str) -> str:
response = httpx.get(url)
status_success = httpx.codes.is_success(response.status_code)
allow_status = status_success or httpx.codes.is_redirect(response.status_code)
if not allow_status:
raise InvalidUrlError("Url = '{0}' return status = {1}".format(url, response.status_code))
return url
def mark_expired_dates(yaml_path: str):
yaml_content = Path(yaml_path).read_text()
origin_yaml = yaml.safe_load(yaml_content)
updated_yaml = deepcopy(origin_yaml)
for conf_name, conf_info in yaml.safe_load(yaml_content).items():
if not conf_info["cfp"] or conf_info["cfp"] == "closed":
continue
try:
date_actual(
datetime.datetime.strptime(conf_info["cfp"], "%Y-%m-%d").date(),
)
except ExpiredCfpError:
updated_yaml[conf_name]["cfp"] = "closed"
Path(yaml_path).write_text(
"{0}---\n{1}".format(
yaml_content.split("---")[0],
yaml.safe_dump(updated_yaml),
),
)
def generate(yaml_path, md_path):
mark_expired_dates(yaml_path)
headers = ["name", "publisher", "rank", "scope", "short", "full", "format", "cfp", "country"]
markdown_table_row_template = "".join([
"| {name} ",
"| {publisher} ",
"| {rank} ",
"| {scope} ",
"| {short} ",
"| {full} ",
"| {format} ",
"| {cfp} ",
"| {country} |",
])
markdown_table_rows = ["| {0} |".format(" | ".join(headers))]
markdown_table_rows.append(
"| {0} |".format(
" | ".join(["---" for _ in range(len(headers))]),
),
)
markdown_table_rows.extend(
md_rows(
yaml.safe_load(Path(yaml_path).read_text()),
markdown_table_row_template,
),
)
sep = "<!-- events -->"
splitted_md = Path(md_path).read_text().split(sep)
splitted_md[1] = "\n{0}\n\n".format("\n".join(markdown_table_rows))
Path(md_path).write_text(sep.join(splitted_md))
if __name__ == "__main__":
generate(sys.argv[1], sys.argv[2]) # pragma: no cover