xref: /openbmc/openpower-vpd-parser/vpd-tool/include/tool_utils.hpp (revision a8bb16637a7dcd594296291b72c118e6786dd8b7)
1 #pragma once
2 
3 #include "tool_constants.hpp"
4 #include "tool_types.hpp"
5 
6 #include <nlohmann/json.hpp>
7 #include <sdbusplus/bus.hpp>
8 #include <sdbusplus/exception.hpp>
9 
10 #include <fstream>
11 #include <iostream>
12 
13 namespace vpd
14 {
15 namespace utils
16 {
17 /**
18  * @brief An API to read property from Dbus.
19  *
20  * API reads the property value for the specified interface and object path from
21  * the given Dbus service.
22  *
23  * The caller of the API needs to validate the validity and correctness of the
24  * type and value of data returned. The API will just fetch and return the data
25  * without any data validation.
26  *
27  * Note: It will be caller's responsibility to check for empty value returned
28  * and generate appropriate error if required.
29  *
30  * @param[in] i_serviceName - Name of the Dbus service.
31  * @param[in] i_objectPath - Object path under the service.
32  * @param[in] i_interface - Interface under which property exist.
33  * @param[in] i_property - Property whose value is to be read.
34  *
35  * @return - Value read from Dbus.
36  *
37  * @throw std::runtime_error
38  */
readDbusProperty(const std::string & i_serviceName,const std::string & i_objectPath,const std::string & i_interface,const std::string & i_property)39 inline types::DbusVariantType readDbusProperty(
40     const std::string& i_serviceName, const std::string& i_objectPath,
41     const std::string& i_interface, const std::string& i_property)
42 {
43     types::DbusVariantType l_propertyValue;
44 
45     // Mandatory fields to make a dbus call.
46     if (i_serviceName.empty() || i_objectPath.empty() || i_interface.empty() ||
47         i_property.empty())
48     {
49         // TODO: Enable logging when verbose is enabled.
50         /*std::cout << "One of the parameter to make Dbus read call is empty."
51                   << std::endl;*/
52         throw std::runtime_error("Empty Parameter");
53     }
54 
55     try
56     {
57         auto l_bus = sdbusplus::bus::new_default();
58         auto l_method =
59             l_bus.new_method_call(i_serviceName.c_str(), i_objectPath.c_str(),
60                                   "org.freedesktop.DBus.Properties", "Get");
61         l_method.append(i_interface, i_property);
62 
63         auto result = l_bus.call(l_method);
64         result.read(l_propertyValue);
65     }
66     catch (const sdbusplus::exception::SdBusError& l_ex)
67     {
68         // TODO: Enable logging when verbose is enabled.
69         // std::cout << std::string(l_ex.what()) << std::endl;
70         throw std::runtime_error(std::string(l_ex.what()));
71     }
72     return l_propertyValue;
73 }
74 
75 /**
76  * @brief An API to get property map for an interface.
77  *
78  * This API returns a map of property and its value with respect to a particular
79  * interface.
80  *
81  * Note: It will be caller's responsibility to check for empty map returned and
82  * generate appropriate error.
83  *
84  * @param[in] i_service - Service name.
85  * @param[in] i_objectPath - object path.
86  * @param[in] i_interface - Interface, for the properties to be listed.
87  *
88  * @return - A map of property and value of an interface, if success.
89  *           if failed, empty map.
90  */
getPropertyMap(const std::string & i_service,const std::string & i_objectPath,const std::string & i_interface)91 inline types::PropertyMap getPropertyMap(
92     const std::string& i_service, const std::string& i_objectPath,
93     const std::string& i_interface) noexcept
94 {
95     types::PropertyMap l_propertyValueMap;
96     if (i_service.empty() || i_objectPath.empty() || i_interface.empty())
97     {
98         // TODO: Enable logging when verbose is enabled.
99         // std::cout << "Invalid parameters to get property map" << std::endl;
100         return l_propertyValueMap;
101     }
102 
103     try
104     {
105         auto l_bus = sdbusplus::bus::new_default();
106         auto l_method =
107             l_bus.new_method_call(i_service.c_str(), i_objectPath.c_str(),
108                                   "org.freedesktop.DBus.Properties", "GetAll");
109         l_method.append(i_interface);
110         auto l_result = l_bus.call(l_method);
111         l_result.read(l_propertyValueMap);
112     }
113     catch (const sdbusplus::exception::SdBusError& l_ex)
114     {
115         // TODO: Enable logging when verbose is enabled.
116         // std::cerr << "Failed to get property map for service: [" << i_service
117         //           << "], object path: [" << i_objectPath
118         //           << "] Error : " << l_ex.what() << std::endl;
119     }
120 
121     return l_propertyValueMap;
122 }
123 
124 /**
125  * @brief An API to print json data on stdout.
126  *
127  * @param[in] i_jsonData - JSON object.
128  */
printJson(const nlohmann::json & i_jsonData)129 inline void printJson(const nlohmann::json& i_jsonData)
130 {
131     try
132     {
133         std::cout << i_jsonData.dump(constants::INDENTATION) << std::endl;
134     }
135     catch (const nlohmann::json::type_error& l_ex)
136     {
137         throw std::runtime_error(
138             "Failed to dump JSON data, error: " + std::string(l_ex.what()));
139     }
140 }
141 
142 /**
143  * @brief An API to convert binary value into ascii/hex representation.
144  *
145  * If given data contains printable characters, ASCII formated string value of
146  * the input data will be returned. Otherwise if the data has any non-printable
147  * value, returns the hex represented value of the given data in string format.
148  *
149  * @param[in] i_keywordValue - Data in binary format.
150  *
151  * @throw - Throws std::bad_alloc or std::terminate in case of error.
152  *
153  * @return - Returns the converted string value.
154  */
getPrintableValue(const types::BinaryVector & i_keywordValue)155 inline std::string getPrintableValue(const types::BinaryVector& i_keywordValue)
156 {
157     bool l_allPrintable =
158         std::all_of(i_keywordValue.begin(), i_keywordValue.end(),
159                     [](const auto& l_byte) { return std::isprint(l_byte); });
160 
161     std::ostringstream l_oss;
162     if (l_allPrintable)
163     {
164         l_oss << std::string(i_keywordValue.begin(), i_keywordValue.end());
165     }
166     else
167     {
168         l_oss << "0x";
169         for (const auto& l_byte : i_keywordValue)
170         {
171             l_oss << std::setfill('0') << std::setw(2) << std::hex
172                   << static_cast<int>(l_byte);
173         }
174     }
175 
176     return l_oss.str();
177 }
178 
179 /**
180  * @brief API to read keyword's value from hardware.
181  *
182  * This API reads keyword's value by requesting DBus service(vpd-manager) who
183  * hosts the 'ReadKeyword' method to read keyword's value.
184  *
185  * @param[in] i_eepromPath - EEPROM file path.
186  * @param[in] i_paramsToReadData - Property whose value has to be read.
187  *
188  * @return - Value read from hardware
189  *
190  * @throw std::runtime_error, sdbusplus::exception::SdBusError
191  */
192 inline types::DbusVariantType
readKeywordFromHardware(const std::string & i_eepromPath,const types::ReadVpdParams i_paramsToReadData)193     readKeywordFromHardware(const std::string& i_eepromPath,
194                             const types::ReadVpdParams i_paramsToReadData)
195 {
196     if (i_eepromPath.empty())
197     {
198         throw std::runtime_error("Empty EEPROM path");
199     }
200 
201     try
202     {
203         types::DbusVariantType l_propertyValue;
204 
205         auto l_bus = sdbusplus::bus::new_default();
206 
207         auto l_method = l_bus.new_method_call(
208             constants::vpdManagerService, constants::vpdManagerObjectPath,
209             constants::vpdManagerInfName, "ReadKeyword");
210 
211         l_method.append(i_eepromPath, i_paramsToReadData);
212         auto l_result = l_bus.call(l_method);
213 
214         l_result.read(l_propertyValue);
215 
216         return l_propertyValue;
217     }
218     catch (const sdbusplus::exception::SdBusError& l_error)
219     {
220         throw;
221     }
222 }
223 
224 /**
225  * @brief API to save keyword's value on file.
226  *
227  * API writes keyword's value on the given file path. If the data is in hex
228  * format, API strips '0x' and saves the value on the given file.
229  *
230  * @param[in] i_filePath - File path.
231  * @param[in] i_keywordValue - Keyword's value.
232  *
233  * @return - true on successfully writing to file, false otherwise.
234  */
saveToFile(const std::string & i_filePath,const std::string & i_keywordValue)235 inline bool saveToFile(const std::string& i_filePath,
236                        const std::string& i_keywordValue)
237 {
238     bool l_returnStatus = false;
239 
240     if (i_keywordValue.empty())
241     {
242         // ToDo: log only when verbose is enabled
243         std::cerr << "Save to file[ " << i_filePath
244                   << "] failed, reason: Empty keyword's value received"
245                   << std::endl;
246         return l_returnStatus;
247     }
248 
249     std::string l_keywordValue{i_keywordValue};
250     if (i_keywordValue.substr(0, 2).compare("0x") == constants::STR_CMP_SUCCESS)
251     {
252         l_keywordValue = i_keywordValue.substr(2);
253     }
254 
255     std::ofstream l_outPutFileStream;
256     l_outPutFileStream.exceptions(
257         std::ifstream::badbit | std::ifstream::failbit);
258     try
259     {
260         l_outPutFileStream.open(i_filePath);
261 
262         if (l_outPutFileStream.is_open())
263         {
264             l_outPutFileStream.write(l_keywordValue.c_str(),
265                                      l_keywordValue.size());
266             l_returnStatus = true;
267         }
268         else
269         {
270             // ToDo: log only when verbose is enabled
271             std::cerr << "Error opening output file " << i_filePath
272                       << std::endl;
273         }
274     }
275     catch (const std::ios_base::failure& l_ex)
276     {
277         // ToDo: log only when verbose is enabled
278         std::cerr
279             << "Failed to write to file: " << i_filePath
280             << ", either base folder path doesn't exist or internal error occured, error: "
281             << l_ex.what() << '\n';
282     }
283 
284     return l_returnStatus;
285 }
286 
287 /**
288  * @brief API to print data in JSON format on console
289  *
290  * @param[in] i_fruPath - FRU path.
291  * @param[in] i_keywordName - Keyword name.
292  * @param[in] i_keywordStrValue - Keyword's value.
293  */
displayOnConsole(const std::string & i_fruPath,const std::string & i_keywordName,const std::string & i_keywordStrValue)294 inline void displayOnConsole(const std::string& i_fruPath,
295                              const std::string& i_keywordName,
296                              const std::string& i_keywordStrValue)
297 {
298     nlohmann::json l_resultInJson = nlohmann::json::object({});
299     nlohmann::json l_keywordValInJson = nlohmann::json::object({});
300 
301     l_keywordValInJson.emplace(i_keywordName, i_keywordStrValue);
302     l_resultInJson.emplace(i_fruPath, l_keywordValInJson);
303 
304     printJson(l_resultInJson);
305 }
306 
307 /**
308  * @brief API to write keyword's value.
309  *
310  * This API writes keyword's value by requesting DBus service(vpd-manager) who
311  * hosts the 'UpdateKeyword' method to update keyword's value.
312  *
313  * @param[in] i_vpdPath - EEPROM or object path, where keyword is present.
314  * @param[in] i_paramsToWriteData - Data required to update keyword's value.
315  *
316  * @return - Number of bytes written on success, -1 on failure.
317  *
318  * @throw - std::runtime_error, sdbusplus::exception::SdBusError
319  */
writeKeyword(const std::string & i_vpdPath,const types::WriteVpdParams & i_paramsToWriteData)320 inline int writeKeyword(const std::string& i_vpdPath,
321                         const types::WriteVpdParams& i_paramsToWriteData)
322 {
323     if (i_vpdPath.empty())
324     {
325         throw std::runtime_error("Empty path");
326     }
327 
328     int l_rc = constants::FAILURE;
329     auto l_bus = sdbusplus::bus::new_default();
330 
331     auto l_method = l_bus.new_method_call(
332         constants::vpdManagerService, constants::vpdManagerObjectPath,
333         constants::vpdManagerInfName, "UpdateKeyword");
334 
335     l_method.append(i_vpdPath, i_paramsToWriteData);
336     auto l_result = l_bus.call(l_method);
337 
338     l_result.read(l_rc);
339     return l_rc;
340 }
341 
342 /**
343  * @brief API to write keyword's value on hardware.
344  *
345  * This API writes keyword's value by requesting DBus service(vpd-manager) who
346  * hosts the 'WriteKeywordOnHardware' method to update keyword's value.
347  *
348  * Note: This API updates keyword's value only on the given hardware path, any
349  * backup or redundant EEPROM (if exists) paths won't get updated.
350  *
351  * @param[in] i_eepromPath - EEPROM where keyword is present.
352  * @param[in] i_paramsToWriteData - Data required to update keyword's value.
353  *
354  * @return - Number of bytes written on success, -1 on failure.
355  *
356  * @throw - std::runtime_error, sdbusplus::exception::SdBusError
357  */
358 inline int
writeKeywordOnHardware(const std::string & i_eepromPath,const types::WriteVpdParams & i_paramsToWriteData)359     writeKeywordOnHardware(const std::string& i_eepromPath,
360                            const types::WriteVpdParams& i_paramsToWriteData)
361 {
362     if (i_eepromPath.empty())
363     {
364         throw std::runtime_error("Empty path");
365     }
366 
367     int l_rc = constants::FAILURE;
368     auto l_bus = sdbusplus::bus::new_default();
369 
370     auto l_method = l_bus.new_method_call(
371         constants::vpdManagerService, constants::vpdManagerObjectPath,
372         constants::vpdManagerInfName, "WriteKeywordOnHardware");
373 
374     l_method.append(i_eepromPath, i_paramsToWriteData);
375     auto l_result = l_bus.call(l_method);
376 
377     l_result.read(l_rc);
378 
379     if (l_rc > 0)
380     {
381         std::cout << "Data updated successfully " << std::endl;
382     }
383     return l_rc;
384 }
385 
386 /**
387  * @brief API to get data in binary format.
388  *
389  * This API converts given string value into array of binary data.
390  *
391  * @param[in] i_value - Input data.
392  *
393  * @return - Array of binary data on success, throws as exception in case
394  * of any error.
395  *
396  * @throw std::runtime_error, std::out_of_range, std::bad_alloc,
397  * std::invalid_argument
398  */
convertToBinary(const std::string & i_value)399 inline types::BinaryVector convertToBinary(const std::string& i_value)
400 {
401     if (i_value.empty())
402     {
403         throw std::runtime_error(
404             "Provide a valid hexadecimal input. (Ex. 0x30313233)");
405     }
406 
407     std::vector<uint8_t> l_binaryValue{};
408 
409     if (i_value.substr(0, 2).compare("0x") == constants::STR_CMP_SUCCESS)
410     {
411         if (i_value.length() % 2 != 0)
412         {
413             throw std::runtime_error(
414                 "Write option accepts 2 digit hex numbers. (Ex. 0x1 "
415                 "should be given as 0x01).");
416         }
417 
418         auto l_value = i_value.substr(2);
419 
420         if (l_value.empty())
421         {
422             throw std::runtime_error(
423                 "Provide a valid hexadecimal input. (Ex. 0x30313233)");
424         }
425 
426         if (l_value.find_first_not_of("0123456789abcdefABCDEF") !=
427             std::string::npos)
428         {
429             throw std::runtime_error("Provide a valid hexadecimal input.");
430         }
431 
432         for (size_t l_pos = 0; l_pos < l_value.length(); l_pos += 2)
433         {
434             uint8_t l_byte = static_cast<uint8_t>(
435                 std::stoi(l_value.substr(l_pos, 2), nullptr, 16));
436             l_binaryValue.push_back(l_byte);
437         }
438     }
439     else
440     {
441         l_binaryValue.assign(i_value.begin(), i_value.end());
442     }
443     return l_binaryValue;
444 }
445 
446 /**
447  * @brief API to parse respective JSON.
448  *
449  * @param[in] i_pathToJson - Path to JSON.
450  *
451  * @return Parsed JSON, throws exception in case of error.
452  *
453  * @throw std::runtime_error
454  */
getParsedJson(const std::string & i_pathToJson)455 inline nlohmann::json getParsedJson(const std::string& i_pathToJson)
456 {
457     if (i_pathToJson.empty())
458     {
459         throw std::runtime_error("Path to JSON is missing");
460     }
461 
462     std::error_code l_ec;
463     if (!std::filesystem::exists(i_pathToJson, l_ec))
464     {
465         std::string l_message{
466             "file system call failed for file: " + i_pathToJson};
467 
468         if (l_ec)
469         {
470             l_message += ", error: " + l_ec.message();
471         }
472         throw std::runtime_error(l_message);
473     }
474 
475     if (std::filesystem::is_empty(i_pathToJson, l_ec))
476     {
477         throw std::runtime_error("Empty file: " + i_pathToJson);
478     }
479     else if (l_ec)
480     {
481         throw std::runtime_error("is_empty file system call failed for file: " +
482                                  i_pathToJson + ", error: " + l_ec.message());
483     }
484 
485     std::ifstream l_jsonFile(i_pathToJson);
486     if (!l_jsonFile)
487     {
488         throw std::runtime_error("Failed to access Json path: " + i_pathToJson);
489     }
490 
491     try
492     {
493         return nlohmann::json::parse(l_jsonFile);
494     }
495     catch (const nlohmann::json::parse_error& l_ex)
496     {
497         throw std::runtime_error("Failed to parse JSON file: " + i_pathToJson);
498     }
499 }
500 
501 /**
502  * @brief API to get list of interfaces under a given object path.
503  *
504  * Given a DBus object path, this API returns a map of service -> implemented
505  * interface(s) under that object path. This API calls DBus method GetObject
506  * hosted by ObjectMapper DBus service.
507  *
508  * @param[in] i_objectPath - DBus object path.
509  * @param[in] i_constrainingInterfaces - An array of result set constraining
510  * interfaces.
511  *
512  * @return On success, returns a map of service -> implemented interface(s),
513  * else returns an empty map. The caller of this
514  * API should check for empty map.
515  */
GetServiceInterfacesForObject(const std::string & i_objectPath,const std::vector<std::string> & i_constrainingInterfaces)516 inline types::MapperGetObject GetServiceInterfacesForObject(
517     const std::string& i_objectPath,
518     const std::vector<std::string>& i_constrainingInterfaces) noexcept
519 {
520     types::MapperGetObject l_serviceInfMap;
521     if (i_objectPath.empty())
522     {
523         // TODO: log only when verbose is enabled
524         std::cerr << "Object path is empty." << std::endl;
525         return l_serviceInfMap;
526     }
527 
528     try
529     {
530         auto l_bus = sdbusplus::bus::new_default();
531         auto l_method = l_bus.new_method_call(
532             constants::objectMapperService, constants::objectMapperObjectPath,
533             constants::objectMapperInfName, "GetObject");
534 
535         l_method.append(i_objectPath, i_constrainingInterfaces);
536 
537         auto l_result = l_bus.call(l_method);
538         l_result.read(l_serviceInfMap);
539     }
540     catch (const sdbusplus::exception::SdBusError& l_ex)
541     {
542         // TODO: log only when verbose is enabled
543         // std::cerr << std::string(l_ex.what()) << std::endl;
544     }
545     return l_serviceInfMap;
546 }
547 
548 /** @brief API to get list of sub tree paths for a given object path
549  *
550  * Given a DBus object path, this API returns a list of object paths under that
551  * object path in the DBus tree. This API calls DBus method GetSubTreePaths
552  * hosted by ObjectMapper DBus service.
553  *
554  * @param[in] i_objectPath - DBus object path.
555  * @param[in] i_constrainingInterfaces - An array of result set constraining
556  * interfaces.
557  * @param[in] i_depth - The maximum subtree depth for which results should be
558  * fetched. For unconstrained fetches use a depth of zero.
559  *
560  * @return On success, returns a std::vector<std::string> of object paths in
561  * Phosphor Inventory Manager DBus service's tree, else returns an empty vector.
562  * The caller of this API should check for empty vector.
563  */
GetSubTreePaths(const std::string i_objectPath,const int i_depth=0,const std::vector<std::string> & i_constrainingInterfaces={})564 inline std::vector<std::string> GetSubTreePaths(
565     const std::string i_objectPath, const int i_depth = 0,
566     const std::vector<std::string>& i_constrainingInterfaces = {}) noexcept
567 {
568     std::vector<std::string> l_objectPaths;
569 
570     try
571     {
572         auto l_bus = sdbusplus::bus::new_default();
573         auto l_method = l_bus.new_method_call(
574             constants::objectMapperService, constants::objectMapperObjectPath,
575             constants::objectMapperInfName, "GetSubTreePaths");
576 
577         l_method.append(i_objectPath, i_depth, i_constrainingInterfaces);
578 
579         auto l_result = l_bus.call(l_method);
580         l_result.read(l_objectPaths);
581     }
582     catch (const sdbusplus::exception::SdBusError& l_ex)
583     {
584         // TODO: log only when verbose is enabled
585         std::cerr << std::string(l_ex.what()) << std::endl;
586     }
587     return l_objectPaths;
588 }
589 
590 /**
591  * @brief A class to print data in tabular format
592  *
593  * This class implements methods to print data in a two dimensional tabular
594  * format. All entries in the table must be in string format.
595  *
596  */
597 class Table
598 {
599     class Column : public types::TableColumnNameSizePair
600     {
601       public:
602         /**
603          * @brief API to get the name of the Column
604          *
605          * @return Name of the Column.
606          */
Name() const607         const std::string& Name() const
608         {
609             return this->first;
610         }
611 
612         /**
613          * @brief API to get the width of the Column
614          *
615          * @return Width of the Column.
616          */
Width() const617         std::size_t Width() const
618         {
619             return this->second;
620         }
621     };
622 
623     // Current width of the table
624     std::size_t m_currentWidth;
625 
626     // Character to be used as fill character between entries
627     char m_fillCharacter;
628 
629     // Separator character to be used between columns
630     char m_separator;
631 
632     // Array of columns
633     std::vector<Column> m_columns;
634 
635     /**
636      * @brief API to Print Header
637      *
638      * Header line prints the names of the Column headers separated by the
639      * specified separator character and spaced accordingly.
640      *
641      * @throw std::out_of_range, std::length_error, std::bad_alloc
642      */
PrintHeader() const643     void PrintHeader() const
644     {
645         for (const auto& l_column : m_columns)
646         {
647             PrintEntry(l_column.Name(), l_column.Width());
648         }
649         std::cout << m_separator << std::endl;
650     }
651 
652     /**
653      * @brief API to Print Horizontal Line
654      *
655      * A horizontal line is a sequence of '*'s.
656      *
657      * @throw std::out_of_range, std::length_error, std::bad_alloc
658      */
PrintHorizontalLine() const659     void PrintHorizontalLine() const
660     {
661         std::cout << std::string(m_currentWidth, '*') << std::endl;
662     }
663 
664     /**
665      * @brief API to print an entry in the table
666      *
667      * An entry is a separator character followed by the text to print.
668      * The text is centre-aligned.
669      *
670      * @param[in] i_text - text to print
671      * @param[in] i_columnWidth - width of the column
672      *
673      * @throw std::out_of_range, std::length_error, std::bad_alloc
674      */
PrintEntry(const std::string & i_text,std::size_t i_columnWidth) const675     void PrintEntry(const std::string& i_text, std::size_t i_columnWidth) const
676     {
677         const std::size_t l_textLength{i_text.length()};
678 
679         constexpr std::size_t l_minFillChars{3};
680         const std::size_t l_numFillChars =
681             ((l_textLength >= i_columnWidth ? l_minFillChars
682                                             : i_columnWidth - l_textLength)) -
683             1; // -1 for the separator character
684 
685         const unsigned l_oddFill = l_numFillChars % 2;
686 
687         std::cout << m_separator
688                   << std::string((l_numFillChars / 2) + l_oddFill,
689                                  m_fillCharacter)
690                   << i_text << std::string(l_numFillChars / 2, m_fillCharacter);
691     }
692 
693   public:
694     /**
695      * @brief Table Constructor
696      *
697      * Parameterized constructor for a Table object
698      *
699      */
Table(const char i_fillCharacter=' ',const char i_separator='|')700     constexpr explicit Table(const char i_fillCharacter = ' ',
701                              const char i_separator = '|') noexcept :
702         m_currentWidth{0}, m_fillCharacter{i_fillCharacter},
703         m_separator{i_separator}
704     {}
705 
706     // deleted methods
707     Table(const Table&) = delete;
708     Table operator=(const Table&) = delete;
709     Table(const Table&&) = delete;
710     Table operator=(const Table&&) = delete;
711 
712     ~Table() = default;
713 
714     /**
715      * @brief API to add column to Table
716      *
717      * @param[in] i_name - Name of the column.
718      *
719      * @param[in] i_width - Width to allocate for the column.
720      *
721      * @return On success returns 0, otherwise returns -1.
722      */
AddColumn(const std::string & i_name,std::size_t i_width)723     int AddColumn(const std::string& i_name, std::size_t i_width)
724     {
725         if (i_width < i_name.length())
726             return constants::FAILURE;
727         m_columns.emplace_back(types::TableColumnNameSizePair(i_name, i_width));
728         m_currentWidth += i_width;
729         return constants::SUCCESS;
730     }
731 
732     /**
733      * @brief API to print the Table to console.
734      *
735      * This API prints the table data to console.
736      *
737      * @param[in] i_tableData - The data to be printed.
738      *
739      * @return On success returns 0, otherwise returns -1.
740      *
741      * @throw std::out_of_range, std::length_error, std::bad_alloc
742      */
Print(const types::TableInputData & i_tableData) const743     int Print(const types::TableInputData& i_tableData) const
744     {
745         PrintHorizontalLine();
746         PrintHeader();
747         PrintHorizontalLine();
748 
749         // print the table data
750         for (const auto& l_row : i_tableData)
751         {
752             unsigned l_columnNumber{0};
753 
754             // number of columns in input data is greater than the number of
755             // columns specified in Table
756             if (l_row.size() > m_columns.size())
757             {
758                 return constants::FAILURE;
759             }
760 
761             for (const auto& l_entry : l_row)
762             {
763                 PrintEntry(l_entry, m_columns[l_columnNumber].Width());
764 
765                 ++l_columnNumber;
766             }
767             std::cout << m_separator << std::endl;
768         }
769         PrintHorizontalLine();
770         return constants::SUCCESS;
771     }
772 };
773 
774 } // namespace utils
775 } // namespace vpd
776