1/* 2 * Copyright (c) 2023 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#include "ecmascript/base/path_helper.h" 16 17namespace panda::ecmascript::base { 18/* 19 * Before: ./xxx/../xxx/xxx/ 20 * After: xxx/xxx 21 */ 22CString PathHelper::NormalizePath(const CString &fileName) 23{ 24 if (fileName.empty() || (fileName.find(DOUBLE_SLASH_TAG) == CString::npos && 25 fileName.find(CURRENT_DIREATORY_TAG) == CString::npos && 26 fileName[fileName.size() - 1] != SLASH_TAG)) { 27 return fileName; 28 } 29 CString res = ""; 30 size_t prev = 0; 31 size_t curr = fileName.find(SLASH_TAG); 32 CVector<CString> elems; 33 // eliminate parent directory path 34 while (curr != CString::npos) { 35 if (curr > prev) { 36 CString elem = fileName.substr(prev, curr - prev); 37 if (elem == DOUBLE_POINT_TAG && !elems.empty()) { // looking for xxx/../ 38 elems.pop_back(); 39 } else if (elem != POINT_STRING_TAG && elem != DOUBLE_POINT_TAG) { // remove ./ ../ 40 elems.push_back(elem); 41 } 42 } 43 prev = curr + 1; 44 curr = fileName.find(SLASH_TAG, prev); 45 } 46 if (prev != fileName.size()) { 47 elems.push_back(fileName.substr(prev)); 48 } 49 for (auto e : elems) { 50 if (res.size() == 0 && fileName.at(0) != SLASH_TAG) { 51 res.append(e); 52 continue; 53 } 54 res.append(1, SLASH_TAG).append(e); 55 } 56 return res; 57} 58 59/* 60 * Before: xxx/xxx 61 * After: xxx/ 62 */ 63CString PathHelper::ResolveDirPath(const CString &fileName) 64{ 65 // find last '/', '\\' 66 int foundPos = static_cast<int>(fileName.find_last_of("/\\")); 67 if (foundPos == -1) { 68 return CString(); 69 } 70 return fileName.substr(0, foundPos + 1); 71} 72} // namespace panda::ecmascript::base