1 // Copyright 2019 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #ifndef SANDBOXED_API_SANDBOX2_UTIL_PATH_H_
16 #define SANDBOXED_API_SANDBOX2_UTIL_PATH_H_
17
18 #include <initializer_list>
19 #include <string>
20 #include <utility>
21
22 #include "absl/strings/string_view.h"
23
24 namespace sapi::file {
25
26 namespace internal {
27 // Not part of the public API.
28 std::string JoinPathImpl(std::initializer_list<absl::string_view> paths);
29 } // namespace internal
30
31 // Joins multiple paths together using the platform-specific path separator.
32 // Arguments must be convertible to absl::string_view.
33 template <typename... T>
JoinPath(const T &...args)34 inline std::string JoinPath(const T&... args) {
35 return internal::JoinPathImpl({args...});
36 }
37
38 // Return true if path is absolute.
39 bool IsAbsolutePath(absl::string_view path);
40
41 // Returns the parts of the path, split on the final "/". If there is no
42 // "/" in the path, the first part of the output is empty and the second
43 // is the input. If the only "/" in the path is the first character, it is
44 // the first part of the output.
45 std::pair<absl::string_view, absl::string_view> SplitPath(
46 absl::string_view path);
47
48 // Collapses duplicate "/"s, resolve ".." and "." path elements, removes
49 // trailing "/".
50 //
51 // This is purely a string manipulation and does not invoke any system calls in
52 // order to resolve relative paths to the actual working directory.
53 //
54 // For absolute paths, this is equivalent to the following:
55 // /path/to/./foo/../bar/../baz/ -> /path/to/bar/baz
56 //
57 // For relative paths, this is equivalent to the following:
58 // ./path/to/./foo/../bar/../baz/ -> path/to/bar/baz
59 // ../path/to/./foo/../bar/../baz/ -> ../path/to/bar/baz
60 std::string CleanPath(absl::string_view path);
61
62 } // namespace sapi::file
63
64 #endif // SANDBOXED_API_SANDBOX2_UTIL_PATH_H_
65