Apache Mesos
which.hpp
Go to the documentation of this file.
1 // Licensed under the Apache License, Version 2.0 (the "License");
2 // you may not use this file except in compliance with the License.
3 // You may obtain a copy of the License at
4 //
5 // http://www.apache.org/licenses/LICENSE-2.0
6 //
7 // Unless required by applicable law or agreed to in writing, software
8 // distributed under the License is distributed on an "AS IS" BASIS,
9 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10 // See the License for the specific language governing permissions and
11 // limitations under the License.
12 
13 #ifndef __STOUT_OS_POSIX_WHICH_HPP__
14 #define __STOUT_OS_POSIX_WHICH_HPP__
15 
16 #include <string>
17 #include <vector>
18 
19 #include <stout/none.hpp>
20 #include <stout/option.hpp>
21 #include <stout/os.hpp>
22 #include <stout/path.hpp>
23 #include <stout/strings.hpp>
24 
25 #include <stout/os/exists.hpp>
26 #include <stout/os/permissions.hpp>
27 
28 
29 namespace os {
30 
32  const std::string& command,
33  const Option<std::string>& _path = None())
34 {
35  Option<std::string> path = _path;
36 
37  if (path.isNone()) {
38  path = getenv("PATH");
39 
40  if (path.isNone()) {
41  return None();
42  }
43  }
44 
45  std::vector<std::string> tokens = strings::tokenize(path.get(), ":");
46  foreach (const std::string& token, tokens) {
47  const std::string commandPath = path::join(token, command);
48  if (!os::exists(commandPath)) {
49  continue;
50  }
51 
53  if (permissions.isError()) {
54  continue;
55  }
56 
57  if (!permissions->owner.x &&
58  !permissions->group.x &&
59  !permissions->others.x) {
60  continue;
61  }
62 
63  return commandPath;
64  }
65 
66  return None();
67 }
68 
69 } // namespace os {
70 
71 
72 #endif // __STOUT_OS_POSIX_WHICH_HPP__
Definition: path.hpp:29
bool exists(const std::string &path)
Definition: exists.hpp:26
Definition: check.hpp:33
struct os::Permissions::@21 group
Definition: posix_signalhandler.hpp:23
Try< Permissions > permissions(const std::string &path)
Definition: permissions.hpp:61
std::string join(const std::string &path1, const std::string &path2, const char _separator=os::PATH_SEPARATOR)
Definition: path.hpp:116
Option< std::string > which(const std::string &command, const Option< std::string > &_path=None())
Definition: which.hpp:31
std::vector< std::string > tokenize(const std::string &s, const std::string &delims, const Option< size_t > &maxTokens=None())
Definition: strings.hpp:139
const T & get() const &
Definition: option.hpp:119
Option< std::string > getenv(const std::string &key)
Definition: getenv.hpp:29
struct os::Permissions::@21 others
Definition: none.hpp:27
bool isError() const
Definition: try.hpp:78
struct os::Permissions::@21 owner
bool isNone() const
Definition: option.hpp:117
bool x
Definition: permissions.hpp:51