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