Apache Mesos
ls.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_LS_HPP__
14 #define __STOUT_OS_WINDOWS_LS_HPP__
15 
16 #include <list>
17 #include <string>
18 
19 #include <stout/error.hpp>
20 #include <stout/try.hpp>
21 
23 
24 
25 namespace os {
26 
27 inline Try<std::list<std::string>> ls(const std::string& directory)
28 {
29  // Ensure the path ends with a backslash.
30  std::string path = directory;
31  if (!strings::endsWith(path, "\\")) {
32  path += "\\";
33  }
34 
35  // Get first file matching pattern `X:\path\to\wherever\*`.
36  WIN32_FIND_DATAW found;
37  const std::wstring search_pattern =
38  ::internal::windows::longpath(path) + L"*";
39 
40  const SharedHandle search_handle(
41  ::FindFirstFileW(search_pattern.data(), &found),
42  ::FindClose);
43 
44  if (search_handle.get() == INVALID_HANDLE_VALUE) {
45  return WindowsError("Failed to search '" + directory + "'");
46  }
47 
48  std::list<std::string> result;
49 
50  do {
51  // NOTE: do-while is appropriate here because folder is guaranteed to have
52  // at least a file called `.` (and probably also one called `..`).
53  const std::wstring current_file(found.cFileName);
54 
55  const bool is_current_directory = current_file.compare(L".") == 0;
56  const bool is_parent_directory = current_file.compare(L"..") == 0;
57 
58  // Ignore the `.` and `..` files in the directory.
59  if (is_current_directory || is_parent_directory) {
60  continue;
61  }
62 
63  result.push_back(stringify(current_file));
64  } while (::FindNextFileW(search_handle.get(), &found));
65 
66  return result;
67 }
68 
69 } // namespace os {
70 
71 #endif // __STOUT_OS_WINDOWS_LS_HPP__
bool endsWith(const std::string &s, const std::string &suffix)
Definition: strings.hpp:402
Definition: path.hpp:29
Definition: windows.hpp:72
Definition: check.hpp:33
Definition: error.hpp:108
Definition: posix_signalhandler.hpp:23
std::wstring longpath(const std::string &path)
Definition: longpath.hpp:38
std::string stringify(int flags)
Try< std::list< std::string > > ls(const std::string &directory)
Definition: ls.hpp:29