tmpfile.py 1.72 KB
Newer Older
1 2
# vim: set fileencoding=utf-8 :
#
Markus Lehtonen's avatar
Markus Lehtonen committed
3
# (C) 2012, 2015 Intel Corporation <markus.lehtonen@linux.intel.com>
4 5 6 7 8 9 10 11 12 13 14
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
15 16 17
#    along with this program; if not, please see
#    <http://www.gnu.org/licenses/>
#
18 19 20
"""Temporary directory handling"""

import os
Markus Lehtonen's avatar
Markus Lehtonen committed
21
import shutil
22 23 24 25 26
import tempfile

from gbp.errors import GbpError


Markus Lehtonen's avatar
Markus Lehtonen committed
27 28
_old_tempdirs = []

Guido Günther's avatar
Guido Günther committed
29

Markus Lehtonen's avatar
Markus Lehtonen committed
30 31
def init_tmpdir(path, prefix):
    """Initialize a temporary directory structure"""
32
    try:
Markus Lehtonen's avatar
Markus Lehtonen committed
33 34 35 36 37 38 39 40 41 42 43 44 45
        if not os.path.exists(path):
            os.makedirs(path)
    except OSError as err:
        raise GbpError("Unable to create tmpdir %s (%s)" % (path, err))

    tmpdir = tempfile.mkdtemp(dir=path, prefix=prefix)

    # Set newly created dir as the default value for all further tempfile
    # calls
    _old_tempdirs.append(tempfile.tempdir)
    tempfile.tempdir = tmpdir
    return tmpdir

Guido Günther's avatar
Guido Günther committed
46

Markus Lehtonen's avatar
Markus Lehtonen committed
47 48 49 50 51 52 53
def del_tmpdir():
    """Remove tempdir and restore tempfile module"""
    if _old_tempdirs:
        if os.path.exists(tempfile.tempdir) and \
                not os.getenv('GBP_TMPFILE_NOCLEAN'):
            shutil.rmtree(tempfile.tempdir)
        tempfile.tempdir = _old_tempdirs.pop()
54 55

# vim:et:ts=4:sw=4:et:sts=4:ai:set list listchars=tab\:»·,trail\:·: