1 """This module contains helper functions for working with temp and cache directories."""
2
3
4
5 import os
6 import errno
7 import shutil
8 import tempfile
9 import time
10 from .output import instant_debug, instant_assert
11
12 _tmp_dir = None
14 """Return a temporary directory for the duration of this process.
15
16 Multiple calls in the same process returns the same directory.
17 Remember to call delete_temp_dir() before exiting."""
18 global _tmp_dir
19 if _tmp_dir is None:
20 datestring = "%d-%d-%d-%02d-%02d" % time.localtime()[:5]
21 suffix = datestring + "_instant"
22 _tmp_dir = tempfile.mkdtemp(suffix)
23 instant_debug("Created temp directory '%s'." % _tmp_dir)
24 return _tmp_dir
25
32
34 "Return the default instant directory, creating it if necessary."
35
36
37 instant_dir = os.path.join(os.path.expanduser("~"), ".instant")
38 makedirs(instant_dir)
39 return instant_dir
40
42 "Return the default cache directory."
43 cache_dir = os.environ.get("INSTANT_CACHE_DIR")
44
45 if not cache_dir:
46 cache_dir = os.path.join(get_instant_dir(), "cache")
47 makedirs(cache_dir)
48 return cache_dir
49
51 "Return the default error directory."
52 error_dir = os.environ.get("INSTANT_ERROR_DIR")
53
54 if not error_dir:
55 error_dir = os.path.join(get_instant_dir(), "error")
56 makedirs(error_dir)
57 return error_dir
58
60 if cache_dir is None:
61 return get_default_cache_dir()
62 instant_assert(isinstance(cache_dir, str), "Expecting cache_dir to be a string.")
63 cache_dir = os.path.abspath(cache_dir)
64 makedirs(cache_dir)
65 return cache_dir
66
68 """
69 Creates a directory (tree). If directory already excists it does nothing.
70 """
71 try:
72 os.makedirs(path)
73 instant_debug("In instant.makedirs: Creating directory %r" % path)
74 except os.error as e:
75 if e.errno != errno.EEXIST:
76 raise
77
86
87 if __name__ == "__main__":
88 _test()
89