sphinx-cmd 0.3.0__tar.gz → 0.4.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.3.0/sphinx_cmd.egg-info → sphinx_cmd-0.4.0}/PKG-INFO +50 -15
  2. {sphinx_cmd-0.3.0 → sphinx_cmd-0.4.0}/README.md +48 -14
  3. {sphinx_cmd-0.3.0 → sphinx_cmd-0.4.0}/pyproject.toml +1 -0
  4. {sphinx_cmd-0.3.0 → sphinx_cmd-0.4.0}/sphinx_cmd/__init__.py +1 -1
  5. {sphinx_cmd-0.3.0 → sphinx_cmd-0.4.0}/sphinx_cmd/cli.py +26 -12
  6. {sphinx_cmd-0.3.0 → sphinx_cmd-0.4.0}/sphinx_cmd/commands/mv.py +23 -9
  7. {sphinx_cmd-0.3.0 → sphinx_cmd-0.4.0}/sphinx_cmd/commands/rm.py +114 -17
  8. sphinx_cmd-0.4.0/sphinx_cmd/config.py +161 -0
  9. {sphinx_cmd-0.3.0 → sphinx_cmd-0.4.0/sphinx_cmd.egg-info}/PKG-INFO +50 -15
  10. {sphinx_cmd-0.3.0 → sphinx_cmd-0.4.0}/sphinx_cmd.egg-info/requires.txt +1 -0
  11. {sphinx_cmd-0.3.0 → sphinx_cmd-0.4.0}/tests/test_cli.py +18 -0
  12. sphinx_cmd-0.4.0/tests/test_config.py +191 -0
  13. {sphinx_cmd-0.3.0 → sphinx_cmd-0.4.0}/tests/test_custom_directives.py +4 -5
  14. {sphinx_cmd-0.3.0 → sphinx_cmd-0.4.0}/tests/test_integration.py +2 -2
  15. {sphinx_cmd-0.3.0 → sphinx_cmd-0.4.0}/tests/test_mv.py +3 -1
  16. {sphinx_cmd-0.3.0 → sphinx_cmd-0.4.0}/tests/test_rm.py +124 -14
  17. sphinx_cmd-0.3.0/sphinx_cmd/config.py +0 -81
  18. sphinx_cmd-0.3.0/tests/test_config.py +0 -79
  19. {sphinx_cmd-0.3.0 → sphinx_cmd-0.4.0}/LICENSE +0 -0
  20. {sphinx_cmd-0.3.0 → sphinx_cmd-0.4.0}/MANIFEST.in +0 -0
  21. {sphinx_cmd-0.3.0 → sphinx_cmd-0.4.0}/setup.cfg +0 -0
  22. {sphinx_cmd-0.3.0 → sphinx_cmd-0.4.0}/sphinx_cmd/commands/__init__.py +0 -0
  23. {sphinx_cmd-0.3.0 → sphinx_cmd-0.4.0}/sphinx_cmd/py.typed +0 -0
  24. {sphinx_cmd-0.3.0 → sphinx_cmd-0.4.0}/sphinx_cmd.egg-info/SOURCES.txt +0 -0
  25. {sphinx_cmd-0.3.0 → sphinx_cmd-0.4.0}/sphinx_cmd.egg-info/dependency_links.txt +0 -0
  26. {sphinx_cmd-0.3.0 → sphinx_cmd-0.4.0}/sphinx_cmd.egg-info/entry_points.txt +0 -0
  27. {sphinx_cmd-0.3.0 → sphinx_cmd-0.4.0}/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.3.0
3
+ Version: 0.4.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
@@ -23,6 +23,7 @@ Requires-Dist: black; extra == "dev"
23
23
  Requires-Dist: flake8; extra == "dev"
24
24
  Requires-Dist: mypy; extra == "dev"
25
25
  Requires-Dist: isort; extra == "dev"
26
+ Requires-Dist: pre-commit; extra == "dev"
26
27
  Provides-Extra: test
27
28
  Requires-Dist: pytest>=7.0.0; extra == "test"
28
29
  Dynamic: license-file
@@ -31,6 +32,9 @@ Dynamic: license-file
31
32
 
32
33
  A collection of command-line tools for managing Sphinx documentation.
33
34
 
35
+ [![PyPI version](https://img.shields.io/pypi/v/sphinx-cmd.svg)](https://pypi.python.org/pypi/sphinx-cmd)
36
+ [![Downloads](https://static.pepy.tech/badge/sphinx-cmd/month)](https://pepy.tech/project/sphinx-cmd)
37
+
34
38
  ## Installation
35
39
 
36
40
  ```bash
@@ -41,6 +45,23 @@ pip install sphinx-cmd
41
45
 
42
46
  The `sphinx-cmd` tool provides subcommands for different Sphinx documentation management tasks.
43
47
 
48
+ ### Global Options
49
+
50
+ Options that apply to all commands:
51
+
52
+ ```bash
53
+ # Specify a context path (directory containing conf.py)
54
+ sphinx-cmd --context /path/to/docs COMMAND
55
+
56
+ # Dry run to preview changes without executing them
57
+ sphinx-cmd --dry-run COMMAND
58
+
59
+ # Process additional directives beyond defaults
60
+ sphinx-cmd --directives drawio-figure,drawio-image COMMAND
61
+ ```
62
+
63
+ By default, `sphinx-cmd` will automatically detect the context of your documentation project by finding the nearest `conf.py` file in the directory tree.
64
+
44
65
  ### `sphinx-cmd rm`
45
66
 
46
67
  Delete unused .rst files and their unique assets (images, includes, etc) if not used elsewhere.
@@ -49,13 +70,14 @@ Delete unused .rst files and their unique assets (images, includes, etc) if not
49
70
  # Remove files and assets
50
71
  sphinx-cmd rm path/to/docs
51
72
 
52
- # Dry run to preview deletions
53
- sphinx-cmd rm path/to/docs --dry-run
73
+ # Using global options
74
+ sphinx-cmd --dry-run --directives drawio-figure,drawio-image rm path/to/docs
54
75
  ```
55
76
 
56
- ### Features
77
+ #### Features
57
78
 
58
79
  - Configure custom directives to be processed
80
+ - Only deletes unused unique assets in the provided context path
59
81
 
60
82
  ### `sphinx-cmd mv`
61
83
 
@@ -68,11 +90,11 @@ sphinx-cmd mv old-file.rst new-file.rst
68
90
  # Move to a different directory
69
91
  sphinx-cmd mv chapter1.rst topics/chapter1.rst
70
92
 
71
- # Preview the move without making changes
72
- sphinx-cmd mv old-file.rst new-file.rst --dry-run
73
-
74
93
  # Move without updating references
75
94
  sphinx-cmd mv old-file.rst new-file.rst --no-update-refs
95
+
96
+ # Using global options
97
+ sphinx-cmd --dry-run --directives drawio-figure mv old-file.rst new-file.rst
76
98
  ```
77
99
 
78
100
  #### Features
@@ -82,21 +104,32 @@ sphinx-cmd mv old-file.rst new-file.rst --no-update-refs
82
104
  - Updates `include` and `literalinclude` directives
83
105
  - Handles relative paths correctly
84
106
  - Preserves file relationships
107
+ - Configure custom directives to be processed
85
108
 
86
109
  ## Configuration
87
110
 
88
- You can add custom directives to be processed by creating a `.sphinx-cmd.toml` file in your home directory.
111
+ You can add custom directives to be processed in two ways:
112
+
113
+ ### 1. Command Line
114
+
115
+ Use the `--directives` global option with any command to add custom directives for a single run:
116
+
117
+ ```bash
118
+ sphinx-cmd --directives drawio-figure,drawio-image rm path/to/docs
119
+ ```
120
+
121
+ ### 2. Configuration File
89
122
 
90
- Add your custom directives to `[directives]` with their respective regex patterns, for example:
123
+ Create a `.sphinx-cmd.toml` file in your home directory with your custom directives:
91
124
 
92
125
  ```toml
93
- [directives]
94
- drawio-figure = "^\\s*\\.\\.\\s+drawio-figure::\\s+(.+)$"
95
- drawio-image = "^\\s*\\.\\.\\s+drawio-image::\\s+(.+)$"
126
+ directives = [
127
+ "drawio-figure",
128
+ "drawio-image"
129
+ ]
96
130
  ```
97
131
 
98
- > [!NOTE]
99
- > Each regex pattern must include a capturing group `(.+)` to extract the file path.
132
+ Command line directives will be combined with those in the configuration file and the built-in defaults.
100
133
 
101
134
 
102
135
  ## Development
@@ -114,6 +147,7 @@ pytest
114
147
 
115
148
  # Run linters
116
149
  black sphinx_cmd tests
150
+ isort sphinx_cmd tests
117
151
  flake8 sphinx_cmd tests
118
152
  mypy sphinx_cmd
119
153
 
@@ -123,7 +157,7 @@ sphinx-cmd rm --help
123
157
  sphinx-cmd mv --help
124
158
  ```
125
159
 
126
- ## Adding New Commands
160
+ ### Adding New Commands
127
161
 
128
162
  The architecture is designed to make adding new commands easy:
129
163
 
@@ -131,6 +165,7 @@ The architecture is designed to make adding new commands easy:
131
165
  2. Implement an `execute(args)` function in your new file
132
166
  3. Import the command in `sphinx_cmd/cli.py`
133
167
  4. Add a new subparser for your command in `create_parser()`
168
+ 5. Create new tests (e.g., `tests/test_new_command.py`)
134
169
 
135
170
  ## License
136
171
 
@@ -2,6 +2,9 @@
2
2
 
3
3
  A collection of command-line tools for managing Sphinx documentation.
4
4
 
5
+ [![PyPI version](https://img.shields.io/pypi/v/sphinx-cmd.svg)](https://pypi.python.org/pypi/sphinx-cmd)
6
+ [![Downloads](https://static.pepy.tech/badge/sphinx-cmd/month)](https://pepy.tech/project/sphinx-cmd)
7
+
5
8
  ## Installation
6
9
 
7
10
  ```bash
@@ -12,6 +15,23 @@ pip install sphinx-cmd
12
15
 
13
16
  The `sphinx-cmd` tool provides subcommands for different Sphinx documentation management tasks.
14
17
 
18
+ ### Global Options
19
+
20
+ Options that apply to all commands:
21
+
22
+ ```bash
23
+ # Specify a context path (directory containing conf.py)
24
+ sphinx-cmd --context /path/to/docs COMMAND
25
+
26
+ # Dry run to preview changes without executing them
27
+ sphinx-cmd --dry-run COMMAND
28
+
29
+ # Process additional directives beyond defaults
30
+ sphinx-cmd --directives drawio-figure,drawio-image COMMAND
31
+ ```
32
+
33
+ By default, `sphinx-cmd` will automatically detect the context of your documentation project by finding the nearest `conf.py` file in the directory tree.
34
+
15
35
  ### `sphinx-cmd rm`
16
36
 
17
37
  Delete unused .rst files and their unique assets (images, includes, etc) if not used elsewhere.
@@ -20,13 +40,14 @@ Delete unused .rst files and their unique assets (images, includes, etc) if not
20
40
  # Remove files and assets
21
41
  sphinx-cmd rm path/to/docs
22
42
 
23
- # Dry run to preview deletions
24
- sphinx-cmd rm path/to/docs --dry-run
43
+ # Using global options
44
+ sphinx-cmd --dry-run --directives drawio-figure,drawio-image rm path/to/docs
25
45
  ```
26
46
 
27
- ### Features
47
+ #### Features
28
48
 
29
49
  - Configure custom directives to be processed
50
+ - Only deletes unused unique assets in the provided context path
30
51
 
31
52
  ### `sphinx-cmd mv`
32
53
 
@@ -39,11 +60,11 @@ sphinx-cmd mv old-file.rst new-file.rst
39
60
  # Move to a different directory
40
61
  sphinx-cmd mv chapter1.rst topics/chapter1.rst
41
62
 
42
- # Preview the move without making changes
43
- sphinx-cmd mv old-file.rst new-file.rst --dry-run
44
-
45
63
  # Move without updating references
46
64
  sphinx-cmd mv old-file.rst new-file.rst --no-update-refs
65
+
66
+ # Using global options
67
+ sphinx-cmd --dry-run --directives drawio-figure mv old-file.rst new-file.rst
47
68
  ```
48
69
 
49
70
  #### Features
@@ -53,21 +74,32 @@ sphinx-cmd mv old-file.rst new-file.rst --no-update-refs
53
74
  - Updates `include` and `literalinclude` directives
54
75
  - Handles relative paths correctly
55
76
  - Preserves file relationships
77
+ - Configure custom directives to be processed
56
78
 
57
79
  ## Configuration
58
80
 
59
- You can add custom directives to be processed by creating a `.sphinx-cmd.toml` file in your home directory.
81
+ You can add custom directives to be processed in two ways:
82
+
83
+ ### 1. Command Line
84
+
85
+ Use the `--directives` global option with any command to add custom directives for a single run:
86
+
87
+ ```bash
88
+ sphinx-cmd --directives drawio-figure,drawio-image rm path/to/docs
89
+ ```
90
+
91
+ ### 2. Configuration File
60
92
 
61
- Add your custom directives to `[directives]` with their respective regex patterns, for example:
93
+ Create a `.sphinx-cmd.toml` file in your home directory with your custom directives:
62
94
 
63
95
  ```toml
64
- [directives]
65
- drawio-figure = "^\\s*\\.\\.\\s+drawio-figure::\\s+(.+)$"
66
- drawio-image = "^\\s*\\.\\.\\s+drawio-image::\\s+(.+)$"
96
+ directives = [
97
+ "drawio-figure",
98
+ "drawio-image"
99
+ ]
67
100
  ```
68
101
 
69
- > [!NOTE]
70
- > Each regex pattern must include a capturing group `(.+)` to extract the file path.
102
+ Command line directives will be combined with those in the configuration file and the built-in defaults.
71
103
 
72
104
 
73
105
  ## Development
@@ -85,6 +117,7 @@ pytest
85
117
 
86
118
  # Run linters
87
119
  black sphinx_cmd tests
120
+ isort sphinx_cmd tests
88
121
  flake8 sphinx_cmd tests
89
122
  mypy sphinx_cmd
90
123
 
@@ -94,7 +127,7 @@ sphinx-cmd rm --help
94
127
  sphinx-cmd mv --help
95
128
  ```
96
129
 
97
- ## Adding New Commands
130
+ ### Adding New Commands
98
131
 
99
132
  The architecture is designed to make adding new commands easy:
100
133
 
@@ -102,6 +135,7 @@ The architecture is designed to make adding new commands easy:
102
135
  2. Implement an `execute(args)` function in your new file
103
136
  3. Import the command in `sphinx_cmd/cli.py`
104
137
  4. Add a new subparser for your command in `create_parser()`
138
+ 5. Create new tests (e.g., `tests/test_new_command.py`)
105
139
 
106
140
  ## License
107
141
 
@@ -37,6 +37,7 @@ dev = [
37
37
  "flake8",
38
38
  "mypy",
39
39
  "isort",
40
+ "pre-commit",
40
41
  ]
41
42
  test = [
42
43
  "pytest>=7.0.0",
@@ -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.3.0"
4
+ __version__ = "0.4.0"
@@ -4,6 +4,7 @@ Main CLI entry point for sphinx-cmd with subcommands.
4
4
  """
5
5
 
6
6
  import argparse
7
+ import os
7
8
  import sys
8
9
 
9
10
  from sphinx_cmd import __version__
@@ -21,6 +22,26 @@ def create_parser():
21
22
  "--version", action="version", version=f"%(prog)s {__version__}"
22
23
  )
23
24
 
25
+ # Add global options
26
+ parser.add_argument(
27
+ "--context",
28
+ "-c",
29
+ help="Path to Sphinx documentation context"
30
+ "(will auto-detect nearest conf.py by default)",
31
+ )
32
+ parser.add_argument(
33
+ "-n",
34
+ "--dry-run",
35
+ action="store_true",
36
+ help="Preview operations without making any changes",
37
+ )
38
+ parser.add_argument(
39
+ "--directives",
40
+ type=lambda s: [x.strip() for x in s.split(",")],
41
+ help="Additional directives to process as comma-separated list"
42
+ " (e.g. 'drawio-figure,drawio-image')",
43
+ )
44
+
24
45
  # Create subparsers for subcommands
25
46
  subparsers = parser.add_subparsers(
26
47
  dest="command", help="Available commands", metavar="COMMAND"
@@ -33,12 +54,6 @@ def create_parser():
33
54
  rm_parser.add_argument(
34
55
  "path", help="Path to a single .rst file or a directory of .rst files"
35
56
  )
36
- rm_parser.add_argument(
37
- "-n",
38
- "--dry-run",
39
- action="store_true",
40
- help="Preview deletions without removing files",
41
- )
42
57
  rm_parser.set_defaults(command_name="rm")
43
58
 
44
59
  # Add 'mv' subcommand
@@ -47,12 +62,6 @@ def create_parser():
47
62
  )
48
63
  mv_parser.add_argument("source", help="Source file to move")
49
64
  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
65
  mv_parser.add_argument(
57
66
  "--no-update-refs",
58
67
  action="store_true",
@@ -73,6 +82,11 @@ def main():
73
82
  parser.print_help()
74
83
  sys.exit(1)
75
84
 
85
+ # If context path is provided, check that it exists
86
+ if args.context and not os.path.exists(args.context):
87
+ print(f"Error: Context path does not exist: {args.context}", file=sys.stderr)
88
+ sys.exit(1)
89
+
76
90
  # Import and execute the appropriate command
77
91
  try:
78
92
  if args.command_name == "rm":
@@ -7,7 +7,7 @@ import re
7
7
  import shutil
8
8
  from collections import defaultdict
9
9
  from pathlib import Path
10
- from typing import Dict, List, Tuple
10
+ from typing import Dict, List, Optional, Tuple
11
11
 
12
12
  # Regex patterns for different types of references in reStructuredText
13
13
  REFERENCE_PATTERNS = {
@@ -41,7 +41,9 @@ def find_all_rst_files(root_path: str) -> List[str]:
41
41
  return rst_files
42
42
 
43
43
 
44
- def extract_references(file_path: str) -> Dict[str, List[str]]:
44
+ def extract_references(
45
+ file_path: str, context_path: Optional[str] = None
46
+ ) -> Dict[str, List[str]]:
45
47
  """Extract all file references from an .rst file."""
46
48
  references = defaultdict(list)
47
49
 
@@ -78,7 +80,7 @@ def extract_references(file_path: str) -> Dict[str, List[str]]:
78
80
 
79
81
 
80
82
  def find_files_referencing(
81
- target_file: str, all_files: List[str]
83
+ target_file: str, all_files: List[str], context_path: Optional[str] = None
82
84
  ) -> List[Tuple[str, str]]:
83
85
  """Find all files that reference the target file."""
84
86
  referencing_files = []
@@ -90,7 +92,8 @@ def find_files_referencing(
90
92
  continue
91
93
 
92
94
  try:
93
- references = extract_references(file_path)
95
+ # Extract references using context from conf.py if provided
96
+ references = extract_references(file_path, context_path=context_path)
94
97
 
95
98
  for ref_type, ref_list in references.items():
96
99
  for ref in ref_list:
@@ -166,7 +169,11 @@ def update_references_in_file(file_path: str, old_ref: str, new_ref: str) -> boo
166
169
 
167
170
 
168
171
  def move_rst_file(
169
- source: str, destination: str, update_references: bool = True, dry_run: bool = False
172
+ source: str,
173
+ destination: str,
174
+ update_references: bool = True,
175
+ dry_run: bool = False,
176
+ context_path: Optional[str] = None,
170
177
  ) -> None:
171
178
  """Move an RST file and optionally update all references to it."""
172
179
  source_path = Path(source).resolve()
@@ -208,8 +215,10 @@ def move_rst_file(
208
215
  root_dir = Path.cwd() # Or use a smarter root detection
209
216
  all_files = find_all_rst_files(str(root_dir))
210
217
 
211
- # Find files that reference the moved file
212
- referencing_files = find_files_referencing(str(source_rel), all_files)
218
+ # Find files that reference the moved file, using context if provided
219
+ referencing_files = find_files_referencing(
220
+ str(source_rel), all_files, context_path=context_path
221
+ )
213
222
 
214
223
  if referencing_files:
215
224
  print(f"\nUpdating references in {len(referencing_files)} file(s):")
@@ -241,15 +250,20 @@ def execute(args):
241
250
  update_refs = getattr(args, "no_update_refs", False)
242
251
  update_references = not update_refs
243
252
 
253
+ # Get global options
254
+ context_path = getattr(args, "context", None)
255
+ dry_run = getattr(args, "dry_run", False)
256
+
244
257
  # Perform the move
245
258
  move_rst_file(
246
259
  args.source,
247
260
  args.destination,
248
261
  update_references=update_references,
249
- dry_run=getattr(args, "dry_run", False),
262
+ dry_run=dry_run,
263
+ context_path=context_path,
250
264
  )
251
265
 
252
- if not getattr(args, "dry_run", False):
266
+ if not dry_run:
253
267
  print("\n✓ Move completed successfully!")
254
268
  else:
255
269
  print("\n[Dry run complete - no files were actually moved]")
@@ -21,7 +21,7 @@ def find_rst_files(path):
21
21
  return rst_files
22
22
 
23
23
 
24
- def extract_assets(file_path, visited=None):
24
+ def extract_assets(file_path, visited=None, cli_directives=None, context_path=None):
25
25
  """Extract asset references from an .rst file, recursively parsing includes."""
26
26
  if visited is None:
27
27
  visited = set()
@@ -33,7 +33,7 @@ def extract_assets(file_path, visited=None):
33
33
  visited.add(abs_path)
34
34
 
35
35
  asset_directives = {}
36
- directive_patterns = get_directive_patterns()
36
+ directive_patterns = get_directive_patterns(cli_directives, context_path)
37
37
 
38
38
  # If file doesn't exist, skip it
39
39
  if not os.path.exists(file_path):
@@ -52,7 +52,10 @@ def extract_assets(file_path, visited=None):
52
52
  if directive == "include":
53
53
  # Recursively extract assets from included files
54
54
  included_assets = extract_assets(
55
- asset_full_path, visited.copy()
55
+ asset_full_path,
56
+ visited.copy(),
57
+ cli_directives,
58
+ context_path,
56
59
  )
57
60
  asset_directives.update(included_assets)
58
61
 
@@ -63,14 +66,16 @@ def extract_assets(file_path, visited=None):
63
66
  return asset_directives
64
67
 
65
68
 
66
- def build_asset_index(rst_files):
69
+ def build_asset_index(rst_files, cli_directives=None, context_path=None):
67
70
  """Build an index of assets and which files reference them."""
68
71
  asset_to_files = defaultdict(set)
69
72
  file_to_assets = {}
70
73
  asset_directive_map = {}
71
74
 
72
75
  for rst in rst_files:
73
- asset_directives = extract_assets(rst)
76
+ asset_directives = extract_assets(
77
+ rst, cli_directives=cli_directives, context_path=context_path
78
+ )
74
79
  file_to_assets[rst] = set(asset_directives.keys())
75
80
  for asset, directive in asset_directives.items():
76
81
  asset_to_files[asset].add(rst)
@@ -78,7 +83,9 @@ def build_asset_index(rst_files):
78
83
  return asset_to_files, file_to_assets, asset_directive_map
79
84
 
80
85
 
81
- def get_transitive_includes(file_path, visited=None):
86
+ def get_transitive_includes(
87
+ file_path, visited=None, cli_directives=None, context_path=None
88
+ ):
82
89
  """Get all files included transitively from a file."""
83
90
  if visited is None:
84
91
  visited = set()
@@ -94,7 +101,7 @@ def get_transitive_includes(file_path, visited=None):
94
101
  if not os.path.exists(file_path):
95
102
  return includes
96
103
 
97
- directive_patterns = get_directive_patterns()
104
+ directive_patterns = get_directive_patterns(cli_directives, context_path)
98
105
 
99
106
  try:
100
107
  with open(file_path, encoding="utf-8") as f:
@@ -110,7 +117,12 @@ def get_transitive_includes(file_path, visited=None):
110
117
  includes.add(include_full_path)
111
118
  # Recursively get includes from the included file
112
119
  includes.update(
113
- get_transitive_includes(include_full_path, visited.copy())
120
+ get_transitive_includes(
121
+ include_full_path,
122
+ visited.copy(),
123
+ cli_directives,
124
+ context_path,
125
+ )
114
126
  )
115
127
  except Exception as e:
116
128
  print(f"Warning: Could not read {file_path}: {e}")
@@ -119,12 +131,22 @@ def get_transitive_includes(file_path, visited=None):
119
131
 
120
132
 
121
133
  def delete_unused_assets_and_pages(
122
- asset_to_files, file_to_assets, asset_directive_map, dry_run=False
134
+ asset_to_files,
135
+ file_to_assets,
136
+ asset_directive_map,
137
+ dry_run=False,
138
+ context_path=None,
123
139
  ):
124
- """Delete files and their unique assets if not used elsewhere."""
140
+ """
141
+ Delete files and their unique assets if not used elsewhere.
142
+
143
+ If context_path is provided, only files within that context will be removed
144
+ for safety reasons.
145
+ """
125
146
  deleted_pages = []
126
147
  deleted_assets = []
127
148
  affected_dirs = set()
149
+ would_delete_something = False # Flag to track if anything would be deleted
128
150
 
129
151
  # Track which files have been processed to avoid duplicates
130
152
  processed_files = set()
@@ -157,6 +179,22 @@ def delete_unused_assets_and_pages(
157
179
  for asset in file_unused_assets:
158
180
  directive = asset_directive_map.get(asset, "asset")
159
181
  if os.path.exists(asset) and asset not in deleted_assets:
182
+ # Check if asset is within context path if context is provided
183
+ is_in_context = True
184
+ if context_path:
185
+ asset_abs_path = os.path.abspath(asset)
186
+ context_abs_path = os.path.abspath(context_path)
187
+ # Check if the asset path starts with the context path
188
+ is_in_context = asset_abs_path.startswith(context_abs_path)
189
+
190
+ if not is_in_context:
191
+ if dry_run:
192
+ print(
193
+ f"[dry-run] Skipping {directive} (outside context):"
194
+ f" {asset}"
195
+ )
196
+ continue
197
+
160
198
  if dry_run:
161
199
  origin = (
162
200
  " (from include)" if file_to_process != rst_file else ""
@@ -164,6 +202,7 @@ def delete_unused_assets_and_pages(
164
202
  print(
165
203
  f"[dry-run] Would delete {directive}: {asset}{origin}"
166
204
  )
205
+ would_delete_something = True
167
206
  else:
168
207
  affected_dirs.add(os.path.dirname(asset))
169
208
  os.remove(asset)
@@ -171,10 +210,27 @@ def delete_unused_assets_and_pages(
171
210
 
172
211
  # Delete the file if it exists and isn't the main rst file being checked
173
212
  if file_to_process != rst_file and os.path.exists(file_to_process):
213
+ # Check if file is within context path if context is provided
214
+ is_in_context = True
215
+ if context_path:
216
+ file_abs_path = os.path.abspath(file_to_process)
217
+ context_abs_path = os.path.abspath(context_path)
218
+ # Check if the file path starts with the context path
219
+ is_in_context = file_abs_path.startswith(context_abs_path)
220
+
221
+ if not is_in_context:
222
+ if dry_run:
223
+ print(
224
+ f"[dry-run] Skipping included file (outside context):"
225
+ f" {file_to_process}"
226
+ )
227
+ continue
228
+
174
229
  if dry_run:
175
230
  print(
176
231
  f"[dry-run] Would delete included file: {file_to_process}"
177
232
  )
233
+ would_delete_something = True
178
234
  else:
179
235
  affected_dirs.add(os.path.dirname(file_to_process))
180
236
  os.remove(file_to_process)
@@ -182,14 +238,28 @@ def delete_unused_assets_and_pages(
182
238
 
183
239
  # Finally, delete the main rst file
184
240
  if os.path.exists(rst_file):
241
+ # Check if file is within context path if context is provided
242
+ is_in_context = True
243
+ if context_path:
244
+ file_abs_path = os.path.abspath(rst_file)
245
+ context_abs_path = os.path.abspath(context_path)
246
+ # Check if the file path starts with the context path
247
+ is_in_context = file_abs_path.startswith(context_abs_path)
248
+
249
+ if not is_in_context:
250
+ if dry_run:
251
+ print(f"[dry-run] Skipping page (outside context): {rst_file}")
252
+ continue
253
+
185
254
  if dry_run:
186
255
  print(f"[dry-run] Would delete page: {rst_file}")
256
+ would_delete_something = True
187
257
  else:
188
258
  affected_dirs.add(os.path.dirname(rst_file))
189
259
  os.remove(rst_file)
190
260
  deleted_pages.append(rst_file)
191
261
 
192
- return deleted_pages, deleted_assets, affected_dirs
262
+ return deleted_pages, deleted_assets, affected_dirs, would_delete_something
193
263
 
194
264
 
195
265
  def remove_empty_dirs(dirs, original_path, dry_run=False):
@@ -237,16 +307,43 @@ def execute(args):
237
307
  """Execute the rm command."""
238
308
  original_path = os.path.abspath(args.path)
239
309
  rst_files = find_rst_files(args.path)
240
- asset_to_files, file_to_assets, asset_directive_map = build_asset_index(rst_files)
241
- deleted_pages, deleted_assets, affected_dirs = delete_unused_assets_and_pages(
242
- asset_to_files, file_to_assets, asset_directive_map, args.dry_run
310
+
311
+ # Get global options
312
+ context_path = getattr(args, "context", None)
313
+ dry_run = getattr(args, "dry_run", False)
314
+ directives = getattr(args, "directives", None)
315
+
316
+ # Display context information
317
+ if context_path:
318
+ context_abs_path = os.path.abspath(context_path)
319
+ print(f"Context path: {context_abs_path}")
320
+ print("Safety mode: Only files within the context path will be removed")
321
+ else:
322
+ print("Context path not set - all unused files will be removed")
323
+
324
+ asset_to_files, file_to_assets, asset_directive_map = build_asset_index(
325
+ rst_files, cli_directives=directives, context_path=context_path
326
+ )
327
+ deleted_pages, deleted_assets, affected_dirs, would_delete_something = (
328
+ delete_unused_assets_and_pages(
329
+ asset_to_files,
330
+ file_to_assets,
331
+ asset_directive_map,
332
+ dry_run,
333
+ context_path,
334
+ )
243
335
  )
244
336
 
245
337
  deleted_dirs = []
246
338
  if affected_dirs:
247
- deleted_dirs = remove_empty_dirs(affected_dirs, original_path, args.dry_run)
248
-
249
- if not args.dry_run:
339
+ deleted_dirs = remove_empty_dirs(affected_dirs, original_path, dry_run)
340
+
341
+ if dry_run:
342
+ # In dry-run mode, show a summary of what would be deleted
343
+ if not would_delete_something:
344
+ print("\n[dry-run] No unused files found, nothing would be deleted.")
345
+ else:
346
+ # Not in dry-run mode, report what was actually deleted
250
347
  print(f"\nDeleted {len(deleted_assets)} unused asset(s):")
251
348
  for a in deleted_assets:
252
349
  directive = asset_directive_map.get(a, "asset")