Main program class that manages modules, plugins, and command-line parsing.
More...
#include <CLI/MaCh3Program.hpp>
|
| void | parse_args (int argc, const char *const argv[]) |
| | Parse args after inserting any default subcommands. More...
|
| |
| virtual | ~MaCh3Program ()=default |
| | Destructor that unloads all dynamic plugins Fix plugin lifetime: shutdown-only unloading keeps borrowed parser references valid during use. More...
|
| |
| void | add_core_module (IModule &module) |
| | Add a core module to the program. More...
|
| |
| void | load_dynamic_plugins () |
| | Load dynamic plugins from the MACH3_PLUGINS environment variable. More...
|
| |
| int | install_completions () const |
| | Install shell completion scripts for bash and zsh. More...
|
| |
| void | completions (const std::string &prefix, const std::vector< std::string > &context) const |
| | Generate subcommand or long-option suggestions at the active parser depth. More...
|
| |
| int | Run () |
| | Run the selected subcommand. More...
|
| |
| virtual | ~MaCh3ArgumentParser ()=default |
| |
| const std::string | name () const |
| | Get the name of this parser/subcommand. More...
|
| |
| const std::string & | description () const |
| | Get the description of this parser/subcommand. More...
|
| |
| const std::list< std::reference_wrapper< ArgumentParser > > & | subparsers () const |
| | Get the list of registered subparsers. More...
|
| |
| const MaCh3ArgumentParser & | get_subcommand_used () const |
| | Get the subcommand that was used in parsing. More...
|
| |
| std::vector< std::string > | get_long_option_names () const |
| | Return all long option names (–xxx) registered with this parser. More...
|
| |
| bool | option_takes_value (const std::string &name) const |
| | Return true if the named option expects a value (not a flag) More...
|
| |
| std::vector< std::string > | get_completions (const std::string &prefix, const std::vector< std::string > &context) const |
| | Complete subcommands or long options at any depth without parsing incomplete arguments. More...
|
| |
| void | set_default_subcommand (const std::string &name) |
| | Set a subcommand to use when none of the registered subcommands is given. More...
|
| |
| void | insert_default_subcommands (std::vector< std::string > &args, std::size_t pos=0) const |
| | Insert default subcommands into args where no explicit subcommand was given. More...
|
| |
|
| void | validate_parser (const MaCh3ArgumentParser *parser) const |
| |
| std::string | detect_shell () const |
| | Detect the user's shell from the SHELL environment variable. More...
|
| |
| bool | write_file (const fs::path &path, std::string_view content) const |
| | Write content to a file, creating parent directories if needed. More...
|
| |
| std::vector< std::string > | expand_plugin_path (const std::string &path) const |
| | Expand a plugin path (file or directory) into a list of canonical shared-library paths. More...
|
| |
Main program class that manages modules, plugins, and command-line parsing.
This class extends MaCh3ArgumentParser to provide functionality for:
- Managing core modules and dynamic plugins
- Installing and generating shell completions
- Running selected subcommands
- Author
- Alexander Richards
Definition at line 26 of file MaCh3Program.hpp.
◆ ~MaCh3Program()
| virtual M3::MaCh3Program::~MaCh3Program |
( |
| ) |
|
|
virtualdefault |
Destructor that unloads all dynamic plugins Fix plugin lifetime: shutdown-only unloading keeps borrowed parser references valid during use.
◆ add_core_module()
| void M3::MaCh3Program::add_core_module |
( |
IModule & |
module | ) |
|
Add a core module to the program.
- Parameters
-
| module | Reference to the module to be added |
Definition at line 155 of file MaCh3Program.cpp.
158 [&module](
const auto& entry) { return entry.second == &module; })) {
159 throw std::invalid_argument(
"Core module is already registered");
161 MaCh3ArgumentParser* parser = module.get_parser();
163 this->add_subparser(*parser);
std::map< const MaCh3ArgumentParser *, IModule * > m_module_map
Map of parsers to core modules (non-owning)
void validate_parser(const MaCh3ArgumentParser *parser) const
◆ completions()
| void M3::MaCh3Program::completions |
( |
const std::string & |
prefix, |
|
|
const std::vector< std::string > & |
context |
|
) |
| const |
Generate subcommand or long-option suggestions at the active parser depth.
- Parameters
-
| prefix | The partially-typed word being completed |
| context | Words already typed after the program name but before prefix |
Definition at line 134 of file MaCh3Program.cpp.
136 std::cout <<
name <<
"\n";
const std::string name() const
Get the name of this parser/subcommand.
std::vector< std::string > get_completions(const std::string &prefix, const std::vector< std::string > &context) const
Complete subcommands or long options at any depth without parsing incomplete arguments.
◆ detect_shell()
| std::string M3::MaCh3Program::detect_shell |
( |
| ) |
const |
|
private |
Detect the user's shell from the SHELL environment variable.
- Returns
- Shell name ("bash", "zsh", or empty string if not detected)
Definition at line 76 of file MaCh3Program.cpp.
77 const char* shell = std::getenv(
"SHELL");
78 if (!shell)
return "";
81 const auto name = fs::path(shell).filename().string();
◆ expand_plugin_path()
| std::vector< std::string > M3::MaCh3Program::expand_plugin_path |
( |
const std::string & |
path | ) |
const |
|
private |
Expand a plugin path (file or directory) into a list of canonical shared-library paths.
Expand a plugin path to a list of shared library files.
- Parameters
-
| path | Path to a plugin file or directory containing plugins |
- Returns
- Vector of plugin file paths
If the path is a file, returns it directly. If it's a directory, returns supported shared libraries found in that directory.
- Parameters
-
| path | Path to a plugin file or directory |
- Returns
- Vector of absolute paths to .so files
Definition at line 242 of file MaCh3Program.cpp.
243 std::vector<std::string> result;
247 if (!fs::exists(p)) {
248 std::cerr <<
"Plugin path does not exist: " << path <<
"\n";
252 if (fs::is_regular_file(p)) {
254 result.push_back(fs::canonical(p).
string());
256 else if (fs::is_directory(p)) {
258 for (
auto& entry : fs::directory_iterator(p)) {
259 const auto extension = entry.path().extension();
260 bool is_good_plugin = extension ==
".so";
262 is_good_plugin = is_good_plugin || extension ==
".dylib";
265 is_good_plugin = is_good_plugin && entry.is_regular_file();
267 catch (
const fs::filesystem_error& err) {
269 std::cerr <<
"Cannot inspect plugin '" << entry.path().string() <<
"': " << err.what() <<
"\n";
272 if (is_good_plugin) {
274 result.push_back(fs::canonical(entry.path()).string());
276 catch (
const fs::filesystem_error& err) {
277 std::cerr <<
"Cannot canonicalize plugin '" << entry.path().string() <<
"': " << err.what() <<
"\n";
284 std::cerr <<
"Invalid plugin path (not file or directory): " << path <<
"\n";
288 std::sort(result.begin(), result.end());
◆ install_completions()
| int M3::MaCh3Program::install_completions |
( |
| ) |
const |
Install shell completion scripts for bash and zsh.
Definition at line 88 of file MaCh3Program.cpp.
89 const char* home = std::getenv(
"HOME");
90 if (!home || home[0] ==
'\0') {
91 std::cerr <<
"Cannot determine HOME directory\n";
97 std::cerr <<
"Could not detect your shell (check $SHELL is exported). Supported: bash, zsh\n";
103 const std::string binary_path = shell_quote(executable_path());
107 auto embed_path = [&](std::string_view tmpl) -> std::string {
109 const std::string placeholder =
"mach3 --complete";
110 const std::string replacement = binary_path +
" --complete";
111 for (std::size_t pos = s.find(placeholder); pos != std::string::npos;
112 pos = s.find(placeholder, pos + replacement.size()))
113 s.replace(pos, placeholder.size(), replacement);
117 fs::path home_path(home);
119 if (shell ==
"bash") {
120 fs::path path = home_path /
".local/share/bash-completion/completions/mach3";
122 std::cout <<
"Installed bash completions → " << path <<
"\n";
126 if (shell ==
"zsh") {
127 fs::path path = home_path /
".local/share/zsh/site-functions/_mach3";
129 std::cout <<
"Installed zsh completions → " << path <<
"\n";
bool write_file(const fs::path &path, std::string_view content) const
Write content to a file, creating parent directories if needed.
static constexpr std::string_view ZSH_COMPLETION
static constexpr std::string_view BASH_COMPLETION
std::string detect_shell() const
Detect the user's shell from the SHELL environment variable.
◆ load_dynamic_plugins()
| void M3::MaCh3Program::load_dynamic_plugins |
( |
| ) |
|
Load dynamic plugins from the MACH3_PLUGINS environment variable.
Load dynamic plugins from paths specified in MACH3_PLUGINS environment variable.
Reads the MACH3_PLUGINS environment variable (colon-separated paths), loads each .so file, and registers the plugins with the program. Each plugin must export create_plugin and destroy_plugin functions.
Definition at line 172 of file MaCh3Program.cpp.
173 const char* env = std::getenv(
"MACH3_PLUGINS");
174 if (!env || env[0] ==
'\0')
return;
176 std::stringstream ss(env);
179 while (std::getline(ss, path,
':')) {
181 std::cerr <<
"Ignoring empty plugin path in MACH3_PLUGINS\n";
184 std::vector<std::string> files;
189 catch (
const fs::filesystem_error& err) {
190 std::cerr <<
"Cannot discover plugins in '" << path <<
"': " << err.what() <<
"\n";
193 for (
const auto& sofile : files) {
196 std::cerr <<
"Skipping duplicate plugin library: " << sofile <<
"\n";
200 std::unique_ptr<DynamicPlugin> dlplugin = std::make_unique<DynamicPlugin>(sofile);
201 MaCh3ArgumentParser* parser = dlplugin->get_parser();
203 this->add_subparser(*parser);
206 catch (
const std::exception& e) {
207 std::cerr <<
"Failed to load plugin from " << sofile <<
": " << e.what() <<
"\n";
211 std::cerr <<
"Failed to load plugin from " << sofile <<
": unknown error\n";
std::set< std::string > m_attempted_plugin_paths
std::map< const MaCh3ArgumentParser *, std::unique_ptr< DynamicPlugin > > m_dynamic_plugin_map
Map of parsers to dynamic plugins (owning)
std::vector< std::string > expand_plugin_path(const std::string &path) const
Expand a plugin path (file or directory) into a list of canonical shared-library paths.
◆ parse_args()
| void M3::MaCh3Program::parse_args |
( |
int |
argc, |
|
|
const char *const |
argv[] |
|
) |
| |
Parse args after inserting any default subcommands.
Definition at line 139 of file MaCh3Program.cpp.
140 std::vector<std::string> args(argv, argv + argc);
142 MaCh3ArgumentParser::parse_args(args);
void insert_default_subcommands(std::vector< std::string > &args, std::size_t pos=0) const
Insert default subcommands into args where no explicit subcommand was given.
◆ Run()
| int M3::MaCh3Program::Run |
( |
| ) |
|
Run the selected subcommand.
Execute the selected subcommand.
- Returns
- Exit code from the executed module
Determines which subcommand was invoked and runs the corresponding module or plugin.
- Returns
- Exit code from the executed module (0 on success)
Definition at line 223 of file MaCh3Program.cpp.
226 if (this->is_subcommand_used(*parser))
return module->Run();
229 if (this->is_subcommand_used(*parser))
return dplugin->Run();
◆ validate_parser()
Definition at line 146 of file MaCh3Program.cpp.
147 if (!parser || parser->name().empty()) {
148 throw std::invalid_argument(
"Module/plugin must provide a non-null parser with a non-empty command name");
150 if (m_subparser_map.count(parser->name()) != 0) {
151 throw std::invalid_argument(
"Duplicate command name: " + parser->name());
◆ write_file()
| bool M3::MaCh3Program::write_file |
( |
const fs::path & |
path, |
|
|
std::string_view |
content |
|
) |
| const |
|
private |
Write content to a file, creating parent directories if needed.
- Parameters
-
| path | Filesystem path to write to |
| content | Content to write to the file |
- Returns
- true if successful, false otherwise
Definition at line 52 of file MaCh3Program.cpp.
53 std::string_view operation =
"creating parent directories";
56 fs::create_directories(path.parent_path());
58 out.exceptions(std::ios::failbit | std::ios::badbit);
59 operation =
"opening";
61 operation =
"writing";
63 operation =
"closing";
66 }
catch (
const std::exception& err) {
67 const int error = errno;
68 std::cerr <<
"Cannot write completion script '" << path.string() <<
"' while " << operation
69 <<
": " << err.what();
70 if (error != 0) std::cerr <<
": " << std::strerror(error);
◆ BASH_COMPLETION
| constexpr std::string_view M3::MaCh3Program::BASH_COMPLETION |
|
staticconstexprprivate |
Initial value:= R"(
_mach3_complete() {
local cur prev words cword
_init_completion || return
# Pass current prefix + preceding words as context; binary filters by prefix
local -a raw
mapfile -t raw < <(mach3 --complete "$cur" "${words[@]:1:$((cword-1))}" 2>/dev/null)
if [[ ${#raw[@]} -eq 0 ]]; then
# No completions from binary — fall back to default (file) completion
compopt -o default 2>/dev/null
return
fi
COMPREPLY=( "${raw[@]}" )
}
complete -F _mach3_complete mach3
)"
Definition at line 80 of file MaCh3Program.hpp.
◆ m_attempted_plugin_paths
| std::set<std::string> M3::MaCh3Program::m_attempted_plugin_paths |
|
private |
◆ m_dynamic_plugin_map
Map of parsers to dynamic plugins (owning)
Definition at line 78 of file MaCh3Program.hpp.
◆ m_module_map
Map of parsers to core modules (non-owning)
Definition at line 76 of file MaCh3Program.hpp.
◆ ZSH_COMPLETION
| constexpr std::string_view M3::MaCh3Program::ZSH_COMPLETION |
|
staticconstexprprivate |
Initial value:= R"(
#compdef mach3
_mach3() {
local cur="${words[$CURRENT]}"
local -a ctx
ctx=("${words[@]:1:$((CURRENT-2))}")
local -a completions
completions=("${(@f)$(mach3 --complete "$cur" "${ctx[@]}" 2>/dev/null)}")
if [[ ${#completions[@]} -eq 0 ]]; then
_files
return
fi
compadd -a completions
}
_mach3
)"
Definition at line 98 of file MaCh3Program.hpp.
The documentation for this class was generated from the following files: