File tree 2 files changed +24
-10
lines changed 2 files changed +24
-10
lines changed Original file line number Diff line number Diff line change 31
31
file when actually opening files.
32
32
"""
33
33
34
+ import contextlib
34
35
import itertools
35
36
import os
36
37
import re
38
+ import shutil
37
39
38
40
39
41
_LINK_REGEX = r'\[(.*?)\]\((.*?)\)'
@@ -108,3 +110,17 @@ def slashfix(path):
108
110
def slashfix_open (file , mode ):
109
111
"""An easy way to use slashfix() and open() together."""
110
112
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):
45
45
46
46
47
47
def strip (file ):
48
+ real_file = common .slashfix (file )
48
49
lines = []
49
- with common . slashfix_open ( file , 'r' ) as f :
50
+ with open ( real_file , 'r' ) as f :
50
51
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 )
59
57
60
58
61
59
def main ():
62
60
for file in common .get_markdown_files ():
63
61
if needs_stripping (file ):
64
- print ("Stripping" , file )
62
+ print ("Stripping" , file , "..." )
65
63
strip (file )
66
64
else :
67
65
print ("No trailing whitespace or tabs in" , file )
You can’t perform that action at this time.
0 commit comments