sphinx-cmd 0.4.3__tar.gz → 0.6.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 (27) hide show
  1. {sphinx_cmd-0.4.3/sphinx_cmd.egg-info → sphinx_cmd-0.6.0}/PKG-INFO +26 -5
  2. {sphinx_cmd-0.4.3 → sphinx_cmd-0.6.0}/README.md +23 -0
  3. {sphinx_cmd-0.4.3 → sphinx_cmd-0.6.0}/pyproject.toml +5 -10
  4. {sphinx_cmd-0.4.3 → sphinx_cmd-0.6.0}/sphinx_cmd/__init__.py +1 -1
  5. {sphinx_cmd-0.4.3 → sphinx_cmd-0.6.0}/sphinx_cmd/cli.py +11 -0
  6. sphinx_cmd-0.6.0/sphinx_cmd/commands/intersphinx.py +197 -0
  7. {sphinx_cmd-0.4.3 → sphinx_cmd-0.6.0}/sphinx_cmd/commands/rm.py +274 -0
  8. {sphinx_cmd-0.4.3 → sphinx_cmd-0.6.0}/sphinx_cmd/config.py +1 -7
  9. {sphinx_cmd-0.4.3 → sphinx_cmd-0.6.0/sphinx_cmd.egg-info}/PKG-INFO +26 -5
  10. {sphinx_cmd-0.4.3 → sphinx_cmd-0.6.0}/sphinx_cmd.egg-info/SOURCES.txt +2 -0
  11. {sphinx_cmd-0.4.3 → sphinx_cmd-0.6.0}/sphinx_cmd.egg-info/requires.txt +0 -3
  12. sphinx_cmd-0.6.0/tests/test_intersphinx.py +243 -0
  13. {sphinx_cmd-0.4.3 → sphinx_cmd-0.6.0}/LICENSE +0 -0
  14. {sphinx_cmd-0.4.3 → sphinx_cmd-0.6.0}/MANIFEST.in +0 -0
  15. {sphinx_cmd-0.4.3 → sphinx_cmd-0.6.0}/setup.cfg +0 -0
  16. {sphinx_cmd-0.4.3 → sphinx_cmd-0.6.0}/sphinx_cmd/commands/__init__.py +0 -0
  17. {sphinx_cmd-0.4.3 → sphinx_cmd-0.6.0}/sphinx_cmd/commands/mv.py +0 -0
  18. {sphinx_cmd-0.4.3 → sphinx_cmd-0.6.0}/sphinx_cmd/py.typed +0 -0
  19. {sphinx_cmd-0.4.3 → sphinx_cmd-0.6.0}/sphinx_cmd.egg-info/dependency_links.txt +0 -0
  20. {sphinx_cmd-0.4.3 → sphinx_cmd-0.6.0}/sphinx_cmd.egg-info/entry_points.txt +0 -0
  21. {sphinx_cmd-0.4.3 → sphinx_cmd-0.6.0}/sphinx_cmd.egg-info/top_level.txt +0 -0
  22. {sphinx_cmd-0.4.3 → sphinx_cmd-0.6.0}/tests/test_cli.py +0 -0
  23. {sphinx_cmd-0.4.3 → sphinx_cmd-0.6.0}/tests/test_config.py +0 -0
  24. {sphinx_cmd-0.4.3 → sphinx_cmd-0.6.0}/tests/test_custom_directives.py +0 -0
  25. {sphinx_cmd-0.4.3 → sphinx_cmd-0.6.0}/tests/test_integration.py +0 -0
  26. {sphinx_cmd-0.4.3 → sphinx_cmd-0.6.0}/tests/test_mv.py +0 -0
  27. {sphinx_cmd-0.4.3 → sphinx_cmd-0.6.0}/tests/test_rm.py +0 -0
@@ -1,22 +1,20 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sphinx-cmd
3
- Version: 0.4.3
3
+ Version: 0.6.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
7
7
  Project-URL: Bug Reports, https://github.com/jdillard/sphinx-cmd/issues
