FsUtil.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. #include <folly/experimental/io/FsUtil.h>
  17. #include <folly/Exception.h>
  18. namespace bsys = ::boost::system;
  19. namespace folly {
  20. namespace fs {
  21. namespace {
  22. bool skipPrefix(const path& pth, const path& prefix, path::const_iterator& it) {
  23. it = pth.begin();
  24. for (auto& p : prefix) {
  25. if (it == pth.end()) {
  26. return false;
  27. }
  28. if (p == ".") {
  29. // Should only occur at the end, if prefix ends with a slash
  30. continue;
  31. }
  32. if (*it++ != p) {
  33. return false;
  34. }
  35. }
  36. return true;
  37. }
  38. } // namespace
  39. bool starts_with(const path& pth, const path& prefix) {
  40. path::const_iterator it;
  41. return skipPrefix(pth, prefix, it);
  42. }
  43. path remove_prefix(const path& pth, const path& prefix) {
  44. path::const_iterator it;
  45. if (!skipPrefix(pth, prefix, it)) {
  46. throw filesystem_error(
  47. "Path does not start with prefix",
  48. pth,
  49. prefix,
  50. bsys::errc::make_error_code(bsys::errc::invalid_argument));
  51. }
  52. path p;
  53. for (; it != pth.end(); ++it) {
  54. p /= *it;
  55. }
  56. return p;
  57. }
  58. path canonical_parent(const path& pth, const path& base) {
  59. return canonical(pth.parent_path(), base) / pth.filename();
  60. }
  61. path executable_path() {
  62. return read_symlink("/proc/self/exe");
  63. }
  64. } // namespace fs
  65. } // namespace folly