Apache Mesos
copyfile.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_COPYFILE_HPP__
14 #define __STOUT_OS_WINDOWS_COPYFILE_HPP__
15 
16 #include <string>
17 
18 #include <stout/error.hpp>
19 #include <stout/nothing.hpp>
20 #include <stout/path.hpp>
21 #include <stout/try.hpp>
22 #include <stout/windows.hpp>
23 
25 
26 
27 namespace os {
28 
29 // Uses the `CopyFile` Windows API to perform a file copy.
30 // Unlike the POSIX implementation, we do not need to check if the
31 // source or destination are directories, because `CopyFile` only
32 // works on files.
33 //
34 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363851(v=vs.85).aspx
35 //
36 // NOLINT(whitespace/line_length)
37 
38 inline Try<Nothing> copyfile(
39  const std::string& source, const std::string& destination)
40 {
41  if (!path::is_absolute(source)) {
42  return Error("`source` was a relative path");
43  }
44 
45  if (!path::is_absolute(destination)) {
46  return Error("`destination` was a relative path");
47  }
48 
49  if (!::CopyFileW(
50  ::internal::windows::longpath(source).data(),
51  ::internal::windows::longpath(destination).data(),
52  // NOTE: This allows the destination to be overwritten if the
53  // destination already exists, as is the case in the POSIX version of
54  // `copyfile`.
55  false)) {
56  return WindowsError();
57  }
58 
59  return Nothing();
60 }
61 
62 } // namespace os {
63 
64 #endif // __STOUT_OS_WINDOWS_COPYFILE_HPP__
bool is_absolute(const std::string &path)
Returns whether the given path is an absolute path.
Definition: path.hpp:158
Definition: nothing.hpp:16
Definition: errorbase.hpp:36
Try< Nothing > copyfile(const std::string &source, const std::string &destination)
Definition: copyfile.hpp:40
Definition: check.hpp:33
Definition: error.hpp:108
Definition: posix_signalhandler.hpp:23
std::wstring longpath(const std::string &path)
Definition: longpath.hpp:38