8
8
  Project-URL: Source, https://github.com/jdillard/sphinx-cmd
9
+ Classifier: Framework :: Sphinx
9
10
  Classifier: License :: OSI Approved :: MIT License
10
11
  Classifier: Operating System :: OS Independent
11
12
  Classifier: Programming Language :: Python :: 3
12
- Classifier: Programming Language :: Python :: 3.9
13
- Classifier: Programming Language :: Python :: 3.10
14
13
  Classifier: Programming Language :: Python :: 3.11
15
14
  Classifier: Programming Language :: Python :: 3.12
16
- Requires-Python: >=3.9
15
+ Requires-Python: >=3.11
17
16
  Description-Content-Type: text/markdown
18
17
  License-File: LICENSE
19
- Requires-Dist: tomli>=2.0.0; python_version < "3.11"
20
18
  Provides-Extra: dev
21
19
  Requires-Dist: pytest>=7.0.0; extra == "dev"
22
20
  Requires-Dist: black; extra == "dev"
@@ -109,6 +107,29 @@ sphinx-cmd --dry-run --directives drawio-figure mv old-file.rst new-file.rst
109
107
  - Preserves file relationships
110
108
  - Configure custom directives to be processed
111
109
 
110
+ ### `sphinx-cmd intersphinx`
111
+
112
+ Migrate intersphinx references to the `:external:` role syntax.
113
+
114
+ ```bash
115
+ # Migrate all .rst files in the detected context
116
+ sphinx-cmd intersphinx
117
+
118
+ # Preview changes without writing them
119
+ sphinx-cmd --dry-run intersphinx
120
+
121
+ # Specify the docs directory
122
+ sphinx-cmd --context path/to/docs intersphinx
123
+ ```
124
+
125
+ For example, `` :ref:`python:string-methods` `` becomes `` :external+python:ref:`string-methods` ``, and `` :ref:`Title <python:target>` `` becomes `` :external+python:ref:`Title <target>` ``.
126
+
127
+ #### Features
128
+
129
+ - Handles `:ref:`, `:doc:`, and `:term:` roles, with or without titles
130
+ - Only rewrites references whose prefix is an inventory name in `intersphinx_mapping`, so local labels containing a colon are left alone
131
+ - Reads `intersphinx_mapping` from `conf.py` without executing it; mappings built dynamically are not detected
132
+
112
133
  ## Configuration
113
134
 
114
135
  You can add custom directives to be processed in two ways:
@@ -79,6 +79,29 @@ sphinx-cmd --dry-run --directives drawio-figure mv old-file.rst new-file.rst
79
79
  - Preserves file relationships
80
80
  - Configure custom directives to be processed
81
81
 
82
+ ### `sphinx-cmd intersphinx`
83
+
84
+ Migrate intersphinx references to the `:external:` role syntax.
85
+
86
+ ```bash
87
+ # Migrate all .rst files in the detected context
88
+ sphinx-cmd intersphinx
89
+
90
+ # Preview changes without writing them
91
+ sphinx-cmd --dry-run intersphinx
92
+
93
+ # Specify the docs directory
94
+ sphinx-cmd --context path/to/docs intersphinx
95
+ ```
96
+
97
+ For example, `` :ref:`python:string-methods` `` becomes `` :external+python:ref:`string-methods` ``, and `` :ref:`Title <python:target>` `` becomes `` :external+python:ref:`Title <target>` ``.
98
+
99
+ #### Features
100
+
101
+ - Handles `:ref:`, `:doc:`, and `:term:` roles, with or without titles
102
+ - Only rewrites references whose prefix is an inventory name in `intersphinx_mapping`, so local labels containing a colon are left alone
103
+ - Reads `intersphinx_mapping` from `conf.py` without executing it; mappings built dynamically are not detected
104
+
82
105
  ## Configuration
83
106
 
84
107
  You can add custom directives to be processed in two ways:
@@ -10,17 +10,16 @@ authors = [
10
10
  ]
11
11
  description = "Command-line tools for Sphinx documentation management"
12
12
  readme = "README.md"
