Skip to content

Commit

Permalink
ShellParser: Prefix output filenames starting with a number
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
sphuber authored May 13, 2024
1 parent 31ebfbc commit 352c309
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 4 deletions.
10 changes: 7 additions & 3 deletions src/aiida_shell/parsers/shell.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion tests/parsers/test_shell.py
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand All @@ -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

Expand Down

0 comments on commit 352c309

Please sign in to comment.