Merge pull request #9759 from obsidiansystems/abs-path-string-view

`absPath`: just take a `std::string_view`
This commit is contained in:
John Ericson 2024-01-15 10:22:20 -05:00 committed by GitHub
commit 8a2da82220
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 15 additions and 7 deletions

View file

@ -6,11 +6,11 @@ namespace nix {
CanonPath CanonPath::root = CanonPath("/");
CanonPath::CanonPath(std::string_view raw)
: path(absPath((Path) raw, "/"))
: path(absPath(raw, "/"))
{ }
CanonPath::CanonPath(std::string_view raw, const CanonPath & root)
: path(absPath((Path) raw, root.abs()))
: path(absPath(raw, root.abs()))
{ }
CanonPath::CanonPath(const std::vector<std::string> & elems)
@ -22,7 +22,7 @@ CanonPath::CanonPath(const std::vector<std::string> & elems)
CanonPath CanonPath::fromCwd(std::string_view path)
{
return CanonPath(unchecked_t(), absPath((Path) path));
return CanonPath(unchecked_t(), absPath(path));
}
std::optional<CanonPath> CanonPath::parent() const

View file

@ -21,9 +21,16 @@ namespace fs = std::filesystem;
namespace nix {
Path absPath(Path path, std::optional<PathView> dir, bool resolveSymlinks)
Path absPath(PathView path, std::optional<PathView> dir, bool resolveSymlinks)
{
std::string scratch;
if (path[0] != '/') {
// In this case we need to call `canonPath` on a newly-created
// string. We set `scratch` to that string first, and then set
// `path` to `scratch`. This ensures the newly-created string
// lives long enough for the call to `canonPath`, and allows us
// to just accept a `std::string_view`.
if (!dir) {
#ifdef __GNU__
/* GNU (aka. GNU/Hurd) doesn't have any limitation on path
@ -35,12 +42,13 @@ Path absPath(Path path, std::optional<PathView> dir, bool resolveSymlinks)
if (!getcwd(buf, sizeof(buf)))
#endif
throw SysError("cannot get cwd");
path = concatStrings(buf, "/", path);
scratch = concatStrings(buf, "/", path);
#ifdef __GNU__
free(buf);
#endif
} else
path = concatStrings(*dir, "/", path);
scratch = concatStrings(*dir, "/", path);
path = scratch;
}
return canonPath(path, resolveSymlinks);
}

View file

@ -41,7 +41,7 @@ struct Source;
* specified directory, or the current directory otherwise. The path
* is also canonicalised.
*/
Path absPath(Path path,
Path absPath(PathView path,
std::optional<PathView> dir = {},
bool resolveSymlinks = false);