From 91400e3d8cc7b5a076537403b6e34b62c22c920a Mon Sep 17 00:00:00 2001
From: Jason Nucciarone <40342202+NucciTheBoss@users.noreply.github.com>
Date: Wed, 23 Aug 2023 12:57:40 -0400
Subject: [PATCH] refactor: Auto-generate version file at packing (#16)

Signed-off-by: Jason C. Nucciarone <jason.nucciarone@canonical.com>
---
 .github/workflows/release.yaml  |  2 --
 charmcraft.yaml                 | 18 ++++++++++++++++++
 tests/integration/conftest.py   |  8 +++-----
 tests/integration/helpers.py    | 13 -------------
 tests/integration/test_charm.py |  3 +--
 5 files changed, 22 insertions(+), 22 deletions(-)

diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml
index 828124a..dc0a8a2 100644
--- a/.github/workflows/release.yaml
+++ b/.github/workflows/release.yaml
@@ -31,8 +31,6 @@ jobs:
     steps:
       - name: Checkout
         uses: actions/checkout@v3
-      - name: Create version file
-        run: git describe --tags --always --dirty > version
       - name: Select charmhub channel
         uses: canonical/charming-actions/channel@2.2.0
         id: channel
diff --git a/charmcraft.yaml b/charmcraft.yaml
index c279920..a42bde6 100644
--- a/charmcraft.yaml
+++ b/charmcraft.yaml
@@ -1,3 +1,6 @@
+# Copyright 2020 Omnivector Solutions, LLC
+# See LICENSE file for licensing details.
+
 type: charm
 bases:
   - build-on:
@@ -13,7 +16,22 @@ bases:
       - name: centos
         channel: "7"
         architectures: [amd64]
+
 parts:
   charm:
     build-packages: [git]
     charm-python-packages: [setuptools]
+
+  # Create a version file and pack it into the charm. This is dynamically generated
+  # as part of the build process for a charm to ensure that the git revision of the
+  # charm is always recorded in this version file.
+  version-file:
+    plugin: nil
+    build-packages:
+      - git
+    override-build: |
+      VERSION=$(git -C $CRAFT_PART_SRC/../../charm/src describe --dirty --always)
+      echo "Setting version to $VERSION"
+      echo $VERSION > $CRAFT_PART_INSTALL/version
+    stage:
+      - version
diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py
index c274453..bb8c872 100644
--- a/tests/integration/conftest.py
+++ b/tests/integration/conftest.py
@@ -18,12 +18,11 @@
 import pathlib
 
 import pytest
-from _pytest.config.argparsing import Parser
-from helpers import NHC, VERSION
+from helpers import NHC
 from pytest_operator.plugin import OpsTest
 
 
-def pytest_addoption(parser: Parser) -> None:
+def pytest_addoption(parser) -> None:
     parser.addoption(
         "--charm-base", action="store", default="ubuntu@22.04", help="Charm base to test."
     )
@@ -31,7 +30,7 @@ def pytest_addoption(parser: Parser) -> None:
 
 @pytest.fixture(scope="module")
 def charm_base(request) -> str:
-    """Get slurmdbd charm base to use."""
+    """Get slurmctld charm base to use."""
     return request.config.getoption("--charm-base")
 
 
@@ -45,4 +44,3 @@ async def slurmctld_charm(ops_test: OpsTest):
 def pytest_sessionfinish(session, exitstatus) -> None:
     """Clean up repository after test session has completed."""
     pathlib.Path(NHC).unlink(missing_ok=True)
-    pathlib.Path(VERSION).unlink(missing_ok=True)
diff --git a/tests/integration/helpers.py b/tests/integration/helpers.py
index 8d11eec..3d4a6da 100644
--- a/tests/integration/helpers.py
+++ b/tests/integration/helpers.py
@@ -16,8 +16,6 @@
 
 import logging
 import pathlib
-import shlex
-import subprocess
 from typing import Dict
 from urllib import request
 
@@ -25,17 +23,6 @@
 
 NHC = "lbnl-nhc-1.4.3.tar.gz"
 NHC_URL = f"https://github.com/mej/nhc/releases/download/1.4.3/{NHC}"
-VERSION = "version"
-VERSION_NUM = subprocess.run(
-    shlex.split("git describe --always"), stdout=subprocess.PIPE, text=True
-).stdout.strip("\n")
-
-
-def get_slurmctld_res() -> None:
-    """Get slurmctld resources needed for charm deployment."""
-    if not (version := pathlib.Path(VERSION)).exists():
-        logger.info(f"Setting resource {VERSION} to value {VERSION_NUM}")
-        version.write_text(VERSION_NUM)
 
 
 def get_slurmd_res() -> Dict[str, pathlib.Path]:
diff --git a/tests/integration/test_charm.py b/tests/integration/test_charm.py
index 7354c9d..4a41894 100644
--- a/tests/integration/test_charm.py
+++ b/tests/integration/test_charm.py
@@ -22,7 +22,7 @@
 
 import pytest
 import tenacity
-from helpers import get_slurmctld_res, get_slurmd_res
+from helpers import get_slurmd_res
 from pytest_operator.plugin import OpsTest
 
 logger = logging.getLogger(__name__)
@@ -42,7 +42,6 @@ async def test_build_and_deploy_against_edge(
 ) -> None:
     """Test that the slurmctld charm can stabilize against slurmd, slurmdbd, and MySQL."""
     logger.info(f"Deploying {SLURMCTLD} against {SLURMD}, {SLURMDBD}, and {DATABASE}")
-    get_slurmctld_res()
     slurmd_res = get_slurmd_res()
     await asyncio.gather(
         ops_test.model.deploy(