sphinx-cmd 0.4.2__tar.gz → 0.5.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.
Files changed (25) hide show
  1. {sphinx_cmd-0.4.2/sphinx_cmd.egg-info → sphinx_cmd-0.5.0}/PKG-INFO +1 -1
  2. {sphinx_cmd-0.4.2 → sphinx_cmd-0.5.0}/sphinx_cmd/__init__.py +1 -1
  3. {sphinx_cmd-0.4.2 → sphinx_cmd-0.5.0}/sphinx_cmd/commands/mv.py +4 -2
  4. {sphinx_cmd-0.4.2 → sphinx_cmd-0.5.0}/sphinx_cmd/commands/rm.py +312 -9
  5. {sphinx_cmd-0.4.2 → sphinx_cmd-0.5.0/sphinx_cmd.egg-info}/PKG-INFO +1 -1
  6. {sphinx_cmd-0.4.2 → sphinx_cmd-0.5.0}/LICENSE +0 -0
  7. {sphinx_cmd-0.4.2 → sphinx_cmd-0.5.0}/MANIFEST.in +0 -0
  8. {sphinx_cmd-0.4.2 → sphinx_cmd-0.5.0}/README.md +0 -0
  9. {sphinx_cmd-0.4.2 → sphinx_cmd-0.5.0}/pyproject.toml +0 -0
  10. {sphinx_cmd-0.4.2 → sphinx_cmd-0.5.0}/setup.cfg +0 -0
  11. {sphinx_cmd-0.4.2 → sphinx_cmd-0.5.0}/sphinx_cmd/cli.py +0 -0
  12. {sphinx_cmd-0.4.2 → sphinx_cmd-0.5.0}/sphinx_cmd/commands/__init__.py +0 -0
  13. {sphinx_cmd-0.4.2 → sphinx_cmd-0.5.0}/sphinx_cmd/config.py +0 -0
  14. {sphinx_cmd-0.4.2 → sphinx_cmd-0.5.0}/sphinx_cmd/py.typed +0 -0
  15. {sphinx_cmd-0.4.2 → sphinx_cmd-0.5.0}/sphinx_cmd.egg-info/SOURCES.txt +0 -0
  16. {sphinx_cmd-0.4.2 → sphinx_cmd-0.5.0}/sphinx_cmd.egg-info/dependency_links.txt +0 -0
  17. {sphinx_cmd-0.4.2 → sphinx_cmd-0.5.0}/sphinx_cmd.egg-info/entry_points.txt +0 -0
  18. {sphinx_cmd-0.4.2 → sphinx_cmd-0.5.0}/sphinx_cmd.egg-info/requires.txt +0 -0
  19. {sphinx_cmd-0.4.2 → sphinx_cmd-0.5.0}/sphinx_cmd.egg-info/top_level.txt +0 -0
  20. {sphinx_cmd-0.4.2 → sphinx_cmd-0.5.0}/tests/test_cli.py +0 -0
  21. {sphinx_cmd-0.4.2 → sphinx_cmd-0.5.0}/tests/test_config.py +0 -0
  22. {sphinx_cmd-0.4.2 → sphinx_cmd-0.5.0}/tests/test_custom_directives.py +0 -0
  23. {sphinx_cmd-0.4.2 → sphinx_cmd-0.5.0}/tests/test_integration.py +0 -0
  24. {sphinx_cmd-0.4.2 → sphinx_cmd-0.5.0}/tests/test_mv.py +0 -0
  25. {sphinx_cmd-0.4.2 → sphinx_cmd-0.5.0}/tests/test_rm.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sphinx-cmd
3
- Version: 0.4.2
3
+ Version: 0.5.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
@@ -1,4 +1,4 @@
1
1
  # This file makes sphinx_cmd a Python package
2
2
  """Sphinx command-line utilities."""
3
3
 
