instant.paths

Package instant :: Module paths |
[hide private]
[frames] | no frames]

# Source Code for Module instant.paths

     1  """This module contains helper functions for working with temp and cache directories."""
     2
     3  # Utilities for directory handling:
     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
    12 -def get_temp_dir():
    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
    25 -def delete_temp_dir():
    26      """Delete the temporary directory created by get_temp_dir()."""
    27      global _tmp_dir
    28      if _tmp_dir and os.path.isdir(_tmp_dir):
    29          shutil.rmtree(_tmp_dir, ignore_errors=True)
    30      _tmp_dir = None
    31
    32 -def get_instant_dir():
    33      "Return a temporary directory for the duration of this process."
    34      # os.path.expanduser works for Windows, Linux, and Mac
    35      # In Windows, $HOME is os.environ['HOMEDRIVE'] + os.environ['HOMEPATH']
    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
    42 -def get_default_cache_dir():
    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
    50 -def validate_cache_dir(cache_dir):
    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
    59 -def _test():
    60      print "Temp dir:", get_temp_dir()
    61      print "Instant dir:", get_instant_dir()
    62      print "Default cache dir:", get_default_cache_dir()
    63      delete_temp_dir()
    64
    65  if __name__ == "__main__":
    66      _test()
    67