Skip to content

Commit 5bc4746

Browse files
authored
Merge pull request #4525 from lexming/get_cwd
add new `get_cwd` function to `tools.filetools` to retrieve current working directory
2 parents cf36c7e + 336d5b0 commit 5bc4746

File tree

13 files changed

+82
-44
lines changed

13 files changed

+82
-44
lines changed

easybuild/base/optcomplete.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,7 @@
107107
from optparse import OptionParser, Option
108108
from pprint import pformat
109109

110+
from easybuild.tools.filetools import get_cwd
110111
from easybuild.tools.utilities import shell_quote
111112

112113
debugfn = None # for debugging only
@@ -537,7 +538,7 @@ def autocomplete(parser, arg_completer=None, opt_completer=None, subcmd_complete
537538
# Note: this will get filtered properly below.
538539

539540
completer_kwargs = {
540-
'pwd': os.getcwd(),
541+
'pwd': get_cwd(),
541542
'cline': cline,
542543
'cpoint': cpoint,
543544
'prefix': prefix,

easybuild/framework/easyblock.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -81,8 +81,8 @@
8181
from easybuild.tools.filetools import adjust_permissions, apply_patch, back_up_file, change_dir, check_lock
8282
from easybuild.tools.filetools import compute_checksum, convert_name, copy_file, create_lock, create_patch_info
8383
from easybuild.tools.filetools import derive_alt_pypi_url, diff_files, dir_contains_files, download_file
84-
from easybuild.tools.filetools import encode_class_name, extract_file
85-
from easybuild.tools.filetools import find_backup_name_candidate, get_source_tarball_from_git, is_alt_pypi_url
84+
from easybuild.tools.filetools import encode_class_name, extract_file, find_backup_name_candidate
85+
from easybuild.tools.filetools import get_cwd, get_source_tarball_from_git, is_alt_pypi_url
8686
from easybuild.tools.filetools import is_binary, is_sha256_checksum, mkdir, move_file, move_logs, read_file, remove_dir
8787
from easybuild.tools.filetools import remove_file, remove_lock, verify_checksum, weld_paths, write_file, symlink
8888
from easybuild.tools.hooks import BUILD_STEP, CLEANUP_STEP, CONFIGURE_STEP, EXTENSIONS_STEP, FETCH_STEP, INSTALL_STEP
@@ -151,7 +151,7 @@ def __init__(self, ec):
151151
"""
152152

153153
# keep track of original working directory, so we can go back there
154-
self.orig_workdir = os.getcwd()
154+
self.orig_workdir = get_cwd()
155155

156156
# dict of all hooks (mapping of name to function)
157157
self.hooks = load_hooks(build_option('hooks'))
@@ -3721,7 +3721,7 @@ def cleanup_step(self):
37213721

37223722
# make sure we're out of the dir we're removing
37233723
change_dir(self.orig_workdir)
3724-
self.log.info("Cleaning up builddir %s (in %s)", self.builddir, os.getcwd())
3724+
self.log.info("Cleaning up builddir %s (in %s)", self.builddir, get_cwd())
37253725

37263726
try:
37273727
remove_dir(self.builddir)
@@ -4245,7 +4245,7 @@ def build_and_install_one(ecdict, init_env):
42454245
restore_env(init_env)
42464246
sanitize_env()
42474247

4248-
cwd = os.getcwd()
4248+
cwd = get_cwd()
42494249

42504250
# load easyblock
42514251
easyblock = build_option('easyblock')
@@ -4550,7 +4550,7 @@ def build_easyconfigs(easyconfigs, output_dir, test_results):
45504550
instance = get_easyblock_instance(ec)
45514551
apps.append(instance)
45524552

4553-
base_dir = os.getcwd()
4553+
base_dir = get_cwd()
45544554

45554555
# keep track of environment right before initiating builds
45564556
# note: may be different from ORIG_OS_ENVIRON, since EasyBuild may have defined additional env vars itself by now

easybuild/framework/easyconfig/tools.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@
5757
from easybuild.tools.build_log import EasyBuildError, print_msg, print_warning
5858
from easybuild.tools.config import build_option
5959
from easybuild.tools.environment import restore_env
60-
from easybuild.tools.filetools import find_easyconfigs, is_patch_file, locate_files
60+
from easybuild.tools.filetools import find_easyconfigs, get_cwd, is_patch_file, locate_files
6161
from easybuild.tools.filetools import read_file, resolve_path, which, write_file
6262
from easybuild.tools.github import GITHUB_EASYCONFIGS_REPO
6363
from easybuild.tools.github import det_pr_labels, det_pr_title, download_repo, fetch_easyconfigs_from_commit
@@ -792,14 +792,13 @@ def det_copy_ec_specs(orig_paths, from_pr=None, from_commit=None):
792792

793793
target_path, paths = None, []
794794

795-
# if only one argument is specified, use current directory as target directory
796795
if len(orig_paths) == 1:
797-
target_path = os.getcwd()
796+
# if only one argument is specified, use current directory as target directory
797+
target_path = get_cwd()
798798
paths = orig_paths[:]
799-
800-
# if multiple arguments are specified, assume that last argument is target location,
801-
# and remove that from list of paths to copy
802799
elif orig_paths:
800+
# if multiple arguments are specified, assume that last argument is target location,
801+
# and remove that from list of paths to copy
803802
target_path = orig_paths[-1]
804803
paths = orig_paths[:-1]
805804

@@ -817,7 +816,7 @@ def det_copy_ec_specs(orig_paths, from_pr=None, from_commit=None):
817816
pr_paths.extend(fetch_files_from_pr(pr=pr, path=tmpdir))
818817

819818
# assume that files need to be copied to current working directory for now
820-
target_path = os.getcwd()
819+
target_path = get_cwd()
821820

822821
if orig_paths:
823822
last_path = orig_paths[-1]
@@ -854,7 +853,7 @@ def det_copy_ec_specs(orig_paths, from_pr=None, from_commit=None):
854853
commit_paths = fetch_files_from_commit(from_commit, path=tmpdir)
855854

856855
# assume that files need to be copied to current working directory for now
857-
target_path = os.getcwd()
856+
target_path = get_cwd()
858857

859858
if orig_paths:
860859
last_path = orig_paths[-1]

easybuild/tools/build_log.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,11 @@
6161
DRY_RUN_SOFTWARE_INSTALL_DIR = None
6262
DRY_RUN_MODULES_INSTALL_DIR = None
6363

64+
CWD_NOTFOUND_ERROR = (
65+
"Current working directory does not exist! It was either unexpectedly removed "
66+
"by an external process to EasyBuild or the filesystem is misbehaving."
67+
)
68+
6469

6570
DEVEL_LOG_LEVEL = logging.DEBUG - 1
6671
logging.addLevelName(DEVEL_LOG_LEVEL, 'DEVEL')

easybuild/tools/filetools.py

Lines changed: 30 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@
6262

6363
from easybuild.base import fancylogger
6464
# import build_log must stay, to use of EasyBuildLog
65-
from easybuild.tools.build_log import EasyBuildError, dry_run_msg, print_msg, print_warning
65+
from easybuild.tools.build_log import EasyBuildError, CWD_NOTFOUND_ERROR, dry_run_msg, print_msg, print_warning
6666
from easybuild.tools.config import ERROR, GENERIC_EASYBLOCK_PKG, IGNORE, WARN, build_option, install_path
6767
from easybuild.tools.output import PROGRESS_BAR_DOWNLOAD_ONE, start_progress_bar, stop_progress_bar, update_progress_bar
6868
from easybuild.tools.hooks import load_source
@@ -407,26 +407,42 @@ def remove(paths):
407407
raise EasyBuildError("Specified path to remove is not an existing file or directory: %s", path)
408408

409409

410+
def get_cwd(must_exist=True):
411+
"""
412+
Retrieve current working directory
413+
"""
414+
try:
415+
cwd = os.getcwd()
416+
except FileNotFoundError as err:
417+
if must_exist is True:
418+
raise EasyBuildError(CWD_NOTFOUND_ERROR)
419+
420+
_log.debug("Failed to determine current working directory, but proceeding anyway: %s", err)
421+
cwd = None
422+
423+
return cwd
424+
425+
410426
def change_dir(path):
411427
"""
412428
Change to directory at specified location.
413429
414430
:param path: location to change to
415431
:return: previous location we were in
416432
"""
417-
# determining the current working directory can fail if we're in a non-existing directory
418-
try:
419-
cwd = os.getcwd()
420-
except OSError as err:
421-
_log.debug("Failed to determine current working directory (but proceeding anyway: %s", err)
422-
cwd = None
433+
# determine origin working directory: can fail if non-existent
434+
prev_dir = get_cwd(must_exist=False)
423435

424436
try:
425437
os.chdir(path)
426438
except OSError as err:
427-
raise EasyBuildError("Failed to change from %s to %s: %s", cwd, path, err)
439+
raise EasyBuildError("Failed to change from %s to %s: %s", prev_dir, path, err)
428440

429-
return cwd
441+
# determine final working directory: must exist
442+
# stoplight meant to catch filesystems in a faulty state
443+
get_cwd()
444+
445+
return prev_dir
430446

431447

432448
def extract_file(fn, dest, cmd=None, extra_options=None, overwrite=False, forced=False, change_into_dir=False,
@@ -671,9 +687,9 @@ def parse_http_header_fields_urlpat(arg, urlpat=None, header=None, urlpat_header
671687
if argline == '' or '#' in argline[0]:
672688
continue # permit comment lines: ignore them
673689

674-
if os.path.isfile(os.path.join(os.getcwd(), argline)):
690+
if os.path.isfile(os.path.join(get_cwd(), argline)):
675691
# expand existing relative path to absolute
676-
argline = os.path.join(os.path.join(os.getcwd(), argline))
692+
argline = os.path.join(os.path.join(get_cwd(), argline))
677693
if os.path.isfile(argline):
678694
# argline is a file path, so read that instead
679695
_log.debug('File included in parse_http_header_fields_urlpat: %s' % argline)
@@ -1332,14 +1348,14 @@ def get_local_dirs_purged():
13321348
# and hidden directories
13331349
ignoredirs = ["easybuild"]
13341350

1335-
lst = os.listdir(os.getcwd())
1351+
lst = os.listdir(get_cwd())
13361352
lst = [d for d in lst if not d.startswith('.') and d not in ignoredirs]
13371353
return lst
13381354

13391355
lst = get_local_dirs_purged()
1340-
new_dir = os.getcwd()
1356+
new_dir = get_cwd()
13411357
while len(lst) == 1:
1342-
new_dir = os.path.join(os.getcwd(), lst[0])
1358+
new_dir = os.path.join(get_cwd(), lst[0])
13431359
if not os.path.isdir(new_dir):
13441360
break
13451361

easybuild/tools/job/pbs_python.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939
from easybuild.base import fancylogger
4040
from easybuild.tools.build_log import EasyBuildError, print_msg
4141
from easybuild.tools.config import JOB_DEPS_TYPE_ABORT_ON_ERROR, JOB_DEPS_TYPE_ALWAYS_RUN, build_option
42+
from easybuild.tools.filetools import get_cwd
4243
from easybuild.tools.job.backend import JobBackend
4344
from easybuild.tools.utilities import only_if_module_is_available
4445

@@ -320,8 +321,8 @@ def _submit(self):
320321
self.log.debug("Job hold attributes: %s" % hold_attributes[0].value)
321322

322323
# add a bunch of variables (added by qsub)
323-
# also set PBS_O_WORKDIR to os.getcwd()
324-
os.environ.setdefault('WORKDIR', os.getcwd())
324+
# also set PBS_O_WORKDIR to current working dir
325+
os.environ.setdefault('WORKDIR', get_cwd())
325326

326327
defvars = ['MAIL', 'HOME', 'PATH', 'SHELL', 'WORKDIR']
327328
pbsvars = ["PBS_O_%s=%s" % (x, os.environ.get(x, 'NOTFOUND_%s' % x)) for x in defvars]

easybuild/tools/options.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -84,8 +84,8 @@
8484
from easybuild.tools.docs import avail_toolchain_opts, avail_easyconfig_params, avail_easyconfig_templates
8585
from easybuild.tools.docs import list_easyblocks, list_toolchains
8686
from easybuild.tools.environment import restore_env, unset_env_vars
87-
from easybuild.tools.filetools import CHECKSUM_TYPE_SHA256, CHECKSUM_TYPES, expand_glob_paths, install_fake_vsc
88-
from easybuild.tools.filetools import move_file, which
87+
from easybuild.tools.filetools import CHECKSUM_TYPE_SHA256, CHECKSUM_TYPES, expand_glob_paths, get_cwd
88+
from easybuild.tools.filetools import install_fake_vsc, move_file, which
8989
from easybuild.tools.github import GITHUB_PR_DIRECTION_DESC, GITHUB_PR_ORDER_CREATED
9090
from easybuild.tools.github import GITHUB_PR_STATE_OPEN, GITHUB_PR_STATES, GITHUB_PR_ORDERS, GITHUB_PR_DIRECTIONS
9191
from easybuild.tools.github import HAVE_GITHUB_API, HAVE_KEYRING, VALID_CLOSE_PR_REASONS
@@ -829,7 +829,7 @@ def job_options(self):
829829
'eb-cmd': ("EasyBuild command to use in jobs", 'str', 'store', DEFAULT_JOB_EB_CMD),
830830
'max-jobs': ("Maximum number of concurrent jobs (queued and running, 0 = unlimited)", 'int', 'store', 0),
831831
'max-walltime': ("Maximum walltime for jobs (in hours)", 'int', 'store', 24),
832-
'output-dir': ("Output directory for jobs (default: current directory)", None, 'store', os.getcwd()),
832+
'output-dir': ("Output directory for jobs (default: current directory)", None, 'store', get_cwd()),
833833
'polling-interval': ("Interval between polls for status of jobs (in seconds)", float, 'store', 30.0),
834834
'target-resource': ("Target resource for jobs", None, 'store', None),
835835
})

easybuild/tools/parallelbuild.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@
4343
from easybuild.framework.easyconfig.easyconfig import ActiveMNS
4444
from easybuild.tools.build_log import EasyBuildError
4545
from easybuild.tools.config import build_option, get_repository, get_repositorypath
46+
from easybuild.tools.filetools import get_cwd
4647
from easybuild.tools.module_naming_scheme.utilities import det_full_ec_version
4748
from easybuild.tools.job.backend import job_backend
4849
from easybuild.tools.repository.repository import init_repository
@@ -126,7 +127,7 @@ def submit_jobs(ordered_ecs, cmd_line_opts, testing=False, prepare_first=True):
126127
:param testing: If `True`, skip actual job submission
127128
:param prepare_first: prepare by runnning fetch step first for each easyconfig
128129
"""
129-
curdir = os.getcwd()
130+
curdir = get_cwd()
130131

131132
# regex pattern for options to ignore (help options can't reach here)
132133
ignore_opts = re.compile('^--robot$|^--job|^--try-.*$|^--easystack$')

easybuild/tools/repository/svnrepo.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@
4646

4747
from easybuild.base import fancylogger
4848
from easybuild.tools.build_log import EasyBuildError
49-
from easybuild.tools.filetools import remove_dir
49+
from easybuild.tools.filetools import get_cwd, remove_dir
5050
from easybuild.tools.repository.filerepo import FileRepository
5151
from easybuild.tools.utilities import only_if_module_is_available
5252

@@ -145,7 +145,7 @@ def stage_file(self, path):
145145
"""
146146
if self.client and not self.client.status(path)[0].is_versioned:
147147
# add it to version control
148-
self.log.debug("Going to add %s (working copy: %s, cwd %s)" % (path, self.wc, os.getcwd()))
148+
self.log.debug("Going to add %s (working copy: %s, cwd %s)" % (path, self.wc, get_cwd()))
149149
self.client.add(path)
150150

151151
def add_easyconfig(self, cfg, name, version, stats, previous_stats):

easybuild/tools/robot.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@
4545
from easybuild.framework.easyconfig.tools import find_resolved_modules, skip_available
4646
from easybuild.tools.build_log import EasyBuildError
4747
from easybuild.tools.config import build_option
48-
from easybuild.tools.filetools import det_common_path_prefix, search_file
48+
from easybuild.tools.filetools import det_common_path_prefix, get_cwd, search_file
4949
from easybuild.tools.module_naming_scheme.easybuild_mns import EasyBuildMNS
5050
from easybuild.tools.module_naming_scheme.utilities import det_full_ec_version
5151
from easybuild.tools.utilities import flatten, nub
@@ -491,7 +491,7 @@ def search_easyconfigs(query, short=False, filename_only=False, terse=False, con
491491
"""
492492
search_path = build_option('robot_path')
493493
if not search_path:
494-
search_path = [os.getcwd()]
494+
search_path = [get_cwd()]
495495
extra_search_paths = build_option('search_paths')
496496
# If we're returning a list of possible resolutions by the robot, don't include the extra_search_paths
497497
if extra_search_paths and consider_extra_paths:

0 commit comments

Comments
 (0)