From 0b57cdff82174af573fdd668d1bff36d41712b79 Mon Sep 17 00:00:00 2001 From: AnotherTest Date: Sun, 13 Sep 2020 13:59:34 +0430 Subject: [PATCH] Shell: Add support for $0,$1,... --- Shell/Shell.cpp | 28 ++++++++++++++++++++++++++++ Shell/Shell.h | 3 +++ Shell/main.cpp | 2 ++ 3 files changed, 33 insertions(+) diff --git a/Shell/Shell.cpp b/Shell/Shell.cpp index b3b406e0e5..057c1357c1 100644 --- a/Shell/Shell.cpp +++ b/Shell/Shell.cpp @@ -333,6 +333,33 @@ RefPtr Shell::lookup_local_variable(const String& name) if (auto* frame = find_frame_containing_local_variable(name)) return frame->local_variables.get(name).value(); + if (auto index = name.to_uint(); index.has_value()) + return get_argument(index.value()); + + return nullptr; +} + +RefPtr Shell::get_argument(size_t index) +{ + if (index == 0) + return adopt(*new AST::StringValue(current_script)); + + --index; + if (auto argv = lookup_local_variable("ARGV")) { + if (argv->is_list_without_resolution()) { + AST::ListValue* list = static_cast(argv.ptr()); + if (list->values().size() <= index) + return nullptr; + + return list->values().at(index); + } + + if (index != 0) + return nullptr; + + return argv; + } + return nullptr; } @@ -750,6 +777,7 @@ NonnullRefPtrVector Shell::run_commands(Vector& commands) bool Shell::run_file(const String& filename, bool explicitly_invoked) { + TemporaryChange script_change { current_script, filename }; auto file_result = Core::File::open(filename, Core::File::ReadOnly); if (file_result.is_error()) { if (explicitly_invoked) diff --git a/Shell/Shell.h b/Shell/Shell.h index 9f168f8116..a95d73aafd 100644 --- a/Shell/Shell.h +++ b/Shell/Shell.h @@ -92,6 +92,7 @@ public: String resolve_path(String) const; String resolve_alias(const String&) const; + RefPtr get_argument(size_t); RefPtr lookup_local_variable(const String&); String local_variable_or(const String&, const String&); void set_local_variable(const String&, RefPtr); @@ -170,6 +171,8 @@ public: HashMap> jobs; Vector cached_path; + String current_script; + enum ShellEventType { ReadLine, }; diff --git a/Shell/main.cpp b/Shell/main.cpp index 83877ccfad..5961086680 100644 --- a/Shell/main.cpp +++ b/Shell/main.cpp @@ -209,6 +209,8 @@ int main(int argc, char** argv) parser.parse(argc, argv); + shell->current_script = argv[0]; + if (!skip_rc_files) { auto run_rc_file = [&](auto& name) { String file_path = name;