sphinx-cmd 0.2.1__tar.gz → 0.3.0__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.
- {sphinx_cmd-0.2.1/sphinx_cmd.egg-info → sphinx_cmd-0.3.0}/PKG-INFO +23 -2
- {sphinx_cmd-0.2.1 → sphinx_cmd-0.3.0}/README.md +21 -1
- {sphinx_cmd-0.2.1 → sphinx_cmd-0.3.0}/pyproject.toml +5 -1
- {sphinx_cmd-0.2.1 → sphinx_cmd-0.3.0}/sphinx_cmd/__init__.py +1 -1
- sphinx_cmd-0.3.0/sphinx_cmd/commands/rm.py +262 -0
- sphinx_cmd-0.3.0/sphinx_cmd/config.py +81 -0
- {sphinx_cmd-0.2.1 → sphinx_cmd-0.3.0/sphinx_cmd.egg-info}/PKG-INFO +23 -2
- {sphinx_cmd-0.2.1 → sphinx_cmd-0.3.0}/sphinx_cmd.egg-info/SOURCES.txt +3 -0
- {sphinx_cmd-0.2.1 → sphinx_cmd-0.3.0}/sphinx_cmd.egg-info/requires.txt +3 -0
- sphinx_cmd-0.3.0/tests/test_config.py +79 -0
- sphinx_cmd-0.3.0/tests/test_custom_directives.py +125 -0
- {sphinx_cmd-0.2.1 → sphinx_cmd-0.3.0}/tests/test_rm.py +109 -0
- sphinx_cmd-0.2.1/sphinx_cmd/commands/rm.py +0 -158
- {sphinx_cmd-0.2.1 → sphinx_cmd-0.3.0}/LICENSE +0 -0
- {sphinx_cmd-0.2.1 → sphinx_cmd-0.3.0}/MANIFEST.in +0 -0
- {sphinx_cmd-0.2.1 → sphinx_cmd-0.3.0}/setup.cfg +0 -0
- {sphinx_cmd-0.2.1 → sphinx_cmd-0.3.0}/sphinx_cmd/cli.py +0 -0
- {sphinx_cmd-0.2.1 → sphinx_cmd-0.3.0}/sphinx_cmd/commands/__init__.py +0 -0
- {sphinx_cmd-0.2.1 → sphinx_cmd-0.3.0}/sphinx_cmd/commands/mv.py +0 -0
- {sphinx_cmd-0.2.1 → sphinx_cmd-0.3.0}/sphinx_cmd/py.typed +0 -0
- {sphinx_cmd-0.2.1 → sphinx_cmd-0.3.0}/sphinx_cmd.egg-info/dependency_links.txt +0 -0
- {sphinx_cmd-0.2.1 → sphinx_cmd-0.3.0}/sphinx_cmd.egg-info/entry_points.txt +0 -0
- {sphinx_cmd-0.2.1 → sphinx_cmd-0.3.0}/sphinx_cmd.egg-info/top_level.txt +0 -0
- {sphinx_cmd-0.2.1 → sphinx_cmd-0.3.0}/tests/test_cli.py +0 -0
- {sphinx_cmd-0.2.1 → sphinx_cmd-0.3.0}/tests/test_integration.py +0 -0
- {sphinx_cmd-0.2.1 → sphinx_cmd-0.3.0}/tests/test_mv.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: sphinx-cmd
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0
|
|
4
4
|
Summary: Command-line tools for Sphinx documentation management
|
|
5
5
|
Author-email: Jared Dillard <jared.dillard@gmail.com>
|
|
6
6
|
Project-URL: Homepage, https://github.com/jdillard/sphinx-cmd
|
|
@@ -16,6 +16,7 @@ Classifier: Programming Language :: Python :: 3.12
|
|
|
16
16
|
Requires-Python: >=3.9
|
|
17
17
|
Description-Content-Type: text/markdown
|
|
18
18
|
License-File: LICENSE
|
|
19
|
+
Requires-Dist: tomli>=2.0.0; python_version < "3.11"
|
|
19
20
|
Provides-Extra: dev
|
|
20
21
|
Requires-Dist: pytest>=7.0.0; extra == "dev"
|
|
21
22
|
Requires-Dist: black; extra == "dev"
|
|
@@ -42,7 +43,7 @@ The `sphinx-cmd` tool provides subcommands for different Sphinx documentation ma
|
|
|
42
43
|
|
|
43
44
|
### `sphinx-cmd rm`
|
|
44
45
|
|
|
45
|
-
Delete unused .rst files and their unique assets if not used elsewhere.
|
|
46
|
+
Delete unused .rst files and their unique assets (images, includes, etc) if not used elsewhere.
|
|
46
47
|
|
|
47
48
|
```bash
|
|
48
49
|
# Remove files and assets
|
|
@@ -52,6 +53,10 @@ sphinx-cmd rm path/to/docs
|
|
|
52
53
|
sphinx-cmd rm path/to/docs --dry-run
|
|
53
54
|
```
|
|
54
55
|
|
|
56
|
+
### Features
|
|
57
|
+
|
|
58
|
+
- Configure custom directives to be processed
|
|
59
|
+
|
|
55
60
|
### `sphinx-cmd mv`
|
|
56
61
|
|
|
57
62
|
Move/rename .rst files and automatically update all references to them.
|
|
@@ -78,6 +83,22 @@ sphinx-cmd mv old-file.rst new-file.rst --no-update-refs
|
|
|
78
83
|
- Handles relative paths correctly
|
|
79
84
|
- Preserves file relationships
|
|
80
85
|
|
|
86
|
+
## Configuration
|
|
87
|
+
|
|
88
|
+
You can add custom directives to be processed by creating a `.sphinx-cmd.toml` file in your home directory.
|
|
89
|
+
|
|
90
|
+
Add your custom directives to `[directives]` with their respective regex patterns, for example:
|
|
91
|
+
|
|
92
|
+
```toml
|
|
93
|
+
[directives]
|
|
94
|
+
drawio-figure = "^\\s*\\.\\.\\s+drawio-figure::\\s+(.+)$"
|
|
95
|
+
drawio-image = "^\\s*\\.\\.\\s+drawio-image::\\s+(.+)$"
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
> [!NOTE]
|
|
99
|
+
> Each regex pattern must include a capturing group `(.+)` to extract the file path.
|
|
100
|
+
|
|
101
|
+
|
|
81
102
|
## Development
|
|
82
103
|
|
|
83
104
|
```bash
|
|
@@ -14,7 +14,7 @@ The `sphinx-cmd` tool provides subcommands for different Sphinx documentation ma
|
|
|
14
14
|
|
|
15
15
|
### `sphinx-cmd rm`
|
|
16
16
|
|
|
17
|
-
Delete unused .rst files and their unique assets if not used elsewhere.
|
|
17
|
+
Delete unused .rst files and their unique assets (images, includes, etc) if not used elsewhere.
|
|
18
18
|
|
|
19
19
|
```bash
|
|
20
20
|
# Remove files and assets
|
|
@@ -24,6 +24,10 @@ sphinx-cmd rm path/to/docs
|
|
|
24
24
|
sphinx-cmd rm path/to/docs --dry-run
|
|
25
25
|
```
|
|
26
26
|
|
|
27
|
+
### Features
|
|
28
|
+
|
|
29
|
+
- Configure custom directives to be processed
|
|
30
|
+
|
|
27
31
|
### `sphinx-cmd mv`
|
|
28
32
|
|
|
29
33
|
Move/rename .rst files and automatically update all references to them.
|
|
@@ -50,6 +54,22 @@ sphinx-cmd mv old-file.rst new-file.rst --no-update-refs
|
|
|
50
54
|
- Handles relative paths correctly
|
|
51
55
|
- Preserves file relationships
|
|
52
56
|
|
|
57
|
+
## Configuration
|
|
58
|
+
|
|
59
|
+
You can add custom directives to be processed by creating a `.sphinx-cmd.toml` file in your home directory.
|
|
60
|
+
|
|
61
|
+
Add your custom directives to `[directives]` with their respective regex patterns, for example:
|
|
62
|
+
|
|
63
|
+
```toml
|
|
64
|
+
[directives]
|
|
65
|
+
drawio-figure = "^\\s*\\.\\.\\s+drawio-figure::\\s+(.+)$"
|
|
66
|
+
drawio-image = "^\\s*\\.\\.\\s+drawio-image::\\s+(.+)$"
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
> [!NOTE]
|
|
70
|
+
> Each regex pattern must include a capturing group `(.+)` to extract the file path.
|
|
71
|
+
|
|
72
|
+
|
|
53
73
|
## Development
|
|
54
74
|
|
|
55
75
|
```bash
|
|
@@ -20,7 +20,7 @@ classifiers = [
|
|
|
20
20
|
"Programming Language :: Python :: 3.11",
|
|
21
21
|
"Programming Language :: Python :: 3.12",
|
|
22
22
|
]
|
|
23
|
-
dependencies = []
|
|
23
|
+
dependencies = ["tomli>=2.0.0; python_version < '3.11'"]
|
|
24
24
|
|
|
25
25
|
[project.urls]
|
|
26
26
|
"Homepage" = "https://github.com/jdillard/sphinx-cmd"
|
|
@@ -77,6 +77,10 @@ profile = "black"
|
|
|
77
77
|
[tool.mypy]
|
|
78
78
|
python_version = "3.9"
|
|
79
79
|
|
|
80
|
+
[[tool.mypy.overrides]]
|
|
81
|
+
module = "tomli"
|
|
82
|
+
ignore_missing_imports = true
|
|
83
|
+
|
|
80
84
|
[tool.pytest.ini_options]
|
|
81
85
|
testpaths = ["tests"]
|
|
82
86
|
python_files = ["test_*.py"]
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
Command to delete unused .rst files and their unique assets.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import os
|
|
7
|
+
from collections import defaultdict
|
|
8
|
+
|
|
9
|
+
from sphinx_cmd.config import get_directive_patterns
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def find_rst_files(path):
|
|
13
|
+
"""Find all .rst files in the given path."""
|
|
14
|
+
if os.path.isfile(path) and path.endswith(".rst"):
|
|
15
|
+
return [path]
|
|
16
|
+
rst_files = []
|
|
17
|
+
for root, _, files in os.walk(path):
|
|
18
|
+
for file in files:
|
|
19
|
+
if file.endswith(".rst"):
|
|
20
|
+
rst_files.append(os.path.join(root, file))
|
|
21
|
+
return rst_files
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def extract_assets(file_path, visited=None):
|
|
25
|
+
"""Extract asset references from an .rst file, recursively parsing includes."""
|
|
26
|
+
if visited is None:
|
|
27
|
+
visited = set()
|
|
28
|
+
|
|
29
|
+
# Avoid circular includes
|
|
30
|
+
abs_path = os.path.abspath(file_path)
|
|
31
|
+
if abs_path in visited:
|
|
32
|
+
return {}
|
|
33
|
+
visited.add(abs_path)
|
|
34
|
+
|
|
35
|
+
asset_directives = {}
|
|
36
|
+
directive_patterns = get_directive_patterns()
|
|
37
|
+
|
|
38
|
+
# If file doesn't exist, skip it
|
|
39
|
+
if not os.path.exists(file_path):
|
|
40
|
+
return asset_directives
|
|
41
|
+
|
|
42
|
+
try:
|
|
43
|
+
with open(file_path, encoding="utf-8") as f:
|
|
44
|
+
content = f.read()
|
|
45
|
+
for directive, pattern in directive_patterns.items():
|
|
46
|
+
for match in pattern.findall(content):
|
|
47
|
+
asset_path = match.strip()
|
|
48
|
+
asset_full_path = os.path.normpath(
|
|
49
|
+
os.path.join(os.path.dirname(file_path), asset_path)
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
if directive == "include":
|
|
53
|
+
# Recursively extract assets from included files
|
|
54
|
+
included_assets = extract_assets(
|
|
55
|
+
asset_full_path, visited.copy()
|
|
56
|
+
)
|
|
57
|
+
asset_directives.update(included_assets)
|
|
58
|
+
|
|
59
|
+
asset_directives[asset_full_path] = directive
|
|
60
|
+
except Exception as e:
|
|
61
|
+
print(f"Warning: Could not read {file_path}: {e}")
|
|
62
|
+
|
|
63
|
+
return asset_directives
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def build_asset_index(rst_files):
|
|
67
|
+
"""Build an index of assets and which files reference them."""
|
|
68
|
+
asset_to_files = defaultdict(set)
|
|
69
|
+
file_to_assets = {}
|
|
70
|
+
asset_directive_map = {}
|
|
71
|
+
|
|
72
|
+
for rst in rst_files:
|
|
73
|
+
asset_directives = extract_assets(rst)
|
|
74
|
+
file_to_assets[rst] = set(asset_directives.keys())
|
|
75
|
+
for asset, directive in asset_directives.items():
|
|
76
|
+
asset_to_files[asset].add(rst)
|
|
77
|
+
asset_directive_map[asset] = directive
|
|
78
|
+
return asset_to_files, file_to_assets, asset_directive_map
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def get_transitive_includes(file_path, visited=None):
|
|
82
|
+
"""Get all files included transitively from a file."""
|
|
83
|
+
if visited is None:
|
|
84
|
+
visited = set()
|
|
85
|
+
|
|
86
|
+
# Avoid circular includes
|
|
87
|
+
abs_path = os.path.abspath(file_path)
|
|
88
|
+
if abs_path in visited:
|
|
89
|
+
return set()
|
|
90
|
+
visited.add(abs_path)
|
|
91
|
+
|
|
92
|
+
includes = set()
|
|
93
|
+
|
|
94
|
+
if not os.path.exists(file_path):
|
|
95
|
+
return includes
|
|
96
|
+
|
|
97
|
+
directive_patterns = get_directive_patterns()
|
|
98
|
+
|
|
99
|
+
try:
|
|
100
|
+
with open(file_path, encoding="utf-8") as f:
|
|
101
|
+
content = f.read()
|
|
102
|
+
# Only process include directive
|
|
103
|
+
if "include" in directive_patterns:
|
|
104
|
+
pattern = directive_patterns["include"]
|
|
105
|
+
for match in pattern.findall(content):
|
|
106
|
+
include_path = match.strip()
|
|
107
|
+
include_full_path = os.path.normpath(
|
|
108
|
+
os.path.join(os.path.dirname(file_path), include_path)
|
|
109
|
+
)
|
|
110
|
+
includes.add(include_full_path)
|
|
111
|
+
# Recursively get includes from the included file
|
|
112
|
+
includes.update(
|
|
113
|
+
get_transitive_includes(include_full_path, visited.copy())
|
|
114
|
+
)
|
|
115
|
+
except Exception as e:
|
|
116
|
+
print(f"Warning: Could not read {file_path}: {e}")
|
|
117
|
+
|
|
118
|
+
return includes
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def delete_unused_assets_and_pages(
|
|
122
|
+
asset_to_files, file_to_assets, asset_directive_map, dry_run=False
|
|
123
|
+
):
|
|
124
|
+
"""Delete files and their unique assets if not used elsewhere."""
|
|
125
|
+
deleted_pages = []
|
|
126
|
+
deleted_assets = []
|
|
127
|
+
affected_dirs = set()
|
|
128
|
+
|
|
129
|
+
# Track which files have been processed to avoid duplicates
|
|
130
|
+
processed_files = set()
|
|
131
|
+
|
|
132
|
+
for rst_file, assets in file_to_assets.items():
|
|
133
|
+
# Skip if already processed (can happen with transitive includes)
|
|
134
|
+
if rst_file in processed_files:
|
|
135
|
+
continue
|
|
136
|
+
|
|
137
|
+
unused_assets = [a for a in assets if len(asset_to_files[a]) == 1]
|
|
138
|
+
if len(unused_assets) == len(assets): # All assets are unique to this file
|
|
139
|
+
# Get all files transitively included by this file
|
|
140
|
+
included_files = get_transitive_includes(rst_file)
|
|
141
|
+
|
|
142
|
+
# Process the main file and all its includes
|
|
143
|
+
for file_to_process in [rst_file] + list(included_files):
|
|
144
|
+
if (
|
|
145
|
+
file_to_process in processed_files
|
|
146
|
+
or file_to_process not in file_to_assets
|
|
147
|
+
):
|
|
148
|
+
continue
|
|
149
|
+
|
|
150
|
+
processed_files.add(file_to_process)
|
|
151
|
+
file_assets = file_to_assets.get(file_to_process, set())
|
|
152
|
+
file_unused_assets = [
|
|
153
|
+
a for a in file_assets if len(asset_to_files[a]) == 1
|
|
154
|
+
]
|
|
155
|
+
|
|
156
|
+
# Delete unused assets for this file
|
|
157
|
+
for asset in file_unused_assets:
|
|
158
|
+
directive = asset_directive_map.get(asset, "asset")
|
|
159
|
+
if os.path.exists(asset) and asset not in deleted_assets:
|
|
160
|
+
if dry_run:
|
|
161
|
+
origin = (
|
|
162
|
+
" (from include)" if file_to_process != rst_file else ""
|
|
163
|
+
)
|
|
164
|
+
print(
|
|
165
|
+
f"[dry-run] Would delete {directive}: {asset}{origin}"
|
|
166
|
+
)
|
|
167
|
+
else:
|
|
168
|
+
affected_dirs.add(os.path.dirname(asset))
|
|
169
|
+
os.remove(asset)
|
|
170
|
+
deleted_assets.append(asset)
|
|
171
|
+
|
|
172
|
+
# Delete the file if it exists and isn't the main rst file being checked
|
|
173
|
+
if file_to_process != rst_file and os.path.exists(file_to_process):
|
|
174
|
+
if dry_run:
|
|
175
|
+
print(
|
|
176
|
+
f"[dry-run] Would delete included file: {file_to_process}"
|
|
177
|
+
)
|
|
178
|
+
else:
|
|
179
|
+
affected_dirs.add(os.path.dirname(file_to_process))
|
|
180
|
+
os.remove(file_to_process)
|
|
181
|
+
deleted_pages.append(file_to_process)
|
|
182
|
+
|
|
183
|
+
# Finally, delete the main rst file
|
|
184
|
+
if os.path.exists(rst_file):
|
|
185
|
+
if dry_run:
|
|
186
|
+
print(f"[dry-run] Would delete page: {rst_file}")
|
|
187
|
+
else:
|
|
188
|
+
affected_dirs.add(os.path.dirname(rst_file))
|
|
189
|
+
os.remove(rst_file)
|
|
190
|
+
deleted_pages.append(rst_file)
|
|
191
|
+
|
|
192
|
+
return deleted_pages, deleted_assets, affected_dirs
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def remove_empty_dirs(dirs, original_path, dry_run=False):
|
|
196
|
+
"""Remove empty directories, bottom-up."""
|
|
197
|
+
deleted_dirs = []
|
|
198
|
+
|
|
199
|
+
# Add parent directories to the affected dirs set
|
|
200
|
+
all_dirs = set(dirs)
|
|
201
|
+
for dir_path in dirs:
|
|
202
|
+
# Add all parent directories up to but not including the original path
|
|
203
|
+
parent = os.path.dirname(dir_path)
|
|
204
|
+
while parent and os.path.exists(parent) and parent != original_path:
|
|
205
|
+
all_dirs.add(parent)
|
|
206
|
+
parent = os.path.dirname(parent)
|
|
207
|
+
|
|
208
|
+
# Sort by path depth (deepest first)
|
|
209
|
+
sorted_dirs = sorted(all_dirs, key=lambda d: d.count(os.sep), reverse=True)
|
|
210
|
+
|
|
211
|
+
# Process directories from deepest to shallowest
|
|
212
|
+
for dir_path in sorted_dirs:
|
|
213
|
+
if not os.path.exists(dir_path) or not os.path.isdir(dir_path):
|
|
214
|
+
continue
|
|
215
|
+
|
|
216
|
+
# Check if directory is empty
|
|
217
|
+
if not os.listdir(dir_path):
|
|
218
|
+
if dry_run:
|
|
219
|
+
print(f"[dry-run] Would delete empty directory: {dir_path}")
|
|
220
|
+
else:
|
|
221
|
+
os.rmdir(dir_path)
|
|
222
|
+
deleted_dirs.append(dir_path)
|
|
223
|
+
|
|
224
|
+
# Check if the original path (if it's a directory) is now empty and should
|
|
225
|
+
# be removed
|
|
226
|
+
if os.path.isdir(original_path) and not os.listdir(original_path):
|
|
227
|
+
if dry_run:
|
|
228
|
+
print(f"[dry-run] Would delete empty directory: {original_path}")
|
|
229
|
+
else:
|
|
230
|
+
os.rmdir(original_path)
|
|
231
|
+
deleted_dirs.append(original_path)
|
|
232
|
+
|
|
233
|
+
return deleted_dirs
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def execute(args):
|
|
237
|
+
"""Execute the rm command."""
|
|
238
|
+
original_path = os.path.abspath(args.path)
|
|
239
|
+
rst_files = find_rst_files(args.path)
|
|
240
|
+
asset_to_files, file_to_assets, asset_directive_map = build_asset_index(rst_files)
|
|
241
|
+
deleted_pages, deleted_assets, affected_dirs = delete_unused_assets_and_pages(
|
|
242
|
+
asset_to_files, file_to_assets, asset_directive_map, args.dry_run
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
deleted_dirs = []
|
|
246
|
+
if affected_dirs:
|
|
247
|
+
deleted_dirs = remove_empty_dirs(affected_dirs, original_path, args.dry_run)
|
|
248
|
+
|
|
249
|
+
if not args.dry_run:
|
|
250
|
+
print(f"\nDeleted {len(deleted_assets)} unused asset(s):")
|
|
251
|
+
for a in deleted_assets:
|
|
252
|
+
directive = asset_directive_map.get(a, "asset")
|
|
253
|
+
print(f" - ({directive}) {a}")
|
|
254
|
+
|
|
255
|
+
print(f"\nDeleted {len(deleted_pages)} RST page(s):")
|
|
256
|
+
for p in deleted_pages:
|
|
257
|
+
print(f" - {p}")
|
|
258
|
+
|
|
259
|
+
if deleted_dirs:
|
|
260
|
+
print(f"\nDeleted {len(deleted_dirs)} empty directory/directories:")
|
|
261
|
+
for d in deleted_dirs:
|
|
262
|
+
print(f" - {d}")
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
Configuration handling for sphinx-cmd.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import re
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Dict, Optional
|
|
10
|
+
|
|
11
|
+
# Use the standard library tomllib if Python 3.11+, otherwise use tomli package
|
|
12
|
+
if sys.version_info >= (3, 11):
|
|
13
|
+
import tomllib
|
|
14
|
+
else:
|
|
15
|
+
import tomli as tomllib
|
|
16
|
+
|
|
17
|
+
# Default configuration with built-in directives
|
|
18
|
+
DEFAULT_CONFIG = {
|
|
19
|
+
"directives": {
|
|
20
|
+
"image": r"^\s*\.\.\s+image::\s+(.+)$",
|
|
21
|
+
"figure": r"^\s*\.\.\s+figure::\s+(.+)$",
|
|
22
|
+
"include": r"^\s*\.\.\s+include::\s+(.+)$",
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def get_config_path() -> Optional[Path]:
|
|
28
|
+
"""Get the path to the configuration file."""
|
|
29
|
+
# Check for config in user's home directory
|
|
30
|
+
home_config = Path.home() / ".sphinx-cmd.toml"
|
|
31
|
+
if home_config.exists():
|
|
32
|
+
return home_config
|
|
33
|
+
|
|
34
|
+
return None
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def load_config() -> Dict:
|
|
38
|
+
"""
|
|
39
|
+
Load configuration from a TOML file.
|
|
40
|
+
|
|
41
|
+
The function looks for a config file at:
|
|
42
|
+
- user's home directory
|
|
43
|
+
|
|
44
|
+
Returns:
|
|
45
|
+
Dict: The merged configuration (defaults + user config)
|
|
46
|
+
"""
|
|
47
|
+
config = DEFAULT_CONFIG.copy()
|
|
48
|
+
|
|
49
|
+
config_path = get_config_path()
|
|
50
|
+
if not config_path:
|
|
51
|
+
return config
|
|
52
|
+
|
|
53
|
+
try:
|
|
54
|
+
with open(config_path, "rb") as f:
|
|
55
|
+
user_config = tomllib.load(f)
|
|
56
|
+
|
|
57
|
+
# Merge user directives with default directives
|
|
58
|
+
if "directives" in user_config:
|
|
59
|
+
for name, pattern in user_config["directives"].items():
|
|
60
|
+
config["directives"][name] = pattern
|
|
61
|
+
|
|
62
|
+
except Exception as e:
|
|
63
|
+
print(f"Warning: Error loading config from {config_path}: {e}")
|
|
64
|
+
|
|
65
|
+
return config
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def get_directive_patterns() -> Dict[str, re.Pattern]:
|
|
69
|
+
"""
|
|
70
|
+
Get compiled regex patterns for all directives.
|
|
71
|
+
|
|
72
|
+
Returns:
|
|
73
|
+
Dict[str, re.Pattern]: Dictionary of directive names to compiled regex patterns
|
|
74
|
+
"""
|
|
75
|
+
config = load_config()
|
|
76
|
+
patterns = {}
|
|
77
|
+
|
|
78
|
+
for name, pattern in config["directives"].items():
|
|
79
|
+
patterns[name] = re.compile(pattern, re.MULTILINE)
|
|
80
|
+
|
|
81
|
+
return patterns
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: sphinx-cmd
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0
|
|
4
4
|
Summary: Command-line tools for Sphinx documentation management
|
|
5
5
|
Author-email: Jared Dillard <jared.dillard@gmail.com>
|
|
6
6
|
Project-URL: Homepage, https://github.com/jdillard/sphinx-cmd
|
|
@@ -16,6 +16,7 @@ Classifier: Programming Language :: Python :: 3.12
|
|
|
16
16
|
Requires-Python: >=3.9
|
|
17
17
|
Description-Content-Type: text/markdown
|
|
18
18
|
License-File: LICENSE
|
|
19
|
+
Requires-Dist: tomli>=2.0.0; python_version < "3.11"
|
|
19
20
|
Provides-Extra: dev
|
|
20
21
|
Requires-Dist: pytest>=7.0.0; extra == "dev"
|
|
21
22
|
Requires-Dist: black; extra == "dev"
|
|
@@ -42,7 +43,7 @@ The `sphinx-cmd` tool provides subcommands for different Sphinx documentation ma
|
|
|
42
43
|
|
|
43
44
|
### `sphinx-cmd rm`
|
|
44
45
|
|
|
45
|
-
Delete unused .rst files and their unique assets if not used elsewhere.
|
|
46
|
+
Delete unused .rst files and their unique assets (images, includes, etc) if not used elsewhere.
|
|
46
47
|
|
|
47
48
|
```bash
|
|
48
49
|
# Remove files and assets
|
|
@@ -52,6 +53,10 @@ sphinx-cmd rm path/to/docs
|
|
|
52
53
|
sphinx-cmd rm path/to/docs --dry-run
|
|
53
54
|
```
|
|
54
55
|
|
|
56
|
+
### Features
|
|
57
|
+
|
|
58
|
+
- Configure custom directives to be processed
|
|
59
|
+
|
|
55
60
|
### `sphinx-cmd mv`
|
|
56
61
|
|
|
57
62
|
Move/rename .rst files and automatically update all references to them.
|
|
@@ -78,6 +83,22 @@ sphinx-cmd mv old-file.rst new-file.rst --no-update-refs
|
|
|
78
83
|
- Handles relative paths correctly
|
|
79
84
|
- Preserves file relationships
|
|
80
85
|
|
|
86
|
+
## Configuration
|
|
87
|
+
|
|
88
|
+
You can add custom directives to be processed by creating a `.sphinx-cmd.toml` file in your home directory.
|
|
89
|
+
|
|
90
|
+
Add your custom directives to `[directives]` with their respective regex patterns, for example:
|
|
91
|
+
|
|
92
|
+
```toml
|
|
93
|
+
[directives]
|
|
94
|
+
drawio-figure = "^\\s*\\.\\.\\s+drawio-figure::\\s+(.+)$"
|
|
95
|
+
drawio-image = "^\\s*\\.\\.\\s+drawio-image::\\s+(.+)$"
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
> [!NOTE]
|
|
99
|
+
> Each regex pattern must include a capturing group `(.+)` to extract the file path.
|
|
100
|
+
|
|
101
|
+
|
|
81
102
|
## Development
|
|
82
103
|
|
|
83
104
|
```bash
|
|
@@ -4,6 +4,7 @@ README.md
|
|
|
4
4
|
pyproject.toml
|
|
5
5
|
sphinx_cmd/__init__.py
|
|
6
6
|
sphinx_cmd/cli.py
|
|
7
|
+
sphinx_cmd/config.py
|
|
7
8
|
sphinx_cmd/py.typed
|
|
8
9
|
sphinx_cmd.egg-info/PKG-INFO
|
|
9
10
|
sphinx_cmd.egg-info/SOURCES.txt
|
|
@@ -15,6 +16,8 @@ sphinx_cmd/commands/__init__.py
|
|
|
15
16
|
sphinx_cmd/commands/mv.py
|
|
16
17
|
sphinx_cmd/commands/rm.py
|
|
17
18
|
tests/test_cli.py
|
|
19
|
+
tests/test_config.py
|
|
20
|
+
tests/test_custom_directives.py
|
|
18
21
|
tests/test_integration.py
|
|
19
22
|
tests/test_mv.py
|
|
20
23
|
tests/test_rm.py
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import tempfile
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from unittest.mock import patch
|
|
4
|
+
|
|
5
|
+
from sphinx_cmd.config import get_directive_patterns, load_config
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def test_default_config():
|
|
9
|
+
"""Test that default config is returned when no config file exists."""
|
|
10
|
+
with patch("sphinx_cmd.config.get_config_path", return_value=None):
|
|
11
|
+
config = load_config()
|
|
12
|
+
|
|
13
|
+
# Check that default directives are present
|
|
14
|
+
assert "directives" in config
|
|
15
|
+
assert "image" in config["directives"]
|
|
16
|
+
assert "figure" in config["directives"]
|
|
17
|
+
assert "include" in config["directives"]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def test_load_custom_config():
|
|
21
|
+
"""Test loading a custom configuration file."""
|
|
22
|
+
with tempfile.TemporaryDirectory() as tmpdir:
|
|
23
|
+
config_path = Path(tmpdir) / ".sphinx-cmd.toml"
|
|
24
|
+
|
|
25
|
+
# Create a custom config file with proper TOML syntax
|
|
26
|
+
toml_content = """
|
|
27
|
+
[directives]
|
|
28
|
+
image = "^\\\\s*\\\\.\\\\.\\\\s+image::\\\\s+(.+)$"
|
|
29
|
+
figure = "^\\\\s*\\\\.\\\\.\\\\s+figure::\\\\s+(.+)$"
|
|
30
|
+
include = "^\\\\s*\\\\.\\\\.\\\\s+include::\\\\s+(.+)$"
|
|
31
|
+
drawio-figure = "^\\\\s*\\\\.\\\\.\\\\s+drawio-figure::\\\\s+(.+)$"
|
|
32
|
+
drawio-image = "^\\\\s*\\\\.\\\\.\\\\s+drawio-image::\\\\s+(.+)$"
|
|
33
|
+
"""
|
|
34
|
+
with open(config_path, "wb") as f:
|
|
35
|
+
f.write(toml_content.encode())
|
|
36
|
+
|
|
37
|
+
with patch("sphinx_cmd.config.get_config_path", return_value=config_path):
|
|
38
|
+
config = load_config()
|
|
39
|
+
|
|
40
|
+
# Check that custom directives are present
|
|
41
|
+
assert "directives" in config
|
|
42
|
+
assert "drawio-figure" in config["directives"]
|
|
43
|
+
assert "drawio-image" in config["directives"]
|
|
44
|
+
|
|
45
|
+
# Check original directives are still there
|
|
46
|
+
assert "image" in config["directives"]
|
|
47
|
+
assert "figure" in config["directives"]
|
|
48
|
+
assert "include" in config["directives"]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def test_get_directive_patterns():
|
|
52
|
+
"""Test that directive patterns are compiled correctly."""
|
|
53
|
+
with tempfile.TemporaryDirectory() as tmpdir:
|
|
54
|
+
config_path = Path(tmpdir) / ".sphinx-cmd.toml"
|
|
55
|
+
|
|
56
|
+
# Create a custom config file with drawio directives with proper TOML syntax
|
|
57
|
+
toml_content = """
|
|
58
|
+
[directives]
|
|
59
|
+
drawio-figure = "^\\\\s*\\\\.\\\\.\\\\s+drawio-figure::\\\\s+(.+)$"
|
|
60
|
+
"""
|
|
61
|
+
with open(config_path, "wb") as f:
|
|
62
|
+
f.write(toml_content.encode())
|
|
63
|
+
|
|
64
|
+
with patch("sphinx_cmd.config.get_config_path", return_value=config_path):
|
|
65
|
+
patterns = get_directive_patterns()
|
|
66
|
+
|
|
67
|
+
# Default patterns should be included
|
|
68
|
+
assert "image" in patterns
|
|
69
|
+
assert "figure" in patterns
|
|
70
|
+
assert "include" in patterns
|
|
71
|
+
|
|
72
|
+
# Custom pattern should be included and be a compiled regex
|
|
73
|
+
assert "drawio-figure" in patterns
|
|
74
|
+
|
|
75
|
+
# Test the pattern works
|
|
76
|
+
test_string = ".. drawio-figure:: path/to/diagram.drawio"
|
|
77
|
+
match = patterns["drawio-figure"].findall(test_string)
|
|
78
|
+
assert len(match) == 1
|
|
79
|
+
assert match[0] == "path/to/diagram.drawio"
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import tempfile
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from unittest.mock import Mock, patch
|
|
5
|
+
|
|
6
|
+
from sphinx_cmd.commands.rm import execute, extract_assets
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def test_custom_directive_extraction():
|
|
10
|
+
"""Test that custom directives are extracted from RST files."""
|
|
11
|
+
with tempfile.TemporaryDirectory() as tmpdir:
|
|
12
|
+
# Create a test config with custom directives
|
|
13
|
+
config_path = Path(tmpdir) / ".sphinx-cmd.toml"
|
|
14
|
+
|
|
15
|
+
# Create config with proper TOML syntax
|
|
16
|
+
toml_content = """
|
|
17
|
+
[directives]
|
|
18
|
+
drawio-figure = "^\\\\s*\\\\.\\\\.\\\\s+drawio-figure::\\\\s+(.+)$"
|
|
19
|
+
drawio-image = "^\\\\s*\\\\.\\\\.\\\\s+drawio-image::\\\\s+(.+)$"
|
|
20
|
+
"""
|
|
21
|
+
with open(config_path, "wb") as f:
|
|
22
|
+
f.write(toml_content.encode())
|
|
23
|
+
|
|
24
|
+
# Create a test file with custom directives
|
|
25
|
+
test_file = os.path.join(tmpdir, "test.rst")
|
|
26
|
+
with open(test_file, "w") as f:
|
|
27
|
+
f.write(
|
|
28
|
+
"""
|
|
29
|
+
Test Document
|
|
30
|
+
============
|
|
31
|
+
|
|
32
|
+
.. image:: standard-image.png
|
|
33
|
+
.. drawio-figure:: custom-figure.drawio
|
|
34
|
+
.. drawio-image:: custom-image.drawio
|
|
35
|
+
"""
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
# Mock the config path function to use our temp config
|
|
39
|
+
with patch("sphinx_cmd.config.get_config_path", return_value=config_path):
|
|
40
|
+
# Extract assets
|
|
41
|
+
assets = extract_assets(test_file)
|
|
42
|
+
|
|
43
|
+
# Check we have the right number of assets (3)
|
|
44
|
+
assert len(assets) == 3
|
|
45
|
+
|
|
46
|
+
# Check all asset paths are correct
|
|
47
|
+
img_path = os.path.join(tmpdir, "standard-image.png")
|
|
48
|
+
custom_figure_path = os.path.join(tmpdir, "custom-figure.drawio")
|
|
49
|
+
custom_image_path = os.path.join(tmpdir, "custom-image.drawio")
|
|
50
|
+
|
|
51
|
+
assert img_path in assets
|
|
52
|
+
assert custom_figure_path in assets
|
|
53
|
+
assert custom_image_path in assets
|
|
54
|
+
|
|
55
|
+
# Check the directive types are correct
|
|
56
|
+
assert assets[img_path] == "image"
|
|
57
|
+
assert assets[custom_figure_path] == "drawio-figure"
|
|
58
|
+
assert assets[custom_image_path] == "drawio-image"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def test_rm_command_with_custom_directives():
|
|
62
|
+
"""Test the rm command with custom directives (using dry-run)."""
|
|
63
|
+
with tempfile.TemporaryDirectory() as tmpdir:
|
|
64
|
+
# Create a test config with custom directives
|
|
65
|
+
config_path = Path(tmpdir) / ".sphinx-cmd.toml"
|
|
66
|
+
|
|
67
|
+
# Create config with proper TOML syntax
|
|
68
|
+
toml_content = """
|
|
69
|
+
[directives]
|
|
70
|
+
drawio-figure = "^\\\\s*\\\\.\\\\.\\\\s+drawio-figure::\\\\s+(.+)$"
|
|
71
|
+
"""
|
|
72
|
+
with open(config_path, "wb") as f:
|
|
73
|
+
f.write(toml_content.encode())
|
|
74
|
+
|
|
75
|
+
# Create test directory
|
|
76
|
+
test_dir = os.path.join(tmpdir, "docs")
|
|
77
|
+
os.makedirs(test_dir)
|
|
78
|
+
|
|
79
|
+
# Create an RST file with custom directives
|
|
80
|
+
rst_content = """
|
|
81
|
+
Test Page
|
|
82
|
+
=========
|
|
83
|
+
|
|
84
|
+
.. drawio-figure:: custom.drawio
|
|
85
|
+
"""
|
|
86
|
+
with open(os.path.join(test_dir, "test.rst"), "w") as f:
|
|
87
|
+
f.write(rst_content)
|
|
88
|
+
|
|
89
|
+
# Create the asset files
|
|
90
|
+
with open(os.path.join(test_dir, "custom.drawio"), "w") as f:
|
|
91
|
+
f.write("fake drawio")
|
|
92
|
+
|
|
93
|
+
# Execute the rm command with mocked config
|
|
94
|
+
with patch("sphinx_cmd.config.get_config_path", return_value=config_path):
|
|
95
|
+
# Setup to capture stdout
|
|
96
|
+
import sys
|
|
97
|
+
from io import StringIO
|
|
98
|
+
|
|
99
|
+
captured_output = StringIO()
|
|
100
|
+
original_stdout = sys.stdout
|
|
101
|
+
sys.stdout = captured_output
|
|
102
|
+
|
|
103
|
+
try:
|
|
104
|
+
args = Mock()
|
|
105
|
+
args.path = test_dir
|
|
106
|
+
args.dry_run = True
|
|
107
|
+
|
|
108
|
+
# Run with dry-run to test detection
|
|
109
|
+
execute(args)
|
|
110
|
+
|
|
111
|
+
# Get the captured output
|
|
112
|
+
output = captured_output.getvalue()
|
|
113
|
+
|
|
114
|
+
# Verify the correct files would be deleted
|
|
115
|
+
assert "[dry-run] Would delete drawio-figure:" in output
|
|
116
|
+
assert "custom.drawio" in output
|
|
117
|
+
assert "[dry-run] Would delete page:" in output
|
|
118
|
+
assert "test.rst" in output
|
|
119
|
+
finally:
|
|
120
|
+
sys.stdout = original_stdout
|
|
121
|
+
|
|
122
|
+
# Files should still exist after dry run
|
|
123
|
+
assert os.path.exists(os.path.join(test_dir, "test.rst"))
|
|
124
|
+
assert os.path.exists(os.path.join(test_dir, "custom.drawio"))
|
|
125
|
+
assert os.path.exists(test_dir)
|
|
@@ -7,10 +7,38 @@ from sphinx_cmd.commands.rm import (
|
|
|
7
7
|
execute,
|
|
8
8
|
extract_assets,
|
|
9
9
|
find_rst_files,
|
|
10
|
+
get_transitive_includes,
|
|
10
11
|
remove_empty_dirs,
|
|
11
12
|
)
|
|
12
13
|
|
|
13
14
|
|
|
15
|
+
def test_nested_includes_extraction():
|
|
16
|
+
"""Test that nested includes are properly extracted."""
|
|
17
|
+
with tempfile.TemporaryDirectory() as tmpdir:
|
|
18
|
+
# Create a more complex nested include structure
|
|
19
|
+
main_file = os.path.join(tmpdir, "main.rst")
|
|
20
|
+
include1 = os.path.join(tmpdir, "include1.rst")
|
|
21
|
+
include2 = os.path.join(tmpdir, "include2.rst")
|
|
22
|
+
|
|
23
|
+
# Create the files with content
|
|
24
|
+
with open(include2, "w") as f:
|
|
25
|
+
f.write("Level 2 include\n")
|
|
26
|
+
|
|
27
|
+
with open(include1, "w") as f:
|
|
28
|
+
f.write("Level 1 include\n.. include:: include2.rst\n")
|
|
29
|
+
|
|
30
|
+
with open(main_file, "w") as f:
|
|
31
|
+
f.write("Main file\n.. include:: include1.rst\n")
|
|
32
|
+
|
|
33
|
+
# Test the transitive includes function
|
|
34
|
+
includes = get_transitive_includes(main_file)
|
|
35
|
+
|
|
36
|
+
# Should have found both include files
|
|
37
|
+
assert len(includes) == 2
|
|
38
|
+
assert include1 in includes
|
|
39
|
+
assert include2 in includes
|
|
40
|
+
|
|
41
|
+
|
|
14
42
|
def test_rm_command_functionality():
|
|
15
43
|
"""Test the rm command functionality."""
|
|
16
44
|
# Create a temporary directory structure
|
|
@@ -152,6 +180,87 @@ def test_non_empty_directory_retained():
|
|
|
152
180
|
assert os.path.exists(other_file)
|
|
153
181
|
|
|
154
182
|
|
|
183
|
+
def test_extract_assets_basic():
|
|
184
|
+
"""Test that extract_assets finds assets in a simple file."""
|
|
185
|
+
with tempfile.TemporaryDirectory() as tmpdir:
|
|
186
|
+
# Create a test file with multiple directives
|
|
187
|
+
test_file = os.path.join(tmpdir, "test.rst")
|
|
188
|
+
|
|
189
|
+
with open(test_file, "w") as f:
|
|
190
|
+
f.write(
|
|
191
|
+
"""
|
|
192
|
+
Test Document
|
|
193
|
+
============
|
|
194
|
+
|
|
195
|
+
.. image:: img.png
|
|
196
|
+
.. figure:: fig.jpg
|
|
197
|
+
.. include:: inc.rst
|
|
198
|
+
"""
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
# Extract assets
|
|
202
|
+
assets = extract_assets(test_file)
|
|
203
|
+
|
|
204
|
+
# Check we have the right number of assets
|
|
205
|
+
assert len(assets) == 3
|
|
206
|
+
|
|
207
|
+
# Check all asset paths are correct
|
|
208
|
+
img_path = os.path.join(tmpdir, "img.png")
|
|
209
|
+
fig_path = os.path.join(tmpdir, "fig.jpg")
|
|
210
|
+
inc_path = os.path.join(tmpdir, "inc.rst")
|
|
211
|
+
|
|
212
|
+
assert img_path in assets
|
|
213
|
+
assert fig_path in assets
|
|
214
|
+
assert inc_path in assets
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def test_get_transitive_includes():
|
|
218
|
+
"""Test that get_transitive_includes correctly finds all included files."""
|
|
219
|
+
with tempfile.TemporaryDirectory() as tmpdir:
|
|
220
|
+
# Create a multi-level include structure
|
|
221
|
+
main_file = os.path.join(tmpdir, "main.rst")
|
|
222
|
+
first_include = os.path.join(tmpdir, "first.rst")
|
|
223
|
+
second_include = os.path.join(tmpdir, "second.rst")
|
|
224
|
+
|
|
225
|
+
# Create the files
|
|
226
|
+
with open(second_include, "w") as f:
|
|
227
|
+
f.write("Content in second include\n")
|
|
228
|
+
|
|
229
|
+
with open(first_include, "w") as f:
|
|
230
|
+
f.write(".. include:: second.rst\n")
|
|
231
|
+
|
|
232
|
+
with open(main_file, "w") as f:
|
|
233
|
+
f.write(".. include:: first.rst\n")
|
|
234
|
+
|
|
235
|
+
# Get all transitive includes from main file
|
|
236
|
+
includes = get_transitive_includes(main_file)
|
|
237
|
+
|
|
238
|
+
# Should find both included files
|
|
239
|
+
assert len(includes) == 2
|
|
240
|
+
assert first_include in includes
|
|
241
|
+
assert second_include in includes
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def test_circular_includes_detection():
|
|
245
|
+
"""Test that circular includes are detected and don't cause infinite recursion."""
|
|
246
|
+
with tempfile.TemporaryDirectory() as tmpdir:
|
|
247
|
+
# Create two files that include each other
|
|
248
|
+
file1 = os.path.join(tmpdir, "file1.rst")
|
|
249
|
+
file2 = os.path.join(tmpdir, "file2.rst")
|
|
250
|
+
|
|
251
|
+
with open(file1, "w") as f:
|
|
252
|
+
f.write("File 1\n\n.. include:: file2.rst\n")
|
|
253
|
+
|
|
254
|
+
with open(file2, "w") as f:
|
|
255
|
+
f.write("File 2\n\n.. include:: file1.rst\n")
|
|
256
|
+
|
|
257
|
+
# Should find both includes but avoid infinite recursion
|
|
258
|
+
includes = get_transitive_includes(file1)
|
|
259
|
+
assert len(includes) == 2 # Changed from 1 to 2
|
|
260
|
+
assert file2 in includes
|
|
261
|
+
assert file1 in includes # file1 is included by file2
|
|
262
|
+
|
|
263
|
+
|
|
155
264
|
def test_remove_empty_dirs_function():
|
|
156
265
|
"""Test the remove_empty_dirs function directly."""
|
|
157
266
|
with tempfile.TemporaryDirectory() as tmpdir:
|
|
@@ -1,158 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env python3
|
|
2
|
-
"""
|
|
3
|
-
Command to delete unused .rst files and their unique assets.
|
|
4
|
-
"""
|
|
5
|
-
|
|
6
|
-
import os
|
|
7
|
-
import re
|
|
8
|
-
from collections import defaultdict
|
|
9
|
-
|
|
10
|
-
# Regex patterns for reStructuredText directives
|
|
11
|
-
DIRECTIVE_PATTERNS = {
|
|
12
|
-
"image": re.compile(r"^\s*\.\.\s+image::\s+(.+)$", re.MULTILINE),
|
|
13
|
-
"figure": re.compile(r"^\s*\.\.\s+figure::\s+(.+)$", re.MULTILINE),
|
|
14
|
-
"include": re.compile(r"^\s*\.\.\s+include::\s+(.+)$", re.MULTILINE),
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
def find_rst_files(path):
|
|
19
|
-
"""Find all .rst files in the given path."""
|
|
20
|
-
if os.path.isfile(path) and path.endswith(".rst"):
|
|
21
|
-
return [path]
|
|
22
|
-
rst_files = []
|
|
23
|
-
for root, _, files in os.walk(path):
|
|
24
|
-
for file in files:
|
|
25
|
-
if file.endswith(".rst"):
|
|
26
|
-
rst_files.append(os.path.join(root, file))
|
|
27
|
-
return rst_files
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
def extract_assets(file_path):
|
|
31
|
-
"""Extract asset references from an .rst file."""
|
|
32
|
-
asset_directives = {}
|
|
33
|
-
with open(file_path, encoding="utf-8") as f:
|
|
34
|
-
content = f.read()
|
|
35
|
-
for directive, pattern in DIRECTIVE_PATTERNS.items():
|
|
36
|
-
for match in pattern.findall(content):
|
|
37
|
-
asset_path = match.strip()
|
|
38
|
-
asset_full_path = os.path.normpath(
|
|
39
|
-
os.path.join(os.path.dirname(file_path), asset_path)
|
|
40
|
-
)
|
|
41
|
-
asset_directives[asset_full_path] = directive
|
|
42
|
-
return asset_directives
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
def build_asset_index(rst_files):
|
|
46
|
-
"""Build an index of assets and which files reference them."""
|
|
47
|
-
asset_to_files = defaultdict(set)
|
|
48
|
-
file_to_assets = {}
|
|
49
|
-
asset_directive_map = {}
|
|
50
|
-
|
|
51
|
-
for rst in rst_files:
|
|
52
|
-
asset_directives = extract_assets(rst)
|
|
53
|
-
file_to_assets[rst] = set(asset_directives.keys())
|
|
54
|
-
for asset, directive in asset_directives.items():
|
|
55
|
-
asset_to_files[asset].add(rst)
|
|
56
|
-
asset_directive_map[asset] = directive
|
|
57
|
-
return asset_to_files, file_to_assets, asset_directive_map
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
def delete_unused_assets_and_pages(
|
|
61
|
-
asset_to_files, file_to_assets, asset_directive_map, dry_run=False
|
|
62
|
-
):
|
|
63
|
-
"""Delete files and their unique assets if not used elsewhere."""
|
|
64
|
-
deleted_pages = []
|
|
65
|
-
deleted_assets = []
|
|
66
|
-
affected_dirs = set()
|
|
67
|
-
|
|
68
|
-
for rst_file, assets in file_to_assets.items():
|
|
69
|
-
unused_assets = [a for a in assets if len(asset_to_files[a]) == 1]
|
|
70
|
-
if len(unused_assets) == len(assets): # All assets are unique to this file
|
|
71
|
-
for asset in unused_assets:
|
|
72
|
-
directive = asset_directive_map.get(asset, "asset")
|
|
73
|
-
if os.path.exists(asset):
|
|
74
|
-
if dry_run:
|
|
75
|
-
print(f"[dry-run] Would delete {directive}: {asset}")
|
|
76
|
-
else:
|
|
77
|
-
affected_dirs.add(os.path.dirname(asset))
|
|
78
|
-
os.remove(asset)
|
|
79
|
-
deleted_assets.append(asset)
|
|
80
|
-
if os.path.exists(rst_file):
|
|
81
|
-
if dry_run:
|
|
82
|
-
print(f"[dry-run] Would delete page: {rst_file}")
|
|
83
|
-
else:
|
|
84
|
-
affected_dirs.add(os.path.dirname(rst_file))
|
|
85
|
-
os.remove(rst_file)
|
|
86
|
-
deleted_pages.append(rst_file)
|
|
87
|
-
|
|
88
|
-
return deleted_pages, deleted_assets, affected_dirs
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
def remove_empty_dirs(dirs, original_path, dry_run=False):
|
|
92
|
-
"""Remove empty directories, bottom-up."""
|
|
93
|
-
deleted_dirs = []
|
|
94
|
-
|
|
95
|
-
# Add parent directories to the affected dirs set
|
|
96
|
-
all_dirs = set(dirs)
|
|
97
|
-
for dir_path in dirs:
|
|
98
|
-
# Add all parent directories up to but not including the original path
|
|
99
|
-
parent = os.path.dirname(dir_path)
|
|
100
|
-
while parent and os.path.exists(parent) and parent != original_path:
|
|
101
|
-
all_dirs.add(parent)
|
|
102
|
-
parent = os.path.dirname(parent)
|
|
103
|
-
|
|
104
|
-
# Sort by path depth (deepest first)
|
|
105
|
-
sorted_dirs = sorted(all_dirs, key=lambda d: d.count(os.sep), reverse=True)
|
|
106
|
-
|
|
107
|
-
# Process directories from deepest to shallowest
|
|
108
|
-
for dir_path in sorted_dirs:
|
|
109
|
-
if not os.path.exists(dir_path) or not os.path.isdir(dir_path):
|
|
110
|
-
continue
|
|
111
|
-
|
|
112
|
-
# Check if directory is empty
|
|
113
|
-
if not os.listdir(dir_path):
|
|
114
|
-
if dry_run:
|
|
115
|
-
print(f"[dry-run] Would delete empty directory: {dir_path}")
|
|
116
|
-
else:
|
|
117
|
-
os.rmdir(dir_path)
|
|
118
|
-
deleted_dirs.append(dir_path)
|
|
119
|
-
|
|
120
|
-
# Check if the original path (if it's a directory) is now empty and should
|
|
121
|
-
# be removed
|
|
122
|
-
if os.path.isdir(original_path) and not os.listdir(original_path):
|
|
123
|
-
if dry_run:
|
|
124
|
-
print(f"[dry-run] Would delete empty directory: {original_path}")
|
|
125
|
-
else:
|
|
126
|
-
os.rmdir(original_path)
|
|
127
|
-
deleted_dirs.append(original_path)
|
|
128
|
-
|
|
129
|
-
return deleted_dirs
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
def execute(args):
|
|
133
|
-
"""Execute the rm command."""
|
|
134
|
-
original_path = os.path.abspath(args.path)
|
|
135
|
-
rst_files = find_rst_files(args.path)
|
|
136
|
-
asset_to_files, file_to_assets, asset_directive_map = build_asset_index(rst_files)
|
|
137
|
-
deleted_pages, deleted_assets, affected_dirs = delete_unused_assets_and_pages(
|
|
138
|
-
asset_to_files, file_to_assets, asset_directive_map, args.dry_run
|
|
139
|
-
)
|
|
140
|
-
|
|
141
|
-
deleted_dirs = []
|
|
142
|
-
if affected_dirs:
|
|
143
|
-
deleted_dirs = remove_empty_dirs(affected_dirs, original_path, args.dry_run)
|
|
144
|
-
|
|
145
|
-
if not args.dry_run:
|
|
146
|
-
print(f"\nDeleted {len(deleted_assets)} unused asset(s):")
|
|
147
|
-
for a in deleted_assets:
|
|
148
|
-
directive = asset_directive_map.get(a, "asset")
|
|
149
|
-
print(f" - ({directive}) {a}")
|
|
150
|
-
|
|
151
|
-
print(f"\nDeleted {len(deleted_pages)} RST page(s):")
|
|
152
|
-
for p in deleted_pages:
|
|
153
|
-
print(f" - {p}")
|
|
154
|
-
|
|
155
|
-
if deleted_dirs:
|
|
156
|
-
print(f"\nDeleted {len(deleted_dirs)} empty directory/directories:")
|
|
157
|
-
for d in deleted_dirs:
|
|
158
|
-
print(f" - {d}")
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|