Angular Generate and Display Build Git Info

March 6, 2024 · 2 min readLucian Ciobanu
Tags:AngularNodeDocker

Given the numerous release versions we were working on, my colleagues in the QA department asked for the release git branch name and the release git short hash to be displayed somewhere in the app to better manage their workload.

First step was to create at the same level with src folder an ECMAScript modules file "release-info.mjs"

import { execSync } from 'child_process';
import { writeFileSync } from 'fs';

const shortSHA = childProcess.execSync("git rev-parse --short HEAD").toString().trim();
const branch = childProcess.execSync('git rev-parse --abbrev-ref HEAD').toString().trim();
//the above were the only ones I needed but you can also use:
//const longSHA = childProcess.execSync("git rev-parse HEAD").toString().trim();
//const authorName = childProcess.execSync("git log -1 --pretty=format:'%an'").toString().trim();
//const commitTime = childProcess.execSync("git log -1 --pretty=format:'%cd'").toString().trim();
//const commitMsg = childProcess.execSync("git log -1 --pretty=%B").toString().trim();
//const totalCommitCount = childProcess.execSync("git rev-list --count HEAD").toString().trim();

const versionInfo = {
  shortSHA: shortSHA,
  branch: branch
}

const versionInfoJson = JSON.stringify(versionInfo, null, 2);

writeFileSync('./src/release-info.json', versionInfoJson);

We also need to create a release-info.json file where we tell the above file to write and some placeholder data:

{
  "branch": "local",
  "shortSHA": "pl4c3h0ld3r"
}

Very important to set "resolveJsonModule": true under "compilerOptions" object in tsconfig.json.

In package.json, I've added a new script:

"build-version": "node releases-info.mjs && ng build --configuration production"

This will run our mjs file and update the content of releases-info.json when we build our app.

In this scenario, I was using docker so I also had to include to docker/Dockerfile the following:

RUN npm run build-version

After we set the compiler options - resolve json module to true, we can import the json file to any component.ts we want to use it, as such:

import * as releaseInfo from 'src/release-info.json';
// ...
export class MyComponent {
  releaseInfo = releaseInfo as { branch: string, shortSHA: string };
  // ...
}

From here, it's straight forward to use the data in the template with {{ interpolation }} and style it as needed.

Hope this helped!

Cheers,
Lucian

Picture of author

Web Development & Software Delivery