From ec7096ca1266003f1f5877a73d68c3564ce857f8 Mon Sep 17 00:00:00 2001 From: Hilary James Oliver Date: Wed, 16 Aug 2023 15:57:48 +1200 Subject: [PATCH 1/2] file parsing: check for PWD existence --- cylc/flow/parsec/fileparse.py | 13 +++++++++++-- tests/unit/parsec/test_fileparse.py | 18 ++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/cylc/flow/parsec/fileparse.py b/cylc/flow/parsec/fileparse.py index 9dd757c7cdb..38c959d5e90 100644 --- a/cylc/flow/parsec/fileparse.py +++ b/cylc/flow/parsec/fileparse.py @@ -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). @@ -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] diff --git a/tests/unit/parsec/test_fileparse.py b/tests/unit/parsec/test_fileparse.py index 04b7245f492..a264c04bdb6 100644 --- a/tests/unit/parsec/test_fileparse.py +++ b/tests/unit/parsec/test_fileparse.py @@ -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="") From a1d558b6d0e9c12d9b031c95c6f8016fa83b18cc Mon Sep 17 00:00:00 2001 From: Hilary James Oliver Date: Fri, 25 Aug 2023 10:23:42 +1200 Subject: [PATCH 2/2] Add change log. --- changes.d/5694.fix.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 changes.d/5694.fix.md diff --git a/changes.d/5694.fix.md b/changes.d/5694.fix.md new file mode 100644 index 00000000000..f8fa04eaa9c --- /dev/null +++ b/changes.d/5694.fix.md @@ -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).