Skip to content

Commit 2888d95

Browse files
authored
file parsing: check for CWD existence (#5694)
file parsing: check for PWD existence
1 parent 17d6012 commit 2888d95

File tree

3 files changed

+32
-2
lines changed

3 files changed

+32
-2
lines changed

changes.d/5694.fix.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Don't fail config file parsing if current working directory does not exist.
2+
(Note however this may not be enough to prevent file parsing commands failing
3+
elsewhere in the Python library).

cylc/flow/parsec/fileparse.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -401,7 +401,14 @@ def read_and_proc(
401401
fpath = _get_fpath_for_source(fpath, opts)
402402
fdir = os.path.dirname(fpath)
403403

404-
odir = os.getcwd()
404+
try:
405+
original_cwd = os.getcwd()
406+
except FileNotFoundError:
407+
# User's current working directory does not actually exist, so we won't
408+
# be able to change back to it later. (Note this might not be enough to
409+
# prevent file parsing commands failing due to missing cwd elsewhere in
410+
# the Python library).
411+
original_cwd = None
405412

406413
# Move to the file location to give the template processor easy access to
407414
# other files in the workflow directory (whether source or installed).
@@ -500,7 +507,9 @@ def read_and_proc(
500507
if do_contin:
501508
flines = _concatenate(flines)
502509

503-
os.chdir(odir)
510+
# If the user's original working directory exists, change back to it.
511+
if original_cwd is not None:
512+
os.chdir(original_cwd)
504513

505514
# return rstripped lines
506515
return [fl.rstrip() for fl in flines]

tests/unit/parsec/test_fileparse.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -736,3 +736,21 @@ def test_get_fpath_for_source(tmp_path):
736736
opts.against_source = True
737737
assert _get_fpath_for_source(
738738
rundir / 'flow.cylc', opts) == str(srcdir / 'flow.cylc')
739+
740+
def test_user_has_no_cwd(tmp_path):
741+
"""Test we can parse a config file even if cwd does not exist."""
742+
cwd = tmp_path/"cwd"
743+
os.mkdir(cwd)
744+
os.chdir(cwd)
745+
os.rmdir(cwd)
746+
# (I am now located in a non-existent directory. Outrageous!)
747+
with NamedTemporaryFile() as tf:
748+
fpath = tf.name
749+
tf.write(('''
750+
[scheduling]
751+
[[graph]]
752+
R1 = "foo"
753+
''').encode())
754+
tf.flush()
755+
# Should not raise FileNotFoundError from os.getcwd():
756+
parse(fpath=fpath, output_fname="")

0 commit comments

Comments
 (0)