Add context manager to change working dir

The context manager takes care of restoring the current working
directory when we are done. This is useful when the directory we set as
working directory stops existing.
pull/443/head
Tim Head 2018-10-16 10:41:06 +02:00
rodzic 4e1eff5f1b
commit df7251dff6
3 zmienionych plików z 56 dodań i 35 usunięć

Wyświetl plik

@ -35,7 +35,7 @@ from .buildpacks import (
from . import contentproviders from . import contentproviders
from .utils import ( from .utils import (
ByteSpecification, maybe_cleanup, is_valid_docker_image_name, ByteSpecification, maybe_cleanup, is_valid_docker_image_name,
validate_and_generate_port_mapping validate_and_generate_port_mapping, execute_cmd, check_ref, chdir
) )
@ -710,43 +710,42 @@ class Repo2Docker(Application):
self.subdir, extra=dict(phase='failure')) self.subdir, extra=dict(phase='failure'))
sys.exit(1) sys.exit(1)
os.chdir(checkout_path) with chdir(checkout_path):
for BP in self.buildpacks:
bp = BP()
if bp.detect():
picked_buildpack = bp
break
else:
picked_buildpack = self.default_buildpack()
for BP in self.buildpacks: picked_buildpack.appendix = self.appendix
bp = BP()
if bp.detect():
picked_buildpack = bp
break
else:
picked_buildpack = self.default_buildpack()
picked_buildpack.appendix = self.appendix self.log.debug(picked_buildpack.render(),
extra=dict(phase='building'))
self.log.debug(picked_buildpack.render(), if self.build:
extra=dict(phase='building')) build_args = {
'NB_USER': self.user_name,
'NB_UID': str(self.user_id)
}
self.log.info('Using %s builder\n', bp.__class__.__name__,
extra=dict(phase='building'))
if self.build: for l in picked_buildpack.build(self.output_image_spec,
build_args = { self.build_memory_limit, build_args):
'NB_USER': self.user_name, if 'stream' in l:
'NB_UID': str(self.user_id) self.log.info(l['stream'],
} extra=dict(phase='building'))
self.log.info('Using %s builder\n', bp.__class__.__name__, elif 'error' in l:
extra=dict(phase='building')) self.log.info(l['error'], extra=dict(phase='failure'))
sys.exit(1)
for l in picked_buildpack.build(self.output_image_spec, elif 'status' in l:
self.build_memory_limit, build_args): self.log.info('Fetching base image...\r',
if 'stream' in l: extra=dict(phase='building'))
self.log.info(l['stream'], else:
extra=dict(phase='building')) self.log.info(json.dumps(l),
elif 'error' in l:
self.log.info(l['error'], extra=dict(phase='failure'))
sys.exit(1)
elif 'status' in l:
self.log.info('Fetching base image...\r',
extra=dict(phase='building')) extra=dict(phase='building'))
else:
self.log.info(json.dumps(l),
extra=dict(phase='building'))
if self.push: if self.push:
self.push_image() self.push_image()

Wyświetl plik

@ -1,5 +1,6 @@
from contextlib import contextmanager from contextlib import contextmanager
from functools import partial from functools import partial
import os
import re import re
import shutil import shutil
import subprocess import subprocess
@ -51,6 +52,21 @@ def execute_cmd(cmd, capture=False, **kwargs):
raise subprocess.CalledProcessError(ret, cmd) raise subprocess.CalledProcessError(ret, cmd)
@contextmanager
def chdir(path):
"""Change working directory to `path` and restore it again
This context maanger is useful if `path` stops existing during your
operations.
"""
old_dir = os.getcwd()
os.chdir(path)
try:
yield
finally:
os.chdir(old_dir)
@contextmanager @contextmanager
def maybe_cleanup(path, cleanup=False): def maybe_cleanup(path, cleanup=False):
"""Delete the directory at passed path if cleanup flag is True.""" """Delete the directory at passed path if cleanup flag is True."""

Wyświetl plik

@ -1,6 +1,7 @@
""" """
Test if the subdirectory is correctly navigated to Test if the subdirectory is correctly navigated to
""" """
import os
import logging import logging
import pytest import pytest
@ -13,13 +14,18 @@ def test_subdir(run_repo2docker):
# Build from a subdirectory # Build from a subdirectory
# if subdir support is broken this will fail as the instructions in the # if subdir support is broken this will fail as the instructions in the
# root of the test repo are invalid # root of the test repo are invalid
cwd = os.getcwd()
argv = ['--subdir', 'a directory', TEST_REPO] argv = ['--subdir', 'a directory', TEST_REPO]
run_repo2docker(argv) run_repo2docker(argv)
# check that we restored the current working directory
assert cwd == os.getcwd(), "We should be back in %s" % cwd
def test_subdir_invalid(caplog): def test_subdir_invalid(caplog):
# test an error is raised when requesting a non existent subdir # test an error is raised when requesting a non existent subdir
caplog.set_level(logging.INFO) #caplog.set_level(logging.INFO, logger='Repo2Docker')
app = Repo2Docker() app = Repo2Docker()
argv = ['--subdir', 'invalid-sub-dir', TEST_REPO] argv = ['--subdir', 'invalid-sub-dir', TEST_REPO]
@ -34,4 +40,4 @@ def test_subdir_invalid(caplog):
assert excinfo.value.code == 1 assert excinfo.value.code == 1
# Can't get this to record the logs? # Can't get this to record the logs?
assert caplog.text == "Subdirectory tests/conda/invalid does not exist" #assert caplog.text == "Subdirectory tests/conda/invalid does not exist"