1 """This module contains helper functions for working with temp and cache directories."""
2
3
4
5 import os
6 import shutil
7 import tempfile
8 import time
9 from output import instant_debug, instant_assert
10
11 _tmp_dir = None
13 """Return a temporary directory for the duration of this process.
14
15 Multiple calls in the same process returns the same directory.
16 Remember to all delete_temp_dir() before exiting."""
17 global _tmp_dir
18 if _tmp_dir is None:
19 datestring = "%d-%d-%d-%02d-%02d" % time.localtime()[:5]
20 suffix = datestring + "_instant"
21 _tmp_dir = tempfile.mkdtemp(suffix)
22 instant_debug("Created temp directory '%s'." % _tmp_dir)
23 return _tmp_dir
24
31
33 "Return a temporary directory for the duration of this process."
34
35
36 instant_dir = os.path.join(os.path.expanduser("~"), ".instant")
37 if not os.path.isdir(instant_dir):
38 instant_debug("Creating instant directory '%s'." % instant_dir)
39 os.mkdir(instant_dir)
40 return instant_dir
41
43 "Return the default cache directory."
44 cache_dir = os.path.join(get_instant_dir(), "cache")
45 if not os.path.isdir(cache_dir):
46 instant_debug("Creating cache directory '%s'." % cache_dir)
47 os.mkdir(cache_dir)
48 return cache_dir
49
51 if cache_dir is None:
52 return get_default_cache_dir()
53 instant_assert(isinstance(cache_dir, str), "Expecting cache_dir to be a string.")
54 cache_dir = os.path.abspath(cache_dir)
55 if not os.path.isdir(cache_dir):
56 os.mkdir(cache_dir)
57 return cache_dir
58
64
65 if __name__ == "__main__":
66 _test()
67