Created
June 4, 2025 04:04
-
-
Save OhadRubin/7aba35ef832ba2c1e016b27396b9a83e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
""" | |
Parse a listing like the one in stdin and write each file to disk. | |
""" | |
import re | |
import sys | |
from pathlib import Path | |
_PATH_LINE = re.compile(r"^/.*:$") | |
_DASH_LINE = re.compile(r"^[\-\u2500\u2501]+$") # ascii or box-drawing dashes | |
_NUM_LINE = re.compile(r"^\s*\d+\s*\|\s?(.*)$") | |
def _is_path(line: str) -> bool: | |
return bool(_PATH_LINE.match(line.strip())) | |
def _is_dash(line: str) -> bool: | |
return bool(_DASH_LINE.match(line.strip())) | |
def _strip_prefix(line: str) -> str: | |
m = _NUM_LINE.match(line) | |
return m.group(1) if m else line | |
def parse(text: str) -> dict[str, str]: | |
"""Return {path: file_content} from the input text.""" | |
files: dict[str, list[str]] = {} | |
lines = text.splitlines() | |
i = 0 | |
while i < len(lines): | |
if not _is_path(lines[i]): | |
i += 1 | |
continue | |
path = lines[i].strip()[:-1] # drop trailing ':' | |
i += 1 | |
if i < len(lines) and _is_dash(lines[i]): | |
i += 1 # skip separator line | |
content: list[str] = [] | |
while i < len(lines) and not _is_path(lines[i]): | |
if _is_dash(lines[i]) and i + 1 < len(lines) and _is_path(lines[i + 1]): | |
break # end of this file block | |
content.append(_strip_prefix(lines[i])) | |
i += 1 | |
files[path] = "\n".join(content).rstrip("\n") + "\n" | |
return files | |
def write_files(files: dict[str, str], root: Path = Path(".")) -> None: | |
"""Create directories and write file contents.""" | |
for rel_path, body in files.items(): | |
dst = root / rel_path.lstrip("/") | |
dst.parent.mkdir(parents=True, exist_ok=True) | |
dst.write_text(body, encoding="utf-8") | |
if __name__ == "__main__": | |
data = sys.stdin.read() | |
write_files(parse(data)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment