From 352c309c0b4b5fd2c6af78dcf01013bfb6def6a6 Mon Sep 17 00:00:00 2001 From: Sebastiaan Huber Date: Mon, 13 May 2024 16:18:13 +0200 Subject: [PATCH] `ShellParser`: Prefix output filenames starting with a number The `format_link_label` now checks whether the filename starts with a number, in which case the link label is prefixed with `aiida_shell_` because Python identifiers cannot start with a number. --- src/aiida_shell/parsers/shell.py | 10 +++++++--- tests/parsers/test_shell.py | 4 +++- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/src/aiida_shell/parsers/shell.py b/src/aiida_shell/parsers/shell.py index 8878a3a..ef64640 100644 --- a/src/aiida_shell/parsers/shell.py +++ b/src/aiida_shell/parsers/shell.py @@ -57,13 +57,17 @@ def exit_code(self, key: str, **kwargs: t.Any) -> ExitCode: def format_link_label(filename: str) -> str: """Format the link label from a given filename. - Valid link labels can only contain alphanumeric characters and underscores, without consecutive underscores. So - all characters that are not alphanumeric or an underscore are converted to underscores, where consecutive - underscores are merged into one. + Valid link labels can only contain alphanumeric characters and underscores, without consecutive underscores. + They can also not start with a number. So all characters that are not alphanumeric or an underscore are + converted to underscores, where consecutive underscores are merged into one. Filenames that start with a number + are prefixed with ``aiida_shell_``. :param filename: The filename. :returns: The link label. """ + if re.match('^[0-9]+.*', filename): + filename = f'aiida_shell_{filename}' + alphanumeric = re.sub('[^0-9a-zA-Z_]+', '_', filename) link_label = re.sub('_[_]+', '_', alphanumeric) return link_label diff --git a/tests/parsers/test_shell.py b/tests/parsers/test_shell.py index e06dd1a..176c6ef 100644 --- a/tests/parsers/test_shell.py +++ b/tests/parsers/test_shell.py @@ -120,13 +120,14 @@ def test_outputs_missing(parse_calc_job, create_retrieved_temporary): ( ('filename-with-dashes.txt', 'filename_with_dashes_txt'), ('file@@name.txt', 'file_name_txt'), + ('123startingnumbers', 'aiida_shell_123startingnumbers'), ), ) def test_outputs_link_labels(parse_calc_job, create_retrieved_temporary, filename, link_label): """Test that filenames are converted into valid link labels. Any characters that are non-alphanumeric or underscores should be converted to underscores where consecutive - underscores are merged into one. + underscores are merged into one. Filenames starting with a number are prefixed with ``aiida_shell_``. """ files = { filename: 'content_a', @@ -138,6 +139,7 @@ def test_outputs_link_labels(parse_calc_job, create_retrieved_temporary, filenam assert calcfunction.is_finished_ok for content in files.values(): + assert link_label in results assert isinstance(results[link_label], SinglefileData) assert results[link_label].get_content() == content