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 <fstream>
16#include <sstream>
17#include "hidumper_test_utils.h"
18
19using namespace std;
20namespace OHOS {
21namespace HiviewDFX {
22HidumperTestUtils::HidumperTestUtils()
23{
24}
25
26HidumperTestUtils::~HidumperTestUtils()
27{
28}
29
30bool HidumperTestUtils::IsExistInCmdResult(const std::string &cmd, const std::string &str)
31{
32    std::string line = "";
33    return GetSpecialLine(cmd, str, line);
34}
35
36bool HidumperTestUtils::IsExistStrInFile(const std::string &cmd, const std::string &str, const std::string &filePath)
37{
38    bool res = false;
39    FILE *fp = popen(cmd.c_str(), "r");
40    pclose(fp);
41
42    std::ifstream file(filePath);
43    if (!file.is_open()) {
44        return res;
45    }
46    std::string line;
47    while (std::getline(file, line)) {
48        if (line.find(str) != string::npos) {
49            res = true;
50            break;
51        }
52    }
53    file.close();
54    return res;
55}
56
57pid_t HidumperTestUtils::GetPidByName(const std::string& processName)
58{
59    FILE *fp = nullptr;
60    char buf[100]; // 100: buf size
61    pid_t pid = -1;
62    std::string cmd = "pidof " + processName;
63    if ((fp = popen(cmd.c_str(), "r")) != nullptr) {
64        if (fgets(buf, sizeof(buf), fp) != nullptr) {
65            pid = std::atoi(buf);
66        }
67        pclose(fp);
68    }
69    return pid;
70}
71
72bool HidumperTestUtils::GetSpecialLine(const std::string &cmd, const std::string &str, std::string &specialLine)
73{
74    bool res = false;
75    size_t len = 0;
76    FILE *fp = popen(cmd.c_str(), "r");
77    char* buffer = nullptr;
78    while (getline(&buffer, &len, fp) != -1) {
79        std::string line = buffer;
80        if (line.find(str) != string::npos) {
81            res = true;
82            specialLine = line;
83            break;
84        }
85    }
86    pclose(fp);
87    return res;
88}
89
90std::string HidumperTestUtils::GetValueInLine(const std::string &line, int index)
91{
92    std::istringstream iss(line);
93    std::vector<std::string> tokens;
94    std::string token;
95    while (iss >> token) {
96        tokens.push_back(token);
97    }
98    if (index < tokens.size()) {
99        return tokens[index];
100    }
101    return "";
102}
103} // namespace HiviewDFX
104} // namespace OHOS
105