ptrad
[redakcja.git] / src / sources / utils.py
1 from contextlib import contextmanager
2 import os
3 import shutil
4 from time import time
5
6
7 @contextmanager
8 def replace_dir(d):
9     # create tmp dir
10     d = d.rstrip('/')
11     ts = int(time())
12     dnew = f'{d}.{ts}.new'
13     dold = f'{d}.{ts}.old'
14     os.makedirs(dnew)
15     try:
16         yield dnew
17     except:
18         shutil.rmtree(dnew)
19         raise
20     else:
21         if os.path.exists(d):
22             shutil.move(d, dold)
23         shutil.move(dnew, d)
24         if os.path.exists(dold):
25             shutil.rmtree(dold)