Commit e99f836d authored by aligungr's avatar aligungr

Opt utils improvement

parent 25ab36e0
...@@ -14,6 +14,7 @@ ...@@ -14,6 +14,7 @@
#include <ctime> #include <ctime>
#include <iostream> #include <iostream>
#include <sstream> #include <sstream>
#include <wordexp.h>
static constexpr const size_t MAX_WIDTH = 90; static constexpr const size_t MAX_WIDTH = 90;
...@@ -238,3 +239,60 @@ std::string opt::OptionsResult::getOption(const OptionItem &item) const ...@@ -238,3 +239,60 @@ std::string opt::OptionsResult::getOption(const OptionItem &item) const
return m_options.at(*item.longName); return m_options.at(*item.longName);
return {}; return {};
} }
opt::ExpansionResult opt::PerformExpansion(const std::string &command, std::vector<std::string> &argv)
{
wordexp_t p = {};
int ret = wordexp(command.c_str(), &p, WRDE_NOCMD | WRDE_UNDEF);
if (ret == 0)
{
for (size_t i = 0; i < p.we_wordc; i++)
argv.emplace_back(p.we_wordv[i]);
wordfree(&p);
return ExpansionResult::SUCCESS;
}
wordfree(&p);
if (ret == WRDE_BADCHAR)
return ExpansionResult::ILLEGAL_CHARACTER;
if (ret == WRDE_BADVAL)
return ExpansionResult::UNDEFINED_VARIABLE;
if (ret == WRDE_CMDSUB)
return ExpansionResult::CMD_SUBS_NOT_ALLOWED;
if (ret == WRDE_SYNTAX)
return ExpansionResult::SYNTAX_ERROR;
return ExpansionResult::UNSPECIFIED_ERROR;
}
bool opt::ReadLine(std::istream &istream, std::ostream &ostream, std::string &line, std::vector<std::string> &tokens)
{
std::cout << ">> ";
std::string input{};
while (true)
{
std::string ln{};
std::getline(std::cin, ln);
if (!std::cin)
return false;
input += ln;
std::vector<std::string> vec{};
auto exp = PerformExpansion(input, vec);
if (exp == ExpansionResult::SUCCESS)
{
line = input;
tokens = vec;
return true;
}
if (exp == ExpansionResult::SYNTAX_ERROR)
{
std::cout << ".. ";
input += "\n";
continue;
}
return false;
}
}
...@@ -9,7 +9,9 @@ ...@@ -9,7 +9,9 @@
#pragma once #pragma once
#include <cstring> #include <cstring>
#include <istream>
#include <optional> #include <optional>
#include <ostream>
#include <stdexcept> #include <stdexcept>
#include <string> #include <string>
#include <unordered_map> #include <unordered_map>
...@@ -101,4 +103,18 @@ class OptionsResult ...@@ -101,4 +103,18 @@ class OptionsResult
[[noreturn]] void error(const std::string &msg) const; [[noreturn]] void error(const std::string &msg) const;
}; };
enum class ExpansionResult
{
SUCCESS,
ILLEGAL_CHARACTER,
UNDEFINED_VARIABLE,
CMD_SUBS_NOT_ALLOWED,
SYNTAX_ERROR,
UNSPECIFIED_ERROR
};
ExpansionResult PerformExpansion(const std::string &command, std::vector<std::string> &argv);
bool ReadLine(std::istream &istream, std::ostream &ostream, std::string &line, std::vector<std::string> &tokens);
} // namespace opt } // namespace opt
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment