Skip to content

Commit 0d2a356

Browse files
committed
backups are important
1 parent 9aeca53 commit 0d2a356

File tree

2 files changed

+24
-10
lines changed

2 files changed

+24
-10
lines changed

common.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,11 @@
3131
file when actually opening files.
3232
"""
3333

34+
import contextlib
3435
import itertools
3536
import os
3637
import re
38+
import shutil
3739

3840

3941
_LINK_REGEX = r'\[(.*?)\]\((.*?)\)'
@@ -108,3 +110,17 @@ def slashfix(path):
108110
def 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')

strip.py

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -45,23 +45,21 @@ def needs_stripping(file):
4545

4646

4747
def 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

6159
def 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)

0 commit comments

Comments
 (0)