2017
[folly.git] / folly / experimental / io / FsUtil.cpp
1 /*
2  * Copyright 2017 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <folly/experimental/io/FsUtil.h>
18
19 #include <folly/Exception.h>
20
21 namespace bsys = ::boost::system;
22
23 namespace folly {
24 namespace fs {
25
26 namespace {
27 bool skipPrefix(const path& pth, const path& prefix, path::const_iterator& it) {
28   it = pth.begin();
29   for (auto& p : prefix) {
30     if (it == pth.end()) {
31       return false;
32     }
33     if (p == ".") {
34       // Should only occur at the end, if prefix ends with a slash
35       continue;
36     }
37     if (*it++ != p) {
38       return false;
39     }
40   }
41   return true;
42 }
43 }  // namespace
44
45 bool starts_with(const path& pth, const path& prefix) {
46   path::const_iterator it;
47   return skipPrefix(pth, prefix, it);
48 }
49
50 path remove_prefix(const path& pth, const path& prefix) {
51   path::const_iterator it;
52   if (!skipPrefix(pth, prefix, it)) {
53     throw filesystem_error(
54         "Path does not start with prefix",
55         pth, prefix,
56         bsys::errc::make_error_code(bsys::errc::invalid_argument));
57   }
58
59   path p;
60   for (; it != pth.end(); ++it) {
61     p /= *it;
62   }
63
64   return p;
65 }
66
67 path canonical_parent(const path& pth, const path& base) {
68   return canonical(pth.parent_path(), base) / pth.filename();
69 }
70
71 path executable_path() {
72   return read_symlink("/proc/self/exe");
73 }
74
75 }  // namespace fs
76 }  // namespace folly