File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 3131file when actually opening files.
3232"""
3333
34+ import contextlib
3435import itertools
3536import os
3637import re
38+ import shutil
3739
3840
3941_LINK_REGEX = r'\[(.*?)\]\((.*?)\)'
@@ -108,3 +110,17 @@ def slashfix(path):
108110def slashfix_open (file , mode ):
109111 """An easy way to use slashfix() and open() together."""
110112 return open (slashfix (file ), mode )
113+
114+
115+ @contextlib .contextmanager
116+ def backup (filename ):
117+ """A context manager that backs up a file."""
118+ shutil .copy (filename , filename + '.backup' )
119+ try :
120+ yield
121+ except Exception :
122+ # It failed, we need to restore from the backup.
123+ shutil .copy (filename + '.backup' , filename )
124+ else :
125+ # Everything's fine, we can safely get rid of the backup.
126+ os .remove (filename + '.backup' )
Original file line number Diff line number Diff line change @@ -45,23 +45,21 @@ def needs_stripping(file):
4545
4646
4747def strip (file ):
48+ real_file = common .slashfix (file )
4849 lines = []
49- with common . slashfix_open ( file , 'r' ) as f :
50+ with open ( real_file , 'r' ) as f :
5051 for line in f :
51- line = line .rstrip ('\n ' )
52- # it's important to do as much as possible here because the
53- # file may be lost if writing fails, that's why fix() is
54- # here
55- lines .append (fix (line ))
56- with common .slashfix_open (file , 'w' ) as f :
57- for line in lines :
58- print (line , file = f )
52+ lines .append (fix (line .rstrip ('\n ' )))
53+ with common .backup (real_file ):
54+ with open (real_file , 'w' ) as f :
55+ for line in lines :
56+ print (line , file = f )
5957
6058
6159def main ():
6260 for file in common .get_markdown_files ():
6361 if needs_stripping (file ):
64- print ("Stripping" , file )
62+ print ("Stripping" , file , "..." )
6563 strip (file )
6664 else :
6765 print ("No trailing whitespace or tabs in" , file )
You can’t perform that action at this time.
0 commit comments