Created
March 18, 2024 09:58
-
-
Save attitude/46ea4a87970a080706a2bba080c41810 to your computer and use it in GitHub Desktop.
Retrieves the current Git hash for a given .git path.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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