Piped commands (almost) working
[minishell-2.git] / Sources / input.cpp
blob17a91c670961ef6f137a0c2aa15d0cefd4f1fbcf
1 #include "Headers/opsys.h"
2 #include <regex> // std::regex and std::regex_replace
3 #include <termios.h>
5 bool is_verbose = false;
6 bool cwd_changed = false;
8 #include <unistd.h> // fork, execvp
9 #include <pwd.h> // struct password, getpwuid_r
10 #include <sstream> // isstreams, osstreams
11 #include <algorithm> // copy
12 #include <iterator> // istream_iterator, iterator, back_inserter
14 using std::istringstream;
15 using std::copy;
16 using std::istream_iterator;
17 using std::ostream_iterator;
18 using std::cin;
19 using std::cout;
21 CLIInputs::CLIInputs(int argc, char **argv)
23 if(argc > 1)
25 for(short unsigned int i = 1; i < argc; i++)
27 string s_argv = argv[i];
28 if (!s_argv.compare("-h") || !s_argv.compare("--help"))
30 printf("%-20s\tObtain help.\n", "-h, --help");
31 printf("%-20s\tShows additional execution data.\n", "-v, --verbose");
32 exit(0);
34 if (!s_argv.compare("-v") || !s_argv.compare("--verbose"))
36 printf("Executing in verbose mode.\n");
37 is_verbose = true;
43 void Prompt::get_last_dir()
45 string last_dir = OS.cwd;
46 string home_dir = getenv("HOME");
47 last_dir = std::regex_replace(last_dir, std::regex(home_dir), "~"); // Change HOME to ~ on the prompt line.
48 this->last_dir = last_dir;
51 Prompt::Prompt()
53 // struct termios t;
54 // tcgetattr(STDIN_FILENO, &t);
55 // t.c_lflag &= ~ICANON;
56 // tcsetattr(STDIN_FILENO, TCSANOW, &t); // WIP for arrow keys support
58 get_last_dir(); // Process cwd for exibition on prompt
61 void Prompt::print()
63 if (cwd_changed)
65 get_last_dir();
66 cwd_changed = false;
68 cout << BLUE_ANSI << OS.username << "@" << OS.hostname << ":" << RED_ANSI << last_dir << RESET_ANSI << "$ ";
71 void Prompt::parse(string input)
73 if(!tokens.empty())
74 tokens.clear();
75 istringstream iss (input);
76 copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter(tokens));
78 if(is_verbose)
80 cout << "Parsed: [";
81 for(unsigned short int i = 0; i < tokens.size()-1; i++)
82 cout << "\"" << tokens[i] << "\", ";
83 cout << "\"" << tokens.back() << "\"]\n";
87 short int Prompt::run()
89 string pipe = "|";
90 int pipe_count = std::count(tokens.begin(), tokens.end(), pipe);
92 if(pipe_count)
93 { // Checks if there's any pipe in the given command
94 OS.piped_command(tokens, pipe_count);
96 if(!tokens[0].compare("cd"))
98 OS.change_dir(tokens);
99 return cwd_changed;
100 } else if (!tokens[0].compare("pwd"))
102 cout << OS.cwd << '\n';
103 return 1;
104 } else if (!tokens[0].compare("help"))
106 cout << "Insert help text here.\n";
107 return 1;
108 } else if (!tokens[0].compare("quit"))
110 std::cerr << "Exiting.\n";
111 exit_program = true;
112 return 1;
114 else
116 return OS.simple_command(tokens);