1/*
2 * Copyright 2012-present 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
21namespace bsys = ::boost::system;
22
23namespace folly {
24namespace fs {
25
26namespace {
27bool 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
45bool starts_with(const path& pth, const path& prefix) {
46 path::const_iterator it;
47 return skipPrefix(pth, prefix, it);
48}
49
50path 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,
56 prefix,
57 bsys::errc::make_error_code(bsys::errc::invalid_argument));
58 }
59
60 path p;
61 for (; it != pth.end(); ++it) {
62 p /= *it;
63 }
64
65 return p;
66}
67
68path canonical_parent(const path& pth, const path& base) {
69 return canonical(pth.parent_path(), base) / pth.filename();
70}
71
72path executable_path() {
73 return read_symlink("/proc/self/exe");
74}
75
76} // namespace fs
77} // namespace folly
78