13
- requires-python = ">=3.9"
13
+ requires-python = ">=3.11"
14
14
  classifiers = [
15
+ "Framework :: Sphinx",
15
16
  "License :: OSI Approved :: MIT License",
16
17
  "Operating System :: OS Independent",
17
18
  "Programming Language :: Python :: 3",
18
- "Programming Language :: Python :: 3.9",
19
- "Programming Language :: Python :: 3.10",
20
19
  "Programming Language :: Python :: 3.11",
21
20
  "Programming Language :: Python :: 3.12",
22
21
  ]
23
- dependencies = ["tomli>=2.0.0; python_version < '3.11'"]
22
+ dependencies = []
24
23
 
25
24
  [project.urls]
26
25
  "Homepage" = "https://github.com/jdillard/sphinx-cmd"
@@ -54,7 +53,7 @@ version = {attr = "sphinx_cmd.__version__"}
54
53
 
55
54
  [tool.black]
56
55
  line-length = 88
57
- target-version = ['py39', 'py310', 'py311', 'py312']
56
+ target-version = ['py311', 'py312']
58
57
  include = '\.pyi?$'
59
58
  extend-exclude = '''
60
59
  /(
@@ -76,11 +75,7 @@ extend-exclude = '''
76
75
  profile = "black"
77
76
 
78
77
  [tool.mypy]
79
- python_version = "3.9"
80
-
81
- [[tool.mypy.overrides]]
82
- module = "tomli"
83
- ignore_missing_imports = true
78
+ python_version = "3.11"
84
79
 
85
80
  [tool.pytest.ini_options]
86
81
  testpaths = ["tests"]
@@ -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.6.0"
@@ -75,6 +75,13 @@ def create_parser():
75
75
  )
76
76
  mv_parser.set_defaults(command_name="mv")
77
77
 
78
+ # Add 'intersphinx' subcommand
79
+ intersphinx_parser = subparsers.add_parser(
80
+ "intersphinx",
81
+ help="Migrate intersphinx syntax to new external role format",
82
+ )
83
+ intersphinx_parser.set_defaults(command_name="intersphinx")
84
+
78
85
  return parser
79
86
 
80
87
 
@@ -102,6 +109,10 @@ def main():
102
109
  elif args.command_name == "mv":
103
110
  from sphinx_cmd.commands.mv import execute
104
111
 
112
+ execute(args)
113
+ elif args.command_name == "intersphinx":
114
+ from sphinx_cmd.commands.intersphinx import execute
115
+
105
116
  execute(args)
106
117
  else:
107
118
  print(f"Unknown command: {args.command_name}", file=sys.stderr)
