Skip to content

Instantly share code, notes, and snippets.

@coreymcmahon
Last active April 4, 2021 07:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coreymcmahon/b16eaf7150b29c4944d3704f0303d590 to your computer and use it in GitHub Desktop.
Save coreymcmahon/b16eaf7150b29c4944d3704f0303d590 to your computer and use it in GitHub Desktop.
Generate a "version number" for a PHP/Laravel application
<?php
use Carbon\Carbon;
use Illuminate\Support\Arr;
if (!function_exists('version')) {
/**
* Attempts to determine the current version of the application, based on `version` set in config/app.php and either
* the file public/version.html (which should be created during the build process) or by exec'ing Git commands directly
* at runtime. This results in a string of the format `<app-version>-<hash> (<last-modified>)`
* E.g: `7.0.0-81f63aa78c (2020-10-09 17:17:48)`
*
* @return string
*/
function version(): string
{
$appVersion = config('app.version'); // Manually incremented in config/app.php when new feature released.
$fileWithCommitHash = base_path('/public/version.html'); // Created during build process.
if (file_exists($fileWithCommitHash)) {
// Attempt to read values from public/version.html
$values = explode("\n", file_get_contents($fileWithCommitHash));
$commit = Arr::get($values, '0', 'unknown');
if ($commitTime = Arr::get($values, '1')) {
$commitTime = new Carbon($commitTime);
} else {
$commitTime = 'unknown';
}
} else {
// File is not available so read from Git directly (NOTE: this will fail in staging/prod as the deployed assets
// are inside a folder that is not a valid Git repo).
if ($commit = trim(exec('git log --pretty="%h" -n1 HEAD'))) {
if ($commitTime = trim(exec('git log -n1 --pretty=%ci HEAD'))) {
$commitTime = new Carbon($commitTime);
$commitTime->setTimezone('UTC');
}
}
}
// If for some reason we can't determine the app version, fallback to `unknown` for both values.
$commit = !empty($commit) ? $commit : 'unknown';
$commitTime = !empty($commitTime) ? $commitTime->format('Y-m-d H:i:s') : 'unknown';
return "{$appVersion}-{$commit} ({$commitTime})";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment