tocs 1.0.2__tar.gz

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-1.0.2/LICENSE ADDED
@@ -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.
tocs-1.0.2/PKG-INFO ADDED
@@ -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`
tocs-1.0.2/README.md ADDED
@@ -0,0 +1,70 @@
1
+ # tocs
2
+ **tocs** is a simple CLI application written in Python that generates **the table of contents (TOC)** section for markdown files.<br>
3
+ As a person who loves to write personal technical notes in markdown files, I needed something simple to use.
4
+
5
+ ## How to install and use tocs
6
+ **Prerequisites:** Python 3.11.9+ and pipx installed (`pip install pipx`).
7
+
8
+ At the moment only a **manual installation** is available:
9
+ - clone the repository
10
+ - from the root of the repository: `pipx install .`
11
+ - to upgrade tocs version: `pipx upgrade tocs`
12
+
13
+ **Basic usage:**<br>
14
+ - `tocs input_file.md` - Generate TOC for the file
15
+ - `tocs --help` - Show usage instructions
16
+ - `tocs --version` - Display version information
17
+
18
+ ### tocs example
19
+ Given the following markdown file **input_file.md**:
20
+ ```md
21
+ # header 1
22
+ Lorem ipsum dolor sit amet...
23
+
24
+ ## header 2
25
+ Lorem ipsum dolor sit amet...
26
+
27
+ ### header 3
28
+ Lorem ipsum dolor sit amet...
29
+ ```
30
+
31
+ Add two tags where you want the TOCs table:
32
+ ```md
33
+ <!-- init-tocs -->
34
+ <!-- end-tocs -->
35
+
36
+ # header 1
37
+ Lorem ipsum dolor sit amet...
38
+
39
+ ## header 2
40
+ Lorem ipsum dolor sit amet...
41
+
42
+ ### header 3
43
+ Lorem ipsum dolor sit amet...
44
+ ```
45
+
46
+ Run `tocs input_file.md` and here's the output:
47
+
48
+ ```md
49
+ <!-- init-tocs -->
50
+ - [header 1](#header-1)
51
+ - [header 2](#header-2)
52
+ - [header 3](#header-3)
53
+
54
+ <!-- end-tocs -->
55
+
56
+ # header 1
57
+ Lorem ipsum dolor sit amet...
58
+
59
+ ## header 2
60
+ Lorem ipsum dolor sit amet...
61
+
62
+ ### header 3
63
+ Lorem ipsum dolor sit amet...
64
+ ```
65
+
66
+ ## Development
67
+ - create venv: `python -m venv .venv`
68
+ - activate venv: `source .venv/bin/activate`
69
+ - install project and dependencies (editable mode): `pip install -e .[dev]`
70
+ - deactivate venv: `deactivate`
@@ -0,0 +1,40 @@
1
+ [project]
2
+ name = "tocs"
3
+ description = "Generate TOC for markdown files"
4
+ authors = [{ name = "Andrea Bondanini", email = "bondaniniandrea@gmail.com" }]
5
+ license = { text = "MIT" }
6
+ version = "1.0.2"
7
+ requires-python = ">=3.11.9"
8
+ readme = "README.md"
9
+ keywords = ["markdown", "tocs", "cli", "documentation", "generator"]
10
+ urls = { "Homepage" = "https://github.com/sbundaz/tocs", "Repository" = "https://github.com/sbundaz/tocs", "Issues" = "https://github.com/sbundaz/tocs/issues" }
11
+
12
+ [project.optional-dependencies]
13
+ dev = ["pytest", "black"]
14
+
15
+ [build-system]
16
+ requires = ["setuptools>=45", "wheel"]
17
+ build-backend = "setuptools.build_meta"
18
+
19
+ [tool.setuptools]
20
+ packages = ["tocs"]
21
+
22
+ [project.scripts]
23
+ tocs = "tocs.main:main"
24
+
25
+ [tool.black]
26
+ line-length = 88
27
+ include = '\.pyi?$'
28
+ extend-exclude = '''
29
+ /(
30
+ # directories
31
+ \.eggs
32
+ | \.git
33
+ | \.hg
34
+ | \.mypy_cache
35
+ | \.tox
36
+ | \.venv
37
+ | build
38
+ | dist
39
+ )/
40
+ '''
tocs-1.0.2/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,148 @@
1
+ import shutil
2
+ import subprocess
3
+ import tempfile
4
+ import pytest
5
+ from tocs.main import INDENT_LEVEL, create_toc_row
6
+
7
+
8
+ def test_lorem_ipsum():
9
+ with tempfile.NamedTemporaryFile(mode="w", suffix=".md") as tmp:
10
+ shutil.copy("tests/fixtures/lorem_ipsum_input.md", tmp.name)
11
+
12
+ result = subprocess.run(
13
+ ["python3", "tocs/main.py", tmp.name], capture_output=True, text=True
14
+ )
15
+
16
+ assert result.returncode == 0
17
+
18
+ with open(tmp.name) as f:
19
+ actual = f.read()
20
+
21
+ with open("tests/fixtures/lorem_ipsum_output.md") as f:
22
+ expected = f.read()
23
+
24
+ assert actual == expected
25
+
26
+
27
+ def test_lorem_ipsum_depth_2():
28
+ with tempfile.NamedTemporaryFile(mode="w", suffix=".md") as tmp:
29
+ shutil.copy("tests/fixtures/lorem_ipsum_depth_2_input.md", tmp.name)
30
+
31
+ result = subprocess.run(
32
+ ["python3", "tocs/main.py", tmp.name, "--depth", "2"],
33
+ capture_output=True,
34
+ text=True,
35
+ )
36
+
37
+ assert result.returncode == 0
38
+
39
+ with open(tmp.name) as f:
40
+ actual = f.read()
41
+
42
+ with open("tests/fixtures/lorem_ipsum_depth_2_output.md") as f:
43
+ expected = f.read()
44
+
45
+ assert actual == expected
46
+
47
+
48
+ def test_lorem_ipsum_with_invalid_depth():
49
+ with tempfile.NamedTemporaryFile(mode="w", suffix=".md") as tmp:
50
+ shutil.copy("tests/fixtures/lorem_ipsum_depth_2_input.md", tmp.name)
51
+
52
+ result = subprocess.run(
53
+ ["python3", "tocs/main.py", tmp.name, "--depth", "0"],
54
+ capture_output=True,
55
+ text=True,
56
+ )
57
+
58
+ print(result)
59
+
60
+ assert result.returncode == 1
61
+ assert result.stderr == "Error: depth must be greater than 0\n"
62
+
63
+
64
+ @pytest.mark.parametrize(
65
+ "fixture_file_name",
66
+ [
67
+ "wrong_toc_config_init.md",
68
+ "wrong_toc_config_end.md",
69
+ "wrong_toc_config_order.md",
70
+ ],
71
+ )
72
+ def test_invalid_toc_configuration(fixture_file_name):
73
+ with tempfile.NamedTemporaryFile(mode="w", suffix=".md") as tmp:
74
+ shutil.copy(f"tests/fixtures/{fixture_file_name}", tmp.name)
75
+
76
+ result = subprocess.run(
77
+ ["python3", "tocs/main.py", tmp.name], capture_output=True, text=True
78
+ )
79
+
80
+ assert result.returncode == 1
81
+ assert (
82
+ result.stderr
83
+ == "Error: Missing or invalid TOC markers. Add '<!-- init-tocs -->' and '<!-- end-tocs -->' to your file.\n"
84
+ )
85
+
86
+
87
+ def test_create_toc_row_h1():
88
+ header = "# Hello World"
89
+
90
+ result = create_toc_row(header)
91
+
92
+ assert result == "- [Hello World](#hello-world)"
93
+
94
+
95
+ def test_create_toc_row_h2():
96
+ header = "## Hello World"
97
+
98
+ result = create_toc_row(header)
99
+
100
+ assert result == f"{INDENT_LEVEL}- [Hello World](#hello-world)"
101
+
102
+
103
+ def test_create_toc_row_h3():
104
+ header = "### Hello World"
105
+
106
+ result = create_toc_row(header)
107
+
108
+ assert result == f"{INDENT_LEVEL}{INDENT_LEVEL}- [Hello World](#hello-world)"
109
+
110
+
111
+ def test_create_toc_with_hyphen():
112
+ header = "# Hello-World"
113
+
114
+ result = create_toc_row(header)
115
+
116
+ assert result == "- [Hello-World](#hello-world)"
117
+
118
+
119
+ def test_create_toc_with_multiple_hyphens():
120
+ header = "# Hello--World"
121
+
122
+ result = create_toc_row(header)
123
+
124
+ assert result == "- [Hello--World](#hello--world)"
125
+
126
+
127
+ def test_create_toc_with_underscore():
128
+ header = "# Hello_World"
129
+
130
+ result = create_toc_row(header)
131
+
132
+ assert result == "- [Hello_World](#hello_world)"
133
+
134
+
135
+ def test_create_toc_with_multiple_underscore():
136
+ header = "# Hello__World"
137
+
138
+ result = create_toc_row(header)
139
+
140
+ assert result == "- [Hello__World](#hello__world)"
141
+
142
+
143
+ def test_create_toc_remove_special_chars():
144
+ header = "# Hello!?.:;'\"()[]{}@#$%^&*+=<>/\\|`~World"
145
+
146
+ result = create_toc_row(header)
147
+
148
+ assert result == "- [Hello!?.:;'\"()[]{}@#$%^&*+=<>/\\|`~World](#helloworld)"
File without changes
@@ -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,12 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ tests/test_toc.py
5
+ tocs/__init__.py
6
+ tocs/main.py
7
+ tocs.egg-info/PKG-INFO
8
+ tocs.egg-info/SOURCES.txt
9
+ tocs.egg-info/dependency_links.txt
10
+ tocs.egg-info/entry_points.txt
11
+ tocs.egg-info/requires.txt
12
+ tocs.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ tocs = tocs.main:main
@@ -0,0 +1,4 @@
1
+
2
+ [dev]
3
+ pytest
4
+ black
@@ -0,0 +1 @@
1
+ tocs