Skip to content

Commit

Permalink
file parsing: check for CWD existence (#5694)
Browse files Browse the repository at this point in the history
file parsing: check for PWD existence
  • Loading branch information
hjoliver authored Aug 25, 2023
1 parent 17d6012 commit 2888d95
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 2 deletions.
3 changes: 3 additions & 0 deletions changes.d/5694.fix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Don't fail config file parsing if current working directory does not exist.
(Note however this may not be enough to prevent file parsing commands failing
elsewhere in the Python library).
13 changes: 11 additions & 2 deletions cylc/flow/parsec/fileparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -401,7 +401,14 @@ def read_and_proc(
fpath = _get_fpath_for_source(fpath, opts)
fdir = os.path.dirname(fpath)

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

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

os.chdir(odir)
# If the user's original working directory exists, change back to it.
if original_cwd is not None:
os.chdir(original_cwd)

# return rstripped lines
return [fl.rstrip() for fl in flines]
Expand Down
18 changes: 18 additions & 0 deletions tests/unit/parsec/test_fileparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -736,3 +736,21 @@ def test_get_fpath_for_source(tmp_path):
opts.against_source = True
assert _get_fpath_for_source(
rundir / 'flow.cylc', opts) == str(srcdir / 'flow.cylc')

def test_user_has_no_cwd(tmp_path):
"""Test we can parse a config file even if cwd does not exist."""
cwd = tmp_path/"cwd"
os.mkdir(cwd)
os.chdir(cwd)
os.rmdir(cwd)
# (I am now located in a non-existent directory. Outrageous!)
with NamedTemporaryFile() as tf:
fpath = tf.name
tf.write(('''
[scheduling]
[[graph]]
R1 = "foo"
''').encode())
tf.flush()
# Should not raise FileNotFoundError from os.getcwd():
parse(fpath=fpath, output_fname="")

0 comments on commit 2888d95

Please sign in to comment.