-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_guideline_templates.py
More file actions
executable file
·488 lines (410 loc) · 15 KB
/
Copy pathgenerate_guideline_templates.py
File metadata and controls
executable file
·488 lines (410 loc) · 15 KB
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
#!/usr/bin/env -S uv run
# SPDX-License-Identifier: MIT OR Apache-2.0
# SPDX-FileCopyrightText: The Coding Guidelines Subcommittee Contributors
import argparse
import random
import string
from textwrap import dedent, indent
# Configuration
CHARS = string.ascii_letters + string.digits
ID_LENGTH = 12
# Mapping from issue body headers to dict keys
# Changing issues fields name to snake_case (eg. 'Guideline Title' => 'guideline_title')
issue_header_map = {
"Chapter": "chapter",
"Guideline Title": "guideline_title",
"Category": "category",
"Status": "status",
"Release Begin": "release_begin",
"Release End": "release_end",
"FLS Paragraph ID": "fls_id",
"Decidability": "decidability",
"Scope": "scope",
"Tags": "tags",
"Amplification": "amplification",
"Exception(s)": "exceptions",
"Rationale": "rationale",
# Non-Compliant Examples (1-4)
"Non-Compliant Example 1 - Prose": "non_compliant_ex_prose_1",
"Non-Compliant Example 1 - Code": "non_compliant_ex_1",
"Non-Compliant Example 2 - Prose (Optional)": "non_compliant_ex_prose_2",
"Non-Compliant Example 2 - Code (Optional)": "non_compliant_ex_2",
"Non-Compliant Example 3 - Prose (Optional)": "non_compliant_ex_prose_3",
"Non-Compliant Example 3 - Code (Optional)": "non_compliant_ex_3",
"Non-Compliant Example 4 - Prose (Optional)": "non_compliant_ex_prose_4",
"Non-Compliant Example 4 - Code (Optional)": "non_compliant_ex_4",
# Compliant Examples (1-4)
"Compliant Example 1 - Prose": "compliant_ex_prose_1",
"Compliant Example 1 - Code": "compliant_ex_1",
"Compliant Example 2 - Prose (Optional)": "compliant_ex_prose_2",
"Compliant Example 2 - Code (Optional)": "compliant_ex_2",
"Compliant Example 3 - Prose (Optional)": "compliant_ex_prose_3",
"Compliant Example 3 - Code (Optional)": "compliant_ex_3",
"Compliant Example 4 - Prose (Optional)": "compliant_ex_prose_4",
"Compliant Example 4 - Code (Optional)": "compliant_ex_4",
# Bibliography (Optional)
"Bibliography": "bibliography",
# Legacy field names (for backwards compatibility with old issues)
"Non-Compliant Example - Prose": "non_compliant_ex_prose_1",
"Non-Compliant Example - Code": "non_compliant_ex_1",
"Compliant Example - Prose": "compliant_ex_prose_1",
"Compliant Example - Code": "compliant_ex_1",
}
def generate_id(prefix):
"""Generate a random ID with the given prefix."""
random_part = "".join(random.choice(CHARS) for _ in range(ID_LENGTH))
return f"{prefix}_{random_part}"
def generate_example_block(
example_type: str,
example_id: str,
status: str,
prose: str,
code: str,
) -> str:
"""
Generate a single example block (compliant or non-compliant).
Args:
example_type: Either "compliant_example" or "non_compliant_example"
example_id: The unique ID for this example
status: The status (e.g., "draft")
prose: The prose description
code: The code block content
Returns:
Formatted RST string for the example
"""
indented_code = indent(code.strip(), " " * 13)
return dedent(f"""
.. {example_type}::
:id: {example_id}
:status: {status}
{prose.strip()}
.. rust-example::
{indented_code.strip()}
""")
def generate_bibliography_block(
bibliography_id: str,
guideline_id: str,
status: str,
entries: list, # List of (citation_key, author, title, url) tuples
) -> str:
"""
Generate a bibliography block.
Args:
bibliography_id: The unique ID for this bibliography
guideline_id: The parent guideline ID (for namespacing citations)
status: The status (e.g., "draft")
entries: List of (citation_key, author, title, url) tuples
Returns:
Formatted RST string for the bibliography
Note:
Uses :bibentry: role for citation anchors, namespaced by guideline ID
to avoid conflicts between guidelines using the same citation keys.
"""
if not entries:
return ""
# Build the list-table content
# Use :bibentry: role with guideline_id prefix for namespacing
table_rows = []
for citation_key, author, title, url in entries:
row = f" * - :bibentry:`{guideline_id}:{citation_key}`\n - {author}. \"{title}.\" {url}"
table_rows.append(row)
table_content = "\n".join(table_rows)
return dedent(f"""
.. bibliography::
:id: {bibliography_id}
:status: {status}
.. list-table::
:header-rows: 0
:widths: auto
:class: bibliography-table
{table_content}
""")
def parse_bibliography_entries(bibliography_text: str) -> list:
"""
Parse bibliography entries from text input.
Expected format (one entry per line or block):
[CITATION-KEY] Author. "Title." URL
Or multi-line format:
[CITATION-KEY]
Author: Author Name
Title: The Title
URL: https://example.com
Args:
bibliography_text: Raw bibliography text from issue
Returns:
List of (citation_key, author, title, url) tuples
"""
import re
entries = []
if not bibliography_text or not bibliography_text.strip():
return entries
# Try to parse single-line format first
# Pattern: [KEY] Author. "Title." URL
single_line_pattern = re.compile(
r'\[([A-Z][A-Z0-9-]*[A-Z0-9])\]\s+' # Citation key
r'([^"]+?)\.\s+' # Author (ends with .)
r'"([^"]+)"\.\s*' # Title in quotes
r'(https?://\S+)', # URL
re.MULTILINE
)
for match in single_line_pattern.finditer(bibliography_text):
key, author, title, url = match.groups()
entries.append((key.strip(), author.strip(), title.strip(), url.strip()))
if entries:
return entries
# Try multi-line format
# Split by citation keys
blocks = re.split(r'(?=\[[A-Z][A-Z0-9-]*[A-Z0-9]\])', bibliography_text)
for block in blocks:
block = block.strip()
if not block:
continue
# Extract citation key
key_match = re.match(r'\[([A-Z][A-Z0-9-]*[A-Z0-9])\]', block)
if not key_match:
continue
key = key_match.group(1)
rest = block[key_match.end():].strip()
# Try to extract author, title, url from rest
author = ""
title = ""
url = ""
# Look for labeled format
author_match = re.search(r'Author:\s*(.+?)(?:\n|$)', rest, re.IGNORECASE)
title_match = re.search(r'Title:\s*(.+?)(?:\n|$)', rest, re.IGNORECASE)
url_match = re.search(r'URL:\s*(https?://\S+)', rest, re.IGNORECASE)
if author_match:
author = author_match.group(1).strip()
if title_match:
title = title_match.group(1).strip()
if url_match:
url = url_match.group(1).strip()
# If we didn't find labeled format, try simple line format
if not (author and title and url):
lines = rest.split('\n')
for line in lines:
line = line.strip()
if line.startswith('http'):
url = line
elif not author:
author = line
elif not title:
title = line
if key and (author or title or url):
entries.append((key, author or "Unknown", title or "Untitled", url or ""))
return entries
def guideline_rst_template(
guideline_title: str,
category: str,
status: str,
release_begin: str,
release_end: str,
fls_id: str,
decidability: str,
scope: str,
tags: str,
amplification: str,
exceptions: str,
rationale: str,
non_compliant_examples: list, # List of (prose, code) tuples
compliant_examples: list, # List of (prose, code) tuples
bibliography_entries: list = None, # List of (key, author, title, url) tuples
) -> str:
"""
Generate a .rst guideline entry from field values.
Args:
non_compliant_examples: List of (prose, code) tuples for non-compliant examples
compliant_examples: List of (prose, code) tuples for compliant examples
bibliography_entries: Optional list of (key, author, title, url) tuples
"""
# Generate unique IDs
guideline_id = generate_id("gui")
rationale_id = generate_id("rat")
# Normalize inputs
def norm(value: str) -> str:
return value.strip().lower()
# Build optional exception section
exception_section = ""
if exceptions and exceptions.strip():
exception_section = f"""
**Exceptions**
{exceptions.strip()}
"""
# Generate non-compliant example blocks
non_compliant_blocks = []
for i, (prose, code) in enumerate(non_compliant_examples):
if prose.strip() and code.strip():
example_id = generate_id("non_compl_ex")
block = generate_example_block(
"non_compliant_example",
example_id,
norm(status),
prose,
code,
)
non_compliant_blocks.append(block)
# Generate compliant example blocks
compliant_blocks = []
for i, (prose, code) in enumerate(compliant_examples):
if prose.strip() and code.strip():
example_id = generate_id("compl_ex")
block = generate_example_block(
"compliant_example",
example_id,
norm(status),
prose,
code,
)
compliant_blocks.append(block)
# Generate bibliography block if entries provided
bibliography_block = ""
if bibliography_entries:
bibliography_id = generate_id("bib")
bibliography_block = generate_bibliography_block(
bibliography_id,
guideline_id,
norm(status),
bibliography_entries,
)
# Combine all example blocks
all_examples = "\n".join(non_compliant_blocks + compliant_blocks)
# Add bibliography if present
if bibliography_block:
all_examples += "\n" + bibliography_block
guideline_text = dedent(f"""
.. guideline:: {guideline_title.strip()}
:id: {guideline_id}
:category: {norm(category)}
:status: {norm(status)}
:release: {norm(release_begin)}-{release_end.strip()}
:fls: {norm(fls_id)}
:decidability: {norm(decidability)}
:scope: {norm(scope)}
:tags: {tags}
{amplification.strip()}
{exception_section.strip()}
.. rationale::
:id: {rationale_id}
:status: {norm(status)}
{rationale.strip()}
{all_examples}
""")
return guideline_text
def generate_guideline_template(
num_non_compliant: int = 1,
num_compliant: int = 1,
include_bibliography: bool = False,
num_bib_entries: int = 1,
):
"""
Generate a complete guideline template with all required sections.
Args:
num_non_compliant: Number of non-compliant examples to include (1-4)
num_compliant: Number of compliant examples to include (1-4)
include_bibliography: Whether to include a bibliography section
num_bib_entries: Number of bibliography entries to include (1-5)
"""
# Clamp to valid range
num_non_compliant = max(1, min(4, num_non_compliant))
num_compliant = max(1, min(4, num_compliant))
num_bib_entries = max(1, min(5, num_bib_entries))
# Generate non-compliant examples
non_compliant_examples = []
for i in range(1, num_non_compliant + 1):
non_compliant_examples.append((
f"Explanation of non-compliant example {i}.",
f"fn non_compliant_example_{i}() {{\n // Non-compliant implementation {i}\n}}"
))
# Generate compliant examples
compliant_examples = []
for i in range(1, num_compliant + 1):
compliant_examples.append((
f"Explanation of compliant example {i}.",
f"fn compliant_example_{i}() {{\n // Compliant implementation {i}\n}}"
))
# Generate bibliography entries if requested
bibliography_entries = None
if include_bibliography:
bibliography_entries = []
for i in range(1, num_bib_entries + 1):
bibliography_entries.append((
f"REF-KEY-{i}",
f"Author {i}",
f"Reference Title {i}",
f"https://example.com/ref{i}"
))
template = guideline_rst_template(
guideline_title="Title Here",
category="",
status="draft",
release_begin="",
release_end="",
fls_id="",
decidability="",
scope="",
tags="",
amplification="Description of the guideline goes here.",
exceptions="",
rationale="Explanation of why this guideline is important.",
non_compliant_examples=non_compliant_examples,
compliant_examples=compliant_examples,
bibliography_entries=bibliography_entries,
)
return template
def parse_args():
"""Parse command-line arguments."""
parser = argparse.ArgumentParser(
description="Generate guideline templates with randomly generated IDs"
)
parser.add_argument(
"-n",
"--number-of-templates",
type=int,
default=1,
help="Number of templates to generate (default: 1)",
)
parser.add_argument(
"--non-compliant",
type=int,
default=1,
choices=[1, 2, 3, 4],
help="Number of non-compliant examples to include (default: 1, max: 4)",
)
parser.add_argument(
"--compliant",
type=int,
default=1,
choices=[1, 2, 3, 4],
help="Number of compliant examples to include (default: 1, max: 4)",
)
parser.add_argument(
"--bibliography",
action="store_true",
help="Include a bibliography section in the template",
)
parser.add_argument(
"--bib-entries",
type=int,
default=1,
choices=[1, 2, 3, 4, 5],
help="Number of bibliography entries to include (default: 1, max: 5)",
)
return parser.parse_args()
def main():
"""Generate the specified number of guideline templates."""
args = parse_args()
num_templates = args.number_of_templates
for i in range(num_templates):
if num_templates > 1:
print(f"=== Template {i + 1} ===\n")
template = generate_guideline_template(
num_non_compliant=args.non_compliant,
num_compliant=args.compliant,
include_bibliography=args.bibliography,
num_bib_entries=args.bib_entries,
)
print(template)
if num_templates > 1 and i < num_templates - 1:
print("\n" + "=" * 80 + "\n")
if __name__ == "__main__":
main()