Skip to content

Instantly share code, notes, and snippets.

@attitude
Created March 18, 2024 09:58
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 attitude/46ea4a87970a080706a2bba080c41810 to your computer and use it in GitHub Desktop.
Save attitude/46ea4a87970a080706a2bba080c41810 to your computer and use it in GitHub Desktop.
Retrieves the current Git hash for a given .git path.
<?php
/**
* Retrieves the current Git hash for a given .git path.
*
* @param string $dotGitPath The path to the .git directory or file.
* @return string The current Git hash.
* @throws \ErrorException If there is an error reading the .git path or its contents.
*/
function currentGitHash(string $path): string {
if ($dotGitPath = realpath($path)) {
if ($headPath = realpath("{$dotGitPath}/HEAD")) {
if ($headContents = file_get_contents($headPath)) {
if (false === strstr($headContents, 'ref:')) {
return $headContents;
} else {
$branchPath = explode('ref:', $headContents);
$branchPath = trim(array_pop($branchPath));
$branchPath = "{$dotGitPath}/{$branchPath}";
if ($branchContents = file_get_contents($branchPath)) {
return trim($branchContents);
} else {
$error = error_get_last();
throw new \ErrorException('Cannot read branch contents. '.($error['message'] ?? 'Unknown error occurred'), 0, $error['type'] ?? E_ERROR);
}
}
} else {
$error = error_get_last();
throw new \ErrorException('Cannot read HEAD contents. '.($error['message'] ?? 'Unknown error occurred'), 0, $error['type'] ?? E_ERROR);
}
} else {
$error = error_get_last();
throw new \ErrorException('Invalid HEAD path. '.($error['message'] ?? 'Unknown error occurred'), 0, $error['type'] ?? E_ERROR);
}
} elseif (is_file($path)) {
if ($submoduleContents = file_get_contents($path)) {
$submoduleContents = explode('gitdir:', $submoduleContents);
$submoduleContents = trim(array_pop($submoduleContents));
$submoduleContents = dirname($dotGitPath)."/$submoduleContents";
return currentGitHash($submoduleContents);
} else {
$error = error_get_last();
throw new \ErrorException('Cannot read submodule contents. '.($error['message'] ?? 'Unknown error occurred'), 0, $error['type'] ?? E_ERROR);
}
} else {
throw new \ErrorException('Invalid path to Git directory specified: '.json_encode($path), 0, E_ERROR);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment