|
| 1 | +# SPDX-FileCopyrightText: 2025-present Datadog, Inc. <dev@datadoghq.com> |
| 2 | +# |
| 3 | +# SPDX-License-Identifier: MIT |
| 4 | + |
| 5 | +from __future__ import annotations |
| 6 | + |
| 7 | +from dataclasses import dataclass |
| 8 | +from datetime import datetime |
| 9 | +from typing import TYPE_CHECKING |
| 10 | + |
| 11 | +from dda.build.metadata.enums import OS, Arch, ArtifactFormat |
| 12 | + |
| 13 | +if TYPE_CHECKING: |
| 14 | + from click import Context |
| 15 | + |
| 16 | + from dda.cli.application import Application |
| 17 | + from dda.utils.git.changeset import ChangeSet |
| 18 | + from dda.utils.git.commit import Commit |
| 19 | + |
| 20 | + |
| 21 | +@dataclass |
| 22 | +class BuildMetadata: |
| 23 | + """ |
| 24 | + Metadata about a build that can be used to identify it. |
| 25 | + """ |
| 26 | + |
| 27 | + agent_component: str |
| 28 | + artifact_format: ArtifactFormat |
| 29 | + commit: Commit |
| 30 | + arch: Arch |
| 31 | + os: OS |
| 32 | + build_time: datetime |
| 33 | + |
| 34 | + worktree_diff: ChangeSet |
| 35 | + |
| 36 | + @property |
| 37 | + def platform(self) -> str: |
| 38 | + """ |
| 39 | + Return the platform string in the format `os-arch`. |
| 40 | + """ |
| 41 | + return f"{self.os}-{self.arch}" |
| 42 | + |
| 43 | + @classmethod |
| 44 | + def this(cls, ctx: Context, app: Application) -> BuildMetadata: |
| 45 | + """ |
| 46 | + Create a BuildMetadata instance for the current build. |
| 47 | + """ |
| 48 | + import platform |
| 49 | + |
| 50 | + # Current time |
| 51 | + build_time = datetime.now() # noqa: DTZ005 |
| 52 | + |
| 53 | + # Parse calling command - the two last parts are the component and format respectively |
| 54 | + # e.g. `dda build core-agent bin` -> `core-agent` and `bin` |
| 55 | + command_parts = ctx.command_path.split(" ") |
| 56 | + if command_parts[-3] != "build": |
| 57 | + msg = f"Unexpected command path, BuildMetadata.this can only be called from within: {ctx.command_path}" |
| 58 | + raise ValueError(msg) |
| 59 | + |
| 60 | + agent_component = command_parts[-2] |
| 61 | + artifact_format = ArtifactFormat(command_parts[-1]) |
| 62 | + |
| 63 | + # Arch and OS |
| 64 | + arch = Arch(platform.machine()) |
| 65 | + os = OS(platform.system().lower()) |
| 66 | + |
| 67 | + # Get worktree information - base commit and diff hash |
| 68 | + worktree_diff = app.tools.git.get_working_tree_changes() |
| 69 | + commit = app.tools.git.get_head_commit() |
| 70 | + |
| 71 | + return cls( |
| 72 | + agent_component=agent_component, |
| 73 | + artifact_format=artifact_format, |
| 74 | + commit=commit, |
| 75 | + arch=arch, |
| 76 | + os=os, |
| 77 | + build_time=build_time, |
| 78 | + worktree_diff=worktree_diff, |
| 79 | + ) |
0 commit comments