Skip to content

Commit

Permalink
added a more centralized way to preserve temp files for debugging (#659)
Browse files Browse the repository at this point in the history
  • Loading branch information
notestaff committed Aug 23, 2017
1 parent b985ebb commit b2065ad
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 9 deletions.
3 changes: 2 additions & 1 deletion util/cmd.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import logging
import argparse
import util.version
import util.file

__author__ = "dpark@broadinstitute.org"
__version__ = util.version.get_version()
Expand Down Expand Up @@ -200,7 +201,7 @@ def main_argparse(commands, description):
try:
ret = args.func_main(args)
finally:
if hasattr(args, 'tmp_dirKeep') and args.tmp_dirKeep:
if (hasattr(args, 'tmp_dirKeep') and args.tmp_dirKeep) or util.file.keep_tmp():
log.exception(
"Exception occurred while running %s, saving tmp_dir at %s", args.command, tempfile.tempdir)
else:
Expand Down
36 changes: 28 additions & 8 deletions util/file.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,6 @@ def get_resources():
resources = json.load(inf)
return resources


def mkstempfname(suffix='', prefix='tmp', directory=None, text=False):
''' There's no other one-liner way to securely ask for a temp file by
filename only. This calls mkstemp, which does what we want, except
Expand Down Expand Up @@ -111,9 +110,29 @@ def tempfnames(suffixes, *args, **kwargs):
try:
yield fns
finally:
for fn in fns:
if os.path.isfile(fn):
os.unlink(fn)
if not keep_tmp():
for fn in fns:
if os.path.isfile(fn):
os.unlink(fn)

@contextlib.contextmanager
def tmp_dir(*args, **kwargs):
"""Create and return a temporary directory, which is cleaned up on context exit
unless keep_tmp() is True."""
try:
name = tempfile.mkdtemp(*args, **kwargs)
yield name
finally:
if keep_tmp():
log.debug('keeping tempdir ' + name)
else:
shutil.rmtree(name)

def keep_tmp():
"""Whether to preserve temporary directories and files (useful during debugging).
Return True if the environment variable VIRAL_NGS_TMP_DIRKEEP is set.
"""
return 'VIRAL_NGS_TMP_DIRKEEP' in os.environ

def set_tmp_dir(name):
proposed_prefix = ['tmp']
Expand All @@ -129,10 +148,11 @@ def set_tmp_dir(name):


def destroy_tmp_dir(tempdir=None):
if tempdir:
shutil.rmtree(tempdir)
elif tempfile.tempdir:
shutil.rmtree(tempfile.tempdir)
if not keep_tmp():
if tempdir:
shutil.rmtree(tempdir)
elif tempfile.tempdir:
shutil.rmtree(tempfile.tempdir)
tempfile.tempdir = None


Expand Down

0 comments on commit b2065ad

Please sign in to comment.