sphinx-codelinks 1.0.0__tar.gz → 1.1.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 (21) hide show
  1. {sphinx_codelinks-1.0.0 → sphinx_codelinks-1.1.0}/PKG-INFO +3 -1
  2. {sphinx_codelinks-1.0.0 → sphinx_codelinks-1.1.0}/pyproject.toml +3 -2
  3. {sphinx_codelinks-1.0.0 → sphinx_codelinks-1.1.0}/src/sphinx_codelinks/analyse/analyse.py +1 -1
  4. {sphinx_codelinks-1.0.0 → sphinx_codelinks-1.1.0}/src/sphinx_codelinks/analyse/oneline_parser.py +1 -18
  5. {sphinx_codelinks-1.0.0 → sphinx_codelinks-1.1.0}/src/sphinx_codelinks/analyse/utils.py +123 -9
  6. {sphinx_codelinks-1.0.0 → sphinx_codelinks-1.1.0}/src/sphinx_codelinks/config.py +11 -8
  7. {sphinx_codelinks-1.0.0 → sphinx_codelinks-1.1.0}/src/sphinx_codelinks/needextend_write.py +4 -4
  8. {sphinx_codelinks-1.0.0 → sphinx_codelinks-1.1.0}/src/sphinx_codelinks/source_discover/config.py +10 -3
  9. {sphinx_codelinks-1.0.0 → sphinx_codelinks-1.1.0}/src/sphinx_codelinks/sphinx_extension/directives/src_trace.py +25 -28
  10. {sphinx_codelinks-1.0.0 → sphinx_codelinks-1.1.0}/src/sphinx_codelinks/sphinx_extension/source_tracing.py +29 -6
  11. {sphinx_codelinks-1.0.0 → sphinx_codelinks-1.1.0}/LICENSE +0 -0
  12. {sphinx_codelinks-1.0.0 → sphinx_codelinks-1.1.0}/README.md +0 -0
  13. {sphinx_codelinks-1.0.0 → sphinx_codelinks-1.1.0}/src/sphinx_codelinks/__init__.py +0 -0
  14. {sphinx_codelinks-1.0.0 → sphinx_codelinks-1.1.0}/src/sphinx_codelinks/analyse/models.py +0 -0
  15. {sphinx_codelinks-1.0.0 → sphinx_codelinks-1.1.0}/src/sphinx_codelinks/analyse/projects.py +0 -0
  16. {sphinx_codelinks-1.0.0 → sphinx_codelinks-1.1.0}/src/sphinx_codelinks/cmd.py +0 -0
  17. {sphinx_codelinks-1.0.0 → sphinx_codelinks-1.1.0}/src/sphinx_codelinks/logger.py +0 -0
  18. {sphinx_codelinks-1.0.0 → sphinx_codelinks-1.1.0}/src/sphinx_codelinks/source_discover/source_discover.py +0 -0
  19. {sphinx_codelinks-1.0.0 → sphinx_codelinks-1.1.0}/src/sphinx_codelinks/sphinx_extension/debug.py +0 -0
  20. {sphinx_codelinks-1.0.0 → sphinx_codelinks-1.1.0}/src/sphinx_codelinks/sphinx_extension/html_wrapper.py +0 -0
  21. {sphinx_codelinks-1.0.0 → sphinx_codelinks-1.1.0}/src/sphinx_codelinks/sphinx_extension/ub_sct.css +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sphinx-codelinks
3
- Version: 1.0.0
3
+ Version: 1.1.0
4
4
  Summary: Fast Source Code Traceability for Sphinx-Needs
5
5
  Author-email: team useblocks <info@useblocks.com>
6
6
  Maintainer-email: Marco Heinemann <marco.heinemann@useblocks.com>, Jui-Wen Chen <jui-wen.chen@useblocks.com>
@@ -21,6 +21,8 @@ Requires-Dist: tree-sitter-cpp>=0.23.4
21
21
  Requires-Dist: giturlparse>=0.12.0
