Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added build metadata string formatting. #7

Merged
merged 1 commit into from
Oct 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 42 additions & 1 deletion concoursetools/metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,47 @@ def build_url(self) -> str:

return f"{self.ATC_EXTERNAL_URL}/{quote(build_path)}{query_string}"

def format_string(self, string: str) -> str:
"""
Format a string with metadata using standard bash ``$`` notation.

Only a handful of "safe" values will be interpolated, not arbitrary attributes on the instance.
These are the :concourse:`original environment variables <implementing-resource-types.resource-metadata>`,
including :attr:`BUILD_CREATED_BY` if it exists. Any missing environment variable (such as in the case of a
one-off build) will be empty. A ``$BUILD_URL`` variable is also added for ease.

.. note::
The interpolation is done by iterating over all possible variables and calling :meth:`str.replace`.
This is actually the `fastest method <https://stackoverflow.com/q/3411006>`_ for small strings.

:param string: The string to be interpolated.
:returns: The interpolated string.

:Example:
>>> from concoursetools.mocking import TestBuildMetadata
>>> metadata = TestBuildMetadata()
>>> metadata.format_string("The build id is $BUILD_ID.")
'The build id is 12345678.'
"""
possible_vars = {
"$BUILD_ID": self.BUILD_ID,
"$BUILD_TEAM_NAME": self.BUILD_TEAM_NAME,
"$BUILD_NAME": self.BUILD_NAME,
"$BUILD_JOB_NAME": self.BUILD_JOB_NAME,
"$BUILD_PIPELINE_NAME": self.BUILD_PIPELINE_NAME,
"$BUILD_PIPELINE_INSTANCE_VARS": self.BUILD_PIPELINE_INSTANCE_VARS,
"$ATC_EXTERNAL_URL": self.ATC_EXTERNAL_URL,
"$BUILD_URL": self.build_url(),
}
try:
possible_vars["$BUILD_CREATED_BY"] = self.BUILD_CREATED_BY
except PermissionError:
pass

for variable, value in possible_vars.items():
string = string.replace(variable, value or "")
return string

@classmethod
def from_env(cls) -> "BuildMetadata":
"""Return an instance populated from the environment."""
Expand Down Expand Up @@ -187,7 +228,7 @@ def _flatten_dict(d: Dict[str, Any]) -> Dict[str, Any]:
... }
... }
>>> _flatten_dict(d)
{"key_1": "value_1", "key_2.1": "value_2_1", "key_2.2", "value_2_2"}
{'key_1': 'value_1', 'key_2.1': 'value_2_1', 'key_2.2': 'value_2_2'}
"""
flattened_dict: Dict[str, Any] = {}
for key, value in d.items():
Expand Down
1 change: 1 addition & 0 deletions cspell.config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ words:
- rstrip
- rwxr
- seealso
- srcset
- stringifying
- termcolor
- toctree
Expand Down
28 changes: 28 additions & 0 deletions tests/test_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

from concoursetools import BuildMetadata
from concoursetools.metadata import _flatten_dict
from concoursetools.mocking import TestBuildMetadata
from concoursetools.testing import create_env_vars, mock_environ


Expand Down Expand Up @@ -150,3 +151,30 @@ def test_flattening_double_nested_dict(self) -> None:
"version.parents.to": "2.0.0",
}
self.assertDictEqual(_flatten_dict(nested_dict), flattened_dict)


class MetadataFormattingTests(TestCase):
"""
Tests for the BuildMetadata.format_string method.
"""
def setUp(self) -> None:
"""Code to run before each test."""
self.metadata = TestBuildMetadata()

def test_no_interpolation(self) -> None:
new_string = self.metadata.format_string("This is a normal string.")
self.assertEqual(new_string, "This is a normal string.")

def test_simple_interpolation(self) -> None:
new_string = self.metadata.format_string("The build id is $BUILD_ID and the job name is $BUILD_JOB_NAME.")
self.assertEqual(new_string, "The build id is 12345678 and the job name is my-job.")

def test_interpolation_with_one_off(self) -> None:
metadata = TestBuildMetadata(one_off_build=True)
new_string = metadata.format_string("The build id is $BUILD_ID and the job name is $BUILD_JOB_NAME.")
self.assertEqual(new_string, "The build id is 12345678 and the job name is .")

def test_interpolation_incorrect_value(self) -> None:
metadata = TestBuildMetadata(one_off_build=True)
new_string = metadata.format_string("The build id is $OTHER.")
self.assertEqual(new_string, "The build id is $OTHER.")