Max Rasskazov | 4e1f311 | 2015-06-04 21:22:42 +0300 | [diff] [blame] | 1 | #-*- coding: utf-8 -*- |
| 2 | |
| 3 | import os |
| 4 | import shutil |
| 5 | import tempfile |
| 6 | |
| 7 | import utils |
| 8 | |
| 9 | |
| 10 | class TempFiles(object): |
| 11 | def __init__(self): |
| 12 | self.logger = utils.logger.getChild('TempFiles') |
| 13 | self._temp_dirs = list() |
| 14 | self.empty_dir |
| 15 | |
| 16 | def __enter__(self): |
| 17 | return self |
| 18 | |
| 19 | def __exit__(self, type, value, traceback): |
| 20 | self.__del__() |
| 21 | |
| 22 | def __del__(self): |
| 23 | for d in self._temp_dirs: |
| 24 | if os.path.isdir(d): |
| 25 | shutil.rmtree(d) |
| 26 | self.logger.debug('Removed temporary directory "{}"'.format(d)) |
| 27 | |
| 28 | @property |
| 29 | def empty_dir(self): |
| 30 | if self.__dict__.get('_empty_dir') is None: |
| 31 | self._empty_dir = self.get_temp_dir() |
| 32 | return self._empty_dir |
| 33 | |
| 34 | def get_temp_dir(self, subdirs=None): |
| 35 | temp_dir = tempfile.mkdtemp() |
| 36 | self._temp_dirs.append(temp_dir) |
| 37 | msg = 'Created temporary directory "{}"'.format(temp_dir) |
| 38 | if subdirs is not None: |
| 39 | self.create_subdirs(subdirs, temp_dir) |
| 40 | msg += ' including subdirs "{}"'.format(subdirs) |
| 41 | self.logger.debug(msg) |
| 42 | return temp_dir |
| 43 | |
| 44 | def create_subdirs(self, subdirs, temp_dir): |
| 45 | if not os.path.isdir(temp_dir): |
| 46 | temp_dir = self.get_temp_dir() |
| 47 | if subdirs is not None: |
| 48 | if type(subdirs) == str: |
| 49 | _ = subdirs |
| 50 | subdirs = list() |
| 51 | subdirs.append(_) |
| 52 | if type(subdirs) in (list, tuple): |
| 53 | for s in subdirs: |
Max Rasskazov | ccaf041 | 2015-06-16 17:34:07 +0300 | [diff] [blame] | 54 | os.makedirs(os.path.join(temp_dir, |
| 55 | s.strip(os.path.sep + '~'))) |
Max Rasskazov | 4e1f311 | 2015-06-04 21:22:42 +0300 | [diff] [blame] | 56 | else: |
| 57 | raise Exception('subdirs should be tuple or list of strings, ' |
| 58 | 'but currentry subdirs == {}'.format(subdirs)) |
| 59 | return temp_dir |
| 60 | |
| 61 | def get_symlink_to(self, target, temp_dir=None): |
| 62 | if temp_dir is None: |
| 63 | temp_dir = self.get_temp_dir() |
| 64 | linkname = tempfile.mktemp(dir=temp_dir) |
| 65 | os.symlink(target.strip(os.path.sep), linkname) |
| 66 | self.logger.debug('Creates temporary symlink "{} -> {}"' |
| 67 | ''.format(linkname, target)) |
| 68 | return linkname |