From cfa051322666f1a1cd26616ad5ac4ca83eae6f52 Mon Sep 17 00:00:00 2001 From: Robert Bendun Date: Tue, 11 Oct 2022 10:06:42 +0200 Subject: [PATCH] :load command inside interactive mode --- musique/main.cc | 49 ++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 44 insertions(+), 5 deletions(-) diff --git a/musique/main.cc b/musique/main.cc index 6024f8b..9e0ef78 100644 --- a/musique/main.cc +++ b/musique/main.cc @@ -95,6 +95,7 @@ void print_repl_help() ":help - prints this help message\n" ":! - allows for execution of any shell command\n" ":clear - clears screen\n" + ":load - loads file into Musique session\n" ; } @@ -224,6 +225,46 @@ bool is_tty() #endif } +/// Handles commands inside REPL session (those starting with ':') +/// +/// Returns if one of command matched +static Result handle_repl_session_commands(std::string_view command, Runner &runner) +{ + if (command == "exit") { + std::exit(0); + } + + if (command == "clear") { + std::cout << "\x1b[1;1H\x1b[2J" << std::flush; + return true; + } + + if (command.starts_with('!')) { + // TODO Maybe use different shell invoking mechanism then system + // since on Windows it uses cmd.exe and not powershell which is + // strictly superior + Ignore(system(command.data() + 1)); + return true; + } + + if (command == "help") { + print_repl_help(); + return true; + } + + if (command.starts_with("load")) { + command = command.substr("load"sv.size()); + trim(command); + std::ifstream source_file{std::string(command)}; + eternal_sources.emplace_back(std::istreambuf_iterator(source_file), std::istreambuf_iterator()); + Lines::the.add_file(std::string(command), eternal_sources.back()); + Try(runner.run(eternal_sources.back(), command)); + return true; + } + + return false; +} + /// Fancy main that supports Result forwarding on error (Try macro) static std::optional Main(std::span args) { @@ -371,11 +412,9 @@ static std::optional Main(std::span args) if (command.starts_with(':')) { command.remove_prefix(1); - if (command == "exit") { break; } - if (command == "clear") { std::cout << "\x1b[1;1H\x1b[2J" << std::flush; continue; } - if (command.starts_with('!')) { Ignore(system(command.data() + 1)); continue; } - if (command == "help") { print_repl_help(); continue; } - std::cerr << "musique: error: unrecognized REPL command '" << command << '\'' << std::endl; + if (!Try(handle_repl_session_commands(command, runner))) { + std::cerr << "musique: error: unrecognized REPL command '" << command << '\'' << std::endl; + } continue; }