blob: c3ffb3dcc7eee047f746c0217fa547a3c7056f5b [file] [log] [blame]
Max Rasskazov4e1f3112015-06-04 21:22:42 +03001#-*- coding: utf-8 -*-
2
3import os
4import shutil
5import tempfile
6
7import utils
8
9
10class 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
Max Rasskazov96bb0292015-06-23 15:22:05 +030044 @property
45 def last_temp_dir(self):
46 return self._temp_dirs[-1]
47
Max Rasskazov4e1f3112015-06-04 21:22:42 +030048 def create_subdirs(self, subdirs, temp_dir):
49 if not os.path.isdir(temp_dir):
50 temp_dir = self.get_temp_dir()
51 if subdirs is not None:
52 if type(subdirs) == str:
53 _ = subdirs
54 subdirs = list()
55 subdirs.append(_)
56 if type(subdirs) in (list, tuple):
57 for s in subdirs:
Max Rasskazovccaf0412015-06-16 17:34:07 +030058 os.makedirs(os.path.join(temp_dir,
59 s.strip(os.path.sep + '~')))
Max Rasskazov4e1f3112015-06-04 21:22:42 +030060 else:
61 raise Exception('subdirs should be tuple or list of strings, '
62 'but currentry subdirs == {}'.format(subdirs))
63 return temp_dir
64
65 def get_symlink_to(self, target, temp_dir=None):
66 if temp_dir is None:
67 temp_dir = self.get_temp_dir()
68 linkname = tempfile.mktemp(dir=temp_dir)
69 os.symlink(target.strip(os.path.sep), linkname)
70 self.logger.debug('Creates temporary symlink "{} -> {}"'
71 ''.format(linkname, target))
72 return linkname
Max Rasskazov96bb0292015-06-23 15:22:05 +030073
74 def get_file(self, content='', temp_dir=None):
75 if temp_dir is None:
76 temp_dir = self.get_temp_dir()
77 filename = tempfile.mktemp(dir=temp_dir)
78 with open(filename, 'w') as outfile:
79 outfile.write(content)
80 self.logger.debug('Creates temporary file "{}"'.format(filename))
81 return filename