xref: /openbmc/google-ipmi-sys/util.cpp (revision 8d5c9cec)
1 #include "util.hpp"
2 
3 #include <cstdio>
4 #include <fstream>
5 #include <nlohmann/json.hpp>
6 #include <phosphor-logging/elog-errors.hpp>
7 #include <string>
8 #include <xyz/openbmc_project/Common/error.hpp>
9 
10 namespace google
11 {
12 namespace ipmi
13 {
14 
15 using namespace phosphor::logging;
16 using InternalFailure =
17     sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure;
18 
19 nlohmann::json parseConfig(const std::string& file)
20 {
21     std::ifstream jsonFile(file);
22     if (!jsonFile.is_open())
23     {
24         log<level::ERR>("Entity association JSON file not found");
25         elog<InternalFailure>();
26     }
27 
28     auto data = nlohmann::json::parse(jsonFile, nullptr, false);
29     if (data.is_discarded())
30     {
31         log<level::ERR>("Entity association JSON parser failure");
32         elog<InternalFailure>();
33     }
34 
35     return data;
36 }
37 
38 std::string readPropertyFile(const std::string& fileName)
39 {
40     std::ifstream ifs(fileName);
41     std::string contents;
42 
43     if (!ifs.is_open())
44     {
45         std::fprintf(stderr, "Unable to open file %s.\n", fileName.c_str());
46     }
47     else
48     {
49         if (ifs >> contents)
50         {
51             // If the last character is a null terminator; remove it.
52             if (!contents.empty())
53             {
54                 char const& back = contents.back();
55                 if (back == '\0')
56                     contents.pop_back();
57             }
58 
59             return contents;
60         }
61         else
62         {
63             std::fprintf(stderr, "Unable to read file %s.\n", fileName.c_str());
64         }
65     }
66 
67     return "";
68 }
69 
70 } // namespace ipmi
71 } // namespace google
72