• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright (c) 2024 Huawei Device Co., Ltd.
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  *     http://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 
16 #include "importPathManager.h"
17 #include <libpandabase/os/filesystem.h>
18 
19 #ifdef USE_UNIX_SYSCALL
20 #include <dirent.h>
21 #include <sys/types.h>
22 #include <unistd.h>
23 #else
24 #if __has_include(<filesystem>)
25 #include <filesystem>
26 namespace fs = std::filesystem;
27 #elif __has_include(<experimental/filesystem>)
28 #include <experimental/filesystem>
29 namespace fs = std::experimental::filesystem;
30 #endif
31 #endif
32 namespace ark::es2panda::util {
33 
34 constexpr size_t SUPPORTED_INDEX_FILES_SIZE = 2;
35 constexpr size_t SUPPORTED_EXTENSIONS_SIZE = 2;
36 
IsCompitableExtension(const std::string & extension)37 static bool IsCompitableExtension(const std::string &extension)
38 {
39     return extension == ".sts" || extension == ".ts";
40 }
41 
ResolvePath(const StringView & currentModulePath,const StringView & importPath) const42 StringView ImportPathManager::ResolvePath(const StringView &currentModulePath, const StringView &importPath) const
43 {
44     if (importPath.Empty()) {
45         throw Error(ErrorType::GENERIC, "", "Import path cannot be empty");
46     }
47 
48     if (IsRelativePath(importPath)) {
49         const size_t pos = currentModulePath.Mutf8().find_last_of(pathDelimiter_);
50         ASSERT(pos != std::string::npos);
51 
52         auto currentDirectory = currentModulePath.Mutf8().substr(0, pos);
53         auto resolvedPath = UString(currentDirectory, allocator_);
54         resolvedPath.Append(pathDelimiter_);
55         resolvedPath.Append(importPath.Mutf8());
56 
57         return AppendExtensionOrIndexFileIfOmitted(resolvedPath.View());
58     }
59 
60     std::string baseUrl;
61     if (importPath.Mutf8()[0] == pathDelimiter_.at(0)) {
62         baseUrl = arktsConfig_->BaseUrl();
63         baseUrl.append(importPath.Mutf8(), 0, importPath.Mutf8().length());
64         return AppendExtensionOrIndexFileIfOmitted(UString(baseUrl, allocator_).View());
65     }
66 
67     auto &dynamicPaths = arktsConfig_->DynamicPaths();
68     if (auto it = dynamicPaths.find(importPath.Mutf8()); it != dynamicPaths.cend() && !it->second.HasDecl()) {
69         return AppendExtensionOrIndexFileIfOmitted(importPath);
70     }
71 
72     const size_t pos = importPath.Mutf8().find(pathDelimiter_);
73     bool containsDelim = (pos != std::string::npos);
74     auto rootPart = containsDelim ? importPath.Substr(0, pos) : importPath;
75     if (!stdLib_.empty() &&
76         (rootPart.Is("std") || rootPart.Is("escompat"))) {  // Get std or escompat path from CLI if provided
77         baseUrl = stdLib_ + pathDelimiter_.at(0) + rootPart.Mutf8();
78     } else {
79         ASSERT(arktsConfig_ != nullptr);
80         auto resolvedPath = arktsConfig_->ResolvePath(importPath.Mutf8());
81         if (!resolvedPath) {
82             throw Error(ErrorType::GENERIC, "",
83                         "Can't find prefix for '" + importPath.Mutf8() + "' in " + arktsConfig_->ConfigPath());
84         }
85 
86         return AppendExtensionOrIndexFileIfOmitted(UString(resolvedPath.value(), allocator_).View());
87     }
88 
89     if (containsDelim) {
90         baseUrl.append(1, pathDelimiter_.at(0));
91         baseUrl.append(importPath.Mutf8(), rootPart.Mutf8().length() + 1, importPath.Mutf8().length());
92     }
93 
94     return UString(baseUrl, allocator_).View();
95 }
96 
97 #ifdef USE_UNIX_SYSCALL
UnixWalkThroughDirectoryAndAddToParseList(const StringView & directoryPath,bool isDefaultImport)98 void ImportPathManager::UnixWalkThroughDirectoryAndAddToParseList(const StringView &directoryPath, bool isDefaultImport)
99 {
100     DIR *dir = opendir(directoryPath.Mutf8().c_str());
101     if (dir == nullptr) {
102         throw Error(ErrorType::GENERIC, "", "Cannot open folder: " + directoryPath.Mutf8());
103     }
104 
105     struct dirent *entry;
106     while ((entry = readdir(dir)) != nullptr) {
107         if (entry->d_type != DT_REG) {
108             continue;
109         }
110 
111         std::string fileName = entry->d_name;
112         std::string::size_type pos = fileName.find_last_of('.');
113         if (pos == std::string::npos || !IsCompitableExtension(fileName.substr(pos))) {
114             continue;
115         }
116 
117         std::string filePath = directoryPath.Mutf8() + "/" + entry->d_name;
118         AddToParseList(UString(filePath, allocator_).View(), isDefaultImport);
119     }
120 
121     closedir(dir);
122     return;
123 }
124 #endif
125 
AddToParseList(const StringView & resolvedPath,bool isDefaultImport)126 void ImportPathManager::AddToParseList(const StringView &resolvedPath, bool isDefaultImport)
127 {
128     if (ark::os::file::File::IsDirectory(resolvedPath.Mutf8())) {
129 #ifdef USE_UNIX_SYSCALL
130         UnixWalkThroughDirectoryAndAddToParseList(resolvedPath, isDefaultImport);
131 #else
132         for (auto const &entry : fs::directory_iterator(resolvedPath.Mutf8())) {
133             if (!fs::is_regular_file(entry) || !IsCompitableExtension(entry.path().extension().string())) {
134                 continue;
135             }
136 
137             AddToParseList(UString(entry.path().string(), allocator_).View(), isDefaultImport);
138         }
139         return;
140 #endif
141     }
142 
143     for (const auto &parseInfo : parseList_) {
144         if (parseInfo.sourcePath == resolvedPath) {
145             return;
146         }
147     }
148 
149     auto &dynamicPaths = arktsConfig_->DynamicPaths();
150     if (auto it = dynamicPaths.find(resolvedPath.Mutf8()); it != dynamicPaths.cend()) {
151         parseList_.emplace(parseList_.begin(), ParseInfo {resolvedPath, false});
152         return;
153     }
154 
155     if (!ark::os::file::File::IsRegularFile(resolvedPath.Mutf8())) {
156         throw Error(ErrorType::GENERIC, "", "Not an available source path: " + resolvedPath.Mutf8());
157     }
158 
159     if (isDefaultImport) {
160         int position = resolvedPath.Mutf8().find_last_of(pathDelimiter_);
161         if (resolvedPath.Substr(position + 1, resolvedPath.Length()).Is("Object.sts")) {
162             parseList_.emplace(parseList_.begin(), ParseInfo {resolvedPath, false});
163             return;
164         }
165     }
166 
167     parseList_.emplace_back(ParseInfo {resolvedPath, false});
168 }
169 
ParseList()170 const ArenaVector<ImportPathManager::ParseInfo> &ImportPathManager::ParseList()
171 {
172     return parseList_;
173 }
174 
GetImportData(const util::StringView & path,const ScriptExtension & extension) const175 ImportPathManager::ImportData ImportPathManager::GetImportData(const util::StringView &path,
176                                                                const ScriptExtension &extension) const
177 {
178     const auto &dynamicPaths = arktsConfig_->DynamicPaths();
179     auto key = ark::os::NormalizePath(path.Mutf8());
180 
181     auto it = dynamicPaths.find(key);
182     if (it == dynamicPaths.cend()) {
183         key = ark::os::RemoveExtension(key);
184     }
185 
186     while (it == dynamicPaths.cend() && !key.empty()) {
187         it = dynamicPaths.find(key);
188         if (it != dynamicPaths.cend()) {
189             break;
190         }
191         key = ark::os::GetParentDir(key);
192     }
193 
194     if (it != dynamicPaths.cend()) {
195         return {it->second.GetLanguage(), key, it->second.HasDecl()};
196     }
197 
198     return {ToLanguage(extension), path.Mutf8(), true};
199 }
200 
MarkAsParsed(const StringView & path)201 void ImportPathManager::MarkAsParsed(const StringView &path)
202 {
203     for (auto &parseInfo : parseList_) {
204         if (parseInfo.sourcePath == path) {
205             parseInfo.isParsed = true;
206             return;
207         }
208     }
209 }
210 
IsRelativePath(const StringView & path) const211 bool ImportPathManager::IsRelativePath(const StringView &path) const
212 {
213     std::string currentDirReference = ".";
214     std::string parentDirReference = "..";
215 
216     currentDirReference.append(pathDelimiter_);
217     parentDirReference.append(pathDelimiter_);
218 
219     return ((path.Mutf8().find(currentDirReference) == 0) || (path.Mutf8().find(parentDirReference) == 0));
220 }
221 
GetRealPath(const StringView & path) const222 StringView ImportPathManager::GetRealPath(const StringView &path) const
223 {
224     const std::string realPath = ark::os::GetAbsolutePath(path.Mutf8());
225     if (realPath.empty() || realPath == path.Mutf8()) {
226         return path;
227     }
228 
229     return UString(realPath, allocator_).View();
230 }
231 
AppendExtensionOrIndexFileIfOmitted(const StringView & path) const232 StringView ImportPathManager::AppendExtensionOrIndexFileIfOmitted(const StringView &path) const
233 {
234     StringView realPath = GetRealPath(path);
235     if (ark::os::file::File::IsRegularFile(realPath.Mutf8())) {
236         return realPath;
237     }
238 
239     if (ark::os::file::File::IsDirectory(realPath.Mutf8())) {
240         // Supported index files: keep this checking order
241         std::array<std::string, SUPPORTED_INDEX_FILES_SIZE> supportedIndexFiles = {"index.sts", "index.ts"};
242         for (const auto &indexFile : supportedIndexFiles) {
243             std::string indexFilePath = realPath.Mutf8() + pathDelimiter_.data() + indexFile;
244             if (ark::os::file::File::IsRegularFile(indexFilePath)) {
245                 return GetRealPath(UString(indexFilePath, allocator_).View());
246             }
247         }
248 
249         return realPath;
250     }
251 
252     // Supported extensions: keep this checking order
253     std::array<std::string, SUPPORTED_EXTENSIONS_SIZE> supportedExtensions = {".sts", ".ts"};
254 
255     for (const auto &extension : supportedExtensions) {
256         if (ark::os::file::File::IsRegularFile(path.Mutf8() + extension)) {
257             return GetRealPath(UString(path.Mutf8().append(extension), allocator_).View());
258         }
259     }
260 
261     auto &dynamicPaths = arktsConfig_->DynamicPaths();
262     if (auto it = dynamicPaths.find(path.Mutf8()); it != dynamicPaths.cend()) {
263         return path;
264     }
265 
266     throw Error(ErrorType::GENERIC, "", "Not supported path: " + path.Mutf8());
267 }
268 
269 }  // namespace ark::es2panda::util
270 #undef USE_UNIX_SYSCALL
271