xref: /openbmc/openpower-pnor-code-mgmt/version.cpp (revision a93a07b3922aa12334f0a728cb9325633a4415a0)
1 #include <iostream>
2 #include <string>
3 #include <sstream>
4 #include <fstream>
5 #include <stdexcept>
6 #include <phosphor-logging/log.hpp>
7 #include "version.hpp"
8 #include <phosphor-logging/elog-errors.hpp>
9 #include "xyz/openbmc_project/Common/error.hpp"
10 #include "item_updater.hpp"
11 
12 namespace openpower
13 {
14 namespace software
15 {
16 namespace updater
17 {
18 
19 using namespace sdbusplus::xyz::openbmc_project::Common::Error;
20 using namespace phosphor::logging;
21 using Argument = xyz::openbmc_project::Common::InvalidArgument;
22 
23 std::string Version::getId(const std::string& version)
24 {
25     std::stringstream hexId;
26 
27     if (version.empty())
28     {
29         log<level::ERR>("Error version is empty");
30         elog<InvalidArgument>(Argument::ARGUMENT_NAME("Version"),
31                               Argument::ARGUMENT_VALUE(version.c_str()));
32     }
33 
34     // Only want 8 hex digits.
35     hexId << std::hex << ((std::hash<std::string> {}(
36                                version)) & 0xFFFFFFFF);
37     return hexId.str();
38 }
39 
40 std::map<std::string, std::string> Version::getValue(
41         const std::string& filePath, std::map<std::string, std::string> keys)
42 {
43     if (filePath.empty())
44     {
45         log<level::ERR>("Error filePath is empty");
46         elog<InvalidArgument>(Argument::ARGUMENT_NAME("FilePath"),
47                               Argument::ARGUMENT_VALUE(filePath.c_str()));
48     }
49 
50     std::ifstream efile;
51     std::string line;
52     efile.exceptions(std::ifstream::failbit |
53                      std::ifstream::badbit |
54                      std::ifstream::eofbit);
55 
56     try
57     {
58         efile.open(filePath);
59         while (getline(efile, line))
60         {
61             for(auto& key : keys)
62             {
63                 auto value = key.first + "=";
64                 auto keySize = value.length();
65                 if (line.compare(0, keySize, value) == 0)
66                 {
67                     key.second = line.substr(keySize);
68                     break;
69                 }
70             }
71         }
72         efile.close();
73     }
74     catch (const std::exception& e)
75     {
76         if (!efile.eof())
77         {
78             log<level::ERR>("Error in reading file");
79         }
80         efile.close();
81     }
82 
83     return keys;
84 }
85 
86 void Version::delete_()
87 {
88     parent.erase(getId(version()));
89 }
90 
91 } // namespace updater
92 } // namespace software
93 } // namespace openpower
94