1 /*
2 * Copyright (c) 2025 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 "common.h"
17
18 #include <array>
19 #include <cstdio>
20 #include <cstring>
21 #include <dirent.h>
22 #include <string>
23 #include <sys/stat.h>
24 #include <sys/types.h>
25 #include <unistd.h>
26
27 using namespace std;
28
29 namespace UnitTest {
30 namespace SQLiteTest {
RemoveDir(const char * dir)31 int Common::RemoveDir(const char *dir)
32 {
33 if (dir == nullptr) {
34 return TEST_STATUS_ERR;
35 }
36 if (access(dir, F_OK) != 0) {
37 return TEST_STATUS_OK;
38 }
39 struct stat dirStat;
40 if (stat(dir, &dirStat) < 0) {
41 return TEST_STATUS_ERR;
42 }
43 DIR *dirPtr = nullptr;
44 struct dirent *dr = nullptr;
45 if (S_ISREG(dirStat.st_mode)) {
46 remove(dir);
47 } else if (S_ISDIR(dirStat.st_mode)) {
48 dirPtr = opendir(dir);
49 while ((dr = readdir(dirPtr)) != nullptr) {
50 if ((strcmp(".", dr->d_name) == 0) || (strcmp("..", dr->d_name) == 0)) {
51 continue;
52 }
53 string dirName = dir;
54 dirName += "/";
55 dirName += dr->d_name;
56 RemoveDir(dirName.c_str());
57 }
58 closedir(dirPtr);
59 rmdir(dir);
60 } else {
61 return TEST_STATUS_ERR;
62 }
63 return TEST_STATUS_OK;
64 }
65
MakeDir(const char * dir)66 int Common::MakeDir(const char *dir)
67 {
68 if (dir == nullptr) {
69 return TEST_STATUS_ERR;
70 }
71 if (strlen(dir) > PATH_MAX) {
72 return TEST_STATUS_ERR;
73 }
74 if (access(dir, 0) != -1) {
75 return TEST_STATUS_OK;
76 }
77 char tmpPath[PATH_MAX + 1] = {0};
78 const char *pcur = dir;
79 int pos = 0;
80 while (*pcur++ != '\0') {
81 tmpPath[pos++] = *const_cast<char *>(pcur - 1);
82 if ((*pcur == '/' || *pcur == '\0') && access(tmpPath, 0) != 0 && strlen(tmpPath) > 0) {
83 if (mkdir(tmpPath, (S_IRUSR | S_IWUSR | S_IXUSR)) != 0) {
84 return TEST_STATUS_ERR;
85 }
86 }
87 }
88 return TEST_STATUS_OK;
89 }
90
IsFileExist(const char * fullPath)91 bool Common::IsFileExist(const char *fullPath)
92 {
93 struct stat statBuf;
94 if (stat(fullPath, &statBuf) < 0) {
95 return false;
96 }
97 return S_ISREG(statBuf.st_mode);
98 }
99
100 } // namespace SQLiteTest
101 } // namespace UnitTest