MaCh3  2.8.0
Reference Guide
MaCh3Program.cpp
Go to the documentation of this file.
1 
4 #include <dlfcn.h>
5 #include <algorithm>
6 #include <cerrno>
7 #include <cstring>
8 #include <filesystem>
9 #include <fstream>
10 #include <iostream>
11 #include <memory>
12 #include <sstream>
13 #ifdef __APPLE__
14 #include <mach-o/dyld.h>
15 #endif
16 #include "CLI/MaCh3Program.hpp"
17 
18 using std::vector, std::string, std::map;
19 namespace fs = std::filesystem;
20 
21 namespace {
22  // Fix executable paths: resolve natively on Linux/macOS, retaining a PATH fallback.
23  std::string executable_path() {
24  std::error_code error;
25 #ifdef __APPLE__
26  constexpr std::uint32_t size = 1024;
27  std::vector<char> buffer(size);
28  if (_NSGetExecutablePath(buffer.data(), &size) != 0) {
29  buffer.resize(size);
30  if (_NSGetExecutablePath(buffer.data(), &size) != 0) return "mach3";
31  }
32  const auto path = fs::canonical(buffer.data(), error);
33 #else
34  const auto path = fs::read_symlink("/proc/self/exe", error);
35 #endif
36  return error ? "mach3" : path.string();
37  }
38 
39  // Fix executable paths: prevent spaces, quotes or metacharacters changing shell parsing.
40  std::string shell_quote(const std::string& value) {
41  std::string result = "'";
42  for (const char character : value) {
43  if (character == '\'') result += "'\\''";
44  else result += character;
45  }
46  return result + "'";
47  }
48 }
49 
50 namespace M3{
51  // Fix completion installation: check open/write/close and report the failing operation.
52  bool MaCh3Program::write_file(const fs::path& path, std::string_view content) const{
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  }
75 
76  std::string MaCh3Program::detect_shell() const{
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  }
86 
87  // Fix completion installation: environment and file failures must reach the caller as status 1.
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  }
133 
134  void MaCh3Program::completions(const std::string& prefix, const std::vector<std::string>& context) const {
135  for (const auto& name : get_completions(prefix, context))
136  std::cout << name << "\n";
137  }
138 
139  void MaCh3Program::parse_args(int argc, const char *const argv[]) {
140  std::vector<std::string> args(argv, argv + argc);
141  this->insert_default_subcommands(args);
142  MaCh3ArgumentParser::parse_args(args);
143  }
144 
145  // Fix registration safeguards: reject invalid parsers/collisions before mutating argparse's maps.
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  }
154 
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  }
166 
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  }
217 
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  }
233 
234 
242  std::vector<std::string> MaCh3Program::expand_plugin_path(const std::string& path) const {
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  }
291 }
Core program class for the MaCh3 command-line interface.
Interface for MaCh3 plugins and modules.
Definition: plugin.hpp:19
virtual MaCh3ArgumentParser * get_parser()=0
Get the argument parser for this plugin.
Extended ArgumentParser with MaCh3-specific functionality.
Definition: m3argparse.hpp:17
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
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
void add_core_module(IModule &module)
Add a core module to the program.
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
void completions(const std::string &prefix, const std::vector< std::string > &context) const
Generate subcommand or long-option suggestions at the active parser depth.
static constexpr std::string_view BASH_COMPLETION
int install_completions() const
Install shell completion scripts for bash and zsh.
int Run()
Run the selected subcommand.
std::map< const MaCh3ArgumentParser *, IModule * > m_module_map
Map of parsers to core modules (non-owning)
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::string detect_shell() const
Detect the user's shell from the SHELL environment variable.
void load_dynamic_plugins()
Load dynamic plugins from the MACH3_PLUGINS environment variable.
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.
void validate_parser(const MaCh3ArgumentParser *parser) const
void parse_args(int argc, const char *const argv[])
Parse args after inserting any default subcommands.
Main namespace for MaCh3 software.