blob: bd6893aa867f6ea1ce65449a691ffb17e08ab394 [file] [log] [blame]
awlane879afac2025-04-28 17:59:36 -05001/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2/*
3 * Copyright (c) 2014-2025, The University of Memphis,
4 * Regents of the University of California,
5 * Arizona Board of Regents.
6 *
7 * This file is part of NLSR (Named-data Link State Routing).
8 * See AUTHORS.md for complete list of NLSR authors and contributors.
9 *
10 * NLSR is free software: you can redistribute it and/or modify it under the terms
11 * of the GNU General Public License as published by the Free Software Foundation,
12 * either version 3 of the License, or (at your option) any later version.
13 *
14 * NLSR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
15 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
16 * PURPOSE. See the GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along with
19 * NLSR, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
20 */
21
22#include "boost-info-editor.hpp"
23#include "logger.hpp"
24
25#include <boost/property_tree/info_parser.hpp>
26
27namespace nlsr::util::boost_info_editor {
28
29// Incorporates Apache 2.0 licensed code by Yanbiao Li under a compatible license
30boost::property_tree::ptree
31load(const std::string& fileName)
32{
33 boost::property_tree::ptree info;
34 std::ifstream input(fileName);
35
36 // Thrown errors are received at calling function
37 boost::property_tree::info_parser::read_info(input, info);
38
39 input.close();
40 return info;
41}
42
43bool
44save(const std::string& fileName, boost::property_tree::ptree& info)
45{
46 std::ofstream output(fileName);
47 try {
48 write_info(output, info);
49 } catch (const boost::property_tree::info_parser::info_parser_error& error) {
50 return false;
51 }
52 output.close();
53 return true;
54}
55
56bool
57put(const std::string& fileName, const std::string& section, const std::string& value)
58{
59 boost::property_tree::ptree info;
60 try {
61 info = load(fileName);
62 }
63 catch (const boost::property_tree::info_parser::info_parser_error& error) {
64 return false;
65 }
66 info.put(section.c_str(), value.c_str());
67 return save(fileName, info);
68}
69
70bool
71remove(const std::string& fileName, const std::string& section)
72{
73 boost::property_tree::ptree info;
74 try {
75 info = load(fileName);
76 }
77 catch (const boost::property_tree::info_parser::info_parser_error& error) {
78 return false;
79 }
80 std::size_t pos = section.find_last_of(".");
81 if (pos == std::string::npos) {
82 info.erase(section.c_str());
83 }
84 else {
85 boost::optional<boost::property_tree::ptree&> child =
86 info.get_child_optional(section.substr(0, pos));
87 if (child) {
88 child->erase(section.substr(pos + 1));
89 }
90 }
91 return save(fileName, info);
92}
93} // namespace nlsr::util::boost_info_editor