-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinit.py
executable file
·320 lines (241 loc) · 8.54 KB
/
init.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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
#! /usr/bin/env python3
"""init.py.
Initializer script for Advent of Code 2024. Initializes a new day from
the template in 00/zig_template.
"""
from __future__ import annotations
import os
import re
import sys
import argparse
from pathlib import Path
description = """
Initializes a new day from the template in 00/zig_template."""
help = """\
----------------------------------------------------------------------
Example uses:
init.py --name <name>
Initializes the next uninitialized day.
init.py --name <name> --day <day>
Initializes a given day.
"""
TEMPLATE_DAY = 0
TEMPLATE_NAME = "Zig Template"
# -------------------------------------------------------------------- #
def get_day(day: int) -> str:
"""Get a two-digit day string.
Args:
day (int): Given or the next day.
Returns:
str: The two-digit day string.
"""
day_str = "0" if day <= 9 else ""
day_str += str(day)
return day_str
def snake_case(name: str) -> str:
"""Get snake case string.
Args:
name (str): A string.
Returns:
str: A snake case version of the given string.
"""
name_parts = name.lower().split(" ")
return "_".join(name_parts).replace("-", "_")
def pascal_case(name: str) -> str:
"""Get PascalCase string.
Args:
name (str): A string.
Returns:
str: A PascalCase version of the given string.
"""
name_parts = name.lower().split(" ")
for i in range(len(name_parts)):
name_parts[i] = name_parts[i].capitalize()
return "".join(name_parts)
def camel_case(name: str) -> str:
"""Get camelCase string.
Args:
name (str): A string.
Returns:
str: A camelCase version of the given string.
"""
name_parts = name.lower().split(" ")
for i in range(len(name_parts)):
if i > 0:
name_parts[i] = name_parts[i].capitalize()
return "".join(name_parts)
def get_day_folder(day: int, name: str | None = None) -> Path:
"""Get the folder name for a given day.
Args:
day (int): The new day.
name (str | None, optional): The project name. Defaults to None.
Returns:
Path: The path to the subproject.
"""
day_folder = Path(get_day(day))
if name:
day_folder /= snake_case(name)
return Path(__file__).parent / day_folder
def find_next_day() -> int:
"""Find the next day if no day was given.
Returns:
int: The next uninitialized day.
"""
day = 1
while get_day_folder(day).exists():
day += 1
return day
# -------------------------------------------------------------------- #
# Command line options
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description=description,
epilog=help,
)
parser.add_argument(
"-n",
"--name",
action="store",
help="Name of the subproject",
required=True,
)
parser.add_argument(
"-d",
"--day",
action="store",
help="The number of the day",
type=int,
default=find_next_day(),
)
opts = parser.parse_args()
# -------------------------------------------------------------------- #
def search_and_replace(day: int, name: str, contents: str) -> str:
"""Search and Replace day and project name.
Searches for the template project name and the day in different
naming styles and replaces them with the given / next day and given
project name.
Args:
day (int): The new day (replacement for 00 in the template)
name (str): The project name (replacement for the template name)
contents (str): The template project file contents
Returns:
str: The file contents of the new subproject
"""
contents = re.sub(" " + get_day(TEMPLATE_DAY), " " + get_day(day), contents)
contents = re.sub(TEMPLATE_NAME, name, contents)
contents = re.sub(snake_case(TEMPLATE_NAME), snake_case(name), contents)
contents = re.sub(pascal_case(TEMPLATE_NAME), pascal_case(name), contents)
contents = re.sub(camel_case(TEMPLATE_NAME), camel_case(name), contents)
return contents
def init_project(
day: int,
name: str,
) -> None:
"""Initialize a new subproject from the template.
Walk through each file in the template project and replace the day
and project name.
Args:
day (int): The new day (replacement for 00 in the template)
name (str): The project name (replacement for the template name)
"""
source = get_day_folder(TEMPLATE_DAY, TEMPLATE_NAME).as_posix()
destination = get_day_folder(day, name).as_posix()
for dirpath, _, files in os.walk(source):
if "zig-out" in dirpath or "zig-cache" in dirpath:
continue
output_dir = re.sub(source, destination, Path(dirpath).as_posix())
output_dir = search_and_replace(day, name, output_dir)
os.makedirs(output_dir)
for filename in files:
input = Path(dirpath) / filename
with open(input, "r") as file:
contents = file.read()
output = Path(output_dir) / search_and_replace(day, name, filename)
with open(output, "w") as file:
file.write(search_and_replace(day, name, contents))
def subproject_registration(zon: bool) -> str:
"""Generate a subproject string.
Generate a subproject string which registers the subproject in the
root project (build.zig and build.zig.zon).
Args:
zon (bool): Wether to create the subproject string for
build.zig.zon or build.zig.
Returns:
str: The subproject registration string
"""
subproject = ""
if zon:
subproject += " .day_"
subproject += get_day(opts.day) + "_" + snake_case(opts.name)
subproject += ' = .{ .path = "'
subproject += get_day(opts.day) + "/" + snake_case(opts.name) + '" },\n'
else:
subproject += " add_subproject("
subproject += 'b, target, optimize, test_step, benchmark_step, "'
subproject += get_day(opts.day) + '", "'
subproject += snake_case(opts.name) + '");\n'
return subproject
def register_subproject(
filename: str, subproject_pattern: str, registration_string: str
) -> None:
"""Register the subproject in the gven config file.
Args:
filename (str): The config file.
subproject_pattern (str): The regex that matches existing subprojects.
registration_string (str): New subproject string.
"""
config_file = Path(__file__).parent / filename
config: list[str] = []
with open(config_file, "r") as file:
last_line_matched = False
subproject_added = False
for line in file.readlines():
if not subproject_added:
subproject_added = last_line_matched
m = re.match(subproject_pattern, line)
if m and len(m.groups()) == 1:
last_line_matched = True
subproject_added = int(m.group(1)) > opts.day
# Add subproject if the day of the next entry is larger
# or if this is the last entry in the subproject list
if subproject_added:
config.append(registration_string)
config.append(line)
# Add subproject entry at the end of the file
if last_line_matched and not subproject_added:
config.append(registration_string)
with open(config_file, "w") as file:
file.writelines(config)
# -------------------------------------------------------------------- #
def main() -> int:
"""Execute subproject initialization.
Raises:
RuntimeError: If the day is not between 1 and 25.
RuntimeError: If there is already a project for the given day.
Returns:
int: System exit code.
"""
# Check day
if opts.day < 1 or opts.day > 25:
raise RuntimeError("Day needs to be between 1 and 25.")
# Test if folder already exists
folder = get_day_folder(opts.day)
if folder.exists():
raise RuntimeError("Day '{0}' already exists.".format(folder))
# Initialize project
init_project(opts.day, opts.name)
# Initialize as a subproject
register_subproject(
"build.zig",
r".*add_subproject\(.*([0-9]{2}).*\).*",
subproject_registration(zon=False),
)
register_subproject(
"build.zig.zon", r".*_([0-9]{2})_.*", subproject_registration(zon=True)
)
register_subproject(
"build.zig.zon", r'.*"([0-9]{2})".*', ' "' + get_day(opts.day) + '",\n'
)
return 0
if __name__ == "__main__":
sys.exit(main())