4
- __version__ = "0.4.2"
4
+ __version__ = "0.5.0"
@@ -86,7 +86,8 @@ def extract_references(
86
86
 
87
87
  if verbose:
88
88
  print(f"Found {ref_type} reference: {ref_path}")
89
- # For references that could be image files or other assets, show absolute path
89
+ # For references that could be image files or other assets,
90
+ # show absolute path
90
91
  if ref_type in ["image", "figure", "include"]:
91
92
  ref_full_path = Path(file_path).parent / ref_path
92
93
  ref_abs_path = ref_full_path.resolve()
@@ -139,7 +140,8 @@ def find_files_referencing(
139
140
  referencing_files.append((file_path, ref_type))
140
141
  if verbose:
141
142
  print(f"Found reference in {file_path} ({ref_type}): {ref}")
142
- # For references that could be image files or other assets, show absolute path
143
+ # For references that could be image files or other assets,
144
+ # show absolute path
143
145
  if ref_type in ["image", "figure", "include"]:
144
146
  ref_full_path = Path(file_path).parent / ref
145
147
  ref_abs_path = ref_full_path.resolve()
@@ -4,7 +4,9 @@ Command to delete unused .rst files and their unique assets.
4
4
  """
5
5
 
6
6
  import os
7
+ import re
7
8
  from collections import defaultdict
9
+ from pathlib import Path
8
10
 
9
11
  from sphinx_cmd.config import get_directive_patterns
10
12
 
@@ -22,12 +24,21 @@ def find_rst_files(path):
22
24
 
23
25
 
24
26
  def extract_assets(
25
- file_path, visited=None, cli_directives=None, context_path=None, verbose=False
27
+ file_path,
28
+ visited=None,
29
+ cli_directives=None,
30
+ context_path=None,
31
+ verbose=False,
32
+ base_dir=None,
26
33
  ):
27
34
  """Extract asset references from an .rst file, recursively parsing includes."""
28
35
  if visited is None:
29
36
  visited = set()
30
37
 
38
+ # Use the directory of the original file as base for relative path resolution
39
+ if base_dir is None:
40
+ base_dir = os.path.dirname(file_path)
41
+
31
42
  # Avoid circular includes
32
43
  abs_path = os.path.abspath(file_path)
33
44
  if abs_path in visited:
@@ -52,9 +63,16 @@ def extract_assets(
52
63
  for directive, pattern in directive_patterns.items():
53
64
  for match in pattern.findall(content):
54
65
  asset_path = match.strip()
55
- asset_full_path = os.path.normpath(
56
- os.path.join(os.path.dirname(file_path), asset_path)
57
- )
66
+ if directive == "include":
67
+ # Include paths are resolved relative to the current file
68
+ asset_full_path = os.path.normpath(
69
+ os.path.join(os.path.dirname(file_path), asset_path)
70
+ )
71
+ else:
72
+ # Non-include assets are resolved relative to the base directory
73
+ asset_full_path = os.path.normpath(
74
+ os.path.join(base_dir, asset_path)
75
+ )
58
76
  asset_abs_path = os.path.abspath(asset_full_path)
59
77
 
60
78
  if verbose:
@@ -64,13 +82,15 @@ def extract_assets(
64
82
  if directive == "include":
65
83
  if verbose:
66
84
  print(f"Parsing include: {asset_full_path}")
67
- # Recursively extract assets from included files
85
+ # Recursively extract assets from included files,
86
+ # preserving base_dir
68
87
  included_assets = extract_assets(
69
88
  asset_full_path,
70
- visited.copy(),
89
+ visited,
71
90
  cli_directives,
72
91
  context_path,
73
92
  verbose,
93
+ base_dir,
74
94
  )
75
95
  asset_directives.update(included_assets)
76
96
 
@@ -109,12 +129,21 @@ def build_asset_index(rst_files, cli_directives=None, context_path=None, verbose
109
129
 
110
130
 
111
131
  def get_transitive_includes(
112
- file_path, visited=None, cli_directives=None, context_path=None, verbose=False
132
+ file_path,
133
+ visited=None,
134
+ cli_directives=None,
135
+ context_path=None,
136
+ verbose=False,
137
+ base_dir=None,
113
138
  ):
114
139
  """Get all files included transitively from a file."""
115
140
  if visited is None:
116
141
  visited = set()
117
142
 
143
+ # Use the directory of the original file as base for relative path resolution
144
+ if base_dir is None:
145
+ base_dir = os.path.dirname(file_path)
146
+
118
147
  # Avoid circular includes
119
148
  abs_path = os.path.abspath(file_path)
120
149
  if abs_path in visited:
@@ -148,14 +177,16 @@ def get_transitive_includes(
148
177
  if verbose:
149
178
  print(f"Found include: {include_path}")
150
179
 
151
- # Recursively get includes from the included file
180
+ # Recursively get includes from the included file,
181
+ # preserving base_dir
152
182
  includes.update(
153
183
  get_transitive_includes(
154
184
  include_full_path,
155
- visited.copy(),
185
+ visited,
156
186
  cli_directives,
157
187
  context_path,
158
188
  verbose,
189
+ base_dir,
159
190
  )
160
191
  )
161
192
  except Exception as e:
@@ -164,6 +195,209 @@ def get_transitive_includes(
164
195
  return includes
165
196
 
166
197
 
198
+ # Toctree pattern similar to mv.py
199
+ TOCTREE_PATTERN = re.compile(
200
+ r"^\s*\.\.\s+toctree::(.*?)(?=^\S|\Z)", re.DOTALL | re.MULTILINE
201
+ )
202
+
203
+
204
+ def find_toctree_references(rst_files, removed_files, verbose=False):
205
+ """Find which files contain toctree references to files being removed."""
206
+ toctree_references = {}
207
+
208
+ if verbose:
209
+ print(
210
+ f"Checking for toctree references to removed files "
211
+ f"in {len(rst_files)} files..."
212
+ )
213
+
214
+ # Convert removed files to Path objects for proper comparison
215
+ removed_paths = {Path(f).resolve() for f in removed_files}
216
+ removed_stems = {Path(f).stem for f in removed_files}
217
+
218
+ for rst_file in rst_files:
219
+ if rst_file in removed_files:
220
+ continue # Skip files that are being removed
221
+
222
+ if not os.path.exists(rst_file):
223
+ continue
224
+
225
+ try:
226
+ with open(rst_file, "r", encoding="utf-8") as f:
227
+ content = f.read()
228
+
229
+ # Find toctree entries
230
+ toctree_matches = TOCTREE_PATTERN.findall(content)
231
+ for toctree_content in toctree_matches:
232
+ # Extract file references from toctree
233
+ lines = toctree_content.split("\n")
234
+ matching_entries = []
235
+ rst_file_path = Path(rst_file)
236
+
237
+ for line in lines:
238
+ line = line.strip()
239
+ if line and not line.startswith(":"): # Skip options
240
+ ref_file = line.split()[0] if line.split() else ""
241
+ if ref_file:
242
+ ref_path = Path(ref_file)
243
+
244
+ # Check for matches using multiple strategies
245
+ is_match = False
246
+
247
+ # Strategy 1: Try to resolve the reference relative
248
+ # to the toctree file
249
+ try:
250
+ resolved_ref = (
251
+ (rst_file_path.parent / ref_path)
252
+ .with_suffix(".rst")
253
+ .resolve()
254
+ )
255
+ if resolved_ref in removed_paths:
256
+ is_match = True
257
+ except Exception:
258
+ pass
259
+
260
+ # Strategy 2: Check if reference with .rst extension
261
+ # matches any removed file
262
+ if not is_match:
263
+ ref_with_rst = ref_path.with_suffix(".rst").resolve()
264
+ if ref_with_rst in removed_paths:
265
+ is_match = True
266
+
267
+ # Strategy 3: Check direct path match
268
+ # (for absolute or root-relative paths)
269
+ if not is_match:
270
+ try:
271
+ # If the reference starts with '/', treat it as
272
+ # relative to the directory containing the toctree
273
+ if str(ref_path).startswith("/"):
274
+ # Remove leading slash and resolve relative
275
+ # to the directory containing the toctree file
276
+ rel_ref_path = Path(str(ref_path)[1:])
277
+ resolved_ref = (
278
+ (rst_file_path.parent / rel_ref_path)
279
+ .with_suffix(".rst")
280
+ .resolve()
281
+ )
282
+ if resolved_ref in removed_paths:
283
+ is_match = True
284
+ # Also check without adding .rst extension
285
+ # in case it's already there
286
+ resolved_ref_no_ext = (
287
+ rst_file_path.parent / rel_ref_path
288
+ ).resolve()
289
+ if resolved_ref_no_ext in removed_paths:
290
+ is_match = True
291
+ else:
292
+ # Regular path resolution for non-absolute paths
293
+ if (
294
+ ref_path.resolve() in removed_paths
295
+ or Path(str(ref_path) + ".rst").resolve()
296
+ in removed_paths
297
+ ):
298
+ is_match = True
299
+ except Exception:
300
+ pass
301
+
302
+ # Strategy 4: Only fall back to stem matching if the
303
+ # previous strategies failed to resolve paths
304
+ # This should only happen when files don't exist
305
+ # or paths are broken
306
+ if not is_match and ref_path.stem in removed_stems:
307
+ # Only use stem matching if we couldn't resolve the path
308
+ # in previous strategies. Check if the reference file
309
+ # actually exists at the resolved location
310
+ try:
311
+ expected_location = (
312
+ rst_file_path.parent / ref_path
313
+ ).with_suffix(".rst")
314
+ if not expected_location.exists():
315
+ # File doesn't exist where it should, so stem
316
+ # matching might be appropriate
317
+ for removed_path in removed_paths:
318
+ if (
319
+ ref_path.stem == removed_path.stem
320
+ and len(ref_path.parts)
321
+ == 1 # Only simple filename references
322
+ and str(ref_path) == removed_path.stem
323
+ ): # Exact stem match only
324
+ is_match = True
325
+ break
326
+ except Exception:
327
+ # If we can't even check if the file exists,
328
+ # skip stem matching entirely
329
+ pass
330
+
331
+ if is_match:
332
+ matching_entries.append(ref_file)
333
+ if verbose:
334
+ print(
335
+ f"Found toctree reference to "
336
+ f"'{ref_file}' in {rst_file}"
337
+ )
338
+
339
+ if matching_entries:
340
+ if rst_file not in toctree_references:
341
+ toctree_references[rst_file] = []
342
+ toctree_references[rst_file].extend(matching_entries)
343
+
344
+ except Exception as e:
345
+ print(f"Warning: Could not read {rst_file}: {e}")
346
+
347
+ return toctree_references
348
+
349
+
350
+ def remove_toctree_entries(file_path, entries_to_remove, dry_run=False, verbose=False):
351
+ """Remove specific entries from toctree directives in a file."""
352
+ if not os.path.exists(file_path):
353
+ return False
354
+
355
+ try:
356
+ with open(file_path, "r", encoding="utf-8") as f:
357
+ content = f.read()
358
+
359
+ original_content = content
360
+
361
+ # Process each toctree directive
362
+ def replace_toctree(match):
363
+ toctree_content = match.group(1)
364
+ lines = toctree_content.split("\n")
365
+ new_lines = []
366
+
367
+ for line in lines:
368
+ stripped = line.strip()
369
+ if stripped and not stripped.startswith(":"): # Skip options
370
+ ref_file = stripped.split()[0] if stripped.split() else ""
371
+ if ref_file not in entries_to_remove:
372
+ new_lines.append(line)
373
+ elif verbose:
374
+ print(f" Removing toctree entry: {ref_file}")
375
+ else:
376
+ new_lines.append(line)
377
+
378
+ return ".. toctree::" + "\n".join(new_lines)
379
+
380
+ new_content = TOCTREE_PATTERN.sub(replace_toctree, content)
381
+
382
+ if new_content != original_content:
383
+ if dry_run:
384
+ print(f"[dry-run] Would update toctree entries in: {file_path}")
385
+ else:
386
+ with open(file_path, "w", encoding="utf-8") as f:
387
+ f.write(new_content)
388
+ if verbose:
389
+ print(f"Updated toctree entries in: {file_path}")
390
+ return True
391
+ else:
392
+ if verbose:
393
+ print(f"No toctree changes needed in: {file_path}")
394
+ return False
395
+
396
+ except Exception as e:
397
+ print(f"Error updating toctree entries in {file_path}: {e}")
398
+ return False
399
+
400
+
167
401
  def delete_unused_assets_and_pages(
168
402
  asset_to_files,
169
403
  file_to_assets,
@@ -429,6 +663,64 @@ def execute(args):
429
663
  )
430
664
  )
431
665
 
666
+ # Handle toctree updates (default behavior)
667
+ toctree_updates = 0
668
+ updated_toctree_files = []
669
+ if deleted_pages or would_delete_something:
670
+ # Get list of files to be deleted (or would be deleted in dry-run)
671
+ files_to_remove = deleted_pages if not dry_run else []
672
+
673
+ # In dry-run mode, we need to determine which files would be deleted
674
+ if dry_run and would_delete_something:
675
+ files_to_remove = []
676
+ for rst_file, assets in file_to_assets.items():
677
+ unused_assets = [a for a in assets if len(asset_to_files[a]) == 1]
678
+ if len(unused_assets) == len(
679
+ assets
680
+ ): # All assets are unique to this file
681
+ # Check context constraints like in delete_unused_assets_and_pages
682
+ is_in_context = True
683
+ if context_path:
684
+ file_abs_path = os.path.abspath(rst_file)
685
+ context_abs_path = os.path.abspath(context_path)
686
+ is_in_context = file_abs_path.startswith(context_abs_path)
687
+ if is_in_context:
688
+ files_to_remove.append(rst_file)
689
+
690
+ if files_to_remove:
691
+ if verbose:
692
+ print(
693
+ f"Checking for toctree references to "
694
+ f"{len(files_to_remove)} removed files..."
695
+ )
696
+
697
+ # Find all RST files that might contain toctrees
698
+ all_rst_files = find_rst_files(context_path if context_path else ".")
699
+
700
+ # Find toctree references to files being removed
701
+ toctree_references = find_toctree_references(
702
+ all_rst_files, files_to_remove, verbose
703
+ )
704
+
705
+ if toctree_references:
706
+ print(
707
+ f"\nFound toctree references in {len(toctree_references)} file(s):"
708
+ )
709
+
710
+ for file_path, entries in toctree_references.items():
711
+ print(f" - {file_path}: {', '.join(entries)}")
712
+
713
+ # Remove the toctree entries
714
+ if remove_toctree_entries(file_path, entries, dry_run, verbose):
715
+ toctree_updates += 1
716
+ updated_toctree_files.append(file_path)
717
+ else:
718
+ if verbose:
719
+ print("No toctree references found to removed files.")
720
+ else:
721
+ if verbose:
722
+ print("No files removed, skipping toctree updates.")
723
+
432
724
  deleted_dirs = []
433
725
  if affected_dirs:
434
726
  deleted_dirs = remove_empty_dirs(affected_dirs, original_path, dry_run, verbose)
@@ -437,6 +729,12 @@ def execute(args):
437
729
  # In dry-run mode, show a summary of what would be deleted
438
730
  if not would_delete_something:
439
731
  print("\n[dry-run] No unused files found, nothing would be deleted.")
732
+ if toctree_updates > 0:
733
+ print(
734
+ f"[dry-run] Would update toctree entries in {toctree_updates} file(s):"
735
+ )
736
+ for file_path in updated_toctree_files:
737
+ print(f" - {file_path}")
440
738
  else:
441
739
  # Not in dry-run mode, report what was actually deleted
442
740
  print(f"\nDeleted {len(deleted_assets)} unused asset(s):")
@@ -453,5 +751,10 @@ def execute(args):
453
751
  for d in deleted_dirs:
454
752
  print(f" - {d}")
455
753
 
754
+ if toctree_updates > 0:
755
+ print(f"\nUpdated toctree entries in {toctree_updates} file(s):")
756
+ for file_path in updated_toctree_files:
757
+ print(f" - {file_path}")
758
+
456
759
  if verbose:
457
760
  print("Operation completed successfully")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sphinx-cmd
3
- Version: 0.4.2
3
+ Version: 0.5.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
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