13af6ab5fSopenharmony_ci/**
23af6ab5fSopenharmony_ci * Copyright (c) 2024 Huawei Device Co., Ltd.
33af6ab5fSopenharmony_ci * Licensed under the Apache License, Version 2.0 (the "License");
43af6ab5fSopenharmony_ci * you may not use this file except in compliance with the License.
53af6ab5fSopenharmony_ci * You may obtain a copy of the License at
63af6ab5fSopenharmony_ci *
73af6ab5fSopenharmony_ci *     http://www.apache.org/licenses/LICENSE-2.0
83af6ab5fSopenharmony_ci *
93af6ab5fSopenharmony_ci * Unless required by applicable law or agreed to in writing, software
103af6ab5fSopenharmony_ci * distributed under the License is distributed on an "AS IS" BASIS,
113af6ab5fSopenharmony_ci * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
123af6ab5fSopenharmony_ci * See the License for the specific language governing permissions and
133af6ab5fSopenharmony_ci * limitations under the License.
143af6ab5fSopenharmony_ci */
153af6ab5fSopenharmony_ci
163af6ab5fSopenharmony_ci#include "importPathManager.h"
173af6ab5fSopenharmony_ci#include <libpandabase/os/filesystem.h>
183af6ab5fSopenharmony_ci
193af6ab5fSopenharmony_ci#ifdef USE_UNIX_SYSCALL
203af6ab5fSopenharmony_ci#include <dirent.h>
213af6ab5fSopenharmony_ci#include <sys/types.h>
223af6ab5fSopenharmony_ci#include <unistd.h>
233af6ab5fSopenharmony_ci#else
243af6ab5fSopenharmony_ci#if __has_include(<filesystem>)
253af6ab5fSopenharmony_ci#include <filesystem>
263af6ab5fSopenharmony_cinamespace fs = std::filesystem;
273af6ab5fSopenharmony_ci#elif __has_include(<experimental/filesystem>)
283af6ab5fSopenharmony_ci#include <experimental/filesystem>
293af6ab5fSopenharmony_cinamespace fs = std::experimental::filesystem;
303af6ab5fSopenharmony_ci#endif
313af6ab5fSopenharmony_ci#endif
323af6ab5fSopenharmony_cinamespace ark::es2panda::util {
333af6ab5fSopenharmony_ci
343af6ab5fSopenharmony_ciconstexpr size_t SUPPORTED_INDEX_FILES_SIZE = 2;
353af6ab5fSopenharmony_ciconstexpr size_t SUPPORTED_EXTENSIONS_SIZE = 2;
363af6ab5fSopenharmony_ci
373af6ab5fSopenharmony_cistatic bool IsCompatibleExtension(const std::string &extension)
383af6ab5fSopenharmony_ci{
393af6ab5fSopenharmony_ci    return extension == ".sts" || extension == ".ts";
403af6ab5fSopenharmony_ci}
413af6ab5fSopenharmony_ci
423af6ab5fSopenharmony_ciStringView ImportPathManager::ResolvePath(const StringView &currentModulePath, const StringView &importPath) const
433af6ab5fSopenharmony_ci{
443af6ab5fSopenharmony_ci    if (importPath.Empty()) {
453af6ab5fSopenharmony_ci        throw Error(ErrorType::GENERIC, "", "Import path cannot be empty");
463af6ab5fSopenharmony_ci    }
473af6ab5fSopenharmony_ci
483af6ab5fSopenharmony_ci    if (IsRelativePath(importPath)) {
493af6ab5fSopenharmony_ci        const size_t pos = currentModulePath.Mutf8().find_last_of(pathDelimiter_);
503af6ab5fSopenharmony_ci        ASSERT(pos != std::string::npos);
513af6ab5fSopenharmony_ci
523af6ab5fSopenharmony_ci        auto currentDirectory = currentModulePath.Mutf8().substr(0, pos);
533af6ab5fSopenharmony_ci        auto resolvedPath = UString(currentDirectory, allocator_);
543af6ab5fSopenharmony_ci        resolvedPath.Append(pathDelimiter_);
553af6ab5fSopenharmony_ci        resolvedPath.Append(importPath.Mutf8());
563af6ab5fSopenharmony_ci
573af6ab5fSopenharmony_ci        return AppendExtensionOrIndexFileIfOmitted(resolvedPath.View());
583af6ab5fSopenharmony_ci    }
593af6ab5fSopenharmony_ci
603af6ab5fSopenharmony_ci    std::string baseUrl;
613af6ab5fSopenharmony_ci    if (importPath.Mutf8()[0] == pathDelimiter_.at(0)) {
623af6ab5fSopenharmony_ci        baseUrl = arktsConfig_->BaseUrl();
633af6ab5fSopenharmony_ci        baseUrl.append(importPath.Mutf8(), 0, importPath.Mutf8().length());
643af6ab5fSopenharmony_ci        return AppendExtensionOrIndexFileIfOmitted(UString(baseUrl, allocator_).View());
653af6ab5fSopenharmony_ci    }
663af6ab5fSopenharmony_ci
673af6ab5fSopenharmony_ci    auto &dynamicPaths = arktsConfig_->DynamicPaths();
683af6ab5fSopenharmony_ci    if (auto it = dynamicPaths.find(importPath.Mutf8()); it != dynamicPaths.cend() && !it->second.HasDecl()) {
693af6ab5fSopenharmony_ci        return AppendExtensionOrIndexFileIfOmitted(importPath);
703af6ab5fSopenharmony_ci    }
713af6ab5fSopenharmony_ci
723af6ab5fSopenharmony_ci    const size_t pos = importPath.Mutf8().find(pathDelimiter_);
733af6ab5fSopenharmony_ci    bool containsDelim = (pos != std::string::npos);
743af6ab5fSopenharmony_ci    auto rootPart = containsDelim ? importPath.Substr(0, pos) : importPath;
753af6ab5fSopenharmony_ci    if (!stdLib_.empty() &&
763af6ab5fSopenharmony_ci        (rootPart.Is("std") || rootPart.Is("escompat"))) {  // Get std or escompat path from CLI if provided
773af6ab5fSopenharmony_ci        baseUrl = stdLib_ + pathDelimiter_.at(0) + rootPart.Mutf8();
783af6ab5fSopenharmony_ci    } else {
793af6ab5fSopenharmony_ci        ASSERT(arktsConfig_ != nullptr);
803af6ab5fSopenharmony_ci        auto resolvedPath = arktsConfig_->ResolvePath(importPath.Mutf8());
813af6ab5fSopenharmony_ci        if (!resolvedPath) {
823af6ab5fSopenharmony_ci            throw Error(ErrorType::GENERIC, "",
833af6ab5fSopenharmony_ci                        "Can't find prefix for '" + importPath.Mutf8() + "' in " + arktsConfig_->ConfigPath());
843af6ab5fSopenharmony_ci        }
853af6ab5fSopenharmony_ci
863af6ab5fSopenharmony_ci        return AppendExtensionOrIndexFileIfOmitted(UString(resolvedPath.value(), allocator_).View());
873af6ab5fSopenharmony_ci    }
883af6ab5fSopenharmony_ci
893af6ab5fSopenharmony_ci    if (containsDelim) {
903af6ab5fSopenharmony_ci        baseUrl.append(1, pathDelimiter_.at(0));
913af6ab5fSopenharmony_ci        baseUrl.append(importPath.Mutf8(), rootPart.Mutf8().length() + 1, importPath.Mutf8().length());
923af6ab5fSopenharmony_ci    }
933af6ab5fSopenharmony_ci
943af6ab5fSopenharmony_ci    return UString(baseUrl, allocator_).View();
953af6ab5fSopenharmony_ci}
963af6ab5fSopenharmony_ci
973af6ab5fSopenharmony_ci#ifdef USE_UNIX_SYSCALL
983af6ab5fSopenharmony_civoid ImportPathManager::UnixWalkThroughDirectoryAndAddToParseList(const StringView &directoryPath,
993af6ab5fSopenharmony_ci                                                                  const ImportFlags importFlags)
1003af6ab5fSopenharmony_ci{
1013af6ab5fSopenharmony_ci    DIR *dir = opendir(directoryPath.Mutf8().c_str());
1023af6ab5fSopenharmony_ci    if (dir == nullptr) {
1033af6ab5fSopenharmony_ci        throw Error(ErrorType::GENERIC, "", "Cannot open folder: " + directoryPath.Mutf8());
1043af6ab5fSopenharmony_ci    }
1053af6ab5fSopenharmony_ci
1063af6ab5fSopenharmony_ci    struct dirent *entry;
1073af6ab5fSopenharmony_ci    while ((entry = readdir(dir)) != nullptr) {
1083af6ab5fSopenharmony_ci        if (entry->d_type != DT_REG) {
1093af6ab5fSopenharmony_ci            continue;
1103af6ab5fSopenharmony_ci        }
1113af6ab5fSopenharmony_ci
1123af6ab5fSopenharmony_ci        std::string fileName = entry->d_name;
1133af6ab5fSopenharmony_ci        std::string::size_type pos = fileName.find_last_of('.');
1143af6ab5fSopenharmony_ci        if (pos == std::string::npos || !IsCompatibleExtension(fileName.substr(pos))) {
1153af6ab5fSopenharmony_ci            continue;
1163af6ab5fSopenharmony_ci        }
1173af6ab5fSopenharmony_ci
1183af6ab5fSopenharmony_ci        std::string filePath = directoryPath.Mutf8() + "/" + entry->d_name;
1193af6ab5fSopenharmony_ci        AddToParseList(UString(filePath, allocator_).View(), importFlags);
1203af6ab5fSopenharmony_ci    }
1213af6ab5fSopenharmony_ci
1223af6ab5fSopenharmony_ci    closedir(dir);
1233af6ab5fSopenharmony_ci    return;
1243af6ab5fSopenharmony_ci}
1253af6ab5fSopenharmony_ci#endif
1263af6ab5fSopenharmony_ci
1273af6ab5fSopenharmony_civoid ImportPathManager::AddToParseList(const StringView &resolvedPath, const ImportFlags importFlags)
1283af6ab5fSopenharmony_ci{
1293af6ab5fSopenharmony_ci    const bool isDefaultImport = (importFlags & ImportFlags::DEFAULT_IMPORT) != 0;
1303af6ab5fSopenharmony_ci    const bool isImplicitPackageImport = (importFlags & ImportFlags::IMPLICIT_PACKAGE_IMPORT) != 0;
1313af6ab5fSopenharmony_ci    const auto parseInfo = ParseInfo {resolvedPath, false, isImplicitPackageImport};
1323af6ab5fSopenharmony_ci
1333af6ab5fSopenharmony_ci    if (ark::os::file::File::IsDirectory(resolvedPath.Mutf8())) {
1343af6ab5fSopenharmony_ci#ifdef USE_UNIX_SYSCALL
1353af6ab5fSopenharmony_ci        UnixWalkThroughDirectoryAndAddToParseList(resolvedPath, importFlags);
1363af6ab5fSopenharmony_ci#else
1373af6ab5fSopenharmony_ci        for (auto const &entry : fs::directory_iterator(resolvedPath.Mutf8())) {
1383af6ab5fSopenharmony_ci            if (!fs::is_regular_file(entry) || !IsCompatibleExtension(entry.path().extension().string())) {
1393af6ab5fSopenharmony_ci                continue;
1403af6ab5fSopenharmony_ci            }
1413af6ab5fSopenharmony_ci
1423af6ab5fSopenharmony_ci            AddToParseList(UString(entry.path().string(), allocator_).View(), importFlags);
1433af6ab5fSopenharmony_ci        }
1443af6ab5fSopenharmony_ci        return;
1453af6ab5fSopenharmony_ci#endif
1463af6ab5fSopenharmony_ci    }
1473af6ab5fSopenharmony_ci
1483af6ab5fSopenharmony_ci    // Check if file has been already added to parse list
1493af6ab5fSopenharmony_ci    if (const auto &found =
1503af6ab5fSopenharmony_ci            std::find_if(parseList_.begin(), parseList_.end(),
1513af6ab5fSopenharmony_ci                         [&resolvedPath](const ParseInfo &info) { return (info.sourcePath == resolvedPath); });
1523af6ab5fSopenharmony_ci        found != parseList_.end()) {
1533af6ab5fSopenharmony_ci        // The 'parseList_' can contain at most 1 record with the same source file path (else it'll break things).
1543af6ab5fSopenharmony_ci        //
1553af6ab5fSopenharmony_ci        // If a file is added as implicit package imported before, then we may add it again without the implicit import
1563af6ab5fSopenharmony_ci        // directive (and remove the other one), to handle when an implicitly package imported file explicitly imports
1573af6ab5fSopenharmony_ci        // it. Re-parsing it is necessary, because if the implicitly package imported file contains a syntax error, then
1583af6ab5fSopenharmony_ci        // it'll be ignored, but we must not ignore it if an explicitly imported file contains a parse error. Also this
1593af6ab5fSopenharmony_ci        // addition can happen during parsing the files in the parse list, so re-addition is necessary in order to
1603af6ab5fSopenharmony_ci        // surely re-parse it.
1613af6ab5fSopenharmony_ci        //
1623af6ab5fSopenharmony_ci        // If a file was already not implicitly package imported, then it's just a duplicate, return
1633af6ab5fSopenharmony_ci        if (!found->isImplicitPackageImported) {
1643af6ab5fSopenharmony_ci            return;
1653af6ab5fSopenharmony_ci        }
1663af6ab5fSopenharmony_ci
1673af6ab5fSopenharmony_ci        parseList_.erase(found);
1683af6ab5fSopenharmony_ci    }
1693af6ab5fSopenharmony_ci
1703af6ab5fSopenharmony_ci    if (const auto &dynamicPaths = arktsConfig_->DynamicPaths();
1713af6ab5fSopenharmony_ci        dynamicPaths.find(resolvedPath.Mutf8()) != dynamicPaths.cend()) {
1723af6ab5fSopenharmony_ci        parseList_.emplace(parseList_.begin(), parseInfo);
1733af6ab5fSopenharmony_ci        return;
1743af6ab5fSopenharmony_ci    }
1753af6ab5fSopenharmony_ci
1763af6ab5fSopenharmony_ci    if (!ark::os::file::File::IsRegularFile(resolvedPath.Mutf8())) {
1773af6ab5fSopenharmony_ci        throw Error(ErrorType::GENERIC, "", "Not an available source path: " + resolvedPath.Mutf8());
1783af6ab5fSopenharmony_ci    }
1793af6ab5fSopenharmony_ci
1803af6ab5fSopenharmony_ci    // 'Object.sts' must be the first in the parse list
1813af6ab5fSopenharmony_ci    // NOTE (mmartin): still must be the first?
1823af6ab5fSopenharmony_ci    const std::size_t position = resolvedPath.Mutf8().find_last_of(pathDelimiter_);
1833af6ab5fSopenharmony_ci    if (isDefaultImport && resolvedPath.Substr(position + 1, resolvedPath.Length()).Is("Object.sts")) {
1843af6ab5fSopenharmony_ci        parseList_.emplace(parseList_.begin(), parseInfo);
1853af6ab5fSopenharmony_ci    } else {
1863af6ab5fSopenharmony_ci        parseList_.emplace_back(parseInfo);
1873af6ab5fSopenharmony_ci    }
1883af6ab5fSopenharmony_ci}
1893af6ab5fSopenharmony_ci
1903af6ab5fSopenharmony_ciImportPathManager::ImportData ImportPathManager::GetImportData(const util::StringView &path,
1913af6ab5fSopenharmony_ci                                                               const ScriptExtension &extension) const
1923af6ab5fSopenharmony_ci{
1933af6ab5fSopenharmony_ci    const auto &dynamicPaths = arktsConfig_->DynamicPaths();
1943af6ab5fSopenharmony_ci    auto key = ark::os::NormalizePath(path.Mutf8());
1953af6ab5fSopenharmony_ci
1963af6ab5fSopenharmony_ci    auto it = dynamicPaths.find(key);
1973af6ab5fSopenharmony_ci    if (it == dynamicPaths.cend()) {
1983af6ab5fSopenharmony_ci        key = ark::os::RemoveExtension(key);
1993af6ab5fSopenharmony_ci    }
2003af6ab5fSopenharmony_ci
2013af6ab5fSopenharmony_ci    while (it == dynamicPaths.cend() && !key.empty()) {
2023af6ab5fSopenharmony_ci        it = dynamicPaths.find(key);
2033af6ab5fSopenharmony_ci        if (it != dynamicPaths.cend()) {
2043af6ab5fSopenharmony_ci            break;
2053af6ab5fSopenharmony_ci        }
2063af6ab5fSopenharmony_ci        key = ark::os::GetParentDir(key);
2073af6ab5fSopenharmony_ci    }
2083af6ab5fSopenharmony_ci
2093af6ab5fSopenharmony_ci    if (it != dynamicPaths.cend()) {
2103af6ab5fSopenharmony_ci        return {it->second.GetLanguage(), key, it->second.HasDecl()};
2113af6ab5fSopenharmony_ci    }
2123af6ab5fSopenharmony_ci
2133af6ab5fSopenharmony_ci    return {ToLanguage(extension), path.Mutf8(), true};
2143af6ab5fSopenharmony_ci}
2153af6ab5fSopenharmony_ci
2163af6ab5fSopenharmony_civoid ImportPathManager::MarkAsParsed(const StringView &path)
2173af6ab5fSopenharmony_ci{
2183af6ab5fSopenharmony_ci    for (auto &parseInfo : parseList_) {
2193af6ab5fSopenharmony_ci        if (parseInfo.sourcePath == path) {
2203af6ab5fSopenharmony_ci            parseInfo.isParsed = true;
2213af6ab5fSopenharmony_ci            return;
2223af6ab5fSopenharmony_ci        }
2233af6ab5fSopenharmony_ci    }
2243af6ab5fSopenharmony_ci}
2253af6ab5fSopenharmony_ci
2263af6ab5fSopenharmony_cibool ImportPathManager::IsRelativePath(const StringView &path) const
2273af6ab5fSopenharmony_ci{
2283af6ab5fSopenharmony_ci    std::string currentDirReference = ".";
2293af6ab5fSopenharmony_ci    std::string parentDirReference = "..";
2303af6ab5fSopenharmony_ci
2313af6ab5fSopenharmony_ci    currentDirReference.append(pathDelimiter_);
2323af6ab5fSopenharmony_ci    parentDirReference.append(pathDelimiter_);
2333af6ab5fSopenharmony_ci
2343af6ab5fSopenharmony_ci    return ((path.Mutf8().find(currentDirReference) == 0) || (path.Mutf8().find(parentDirReference) == 0));
2353af6ab5fSopenharmony_ci}
2363af6ab5fSopenharmony_ci
2373af6ab5fSopenharmony_ciStringView ImportPathManager::GetRealPath(const StringView &path) const
2383af6ab5fSopenharmony_ci{
2393af6ab5fSopenharmony_ci    const std::string realPath = ark::os::GetAbsolutePath(path.Mutf8());
2403af6ab5fSopenharmony_ci    if (realPath.empty() || realPath == path.Mutf8()) {
2413af6ab5fSopenharmony_ci        return path;
2423af6ab5fSopenharmony_ci    }
2433af6ab5fSopenharmony_ci
2443af6ab5fSopenharmony_ci    return UString(realPath, allocator_).View();
2453af6ab5fSopenharmony_ci}
2463af6ab5fSopenharmony_ci
2473af6ab5fSopenharmony_ciStringView ImportPathManager::AppendExtensionOrIndexFileIfOmitted(const StringView &path) const
2483af6ab5fSopenharmony_ci{
2493af6ab5fSopenharmony_ci    StringView realPath = GetRealPath(path);
2503af6ab5fSopenharmony_ci    if (ark::os::file::File::IsRegularFile(realPath.Mutf8())) {
2513af6ab5fSopenharmony_ci        return realPath;
2523af6ab5fSopenharmony_ci    }
2533af6ab5fSopenharmony_ci
2543af6ab5fSopenharmony_ci    if (ark::os::file::File::IsDirectory(realPath.Mutf8())) {
2553af6ab5fSopenharmony_ci        // Supported index files: keep this checking order
2563af6ab5fSopenharmony_ci        std::array<std::string, SUPPORTED_INDEX_FILES_SIZE> supportedIndexFiles = {"index.sts", "index.ts"};
2573af6ab5fSopenharmony_ci        for (const auto &indexFile : supportedIndexFiles) {
2583af6ab5fSopenharmony_ci            std::string indexFilePath = realPath.Mutf8() + pathDelimiter_.data() + indexFile;
2593af6ab5fSopenharmony_ci            if (ark::os::file::File::IsRegularFile(indexFilePath)) {
2603af6ab5fSopenharmony_ci                return GetRealPath(UString(indexFilePath, allocator_).View());
2613af6ab5fSopenharmony_ci            }
2623af6ab5fSopenharmony_ci        }
2633af6ab5fSopenharmony_ci
2643af6ab5fSopenharmony_ci        return realPath;
2653af6ab5fSopenharmony_ci    }
2663af6ab5fSopenharmony_ci
2673af6ab5fSopenharmony_ci    // Supported extensions: keep this checking order
2683af6ab5fSopenharmony_ci    std::array<std::string, SUPPORTED_EXTENSIONS_SIZE> supportedExtensions = {".sts", ".ts"};
2693af6ab5fSopenharmony_ci
2703af6ab5fSopenharmony_ci    for (const auto &extension : supportedExtensions) {
2713af6ab5fSopenharmony_ci        if (ark::os::file::File::IsRegularFile(path.Mutf8() + extension)) {
2723af6ab5fSopenharmony_ci            return GetRealPath(UString(path.Mutf8().append(extension), allocator_).View());
2733af6ab5fSopenharmony_ci        }
2743af6ab5fSopenharmony_ci    }
2753af6ab5fSopenharmony_ci
2763af6ab5fSopenharmony_ci    auto &dynamicPaths = arktsConfig_->DynamicPaths();
2773af6ab5fSopenharmony_ci    if (auto it = dynamicPaths.find(path.Mutf8()); it != dynamicPaths.cend()) {
2783af6ab5fSopenharmony_ci        return path;
2793af6ab5fSopenharmony_ci    }
2803af6ab5fSopenharmony_ci
2813af6ab5fSopenharmony_ci    throw Error(ErrorType::GENERIC, "", "Not supported path: " + path.Mutf8());
2823af6ab5fSopenharmony_ci}
2833af6ab5fSopenharmony_ci
2843af6ab5fSopenharmony_ci}  // namespace ark::es2panda::util
2853af6ab5fSopenharmony_ci#undef USE_UNIX_SYSCALL
286