-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathparse_config.py
More file actions
93 lines (74 loc) · 2.62 KB
/
Copy pathparse_config.py
File metadata and controls
93 lines (74 loc) · 2.62 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
#!/usr/bin/env python3
"""Parse YAML frontmatter from Facet config files.
Replaces the sed-based parse_frontmatter() in sim.sh with a single
Python parser that handles both scalar values and YAML arrays.
Usage:
python3 parse_config.py <file> <key> # print scalar value
python3 parse_config.py <file> <key> --list # print array, one item per line
python3 parse_config.py <file> --body # print body (everything after frontmatter)
"""
import sys
import yaml
def parse_frontmatter(filepath):
"""Extract YAML frontmatter and body from a markdown file."""
with open(filepath, 'r') as f:
content = f.read()
if not content.startswith('---'):
return {}, content
# Find the closing --- at the start of a line
# (content.find('---', 3) would match '---' inside YAML string values)
end = -1
search_start = 3
while True:
pos = content.find('---', search_start)
if pos == -1:
break
# Must be at start of line (pos == 0 already handled, check for \n before)
if pos > 0 and content[pos - 1] == '\n':
end = pos
break
search_start = pos + 3
if end == -1:
return {}, content
frontmatter_str = content[3:end].strip()
body = content[end + 3:].strip()
try:
frontmatter = yaml.safe_load(frontmatter_str) or {}
except yaml.YAMLError:
frontmatter = {}
return frontmatter, body
def main():
if len(sys.argv) < 3:
print(f"Usage: {sys.argv[0]} <file> <key> [--list]", file=sys.stderr)
print(f" {sys.argv[0]} <file> --body", file=sys.stderr)
sys.exit(1)
filepath = sys.argv[1]
if sys.argv[2] == '--body':
_, body = parse_frontmatter(filepath)
print(body)
return
key = sys.argv[2]
as_list = '--list' in sys.argv
frontmatter, _ = parse_frontmatter(filepath)
value = frontmatter.get(key, '')
if as_list:
if isinstance(value, list):
for item in value:
if isinstance(item, dict):
# Handle list of dicts — extract 'config' key if present, else first value
if 'config' in item:
print(item['config'])
else:
first_val = next(iter(item.values()), None)
if first_val is not None:
print(first_val)
else:
print(item)
elif value:
print(value)
else:
if value is None:
value = ''
print(value)
if __name__ == '__main__':
main()