Apache Mesos
mkdir.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_MKDIR_HPP__
14 #define __STOUT_OS_WINDOWS_MKDIR_HPP__
15 
16 #include <string>
17 #include <vector>
18 
19 #include <stout/error.hpp>
20 #include <stout/nothing.hpp>
21 #include <stout/strings.hpp>
22 #include <stout/try.hpp>
23 #include <stout/windows.hpp>
24 
25 #include <stout/os/exists.hpp>
26 #include <stout/os/constants.hpp>
27 
29 
30 
31 namespace os {
32 
33 inline Try<Nothing> mkdir(const std::string& directory, bool recursive = true)
34 {
35  if (!recursive) {
36  // NOTE: We check for existence because parts of certain directories
37  // like `C:\` will return an error if passed to `CreateDirectory`,
38  // even though the drive may already exist.
39  if (os::exists(directory)) {
40  return Nothing();
41  }
42 
43  std::wstring longpath = ::internal::windows::longpath(directory);
44  if (::CreateDirectoryW(longpath.data(), nullptr) == 0) {
45  return WindowsError("Failed to create directory: " + directory);
46  }
47  } else {
48  // Remove the long path prefix, if it already exists, otherwise the
49  // tokenizer includes the long path prefix (`\\?\`) as the first part
50  // of the path.
51  std::vector<std::string> tokens = strings::tokenize(
52  strings::remove(directory, os::LONGPATH_PREFIX, strings::Mode::PREFIX),
54 
55  std::string path;
56 
57  foreach (const std::string& token, tokens) {
58  path += token + os::PATH_SEPARATOR;
59  Try<Nothing> result = mkdir(path, false);
60  if (result.isError()) {
61  return result;
62  }
63  }
64  }
65 
66  return Nothing();
67 }
68 
69 } // namespace os {
70 
71 #endif // __STOUT_OS_WINDOWS_MKDIR_HPP__
bool exists(const std::string &path)
Definition: exists.hpp:26
Definition: nothing.hpp:16
Definition: try.hpp:34
Definition: error.hpp:106
std::string remove(const std::string &from, const std::string &substring, Mode mode=ANY)
Definition: strings.hpp:40
std::vector< std::string > tokenize(const std::string &s, const std::string &delims, const Option< size_t > &maxTokens=None())
Definition: strings.hpp:138
Try< Nothing > mkdir(const std::string &directory, bool recursive=true)
Definition: mkdir.hpp:31
bool isError() const
Definition: try.hpp:71
std::wstring longpath(const std::string &path)
Definition: longpath.hpp:38
std::string stringify(int flags)
constexpr char PATH_SEPARATOR
Definition: constants.hpp:24