Compare commits

..

2 Commits

3 changed files with 330 additions and 87 deletions

View File

@ -6,6 +6,7 @@
#include <cstdlib>
#include <filesystem>
#include <vector>
#include <optional>
namespace sh
{
@ -39,9 +40,15 @@ namespace sh
std::optional<std::filesystem::path> isExec(const std::string& input);
void printType(const std::string& input);
void printType(const std::string& input, const std::optional<std::filesystem::path>& stdoutFilePath = std::nullopt);
std::filesystem::path getWorkingDir();
void changeDir(const std::vector<std::string>& tokens);
}
void changeDir(const std::vector<std::string>& tokens, const std::optional<std::filesystem::path>& stdoutFilePath = std::nullopt);
void printCommandStdout(std::string_view input, const std::optional<std::filesystem::path>& outputFilePath = std::nullopt, bool append = false);
void printCommandStderr(std::string_view input, const std::optional<std::filesystem::path>& outputFilePath = std::nullopt, bool append = false);
void executeCommand(const std::filesystem::path& exePath, const std::vector<std::string>& tokens, const std::optional<std::filesystem::path>& stdoutFilePath = std::nullopt, const std::optional<std::filesystem::path>& stderrFilePath = std::nullopt, bool appendStdout = false, bool appendStderr = false);
}

View File

