utils: add expand_path (wordexp wrapper)

For expanding command-line options for shells that don't do that by themselves.
This commit is contained in:
Dirk-Jan C. Binnema 2023-08-02 20:43:45 +03:00
parent b91272aca2
commit 111e48efa3
2 changed files with 38 additions and 0 deletions

View File

@ -28,6 +28,10 @@
#include <gio/gio.h>
#include <gio/gunixinputstream.h>
#ifdef HAVE_WORDEXP_H
#include <wordexp.h>
#endif /*HAVE_WORDEXP_H*/
using namespace Mu;
@ -309,6 +313,30 @@ Mu::run_command(std::initializer_list<std::string> args)
}
Result<std::string>
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
/*

View File

@ -75,6 +75,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<std::string> expand_path(const std::string& str);
/*
* for OSs with out support for direntry->d_type, like Solaris
*/