Apache Mesos
realpath.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_WINDOWS_REALPATH_HPP__
14 #define __STOUT_OS_WINDOWS_REALPATH_HPP__
15 
16 
17 #include <stout/error.hpp>
18 #include <stout/result.hpp>
19 #include <stout/stringify.hpp>
20 #include <stout/strings.hpp>
21 #include <stout/windows.hpp>
22 
25 
26 
27 namespace os {
28 
29 // This should behave like the POSIX `realpath` API: specifically it should
30 // resolve symlinks in the path, and succeed only if the target file exists.
31 // This requires that the user has permissions to resolve each component of the
32 // path.
33 inline Result<std::string> realpath(const std::string& path)
34 {
36  if (handle.isError()) {
37  return Error(handle.error());
38  }
39 
40  // First query for the buffer size required.
41  const DWORD length = ::GetFinalPathNameByHandleW(
42  handle.get().get_handle(), nullptr, 0, FILE_NAME_NORMALIZED);
43  if (length == 0) {
44  return WindowsError("Failed to retrieve realpath buffer size");
45  }
46 
47  std::vector<wchar_t> buffer;
48  buffer.reserve(static_cast<size_t>(length));
49 
50  DWORD result = ::GetFinalPathNameByHandleW(
51  handle.get().get_handle(), buffer.data(), length, FILE_NAME_NORMALIZED);
52 
53  if (result == 0) {
54  return WindowsError("Failed to determine realpath");
55  }
56 
57  return strings::remove(
58  stringify(std::wstring(buffer.data())),
59  os::LONGPATH_PREFIX,
61 }
62 
63 } // namespace os {
64 
65 #endif // __STOUT_OS_WINDOWS_REALPATH_HPP__
Definition: path.hpp:29
Definition: errorbase.hpp:36
T & get()&
Definition: try.hpp:80
HANDLE get_handle() const
Definition: windows.hpp:90
Definition: check.hpp:33
Result< std::string > realpath(const std::string &path)
Definition: realpath.hpp:24
Definition: error.hpp:108
Definition: posix_signalhandler.hpp:23
Definition: check.hpp:30
std::string remove(const std::string &from, const std::string &substring, Mode mode=ANY)
Definition: strings.hpp:41
static Try error(const E &e)
Definition: try.hpp:43
Try< SharedHandle > get_handle_follow(const std::string &absolute_path)
Definition: reparsepoint.hpp:155
bool isError() const
Definition: try.hpp:78
std::string stringify(int flags)