• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
17 namespace panda::ecmascript::base {
18 /*
19  * Before: ./xxx/../xxx/xxx/
20  * After:  xxx/xxx
21  */
NormalizePath(const CString & fileName)22 CString PathHelper::NormalizePath(const CString &fileName)
23 {
24     if (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  */
ResolveDirPath(JSThread * thread,CString fileName)63 JSHandle<EcmaString> PathHelper::ResolveDirPath(JSThread *thread, CString fileName)
64 {
65     ObjectFactory *factory = thread->GetEcmaVM()->GetFactory();
66     // find last '/', '\\'
67     int foundPos = static_cast<int>(fileName.find_last_of("/\\"));
68     if (foundPos == -1) {
69         return factory->NewFromUtf8("");
70     }
71     CString dirPathStr = fileName.substr(0, foundPos + 1);
72     return factory->NewFromUtf8(dirPathStr);
73 }
74 }  // namespace panda::ecmascript::base