]> git.armaanb.net Git - gen-shell.git/blob - src/main.cpp
Major restructuring
[gen-shell.git] / src / main.cpp
1 // gen-shell - the generic REPL
2 // Copyright (c) 2021, Armaan Bhojwani <me@armaanb.net>
3
4 #include <iostream>
5 #include "sarge.h"
6
7 #include <vector>
8 #include <string>
9
10 #include <readline/readline.h>
11 #include <readline/history.h>
12
13 ////////////////////////////////////////////////////////////////////////////////
14
15 using namespace std;
16
17 const std::string
18 getResponse(const std::string & prompt) {
19   std::string response {
20     ""
21   };
22
23   // Display prompt, get input
24   char * line_read = readline(prompt.c_str());
25   if (!line_read) {
26     std::cout << "\n";
27     response = "<EOF>";
28   } else {
29     if (*line_read) {
30       add_history(line_read);
31     }
32
33     response = std::string(line_read);
34     free(line_read);
35   }
36
37   return response;
38 }
39
40 ////////////////////////////////////////////////////////////////////////////////
41
42 int
43 main(int argc, char** argv)
44 {
45   // Command line arguments
46   Sarge sarge;
47
48   sarge.setArgument("c", "command", "Command to convert to REPL", true);
49   sarge.setArgument("h", "help", "Show this message.", false);
50   sarge.setArgument("p", "prompt", "Define a custom prompt", true);
51   sarge.setArgument("q", "quotes", "Treat whole input as argv[1]", false);
52   sarge.setDescription("Make a REPL from any executable");
53   sarge.setUsage("gen-shell <options>");
54
55   if (!sarge.parseArguments(argc, argv)) {
56     std::cerr << "Could not parse command line arguments" << std::endl;
57     return 1;
58   }
59
60   if (sarge.exists("help")) {
61     sarge.printHelp();
62     return 0;
63   }
64
65   string arg_cmd;
66   sarge.getFlag("command", arg_cmd);
67
68   string prompt = "";
69   sarge.getFlag("prompt", prompt);
70   if (prompt == "") {
71     prompt = "% ";
72   }
73
74   // Do the stuffs!
75   while (true) {
76     auto command = getResponse(prompt);
77
78     if (command == "<EOF>" || command == "exit" || command == "quit" ) {
79       return 0;
80     } else {
81       string whole_command = arg_cmd + " ";
82       if (sarge.exists("quotes")) {
83         whole_command = whole_command + "\"" + command + "\"";
84       } else {
85         whole_command += command;
86       }
87       system(whole_command.c_str());
88     }
89   }
90 }
91
92 ////////////////////////////////////////////////////////////////////////////////