aboutsummaryrefslogtreecommitdiffstats
path: root/nihil.posix/find_in_path.ccm
blob: 7bfa3b9cda6bdaa5b053290fdb6d2066389b71ee (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// This source code is released into the public domain.
module;

#include <filesystem>
#include <optional>
#include <ranges>

#include <paths.h>
#include <unistd.h>

export module nihil.posix:find_in_path;

import nihil.error;
import :fd;
import :getenv;

namespace nihil {

/*
 * Find an executable in $PATH and return the full path.  If $PATH is not set, uses _PATH_DEFPATH.
 * If the file can't be found or is not executable, returns std::nullopt.
 */
export [[nodiscard]] auto
find_in_path(std::filesystem::path const &file) -> std::optional<std::filesystem::path>
{
	using namespace std::literals;

	auto try_return = [](std::filesystem::path file) -> std::optional<std::filesystem::path> {
		auto ret = ::access(file.string().c_str(), X_OK);
		if (ret == 0)
			return {std::move(file)};
		return {};
	};

	// Absolute pathname skips the search.
	if (file.is_absolute())
		return try_return(file);

	auto const path = getenv("PATH").value_or(_PATH_DEFPATH); // NOLINT

	for (auto &&dir : path | std::views::split(':')) {
		// An empty $PATH element means cwd.
		auto sdir = dir.empty() ? std::filesystem::path(".")
		                        : std::filesystem::path(std::string_view(dir));

		if (auto ret = try_return(sdir / file); ret)
			return {ret};
	}

	return {};
}

} // namespace nihil