Skip to content

Commit 34e9d11

Browse files
authored
Merge pull request pre-commit#1378 from sophgn/master
fix CJK characters width in output
2 parents 528c7af + 605b39f commit 34e9d11

File tree

2 files changed

+21
-3
lines changed

2 files changed

+21
-3
lines changed

pre_commit/commands/run.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import re
77
import subprocess
88
import time
9+
import unicodedata
910
from typing import Any
1011
from typing import Collection
1112
from typing import Dict
@@ -33,8 +34,13 @@
3334
logger = logging.getLogger('pre_commit')
3435

3536

37+
def _len_cjk(msg: str) -> int:
38+
widths = {'A': 1, 'F': 2, 'H': 1, 'N': 1, 'Na': 1, 'W': 2}
39+
return sum(widths[unicodedata.east_asian_width(c)] for c in msg)
40+
41+
3642
def _start_msg(*, start: str, cols: int, end_len: int) -> str:
37-
dots = '.' * (cols - len(start) - end_len - 1)
43+
dots = '.' * (cols - _len_cjk(start) - end_len - 1)
3844
return f'{start}{dots}'
3945

4046

@@ -47,7 +53,7 @@ def _full_msg(
4753
use_color: bool,
4854
postfix: str = '',
4955
) -> str:
50-
dots = '.' * (cols - len(start) - len(postfix) - len(end_msg) - 1)
56+
dots = '.' * (cols - _len_cjk(start) - len(postfix) - len(end_msg) - 1)
5157
end = color.format_color(end_msg, end_color, use_color)
5258
return f'{start}{dots}{postfix}{end}\n'
5359

@@ -206,7 +212,7 @@ def _compute_cols(hooks: Sequence[Hook]) -> int:
206212
Hook name...(no files to check) Skipped
207213
"""
208214
if hooks:
209-
name_len = max(len(hook.name) for hook in hooks)
215+
name_len = max(_len_cjk(hook.name) for hook in hooks)
210216
else:
211217
name_len = 0
212218

tests/commands/run_test.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,18 @@ def test_full_msg():
5252
assert ret == 'start......end\n'
5353

5454

55+
def test_full_msg_with_cjk():
56+
ret = _full_msg(
57+
start='啊あ아',
58+
end_msg='end',
59+
end_color='',
60+
use_color=False,
61+
cols=15,
62+
)
63+
# 5 dots: 15 - 6 - 3 - 1
64+
assert ret == '啊あ아.....end\n'
65+
66+
5567
def test_full_msg_with_color():
5668
ret = _full_msg(
5769
start='start',

0 commit comments

Comments
 (0)