From a0e8075d89e525b2f077983ec1e575497b99bf3c Mon Sep 17 00:00:00 2001 From: Baptiste Wicht Date: Sun, 9 Feb 2014 17:30:16 +0100 Subject: [PATCH] Complete the shell --- programs/tsh/src/main.cpp | 60 +++++++++++++++++++++++++++++++++------ tlib/include/print.hpp | 2 ++ tlib/src/print.cpp | 4 +++ 3 files changed, 57 insertions(+), 9 deletions(-) diff --git a/programs/tsh/src/main.cpp b/programs/tsh/src/main.cpp index 16b5389d..3c888119 100644 --- a/programs/tsh/src/main.cpp +++ b/programs/tsh/src/main.cpp @@ -10,6 +10,46 @@ #include #include +namespace { + +void exit_command(const std::vector& params); +void echo_command(const std::vector& params); +void sleep_command(const std::vector& params); + +struct command_definition { + const char* name; + void (*function)(const std::vector&); +}; + +command_definition commands[3] = { + {"exit", exit_command}, + {"echo", echo_command}, + {"sleep", sleep_command}, +}; + +void exit_command(const std::vector&){ + exit(0); +} + +void echo_command(const std::vector& params){ + for(uint64_t i = 1; i < params.size(); ++i){ + print(params[i]); + print(' '); + } + print_line(); +} + +void sleep_command(const std::vector& params){ + if(params.size() == 1){ + print_line("sleep: missing operand"); + } else { + size_t time = std::parse(params[1]); + sleep_ms(time * 1000); + } +} + +} //end of anonymous namespace + int main(){ char input_buffer[64]; std::string current_input; @@ -26,16 +66,16 @@ int main(){ auto params = std::split(current_input);; - if(params[0] == "exit"){ - exit(0); - } else if(params[0] == "sleep"){ - if(params.size() == 1){ - print_line("sleep: missing operand"); - } else { - size_t time = std::parse(params[1]); - sleep_ms(time * 1000); + bool found = false; + for(auto& command : commands){ + if(params[0] == command.name){ + command.function(params); + found = true; + break; } - } else { + } + + if(!found){ auto result = exec_and_wait(params[0].c_str()); if(!result.valid()){ @@ -59,4 +99,6 @@ int main(){ current_input += input_buffer; } } + + __builtin_unreachable(); } \ No newline at end of file diff --git a/tlib/include/print.hpp b/tlib/include/print.hpp index 2b7cbc4e..46f271f4 100644 --- a/tlib/include/print.hpp +++ b/tlib/include/print.hpp @@ -11,10 +11,12 @@ //TODO Rename in console #include +#include void print(char c); void print(const char* s); void print(size_t v); +void print(const std::string& s); void print_line(); void print_line(const char* s); void print_line(size_t v); diff --git a/tlib/src/print.cpp b/tlib/src/print.cpp index 76b6be6f..418d537f 100644 --- a/tlib/src/print.cpp +++ b/tlib/src/print.cpp @@ -28,6 +28,10 @@ void print(size_t v){ : "rax", "rbx"); } +void print(const std::string& s){ + return print(s.c_str()); +} + void print_line(){ print('\n'); }