Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Generate config descriptions #1842

Merged
15 changes: 8 additions & 7 deletions src/app/CliArgs.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
#include <boost/program_options/variables_map.hpp>

#include <cstdlib>
#include <filesystem>
#include <iostream>
#include <string>
#include <utility>
Expand All @@ -43,13 +44,13 @@ CliArgs::parse(int argc, char const* argv[])
// clang-format off
po::options_description description("Options");
description.add_options()
("help,h", "print help message and exit")
("version,v", "print version and exit")
("conf,c", po::value<std::string>()->default_value(kDEFAULT_CONFIG_PATH), "configuration file")
("help,h", "Print help message and exit")
("version,v", "Print version and exit")
("conf,c", po::value<std::string>()->default_value(kDEFAULT_CONFIG_PATH), "Configuration file")
("ng-web-server,w", "Use ng-web-server")
("migrate", po::value<std::string>(), "start migration helper")
("migrate", po::value<std::string>(), "Start migration helper")
("verify", "Checks the validity of config values")
("config-description,d", po::value<std::string>(),"generate config description")
("config-description,d", po::value<std::string>(), "Generate config description markdown file")
;
// clang-format on
po::positional_options_description positional;
Expand All @@ -70,9 +71,9 @@ CliArgs::parse(int argc, char const* argv[])
}