@@ -0,0 +1,197 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Command to migrate intersphinx syntax from old format to new external role format.
4
+
5
+ Old syntax: :ref:`invname:target` or :ref:`Title <invname:target>`
6
+ New syntax: :external+invname:ref:`target` or :external+invname:ref:`Title <target>`
7
+ """
8
+
9
+ import ast
10
+ import re
11
+ from pathlib import Path
12
+ from typing import Iterable, List, Optional, Set, Tuple
13
+
14
+ from sphinx_cmd.config import get_sphinx_context
15
+
16
+ # Regex patterns for old intersphinx syntax. The lookbehind ensures only bare
17
+ # roles match, not the tail of a domain-qualified role such as :std:ref: or an
18
+ # already-migrated :external+inv:ref:.
19
+ _ROLE = r"(?<![\w:+-]):(ref|doc|term):"
20
+
21
+ # Pattern for references without titles: :ref:`invname:target`
22
+ PATTERN_NO_TITLE = re.compile(_ROLE + r"`([^<`:]+):([^`:]+)`")
23
+
24
+ # Pattern for references with titles: :ref:`Title <invname:target>`
25
+ PATTERN_WITH_TITLE = re.compile(_ROLE + r"`([^`]+)\s+<([^:`]+):([^>`]+)>`")
26
+
27
+
28
+ def find_rst_files(root_path: str) -> List[str]:
29
+ """Find all .rst files in the given directory tree."""
30
+ rst_files = []
31
+ root = Path(root_path)
32
+
33
+ if root.is_file() and root.suffix == ".rst":
34
+ return [str(root)]
35
+
36
+ for file_path in root.rglob("*.rst"):
37
+ rst_files.append(str(file_path))
38
+
39
+ return rst_files
40
+
41
+
42
+ def get_intersphinx_inventories(conf_path: Path) -> Optional[Set[str]]:
43
+ """
44
+ Statically read the inventory names from ``intersphinx_mapping`` in conf.py.
45
+
46
+ conf.py is parsed with ``ast`` rather than executed, so only literal
47
+ definitions are understood::
48
+
49
+ intersphinx_mapping = {"python": (...), ...}
50
+ intersphinx_mapping["python"] = (...)
51
+ intersphinx_mapping.update({"python": (...)})
52
+
53
+ Returns the set of inventory names, or None if no mapping was found.
54
+ """
55
+ try:
56
+ tree = ast.parse(conf_path.read_text(encoding="utf-8"))
57
+ except (OSError, SyntaxError, UnicodeDecodeError):
58
+ return None
59
+
60
+ names: Set[str] = set()
61
+ found = False
62
+
63
+ def add_dict_keys(node: Optional[ast.AST]) -> None:
64
+ if isinstance(node, ast.Dict):
65
+ for key in node.keys:
66
+ if isinstance(key, ast.Constant) and isinstance(key.value, str):
67
+ names.add(key.value)
68
+
69
+ def is_mapping(node: ast.AST) -> bool:
70
+ return isinstance(node, ast.Name) and node.id == "intersphinx_mapping"
71
+
72
+ for node in ast.walk(tree):
73
+ if isinstance(node, (ast.Assign, ast.AnnAssign)):
74
+ targets = node.targets if isinstance(node, ast.Assign) else [node.target]
75
+ for target in targets:
76
+ if is_mapping(target):
77
+ found = True
78
+ add_dict_keys(node.value)
79
+ elif isinstance(target, ast.Subscript) and is_mapping(target.value):
80
+ found = True
81
+ key = target.slice
82
+ if isinstance(key, ast.Constant) and isinstance(key.value, str):
83
+ names.add(key.value)
84
+ elif (
85
+ isinstance(node, ast.Call)
86
+ and isinstance(node.func, ast.Attribute)
87
+ and node.func.attr == "update"
88
+ and is_mapping(node.func.value)
89
+ ):
90
+ found = True
91
+ for arg in node.args:
92
+ add_dict_keys(arg)
93
+
94
+ return names if found else None
95
+
96
+
97
+ def migrate_content(content: str, inventories: Iterable[str]) -> Tuple[str, int]:
98
+ """
99
+ Migrate intersphinx syntax in content from old to new format.
100
+
101
+ Only references whose prefix is a known inventory name are rewritten, so
102
+ local labels that happen to contain a colon are left alone.
103
+
104
+ Returns tuple of (new_content, count_of_replacements).
105
+ """
106
+ inventories = set(inventories)
107
+ count = 0
108
+
109
+ def replace_with_title(match):
110
+ nonlocal count
111
+ role, title, invname, target = match.groups()
112
+ if invname not in inventories:
113
+ return match.group(0)
114
+ count += 1
115
+ return f":external+{invname}:{role}:`{title.strip()} <{target}>`"
116
+
117
+ def replace_no_title(match):
118
+ nonlocal count
119
+ role, invname, target = match.groups()
120
+ if invname not in inventories:
121
+ return match.group(0)
122
+ count += 1
123
+ return f":external+{invname}:{role}:`{target}`"
124
+
125
+ # Apply with-title pattern first (more specific)
126
+ new_content = PATTERN_WITH_TITLE.sub(replace_with_title, content)
127
+ # Then apply no-title pattern
128
+ new_content = PATTERN_NO_TITLE.sub(replace_no_title, new_content)
129
+
130
+ return new_content, count
131
+
132
+
133
+ def execute(args):
134
+ """Execute the intersphinx migration command."""
135
+ context_path = getattr(args, "context", None)
136
+ dry_run = getattr(args, "dry_run", False)
137
+ verbose = getattr(args, "verbose", False)
138
+
139
+ # Get the Sphinx context directory
140
+ context = get_sphinx_context(context_path)
141
+ if not context:
142
+ print("Error: Could not determine Sphinx context. Use --context to specify.")
143
+ return
144
+
145
+ if verbose:
146
+ print(f"Sphinx context: {context}")
147
+
148
+ inventories = get_intersphinx_inventories(Path(context) / "conf.py")
149
+ if not inventories:
150
+ print(
151
+ "Error: No intersphinx_mapping entries found in conf.py. "
152
+ "Nothing to migrate."
153
+ )
154
+ return
155
+
156
+ if verbose:
157
+ print(f"Intersphinx inventories: {', '.join(sorted(inventories))}")
158
+
159
+ # Find all RST files
160
+ rst_files = find_rst_files(context)
161
+ if verbose:
162
+ print(f"Found {len(rst_files)} RST files")
163
+
164
+ total_replacements = 0
165
+ files_modified = 0
166
+
167
+ for file_path in rst_files:
168
+ try:
169
+ with open(file_path, "r", encoding="utf-8") as f:
170
+ content = f.read()
171
+ except Exception as e:
172
+ print(f"Error reading {file_path}: {e}")
173
+ continue
174
+
175
+ new_content, count = migrate_content(content, inventories)
176
+
177
+ if count > 0:
178
+ files_modified += 1
179
+ total_replacements += count
180
+
181
+ if verbose or dry_run:
182
+ print(f"{file_path}: {count} replacement(s)")
183
+
184
+ if not dry_run:
185
+ try:
186
+ with open(file_path, "w", encoding="utf-8") as f:
187
+ f.write(new_content)
188
+ except Exception as e:
189
+ print(f"Error writing {file_path}: {e}")
190
+ continue
191
+
192
+ # Summary
193
+ action = "Would migrate" if dry_run else "Migrated"
194
+ print(
195
+ f"{action} {total_replacements} intersphinx reference(s) "
196
+ f"in {files_modified} file(s)"
197
+ )
@@ -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")
@@ -4,16 +4,10 @@ Configuration handling for sphinx-cmd.
4
4
  """
