tocs 1.0.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
tocs/__init__.py ADDED
File without changes
tocs/main.py ADDED
@@ -0,0 +1,133 @@
1
+ import argparse
2
+ from pathlib import Path
3
+ import re
4
+ import sys
5
+
6
+ INDENT_LEVEL = " "
7
+
8
+
9
+ def create_toc_row(line: str, max_depth: int = None) -> str:
10
+ hashes = 0
11
+ j = 0
12
+
13
+ while line[j] == "#":
14
+ hashes += 1
15
+ j += 1
16
+
17
+ if max_depth and hashes > max_depth:
18
+ return None
19
+
20
+ line_content = line[hashes + 1 :]
21
+ anchor = create_anchor(line_content)
22
+ toc_row = f"{INDENT_LEVEL *(hashes-1)}- [{line_content}](#{anchor})"
23
+ return toc_row
24
+
25
+
26
+ def create_anchor(line_content: str) -> str:
27
+ anchor = re.sub(r"[^a-zA-Z0-9\-_ ]", "", line_content)
28
+ return anchor.replace(" ", "-").lower()
29
+
30
+
31
+ def toggle_ignore_rows_flag(ignore_rows: bool, line: str):
32
+ """
33
+ Controls whether to ignore rows inside code snippets that start with ```.
34
+ Also handles multiline snippets.
35
+ """
36
+ if line == "```":
37
+ return not ignore_rows
38
+ elif line.startswith("```") and not line.endswith("```"):
39
+ return True
40
+ elif line.startswith("```") and line.endswith("```"):
41
+ return False
42
+ else:
43
+ return ignore_rows
44
+
45
+
46
+ def process_file(path, depth=None):
47
+ lines = []
48
+ tocs = []
49
+ init_toc_position = -1
50
+ end_toc_position = -1
51
+ ignore_rows = False
52
+
53
+ try:
54
+ with open(path, "rt") as f:
55
+ lines = f.read().splitlines()
56
+ except (IOError, PermissionError) as e:
57
+ print(f"Error while reading {path}: {e}", file=sys.stderr)
58
+ sys.exit(1)
59
+
60
+ for i, line in enumerate(lines):
61
+ ignore_rows = toggle_ignore_rows_flag(ignore_rows, line)
62
+
63
+ if ignore_rows:
64
+ continue
65
+
66
+ if "<!-- init-tocs -->" in line:
67
+ init_toc_position = i
68
+ elif "<!-- end-tocs -->" in line:
69
+ end_toc_position = i
70
+ elif line.startswith("#"):
71
+ toc_row = create_toc_row(line, depth)
72
+ if toc_row:
73
+ tocs.append(toc_row)
74
+
75
+ if (
76
+ init_toc_position == -1
77
+ or end_toc_position == -1
78
+ or init_toc_position >= end_toc_position
79
+ ):
80
+ print(
81
+ f"Error: Missing or invalid TOC markers. Add '<!-- init-tocs -->' and '<!-- end-tocs -->' to your file.",
82
+ file=sys.stderr,
83
+ )
84
+ sys.exit(1)
85
+
86
+ lines_before_tocs = lines[: init_toc_position + 1]
87
+ lines_after_tocs = lines[end_toc_position:]
88
+ new_lines = lines_before_tocs + tocs + lines_after_tocs
89
+
90
+ try:
91
+ with open(path, "w") as f:
92
+ for l in new_lines:
93
+ f.write(l + "\n")
94
+ except (IOError, PermissionError) as e:
95
+ print(f"Error while writing {path}: {e}", file=sys.stderr)
96
+ sys.exit(1)
97
+
98
+
99
+ def main():
100
+ parser = argparse.ArgumentParser(
101
+ prog="tocs",
102
+ description="Generate table of contents for markdown files",
103
+ epilog="""
104
+ Examples:
105
+ tocs /path/to/file.md Generate TOC in file.md
106
+
107
+ Requirements:
108
+ The file must contain <!-- init-tocs --> and <!-- end-tocs --> markers.
109
+ """,
110
+ formatter_class=argparse.RawDescriptionHelpFormatter,
111
+ )
112
+
113
+ parser.add_argument("file", help="Markdown file to process")
114
+ parser.add_argument(
115
+ "--depth", type=int, help="Maximum header depth to include in TOC"
116
+ )
117
+ parser.add_argument("--version", action="version", version="tocs 1.0.2")
118
+ args = parser.parse_args()
119
+ path = Path(args.file).resolve()
120
+
121
+ if not path.exists():
122
+ print(f"Error: File '{args.file}' not found", file=sys.stderr)
123
+ sys.exit(1)
124
+
125
+ if args.depth is not None and args.depth < 1:
126
+ print(f"Error: depth must be greater than 0", file=sys.stderr)
127
+ sys.exit(1)
128
+
129
+ process_file(path, args.depth)
130
+
131
+
132
+ if __name__ == "__main__":
133
+ main()
@@ -0,0 +1,88 @@
1
+ Metadata-Version: 2.4
2
+ Name: tocs
3
+ Version: 1.0.2
4
+ Summary: Generate TOC for markdown files
5
+ Author-email: Andrea Bondanini <bondaniniandrea@gmail.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/sbundaz/tocs
8
+ Project-URL: Repository, https://github.com/sbundaz/tocs
9
+ Project-URL: Issues, https://github.com/sbundaz/tocs/issues
10
+ Keywords: markdown,tocs,cli,documentation,generator
11
+ Requires-Python: >=3.11.9
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Provides-Extra: dev
15
+ Requires-Dist: pytest; extra == "dev"
16
+ Requires-Dist: black; extra == "dev"
17
+ Dynamic: license-file
18
+
19
+ # tocs
20
+ **tocs** is a simple CLI application written in Python that generates **the table of contents (TOC)** section for markdown files.<br>
21
+ As a person who loves to write personal technical notes in markdown files, I needed something simple to use.
22
+
23
+ ## How to install and use tocs
24
+ **Prerequisites:** Python 3.11.9+ and pipx installed (`pip install pipx`).
25
+
26
+ At the moment only a **manual installation** is available:
27
+ - clone the repository
28
+ - from the root of the repository: `pipx install .`
29
+ - to upgrade tocs version: `pipx upgrade tocs`
30
+
31
+ **Basic usage:**<br>
32
+ - `tocs input_file.md` - Generate TOC for the file
33
+ - `tocs --help` - Show usage instructions
34
+ - `tocs --version` - Display version information
35
+
36
+ ### tocs example
37
+ Given the following markdown file **input_file.md**:
38
+ ```md
39
+ # header 1
40
+ Lorem ipsum dolor sit amet...
41
+
42
+ ## header 2
43
+ Lorem ipsum dolor sit amet...
44
+
45
+ ### header 3
46
+ Lorem ipsum dolor sit amet...
47
+ ```
48
+
49
+ Add two tags where you want the TOCs table:
50
+ ```md
51
+ <!-- init-tocs -->
52
+ <!-- end-tocs -->
53
+
54
+ # header 1
55
+ Lorem ipsum dolor sit amet...
56
+
57
+ ## header 2
58
+ Lorem ipsum dolor sit amet...
59
+
60
+ ### header 3
61
+ Lorem ipsum dolor sit amet...
62
+ ```
63
+
64
+ Run `tocs input_file.md` and here's the output:
65
+
66
+ ```md
67
+ <!-- init-tocs -->
68
+ - [header 1](#header-1)
69
+ - [header 2](#header-2)
70
+ - [header 3](#header-3)
71
+
72
+ <!-- end-tocs -->
73
+
74
+ # header 1
75
+ Lorem ipsum dolor sit amet...
76
+
77
+ ## header 2
78
+ Lorem ipsum dolor sit amet...
79
+
80
+ ### header 3
81
+ Lorem ipsum dolor sit amet...
82
+ ```
83
+
84
+ ## Development
85
+ - create venv: `python -m venv .venv`
86
+ - activate venv: `source .venv/bin/activate`
87
+ - install project and dependencies (editable mode): `pip install -e .[dev]`
88
+ - deactivate venv: `deactivate`
@@ -0,0 +1,8 @@
1
+ tocs/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ tocs/main.py,sha256=ombPe8jl7-cVw9DSQCmNPcVnCbM6gNicojiwINChSlM,3664
3
+ tocs-1.0.2.dist-info/licenses/LICENSE,sha256=qJceCqujZXzRT59eqPEsb4TV_ROPTcT-pPB0HCezJRs,1060
4
+ tocs-1.0.2.dist-info/METADATA,sha256=Kgo34yDoDN9_MIlzK21zgUOui4Bq5_7fLsqS2cZL6ko,2242
5
+ tocs-1.0.2.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
6
+ tocs-1.0.2.dist-info/entry_points.txt,sha256=_bClPsOh1CuzHjfiFZjZ0_3XOvhgXE_aohdgVlH9-J8,40
7
+ tocs-1.0.2.dist-info/top_level.txt,sha256=1jLTMx9e_xv0vNs8qX52AELh14SGKXnmDNSiF_cAR0o,5
8
+ tocs-1.0.2.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ tocs = tocs.main:main
@@ -0,0 +1,19 @@
1
+ Copyright (c) 2025 Andrea Bondanini
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
14
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
15
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
16
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
17
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
18
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
19
+ OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1 @@
1
+ tocs