Skip to content

Commit 886dfc4

Browse files
trailing-whitespace: add option for custom chars to strip
1 parent 0f7b5e0 commit 886dfc4

1 file changed

Lines changed: 21 additions & 6 deletions

File tree

pre_commit_hooks/trailing_whitespace_fixer.py

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,15 @@
77
from typing import Sequence
88

99

10-
def _fix_file(filename, is_markdown): # type: (str, bool) -> bool
10+
def _fix_file(filename, is_markdown, chars_to_strip):
11+
# type: (str, bool, Optional[bytes]) -> bool
1112
with open(filename, mode='rb') as file_processed:
1213
lines = file_processed.readlines()
13-
newlines = [_process_line(line, is_markdown) for line in lines]
14+
newlines = [
15+
_process_line(line, is_markdown, chars_to_strip)
16+
for line
17+
in lines
18+
]
1419
if newlines != lines:
1520
with open(filename, mode='wb') as file_processed:
1621
for line in newlines:
@@ -20,7 +25,8 @@ def _fix_file(filename, is_markdown): # type: (str, bool) -> bool
2025
return False
2126

2227

23-
def _process_line(line, is_markdown): # type: (bytes, bool) -> bytes
28+
def _process_line(line, is_markdown, chars_to_strip):
29+
# type: (bytes, bool, Optional[bytes]) -> bytes
2430
if line[-2:] == b'\r\n':
2531
eol = b'\r\n'
2632
elif line[-1:] == b'\n':
@@ -29,8 +35,8 @@ def _process_line(line, is_markdown): # type: (bytes, bool) -> bytes
2935
eol = b''
3036
# preserve trailing two-space for non-blank lines in markdown files
3137
if is_markdown and (not line.isspace()) and line.endswith(b' ' + eol):
32-
return line.rstrip() + b' ' + eol
33-
return line.rstrip() + eol
38+
return line.rstrip(chars_to_strip) + b' ' + eol
39+
return line.rstrip(chars_to_strip) + eol
3440

3541

3642
def main(argv=None): # type: (Optional[Sequence[str]]) -> int
@@ -50,6 +56,11 @@ def main(argv=None): # type: (Optional[Sequence[str]]) -> int
5056
'default: %(default)s'
5157
),
5258
)
59+
parser.add_argument(
60+
'--chars',
61+
help='The set of characters to strip from the end of lines. '
62+
'Defaults to all whitespace characters.',
63+
)
5364
parser.add_argument('filenames', nargs='*', help='Filenames to fix')
5465
args = parser.parse_args(argv)
5566

@@ -78,7 +89,11 @@ def main(argv=None): # type: (Optional[Sequence[str]]) -> int
7889
for filename in args.filenames:
7990
_, extension = os.path.splitext(filename.lower())
8091
md = all_markdown or extension in md_exts
81-
if _fix_file(filename, md):
92+
if _fix_file(
93+
filename,
94+
md,
95+
None if args.chars is None else bytes(args.chars, 'utf-8'),
96+
):
8297
print('Fixing {}'.format(filename))
8398
return_code = 1
8499
return return_code

0 commit comments

Comments
 (0)