77from typing import Sequence
88
99
10- def _fix_file (filename , is_markdown ): # type: (str, bool) -> bool
10+ def _fix_file (filename , is_markdown , chars ):
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 = [_process_line (line , is_markdown , chars ) for line in lines ]
1415 if newlines != lines :
1516 with open (filename , mode = 'wb' ) as file_processed :
1617 for line in newlines :
@@ -20,17 +21,20 @@ def _fix_file(filename, is_markdown): # type: (str, bool) -> bool
2021 return False
2122
2223
23- def _process_line (line , is_markdown ): # type: (bytes, bool) -> bytes
24+ def _process_line (line , is_markdown , chars ):
25+ # type: (bytes, bool, Optional[bytes]) -> bytes
2426 if line [- 2 :] == b'\r \n ' :
2527 eol = b'\r \n '
28+ line = line [:- 2 ]
2629 elif line [- 1 :] == b'\n ' :
2730 eol = b'\n '
31+ line = line [:- 1 ]
2832 else :
2933 eol = b''
3034 # preserve trailing two-space for non-blank lines in markdown files
31- if is_markdown and (not line .isspace ()) and line .endswith (b' ' + eol ):
32- return line .rstrip () + b' ' + eol
33- return line .rstrip () + eol
35+ if is_markdown and (not line .isspace ()) and line .endswith (b' ' ):
36+ return line [: - 2 ] .rstrip (chars ) + b' ' + eol
37+ return line .rstrip (chars ) + eol
3438
3539
3640def main (argv = None ): # type: (Optional[Sequence[str]]) -> int
@@ -50,6 +54,13 @@ def main(argv=None): # type: (Optional[Sequence[str]]) -> int
5054 'default: %(default)s'
5155 ),
5256 )
57+ parser .add_argument (
58+ '--chars' ,
59+ help = (
60+ 'The set of characters to strip from the end of lines. '
61+ 'Defaults to all whitespace characters.'
62+ ),
63+ )
5364 parser .add_argument ('filenames' , nargs = '*' , help = 'Filenames to fix' )
5465 args = parser .parse_args (argv )
5566
@@ -73,12 +84,12 @@ def main(argv=None): # type: (Optional[Sequence[str]]) -> int
7384 " (probably filename; use '--markdown-linebreak-ext=EXT')"
7485 .format (ext ),
7586 )
76-
87+ chars = None if args . chars is None else args . chars . encode ( 'utf-8' )
7788 return_code = 0
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 (filename , md , chars ):
8293 print ('Fixing {}' .format (filename ))
8394 return_code = 1
8495 return return_code
0 commit comments