tmpfile.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. # vim: set fileencoding=utf-8 :
  2. #
  3. # (C) 2012, 2015 Intel Corporation <markus.lehtonen@linux.intel.com>
  4. # This program is free software; you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License as published by
  6. # the Free Software Foundation; either version 2 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program; if not, please see
  16. # <http://www.gnu.org/licenses/>
  17. #
  18. """Temporary directory handling"""
  19. import os
  20. import shutil
  21. import tempfile
  22. from gbp.errors import GbpError
  23. _old_tempdirs = []
  24. def init_tmpdir(path, prefix):
  25. """Initialize a temporary directory structure"""
  26. try:
  27. if not os.path.exists(path):
  28. os.makedirs(path)
  29. except OSError as err:
  30. raise GbpError("Unable to create tmpdir %s (%s)" % (path, err))
  31. tmpdir = tempfile.mkdtemp(dir=path, prefix=prefix)
  32. # Set newly created dir as the default value for all further tempfile
  33. # calls
  34. _old_tempdirs.append(tempfile.tempdir)
  35. tempfile.tempdir = tmpdir
  36. return tmpdir
  37. def del_tmpdir():
  38. """Remove tempdir and restore tempfile module"""
  39. if _old_tempdirs:
  40. if os.path.exists(tempfile.tempdir) and \
  41. not os.getenv('GBP_TMPFILE_NOCLEAN'):
  42. shutil.rmtree(tempfile.tempdir)
  43. tempfile.tempdir = _old_tempdirs.pop()
  44. # vim:et:ts=4:sw=4:et:sts=4:ai:set list listchars=tab\:»·,trail\:·: