Skip to content

Commit

Permalink
Add line numbers to Markdown code snippets (#399)
Browse files Browse the repository at this point in the history
* Add line numbers to Markdown code snippets

* Cosmetics

* Pass testing
  • Loading branch information
walles authored Apr 14, 2024
1 parent 98df742 commit 411c5ff
Show file tree
Hide file tree
Showing 4 changed files with 61 additions and 47 deletions.
19 changes: 17 additions & 2 deletions diff_cover/snippets.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,18 +116,33 @@ def markdown(self):
Return a Markdown representation of the snippet using Markdown fenced code blocks.
See https://github.github.com/gfm/#fenced-code-blocks.
"""

line_number_length = len(str(self._last_line))

text = ""
for i, line in enumerate(self.text().splitlines(), start=self._start_line):
if i > self._start_line:
text += "\n"

notice = " "
if i in self._violation_lines:
notice = "!"

format_string = "{} {:>" + str(line_number_length) + "} {}"
text += format_string.format(notice, i, line)

header = "Lines %d-%d\n\n" % (self._start_line, self._last_line)
if self._lexer_name in self.LEXER_TO_MARKDOWN_CODE_HINT:
return header + (
"```"
+ self.LEXER_TO_MARKDOWN_CODE_HINT[self._lexer_name]
+ "\n"
+ self.text()
+ text
+ "\n```\n"
)

# unknown programming language, return a non-decorated fenced code block:
return "```\n" + self.text() + "\n```\n"
return "```\n" + text + "\n```\n"

def terminal(self):
"""
Expand Down
56 changes: 28 additions & 28 deletions tests/fixtures/snippet_list.md
Original file line number Diff line number Diff line change
@@ -1,38 +1,38 @@
Lines 6-17

```python
Line 6
Line 7
Line 8
Line 9
Line 10
Line 11
Line 12
Line 13
Line 14
Line 15
Line 16
Line 17
6 Line 6
7 Line 7
8 Line 8
9 Line 9
! 10 Line 10
11 Line 11
! 12 Line 12
! 13 Line 13
14 Line 14
15 Line 15
16 Line 16
17 Line 17
```


Lines 46-61

```python
Line 46
Line 47
Line 48
Line 49
Line 50
Line 51
Line 52
Line 53
Line 54
Line 55
Line 56
Line 57
Line 58
Line 59
Line 60
Line 61
46 Line 46
47 Line 47
48 Line 48
49 Line 49
! 50 Line 50
! 51 Line 51
52 Line 52
53 Line 53
! 54 Line 54
! 55 Line 55
56 Line 56
! 57 Line 57
58 Line 58
59 Line 59
60 Line 60
61 Line 61
```
15 changes: 7 additions & 8 deletions tests/fixtures/snippet_list2.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
Lines 1-7

```cpp
#include <iostream>

int main() {
std::cout << "Hello World!";
return 0;
}

```
1 #include <iostream>
2
3 int main() {
! 4 std::cout << "Hello World!";
! 5 return 0;
6 }
```
18 changes: 9 additions & 9 deletions tests/fixtures/snippet_list3.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
Lines 8-16

```cpp
// this is line 8
printf("Test2");

// this is line 11
printf("Test");
}

int main()
{
8 // this is line 8
9 printf("Test2");
10
11 // this is line 11
! 12 printf("Test");
13 }
14
15 int main()
16 {
```

0 comments on commit 411c5ff

Please sign in to comment.