sphinx-cmd 0.4.3__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.3/sphinx_cmd.egg-info → sphinx_cmd-0.5.0}/PKG-INFO +1 -1
  2. {sphinx_cmd-0.4.3 → sphinx_cmd-0.5.0}/sphinx_cmd/__init__.py +1 -1
  3. {sphinx_cmd-0.4.3 → sphinx_cmd-0.5.0}/sphinx_cmd/commands/rm.py +274 -0
  4. {sphinx_cmd-0.4.3 → sphinx_cmd-0.5.0/sphinx_cmd.egg-info}/PKG-INFO +1 -1
  5. {sphinx_cmd-0.4.3 → sphinx_cmd-0.5.0}/LICENSE +0 -0
  6. {sphinx_cmd-0.4.3 → sphinx_cmd-0.5.0}/MANIFEST.in +0 -0
  7. {sphinx_cmd-0.4.3 → sphinx_cmd-0.5.0}/README.md +0 -0
  8. {sphinx_cmd-0.4.3 → sphinx_cmd-0.5.0}/pyproject.toml +0 -0
  9. {sphinx_cmd-0.4.3 → sphinx_cmd-0.5.0}/setup.cfg +0 -0
  10. {sphinx_cmd-0.4.3 → sphinx_cmd-0.5.0}/sphinx_cmd/cli.py +0 -0
  11. {sphinx_cmd-0.4.3 → sphinx_cmd-0.5.0}/sphinx_cmd/commands/__init__.py +0 -0
  12. {sphinx_cmd-0.4.3 → sphinx_cmd-0.5.0}/sphinx_cmd/commands/mv.py +0 -0
  13. {sphinx_cmd-0.4.3 → sphinx_cmd-0.5.0}/sphinx_cmd/config.py +0 -0
  14. {sphinx_cmd-0.4.3 → sphinx_cmd-0.5.0}/sphinx_cmd/py.typed +0 -0
  15. {sphinx_cmd-0.4.3 → sphinx_cmd-0.5.0}/sphinx_cmd.egg-info/SOURCES.txt +0 -0
  16. {sphinx_cmd-0.4.3 → sphinx_cmd-0.5.0}/sphinx_cmd.egg-info/dependency_links.txt +0 -0
  17. {sphinx_cmd-0.4.3 → sphinx_cmd-0.5.0}/sphinx_cmd.egg-info/entry_points.txt +0 -0
  18. {sphinx_cmd-0.4.3 → sphinx_cmd-0.5.0}/sphinx_cmd.egg-info/requires.txt +0 -0
  19. {sphinx_cmd-0.4.3 → sphinx_cmd-0.5.0}/sphinx_cmd.egg-info/top_level.txt +0 -0
  20. {sphinx_cmd-0.4.3 → sphinx_cmd-0.5.0}/tests/test_cli.py +0 -0
  21. {sphinx_cmd-0.4.3 → sphinx_cmd-0.5.0}/tests/test_config.py +0 -0
  22. {sphinx_cmd-0.4.3 → sphinx_cmd-0.5.0}/tests/test_custom_directives.py +0 -0
  23. {sphinx_cmd-0.4.3 → sphinx_cmd-0.5.0}/tests/test_integration.py +0 -0
  24. {sphinx_cmd-0.4.3 → sphinx_cmd-0.5.0}/tests/test_mv.py +0 -0
  25. {sphinx_cmd-0.4.3 → 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.3
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.3"
4
+ __version__ = "0.5.0"
@@ -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
 
@@ -193,6 +195,209 @@ def get_transitive_includes(
193
195
  return includes
194
196
 
195
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
+
196
401
  def delete_unused_assets_and_pages(
197
402
  asset_to_files,
198
403
  file_to_assets,
@@ -458,6 +663,64 @@ def execute(args):
458
663
  )
459
664
  )
460
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
+
461
724
  deleted_dirs = []
462
725
  if affected_dirs:
463
726
  deleted_dirs = remove_empty_dirs(affected_dirs, original_path, dry_run, verbose)
@@ -466,6 +729,12 @@ def execute(args):
466
729
  # In dry-run mode, show a summary of what would be deleted
467
730
  if not would_delete_something:
468
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}")
469
738
  else:
470
739
  # Not in dry-run mode, report what was actually deleted
471
740
  print(f"\nDeleted {len(deleted_assets)} unused asset(s):")
@@ -482,5 +751,10 @@ def execute(args):
482
751
  for d in deleted_dirs:
483
752
  print(f" - {d}")
484
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
+
485
759
  if verbose:
486
760
  print("Operation completed successfully")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sphinx-cmd
3
- Version: 0.4.3
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