1# http://pyrocko.org - GPLv3 

2# 

3# The Pyrocko Developers, 21st Century 

4# ---|P------/S----------~Lg---------- 

5 

6import os 

7import logging 

8 

9op = os.path 

10logger = logging.getLogger('psq.lock') 

11 

12 

13class LockDir(object): 

14 

15 def __init__(self, path): 

16 self._path = path 

17 self._lockfile = op.join(path, '.buried') 

18 

19 def __enter__(self): 

20 if op.exists(self._lockfile): 

21 raise EnvironmentError('Directory "%s" is locked' % self._path) 

22 

23 with open(self._lockfile, 'wb') as f: 

24 f.write(b'') 

25 logger.debug('Locked directory "%s"', self._path) 

26 return self 

27 

28 def __exit__(self, type, value, traceback): 

29 try: 

30 os.remove(self._lockfile) 

31 logger.debug('Unlocked directory "%s"', self._path) 

32 except FileNotFoundError: 

33 logger.warning( 

34 'Lockfile "%s" was removed unintentionally', self._lockfile)