1# http://pyrocko.org - GPLv3 

2# 

3# The Pyrocko Developers, 21st Century 

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

5 

6from __future__ import absolute_import, print_function 

7import os 

8import logging 

9 

10op = os.path 

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

12 

13 

14class LockDir(object): 

15 

16 def __init__(self, path): 

17 self._path = path 

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

19 

20 def __enter__(self): 

21 if op.exists(self._lockfile): 

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

23 

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

25 f.write(b'') 

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

27 return self 

28 

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

30 try: 

31 os.remove(self._lockfile) 

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

33 except FileNotFoundError: 

34 logger.warning( 

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