MaCh3  2.8.0
Reference Guide
Public Member Functions | Private Member Functions | Private Attributes | Static Private Attributes | List of all members
M3::MaCh3Program Class Reference

Main program class that manages modules, plugins, and command-line parsing. More...

#include <CLI/MaCh3Program.hpp>

Inheritance diagram for M3::MaCh3Program:
[legend]
Collaboration diagram for M3::MaCh3Program:
[legend]

Public Member Functions

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...
 
- Public Member Functions inherited from M3::MaCh3ArgumentParser
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...
 

Private Member Functions

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...
 

Private Attributes

std::map< const MaCh3ArgumentParser *, IModule * > m_module_map
 Map of parsers to core modules (non-owning) More...
 
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) More...
 

Static Private Attributes

static constexpr std::string_view BASH_COMPLETION
 
static constexpr std::string_view ZSH_COMPLETION
 

Detailed Description

Main program class that manages modules, plugins, and command-line parsing.

This class extends MaCh3ArgumentParser to provide functionality for:

Author
Alexander Richards

Definition at line 26 of file MaCh3Program.hpp.

Constructor & Destructor Documentation

◆ ~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.

Member Function Documentation

◆ add_core_module()

void M3::MaCh3Program::add_core_module ( IModule &  module)

Add a core module to the program.

Parameters
moduleReference to the module to be added

Definition at line 155 of file MaCh3Program.cpp.

155  {
156  // Fix registration safeguards: another get_parser() call could replace a registered parser.
157  if (std::any_of(m_module_map.begin(), m_module_map.end(),
158  [&module](const auto& entry) { return entry.second == &module; })) {
159  throw std::invalid_argument("Core module is already registered");
160  }
161  MaCh3ArgumentParser* parser = module.get_parser();
162  validate_parser(parser);
163  this->add_subparser(*parser);
164  m_module_map[parser] = &module;
165  }
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
prefixThe partially-typed word being completed
contextWords already typed after the program name but before prefix

Definition at line 134 of file MaCh3Program.cpp.

134  {
135  for (const auto& name : get_completions(prefix, context))
136  std::cout << name << "\n";
137  }
const std::string name() const
Get the name of this parser/subcommand.
Definition: m3argparse.hpp:24
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.
Definition: m3argparse.hpp:75

◆ 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.

76  {
77  const char* shell = std::getenv("SHELL");
78  if (!shell) return "";
79 
80  // Fix completion installation: recognise exact shell names, not substrings such as "notbash".
81  const auto name = fs::path(shell).filename().string();
82  if (name == "bash" || name == "zsh") return name;
83 
84  return "";
85  }

◆ 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
pathPath 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
pathPath to a plugin file or directory
Returns
Vector of absolute paths to .so files

Definition at line 242 of file MaCh3Program.cpp.

242  {
243  std::vector<std::string> result;
244 
245  fs::path p(path);
246 
247  if (!fs::exists(p)) {
248  std::cerr << "Plugin path does not exist: " << path << "\n";
249  return result;
250  }
251 
252  if (fs::is_regular_file(p)) {
253  // Fix registration safeguards: normalise relative paths and symlinks before deduplication.
254  result.push_back(fs::canonical(p).string());
255  }
256  else if (fs::is_directory(p)) {
257  // Fix platform coverage: also recognise native macOS shared-library suffixes.
258  for (auto& entry : fs::directory_iterator(p)) {
259  const auto extension = entry.path().extension();
260  bool is_good_plugin = extension == ".so";
261 #ifdef __APPLE__
262  is_good_plugin = is_good_plugin || extension == ".dylib";
263 #endif
264  try{
265  is_good_plugin = is_good_plugin && entry.is_regular_file();
266  }
267  catch (const fs::filesystem_error& err) {
268  // Fix discovery errors: a broken candidate must not hide valid neighbours.
269  std::cerr << "Cannot inspect plugin '" << entry.path().string() << "': " << err.what() << "\n";
270  continue;
271  }
272  if (is_good_plugin) {
273  try{
274  result.push_back(fs::canonical(entry.path()).string());
275  }
276  catch (const fs::filesystem_error& err) {
277  std::cerr << "Cannot canonicalize plugin '" << entry.path().string() << "': " << err.what() << "\n";
278  continue;
279  }
280  }
281  }
282  }
283  else {
284  std::cerr << "Invalid plugin path (not file or directory): " << path << "\n";
285  }
286 
287  // Fix registration safeguards: make candidate precedence independent of directory iteration order.
288  std::sort(result.begin(), result.end());
289  return result;
290  }

◆ install_completions()

int M3::MaCh3Program::install_completions ( ) const

Install shell completion scripts for bash and zsh.

Definition at line 88 of file MaCh3Program.cpp.