if (parsed.count("config-description") != 0u) {
auto const& filePath = parsed["config-description"].as<std::string>();
std::filesystem::path filePath = parsed["config-description"].as<std::string>();

auto const res = util::config::ClioConfigDescription::getMarkdown(filePath);
auto const res = util::config::ClioConfigDescription::generateConfigDescriptionToFile(filePath);
if (res.has_value())
return Action{Action::Exit{EXIT_SUCCESS}};

Expand Down
1 change: 1 addition & 0 deletions src/util/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ target_sources(
newconfig/ConfigDefinition.cpp
newconfig/ConfigFileJson.cpp
newconfig/ObjectView.cpp
newconfig/Types.cpp
newconfig/ValueView.cpp
)

Expand Down
28 changes: 14 additions & 14 deletions src/util/newconfig/Array.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -99,23 +99,23 @@ class Array {
[[nodiscard]] std::vector<ConfigValue>::const_iterator
end() const;

/**
* @brief Custom output stream for Array
*
* @param stream The output stream
* @param arr The Array
* @return The same ostream we were given
*/
friend std::ostream&
operator<<(std::ostream& stream, Array arr)
{
stream << arr.getArrayPattern();
return stream;
}

private:
ConfigValue itemPattern_;
std::vector<ConfigValue> elements_;
};

/**
* @brief Custom output stream for Array
*
* @param stream The output stream
* @param arr The Array
* @return The same ostream we were given
*/
inline std::ostream&
operator<<(std::ostream& stream, Array arr)
{
stream << arr.getArrayPattern();
return stream;
}

} // namespace util::config
10 changes: 5 additions & 5 deletions src/util/newconfig/ConfigConstraints.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ class PortConstraint final : public Constraint {
void
print(std::ostream& stream) const override
{
stream << fmt::format("The minimum value is `{}`. The maximum value is `{}`", kPORT_MIN, kPORT_MAX) << '\n';
stream << fmt::format("The minimum value is `{}`. The maximum value is `{}", kPORT_MIN, kPORT_MAX);
}

static constexpr uint32_t kPORT_MIN = 1;
Expand Down Expand Up @@ -249,7 +249,7 @@ class ValidIPConstraint final : public Constraint {
void
print(std::ostream& stream) const override
{
stream << fmt::format("The value must be a valid IP address") << '\n';
stream << "The value must be a valid IP address";
}
};

Expand Down Expand Up @@ -313,7 +313,7 @@ class OneOf final : public Constraint {
void
print(std::ostream& stream) const override
{
stream << fmt::format("The value must be one of the following: `{}`", fmt::join(arr_, ", ")) << '\n';
stream << fmt::format("The value must be one of the following: `{}`", fmt::join(arr_, ", "));
}

std::string_view key_;
Expand Down Expand Up @@ -376,7 +376,7 @@ class NumberValueConstraint final : public Constraint {
void
print(std::ostream& stream) const override
{
stream << fmt::format("The minimum value is `{}`. The maximum value is `{}`", min_, max_) << '\n';
stream << fmt::format("The minimum value is `{}`. The maximum value is `{}`", min_, max_);
}

NumType min_;
Expand Down Expand Up @@ -417,7 +417,7 @@ class PositiveDouble final : public Constraint {
void
print(std::ostream& stream) const override
{
stream << fmt::format("The value must be a positive float number") << '\n';
stream << fmt::format("The value must be a positive double number");
}
};

Expand Down
39 changes: 27 additions & 12 deletions src/util/newconfig/ConfigDescription.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@

#include <algorithm>
#include <array>
#include <cerrno>
#include <cstring>
#include <expected>
#include <filesystem>
#include <fstream>
Expand All @@ -42,9 +44,6 @@
*/
struct ClioConfigDescription {
public:
/** @brief Name of the Markdown file containing detailed descriptions of all configuration values. */
static constexpr auto kCONFIG_DESCRIPTION_FILE_NAME = "Config-Descriptions.md";

/** @brief Struct to represent a key-value pair*/
struct KV {
std::string_view key;
Expand Down Expand Up @@ -79,22 +78,42 @@
* @return An Error if generating markdown fails, otherwise nothing
*/
[[nodiscard]] static std::expected<void, Error>
getMarkdown(std::string_view path)
generateConfigDescriptionToFile(std::filesystem::path path)
{
namespace fs = std::filesystem;

// Construct the full file path
auto const fullFilePath = fmt::format("{}/{}", path, kCONFIG_DESCRIPTION_FILE_NAME);
fs::path const fullFilePath = path.string();
PeterChen13579 marked this conversation as resolved.
Show resolved Hide resolved

// Validate the directory exists
auto const dir = fs::path(fullFilePath).parent_path();
PeterChen13579 marked this conversation as resolved.
Show resolved Hide resolved
if (!dir.empty() && !fs::exists(dir))
return std::unexpected<Error>{fmt::format("Error: File path {} does not exist", fullFilePath)};
return std::unexpected<Error>{

Check warning on line 91 in src/util/newconfig/ConfigDescription.hpp

View check run for this annotation

Codecov / codecov/patch

src/util/newconfig/ConfigDescription.hpp#L91

Added line #L91 was not covered by tests
fmt::format("Error: Directory {} does not exist or provided path is invalid", dir.string())
PeterChen13579 marked this conversation as resolved.
Show resolved Hide resolved
};

Check warning on line 93 in src/util/newconfig/ConfigDescription.hpp

View check run for this annotation

Codecov / codecov/patch

src/util/newconfig/ConfigDescription.hpp#L93

Added line #L93 was not covered by tests

std::ofstream file(fullFilePath);
if (!file.is_open())
return std::unexpected<Error>{fmt::format("failed to create file: {}", kCONFIG_DESCRIPTION_FILE_NAME)};
if (!file.is_open()) {
return std::unexpected{
fmt::format("Failed to create file '{}': {}", fullFilePath.string(), std::strerror(errno))
};
}

writeConfigDescriptionToFile(file);
file.close();

std::cout << "Markdown file generated successfully: " << fullFilePath << "\n";
return {};
}

/**
* @brief Writes to Config description to file
*
* @param file The config file to write to
*/
static void
writeConfigDescriptionToFile(std::ostream& file)
{
file << "# Clio Config Description\n";
file << "This file lists all Clio Configuration definitions in detail.\n\n";
file << "## Configuration Details\n\n";
Expand All @@ -112,10 +131,6 @@
file << " - **Description**: " << val << "\n";
}
file << "\n";

file.close();
std::cout << "Markdown file generated successfully: " << fullFilePath << "\n";
return {};
}

private:
Expand Down
8 changes: 4 additions & 4 deletions src/util/newconfig/ConfigValue.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -212,10 +212,10 @@ class ConfigValue {
friend std::ostream&
operator<<(std::ostream& stream, ConfigValue val)
{
stream << " - **Required**: " << (val.isOptional() ? "False" : "True") << "\n";
stream << " - **Type**: : " << val.type() << "\n";
stream << " - **Default value**: " << (val.hasValue() ? *val.value_ : "None") << "\n";
stream << " - **Constraints**: ";
stream << "- **Required**: " << (val.isOptional() ? "False" : "True") << "\n";
stream << "- **Type**: " << val.type() << "\n";
stream << "- **Default value**: " << (val.hasValue() ? *val.value_ : "None") << "\n";
stream << "- **Constraints**: ";

if (val.getConstraint().has_value()) {
stream << val.getConstraint()->get() << "\n";
Expand Down
66 changes: 66 additions & 0 deletions src/util/newconfig/Types.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
//------------------------------------------------------------------------------
/*
This file is part of clio: https://github.com/XRPLF/clio
Copyright (c) 2025, the clio developers.

Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================

#include "util/newconfig/Types.hpp"

#include <cstdint>
#include <ostream>
#include <string>
#include <variant>

namespace util::config {

std::ostream&
operator<<(std::ostream& stream, ConfigType type)
{
switch (type) {
case ConfigType::Integer:
stream << "int";
break;
case ConfigType::String:
stream << "string";
break;
case ConfigType::Double:
stream << "double";
break;
case ConfigType::Boolean:
stream << "boolean";
break;
default:
stream << "unsupported type";

Check warning on line 46 in src/util/newconfig/Types.cpp

View check run for this annotation

Codecov / codecov/patch

src/util/newconfig/Types.cpp#L45-L46

Added lines #L45 - L46 were not covered by tests
}
return stream;
}

std::ostream&
operator<<(std::ostream& stream, Value value)
{
if (std::holds_alternative<std::string>(value)) {
stream << std::get<std::string>(value);
} else if (std::holds_alternative<bool>(value)) {
stream << (std::get<bool>(value) ? "False" : "True");
} else if (std::holds_alternative<double>(value)) {
stream << std::get<double>(value);
} else if (std::holds_alternative<int64_t>(value)) {
stream << std::get<int64_t>(value);
}
return stream;
}

} // namespace util::config
39 changes: 4 additions & 35 deletions src/util/newconfig/Types.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -39,27 +39,8 @@ enum class ConfigType { Integer, String, Double, Boolean };
* @param type The config type
* @return The same ostream we were given
*/
inline std::ostream&
operator<<(std::ostream& stream, ConfigType type)
{
switch (type) {
case ConfigType::Integer:
stream << "int";
break;
case ConfigType::String:
stream << "string";
break;
case ConfigType::Double:
stream << "double";
break;
case ConfigType::Boolean:
stream << "boolean";
break;
default:
stream << "unsupported type";
}
return stream;
}
std::ostream&
operator<<(std::ostream& stream, ConfigType type);

/** @brief Represents the supported Config Values */
using Value = std::variant<int64_t, std::string, bool, double>;
Expand All @@ -71,20 +52,8 @@ using Value = std::variant<int64_t, std::string, bool, double>;
* @param value The value type
* @return The same ostream we were given
*/
inline std::ostream&
operator<<(std::ostream& stream, Value value)
{
if (std::holds_alternative<std::string>(value)) {
stream << std::get<std::string>(value) << "\n";
} else if (std::holds_alternative<bool>(value)) {
stream << (std::get<bool>(value) ? "False" : "True") << "\n";
} else if (std::holds_alternative<double>(value)) {
stream << std::get<double>(value) << "\n";
} else if (std::holds_alternative<int64_t>(value)) {
stream << std::get<int64_t>(value) << "\n";
}
return stream;
}
std::ostream&
operator<<(std::ostream& stream, Value value);

/**
* @brief Get the corresponding clio config type
Expand Down
6 changes: 6 additions & 0 deletions tests/common/util/TmpFile.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@ struct TmpFile {
ofs << content;
}

static TmpFile
empty()
{
return TmpFile{""};
}

TmpFile(TmpFile const&) = delete;
TmpFile(TmpFile&& other) : path{std::move(other.path)}
{
Expand Down
Loading
Loading