main.cpp 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "Shell.h"
  7. #include <LibCore/ArgsParser.h>
  8. #include <LibCore/Event.h>
  9. #include <LibCore/EventLoop.h>
  10. #include <LibCore/File.h>
  11. #include <LibCore/System.h>
  12. #include <LibMain/Main.h>
  13. #include <signal.h>
  14. #include <stdio.h>
  15. #include <string.h>
  16. #include <unistd.h>
  17. RefPtr<Line::Editor> editor;
  18. Shell::Shell* s_shell;
  19. ErrorOr<int> serenity_main(Main::Arguments arguments)
  20. {
  21. Core::EventLoop loop;
  22. Core::EventLoop::register_signal(SIGINT, [](int) {
  23. s_shell->kill_job(s_shell->current_job(), SIGINT);
  24. });
  25. Core::EventLoop::register_signal(SIGWINCH, [](int) {
  26. s_shell->kill_job(s_shell->current_job(), SIGWINCH);
  27. });
  28. Core::EventLoop::register_signal(SIGTTIN, [](int) {});
  29. Core::EventLoop::register_signal(SIGTTOU, [](int) {});
  30. Core::EventLoop::register_signal(SIGHUP, [](int) {
  31. for (auto& it : s_shell->jobs)
  32. s_shell->kill_job(it.value.ptr(), SIGHUP);
  33. s_shell->editor()->save_history(s_shell->get_history_path());
  34. });
  35. TRY(Core::System::pledge("stdio rpath wpath cpath proc exec tty sigaction unix fattr"));
  36. RefPtr<::Shell::Shell> shell;
  37. bool attempt_interactive = false;
  38. auto initialize = [&] {
  39. editor = Line::Editor::construct();
  40. editor->initialize();
  41. shell = Shell::Shell::construct(*editor, attempt_interactive);
  42. s_shell = shell.ptr();
  43. s_shell->setup_signals();
  44. shell->termios = editor->termios();
  45. shell->default_termios = editor->default_termios();
  46. editor->on_display_refresh = [&](auto& editor) {
  47. editor.strip_styles();
  48. if (shell->should_format_live()) {
  49. auto line = editor.line();
  50. ssize_t cursor = editor.cursor();
  51. editor.clear_line();
  52. editor.insert(shell->format(line, cursor));
  53. if (cursor >= 0)
  54. editor.set_cursor(cursor);
  55. }
  56. shell->highlight(editor);
  57. };
  58. editor->on_tab_complete = [&](const Line::Editor&) {
  59. return shell->complete();
  60. };
  61. editor->on_paste = [&](Utf32View data, Line::Editor& editor) {
  62. auto line = editor.line(editor.cursor());
  63. Shell::Parser parser(line, false);
  64. auto ast = parser.parse();
  65. if (!ast) {
  66. editor.insert(data);
  67. return;
  68. }
  69. auto hit_test_result = ast->hit_test_position(editor.cursor());
  70. // If the argument isn't meant to be an entire command, escape it.
  71. // This allows copy-pasting entire commands where commands are expected, and otherwise escapes everything.
  72. auto should_escape = false;
  73. if (!hit_test_result.matching_node && hit_test_result.closest_command_node) {
  74. // There's *some* command, but our cursor is immediate after it
  75. should_escape = editor.cursor() >= hit_test_result.closest_command_node->position().end_offset;
  76. hit_test_result.matching_node = hit_test_result.closest_command_node;
  77. } else if (hit_test_result.matching_node && hit_test_result.closest_command_node) {
  78. // There's a command, and we're at the end of or in the middle of some node.
  79. auto leftmost_literal = hit_test_result.closest_command_node->leftmost_trivial_literal();
  80. if (leftmost_literal)
  81. should_escape = !hit_test_result.matching_node->position().contains(leftmost_literal->position().start_offset);
  82. }
  83. if (should_escape) {
  84. String escaped_string;
  85. Optional<char> trivia {};
  86. bool starting_trivia_already_provided = false;
  87. auto escape_mode = Shell::Shell::EscapeMode::Bareword;
  88. if (hit_test_result.matching_node->kind() == Shell::AST::Node::Kind::StringLiteral) {
  89. // If we're pasting in a string literal, make sure to only consider that specific escape mode
  90. auto* node = static_cast<Shell::AST::StringLiteral const*>(hit_test_result.matching_node.ptr());
  91. switch (node->enclosure_type()) {
  92. case Shell::AST::StringLiteral::EnclosureType::None:
  93. break;
  94. case Shell::AST::StringLiteral::EnclosureType::SingleQuotes:
  95. escape_mode = Shell::Shell::EscapeMode::SingleQuotedString;
  96. trivia = '\'';
  97. starting_trivia_already_provided = true;
  98. break;
  99. case Shell::AST::StringLiteral::EnclosureType::DoubleQuotes:
  100. escape_mode = Shell::Shell::EscapeMode::DoubleQuotedString;
  101. trivia = '"';
  102. starting_trivia_already_provided = true;
  103. break;
  104. }
  105. }
  106. if (starting_trivia_already_provided) {
  107. escaped_string = shell->escape_token(data, escape_mode);
  108. } else {
  109. escaped_string = shell->escape_token(data, Shell::Shell::EscapeMode::Bareword);
  110. if (auto string = shell->escape_token(data, Shell::Shell::EscapeMode::SingleQuotedString); string.length() + 2 < escaped_string.length()) {
  111. escaped_string = move(string);
  112. trivia = '\'';
  113. }
  114. if (auto string = shell->escape_token(data, Shell::Shell::EscapeMode::DoubleQuotedString); string.length() + 2 < escaped_string.length()) {
  115. escaped_string = move(string);
  116. trivia = '"';
  117. }
  118. }
  119. if (trivia.has_value() && !starting_trivia_already_provided)
  120. editor.insert(*trivia);
  121. editor.insert(escaped_string);
  122. if (trivia.has_value())
  123. editor.insert(*trivia);
  124. } else {
  125. editor.insert(data);
  126. }
  127. };
  128. };
  129. StringView command_to_run = {};
  130. StringView file_to_read_from = {};
  131. Vector<String> script_args;
  132. bool skip_rc_files = false;
  133. char const* format = nullptr;
  134. bool should_format_live = false;
  135. bool keep_open = false;
  136. Core::ArgsParser parser;
  137. parser.add_option(command_to_run, "String to read commands from", "command-string", 'c', "command-string");
  138. parser.add_option(skip_rc_files, "Skip running shellrc files", "skip-shellrc", 0);
  139. parser.add_option(format, "Format the given file into stdout and exit", "format", 0, "file");
  140. parser.add_option(should_format_live, "Enable live formatting", "live-formatting", 'f');
  141. parser.add_option(keep_open, "Keep the shell open after running the specified command or file", "keep-open", 0);
  142. parser.add_positional_argument(file_to_read_from, "File to read commands from", "file", Core::ArgsParser::Required::No);
  143. parser.add_positional_argument(script_args, "Extra arguments to pass to the script (via $* and co)", "argument", Core::ArgsParser::Required::No);
  144. parser.set_stop_on_first_non_option(true);
  145. parser.parse(arguments);
  146. if (format) {
  147. auto file = TRY(Core::File::open(format, Core::OpenMode::ReadOnly));
  148. initialize();
  149. ssize_t cursor = -1;
  150. puts(shell->format(file->read_all(), cursor).characters());
  151. return 0;
  152. }
  153. auto pid = getpid();
  154. if (auto sid = getsid(pid); sid == 0) {
  155. if (auto res = Core::System::setsid(); res.is_error())
  156. dbgln("{}", res.release_error());
  157. } else if (sid != pid) {
  158. if (getpgid(pid) != pid) {
  159. if (auto res = Core::System::setpgid(pid, sid); res.is_error())
  160. dbgln("{}", res.release_error());
  161. if (auto res = Core::System::setsid(); res.is_error())
  162. dbgln("{}", res.release_error());
  163. }
  164. }
  165. auto execute_file = !file_to_read_from.is_empty() && "-"sv != file_to_read_from;
  166. attempt_interactive = !execute_file;
  167. if (keep_open && command_to_run.is_empty() && !execute_file) {
  168. warnln("Option --keep-open can only be used in combination with -c or when specifying a file to execute.");
  169. return 1;
  170. }
  171. initialize();
  172. shell->set_live_formatting(should_format_live);
  173. shell->current_script = arguments.strings[0];
  174. if (!skip_rc_files) {
  175. auto run_rc_file = [&](auto& name) {
  176. String file_path = name;
  177. if (file_path.starts_with('~'))
  178. file_path = shell->expand_tilde(file_path);
  179. if (Core::File::exists(file_path)) {
  180. shell->run_file(file_path, false);
  181. }
  182. };
  183. run_rc_file(Shell::Shell::global_init_file_path);
  184. run_rc_file(Shell::Shell::local_init_file_path);
  185. shell->cache_path();
  186. }
  187. shell->set_local_variable("ARGV", adopt_ref(*new Shell::AST::ListValue(move(script_args))));
  188. if (!command_to_run.is_empty()) {
  189. auto result = shell->run_command(command_to_run);
  190. if (!keep_open)
  191. return result;
  192. }
  193. if (execute_file) {
  194. auto result = shell->run_file(file_to_read_from);
  195. if (!keep_open) {
  196. if (result)
  197. return 0;
  198. return 1;
  199. }
  200. }
  201. shell->add_child(*editor);
  202. Core::EventLoop::current().post_event(*shell, make<Core::CustomEvent>(Shell::Shell::ShellEventType::ReadLine));
  203. return loop.exec();
  204. }