88  {
89  const char* home = std::getenv("HOME");
90  if (!home || home[0] == '\0') {
91  std::cerr << "Cannot determine HOME directory\n";
92  return 1;
93  }
94 
95  std::string shell = detect_shell();
96  if (shell.empty()) {
97  std::cerr << "Could not detect your shell (check $SHELL is exported). Supported: bash, zsh\n";
98  return 1;
99  }
100 
101  // Resolve the absolute path of this binary so the completion script
102  // works even when mach3 is not on PATH.
103  const std::string binary_path = shell_quote(executable_path());
104 
105  // Replace the generic "mach3" invocation in the template with the
106  // absolute binary path so the script is self-contained.
107  auto embed_path = [&](std::string_view tmpl) -> std::string {
108  std::string s(tmpl);
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);
114  return s;
115  };
116 
117  fs::path home_path(home);
118 
119  if (shell == "bash") {
120  fs::path path = home_path / ".local/share/bash-completion/completions/mach3";
121  if (!write_file(path, embed_path(MaCh3Program::BASH_COMPLETION))) return 1;
122  std::cout << "Installed bash completions → " << path << "\n";
123  return 0;
124  }
125 
126  if (shell == "zsh") {
127  fs::path path = home_path / ".local/share/zsh/site-functions/_mach3";
128  if (!write_file(path, embed_path(MaCh3Program::ZSH_COMPLETION))) return 1;
129  std::cout << "Installed zsh completions → " << path << "\n";
130  }
131  return 0;
132  }
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.

172  {
173  const char* env = std::getenv("MACH3_PLUGINS");
174  if (!env || env[0] == '\0') return;
175 
176  std::stringstream ss(env);
177  std::string path;
178 
179  while (std::getline(ss, path, ':')) {
180  if (path.empty()) {
181  std::cerr << "Ignoring empty plugin path in MACH3_PLUGINS\n";
182  continue;
183  }
184  std::vector<std::string> files;
185  // Fix discovery errors: one inaccessible path must not block other optional plugins.
186  try {
187  files = this->expand_plugin_path(path);
188  }
189  catch (const fs::filesystem_error& err) {
190  std::cerr << "Cannot discover plugins in '" << path << "': " << err.what() << "\n";
191  continue;
192  }
193  for (const auto& sofile : files) {
194  // Fix registration safeguards: canonical paths also deduplicate symlink aliases.
195  if (!m_attempted_plugin_paths.insert(sofile).second) {
196  std::cerr << "Skipping duplicate plugin library: " << sofile << "\n";
197  continue;
198  }
199  try{
200  std::unique_ptr<DynamicPlugin> dlplugin = std::make_unique<DynamicPlugin>(sofile);
201  MaCh3ArgumentParser* parser = dlplugin->get_parser();
202  validate_parser(parser);
203  this->add_subparser(*parser);
204  m_dynamic_plugin_map[parser] = std::move(dlplugin);
205  }
206  catch (const std::exception& e) {
207  std::cerr << "Failed to load plugin from " << sofile << ": " << e.what() << "\n";
208  continue;
209  }
210  catch (...) {
211  std::cerr << "Failed to load plugin from " << sofile << ": unknown error\n";
212  continue;
213  }
214  }
215  }
216  }
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.

139  {
140  std::vector<std::string> args(argv, argv + argc);
141  this->insert_default_subcommands(args);
142  MaCh3ArgumentParser::parse_args(args);
143  }
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.
Definition: m3argparse.hpp:132

◆ 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.

223  {
224  // Dispatch to the top-level module; modules handle their own nested subcommands
225  for (const auto& [parser, module] : m_module_map) {
226  if (this->is_subcommand_used(*parser)) return module->Run();
227  }
228  for (const auto& [parser, dplugin] : m_dynamic_plugin_map) {
229  if (this->is_subcommand_used(*parser)) return dplugin->Run();
230  }
231  return 0;
232  }

◆ validate_parser()

void M3::MaCh3Program::validate_parser ( const MaCh3ArgumentParser *  parser) const
private

Definition at line 146 of file MaCh3Program.cpp.

146  {
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");
149  }
150  if (m_subparser_map.count(parser->name()) != 0) {
151  throw std::invalid_argument("Duplicate command name: " + parser->name());
152  }
153  }

◆ 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
pathFilesystem path to write to
contentContent to write to the file
Returns
true if successful, false otherwise

Definition at line 52 of file MaCh3Program.cpp.

52  {
53  std::string_view operation = "creating parent directories";
54  try {
55  errno = 0;
56  fs::create_directories(path.parent_path());
57  std::ofstream out;
58  out.exceptions(std::ios::failbit | std::ios::badbit);
59  operation = "opening";
60  out.open(path);
61  operation = "writing";
62  out << content;
63  operation = "closing";
64  out.close();
65  return true;
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);
71  std::cerr << "\n";
72  return false;
73  }
74  }

Member Data Documentation

◆ 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

Definition at line 77 of file MaCh3Program.hpp.

◆ m_dynamic_plugin_map

std::map<const MaCh3ArgumentParser*, std::unique_ptr<DynamicPlugin> > M3::MaCh3Program::m_dynamic_plugin_map
private

Map of parsers to dynamic plugins (owning)

Definition at line 78 of file MaCh3Program.hpp.

◆ m_module_map

std::map<const MaCh3ArgumentParser*, IModule*> M3::MaCh3Program::m_module_map
private

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: