summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorFrederick Yin <fkfd@macaw.me>2020-07-22 16:55:00 +0800
committerFrederick Yin <fkfd@macaw.me>2020-07-22 16:55:00 +0800
commit6333ef00cb5eeba691b83bbed84b7ffc2d583508 (patch)
tree30b902cdd4f2e015e66f2252b2fc509fcdcb8140
parenta034660eb7f235b53f3b6051739179a06b1444f0 (diff)
Add line number in blob view
-rw-r--r--git-gmi/git.py3
-rw-r--r--git-gmi/utils.py17
2 files changed, 19 insertions, 1 deletions
diff --git a/git-gmi/git.py b/git-gmi/git.py
index f249ec5..800dc0f 100644
--- a/git-gmi/git.py
+++ b/git-gmi/git.py
@@ -4,6 +4,7 @@ from datetime import datetime
import mimetypes
from const import *
from config import *
+from utils import *
mimetypes.add_type("text/gemini", ".gmi")
mimetypes.add_type("text/gemini", ".gemini")
@@ -273,7 +274,7 @@ class GitGmiRepo:
elif blob.size < MAX_DISPLAYED_BLOB_SIZE:
response += (
f"=> {blob.name}?raw view raw\n\n"
- "```\n" + blob.data.decode("utf-8") + "\n```"
+ "```\n" + add_line_numbers(blob.data.decode("utf-8")) + "\n```"
)
else:
response += (
diff --git a/git-gmi/utils.py b/git-gmi/utils.py
new file mode 100644
index 0000000..c3dbd59
--- /dev/null
+++ b/git-gmi/utils.py
@@ -0,0 +1,17 @@
+import math
+
+
+def add_line_numbers(code: str) -> str:
+ lines = code.splitlines()
+ if not lines:
+ return code # empty anyway
+
+ # cannot use math.ceil() here bc lg100=2
+ max_digits = math.floor(math.log10(len(lines))) + 1
+
+ for n, l in enumerate(lines, 1):
+ digits_in_n = math.floor(math.log10(n)) + 1
+ spaces_before_number = max_digits - digits_in_n
+ lines[n - 1] = " " * spaces_before_number + str(n) + " " + l
+
+ return "\n".join(lines)