7
7
from typing import Sequence
8
8
9
9
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
11
12
with open (filename , mode = 'rb' ) as file_processed :
12
13
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 ]
14
15
if newlines != lines :
15
16
with open (filename , mode = 'wb' ) as file_processed :
16
17
for line in newlines :
@@ -20,17 +21,20 @@ def _fix_file(filename, is_markdown): # type: (str, bool) -> bool
20
21
return False
21
22
22
23
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
24
26
if line [- 2 :] == b'\r \n ' :
25
27
eol = b'\r \n '
28
+ line = line [:- 2 ]
26
29
elif line [- 1 :] == b'\n ' :
27
30
eol = b'\n '
31
+ line = line [:- 1 ]
28
32
else :
29
33
eol = b''
30
34
# 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
34
38
35
39
36
40
def main (argv = None ): # type: (Optional[Sequence[str]]) -> int
@@ -50,6 +54,13 @@ def main(argv=None): # type: (Optional[Sequence[str]]) -> int
50
54
'default: %(default)s'
51
55
),
52
56
)
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
+ )
53
64
parser .add_argument ('filenames' , nargs = '*' , help = 'Filenames to fix' )
54
65
args = parser .parse_args (argv )
55
66
@@ -73,12 +84,12 @@ def main(argv=None): # type: (Optional[Sequence[str]]) -> int
73
84
" (probably filename; use '--markdown-linebreak-ext=EXT')"
74
85
.format (ext ),
75
86
)
76
-
87
+ chars = None if args . chars is None else args . chars . encode ( 'utf-8' )
77
88
return_code = 0
78
89
for filename in args .filenames :
79
90
_ , extension = os .path .splitext (filename .lower ())
80
91
md = all_markdown or extension in md_exts
81
- if _fix_file (filename , md ):
92
+ if _fix_file (filename , md , chars ):
82
93
print ('Fixing {}' .format (filename ))
83
94
return_code = 1
84
95
return return_code
0 commit comments