1 /*
2 * Copyright (C) 2015, 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 #include "import_resolver.h"
18 #include "aidl_language.h"
19
20 #include <algorithm>
21
22 #include <android-base/file.h>
23 #include <android-base/strings.h>
24 #include <unistd.h>
25
26 #ifdef _WIN32
27 #include <io.h>
28 #endif
29
30 #include "os.h"
31
32 using std::string;
33 using std::vector;
34
35 namespace android {
36 namespace aidl {
37
ImportResolver(const IoDelegate & io_delegate,const string & input_file_name,const set<string> & import_paths,const vector<string> & input_files)38 ImportResolver::ImportResolver(const IoDelegate& io_delegate, const string& input_file_name,
39 const set<string>& import_paths, const vector<string>& input_files)
40 : io_delegate_(io_delegate), input_file_name_(input_file_name), input_files_(input_files) {
41 for (string path : import_paths) {
42 if (path.empty()) {
43 path = ".";
44 }
45 if (path[path.size() - 1] != OS_PATH_SEPARATOR) {
46 path += OS_PATH_SEPARATOR;
47 }
48 import_paths_.push_back(std::move(path));
49 }
50 }
51
FindImportFile(const string & canonical_name) const52 string ImportResolver::FindImportFile(const string& canonical_name) const {
53 // Convert the canonical name to a relative file path.
54 string relative_path = canonical_name;
55 for (char& c : relative_path) {
56 if (c == '.') {
57 c = OS_PATH_SEPARATOR;
58 }
59 }
60 relative_path += ".aidl";
61
62 // Look for that relative path at each of our import roots.
63 vector<string> found_paths;
64 for (string path : import_paths_) {
65 path = path + relative_path;
66 if (io_delegate_.FileIsReadable(path)) {
67 found_paths.emplace_back(path);
68 }
69 }
70 // remove duplicates
71 std::sort(found_paths.begin(), found_paths.end());
72 auto last = std::unique(found_paths.begin(), found_paths.end());
73 found_paths.erase(last, found_paths.end());
74
75 int num_found = found_paths.size();
76 if (num_found == 0) {
77 return "";
78 } else if (num_found == 1) {
79 return found_paths.front();
80 } else {
81 AIDL_ERROR(input_file_name_) << "Duplicate files found for " << canonical_name
82 << " from:" << std::endl
83 << android::base::Join(found_paths, "\n");
84 return "";
85 }
86 }
87
88 } // namespace aidl
89 } // namespace android
90