File: F3DConfigFileTools.cxx

package info (click to toggle)
f3d 3.1.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 23,504 kB
  • sloc: cpp: 99,106; python: 758; sh: 342; xml: 223; java: 101; javascript: 95; makefile: 25
file content (318 lines) | stat: -rw-r--r-- 9,352 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
#include "F3DConfigFileTools.h"

#include "F3DSystemTools.h"

#include "nlohmann/json.hpp"

#include "log.h"
#include "utils.h"

#include <filesystem>
#include <fstream>
#include <set>
#include <vector>

namespace fs = std::filesystem;

namespace
{
//----------------------------------------------------------------------------
/**
 * Recover a OS-specific vector of potential config file directories
 */
std::vector<fs::path> GetConfigPaths(const std::string& configSearch)
{
  std::vector<fs::path> paths;

  fs::path configPath;
  std::vector<fs::path> dirsToCheck = {

#ifdef __APPLE__
    "/usr/local/etc/f3d",
#endif
#if defined(__linux__) || defined(__FreeBSD__)
    "/etc/f3d",
    "/usr/share/f3d/configs",
#endif
    F3DSystemTools::GetBinaryResourceDirectory() / "configs",
    F3DSystemTools::GetUserConfigFileDirectory(),
  };

  for (const fs::path& dir : dirsToCheck)
  {
    try
    {
      if (dir.empty())
      {
        continue;
      }

      std::vector<std::string> configNames;
      if (fs::path(configSearch).stem() == configSearch)
      {
        // If the config search is a stem, add extensions
        configNames.emplace_back(configSearch + ".json");
        configNames.emplace_back(configSearch + ".d");
      }
      else
      {
        // If not, use directly
        configNames.emplace_back(configSearch);
      }

      for (const auto& configName : configNames)
      {
        configPath = dir / (configName);
        if (fs::exists(configPath))
        {
          f3d::log::debug("Config file found: ", configPath.string());
          paths.emplace_back(configPath);
        }
        else
        {
          f3d::log::debug("Candidate config file not found: ", configPath.string());
        }
      }
    }
    catch (const fs::filesystem_error&)
    {
      f3d::log::error("Error recovering configuration file path: ", configPath.string());
    }
  }

  return paths;
}
}

