Skip to content

Instantly share code, notes, and snippets.

@aklump
Last active November 8, 2025 17:21
Show Gist options
  • Save aklump/13e240478d1c3ecc33c320b5477b3acf to your computer and use it in GitHub Desktop.
Save aklump/13e240478d1c3ecc33c320b5477b3acf to your computer and use it in GitHub Desktop.
Search for a path moving up the file tree, e.g. "locate .git from child path"
<?php
/**
* The Upfind class provides functionality to locate a file or directory
* by walking up the directory tree from a starting directory.
*/
class Upfind {
public function __invoke(string $basename): string {
$result = $this->upfind($basename);
if (!$result) {
return '';
}
return $result . DIRECTORY_SEPARATOR . $basename;
}
private function upfind($basename, $start_dir = NULL) {
$path = $start_dir;
if (!isset($path)) {
$path = getcwd();
}
while ($path
&& $path !== DIRECTORY_SEPARATOR
&& ($expected = $path . DIRECTORY_SEPARATOR . $basename)
&& !file_exists($expected)) {
$path = dirname($path);
unset($expected);
}
if (empty($expected)) {
return '';
}
return $path;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment