MCPcopy Create free account
hub / github.com/cdgriffith/Box / extract_comments

Function extract_comments

box/comments.py:118–195  ·  view source on GitHub ↗

Collect the comments of a document loaded with the ruamel.yaml round trip loader. :return: ``{"start": lines, "end": lines, "keys": {path: {"before": lines, "eol": text}}}``, or None when the data carries no comments (other loaders, or a document without any).

(root: Any)

Source from the content-addressed store, hash-verified

116
117
118def extract_comments(root: Any) -> dict | None:
119 """
120 Collect the comments of a document loaded with the ruamel.yaml round trip loader.
121
122 :return: ``{"start": lines, "end": lines, "keys": {path: {"before": lines, "eol": text}}}``,
123 or None when the data carries no comments (other loaders, or a document without any).
124 """
125 try:
126 from ruamel.yaml.comments import CommentedMap, CommentedSeq
127 except ImportError: # pragma: no cover (depends on installed packages)
128 return None
129 if not isinstance(root, (CommentedMap, CommentedSeq)):
130 return None
131
132 model: dict = {"start": None, "end": None, "keys": {}}
133 seen: set[int] = set()
134 pending: list[str] = []
135
136 def entry(path):
137 return model["keys"].setdefault(path, {"before": [], "eol": None})
138
139 def take_lines(tokens):
140 for token in tokens or []:
141 if token is not None and id(token) not in seen:
142 seen.add(id(token))
143 pending.extend(_token_lines(token.value)[:-1])
144
145 def handle(token, path):
146 if token is None or id(token) in seen:
147 return
148 seen.add(id(token))
149 value = token.value
150 if value.startswith("\n"):
151 rest = value[1:]
152 else:
153 # The first line is the end of line comment, the following lines belong to the next key
154 first, _, rest = value.partition("\n")
155 entry(path)["eol"] = first.strip()[1:].strip()
156 if rest:
157 pending.extend(_token_lines(rest)[:-1]) # comment tokens end with a newline
158
159 root_comment = getattr(root.ca, "comment", None)
160 if root_comment and len(root_comment) > 1 and root_comment[1]:
161 model["start"] = [line for token in root_comment[1] for line in _token_lines(token.value)[:-1]]
162 seen.update(id(token) for token in root_comment[1])
163
164 def walk(node, path):
165 if isinstance(node, CommentedMap):
166 items = node.items()
167 is_map = True
168 elif isinstance(node, CommentedSeq):
169 items = enumerate(node)
170 is_map = False
171 else:
172 return
173 node_comment = getattr(node.ca, "comment", None)
174 if path and node_comment and len(node_comment) > 1:
175 take_lines(node_comment[1])

Callers 1

_from_yaml_with_commentsFunction · 0.90

Calls 3

_token_linesFunction · 0.85
walkFunction · 0.85
updateMethod · 0.45

Tested by

no test coverage detected