forked from vemel/handsdown
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrings.py
More file actions
74 lines (53 loc) · 1.67 KB
/
Copy pathstrings.py
File metadata and controls
74 lines (53 loc) · 1.67 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
"""Utils for strings."""
def make_title(file_stem: str) -> str:
"""
Convert `pathlib.Path` part or any other string to a human-readable title.
Replace underscores with spaces and capitalize result.
Examples:
```python
make_title(Path("my_module/my_path.py").stem)
"My Path"
make_title("my_title")
"My Title"
make_title("__init__.py")
"Init Py"
make_title(Path("my_module/__main__.py").stem)
"Module"
```
Arguments:
file_stem -- Stem from path.
Returns:
A human-readable title as a string.
"""
if file_stem == "__main__":
return "Module"
parts = file_stem.replace(".", "_").split("_")
name_parts: list[str] = []
for part in parts:
if not part:
continue
name_part = part.strip().capitalize()
name_parts.append(name_part)
return " ".join(name_parts)
def extract_md_title(content: str) -> tuple[str, str]:
r"""
Extract title from the first line of content.
If title is present - return a title and a remnaing content.
if not - return an empty title and untouched content.
Examples:
```python
extract_md_title('# Title\ncontent')
('Title', 'content')
extract_md_title('no title\ncontent')
('', 'no title\ncontent')
```
Returns:
A tuple fo title and remaining content.
"""
title = ""
if content.startswith("# "):
if "\n" not in content:
content = f"{content}\n"
title_line, content = content.split("\n", 1)
title = title_line.split(" ", 1)[-1].strip()
return title, content