Skip to content

Commit 0aa5b27

Browse files
committed
Fixed replacing code offset
Replacing fenced code would change the line numbers of following code blocks, leading to buggy behavior Ticket: ENT-12737 Signed-off-by: Victor Moene <victor.moene@northern.tech>
1 parent 25b53fa commit 0aa5b27

File tree

1 file changed

+17
-4
lines changed

1 file changed

+17
-4
lines changed

scripts/markdown-code-checker.py

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,9 @@ def extract_inline_code(file_path, languages):
1919
if child.type != "fence":
2020
continue
2121

22+
if not child.info:
23+
continue
24+
2225
info_string = child.info.split()
2326
language = info_string[0]
2427
flags = info_string[1:]
@@ -91,14 +94,18 @@ def replace(path, i, language, first_line, last_line):
9194
return
9295

9396
with open(path, "r") as f:
94-
markdown_content = f.read()
95-
lines = markdown_content.split("\n")
97+
lines = f.read().split("\n")
98+
pretty_lines = pretty_content.split("\n")
99+
100+
offset = len(pretty_lines) - len(lines[first_line + 1 : last_line - 1])
96101

97-
lines[first_line + 1 : last_line - 1] = pretty_content.split("\n")
102+
lines[first_line + 1 : last_line - 1] = pretty_lines
98103

99104
with open(path, "w") as f:
100105
f.write("\n".join(lines))
101106

107+
return offset
108+
102109

103110
def autoformat(path, i, language, first_line, last_line):
104111
file_name = f"{path}.snippet-{i}.{language}"
@@ -184,8 +191,14 @@ def parse_args():
184191
parsed_markdowns = get_markdown_files(args.path, args.languages)
185192

186193
for path in parsed_markdowns["files"].keys():
194+
offset = 0
187195
for i, code_block in enumerate(parsed_markdowns["files"][path]["code-blocks"]):
188196

197+
# adjust line numbers after replace
198+
for cb in parsed_markdowns["files"][path]["code-blocks"][i:]:
199+
cb["first_line"] += offset
200+
cb["last_line"] += offset
201+
189202
if args.extract and "noextract" not in code_block["flags"]:
190203
extract(
191204
path,
@@ -211,7 +224,7 @@ def parse_args():
211224
check_output()
212225

213226
if args.replace and "noreplace" not in code_block["flags"]:
214-
replace(
227+
offset = replace(
215228
path,
216229
i + 1,
217230
supported_languages[code_block["language"]],

0 commit comments

Comments
 (0)