From e38c3bce15e2f435052998e7555703a5f8d698c3 Mon Sep 17 00:00:00 2001 From: CallumAttryde Date: Wed, 19 Jun 2019 10:08:51 +0100 Subject: [PATCH] add ~/.history file for Shell, stores entire command log and loads recent commands into history buffer --- Shell/main.cpp | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/Shell/main.cpp b/Shell/main.cpp index a2f8080165..0e74828378 100644 --- a/Shell/main.cpp +++ b/Shell/main.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -528,6 +529,43 @@ static int run_command(const String& cmd) return return_value; } +CFile get_history_file() +{ + StringBuilder sb; + sb.append(g.home); + sb.append("/.history"); + CFile f(sb.to_string()); + if (!f.open(CIODevice::ReadWrite)) { + fprintf(stderr, "Error opening file '%s': '%s'\n", f.filename().characters(), f.error_string()); + exit(1); + } + return f; +} + +void load_history() +{ + CFile history_file = get_history_file(); + while (history_file.can_read_line()) { + const auto&b = history_file.read_line(1024); + // skip the newline and terminating bytes + editor.add_to_history(String(reinterpret_cast(b.pointer()), b.size() - 2)); + } +} + +void save_history() +{ + CFile history_file = get_history_file(); + for (const auto& line : editor.history()) { + history_file.write(line); + history_file.write("\n"); + } +} + +void handle_sighup(int) +{ + save_history(); +} + int main(int argc, char** argv) { g.uid = getuid(); @@ -544,6 +582,15 @@ int main(int argc, char** argv) assert(rc == 0); } + { + struct sigaction sa; + sa.sa_handler = handle_sighup; + sa.sa_flags = 0; + sa.sa_mask = 0; + int rc = sigaction(SIGHUP, &sa, nullptr); + assert(rc == 0); + } + int rc = gethostname(g.hostname, sizeof(g.hostname)); if (rc < 0) perror("gethostname"); @@ -573,6 +620,9 @@ int main(int argc, char** argv) free(cwd); } + load_history(); + atexit(save_history); + for (;;) { prompt(); auto line = editor.get_line();