//----------------------------------------------------------------------------
F3DConfigFileTools::ParsedConfigFiles F3DConfigFileTools::ReadConfigFiles(
  const std::string& userConfig)
{
  // Default config directory name
  std::string configSearch = "config";
  if (!userConfig.empty())
  {
    // Check if provided userConfig is a full path
    auto path = fs::path(userConfig);
    if (path.stem() == userConfig || path.filename() == userConfig)
    {
      // Only a stem or a filename, use provided userConfig as configSearch
      configSearch = userConfig;
    }
    else
    {
      // Assume its a full path and use as is, not searching for config files
      configSearch = "";
    }
  }

  // Recover config paths to search for config files
  std::vector<fs::path> configPaths;
  if (!configSearch.empty())
  {
    for (const auto& path : ::GetConfigPaths(configSearch))
    {
      configPaths.emplace_back(path);
    }
  }
  else
  {
    // Collapse full path into an absolute path
    configPaths.emplace_back(f3d::utils::collapsePath(userConfig));
  }

  // Recover actual individual config file paths
  std::set<fs::path> actualConfigFilePaths;
  for (auto configPath : configPaths)
  {
    // Recover an absolute canonical path to config file
    try
    {
      configPath = fs::canonical(fs::path(configPath)).string();
    }
    catch (const fs::filesystem_error&)
    {
      f3d::log::error("Configuration file does not exist: ", configPath.string(), " , ignoring it");
      continue;
    }

    // Recover all config files if needed in directories
    if (fs::is_directory(configPath))
    {
      f3d::log::debug("Using config directory ", configPath.string());
      for (auto& entry : fs::directory_iterator(configPath))
      {
        actualConfigFilePaths.emplace(entry);
      }
    }
    else
    {
      f3d::log::debug("Using config file ", configPath.string());
      actualConfigFilePaths.emplace(configPath);
    }
  }

  // If we used a configSearch but did not find any, inform the user
  if (!configSearch.empty() && actualConfigFilePaths.empty())
  {
    f3d::log::info("Configuration file for \"", configSearch, "\" could not be found");
  }

  // Read config files
  F3DOptionsTools::OptionsEntries optionsEntries;
  F3DOptionsTools::OptionsEntries imperativeOptionsEntries;
  F3DConfigFileTools::BindingsEntries bindingsEntries;
  for (const auto& configFilePath : actualConfigFilePaths)
  {
    std::ifstream file(configFilePath);
    if (!file.is_open())
    {
      // Cannot be tested
      f3d::log::warn(
        "Unable to open the configuration file: ", configFilePath.string(), " , ignoring it");
      continue;
    }

    // Read the file into a json
    nlohmann::ordered_json json;
    try
    {
      file >> json;
    }
    catch (const nlohmann::json::parse_error& ex)
    {
      f3d::log::error(
        "Unable to parse the configuration file ", configFilePath.string(), " , ignoring it");
      f3d::log::error(ex.what());
      continue;
    }

    try
    {
      // For each config block in the main array
      for (const auto& configBlock : json)
      {
        // Recover match if any
        std::string match;
        try
        {
          match = configBlock.at("match");
        }
        catch (nlohmann::json::out_of_range&)
        {
          // No match defined, use a catch all regex
          match = ".*";
        }

        // Recover options if any
        nlohmann::ordered_json optionsBlock;
        try
        {
          optionsBlock = configBlock.at("options");
        }
        catch (nlohmann::json::out_of_range&)
        {
        }

        if (!optionsBlock.empty())
        {
          // Add each options config entry into an option dict
          F3DOptionsTools::OptionsDict entry;
          F3DOptionsTools::OptionsDict imperativeEntry;
          for (const auto& item : optionsBlock.items())
          {
            // Individual item can be imperative, store in the right dict
            std::string key = item.key();
            std::reference_wrapper<F3DOptionsTools::OptionsDict> localEntry = std::ref(entry);
            if (!key.empty() && key[0] == '!')
            {
              localEntry = std::ref(imperativeEntry);
              key = key.substr(1);
            }

            if (item.value().is_number() || item.value().is_boolean())
            {
              localEntry.get()[key] = nlohmann::to_string(item.value());
            }
            else if (item.value().is_string())
            {
              localEntry.get()[key] = item.value().get<std::string>();
            }
            else
            {
              f3d::log::error(key, " from ", configFilePath.string(),
                " must be a string, a boolean or a number, ignoring entry");
              continue;
            }
          }

          // Emplace the option dicts for that pattern match into the config entries vector
          if (!entry.empty())
          {
            optionsEntries.emplace_back(entry, configFilePath.string(), match);
          }
          if (!imperativeEntry.empty())
          {
            // The path is only used for logging purpose, store the imperative information inside
            imperativeOptionsEntries.emplace_back(
              imperativeEntry, configFilePath.string() + " (imperative)", match);
          }
        }

        // Recover bindings if any
        nlohmann::ordered_json bindingsBlock;
        try
        {
          bindingsBlock = configBlock.at("bindings");
        }
        catch (nlohmann::json::out_of_range&)
        {
        }

        if (!bindingsBlock.empty())
        {
          // Add each binding config entry
          F3DConfigFileTools::BindingsVector bindingEntry;
          for (const auto& item : bindingsBlock.items())
          {
            if (item.value().is_string())
            {
              bindingEntry.emplace_back(std::make_pair(
                item.key(), std::vector<std::string>{ item.value().get<std::string>() }));
            }
            else if (item.value().is_array())
            {
              // Do not check before we look for simplicity sake
              bindingEntry.emplace_back(
                std::make_pair(item.key(), item.value().get<std::vector<std::string>>()));
            }
            else
            {
              f3d::log::error(item.key(), " from ", configFilePath.string(),
                " must be a string or an array of string, ignoring binding entry");
              continue;
            }
          }

          // Emplace the config dict for that pattern match into the binding entries vector
          bindingsEntries.emplace_back(bindingEntry, configFilePath.string(), match);
        }

        if (optionsBlock.empty() && bindingsBlock.empty())
        {
          // To help users figure out issues with configuration files
          f3d::log::warn("A config block in config file: ", configFilePath.string(),
            " does not contains options nor bindings, ignoring block");
        }
      }
    }
    catch (const nlohmann::json::type_error& ex)
    {
      f3d::log::warn("Error processing config file: ", configFilePath.string(),
        ", configuration may be incorrect");
      f3d::log::error(ex.what());
    }
  }
  return F3DConfigFileTools::ParsedConfigFiles{ std::move(optionsEntries),
    std::move(imperativeOptionsEntries), std::move(bindingsEntries) };
}