sphinx-cmd 0.1.0__tar.gz → 0.2.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {sphinx_cmd-0.1.0/sphinx_cmd.egg-info → sphinx_cmd-0.2.1}/PKG-INFO +28 -1
- {sphinx_cmd-0.1.0 → sphinx_cmd-0.2.1}/README.md +27 -0
- {sphinx_cmd-0.1.0 → sphinx_cmd-0.2.1}/pyproject.toml +4 -1
- sphinx_cmd-0.2.1/sphinx_cmd/__init__.py +4 -0
- {sphinx_cmd-0.1.0 → sphinx_cmd-0.2.1}/sphinx_cmd/cli.py +37 -6
- sphinx_cmd-0.2.1/sphinx_cmd/commands/mv.py +259 -0
- {sphinx_cmd-0.1.0 → sphinx_cmd-0.2.1}/sphinx_cmd/commands/rm.py +56 -2
- {sphinx_cmd-0.1.0 → sphinx_cmd-0.2.1/sphinx_cmd.egg-info}/PKG-INFO +28 -1
- {sphinx_cmd-0.1.0 → sphinx_cmd-0.2.1}/sphinx_cmd.egg-info/SOURCES.txt +4 -0
- sphinx_cmd-0.2.1/tests/test_cli.py +43 -0
- sphinx_cmd-0.2.1/tests/test_integration.py +48 -0
- sphinx_cmd-0.2.1/tests/test_mv.py +158 -0
- sphinx_cmd-0.2.1/tests/test_rm.py +207 -0
- sphinx_cmd-0.1.0/sphinx_cmd/__init__.py +0 -2
- sphinx_cmd-0.1.0/tests/test_rm.py +0 -69
- {sphinx_cmd-0.1.0 → sphinx_cmd-0.2.1}/LICENSE +0 -0
- {sphinx_cmd-0.1.0 → sphinx_cmd-0.2.1}/MANIFEST.in +0 -0
- {sphinx_cmd-0.1.0 → sphinx_cmd-0.2.1}/setup.cfg +0 -0
- {sphinx_cmd-0.1.0 → sphinx_cmd-0.2.1}/sphinx_cmd/commands/__init__.py +0 -0
- {sphinx_cmd-0.1.0 → sphinx_cmd-0.2.1}/sphinx_cmd/py.typed +0 -0
- {sphinx_cmd-0.1.0 → sphinx_cmd-0.2.1}/sphinx_cmd.egg-info/dependency_links.txt +0 -0
- {sphinx_cmd-0.1.0 → sphinx_cmd-0.2.1}/sphinx_cmd.egg-info/entry_points.txt +0 -0
- {sphinx_cmd-0.1.0 → sphinx_cmd-0.2.1}/sphinx_cmd.egg-info/requires.txt +0 -0
- {sphinx_cmd-0.1.0 → sphinx_cmd-0.2.1}/sphinx_cmd.egg-info/top_level.txt +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: sphinx-cmd
|
|
3
|
-
Version: 0.1
|
|
3
|
+
Version: 0.2.1
|
|
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
|
|
@@ -52,6 +52,32 @@ sphinx-cmd rm path/to/docs
|
|
|
52
52
|
sphinx-cmd rm path/to/docs --dry-run
|
|
53
53
|
```
|
|
54
54
|
|
|
55
|
+
### `sphinx-cmd mv`
|
|
56
|
+
|
|
57
|
+
Move/rename .rst files and automatically update all references to them.
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
# Move and update all references
|
|
61
|
+
sphinx-cmd mv old-file.rst new-file.rst
|
|
62
|
+
|
|
63
|
+
# Move to a different directory
|
|
64
|
+
sphinx-cmd mv chapter1.rst topics/chapter1.rst
|
|
65
|
+
|
|
66
|
+
# Preview the move without making changes
|
|
67
|
+
sphinx-cmd mv old-file.rst new-file.rst --dry-run
|
|
68
|
+
|
|
69
|
+
# Move without updating references
|
|
70
|
+
sphinx-cmd mv old-file.rst new-file.rst --no-update-refs
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
#### Features
|
|
74
|
+
|
|
75
|
+
- Automatically updates `toctree` entries
|
|
76
|
+
- Updates `:doc:` references
|
|
77
|
+
- Updates `include` and `literalinclude` directives
|
|
78
|
+
- Handles relative paths correctly
|
|
79
|
+
- Preserves file relationships
|
|
80
|
+
|
|
55
81
|
## Development
|
|
56
82
|
|
|
57
83
|
```bash
|
|
@@ -73,6 +99,7 @@ mypy sphinx_cmd
|
|
|
73
99
|
# Test the command
|
|
74
100
|
sphinx-cmd --help
|
|
75
101
|
sphinx-cmd rm --help
|
|
102
|
+
sphinx-cmd mv --help
|
|
76
103
|
```
|
|
77
104
|
|
|
78
105
|
## Adding New Commands
|
|
@@ -24,6 +24,32 @@ sphinx-cmd rm path/to/docs
|
|
|
24
24
|
sphinx-cmd rm path/to/docs --dry-run
|
|
25
25
|
```
|
|
26
26
|
|
|
27
|
+
### `sphinx-cmd mv`
|
|
28
|
+
|
|
29
|
+
Move/rename .rst files and automatically update all references to them.
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
# Move and update all references
|
|
33
|
+
sphinx-cmd mv old-file.rst new-file.rst
|
|
34
|
+
|
|
35
|
+
# Move to a different directory
|
|
36
|
+
sphinx-cmd mv chapter1.rst topics/chapter1.rst
|
|
37
|
+
|
|
38
|
+
# Preview the move without making changes
|
|
39
|
+
sphinx-cmd mv old-file.rst new-file.rst --dry-run
|
|
40
|
+
|
|
41
|
+
# Move without updating references
|
|
42
|
+
sphinx-cmd mv old-file.rst new-file.rst --no-update-refs
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
#### Features
|
|
46
|
+
|
|
47
|
+
- Automatically updates `toctree` entries
|
|
48
|
+
- Updates `:doc:` references
|
|
49
|
+
- Updates `include` and `literalinclude` directives
|
|
50
|
+
- Handles relative paths correctly
|
|
51
|
+
- Preserves file relationships
|
|
52
|
+
|
|
27
53
|
## Development
|
|
28
54
|
|
|
29
55
|
```bash
|
|
@@ -45,6 +71,7 @@ mypy sphinx_cmd
|
|
|
45
71
|
# Test the command
|
|
46
72
|
sphinx-cmd --help
|
|
47
73
|
sphinx-cmd rm --help
|
|
74
|
+
sphinx-cmd mv --help
|
|
48
75
|
```
|
|
49
76
|
|
|
50
77
|
## Adding New Commands
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "sphinx-cmd"
|
|
7
|
-
|
|
7
|
+
dynamic = ["version"]
|
|
8
8
|
authors = [
|
|
9
9
|
{name = "Jared Dillard", email = "jared.dillard@gmail.com"},
|
|
10
10
|
]
|
|
@@ -48,6 +48,9 @@ packages = ["sphinx_cmd", "sphinx_cmd.commands"]
|
|
|
48
48
|
[tool.setuptools.package-data]
|
|
49
49
|
sphinx_cmd = ["py.typed"]
|
|
50
50
|
|
|
51
|
+
[tool.setuptools.dynamic]
|
|
52
|
+
version = {attr = "sphinx_cmd.__version__"}
|
|
53
|
+
|
|
51
54
|
[tool.black]
|
|
52
55
|
line-length = 88
|
|
53
56
|
target-version = ['py39', 'py310', 'py311', 'py312']
|
|
@@ -6,7 +6,7 @@ Main CLI entry point for sphinx-cmd with subcommands.
|
|
|
6
6
|
import argparse
|
|
7
7
|
import sys
|
|
8
8
|
|
|
9
|
-
from sphinx_cmd
|
|
9
|
+
from sphinx_cmd import __version__
|
|
10
10
|
|
|
11
11
|
|
|
12
12
|
def create_parser():
|
|
@@ -17,7 +17,9 @@ def create_parser():
|
|
|
17
17
|
)
|
|
18
18
|
|
|
19
19
|
# Add version option
|
|
20
|
-
parser.add_argument(
|
|
20
|
+
parser.add_argument(
|
|
21
|
+
"--version", action="version", version=f"%(prog)s {__version__}"
|
|
22
|
+
)
|
|
21
23
|
|
|
22
24
|
# Create subparsers for subcommands
|
|
23
25
|
subparsers = parser.add_subparsers(
|
|
@@ -37,7 +39,26 @@ def create_parser():
|
|
|
37
39
|
action="store_true",
|
|
38
40
|
help="Preview deletions without removing files",
|
|
39
41
|
)
|
|
40
|
-
rm_parser.set_defaults(
|
|
42
|
+
rm_parser.set_defaults(command_name="rm")
|
|
43
|
+
|
|
44
|
+
# Add 'mv' subcommand
|
|
45
|
+
mv_parser = subparsers.add_parser(
|
|
46
|
+
"mv", help="Move/rename .rst files and update references"
|
|
47
|
+
)
|
|
48
|
+
mv_parser.add_argument("source", help="Source file to move")
|
|
49
|
+
mv_parser.add_argument("destination", help="Destination file or directory")
|
|
50
|
+
mv_parser.add_argument(
|
|
51
|
+
"-n",
|
|
52
|
+
"--dry-run",
|
|
53
|
+
action="store_true",
|
|
54
|
+
help="Preview move without actually moving files",
|
|
55
|
+
)
|
|
56
|
+
mv_parser.add_argument(
|
|
57
|
+
"--no-update-refs",
|
|
58
|
+
action="store_true",
|
|
59
|
+
help="Do not update references to the moved file",
|
|
60
|
+
)
|
|
61
|
+
mv_parser.set_defaults(command_name="mv")
|
|
41
62
|
|
|
42
63
|
return parser
|
|
43
64
|
|
|
@@ -48,13 +69,23 @@ def main():
|
|
|
48
69
|
args = parser.parse_args()
|
|
49
70
|
|
|
50
71
|
# If no command is provided, show help
|
|
51
|
-
if not hasattr(args, "
|
|
72
|
+
if not hasattr(args, "command_name"):
|
|
52
73
|
parser.print_help()
|
|
53
74
|
sys.exit(1)
|
|
54
75
|
|
|
55
|
-
#
|
|
76
|
+
# Import and execute the appropriate command
|
|
56
77
|
try:
|
|
57
|
-
args.
|
|
78
|
+
if args.command_name == "rm":
|
|
79
|
+
from sphinx_cmd.commands.rm import execute
|
|
80
|
+
|
|
81
|
+
execute(args)
|
|
82
|
+
elif args.command_name == "mv":
|
|
83
|
+
from sphinx_cmd.commands.mv import execute
|
|
84
|
+
|
|
85
|
+
execute(args)
|
|
86
|
+
else:
|
|
87
|
+
print(f"Unknown command: {args.command_name}", file=sys.stderr)
|
|
88
|
+
sys.exit(1)
|
|
58
89
|
except Exception as e:
|
|
59
90
|
print(f"Error: {e}", file=sys.stderr)
|
|
60
91
|
sys.exit(1)
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
Command to move/rename .rst files and update all references.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import re
|
|
7
|
+
import shutil
|
|
8
|
+
from collections import defaultdict
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Dict, List, Tuple
|
|
11
|
+
|
|
12
|
+
# Regex patterns for different types of references in reStructuredText
|
|
13
|
+
REFERENCE_PATTERNS = {
|
|
14
|
+
"toctree": re.compile(r"^\s*(\S+)\s*$", re.MULTILINE),
|
|
15
|
+
"include": re.compile(r"^\s*\.\.\s+include::\s+(.+)$", re.MULTILINE),
|
|
16
|
+
"literalinclude": re.compile(r"^\s*\.\.\s+literalinclude::\s+(.+)$", re.MULTILINE),
|
|
17
|
+
"code-block": re.compile(
|
|
18
|
+
r"^\s*\.\.\s+code-block::\s+\w+\s*\n\s*:name:\s+(.+)$", re.MULTILINE
|
|
19
|
+
),
|
|
20
|
+
"reference": re.compile(r":doc:`([^`]+)`", re.MULTILINE),
|
|
21
|
+
"internal_link": re.compile(r"`([^<>`]+)\s+<([^>]+)>`__?", re.MULTILINE),
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
# Patterns that appear in toctree contexts
|
|
25
|
+
TOCTREE_PATTERN = re.compile(
|
|
26
|
+
r"^\s*\.\.\s+toctree::(.*?)(?=^\S|\Z)", re.DOTALL | re.MULTILINE
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def find_all_rst_files(root_path: str) -> List[str]:
|
|
31
|
+
"""Find all .rst files in the given directory tree."""
|
|
32
|
+
rst_files = []
|
|
33
|
+
root = Path(root_path)
|
|
34
|
+
|
|
35
|
+
if root.is_file() and root.suffix == ".rst":
|
|
36
|
+
return [str(root)]
|
|
37
|
+
|
|
38
|
+
for file_path in root.rglob("*.rst"):
|
|
39
|
+
rst_files.append(str(file_path))
|
|
40
|
+
|
|
41
|
+
return rst_files
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def extract_references(file_path: str) -> Dict[str, List[str]]:
|
|
45
|
+
"""Extract all file references from an .rst file."""
|
|
46
|
+
references = defaultdict(list)
|
|
47
|
+
|
|
48
|
+
with open(file_path, "r", encoding="utf-8") as f:
|
|
49
|
+
content = f.read()
|
|
50
|
+
|
|
51
|
+
# Find toctree entries
|
|
52
|
+
toctree_matches = TOCTREE_PATTERN.findall(content)
|
|
53
|
+
for toctree_content in toctree_matches:
|
|
54
|
+
# Extract file references from toctree
|
|
55
|
+
lines = toctree_content.split("\n")
|
|
56
|
+
for line in lines:
|
|
57
|
+
line = line.strip()
|
|
58
|
+
if line and not line.startswith(":"): # Skip options
|
|
59
|
+
# Handle both relative and absolute paths
|
|
60
|
+
ref_file = line.split()[0] if line.split() else ""
|
|
61
|
+
if ref_file:
|
|
62
|
+
references["toctree"].append(ref_file)
|
|
63
|
+
|
|
64
|
+
# Find other types of references
|
|
65
|
+
for ref_type, pattern in REFERENCE_PATTERNS.items():
|
|
66
|
+
if ref_type == "toctree":
|
|
67
|
+
continue # Already handled above
|
|
68
|
+
|
|
69
|
+
for match in pattern.findall(content):
|
|
70
|
+
if isinstance(match, tuple):
|
|
71
|
+
# For patterns with multiple groups, take the relevant one
|
|
72
|
+
ref_path = match[1] if ref_type == "internal_link" else match[0]
|
|
73
|
+
else:
|
|
74
|
+
ref_path = match
|
|
75
|
+
references[ref_type].append(ref_path)
|
|
76
|
+
|
|
77
|
+
return dict(references)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def find_files_referencing(
|
|
81
|
+
target_file: str, all_files: List[str]
|
|
82
|
+
) -> List[Tuple[str, str]]:
|
|
83
|
+
"""Find all files that reference the target file."""
|
|
84
|
+
referencing_files = []
|
|
85
|
+
target_path = Path(target_file)
|
|
86
|
+
target_stem = target_path.stem # filename without extension
|
|
87
|
+
|
|
88
|
+
for file_path in all_files:
|
|
89
|
+
if file_path == target_file:
|
|
90
|
+
continue
|
|
91
|
+
|
|
92
|
+
try:
|
|
93
|
+
references = extract_references(file_path)
|
|
94
|
+
|
|
95
|
+
for ref_type, ref_list in references.items():
|
|
96
|
+
for ref in ref_list:
|
|
97
|
+
# Normalize the reference path
|
|
98
|
+
ref_path = Path(ref)
|
|
99
|
+
|
|
100
|
+
# Check if this reference matches our target file
|
|
101
|
+
if (
|
|
102
|
+
ref_path.stem == target_stem
|
|
103
|
+
or ref == target_stem
|
|
104
|
+
or str(ref_path.with_suffix(".rst")) == target_file
|
|
105
|
+
):
|
|
106
|
+
referencing_files.append((file_path, ref_type))
|
|
107
|
+
break
|
|
108
|
+
except Exception as e:
|
|
109
|
+
print(f"Warning: Could not analyze {file_path}: {e}")
|
|
110
|
+
|
|
111
|
+
return referencing_files
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def update_references_in_file(file_path: str, old_ref: str, new_ref: str) -> bool:
|
|
115
|
+
"""Update references to the moved file in a single file."""
|
|
116
|
+
old_path = Path(old_ref)
|
|
117
|
+
new_path = Path(new_ref)
|
|
118
|
+
old_stem = old_path.stem
|
|
119
|
+
new_stem = new_path.stem
|
|
120
|
+
|
|
121
|
+
try:
|
|
122
|
+
with open(file_path, "r", encoding="utf-8") as f:
|
|
123
|
+
content = f.read()
|
|
124
|
+
|
|
125
|
+
original_content = content
|
|
126
|
+
|
|
127
|
+
# Update different types of references
|
|
128
|
+
# 1. Toctree entries
|
|
129
|
+
content = re.sub(
|
|
130
|
+
rf"^\s*{re.escape(old_stem)}\s*$",
|
|
131
|
+
f" {new_stem}",
|
|
132
|
+
content,
|
|
133
|
+
flags=re.MULTILINE,
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
# 2. :doc: references
|
|
137
|
+
content = re.sub(
|
|
138
|
+
rf":doc:`{re.escape(old_stem)}`", f":doc:`{new_stem}`", content
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
# 3. Include directives
|
|
142
|
+
for directive in ["include", "literalinclude"]:
|
|
143
|
+
content = re.sub(
|
|
144
|
+
rf"^\s*\.\.\s+{directive}::\s+{re.escape(old_ref)}",
|
|
145
|
+
f".. {directive}:: {new_ref}",
|
|
146
|
+
content,
|
|
147
|
+
flags=re.MULTILINE,
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
# 4. Internal links
|
|
151
|
+
content = re.sub(
|
|
152
|
+
rf"`([^<>`]+)\s+<{re.escape(old_ref)}>`__?", rf"`\1 <{new_ref}>`_", content
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
# Write back if changes were made
|
|
156
|
+
if content != original_content:
|
|
157
|
+
with open(file_path, "w", encoding="utf-8") as f:
|
|
158
|
+
f.write(content)
|
|
159
|
+
return True
|
|
160
|
+
|
|
161
|
+
return False
|
|
162
|
+
|
|
163
|
+
except Exception as e:
|
|
164
|
+
print(f"Error updating references in {file_path}: {e}")
|
|
165
|
+
return False
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def move_rst_file(
|
|
169
|
+
source: str, destination: str, update_references: bool = True, dry_run: bool = False
|
|
170
|
+
) -> None:
|
|
171
|
+
"""Move an RST file and optionally update all references to it."""
|
|
172
|
+
source_path = Path(source).resolve()
|
|
173
|
+
dest_path = Path(destination).resolve()
|
|
174
|
+
|
|
175
|
+
if not source_path.exists():
|
|
176
|
+
raise FileNotFoundError(f"Source file not found: {source}")
|
|
177
|
+
|
|
178
|
+
if not source_path.suffix == ".rst":
|
|
179
|
+
raise ValueError(f"Source must be an .rst file: {source}")
|
|
180
|
+
|
|
181
|
+
# If destination is a directory, use the same filename
|
|
182
|
+
if dest_path.is_dir():
|
|
183
|
+
dest_path = dest_path / source_path.name
|
|
184
|
+
elif not dest_path.suffix:
|
|
185
|
+
dest_path = dest_path.with_suffix(".rst")
|
|
186
|
+
|
|
187
|
+
# Get the relative paths for updating references
|
|
188
|
+
# Try to find a common root to make relative paths
|
|
189
|
+
try:
|
|
190
|
+
source_rel = source_path.relative_to(Path.cwd())
|
|
191
|
+
dest_rel = dest_path.relative_to(Path.cwd())
|
|
192
|
+
except ValueError:
|
|
193
|
+
# Fall back to absolute paths if no common root
|
|
194
|
+
source_rel = source_path
|
|
195
|
+
dest_rel = dest_path
|
|
196
|
+
|
|
197
|
+
print(f"Moving: {source_rel} -> {dest_rel}")
|
|
198
|
+
|
|
199
|
+
if not dry_run:
|
|
200
|
+
# Create destination directory if it doesn't exist
|
|
201
|
+
dest_path.parent.mkdir(parents=True, exist_ok=True)
|
|
202
|
+
|
|
203
|
+
# Move the file
|
|
204
|
+
shutil.move(str(source_path), str(dest_path))
|
|
205
|
+
|
|
206
|
+
if update_references:
|
|
207
|
+
# Find all .rst files that might reference this file
|
|
208
|
+
root_dir = Path.cwd() # Or use a smarter root detection
|
|
209
|
+
all_files = find_all_rst_files(str(root_dir))
|
|
210
|
+
|
|
211
|
+
# Find files that reference the moved file
|
|
212
|
+
referencing_files = find_files_referencing(str(source_rel), all_files)
|
|
213
|
+
|
|
214
|
+
if referencing_files:
|
|
215
|
+
print(f"\nUpdating references in {len(referencing_files)} file(s):")
|
|
216
|
+
|
|
217
|
+
for ref_file, ref_type in referencing_files:
|
|
218
|
+
print(f" - {ref_file} ({ref_type})")
|
|
219
|
+
|
|
220
|
+
if not dry_run:
|
|
221
|
+
source_stem = source_path.stem
|
|
222
|
+
dest_stem = dest_path.stem
|
|
223
|
+
|
|
224
|
+
# Update the references
|
|
225
|
+
updated = update_references_in_file(
|
|
226
|
+
ref_file, source_stem, dest_stem
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
if updated:
|
|
230
|
+
print(f" ✓ Updated references in {ref_file}")
|
|
231
|
+
else:
|
|
232
|
+
print(f" - No changes needed in {ref_file}")
|
|
233
|
+
else:
|
|
234
|
+
print("\nNo references to update.")
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def execute(args):
|
|
238
|
+
"""Execute the mv command."""
|
|
239
|
+
try:
|
|
240
|
+
# Determine if we should update references (default: yes)
|
|
241
|
+
update_refs = getattr(args, "no_update_refs", False)
|
|
242
|
+
update_references = not update_refs
|
|
243
|
+
|
|
244
|
+
# Perform the move
|
|
245
|
+
move_rst_file(
|
|
246
|
+
args.source,
|
|
247
|
+
args.destination,
|
|
248
|
+
update_references=update_references,
|
|
249
|
+
dry_run=getattr(args, "dry_run", False),
|
|
250
|
+
)
|
|
251
|
+
|
|
252
|
+
if not getattr(args, "dry_run", False):
|
|
253
|
+
print("\n✓ Move completed successfully!")
|
|
254
|
+
else:
|
|
255
|
+
print("\n[Dry run complete - no files were actually moved]")
|
|
256
|
+
|
|
257
|
+
except Exception as e:
|
|
258
|
+
print(f"Error: {e}")
|
|
259
|
+
raise
|
|
@@ -63,6 +63,7 @@ def delete_unused_assets_and_pages(
|
|
|
63
63
|
"""Delete files and their unique assets if not used elsewhere."""
|
|
64
64
|
deleted_pages = []
|
|
65
65
|
deleted_assets = []
|
|
66
|
+
affected_dirs = set()
|
|
66
67
|
|
|
67
68
|
for rst_file, assets in file_to_assets.items():
|
|
68
69
|
unused_assets = [a for a in assets if len(asset_to_files[a]) == 1]
|
|
@@ -73,26 +74,74 @@ def delete_unused_assets_and_pages(
|
|
|
73
74
|
if dry_run:
|
|
74
75
|
print(f"[dry-run] Would delete {directive}: {asset}")
|
|
75
76
|
else:
|
|
77
|
+
affected_dirs.add(os.path.dirname(asset))
|
|
76
78
|
os.remove(asset)
|
|
77
79
|
deleted_assets.append(asset)
|
|
78
80
|
if os.path.exists(rst_file):
|
|
79
81
|
if dry_run:
|
|
80
82
|
print(f"[dry-run] Would delete page: {rst_file}")
|
|
81
83
|
else:
|
|
84
|
+
affected_dirs.add(os.path.dirname(rst_file))
|
|
82
85
|
os.remove(rst_file)
|
|
83
86
|
deleted_pages.append(rst_file)
|
|
84
87
|
|
|
85
|
-
return deleted_pages, deleted_assets
|
|
88
|
+
return deleted_pages, deleted_assets, affected_dirs
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def remove_empty_dirs(dirs, original_path, dry_run=False):
|
|
92
|
+
"""Remove empty directories, bottom-up."""
|
|
93
|
+
deleted_dirs = []
|
|
94
|
+
|
|
95
|
+
# Add parent directories to the affected dirs set
|
|
96
|
+
all_dirs = set(dirs)
|
|
97
|
+
for dir_path in dirs:
|
|
98
|
+
# Add all parent directories up to but not including the original path
|
|
99
|
+
parent = os.path.dirname(dir_path)
|
|
100
|
+
while parent and os.path.exists(parent) and parent != original_path:
|
|
101
|
+
all_dirs.add(parent)
|
|
102
|
+
parent = os.path.dirname(parent)
|
|
103
|
+
|
|
104
|
+
# Sort by path depth (deepest first)
|
|
105
|
+
sorted_dirs = sorted(all_dirs, key=lambda d: d.count(os.sep), reverse=True)
|
|
106
|
+
|
|
107
|
+
# Process directories from deepest to shallowest
|
|
108
|
+
for dir_path in sorted_dirs:
|
|
109
|
+
if not os.path.exists(dir_path) or not os.path.isdir(dir_path):
|
|
110
|
+
continue
|
|
111
|
+
|
|
112
|
+
# Check if directory is empty
|
|
113
|
+
if not os.listdir(dir_path):
|
|
114
|
+
if dry_run:
|
|
115
|
+
print(f"[dry-run] Would delete empty directory: {dir_path}")
|
|
116
|
+
else:
|
|
117
|
+
os.rmdir(dir_path)
|
|
118
|
+
deleted_dirs.append(dir_path)
|
|
119
|
+
|
|
120
|
+
# Check if the original path (if it's a directory) is now empty and should
|
|
121
|
+
# be removed
|
|
122
|
+
if os.path.isdir(original_path) and not os.listdir(original_path):
|
|
123
|
+
if dry_run:
|
|
124
|
+
print(f"[dry-run] Would delete empty directory: {original_path}")
|
|
125
|
+
else:
|
|
126
|
+
os.rmdir(original_path)
|
|
127
|
+
deleted_dirs.append(original_path)
|
|
128
|
+
|
|
129
|
+
return deleted_dirs
|
|
86
130
|
|
|
87
131
|
|
|
88
132
|
def execute(args):
|
|
89
133
|
"""Execute the rm command."""
|
|
134
|
+
original_path = os.path.abspath(args.path)
|
|
90
135
|
rst_files = find_rst_files(args.path)
|
|
91
136
|
asset_to_files, file_to_assets, asset_directive_map = build_asset_index(rst_files)
|
|
92
|
-
deleted_pages, deleted_assets = delete_unused_assets_and_pages(
|
|
137
|
+
deleted_pages, deleted_assets, affected_dirs = delete_unused_assets_and_pages(
|
|
93
138
|
asset_to_files, file_to_assets, asset_directive_map, args.dry_run
|
|
94
139
|
)
|
|
95
140
|
|
|
141
|
+
deleted_dirs = []
|
|
142
|
+
if affected_dirs:
|
|
143
|
+
deleted_dirs = remove_empty_dirs(affected_dirs, original_path, args.dry_run)
|
|
144
|
+
|
|
96
145
|
if not args.dry_run:
|
|
97
146
|
print(f"\nDeleted {len(deleted_assets)} unused asset(s):")
|
|
98
147
|
for a in deleted_assets:
|
|
@@ -102,3 +151,8 @@ def execute(args):
|
|
|
102
151
|
print(f"\nDeleted {len(deleted_pages)} RST page(s):")
|
|
103
152
|
for p in deleted_pages:
|
|
104
153
|
print(f" - {p}")
|
|
154
|
+
|
|
155
|
+
if deleted_dirs:
|
|
156
|
+
print(f"\nDeleted {len(deleted_dirs)} empty directory/directories:")
|
|
157
|
+
for d in deleted_dirs:
|
|
158
|
+
print(f" - {d}")
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: sphinx-cmd
|
|
3
|
-
Version: 0.1
|
|
3
|
+
Version: 0.2.1
|
|
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
|
|
@@ -52,6 +52,32 @@ sphinx-cmd rm path/to/docs
|
|
|
52
52
|
sphinx-cmd rm path/to/docs --dry-run
|
|
53
53
|
```
|
|
54
54
|
|
|
55
|
+
### `sphinx-cmd mv`
|
|
56
|
+
|
|
57
|
+
Move/rename .rst files and automatically update all references to them.
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
# Move and update all references
|
|
61
|
+
sphinx-cmd mv old-file.rst new-file.rst
|
|
62
|
+
|
|
63
|
+
# Move to a different directory
|
|
64
|
+
sphinx-cmd mv chapter1.rst topics/chapter1.rst
|
|
65
|
+
|
|
66
|
+
# Preview the move without making changes
|
|
67
|
+
sphinx-cmd mv old-file.rst new-file.rst --dry-run
|
|
68
|
+
|
|
69
|
+
# Move without updating references
|
|
70
|
+
sphinx-cmd mv old-file.rst new-file.rst --no-update-refs
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
#### Features
|
|
74
|
+
|
|
75
|
+
- Automatically updates `toctree` entries
|
|
76
|
+
- Updates `:doc:` references
|
|
77
|
+
- Updates `include` and `literalinclude` directives
|
|
78
|
+
- Handles relative paths correctly
|
|
79
|
+
- Preserves file relationships
|
|
80
|
+
|
|
55
81
|
## Development
|
|
56
82
|
|
|
57
83
|
```bash
|
|
@@ -73,6 +99,7 @@ mypy sphinx_cmd
|
|
|
73
99
|
# Test the command
|
|
74
100
|
sphinx-cmd --help
|
|
75
101
|
sphinx-cmd rm --help
|
|
102
|
+
sphinx-cmd mv --help
|
|
76
103
|
```
|
|
77
104
|
|
|
78
105
|
## Adding New Commands
|
|
@@ -12,5 +12,9 @@ sphinx_cmd.egg-info/entry_points.txt
|
|
|
12
12
|
sphinx_cmd.egg-info/requires.txt
|
|
13
13
|
sphinx_cmd.egg-info/top_level.txt
|
|
14
14
|
sphinx_cmd/commands/__init__.py
|
|
15
|
+
sphinx_cmd/commands/mv.py
|
|
15
16
|
sphinx_cmd/commands/rm.py
|
|
17
|
+
tests/test_cli.py
|
|
18
|
+
tests/test_integration.py
|
|
19
|
+
tests/test_mv.py
|
|
16
20
|
tests/test_rm.py
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
from unittest.mock import patch
|
|
3
|
+
|
|
4
|
+
import pytest
|
|
5
|
+
|
|
6
|
+
from sphinx_cmd.cli import create_parser, main
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def test_cli_help():
|
|
10
|
+
"""Test that the main CLI shows help information."""
|
|
11
|
+
parser = create_parser()
|
|
12
|
+
# This should not raise an exception
|
|
13
|
+
assert parser is not None
|
|
14
|
+
assert "sphinx-cmd" in parser.format_help()
|
|
15
|
+
assert "rm" in parser.format_help()
|
|
16
|
+
assert "mv" in parser.format_help()
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def test_cli_no_command():
|
|
20
|
+
"""Test CLI behavior when no command is provided."""
|
|
21
|
+
# Mock argv to simulate running with no arguments
|
|
22
|
+
with patch.object(sys, "argv", ["sphinx-cmd"]):
|
|
23
|
+
with pytest.raises(SystemExit) as excinfo:
|
|
24
|
+
main()
|
|
25
|
+
assert excinfo.value.code == 1
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def test_cli_rm_help():
|
|
29
|
+
"""Test that rm subcommand help works."""
|
|
30
|
+
with patch.object(sys, "argv", ["sphinx-cmd", "rm", "--help"]):
|
|
31
|
+
with pytest.raises(SystemExit) as excinfo:
|
|
32
|
+
main()
|
|
33
|
+
# Help should exit with code 0
|
|
34
|
+
assert excinfo.value.code == 0
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def test_cli_mv_help():
|
|
38
|
+
"""Test that mv subcommand help works."""
|
|
39
|
+
with patch.object(sys, "argv", ["sphinx-cmd", "mv", "--help"]):
|
|
40
|
+
with pytest.raises(SystemExit) as excinfo:
|
|
41
|
+
main()
|
|
42
|
+
# Help should exit with code 0
|
|
43
|
+
assert excinfo.value.code == 0
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import subprocess
|
|
3
|
+
import tempfile
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def test_integration_rm_command():
|
|
7
|
+
"""Integration test for the rm command through the CLI."""
|
|
8
|
+
with tempfile.TemporaryDirectory() as tmpdir:
|
|
9
|
+
# Create test files
|
|
10
|
+
rst_content = """
|
|
11
|
+
Test Page
|
|
12
|
+
=========
|
|
13
|
+
|
|
14
|
+
.. image:: test.png
|
|
15
|
+
"""
|
|
16
|
+
with open(os.path.join(tmpdir, "test.rst"), "w") as f:
|
|
17
|
+
f.write(rst_content)
|
|
18
|
+
|
|
19
|
+
with open(os.path.join(tmpdir, "test.png"), "w") as f:
|
|
20
|
+
f.write("fake image")
|
|
21
|
+
|
|
22
|
+
# Run the command with dry-run
|
|
23
|
+
result = subprocess.run(
|
|
24
|
+
["sphinx-cmd", "rm", tmpdir, "--dry-run"], capture_output=True, text=True
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
# Check that it executed successfully
|
|
28
|
+
assert result.returncode == 0
|
|
29
|
+
assert "[dry-run]" in result.stdout
|
|
30
|
+
|
|
31
|
+
# Verify files still exist after dry run
|
|
32
|
+
assert os.path.exists(os.path.join(tmpdir, "test.rst"))
|
|
33
|
+
assert os.path.exists(os.path.join(tmpdir, "test.png"))
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def test_integration_help_commands():
|
|
37
|
+
"""Test that all help commands work."""
|
|
38
|
+
commands = [
|
|
39
|
+
["sphinx-cmd", "--help"],
|
|
40
|
+
["sphinx-cmd", "rm", "--help"],
|
|
41
|
+
["sphinx-cmd", "mv", "--help"],
|
|
42
|
+
["sphinx-cmd", "--version"],
|
|
43
|
+
]
|
|
44
|
+
|
|
45
|
+
for cmd in commands:
|
|
46
|
+
result = subprocess.run(cmd, capture_output=True, text=True)
|
|
47
|
+
# Help commands should exit with 0 or 1 (argparse help exits with 0)
|
|
48
|
+
assert result.returncode in [0, 1]
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import tempfile
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from unittest.mock import Mock
|
|
5
|
+
|
|
6
|
+
from sphinx_cmd.commands.mv import (
|
|
7
|
+
extract_references,
|
|
8
|
+
find_all_rst_files,
|
|
9
|
+
find_files_referencing,
|
|
10
|
+
update_references_in_file,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def test_find_rst_files():
|
|
15
|
+
"""Test finding RST files in a directory tree."""
|
|
16
|
+
with tempfile.TemporaryDirectory() as tmpdir:
|
|
17
|
+
# Create test files
|
|
18
|
+
(Path(tmpdir) / "test1.rst").touch()
|
|
19
|
+
(Path(tmpdir) / "test2.txt").touch() # Not RST
|
|
20
|
+
subdir = Path(tmpdir) / "subdir"
|
|
21
|
+
subdir.mkdir()
|
|
22
|
+
(subdir / "test3.rst").touch()
|
|
23
|
+
|
|
24
|
+
files = find_all_rst_files(tmpdir)
|
|
25
|
+
rst_files = [Path(f).name for f in files]
|
|
26
|
+
|
|
27
|
+
assert "test1.rst" in rst_files
|
|
28
|
+
assert "test3.rst" in rst_files
|
|
29
|
+
assert "test2.txt" not in str(files)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def test_extract_references():
|
|
33
|
+
"""Test extracting references from RST content."""
|
|
34
|
+
with tempfile.TemporaryDirectory() as tmpdir:
|
|
35
|
+
rst_file = Path(tmpdir) / "test.rst"
|
|
36
|
+
content = """
|
|
37
|
+
Test Document
|
|
38
|
+
=============
|
|
39
|
+
|
|
40
|
+
.. toctree::
|
|
41
|
+
:maxdepth: 2
|
|
42
|
+
|
|
43
|
+
intro
|
|
44
|
+
tutorial/basic
|
|
45
|
+
api
|
|
46
|
+
|
|
47
|
+
See :doc:`intro` for more information.
|
|
48
|
+
|
|
49
|
+
.. include:: snippets/example.rst
|
|
50
|
+
|
|
51
|
+
.. literalinclude:: code/example.py
|
|
52
|
+
"""
|
|
53
|
+
rst_file.write_text(content)
|
|
54
|
+
|
|
55
|
+
refs = extract_references(str(rst_file))
|
|
56
|
+
|
|
57
|
+
assert "toctree" in refs
|
|
58
|
+
assert "intro" in refs["toctree"]
|
|
59
|
+
assert "tutorial/basic" in refs["toctree"]
|
|
60
|
+
|
|
61
|
+
assert "reference" in refs
|
|
62
|
+
assert "intro" in refs["reference"]
|
|
63
|
+
|
|
64
|
+
assert "include" in refs
|
|
65
|
+
assert "snippets/example.rst" in refs["include"]
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def test_find_files_referencing():
|
|
69
|
+
"""Test finding files that reference a target file."""
|
|
70
|
+
with tempfile.TemporaryDirectory() as tmpdir:
|
|
71
|
+
# Create target file
|
|
72
|
+
target = Path(tmpdir) / "target.rst"
|
|
73
|
+
target.write_text("Target content")
|
|
74
|
+
|
|
75
|
+
# Create referencing file
|
|
76
|
+
ref_file = Path(tmpdir) / "referencing.rst"
|
|
77
|
+
ref_content = """
|
|
78
|
+
.. toctree::
|
|
79
|
+
|
|
80
|
+
target
|
|
81
|
+
|
|
82
|
+
See :doc:`target` for details.
|
|
83
|
+
"""
|
|
84
|
+
ref_file.write_text(ref_content)
|
|
85
|
+
|
|
86
|
+
# Create non-referencing file
|
|
87
|
+
other_file = Path(tmpdir) / "other.rst"
|
|
88
|
+
other_file.write_text("Other content")
|
|
89
|
+
|
|
90
|
+
all_files = [str(target), str(ref_file), str(other_file)]
|
|
91
|
+
refs = find_files_referencing(str(target), all_files)
|
|
92
|
+
|
|
93
|
+
# The function finds multiple types of references in the same file
|
|
94
|
+
# We expect 2 references: one from toctree and one from :doc:
|
|
95
|
+
assert len(refs) == 2
|
|
96
|
+
assert all(r[0] == str(ref_file) for r in refs)
|
|
97
|
+
|
|
98
|
+
# Check that we found both types of references
|
|
99
|
+
ref_types = {r[1] for r in refs}
|
|
100
|
+
assert "toctree" in ref_types
|
|
101
|
+
assert "reference" in ref_types
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def test_update_references():
|
|
105
|
+
"""Test updating references in a file."""
|
|
106
|
+
with tempfile.TemporaryDirectory() as tmpdir:
|
|
107
|
+
test_file = Path(tmpdir) / "test.rst"
|
|
108
|
+
content = """
|
|
109
|
+
.. toctree::
|
|
110
|
+
|
|
111
|
+
oldname
|
|
112
|
+
|
|
113
|
+
See :doc:`oldname` for details.
|
|
114
|
+
"""
|
|
115
|
+
test_file.write_text(content)
|
|
116
|
+
|
|
117
|
+
updated = update_references_in_file(str(test_file), "oldname", "newname")
|
|
118
|
+
|
|
119
|
+
assert updated
|
|
120
|
+
new_content = test_file.read_text()
|
|
121
|
+
assert "newname" in new_content
|
|
122
|
+
assert "oldname" not in new_content
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def test_move_command_dry_run():
|
|
126
|
+
"""Test mv command in dry run mode."""
|
|
127
|
+
with tempfile.TemporaryDirectory() as tmpdir:
|
|
128
|
+
os.chdir(tmpdir)
|
|
129
|
+
|
|
130
|
+
# Create source file
|
|
131
|
+
source = Path("source.rst")
|
|
132
|
+
source.write_text("Source content")
|
|
133
|
+
|
|
134
|
+
# Create file that references it
|
|
135
|
+
ref_file = Path("index.rst")
|
|
136
|
+
ref_file.write_text(
|
|
137
|
+
"""
|
|
138
|
+
.. toctree::
|
|
139
|
+
|
|
140
|
+
source
|
|
141
|
+
"""
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
# Mock args
|
|
145
|
+
args = Mock()
|
|
146
|
+
args.source = "source.rst"
|
|
147
|
+
args.destination = "destination.rst"
|
|
148
|
+
args.dry_run = True
|
|
149
|
+
args.no_update_refs = False
|
|
150
|
+
|
|
151
|
+
# Run the move command
|
|
152
|
+
from sphinx_cmd.commands.mv import execute
|
|
153
|
+
|
|
154
|
+
execute(args)
|
|
155
|
+
|
|
156
|
+
# Verify source still exists (dry run)
|
|
157
|
+
assert source.exists()
|
|
158
|
+
assert not Path("destination.rst").exists()
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import tempfile
|
|
3
|
+
from unittest.mock import Mock
|
|
4
|
+
|
|
5
|
+
from sphinx_cmd.commands.rm import (
|
|
6
|
+
build_asset_index,
|
|
7
|
+
execute,
|
|
8
|
+
extract_assets,
|
|
9
|
+
find_rst_files,
|
|
10
|
+
remove_empty_dirs,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def test_rm_command_functionality():
|
|
15
|
+
"""Test the rm command functionality."""
|
|
16
|
+
# Create a temporary directory structure
|
|
17
|
+
with tempfile.TemporaryDirectory() as tmpdir:
|
|
18
|
+
# Create test files
|
|
19
|
+
test_dir = os.path.join(tmpdir, "docs")
|
|
20
|
+
os.makedirs(test_dir)
|
|
21
|
+
|
|
22
|
+
# Create an RST file
|
|
23
|
+
rst_content = """
|
|
24
|
+
Test Page
|
|
25
|
+
=========
|
|
26
|
+
|
|
27
|
+
.. image:: image.png
|
|
28
|
+
.. figure:: figure.jpg
|
|
29
|
+
"""
|
|
30
|
+
with open(os.path.join(test_dir, "test.rst"), "w") as f:
|
|
31
|
+
f.write(rst_content)
|
|
32
|
+
|
|
33
|
+
# Create referenced asset files
|
|
34
|
+
with open(os.path.join(test_dir, "image.png"), "w") as f:
|
|
35
|
+
f.write("fake image")
|
|
36
|
+
with open(os.path.join(test_dir, "figure.jpg"), "w") as f:
|
|
37
|
+
f.write("fake figure")
|
|
38
|
+
|
|
39
|
+
# Test finding RST files
|
|
40
|
+
rst_files = find_rst_files(test_dir)
|
|
41
|
+
assert len(rst_files) == 1
|
|
42
|
+
assert "test.rst" in rst_files[0]
|
|
43
|
+
|
|
44
|
+
# Test extracting assets
|
|
45
|
+
assets = extract_assets(rst_files[0])
|
|
46
|
+
assert len(assets) == 2
|
|
47
|
+
|
|
48
|
+
# Test building asset index
|
|
49
|
+
asset_to_files, file_to_assets, asset_directive_map = build_asset_index(
|
|
50
|
+
rst_files
|
|
51
|
+
)
|
|
52
|
+
assert len(asset_to_files) == 2
|
|
53
|
+
assert len(file_to_assets) == 1
|
|
54
|
+
|
|
55
|
+
# Test dry run with mock args
|
|
56
|
+
args = Mock()
|
|
57
|
+
args.path = test_dir
|
|
58
|
+
args.dry_run = True
|
|
59
|
+
execute(args)
|
|
60
|
+
|
|
61
|
+
# Verify files still exist after dry run
|
|
62
|
+
assert os.path.exists(os.path.join(test_dir, "test.rst"))
|
|
63
|
+
assert os.path.exists(os.path.join(test_dir, "image.png"))
|
|
64
|
+
assert os.path.exists(os.path.join(test_dir, "figure.jpg"))
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def test_empty_directory_removal():
|
|
68
|
+
"""Test that empty directories are properly removed."""
|
|
69
|
+
with tempfile.TemporaryDirectory() as tmpdir:
|
|
70
|
+
# Create a nested directory structure
|
|
71
|
+
docs_dir = os.path.join(tmpdir, "docs")
|
|
72
|
+
nested_dir = os.path.join(docs_dir, "nested")
|
|
73
|
+
nested_subdir = os.path.join(nested_dir, "subdir")
|
|
74
|
+
os.makedirs(nested_subdir)
|
|
75
|
+
|
|
76
|
+
# Create an RST file in the nested subdirectory
|
|
77
|
+
rst_path = os.path.join(nested_subdir, "test.rst")
|
|
78
|
+
rst_content = """Test page
|
|
79
|
+
=========
|
|
80
|
+
|
|
81
|
+
.. image:: image.png
|
|
82
|
+
"""
|
|
83
|
+
with open(rst_path, "w") as f:
|
|
84
|
+
f.write(rst_content)
|
|
85
|
+
|
|
86
|
+
# Create an image in the same directory
|
|
87
|
+
img_path = os.path.join(nested_subdir, "image.png")
|
|
88
|
+
with open(img_path, "w") as f:
|
|
89
|
+
f.write("fake image")
|
|
90
|
+
|
|
91
|
+
# Verify that directories exist before the test
|
|
92
|
+
assert os.path.exists(docs_dir)
|
|
93
|
+
assert os.path.exists(nested_dir)
|
|
94
|
+
assert os.path.exists(nested_subdir)
|
|
95
|
+
assert os.path.exists(rst_path)
|
|
96
|
+
assert os.path.exists(img_path)
|
|
97
|
+
|
|
98
|
+
# Execute the rm command
|
|
99
|
+
args = Mock()
|
|
100
|
+
args.path = docs_dir
|
|
101
|
+
args.dry_run = False
|
|
102
|
+
|
|
103
|
+
# Execute the command to remove files
|
|
104
|
+
execute(args)
|
|
105
|
+
|
|
106
|
+
# Verify that the files were removed
|
|
107
|
+
assert not os.path.exists(rst_path)
|
|
108
|
+
assert not os.path.exists(img_path)
|
|
109
|
+
|
|
110
|
+
# Verify that all directories were removed
|
|
111
|
+
assert not os.path.exists(nested_subdir)
|
|
112
|
+
assert not os.path.exists(nested_dir)
|
|
113
|
+
assert not os.path.exists(docs_dir)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def test_non_empty_directory_retained():
|
|
117
|
+
"""Test that non-empty directories are not removed."""
|
|
118
|
+
with tempfile.TemporaryDirectory() as tmpdir:
|
|
119
|
+
# Create a nested directory structure
|
|
120
|
+
docs_dir = os.path.join(tmpdir, "docs")
|
|
121
|
+
nested_dir = os.path.join(docs_dir, "nested")
|
|
122
|
+
nested_subdir = os.path.join(nested_dir, "subdir")
|
|
123
|
+
os.makedirs(nested_subdir)
|
|
124
|
+
|
|
125
|
+
# Create an RST file in the nested subdirectory
|
|
126
|
+
rst_path = os.path.join(nested_subdir, "test.rst")
|
|
127
|
+
with open(rst_path, "w") as f:
|
|
128
|
+
f.write("Test page\n=========\n\n.. image:: image.png")
|
|
129
|
+
|
|
130
|
+
# Create an image in the same directory
|
|
131
|
+
img_path = os.path.join(nested_subdir, "image.png")
|
|
132
|
+
with open(img_path, "w") as f:
|
|
133
|
+
f.write("fake image")
|
|
134
|
+
|
|
135
|
+
# Create another file in the parent directory that should be retained
|
|
136
|
+
other_file = os.path.join(nested_dir, "other.txt")
|
|
137
|
+
with open(other_file, "w") as f:
|
|
138
|
+
f.write("This file should be retained")
|
|
139
|
+
|
|
140
|
+
# Execute the rm command
|
|
141
|
+
args = Mock()
|
|
142
|
+
args.path = docs_dir
|
|
143
|
+
args.dry_run = False
|
|
144
|
+
|
|
145
|
+
# Execute the command to remove files
|
|
146
|
+
execute(args)
|
|
147
|
+
|
|
148
|
+
# Verify that subdir was removed but nested_dir was retained
|
|
149
|
+
assert not os.path.exists(nested_subdir)
|
|
150
|
+
assert os.path.exists(nested_dir)
|
|
151
|
+
assert os.path.exists(docs_dir)
|
|
152
|
+
assert os.path.exists(other_file)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def test_remove_empty_dirs_function():
|
|
156
|
+
"""Test the remove_empty_dirs function directly."""
|
|
157
|
+
with tempfile.TemporaryDirectory() as tmpdir:
|
|
158
|
+
# Create a nested directory structure
|
|
159
|
+
parent_dir = os.path.join(tmpdir, "parent")
|
|
160
|
+
child_dir = os.path.join(parent_dir, "child")
|
|
161
|
+
grandchild_dir = os.path.join(child_dir, "grandchild")
|
|
162
|
+
os.makedirs(grandchild_dir)
|
|
163
|
+
|
|
164
|
+
# Create a separate directory that should not be removed
|
|
165
|
+
other_dir = os.path.join(parent_dir, "other")
|
|
166
|
+
os.makedirs(other_dir)
|
|
167
|
+
with open(os.path.join(other_dir, "file.txt"), "w") as f:
|
|
168
|
+
f.write("Keep this directory")
|
|
169
|
+
|
|
170
|
+
# Test dry run
|
|
171
|
+
affected_dirs = {child_dir, grandchild_dir}
|
|
172
|
+
deleted_dirs = remove_empty_dirs(affected_dirs, parent_dir, dry_run=True)
|
|
173
|
+
|
|
174
|
+
# Verify nothing was deleted in dry run
|
|
175
|
+
assert os.path.exists(grandchild_dir)
|
|
176
|
+
assert os.path.exists(child_dir)
|
|
177
|
+
assert os.path.exists(parent_dir)
|
|
178
|
+
assert len(deleted_dirs) == 0
|
|
179
|
+
|
|
180
|
+
# Test actual removal
|
|
181
|
+
deleted_dirs = remove_empty_dirs(affected_dirs, parent_dir, dry_run=False)
|
|
182
|
+
|
|
183
|
+
# Verify directories were removed
|
|
184
|
+
assert not os.path.exists(grandchild_dir)
|
|
185
|
+
assert not os.path.exists(child_dir)
|
|
186
|
+
assert os.path.exists(parent_dir) # Parent has 'other' dir so is not empty
|
|
187
|
+
assert os.path.exists(other_dir)
|
|
188
|
+
|
|
189
|
+
# Should have removed exactly 2 dirs
|
|
190
|
+
assert len(deleted_dirs) == 2
|
|
191
|
+
assert grandchild_dir in deleted_dirs
|
|
192
|
+
assert child_dir in deleted_dirs
|
|
193
|
+
|
|
194
|
+
# Now test removal of the original path when empty
|
|
195
|
+
# First remove the file in other_dir
|
|
196
|
+
os.remove(os.path.join(other_dir, "file.txt"))
|
|
197
|
+
|
|
198
|
+
# Then remove the now-empty other_dir
|
|
199
|
+
affected_dirs = {other_dir}
|
|
200
|
+
deleted_dirs = remove_empty_dirs(affected_dirs, parent_dir, dry_run=False)
|
|
201
|
+
|
|
202
|
+
# Now parent_dir should also be removed since it's empty
|
|
203
|
+
assert not os.path.exists(other_dir)
|
|
204
|
+
assert not os.path.exists(parent_dir)
|
|
205
|
+
assert len(deleted_dirs) == 2
|
|
206
|
+
assert other_dir in deleted_dirs
|
|
207
|
+
assert parent_dir in deleted_dirs
|
|
@@ -1,69 +0,0 @@
|
|
|
1
|
-
import os
|
|
2
|
-
import tempfile
|
|
3
|
-
from unittest.mock import Mock
|
|
4
|
-
|
|
5
|
-
from sphinx_cmd.commands.rm import (
|
|
6
|
-
build_asset_index,
|
|
7
|
-
execute,
|
|
8
|
-
extract_assets,
|
|
9
|
-
find_rst_files,
|
|
10
|
-
)
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
def test_rm_command():
|
|
14
|
-
"""Test the rm command functionality."""
|
|
15
|
-
# Create a temporary directory structure
|
|
16
|
-
with tempfile.TemporaryDirectory() as tmpdir:
|
|
17
|
-
# Create test files
|
|
18
|
-
test_dir = os.path.join(tmpdir, "docs")
|
|
19
|
-
os.makedirs(test_dir)
|
|
20
|
-
|
|
21
|
-
# Create an RST file
|
|
22
|
-
rst_content = """
|
|
23
|
-
Test Page
|
|
24
|
-
=========
|
|
25
|
-
|
|
26
|
-
.. image:: image.png
|
|
27
|
-
.. figure:: figure.jpg
|
|
28
|
-
"""
|
|
29
|
-
with open(os.path.join(test_dir, "test.rst"), "w") as f:
|
|
30
|
-
f.write(rst_content)
|
|
31
|
-
|
|
32
|
-
# Create referenced asset files
|
|
33
|
-
with open(os.path.join(test_dir, "image.png"), "w") as f:
|
|
34
|
-
f.write("fake image")
|
|
35
|
-
with open(os.path.join(test_dir, "figure.jpg"), "w") as f:
|
|
36
|
-
f.write("fake figure")
|
|
37
|
-
|
|
38
|
-
# Test finding RST files
|
|
39
|
-
rst_files = find_rst_files(test_dir)
|
|
40
|
-
assert len(rst_files) == 1
|
|
41
|
-
assert "test.rst" in rst_files[0]
|
|
42
|
-
|
|
43
|
-
# Test extracting assets
|
|
44
|
-
assets = extract_assets(rst_files[0])
|
|
45
|
-
assert len(assets) == 2
|
|
46
|
-
|
|
47
|
-
# Test building asset index
|
|
48
|
-
asset_to_files, file_to_assets, asset_directive_map = build_asset_index(
|
|
49
|
-
rst_files
|
|
50
|
-
)
|
|
51
|
-
assert len(asset_to_files) == 2
|
|
52
|
-
assert len(file_to_assets) == 1
|
|
53
|
-
|
|
54
|
-
# Test dry run with mock args
|
|
55
|
-
args = Mock()
|
|
56
|
-
args.path = test_dir
|
|
57
|
-
args.dry_run = True
|
|
58
|
-
execute(args)
|
|
59
|
-
|
|
60
|
-
# Verify files still exist after dry run
|
|
61
|
-
assert os.path.exists(os.path.join(test_dir, "test.rst"))
|
|
62
|
-
assert os.path.exists(os.path.join(test_dir, "image.png"))
|
|
63
|
-
assert os.path.exists(os.path.join(test_dir, "figure.jpg"))
|
|
64
|
-
|
|
65
|
-
print("All tests passed!")
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
if __name__ == "__main__":
|
|
69
|
-
test_rm_command()
|
|
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
|