22
22
  Requires-Dist: tree-sitter-python>=0.23.6
23
23
  Requires-Dist: tree-sitter~=0.25.1
24
+ Requires-Dist: tree-sitter-c-sharp>=0.23.1
25
+ Requires-Dist: tree-sitter-yaml>=0.7.1
24
26
 
25
27
  # Sphinx CodeLinks
26
28
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "sphinx-codelinks"
3
- version = "1.0.0"
3
+ version = "1.1.0"
4
4
  description = "Fast Source Code Traceability for Sphinx-Needs"
5
5
  authors = [{ name = "team useblocks", email = "info@useblocks.com" }]
6
6
  maintainers = [
@@ -27,7 +27,8 @@ dependencies = [
27
27
  # Compiling issue on manylinux aarch64 image, so install from git instead of Pypi
28
28
  # https://github.com/tree-sitter/py-tree-sitter/issues/386#issuecomment-3101430799
29
29
  "tree-sitter~=0.25.1",
30
-
30
+ "tree-sitter-c-sharp>=0.23.1",
31
+ "tree-sitter-yaml>=0.7.1",
31
32
  ]
32
33
 
33
34
  [build-system]
@@ -322,7 +322,7 @@ class SourceAnalyse:
322
322
  if not filepath:
323
323
  continue
324
324
  tagged_scope: TreeSitterNode | None = utils.find_associated_scope(
325
- src_comment.node
325
+ src_comment.node, self.analyse_config.comment_type
326
326
  )
327
327
  if self.analyse_config.get_need_id_refs:
328
328
  anchors = self.extract_anchors(
@@ -2,12 +2,7 @@ from dataclasses import dataclass
2
2
  from enum import Enum
3
3
  import logging
4
4
 
5
- from sphinx_codelinks.config import (
6
- ESCAPE,
7
- SUPPORTED_COMMENT_TYPES,
8
- UNIX_NEWLINE,
9
- OneLineCommentStyle,
10
- )
5
+ from sphinx_codelinks.config import ESCAPE, UNIX_NEWLINE, OneLineCommentStyle
11
6
 
12
7
  # initialize logger
13
8
  logger = logging.getLogger(__name__)
@@ -204,15 +199,3 @@ def is_newline_in_field(field: str) -> bool:
204
199
  Check if the field contains a new line character.
205
200
  """
206
201
  return UNIX_NEWLINE in field
207
-
208
-
209
- def get_file_types(comment_type: str) -> list[str] | None:
210
- """
211
- Get the list of file types to be discovered.
212
- """
213
- file_types = (
214
- list(SUPPORTED_COMMENT_TYPES)
215
- if comment_type in SUPPORTED_COMMENT_TYPES
216
- else None
217
- )
218
- return file_types
@@ -12,6 +12,14 @@ from tree_sitter import Node as TreeSitterNode
12
12
  from sphinx_codelinks.config import UNIX_NEWLINE, CommentCategory
13
13
  from sphinx_codelinks.source_discover.config import CommentType
14
14
 
15
+ # Language-specific node types for scope detection
16
+ SCOPE_NODE_TYPES = {
17
+ CommentType.python: {"function_definition", "class_definition"},
18
+ CommentType.cpp: {"function_definition", "class_definition"},
19
+ CommentType.cs: {"method_declaration", "class_declaration", "property_declaration"},
20
+ CommentType.yaml: {"block_mapping_pair", "block_sequence_item", "document"},
21
+ }
22
+
15
23
  # initialize logger
16
24
  logger = logging.getLogger(__name__)
17
25
  logger.setLevel(logging.INFO)
@@ -35,6 +43,8 @@ PYTHON_QUERY = """
35
43
  (class_definition (block (expression_statement (string)) @comment))
36
44
  """
37
45
  CPP_QUERY = """(comment) @comment"""
46
+ C_SHARP_QUERY = """(comment) @comment"""
47
+ YAML_QUERY = """(comment) @comment"""
38
48
 
39
49
 
40
50
  def is_text_file(filepath: Path, sample_size: int = 2048) -> bool:
@@ -63,6 +73,16 @@ def init_tree_sitter(comment_type: CommentType) -> tuple[Parser, Query]:
63
73
 
64
74
  parsed_language = Language(tree_sitter_python.language())
65
75
  query = Query(parsed_language, PYTHON_QUERY)
76
+ elif comment_type == CommentType.cs:
77
+ import tree_sitter_c_sharp # noqa: PLC0415
78
+
79
+ parsed_language = Language(tree_sitter_c_sharp.language())
80
+ query = Query(parsed_language, C_SHARP_QUERY)
81
+ elif comment_type == CommentType.yaml:
82
+ import tree_sitter_yaml # noqa: PLC0415
83
+
84
+ parsed_language = Language(tree_sitter_yaml.language())
85
+ query = Query(parsed_language, YAML_QUERY)
66
86
  else:
67
87
  raise ValueError(f"Unsupported comment style: {comment_type}")
68
88
  parser = Parser(parsed_language)
@@ -90,39 +110,133 @@ def extract_comments(
90
110
  return captures.get("comment")
91
111
 
92
112
 
93
- def find_enclosing_scope(node: TreeSitterNode) -> TreeSitterNode | None:
113
+ def find_enclosing_scope(
114
+ node: TreeSitterNode, comment_type: CommentType = CommentType.cpp
115
+ ) -> TreeSitterNode | None:
94
116
  """Find the enclosing scope of a comment."""
117
+ scope_types = SCOPE_NODE_TYPES.get(comment_type, SCOPE_NODE_TYPES[CommentType.cpp])
95
118
  current: TreeSitterNode = node
96
119
  while current:
97
- if current.type in {"function_definition", "class_definition"}:
120
+ if current.type in scope_types:
98
121
  return current
99
122
  current: TreeSitterNode | None = current.parent # type: ignore[no-redef] # required for node traversal
100
123
  return None
101
124
 
102
125
 
103
- def find_next_scope(node: TreeSitterNode) -> TreeSitterNode | None:
126
+ def find_next_scope(
127
+ node: TreeSitterNode, comment_type: CommentType = CommentType.cpp
128
+ ) -> TreeSitterNode | None:
104
129
  """Find the next scope of a comment."""
130
+ scope_types = SCOPE_NODE_TYPES.get(comment_type, SCOPE_NODE_TYPES[CommentType.cpp])
105
131
  current: TreeSitterNode = node
106
132
  while current:
107
- if current.type in {"function_definition", "class_definition"}:
133
+ if current.type in scope_types:
108
134
  return current
109
135
  current: TreeSitterNode | None = current.next_named_sibling # type: ignore[no-redef] # required for node traversal
110
136
  if current and current.type == "block":
111
137
  for child in current.named_children:
112
- if child.type in {"function_definition", "class_definition"}:
138
+ if child.type in scope_types:
113
139
  return child
114
140
  return None
115
141
 
116
142
 
117
- def find_associated_scope(node: TreeSitterNode) -> TreeSitterNode | None:
143
+ def _find_yaml_structure_in_block_node(
144
+ block_node: TreeSitterNode,
145
+ ) -> TreeSitterNode | None:
146
+ """Find YAML structure elements within a block_node."""
147
+ for grandchild in block_node.named_children:
148
+ if grandchild.type == "block_mapping":
149
+ for ggchild in grandchild.named_children:
150
+ if ggchild.type == "block_mapping_pair":
151
+ return ggchild
152
+ elif grandchild.type == "block_sequence":
153
+ for ggchild in grandchild.named_children:
154
+ if ggchild.type == "block_sequence_item":
155
+ return ggchild
156
+ return None
157
+
158
+
159
+ def find_yaml_next_structure(node: TreeSitterNode) -> TreeSitterNode | None:
160
+ """Find the next YAML structure element after the comment node."""
161
+ current = node.next_named_sibling
162
+ while current:
163
+ if current.type in {
164
+ "block_mapping_pair",
165
+ "block_sequence_item",
166
+ "flow_mapping",
167
+ "flow_sequence",
168
+ }:
169
+ return current
170
+ if current.type == "document":
171
+ for child in current.named_children:
172
+ if child.type == "block_node":
173
+ result = _find_yaml_structure_in_block_node(child)
174
+ if result:
175
+ return result
176
+ if current.type == "block_node":
177
+ result = _find_yaml_structure_in_block_node(current)
178
+ if result:
179
+ return result
180
+ current = current.next_named_sibling
181
+ return None
182
+
183
+
184
+ def find_yaml_prev_sibling_on_same_row(node: TreeSitterNode) -> TreeSitterNode | None:
185
+ """Find a previous named sibling that is on the same row as the comment."""
186
+ comment_row = node.start_point.row
187
+ current = node.prev_named_sibling
188
+
189
+ while current:
190
+ # Check if this sibling ends on the same row as the comment starts
191
+ # This indicates it's an inline comment
192
+ if current.end_point.row == comment_row:
193
+ return current
194
+ # If we find a sibling that ends before the comment row, we can stop
195
+ # as we won't find any siblings on the same row going backwards
196
+ if current.end_point.row < comment_row:
197
+ break
198
+ current = current.prev_named_sibling
199
+
200
+ return None
201
+
202
+
203
+ def find_yaml_associated_structure(node: TreeSitterNode) -> TreeSitterNode | None:
204
+ """Find the YAML structure (key-value pair, list item, etc.) associated with a comment."""
205
+ # First, check if this is an inline comment by looking for a previous sibling on the same row
206
+ prev_sibling_same_row = find_yaml_prev_sibling_on_same_row(node)
207
+ if prev_sibling_same_row:
208
+ return prev_sibling_same_row
209
+
210
+ # If no previous sibling on same row, try to find the next named sibling (structure after the comment)
211
+ structure = find_yaml_next_structure(node)
212
+ if structure:
213
+ return structure
214
+
215
+ # If no next sibling found, traverse up to find parent structure
216
+ parent = node.parent
217
+ while parent:
218
+ if parent.type in {"block_mapping_pair", "block_sequence_item"}:
219
+ return parent
220
+ parent = parent.parent
221
+
222
+ return None
223
+
224
+
225
+ def find_associated_scope(
226
+ node: TreeSitterNode, comment_type: CommentType = CommentType.cpp
227
+ ) -> TreeSitterNode | None:
118
228
  """Find the associated scope of a comment."""
229
+ if comment_type == CommentType.yaml:
230
+ # YAML uses different structure association logic
231
+ return find_yaml_associated_structure(node)
232
+
119
233
  if node.type == CommentCategory.docstring:
120
234
  # Only for python's docstring
121
- return find_enclosing_scope(node)
235
+ return find_enclosing_scope(node, comment_type)
122
236
  # General comments regardless of comment types
123
- associated_scope = find_next_scope(node)
237
+ associated_scope = find_next_scope(node, comment_type)
124
238
  if not associated_scope:
125
- associated_scope = find_enclosing_scope(node)
239
+ associated_scope = find_enclosing_scope(node, comment_type)
126
240
  return associated_scope
127
241
 
128
242
 
@@ -18,9 +18,12 @@ from sphinx_codelinks.source_discover.source_discover import SourceDiscover
18
18
  UNIX_NEWLINE = "\n"
19
19
 
20
20
 
21
- COMMENT_MARKERS = {CommentType.cpp: ["//", "/*"], CommentType.python: ["#"]}
21
+ COMMENT_MARKERS = {
22
+ CommentType.cpp: ["//", "/*"],
23
+ CommentType.python: ["#"],
24
+ CommentType.cs: ["//", "/*", "///"],
25
+ }
22
26
  ESCAPE = "\\"
23
- SUPPORTED_COMMENT_TYPES = {"c", "h", "cpp", "hpp", "py"}
24
27
 
25
28
 
26
29
  class CommentCategory(str, Enum):
@@ -47,7 +50,7 @@ class NeedIdRefsConfig:
47
50
  @classmethod
48
51
  def get_schema(cls, name: str) -> dict[str, Any] | None: # type: ignore[explicit-any]
49
52
  _field = next(_field for _field in fields(cls) if _field.name is name)
50
- if _field.metadata is not MISSING and "schema" in _field.metadata:
53
+ if _field.metadata and "schema" in _field.metadata:
51
54
  return cast(dict[str, Any], _field.metadata["schema"]) # type: ignore[explicit-any]
52
55
  return None
53
56
 
@@ -86,7 +89,7 @@ class MarkedRstConfig:
86
89
  @classmethod
87
90
  def get_schema(cls, name: str) -> dict[str, Any] | None: # type: ignore[explicit-any]
88
91
  _field = next(_field for _field in fields(cls) if _field.name is name)
89
- if _field.metadata is not MISSING and "schema" in _field.metadata:
92
+ if _field.metadata and "schema" in _field.metadata:
90
93
  return cast(dict[str, Any], _field.metadata["schema"]) # type: ignore[explicit-any]
91
94
  return None
92
95
 
@@ -219,14 +222,14 @@ class OneLineCommentStyle:
219
222
  @classmethod
220
223
  def get_required_fields(cls, name: str) -> list[str] | None:
221
224
  _field = next(_field for _field in fields(cls) if _field.name is name)
222
- if _field.metadata is not MISSING:
225
+ if _field.metadata:
223
226
  return cast(list[str], _field.metadata["required_fields"])
224
227
  return None
225
228
 
226
229
  @classmethod
227
230
  def get_schema(cls, name: str) -> dict[str, Any] | None: # type: ignore[explicit-any]
228
231
  _field = next(_field for _field in fields(cls) if _field.name is name)
229
- if _field.metadata is not MISSING and "schema" in _field.metadata:
232
+ if _field.metadata and "schema" in _field.metadata:
230
233
  return cast(dict[str, Any], _field.metadata["schema"]) # type: ignore[explicit-any]
231
234
  return None
232
235
 
@@ -370,7 +373,7 @@ class SourceAnalyseConfig:
370
373
  @classmethod
371
374
  def get_schema(cls, name: str) -> dict[str, Any] | None: # type: ignore[explicit-any]
372
375
  _field = next(_field for _field in fields(cls) if _field.name is name)
373
- if _field.metadata is not MISSING and "schema" in _field.metadata:
376
+ if _field.metadata and "schema" in _field.metadata:
374
377
  return cast(dict[str, Any], _field.metadata["schema"]) # type: ignore[explicit-any]
375
378
  return None
376
379
 
@@ -566,7 +569,7 @@ class CodeLinksConfig:
566
569
  def get_schema(cls, name: str) -> dict[str, Any] | None: # type: ignore[explicit-any]
567
570
  """Get the schema for a config item."""
568
571
  _field = next(field for field in fields(cls) if field.name is name)
569
- if _field.metadata is not MISSING and "schema" in _field.metadata:
572
+ if _field.metadata and "schema" in _field.metadata:
570
573
  return _field.metadata["schema"] # type: ignore[no-any-return]
571
574
  return None
572
575
 
@@ -1,7 +1,7 @@
1
- """Covert the generated JSON file created by CodeLinks anaylse to need-extend in RST."""
1
+ """Convert the generated JSON file created by CodeLinks analyse to need-extend in RST."""
2
2
 
3
3
  from collections import deque
4
- from dataclasses import MISSING, dataclass, field, fields
4
+ from dataclasses import dataclass, field, fields
5
5
  from os import linesep
6
6
  from string import Template
7
7
  from typing import Any, TypedDict, cast
@@ -105,7 +105,7 @@ class MarkedContentSchema:
105
105
  @classmethod
106
106
  def get_schema(cls, name: str) -> dict[str, Any] | None: # type: ignore[explicit-any]
107
107
  _field = next(_field for _field in fields(cls) if _field.name is name)
108
- if _field.metadata is not MISSING and "schema" in _field.metadata:
108
+ if _field.metadata and "schema" in _field.metadata:
109
109
  return cast(dict[str, Any], _field.metadata["schema"]) # type: ignore[explicit-any]
110
110
  return None
111
111
 
@@ -165,7 +165,7 @@ def convert_marked_content(
165
165
  remote_url_field: str = "remote-url",
166
166
  title: str | None = None,
167
167
  ) -> tuple[list[str], list[str]]:
168
- """Convert marked objects extracted by anaylse CLI to needextend in RST"""
168
+ """Convert marked objects extracted by analyse CLI to needextend in RST"""
169
169
  errors = []
170
170
  needextend_texts: list[str] = []
171
171
  intersted_objs = [
@@ -1,16 +1,23 @@
1
- from dataclasses import MISSING, dataclass, field, fields
1
+ from dataclasses import dataclass, field, fields
2
2
  from enum import Enum
3
3
  from pathlib import Path
4
4
  from typing import Any, Required, TypedDict, cast
5
5
 
6
6
  from jsonschema import ValidationError, validate
7
7
 
8
- COMMENT_FILETYPE = {"cpp": ["c", "cpp", "h", "hpp"], "python": ["py"]}
8
+ COMMENT_FILETYPE = {
9
+ "cpp": ["c", "ci", "cpp", "cc", "cxx", "h", "hpp", "hxx", "hh", "ihl"],
10
+ "python": ["py"],
11
+ "cs": ["cs"],
12
+ "yaml": ["yml", "yaml"],
13
+ }
9
14
 
10
15
 
11
16
  class CommentType(str, Enum):
12
17
  python = "python"
13
18
  cpp = "cpp"
19
+ cs = "cs"
20
+ yaml = "yaml"
14
21
 
15
22
 
16
23
  class SourceDiscoverSectionConfigType(TypedDict, total=False):
@@ -73,7 +80,7 @@ class SourceDiscoverConfig:
73
80
  @classmethod
74
81
  def get_schema(cls, name: str) -> dict[str, Any] | None: # type: ignore[explicit-any]
75
82
  _field = next(_field for _field in fields(cls) if _field.name is name)
76
- if _field.metadata is not MISSING and "schema" in _field.metadata:
83
+ if _field.metadata and "schema" in _field.metadata:
77
84
  return cast(dict[str, Any], _field.metadata["schema"]) # type: ignore[explicit-any]
78
85
  return None
79
86
 
@@ -33,6 +33,15 @@ else:
33
33
  logger = logging.getLogger(__name__)
34
34
 
35
35
 
36
+ def get_rel_path(doc_path: Path, code_path: Path, base_dir: Path) -> tuple[Path, Path]:
37
+ """Get the relative path from the document to the source code file and vice versa."""
38
+ doc_depth = len(doc_path.parents) - 1
39
+ src_rel_path = Path(*[".."] * doc_depth) / code_path.relative_to(base_dir)
40
+ code_depth = len(code_path.relative_to(base_dir).parents) - 1
41
+ doc_rel_path = Path(*[".."] * code_depth) / doc_path
42
+ return src_rel_path, doc_rel_path.with_suffix(".html")
43
+
44
+
36
45
  def generate_str_link_name(
37
46
  oneline_need: OneLineNeed,
38
47
  target_filepath: Path,
@@ -67,13 +76,12 @@ class SourceTracing(nodes.General, nodes.Element):
67
76
 
68
77
 
69
78
  class SourceTracingDirective(SphinxDirective):
70
- required_arguments = 1
79
+ required_arguments = 0
71
80
  optional_arguments = 0
72
81
  final_argument_whitespace = True
73
82
  # this enables content in the directive
74
- has_content = True
83
+ has_content = False
75
84
  option_spec: ClassVar[dict[str, Callable[[str], str]] | None] = {
76
- "id": directives.unchanged_required,
77
85
  "project": directives.unchanged_required,
78
86
  "file": directives.unchanged_required,
79
87
  "directory": directives.unchanged_required,
@@ -84,7 +92,6 @@ class SourceTracingDirective(SphinxDirective):
84
92
  validate_option(self.options)
85
93
 
86
94
  project = self.options["project"]
87
- title = self.arguments[0]
88
95
  # get source tracing config
89
96
  src_trace_sphinx_config = CodeLinksConfig.from_sphinx(self.env.config)
90
97
 
@@ -99,7 +106,6 @@ class SourceTracingDirective(SphinxDirective):
99
106
  # the directory where the source files are copied to
100
107
  target_dir = out_dir / src_dir.name
101
108
 
102
- extra_options = {"project": project}
103
109
  source_files = self.get_src_files(self.options, src_dir, src_discover_config)
104
110
 
105
111
  # add source files into the dependency
@@ -113,20 +119,6 @@ class SourceTracingDirective(SphinxDirective):
113
119
  src_analyse = SourceAnalyse(analyse_config)
114
120
  src_analyse.run()
115
121
 
116
- needs = []
117
-
118
- # create the need for src-trace directive
119
- src_trace_need = add_need(
120
- app=self.env.app, # The Sphinx application object
121
- state=self.state, # The docutils state object
122
- docname=self.env.docname, # The current document name
123
- lineno=self.lineno, # The line number where the directive is used
124
- need_type="srctrace", # The type of the need
125
- title=title, # The title of the need
126
- **extra_options,
127
- )
128
- needs.extend(src_trace_need)
129
-
130
122
  dirs = {
131
123
  "src_dir": src_dir,
132
124
  "out_dir": out_dir,
@@ -145,7 +137,7 @@ class SourceTracingDirective(SphinxDirective):
145
137
  to_remove_str = to_remove_str.replace("\\", "\\\\")
146
138
  self.env.config.needs_string_links[local_url_field] = {
147
139
  "regex": r"^(?P<value>.+?)\.[^\.]+#L(?P<lineno>\d+)",
148
- "link_url": ("file://{{value}}.html#L-{{lineno}}"),
140
+ "link_url": ("{{value}}.html#L-{{lineno}}"),
149
141
  "link_name": f"{{{{value | replace('{to_remove_str}', '')}}}}#L{{{{lineno}}}}",
150
142
  "options": [local_url_field],
151
143
  }
@@ -180,18 +172,16 @@ class SourceTracingDirective(SphinxDirective):
180
172
  remote_url_field,
181
173
  dirs,
182
174
  )
183
- if rendered_needs:
184
- needs.extend(rendered_needs)
185
175
 
186
176
  # for post-processing of need links
187
177
  # https://github.com/useblocks/sphinx-needs/issues/1210
188
178
  add_doc(self.env, self.env.docname)
189
179
 
190
- return needs
180
+ return rendered_needs
191
181
 
192
182
  def get_src_files(
193
183
  self,
194
- extra_options: dict[str, str],
184
+ additional_options: dict[str, str],
195
185
  src_dir: Path,
196
186
  src_discover_config: SourceDiscoverConfig,
197
187
  ) -> list[Path]:
@@ -201,14 +191,14 @@ class SourceTracingDirective(SphinxDirective):
201
191
  file: str = self.options["file"]
202
192
  filepath = src_dir / file
203
193
  source_files.append(filepath.resolve())
204
- extra_options["file"] = file
194
+ additional_options["file"] = file
205
195
  else:
206
196
  directory = self.options.get("directory")
207
197
  if directory is None:
208
198
  # when neither "file" and "directory" are given, the project root dir is by default
209
199
  directory = "./"
210
200
  else:
211
- extra_options["directory"] = directory
201
+ additional_options["directory"] = directory
212
202
  dir_path = src_dir / directory
213
203
  # create a new config for the specified directory
214
204
  src_discover = SourceDiscoverConfig(
@@ -259,7 +249,7 @@ class SourceTracingDirective(SphinxDirective):
259
249
  # mapping between lineno and need link in docs for local url
260
250
 
261
251
  # The link to the documentation page for the source file
262
- docs_href = f"{dirs['out_dir'] / self.env.docname}.html"
252
+
263
253
  if local_url_field:
264
254
  # copy files to _build/html
265
255
  target_filepath.parent.mkdir(parents=True, exist_ok=True)
@@ -268,8 +258,15 @@ class SourceTracingDirective(SphinxDirective):
268
258
  remote_link_name = None
269
259
  if local_url_field:
270
260
  # generate link name
261
+ # calculate the relative path from the current doc to the target file
262
+ local_rel_path, docs_href = get_rel_path(
263
+ Path(self.env.docname), target_filepath, dirs["out_dir"]
264
+ )
271
265
  local_link_name = generate_str_link_name(
272
- oneline_need, target_filepath, dirs, local=True
266
+ oneline_need,
267
+ local_rel_path,
268
+ dirs,
269
+ local=True,
273
270
  )
274
271
  if remote_url_field:
275
272
  remote_link_name = generate_str_link_name(
@@ -35,7 +35,34 @@ from sphinx_codelinks.sphinx_extension.html_wrapper import html_wrapper
35
35
  logger = logging.getLogger(__name__)
36
36
 
37
37
 
38
+ def _check_sphinx_needs_dependency(app: Sphinx) -> bool:
39
+ """Check if sphinx-needs is actually loaded as an extension."""
40
+ # Check if sphinx-needs is in the loaded extensions
41
+ if "sphinx_needs" not in app.extensions:
42
+ error_msg = (
43
+ "sphinx-codelinks requires sphinx-needs to be loaded as an extension.\n"
44
+ "Please ensure 'sphinx_needs' is properly installed and added to your extensions list in conf.py:\n"
45
+ " extensions = ['sphinx_needs', 'sphinx_codelinks', ...]\n"
46
+ f"Currently loaded extensions: {list(app.extensions.keys())}\n"
47
+ f"Configured extensions: {app.config.extensions}"
48
+ )
49
+ logger.error(error_msg)
50
+ return False
51
+ return True
52
+
53
+
38
54
  def setup(app: Sphinx) -> dict[str, Any]: # type: ignore[explicit-any]
55
+ # Check if sphinx-needs is available and properly configured
56
+ if not _check_sphinx_needs_dependency(app):
57
+ logger.error(
58
+ "Failed to initialize sphinx-codelinks due to missing sphinx-needs dependency"
59
+ )
60
+ return {
61
+ "version": "builtin",
62
+ "parallel_read_safe": True,
63
+ "parallel_write_safe": True,
64
+ }
65
+
39
66
  app.add_node(SourceTracing)
40
67
  app.add_directive("src-trace", SourceTracingDirective)
41
68
  CodeLinksConfig.add_config_values(app)
@@ -69,7 +96,7 @@ def add_custom_css( # type: ignore[explicit-any]
69
96
  app: Sphinx,
70
97
  pagename: str,
71
98
  templatename: str,
72
- context: dict[str, Any],
99
+ _context: dict[str, Any],
73
100
  _doctree: Any,
74
101
  ) -> None:
75
102
  target_htmls = {
@@ -78,11 +105,7 @@ def add_custom_css( # type: ignore[explicit-any]
78
105
  }
79
106
 
80
107
  if pagename in target_htmls and templatename == "page.html":
81
- if "css_files" not in context:
82
- context["css_files"] = []
83
- context["css_files"].append(
84
- "_static/source_tracing/ub_sct.css"
85
- ) # Add the custom CSS file to the context
108
+ app.add_css_file("_static/source_tracing/ub_sct.css")
86
109
 
87
110
 
88
111
  def generate_code_page(