sphinx-cmd 0.5.0__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.5.0/sphinx_cmd.egg-info → sphinx_cmd-0.6.0}/PKG-INFO +26 -5
  2. {sphinx_cmd-0.5.0 → sphinx_cmd-0.6.0}/README.md +23 -0
  3. {sphinx_cmd-0.5.0 → sphinx_cmd-0.6.0}/pyproject.toml +5 -10
  4. {sphinx_cmd-0.5.0 → sphinx_cmd-0.6.0}/sphinx_cmd/__init__.py +1 -1
  5. {sphinx_cmd-0.5.0 → 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.5.0 → sphinx_cmd-0.6.0}/sphinx_cmd/config.py +1 -7
  8. {sphinx_cmd-0.5.0 → sphinx_cmd-0.6.0/sphinx_cmd.egg-info}/PKG-INFO +26 -5
  9. {sphinx_cmd-0.5.0 → sphinx_cmd-0.6.0}/sphinx_cmd.egg-info/SOURCES.txt +2 -0
  10. {sphinx_cmd-0.5.0 → sphinx_cmd-0.6.0}/sphinx_cmd.egg-info/requires.txt +0 -3
  11. sphinx_cmd-0.6.0/tests/test_intersphinx.py +243 -0
  12. {sphinx_cmd-0.5.0 → sphinx_cmd-0.6.0}/LICENSE +0 -0
  13. {sphinx_cmd-0.5.0 → sphinx_cmd-0.6.0}/MANIFEST.in +0 -0
  14. {sphinx_cmd-0.5.0 → sphinx_cmd-0.6.0}/setup.cfg +0 -0
  15. {sphinx_cmd-0.5.0 → sphinx_cmd-0.6.0}/sphinx_cmd/commands/__init__.py +0 -0
  16. {sphinx_cmd-0.5.0 → sphinx_cmd-0.6.0}/sphinx_cmd/commands/mv.py +0 -0
  17. {sphinx_cmd-0.5.0 → sphinx_cmd-0.6.0}/sphinx_cmd/commands/rm.py +0 -0
  18. {sphinx_cmd-0.5.0 → sphinx_cmd-0.6.0}/sphinx_cmd/py.typed +0 -0
  19. {sphinx_cmd-0.5.0 → sphinx_cmd-0.6.0}/sphinx_cmd.egg-info/dependency_links.txt +0 -0
  20. {sphinx_cmd-0.5.0 → sphinx_cmd-0.6.0}/sphinx_cmd.egg-info/entry_points.txt +0 -0
  21. {sphinx_cmd-0.5.0 → sphinx_cmd-0.6.0}/sphinx_cmd.egg-info/top_level.txt +0 -0
  22. {sphinx_cmd-0.5.0 → sphinx_cmd-0.6.0}/tests/test_cli.py +0 -0
  23. {sphinx_cmd-0.5.0 → sphinx_cmd-0.6.0}/tests/test_config.py +0 -0
  24. {sphinx_cmd-0.5.0 → sphinx_cmd-0.6.0}/tests/test_custom_directives.py +0 -0
  25. {sphinx_cmd-0.5.0 → sphinx_cmd-0.6.0}/tests/test_integration.py +0 -0
  26. {sphinx_cmd-0.5.0 → sphinx_cmd-0.6.0}/tests/test_mv.py +0 -0
  27. {sphinx_cmd-0.5.0 → 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.5.0
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.5.0"
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,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.5.0
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