From d25d4b0b3611e14e008fb6aab1472208a3778b94 Mon Sep 17 00:00:00 2001 From: "Dirk-Jan C. Binnema" Date: Wed, 2 Aug 2023 20:43:45 +0300 Subject: utils: add expand_path (wordexp wrapper) For expanding command-line options for shells that don't do that by themselves. --- lib/utils/mu-utils-file.cc | 28 ++++++++++++++++++++++++++++ lib/utils/mu-utils-file.hh | 10 ++++++++++ 2 files changed, 38 insertions(+) diff --git a/lib/utils/mu-utils-file.cc b/lib/utils/mu-utils-file.cc index 021d4c6..ce31f32 100644 --- a/lib/utils/mu-utils-file.cc +++ b/lib/utils/mu-utils-file.cc @@ -27,6 +27,10 @@ #include #include +#ifdef HAVE_WORDEXP_H +#include +#endif /*HAVE_WORDEXP_H*/ + using namespace Mu; @@ -179,6 +183,30 @@ Mu::runtime_path(Mu::RuntimePath path, const std::string& muhome) } +Result +Mu::expand_path(const std::string& str) +{ +#ifndef HAVE_WORDEXP_H + return Ok(std::string{str}); +#else + int res; + wordexp_t result; + memset(&result, 0, sizeof(result)); + + res = wordexp(str.c_str(), &result, 0); + if (res != 0 || result.we_wordc == 0) + return Err(Error::Code::File, "cannot expand '%s'; err=%d", str.c_str(), res); + + std::string expanded{result.we_wordv[0]}; + wordfree(&result); + + return Ok(std::move(expanded)); + +#endif /*HAVE_WORDEXP_H*/ +} + + + #ifdef BUILD_TESTS /* diff --git a/lib/utils/mu-utils-file.hh b/lib/utils/mu-utils-file.hh index b9e6d92..4863e37 100644 --- a/lib/utils/mu-utils-file.hh +++ b/lib/utils/mu-utils-file.hh @@ -73,6 +73,16 @@ bool check_dir(const std::string& path, bool readable, bool writeable); */ std::string canonicalize_filename(const std::string& path, const std::string& relative_to); +/** + * Expand the filesystem path (as per wordexp(3)) + * + * @param str a filesystem path string + * + * @return the expanded string or some error + */ +Result expand_path(const std::string& str); + + /* * for OSs with out support for direntry->d_type, like Solaris */ -- cgit v1.0