Skip to content

Commit

Permalink
Shell: Add support for $0,$1,...
Browse files Browse the repository at this point in the history
  • Loading branch information
alimpfard authored and awesomekling committed Sep 14, 2020
1 parent 2f97590 commit 0b57cdf
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
28 changes: 28 additions & 0 deletions Shell/Shell.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,33 @@ RefPtr<AST::Value> 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<AST::Value> 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<AST::ListValue*>(argv.ptr());
if (list->values().size() <= index)
return nullptr;

return list->values().at(index);
}

if (index != 0)
return nullptr;

return argv;
}

return nullptr;
}

Expand Down Expand Up @@ -750,6 +777,7 @@ NonnullRefPtrVector<Job> Shell::run_commands(Vector<AST::Command>& 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)
Expand Down
3 changes: 3 additions & 0 deletions Shell/Shell.h
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ class Shell : public Core::Object {
String resolve_path(String) const;
String resolve_alias(const String&) const;

RefPtr<AST::Value> get_argument(size_t);
RefPtr<AST::Value> lookup_local_variable(const String&);
String local_variable_or(const String&, const String&);
void set_local_variable(const String&, RefPtr<AST::Value>);
Expand Down Expand Up @@ -170,6 +171,8 @@ class Shell : public Core::Object {
HashMap<u64, NonnullRefPtr<Job>> jobs;
Vector<String, 256> cached_path;

String current_script;

enum ShellEventType {
ReadLine,
};
Expand Down
2 changes: 2 additions & 0 deletions Shell/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down

0 comments on commit 0b57cdf

Please sign in to comment.