1 /*
2 * Copyright (C) 2016 The Android Open Source Project
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 #pragma once
18
19 #include <errno.h>
20 #include <libgen.h>
21 #include <sys/stat.h>
22 #include <unistd.h>
23
24 #include <string>
25 #include <vector>
26
27 #include <llvm/ADT/StringRef.h>
28
29 std::string getWorkingDir();
30 std::vector<std::string> collectHeaders(const std::string& directory);
31
dirname(const std::string & path)32 static inline std::string dirname(const std::string& path) {
33 std::unique_ptr<char, decltype(&free)> path_copy(strdup(path.c_str()), free);
34 return dirname(path_copy.get());
35 }
36
is_directory(const std::string & path)37 static inline bool is_directory(const std::string& path) {
38 struct stat st;
39 if (stat(path.c_str(), &st) == 0 && S_ISDIR(st.st_mode)) {
40 return true;
41 }
42 return false;
43 }
44
mkdirs(const std::string & path)45 static inline bool mkdirs(const std::string& path) {
46 if (is_directory(path)) {
47 return true;
48 }
49
50 std::string parent = dirname(path);
51 if (parent == path) {
52 return false;
53 }
54
55 if (!mkdirs(parent)) {
56 return false;
57 }
58
59 if (mkdir(path.c_str(), 0700) != 0) {
60 if (errno != EEXIST) {
61 return false;
62 }
63 return is_directory(path);
64 }
65
66 return true;
67 }
68
to_string(const char * c)69 static inline std::string to_string(const char* c) {
70 return c;
71 }
72
to_string(const std::string & str)73 static inline const std::string& to_string(const std::string& str) {
74 return str;
75 }
76
77 template <typename Collection>
78 static inline std::string Join(Collection c, const std::string& delimiter = ", ") {
79 std::string result;
80 for (const auto& item : c) {
81 using namespace std;
82 result.append(to_string(item));
83 result.append(delimiter);
84 }
85 if (!result.empty()) {
86 result.resize(result.length() - delimiter.length());
87 }
88 return result;
89 }
90
91 llvm::StringRef StripPrefix(llvm::StringRef string, llvm::StringRef prefix);
92