@ -1,16 +1,11 @@
#include <iostream>
#include <string>
#include <map>
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <vector>
#include <optional>
#ifdef _WIN32
#include <process.h>
#else
#include <unistd.h>
#include <sys/wait.h>
#endif
#include "shellUtils.h"
@ -25,6 +20,10 @@ int main()
while (!shouldExit)
{
tokens.clear();
std::optional<std::filesystem::path> stdoutFile;
std::optional<std::filesystem::path> stderrFile;
bool appendStdout{false};
bool appendStderr{false};
std::string input;
std::string line;
@ -34,6 +33,12 @@ int main()
while (!finshedInput and std::getline(std::cin, line))
{
if (line.empty())
{
finshedInput = true;
continue;
}
auto end = line.size() - 1;
if (line[end] == '\\')
{
@ -74,7 +79,69 @@ int main()
//we can now assume there is actual text from the input
sh::tokenize(tokens, input);
//check for redirection
for (size_t i = 0; i < tokens.size();)
{
if (tokens[i] == ">>" or tokens[i] == "1>>")
{
if (i + 1 >= tokens.size())
{
std::cerr << "Syntax error: expeceted filepath after '>>'\n";
continue;
}
appendStdout = true;
stdoutFile = tokens[i+1];
tokens.erase(tokens.begin() + i, tokens.begin() + i + 2);
continue;
}
if (tokens[i] == "2>>")
{
if (i + 1 >= tokens.size())
{
std::cerr << "Syntax error: expeceted filepath after '>>'\n";
continue;
}
appendStderr = true;
stderrFile = tokens[i+1];
tokens.erase(tokens.begin() + i, tokens.begin() + i + 2);
continue;
}
if (tokens[i] == ">" or tokens[i] == "1>")
{//stdout redirect
if (i + 1 >= tokens.size())
{//if no output specified, just remove and continue as normal
std::cerr << "Syntax error: expeceted filepath after '>'\n";
continue;
}
stdoutFile = tokens[i+1];
tokens.erase(tokens.begin() + i, tokens.begin() + i + 2);
continue;
}
if (tokens[i] == "2>")
{//stdout redirect
if (i + 1 >= tokens.size())
{//if no output specified, just remove and continue as normal
std::cerr << "Syntax error: expeceted filepath after '>'\n";
continue;
}
stderrFile = tokens[i+1];
tokens.erase(tokens.begin() + i, tokens.begin() + i + 2);
continue;
}
i++;
}
std::optional<std::filesystem::path> result;
std::ostringstream output;
switch (sh::Command command = sh::getCommand(tokens[0]))
{
@ -82,73 +149,43 @@ int main()
shouldExit = true;
break;
case sh::Command::echo:
if (stderrFile)
{
std::ofstream err{stderrFile.value()};
err.close();
}
for (int i = 1; i < tokens.size(); i++)
{
std::cout << tokens[i] << " ";
output << tokens[i];
if (i < tokens.size() - 1) output << " ";
}
std::cout << "\n";
stdoutFile ?
sh::printCommandStdout(output.str(), stdoutFile.value(), appendStdout) :
sh::printCommandStdout(output.str());
break;
case sh::Command::unknown:
result = sh::isExec(tokens[0]);
if (result)
{
std::string filename = result.value().filename().string();
std::string fullPath = result.value().string();
#ifdef _WIN32
std::vector<const char*> args;
args.push_back(filename.c_str());// have exe path on seperate element for _spawnv
for (size_t i = 1; i < tokens.size(); i++)
{
args.push_back(const_cast<char*>(tokens[i].c_str()));
}
args.push_back(nullptr);
intptr_t status = _spawnv(_P_WAIT, fullPath.c_str(), args.data());
if (status == -1)
{
perror("\n\nError executing program\n\n");
return 1;
}
#else
std::vector<char*> args;
args.push_back(const_cast<char*>(filename.c_str()));// have exe path on seperate element for execv
for (size_t i = 1; i < tokens.size(); i++)
{
args.push_back(const_cast<char*>(tokens[i].c_str()));
}
args.push_back(nullptr);
pid_t pid = fork();
if (pid == 0)
{// child process
execv(result.value().c_str(), args.data());
perror("\n\nError executing program\n\n");
exit(1);
}
else
{
int status;
waitpid(pid, &status, 0);
}
#endif
sh::executeCommand(result.value(), tokens, stdoutFile, stderrFile, appendStdout, appendStderr);
}
else
{
std::cout << tokens[0] << ": command not found\n";
output << tokens[0] << ": command not found";
stdoutFile ?
sh::printCommandStdout(output.str(), stdoutFile.value()) :
sh::printCommandStdout(output.str());
}
break;
case sh::Command::type:
sh::printType(tokens[1]);
sh::printType(tokens[1], stdoutFile);
break;
case sh::Command::pwd:
std::cout << std::filesystem::current_path().string() << "\n";
break;
case sh::Command::cd:
sh::changeDir(tokens);
sh::changeDir(tokens, stdoutFile);
break;
}
}

View File

@ -6,14 +6,23 @@
#include <map>
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <sstream>
#include <unistd.h>
#include <fcntl.h> // For _O_RDWR, _O_CREAT, etc.
#ifdef _WIN32
#define HOME "USERPROFILE"
#include <process.h>
#include <io.h>
#include <sys/stat.h> // For _S_IWRITE
#else
#include <unistd.h>
#include <sys/wait.h>
#define HOME "HOME"
#endif
namespace sh
{
void tokenize(std::vector<std::string>& tokens, const std::string& input)
@ -67,19 +76,6 @@ namespace sh
{
tokens.emplace_back(currentToken);
}
// std::istringstream tokens {input};
// std::string currentToken;
// while (tokens >> currentToken)
// {
// // check for escaped white space
// if (currentToken.back() == '\\')
// {//add whitespace to token
// currentToken.append(1, ' ');
// }
// tokenContainer.emplace_back(currentToken);
// }
}
Command getCommand(std::string_view input)
@ -140,31 +136,36 @@ namespace sh
return std::nullopt;
}
void printType(const std::string& input)
void printType(const std::string& input, const std::optional<std::filesystem::path>& stdoutFilePath)
{
std::ostringstream output;
if (commandMap.contains(input))
{
std::cout << input;
std::cout << " is a shell builtin\n";
return;
output << input << " is a shell builtin";
}
if (const auto fullPath {isExec(input)})
else if (const auto fullPath {isExec(input)})
{
std::cout << input;
std::cout << " is " << fullPath.value().string() << "\n";
return;
output << input;
output << " is " << fullPath.value().string();
}
else
{
output << input;
output << ": not found";
}
std::cout << input;
std::cout << ": not found\n";
}
stdoutFilePath ?
printCommandStdout(output.str(), stdoutFilePath.value()) :
printCommandStdout(output.str());
}
void changeDir(const std::vector<std::string>& tokens)
void changeDir(const std::vector<std::string>& tokens, const std::optional<std::filesystem::path>& stdoutFilePath)
{
if (tokens.size() > 2)
{
std::cerr << "cd: too many arguments\n";
stdoutFilePath.has_value() ?
printCommandStderr("cd: too many arguments", stdoutFilePath.value()) :
printCommandStderr("cd: too many arguments");
return;
}
@ -205,9 +206,207 @@ namespace sh
}
else
{
std::cerr << "cd: " << expandedPath.string() << ": No such file or directory\n";
std::ostringstream output;
output << "cd: " << expandedPath.string() << ": No such file or directory";
stdoutFilePath.has_value() ?
printCommandStderr(output.str(), stdoutFilePath.value()) :
printCommandStderr(output.str());
}
}
void printCommandStdout(const std::string_view input, const std::optional<std::filesystem::path>& stdoutFilePath, bool append)
{
if (stdoutFilePath)
{
auto mode = append ? std::ios::app : std::ios::trunc;
std::ofstream output {stdoutFilePath.value(), mode};
if (!output)
{
std::cerr << "ERROR: cannot open " << stdoutFilePath.value().string() << "\n";
}
output << input << "\n";
output.close();
return;
}
std::cout << input << "\n";
}
void printCommandStderr(const std::string_view input, const std::optional<std::filesystem::path>& stderrFilePath, bool append)
{
if (stderrFilePath)
{
auto mode = append ? std::ios::app : std::ios::trunc;
std::ofstream output {stderrFilePath.value(), mode};
if (!output)
{
std::cerr << "ERROR: cannot open " << stderrFilePath.value().string() << "\n";
}
output << input;
output.close();
return;
}
std::cerr << input << "\n";
}
void executeCommand(const std::filesystem::path& exePath,const std::vector<std::string>& tokens, const std::optional<std::filesystem::path>& stdoutFilePath, const std::optional<std::filesystem::path>& stderrFilePath, bool appendStdout, bool appendStderr)
{
std::string filename = exePath.filename().string();
std::string fullPath = exePath.string();
#ifdef _WIN32
std::vector<const char*> args;
args.push_back(filename.c_str());// have exe path on seperate element for _spawnv
for (size_t i = 1; i < tokens.size(); i++)
{
args.push_back(const_cast<char*>(tokens[i].c_str()));
}
args.push_back(nullptr);
int originalStdout = -1;
int originalStderr = -1;
int stdoutFd = -1;
int stderrFd = -1;
if (stdoutFilePath)
{
originalStdout = _dup(1); // save out connection to the shell
if (appendStdout)
{
stdoutFd = _open(stdoutFilePath.value().c_str(), _O_WRONLY | _O_CREAT, _S_IWRITE);
}
else
{
stdoutFd = _open(stdoutFilePath.value().c_str(), _O_WRONLY | _O_CREAT | _O_TRUNC, _S_IWRITE);
}
if (stdoutFd == -1)
{
perror("Could not open redirect file\n");
_close(originalStdout);
return;
}
_dup2(stdoutFd, 1);
}
if (stderrFilePath)
{
originalStderr = _dup(2);
if (appendStderr)
{
stderrFd = _open(stderrFilePath.value().c_str(), _O_WRONLY | _O_CREAT | _O_APPEND, _S_IWRITE);
}
else
{
stderrFd = _open(stderrFilePath.value().c_str(), _O_WRONLY | _O_CREAT | _O_TRUNC, _S_IWRITE);
}
if (stderrFd == -1)
{
perror("could not redirect stderr to file");
return;
}
_dup2(stderrFd, 2);
}
intptr_t status = _spawnv(_P_WAIT, fullPath.c_str(), args.data());
if (stdoutFilePath)
{
_dup2(originalStdout, 1);
_close(originalStdout);
_close(stdoutFd);
}
if (stderrFilePath)
{
_dup2(originalStderr, 2);
_close(originalStderr);
_close(stderrFd);
}
if (status == -1)
{
perror("\n\nError executing program\n\n");
return;
}
#else
std::vector<char*> args;
args.push_back(const_cast<char*>(filename.c_str()));// have exe path on seperate element for execv
for (size_t i = 1; i < tokens.size(); i++)
{
args.push_back(const_cast<char*>(tokens[i].c_str()));
}
args.push_back(nullptr);
pid_t pid = fork();
if (pid == 0)
{// child process
if (stdoutFilePath)
{
int fileFd;
if (appendStdout)
{
fileFd = open(stdoutFilePath.value().c_str(), O_WRONLY | O_CREAT | O_APPEND, 0644);// 0644: Permissions (rw-r--r--)
}
else
{
fileFd = open(stdoutFilePath.value().c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);// 0644: Permissions (rw-r--r--)
}
if (fileFd == -1)
{
perror("Error opening redirect file\n");
exit(1);
}
dup2(fileFd, STDOUT_FILENO);
close(fileFd);
}
if (stderrFilePath)
{
int fileFd;
if (appendStderr)
{
fileFd = open(stderrFilePath.value().c_str(), O_WRONLY | O_CREAT| O_APPEND, 0644);// 0644: Permissions (rw-r--r--)
}
else
{
fileFd = open(stderrFilePath.value().c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);// 0644: Permissions (rw-r--r--)
}
if (fileFd == -1)
{
perror("Error opening redirect file\n");
exit(1);
}
dup2(fileFd, STDERR_FILENO);
close(fileFd);
}
execv(exePath.c_str(), args.data());
perror("\n\nError executing program\n\n");
exit(1);
}
else
{
int status;
waitpid(pid, &status, 0);
}
#endif
}
}