5
5
 
6
6
  import re
7
- import sys
7
+ import tomllib
8
8
  from pathlib import Path
9
9
  from typing import Any, Dict, Optional, Union
10
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
11
  # Default configuration with built-in directives
18
12
  DEFAULT_CONFIG = {"directives": ["image", "figure", "include"]}
19
13
 
@@ -1,22 +1,20 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sphinx-cmd
3
- Version: 0.4.3
3
+ Version: 0.6.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
7
7
  Project-URL: Bug Reports, https://github.com/jdillard/sphinx-cmd/issues
8
8
  Project-URL: Source, https://github.com/jdillard/sphinx-cmd
9
+ Classifier: Framework :: Sphinx
9
10
  Classifier: License :: OSI Approved :: MIT License
10
11
  Classifier: Operating System :: OS Independent
11
12
  Classifier: Programming Language :: Python :: 3
12
- Classifier: Programming Language :: Python :: 3.9
13
- Classifier: Programming Language :: Python :: 3.10
14
13
  Classifier: Programming Language :: Python :: 3.11
15
14
  Classifier: Programming Language :: Python :: 3.12
16
- Requires-Python: >=3.9
15
+ Requires-Python: >=3.11
17
16
  Description-Content-Type: text/markdown
18
17
  License-File: LICENSE
19
- Requires-Dist: tomli>=2.0.0; python_version < "3.11"
20
18
  Provides-Extra: dev
21
19
  Requires-Dist: pytest>=7.0.0; extra == "dev"
22
20
  Requires-Dist: black; extra == "dev"
@@ -109,6 +107,29 @@ sphinx-cmd --dry-run --directives drawio-figure mv old-file.rst new-file.rst
109
107
  - Preserves file relationships
110
108
  - Configure custom directives to be processed
111
109
 
110
+ ### `sphinx-cmd intersphinx`
111
+
112
+ Migrate intersphinx references to the `:external:` role syntax.
113
+
114
+ ```bash
115
+ # Migrate all .rst files in the detected context
116
+ sphinx-cmd intersphinx
117
+
118
+ # Preview changes without writing them
119
+ sphinx-cmd --dry-run intersphinx
120
+
121
+ # Specify the docs directory
122
+ sphinx-cmd --context path/to/docs intersphinx
123
+ ```
124
+
125
+ For example, `` :ref:`python:string-methods` `` becomes `` :external+python:ref:`string-methods` ``, and `` :ref:`Title <python:target>` `` becomes `` :external+python:ref:`Title <target>` ``.
126
+
127
+ #### Features
128
+
129
+ - Handles `:ref:`, `:doc:`, and `:term:` roles, with or without titles
130
+ - Only rewrites references whose prefix is an inventory name in `intersphinx_mapping`, so local labels containing a colon are left alone
131
+ - Reads `intersphinx_mapping` from `conf.py` without executing it; mappings built dynamically are not detected
132
+
112
133
  ## Configuration
113
134
 
114
135
  You can add custom directives to be processed in two ways:
@@ -13,11 +13,13 @@ sphinx_cmd.egg-info/entry_points.txt
13
13
  sphinx_cmd.egg-info/requires.txt
14
14
  sphinx_cmd.egg-info/top_level.txt
15
15
  sphinx_cmd/commands/__init__.py
16
+ sphinx_cmd/commands/intersphinx.py
16
17
  sphinx_cmd/commands/mv.py
17
18
  sphinx_cmd/commands/rm.py
18
19
  tests/test_cli.py
19
20
  tests/test_config.py
20
21
  tests/test_custom_directives.py
21
22
  tests/test_integration.py
23
+ tests/test_intersphinx.py
22
24
  tests/test_mv.py
23
25
  tests/test_rm.py
@@ -1,7 +1,4 @@
1
1
 
2
- [:python_version < "3.11"]
3
- tomli>=2.0.0
4
-
5
2
  [dev]
6
3
  pytest>=7.0.0
7
4
  black
@@ -0,0 +1,243 @@
1
+ import tempfile
2
+ from pathlib import Path
3
+ from unittest.mock import Mock
4
+
5
+ from sphinx_cmd.commands.intersphinx import (
6
+ execute,
7
+ find_rst_files,
8
+ get_intersphinx_inventories,
9
+ migrate_content,
10
+ )
11
+
12
+ INVENTORIES = {"python", "sphinx", "glossary"}
13
+
14
+ CONF_PY = """
15
+ extensions = ["sphinx.ext.intersphinx"]
16
+ intersphinx_mapping = {
17
+ "python": ("https://docs.python.org/3", None),
18
+ }
19
+ """
20
+
21
+
22
+ def make_args(tmpdir, dry_run):
23
+ args = Mock()
24
+ args.context = tmpdir
25
+ args.dry_run = dry_run
26
+ args.verbose = False
27
+ return args
28
+
29
+
30
+ def test_find_rst_files():
31
+ """Test finding RST files in a directory tree."""
32
+ with tempfile.TemporaryDirectory() as tmpdir:
33
+ (Path(tmpdir) / "test1.rst").touch()
34
+ (Path(tmpdir) / "test2.txt").touch() # Not RST
35
+ subdir = Path(tmpdir) / "subdir"
36
+ subdir.mkdir()
37
+ (subdir / "test3.rst").touch()
38
+
39
+ files = find_rst_files(tmpdir)
40
+ rst_files = [Path(f).name for f in files]
41
+
42
+ assert "test1.rst" in rst_files
43
+ assert "test3.rst" in rst_files
44
+ assert "test2.txt" not in str(files)
45
+
46
+
47
+ def test_get_inventories_dict_literal():
48
+ """Test reading inventory names from a dict literal."""
49
+ with tempfile.TemporaryDirectory() as tmpdir:
50
+ conf = Path(tmpdir) / "conf.py"
51
+ conf.write_text(
52
+ 'intersphinx_mapping = {"python": ("a", None), "sphinx": ("b", None)}\n'
53
+ )
54
+ assert get_intersphinx_inventories(conf) == {"python", "sphinx"}
55
+
56
+
57
+ def test_get_inventories_subscript_and_update():
58
+ """Test reading inventory names from item assignment and update()."""
59
+ with tempfile.TemporaryDirectory() as tmpdir:
60
+ conf = Path(tmpdir) / "conf.py"
61
+ conf.write_text(
62
+ "intersphinx_mapping = {}\n"
63
+ 'intersphinx_mapping["python"] = ("a", None)\n'
64
+ 'intersphinx_mapping.update({"sphinx": ("b", None)})\n'
65
+ )
66
+ assert get_intersphinx_inventories(conf) == {"python", "sphinx"}
67
+
68
+
69
+ def test_get_inventories_missing():
70
+ """Test that a conf.py without intersphinx_mapping returns None."""
71
+ with tempfile.TemporaryDirectory() as tmpdir:
72
+ conf = Path(tmpdir) / "conf.py"
73
+ conf.write_text("project = 'test'\n")
74
+ assert get_intersphinx_inventories(conf) is None
75
+
76
+
77
+ def test_migrate_ref_no_title():
78
+ """Test migrating :ref: without title."""
79
+ content = "See :ref:`python:string-methods` for details."
80
+ new_content, count = migrate_content(content, INVENTORIES)
81
+
82
+ assert count == 1
83
+ assert new_content == "See :external+python:ref:`string-methods` for details."
84
+
85
+
86
+ def test_migrate_doc_no_title():
87
+ """Test migrating :doc: without title."""
88
+ content = "See :doc:`sphinx:usage/configuration` for configuration."
89
+ new_content, count = migrate_content(content, INVENTORIES)
90
+
91
+ assert count == 1
92
+ assert (
93
+ new_content
94
+ == "See :external+sphinx:doc:`usage/configuration` for configuration."
95
+ )
96
+
97
+
98
+ def test_migrate_term_no_title():
99
+ """Test migrating :term: without title."""
100
+ content = "See :term:`glossary:builder` definition."
101
+ new_content, count = migrate_content(content, INVENTORIES)
102
+
103
+ assert count == 1
104
+ assert new_content == "See :external+glossary:term:`builder` definition."
105
+
106
+
107
+ def test_migrate_ref_with_title():
108
+ """Test migrating :ref: with title."""
109
+ content = "See :ref:`String Methods <python:string-methods>` for details."
110
+ new_content, count = migrate_content(content, INVENTORIES)
111
+
112
+ assert count == 1
113
+ assert (
114
+ new_content
115
+ == "See :external+python:ref:`String Methods <string-methods>` for details."
116
+ )
117
+
118
+
119
+ def test_migrate_doc_with_title():
120
+ """Test migrating :doc: with title."""
121
+ content = "See :doc:`Configuration Guide <sphinx:usage/configuration>` for details."
122
+ new_content, count = migrate_content(content, INVENTORIES)
123
+
124
+ assert count == 1
125
+ assert new_content == (
126
+ "See :external+sphinx:doc:`Configuration Guide <usage/configuration>` "
127
+ "for details."
128
+ )
129
+
130
+
131
+ def test_migrate_multiple_references():
132
+ """Test migrating multiple references in same content."""
133
+ content = """
134
+ Check :ref:`python:string-methods` and :doc:`sphinx:usage/configuration`.
135
+ Also see :ref:`API Reference <python:library/index>` for more.
136
+ """
137
+ new_content, count = migrate_content(content, INVENTORIES)
138
+
139
+ assert count == 3
140
+ assert ":external+python:ref:`string-methods`" in new_content
141
+ assert ":external+sphinx:doc:`usage/configuration`" in new_content
142
+ assert ":external+python:ref:`API Reference <library/index>`" in new_content
143
+
144
+
145
+ def test_unknown_prefix_not_migrated():
146
+ """Test that local labels containing a colon are left alone."""
147
+ content = (
148
+ "See :ref:`api:foo` and :ref:`Foo <api:foo>` "
149
+ "but :ref:`python:bar` is external."
150
+ )
151
+ new_content, count = migrate_content(content, INVENTORIES)
152
+
153
+ assert count == 1
154
+ assert ":ref:`api:foo`" in new_content
155
+ assert ":ref:`Foo <api:foo>`" in new_content
156
+ assert ":external+python:ref:`bar`" in new_content
157
+
158
+
159
+ def test_domain_qualified_roles_not_migrated():
160
+ """Test that domain-qualified roles are left alone rather than mangled."""
161
+ content = ":std:ref:`python:foo` and :std:doc:`Title <python:bar>`"
162
+ new_content, count = migrate_content(content, INVENTORIES)
163
+
164
+ assert count == 0
165
+ assert new_content == content
166
+
167
+
168
+ def test_no_migration_needed():
169
+ """Test content without old intersphinx syntax."""
170
+ content = """
171
+ Regular :ref:`local-reference` stays unchanged.
172
+ Already migrated :external+python:ref:`string-methods` stays unchanged.
173
+ """
174
+ new_content, count = migrate_content(content, INVENTORIES)
175
+
176
+ assert count == 0
177
+ assert new_content == content
178
+
179
+
180
+ def test_preserve_surrounding_content():
181
+ """Test that surrounding content is preserved."""
182
+ content = """
183
+ Title
184
+ =====
185
+
186
+ Some text before :ref:`python:example` and after.
187
+
188
+ .. code-block:: python
189
+
190
+ print("hello")
191
+ """
192
+ new_content, count = migrate_content(content, INVENTORIES)
193
+
194
+ assert count == 1
195
+ assert "Title\n=====" in new_content
196
+ assert "Some text before :external+python:ref:`example` and after." in new_content
197
+ assert ".. code-block:: python" in new_content
198
+ assert 'print("hello")' in new_content
199
+
200
+
201
+ def test_execute_dry_run():
202
+ """Test execute with dry-run mode."""
203
+ with tempfile.TemporaryDirectory() as tmpdir:
204
+ (Path(tmpdir) / "conf.py").write_text(CONF_PY)
205
+
206
+ rst_file = Path(tmpdir) / "test.rst"
207
+ original_content = "See :ref:`python:example` for details."
208
+ rst_file.write_text(original_content)
209
+
210
+ execute(make_args(tmpdir, dry_run=True))
211
+
212
+ # File should not be modified in dry-run mode
213
+ assert rst_file.read_text() == original_content
214
+
215
+
216
+ def test_execute_actual_migration():
217
+ """Test execute with actual file modification."""
218
+ with tempfile.TemporaryDirectory() as tmpdir:
219
+ (Path(tmpdir) / "conf.py").write_text(CONF_PY)
220
+
221
+ rst_file = Path(tmpdir) / "test.rst"
222
+ rst_file.write_text("See :ref:`python:example` and local :ref:`api:thing`.")
223
+
224
+ execute(make_args(tmpdir, dry_run=False))
225
+
226
+ assert rst_file.read_text() == (
227
+ "See :external+python:ref:`example` and local :ref:`api:thing`."
228
+ )
229
+
230
+
231
+ def test_execute_no_mapping(capsys):
232
+ """Test execute aborts when conf.py has no intersphinx_mapping."""
233
+ with tempfile.TemporaryDirectory() as tmpdir:
234
+ (Path(tmpdir) / "conf.py").write_text("project = 'test'\n")
235
+
236
+ rst_file = Path(tmpdir) / "test.rst"
237
+ original_content = "See :ref:`python:example` for details."
238
+ rst_file.write_text(original_content)
239
+
240
+ execute(make_args(tmpdir, dry_run=False))
241
+
242
+ assert rst_file.read_text() == original_content
243
+ assert "No intersphinx_mapping" in capsys.readouterr().out
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes