/src/serenity/Userland/Libraries/LibShell/Builtin.cpp
Line | Count | Source (jump to first uncovered line) |
1 | | /* |
2 | | * Copyright (c) 2020-2023, the SerenityOS developers. |
3 | | * |
4 | | * SPDX-License-Identifier: BSD-2-Clause |
5 | | */ |
6 | | |
7 | | #include "AST.h" |
8 | | #include "Formatter.h" |
9 | | #include "PosixParser.h" |
10 | | #include "Shell.h" |
11 | | #include <AK/ByteString.h> |
12 | | #include <AK/LexicalPath.h> |
13 | | #include <AK/ScopeGuard.h> |
14 | | #include <AK/Statistics.h> |
15 | | #include <LibCore/ArgsParser.h> |
16 | | #include <LibCore/Environment.h> |
17 | | #include <LibCore/EventLoop.h> |
18 | | #include <LibCore/File.h> |
19 | | #include <LibCore/System.h> |
20 | | #include <LibFileSystem/FileSystem.h> |
21 | | #include <errno.h> |
22 | | #include <inttypes.h> |
23 | | #include <limits.h> |
24 | | #include <signal.h> |
25 | | #include <sys/wait.h> |
26 | | #include <unistd.h> |
27 | | |
28 | | extern char** environ; |
29 | | |
30 | | namespace Shell { |
31 | | |
32 | | ErrorOr<int> Shell::builtin_noop(Main::Arguments) |
33 | 0 | { |
34 | 0 | return 0; |
35 | 0 | } |
36 | | |
37 | | ErrorOr<int> Shell::builtin_dump(Main::Arguments arguments) |
38 | 0 | { |
39 | 0 | bool posix = false; |
40 | 0 | StringView source; |
41 | |
|
42 | 0 | Core::ArgsParser parser; |
43 | 0 | parser.add_positional_argument(source, "Shell code to parse and dump", "source"); |
44 | 0 | parser.add_option(posix, "Use the POSIX parser", "posix", 'p'); |
45 | |
|
46 | 0 | if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage)) |
47 | 0 | return 1; |
48 | | |
49 | 0 | TRY((posix ? Posix::Parser { source }.parse() : Parser { source }.parse())->dump(0)); |
50 | 0 | return 0; |
51 | 0 | } |
52 | | |
53 | | enum FollowSymlinks { |
54 | | Yes, |
55 | | No |
56 | | }; |
57 | | |
58 | | static Vector<ByteString> find_matching_executables_in_path(StringView filename, FollowSymlinks follow_symlinks = FollowSymlinks::No, Optional<StringView> force_path = {}) |
59 | 0 | { |
60 | | // Edge cases in which there are guaranteed no solutions |
61 | 0 | if (filename.is_empty() || filename.contains('/')) |
62 | 0 | return {}; |
63 | | |
64 | 0 | char const* path_str = getenv("PATH"); |
65 | 0 | auto path = force_path.value_or(DEFAULT_PATH_SV); |
66 | 0 | if (path_str != nullptr && !force_path.has_value()) |
67 | 0 | path = { path_str, strlen(path_str) }; |
68 | |
|
69 | 0 | Vector<ByteString> executables; |
70 | 0 | auto directories = path.split_view(':'); |
71 | 0 | for (auto directory : directories) { |
72 | 0 | auto file = ByteString::formatted("{}/{}", directory, filename); |
73 | |
|
74 | 0 | if (follow_symlinks == FollowSymlinks::Yes) { |
75 | 0 | auto path_or_error = FileSystem::read_link(file); |
76 | 0 | if (!path_or_error.is_error()) |
77 | 0 | file = path_or_error.release_value(); |
78 | 0 | } |
79 | 0 | if (!Core::System::access(file, X_OK).is_error()) |
80 | 0 | executables.append(move(file)); |
81 | 0 | } |
82 | |
|
83 | 0 | return executables; |
84 | 0 | } |
85 | | |
86 | | ErrorOr<int> Shell::builtin_where(Main::Arguments arguments) |
87 | 0 | { |
88 | 0 | Vector<StringView> values_to_look_up; |
89 | 0 | bool do_only_path_search { false }; |
90 | 0 | bool do_follow_symlinks { false }; |
91 | 0 | bool do_print_only_type { false }; |
92 | |
|
93 | 0 | Core::ArgsParser parser; |
94 | 0 | parser.add_positional_argument(values_to_look_up, "List of shell builtins, aliases or executables", "arguments"); |
95 | 0 | parser.add_option(do_only_path_search, "Search only for executables in the PATH environment variable", "path-only", 'p'); |
96 | 0 | parser.add_option(do_follow_symlinks, "Follow symlinks and print the symlink free path", "follow-symlink", 's'); |
97 | 0 | parser.add_option(do_print_only_type, "Print the argument type instead of a human readable description", "type", 'w'); |
98 | |
|
99 | 0 | if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage)) |
100 | 0 | return 1; |
101 | | |
102 | 0 | auto const look_up_alias = [do_only_path_search, &m_aliases = this->m_aliases](StringView alias) -> Optional<ByteString> { |
103 | 0 | if (do_only_path_search) |
104 | 0 | return {}; |
105 | 0 | return m_aliases.get(alias).copy(); |
106 | 0 | }; |
107 | |
|
108 | 0 | auto const look_up_builtin = [do_only_path_search](StringView builtin) -> Optional<ByteString> { |
109 | 0 | if (do_only_path_search) |
110 | 0 | return {}; |
111 | 0 | for (auto const& _builtin : builtin_names) { |
112 | 0 | if (_builtin == builtin) { |
113 | 0 | return builtin; |
114 | 0 | } |
115 | 0 | } |
116 | 0 | return {}; |
117 | 0 | }; |
118 | |
|
119 | 0 | bool at_least_one_succeded { false }; |
120 | 0 | for (auto const& argument : values_to_look_up) { |
121 | 0 | auto const alias = look_up_alias(argument); |
122 | 0 | if (alias.has_value()) { |
123 | 0 | if (do_print_only_type) |
124 | 0 | outln("{}: alias", argument); |
125 | 0 | else |
126 | 0 | outln("{}: aliased to {}", argument, alias.value()); |
127 | 0 | at_least_one_succeded = true; |
128 | 0 | } |
129 | |
|
130 | 0 | auto const builtin = look_up_builtin(argument); |
131 | 0 | if (builtin.has_value()) { |
132 | 0 | if (do_print_only_type) |
133 | 0 | outln("{}: builtin", builtin.value()); |
134 | 0 | else |
135 | 0 | outln("{}: shell built-in command", builtin.value()); |
136 | 0 | at_least_one_succeded = true; |
137 | 0 | } |
138 | |
|
139 | 0 | auto const executables = find_matching_executables_in_path(argument, do_follow_symlinks ? FollowSymlinks::Yes : FollowSymlinks::No); |
140 | 0 | for (auto const& path : executables) { |
141 | 0 | if (do_print_only_type) |
142 | 0 | outln("{}: command", argument); |
143 | 0 | else |
144 | 0 | outln(path); |
145 | 0 | at_least_one_succeded = true; |
146 | 0 | } |
147 | 0 | if (!at_least_one_succeded) |
148 | 0 | warnln("{} not found", argument); |
149 | 0 | } |
150 | 0 | return at_least_one_succeded ? 0 : 1; |
151 | 0 | } |
152 | | |
153 | | ErrorOr<int> Shell::builtin_reset(Main::Arguments) |
154 | 0 | { |
155 | 0 | destroy(); |
156 | 0 | initialize(m_is_interactive); |
157 | | |
158 | | // NOTE: As the last step before returning, clear (flush) the shell text entirely. |
159 | 0 | fprintf(stderr, "\033[3J\033[H\033[2J"); |
160 | 0 | fflush(stderr); |
161 | 0 | return 0; |
162 | 0 | } |
163 | | |
164 | | ErrorOr<int> Shell::builtin_alias(Main::Arguments arguments) |
165 | 0 | { |
166 | 0 | Vector<ByteString> aliases; |
167 | |
|
168 | 0 | Core::ArgsParser parser; |
169 | 0 | parser.add_positional_argument(aliases, "List of name[=values]'s", "name[=value]", Core::ArgsParser::Required::No); |
170 | |
|
171 | 0 | if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage)) |
172 | 0 | return 1; |
173 | | |
174 | 0 | if (aliases.is_empty()) { |
175 | 0 | for (auto& alias : m_aliases) |
176 | 0 | printf("%s=%s\n", escape_token(alias.key).characters(), escape_token(alias.value).characters()); |
177 | 0 | return 0; |
178 | 0 | } |
179 | | |
180 | 0 | bool fail = false; |
181 | 0 | for (auto& argument : aliases) { |
182 | 0 | auto parts = argument.split_limit('=', 2, SplitBehavior::KeepEmpty); |
183 | 0 | if (parts.size() == 1) { |
184 | 0 | auto alias = m_aliases.get(parts[0]); |
185 | 0 | if (alias.has_value()) { |
186 | 0 | printf("%s=%s\n", escape_token(parts[0]).characters(), escape_token(alias.value()).characters()); |
187 | 0 | } else { |
188 | 0 | fail = true; |
189 | 0 | } |
190 | 0 | } else { |
191 | 0 | m_aliases.set(parts[0], parts[1]); |
192 | 0 | add_entry_to_cache({ RunnablePath::Kind::Alias, parts[0] }); |
193 | 0 | } |
194 | 0 | } |
195 | |
|
196 | 0 | return fail ? 1 : 0; |
197 | 0 | } |
198 | | |
199 | | ErrorOr<int> Shell::builtin_unalias(Main::Arguments arguments) |
200 | 0 | { |
201 | 0 | bool remove_all { false }; |
202 | 0 | Vector<ByteString> aliases; |
203 | |
|
204 | 0 | Core::ArgsParser parser; |
205 | 0 | parser.set_general_help("Remove alias from the list of aliases"); |
206 | 0 | parser.add_option(remove_all, "Remove all aliases", nullptr, 'a'); |
207 | 0 | parser.add_positional_argument(aliases, "List of aliases to remove", "alias", Core::ArgsParser::Required::Yes); |
208 | |
|
209 | 0 | if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage)) |
210 | 0 | return 1; |
211 | | |
212 | 0 | if (remove_all) { |
213 | 0 | m_aliases.clear(); |
214 | 0 | cache_path(); |
215 | 0 | return 0; |
216 | 0 | } |
217 | | |
218 | 0 | bool failed { false }; |
219 | 0 | for (auto& argument : aliases) { |
220 | 0 | if (!m_aliases.contains(argument)) { |
221 | 0 | warnln("unalias: {}: alias not found", argument); |
222 | 0 | failed = true; |
223 | 0 | continue; |
224 | 0 | } |
225 | 0 | m_aliases.remove(argument); |
226 | 0 | remove_entry_from_cache(argument); |
227 | 0 | } |
228 | |
|
229 | 0 | return failed ? 1 : 0; |
230 | 0 | } |
231 | | |
232 | | ErrorOr<int> Shell::builtin_break(Main::Arguments arguments) |
233 | 0 | { |
234 | 0 | unsigned count = 1; |
235 | |
|
236 | 0 | Core::ArgsParser parser; |
237 | 0 | parser.add_positional_argument(count, "Number of loops to 'break' out of", "count", Core::ArgsParser::Required::No); |
238 | |
|
239 | 0 | if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage)) |
240 | 0 | return 1; |
241 | | |
242 | 0 | if (count != 1) { |
243 | 0 | raise_error(ShellError::EvaluatedSyntaxError, "break: count must be equal to 1 (NYI)"); |
244 | 0 | return 1; |
245 | 0 | } |
246 | | |
247 | 0 | raise_error(ShellError::InternalControlFlowBreak, "POSIX break"); |
248 | |
|
249 | 0 | return 0; |
250 | 0 | } |
251 | | |
252 | | ErrorOr<int> Shell::builtin_continue(Main::Arguments arguments) |
253 | 0 | { |
254 | 0 | unsigned count = 1; |
255 | |
|
256 | 0 | Core::ArgsParser parser; |
257 | 0 | parser.add_positional_argument(count, "Number of loops to 'continue' out of", "count", Core::ArgsParser::Required::No); |
258 | |
|
259 | 0 | if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage)) |
260 | 0 | return 1; |
261 | | |
262 | 0 | if (count != 1) { |
263 | 0 | raise_error(ShellError::EvaluatedSyntaxError, "continue: count must be equal to 1 (NYI)"); |
264 | 0 | return 1; |
265 | 0 | } |
266 | | |
267 | 0 | raise_error(ShellError::InternalControlFlowContinue, "POSIX continue"); |
268 | |
|
269 | 0 | return 0; |
270 | 0 | } |
271 | | |
272 | | ErrorOr<int> Shell::builtin_return(Main::Arguments arguments) |
273 | 0 | { |
274 | 0 | int return_code = last_return_code.value_or(0); |
275 | |
|
276 | 0 | Core::ArgsParser parser; |
277 | 0 | parser.add_positional_argument(return_code, "Return code to return to the parent shell", "return-code", Core::ArgsParser::Required::No); |
278 | 0 | parser.set_general_help("Return from a function or source file"); |
279 | |
|
280 | 0 | if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage)) |
281 | 0 | return 1; |
282 | | |
283 | 0 | last_return_code = return_code & 0xff; |
284 | 0 | raise_error(ShellError::InternalControlFlowReturn, "POSIX return"); |
285 | |
|
286 | 0 | return 0; |
287 | 0 | } |
288 | | |
289 | | ErrorOr<int> Shell::builtin_bg(Main::Arguments arguments) |
290 | 0 | { |
291 | 0 | int job_id = -1; |
292 | 0 | bool is_pid = false; |
293 | |
|
294 | 0 | Core::ArgsParser parser; |
295 | 0 | parser.add_positional_argument(Core::ArgsParser::Arg { |
296 | 0 | .help_string = "Job ID or Jobspec to run in background", |
297 | 0 | .name = "job-id", |
298 | 0 | .min_values = 0, |
299 | 0 | .max_values = 1, |
300 | 0 | .accept_value = [&](StringView value) -> bool { |
301 | | // Check if it's a pid (i.e. literal integer) |
302 | 0 | if (auto number = value.to_number<unsigned>(); number.has_value()) { |
303 | 0 | job_id = number.value(); |
304 | 0 | is_pid = true; |
305 | 0 | return true; |
306 | 0 | } |
307 | | |
308 | | // Check if it's a jobspec |
309 | 0 | if (auto id = resolve_job_spec(value); id.has_value()) { |
310 | 0 | job_id = id.value(); |
311 | 0 | is_pid = false; |
312 | 0 | return true; |
313 | 0 | } |
314 | | |
315 | 0 | return false; |
316 | 0 | } }); |
317 | |
|
318 | 0 | if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage)) |
319 | 0 | return 1; |
320 | | |
321 | 0 | if (job_id == -1 && !jobs.is_empty()) |
322 | 0 | job_id = find_last_job_id(); |
323 | |
|
324 | 0 | auto* job = const_cast<Job*>(find_job(job_id, is_pid)); |
325 | |
|
326 | 0 | if (!job) { |
327 | 0 | if (job_id == -1) { |
328 | 0 | warnln("bg: No current job"); |
329 | 0 | } else { |
330 | 0 | warnln("bg: Job with id/pid {} not found", job_id); |
331 | 0 | } |
332 | 0 | return 1; |
333 | 0 | } |
334 | | |
335 | 0 | job->set_running_in_background(true); |
336 | 0 | job->set_should_announce_exit(true); |
337 | 0 | job->set_shell_did_continue(true); |
338 | |
|
339 | 0 | dbgln("Resuming {} ({})", job->pid(), job->cmd()); |
340 | 0 | warnln("Resuming job {} - {}", job->job_id(), job->cmd()); |
341 | | |
342 | | // Try using the PGID, but if that fails, just use the PID. |
343 | 0 | if (killpg(job->pgid(), SIGCONT) < 0) { |
344 | 0 | if (kill(job->pid(), SIGCONT) < 0) { |
345 | 0 | perror("kill"); |
346 | 0 | return 1; |
347 | 0 | } |
348 | 0 | } |
349 | | |
350 | 0 | return 0; |
351 | 0 | } |
352 | | |
353 | | ErrorOr<String> Shell::serialize_function_definition(ShellFunction const& fn) const |
354 | 0 | { |
355 | 0 | StringBuilder builder; |
356 | 0 | builder.append(fn.name); |
357 | 0 | builder.append('('); |
358 | 0 | for (size_t i = 0; i < fn.arguments.size(); i++) { |
359 | 0 | builder.append(fn.arguments[i]); |
360 | 0 | if (i != fn.arguments.size() - 1) |
361 | 0 | builder.append(' '); |
362 | 0 | } |
363 | 0 | builder.append(") {\n"sv); |
364 | 0 | if (fn.body) { |
365 | 0 | auto formatter = Formatter(*fn.body); |
366 | 0 | builder.append(formatter.format()); |
367 | 0 | } |
368 | 0 | builder.append("\n}"sv); |
369 | |
|
370 | 0 | return builder.to_string(); |
371 | 0 | } |
372 | | |
373 | | ErrorOr<int> Shell::builtin_type(Main::Arguments arguments) |
374 | 0 | { |
375 | 0 | Vector<ByteString> commands; |
376 | 0 | bool dont_show_function_source = false; |
377 | |
|
378 | 0 | Core::ArgsParser parser; |
379 | 0 | parser.set_general_help("Display information about commands."); |
380 | 0 | parser.add_positional_argument(commands, "Command(s) to list info about", "command"); |
381 | 0 | parser.add_option(dont_show_function_source, "Do not show functions source.", "no-fn-source", 'f'); |
382 | |
|
383 | 0 | if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage)) |
384 | 0 | return 1; |
385 | | |
386 | 0 | bool something_not_found = false; |
387 | |
|
388 | 0 | for (auto& command : commands) { |
389 | | // check if it is an alias |
390 | 0 | if (auto alias = m_aliases.get(command); alias.has_value()) { |
391 | 0 | printf("%s is aliased to `%s`\n", escape_token(command).characters(), escape_token(alias.value()).characters()); |
392 | 0 | continue; |
393 | 0 | } |
394 | | |
395 | | // check if it is a function |
396 | 0 | if (auto function = m_functions.get(command); function.has_value()) { |
397 | 0 | auto fn = function.value(); |
398 | 0 | printf("%s is a function\n", command.characters()); |
399 | 0 | if (!dont_show_function_source) { |
400 | 0 | auto source = TRY(serialize_function_definition(fn)); |
401 | 0 | outln("{}", source); |
402 | 0 | } |
403 | 0 | continue; |
404 | 0 | } |
405 | | |
406 | | // check if its a builtin |
407 | 0 | if (has_builtin(command)) { |
408 | 0 | printf("%s is a shell builtin\n", command.characters()); |
409 | 0 | continue; |
410 | 0 | } |
411 | | |
412 | | // check if its an executable in PATH |
413 | 0 | auto fullpath = Core::System::resolve_executable_from_environment(command); |
414 | 0 | if (!fullpath.is_error()) { |
415 | 0 | printf("%s is %s\n", command.characters(), escape_token(fullpath.release_value()).characters()); |
416 | 0 | continue; |
417 | 0 | } |
418 | 0 | something_not_found = true; |
419 | 0 | printf("type: %s not found\n", command.characters()); |
420 | 0 | } |
421 | | |
422 | 0 | if (something_not_found) |
423 | 0 | return 1; |
424 | 0 | else |
425 | 0 | return 0; |
426 | 0 | } |
427 | | |
428 | | ErrorOr<int> Shell::builtin_cd(Main::Arguments arguments) |
429 | 0 | { |
430 | 0 | StringView arg_path; |
431 | |
|
432 | 0 | Core::ArgsParser parser; |
433 | 0 | parser.add_positional_argument(arg_path, "Path to change to", "path", Core::ArgsParser::Required::No); |
434 | |
|
435 | 0 | if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage)) |
436 | 0 | return 1; |
437 | | |
438 | 0 | ByteString new_path; |
439 | |
|
440 | 0 | if (arg_path.is_empty()) { |
441 | 0 | new_path = home; |
442 | 0 | } else { |
443 | 0 | if (arg_path == "-"sv) { |
444 | 0 | char* oldpwd = getenv("OLDPWD"); |
445 | 0 | if (oldpwd == nullptr) |
446 | 0 | return 1; |
447 | 0 | new_path = oldpwd; |
448 | 0 | } else { |
449 | 0 | new_path = arg_path; |
450 | 0 | } |
451 | 0 | } |
452 | | |
453 | 0 | auto const requested_path_is_absolute = !new_path.is_empty() && new_path.starts_with('/'); |
454 | 0 | auto real_path_or_error = FileSystem::real_path(new_path); |
455 | 0 | if (real_path_or_error.is_error()) { |
456 | 0 | warnln("Invalid path '{}'", new_path); |
457 | 0 | return 1; |
458 | 0 | } |
459 | 0 | auto real_path = real_path_or_error.release_value(); |
460 | |
|
461 | 0 | if (cd_history.is_empty() || cd_history.last() != real_path) |
462 | 0 | cd_history.enqueue(real_path); |
463 | |
|
464 | 0 | ByteString path_to_chdir; |
465 | 0 | if (!requested_path_is_absolute) |
466 | 0 | path_to_chdir = LexicalPath::relative_path(real_path, cwd); |
467 | 0 | else |
468 | 0 | path_to_chdir = real_path; |
469 | 0 | char const* path = path_to_chdir.characters(); |
470 | |
|
471 | 0 | Function<int(bool)> do_chdir = [&](bool tried_lexical_resolution) -> int { |
472 | 0 | int rc = chdir(path); |
473 | 0 | if (rc < 0) { |
474 | 0 | if (errno == ENOTDIR) { |
475 | 0 | warnln("Not a directory: {}", path); |
476 | 0 | } else { |
477 | 0 | if (!tried_lexical_resolution && !path_to_chdir.starts_with('/')) { |
478 | | // Resolve lexically then try again. |
479 | 0 | auto new_path = LexicalPath::join(cwd, path_to_chdir).string(); |
480 | 0 | if (new_path != path_to_chdir) { |
481 | 0 | real_path = move(new_path); |
482 | 0 | path = real_path.characters(); |
483 | 0 | return do_chdir(true); |
484 | 0 | } |
485 | 0 | } |
486 | 0 | warnln("chdir({}) failed: {}", path, strerror(errno)); |
487 | 0 | } |
488 | 0 | return 1; |
489 | 0 | } |
490 | 0 | return 0; |
491 | 0 | }; |
492 | 0 | if (do_chdir(false) != 0) |
493 | 0 | return 1; |
494 | | |
495 | 0 | setenv("OLDPWD", cwd.characters(), 1); |
496 | 0 | cwd = move(real_path); |
497 | 0 | setenv("PWD", cwd.characters(), 1); |
498 | 0 | return 0; |
499 | 0 | } |
500 | | |
501 | | ErrorOr<int> Shell::builtin_cdh(Main::Arguments arguments) |
502 | 0 | { |
503 | 0 | int index = -1; |
504 | |
|
505 | 0 | Core::ArgsParser parser; |
506 | 0 | parser.add_positional_argument(index, "Index of the cd history entry (leave out for a list)", "index", Core::ArgsParser::Required::No); |
507 | |
|
508 | 0 | if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage)) |
509 | 0 | return 1; |
510 | | |
511 | 0 | if (index == -1) { |
512 | 0 | if (cd_history.is_empty()) { |
513 | 0 | warnln("cdh: no history available"); |
514 | 0 | return 0; |
515 | 0 | } |
516 | | |
517 | 0 | for (ssize_t i = cd_history.size() - 1; i >= 0; --i) |
518 | 0 | printf("%zu: %s\n", cd_history.size() - i, cd_history.at(i).characters()); |
519 | 0 | return 0; |
520 | 0 | } |
521 | | |
522 | 0 | if (index < 1 || (size_t)index > cd_history.size()) { |
523 | 0 | warnln("cdh: history index out of bounds: {} not in (0, {})", index, cd_history.size()); |
524 | 0 | return 1; |
525 | 0 | } |
526 | | |
527 | 0 | StringView path = cd_history.at(cd_history.size() - index); |
528 | 0 | StringView cd_args[] = { "cd"sv, path }; |
529 | 0 | return Shell::builtin_cd({ .argc = 0, .argv = 0, .strings = cd_args }); |
530 | 0 | } |
531 | | |
532 | | ErrorOr<int> Shell::builtin_command(Main::Arguments arguments) |
533 | 0 | { |
534 | 0 | bool describe = false; |
535 | 0 | bool describe_verbosely = false; |
536 | 0 | bool search_in_default_path = false; |
537 | 0 | Vector<StringView> commands_or_args; |
538 | |
|
539 | 0 | Core::ArgsParser parser; |
540 | 0 | parser.add_option(search_in_default_path, "default-path", "Use a default value for PATH", 'p'); |
541 | 0 | parser.add_option(describe, "describe", "Describe the file that would be executed", 'v'); |
542 | 0 | parser.add_option(describe_verbosely, "describe-verbosely", "Describe the file that would be executed more verbosely", 'V'); |
543 | 0 | parser.add_positional_argument(commands_or_args, "Arguments or command names to search for", "arg"); |
544 | 0 | parser.set_stop_on_first_non_option(true); |
545 | |
|
546 | 0 | if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage)) |
547 | 0 | return 1; |
548 | | |
549 | 0 | auto const look_up_builtin = [](StringView builtin) -> Optional<ByteString> { |
550 | 0 | for (auto const& _builtin : builtin_names) { |
551 | 0 | if (_builtin == builtin) { |
552 | 0 | return builtin; |
553 | 0 | } |
554 | 0 | } |
555 | 0 | return {}; |
556 | 0 | }; |
557 | |
|
558 | 0 | describe |= describe_verbosely; |
559 | 0 | if (!describe) { |
560 | 0 | AST::Command command; |
561 | 0 | TRY(command.argv.try_ensure_capacity(commands_or_args.size())); |
562 | 0 | for (auto& arg : commands_or_args) |
563 | 0 | command.argv.append(TRY(String::from_utf8(arg))); |
564 | | |
565 | 0 | auto commands = TRY(expand_aliases({ move(command) })); |
566 | | |
567 | 0 | int exit_code = 1; |
568 | 0 | for (auto& job : run_commands(commands)) { |
569 | 0 | block_on_job(job); |
570 | 0 | exit_code = job->exit_code(); |
571 | 0 | } |
572 | |
|
573 | 0 | return exit_code; |
574 | 0 | } |
575 | | |
576 | 0 | bool any_failed = false; |
577 | 0 | for (auto const& argument : commands_or_args) { |
578 | 0 | auto alias = m_aliases.get(argument); |
579 | 0 | if (alias.has_value()) { |
580 | 0 | if (describe_verbosely) |
581 | 0 | outln("{}: aliased to {}", argument, alias.value()); |
582 | 0 | else |
583 | 0 | outln("{}", alias.value()); |
584 | 0 | continue; |
585 | 0 | } |
586 | | |
587 | 0 | auto const builtin = look_up_builtin(argument); |
588 | 0 | if (builtin.has_value()) { |
589 | 0 | if (describe_verbosely) |
590 | 0 | outln("{}: shell built-in command", builtin.value()); |
591 | 0 | else |
592 | 0 | outln("{}", builtin.value()); |
593 | 0 | continue; |
594 | 0 | } |
595 | | |
596 | 0 | auto const executables = find_matching_executables_in_path(argument, FollowSymlinks::No, search_in_default_path ? DEFAULT_PATH_SV : Optional<StringView>()); |
597 | 0 | if (!executables.is_empty()) { |
598 | 0 | outln("{}", executables.first()); |
599 | 0 | continue; |
600 | 0 | } |
601 | | |
602 | 0 | if (describe_verbosely) |
603 | 0 | warnln("{} not found", argument); |
604 | 0 | any_failed = true; |
605 | 0 | } |
606 | |
|
607 | 0 | return any_failed ? 1 : 0; |
608 | 0 | } |
609 | | |
610 | | ErrorOr<int> Shell::builtin_dirs(Main::Arguments arguments) |
611 | 0 | { |
612 | | // The first directory in the stack is ALWAYS the current directory |
613 | 0 | directory_stack.at(0) = cwd.characters(); |
614 | |
|
615 | 0 | bool clear = false; |
616 | 0 | bool print = false; |
617 | 0 | bool number_when_printing = false; |
618 | 0 | char separator = ' '; |
619 | |
|
620 | 0 | Vector<ByteString> paths; |
621 | |
|
622 | 0 | Core::ArgsParser parser; |
623 | 0 | parser.add_option(clear, "Clear the directory stack", "clear", 'c'); |
624 | 0 | parser.add_option(print, "Print directory entries one per line", "print", 'p'); |
625 | 0 | parser.add_option(number_when_printing, "Number the directories in the stack when printing", "number", 'v'); |
626 | 0 | parser.add_positional_argument(paths, "Extra paths to put on the stack", "path", Core::ArgsParser::Required::No); |
627 | |
|
628 | 0 | if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage)) |
629 | 0 | return 1; |
630 | | |
631 | | // -v implies -p |
632 | 0 | print = print || number_when_printing; |
633 | |
|
634 | 0 | if (print) { |
635 | 0 | if (!paths.is_empty()) { |
636 | 0 | warnln("dirs: 'print' and 'number' are not allowed when any path is specified"); |
637 | 0 | return 1; |
638 | 0 | } |
639 | 0 | separator = '\n'; |
640 | 0 | } |
641 | | |
642 | 0 | if (clear) { |
643 | 0 | for (size_t i = 1; i < directory_stack.size(); i++) |
644 | 0 | directory_stack.remove(i); |
645 | 0 | } |
646 | |
|
647 | 0 | for (auto& path : paths) |
648 | 0 | directory_stack.append(path); |
649 | |
|
650 | 0 | if (print || (!clear && paths.is_empty())) { |
651 | 0 | int index = 0; |
652 | 0 | for (auto& directory : directory_stack) { |
653 | 0 | if (number_when_printing) |
654 | 0 | printf("%d ", index++); |
655 | 0 | print_path(directory); |
656 | 0 | fputc(separator, stdout); |
657 | 0 | } |
658 | 0 | } |
659 | |
|
660 | 0 | return 0; |
661 | 0 | } |
662 | | |
663 | | ErrorOr<int> Shell::builtin_eval(Main::Arguments arguments) |
664 | 0 | { |
665 | 0 | if (!m_in_posix_mode) { |
666 | 0 | warnln("eval: This shell is not in POSIX mode"); |
667 | 0 | return 1; |
668 | 0 | } |
669 | | |
670 | 0 | StringBuilder joined_arguments; |
671 | 0 | for (size_t i = 1; i < arguments.strings.size(); ++i) { |
672 | 0 | if (i != 1) |
673 | 0 | joined_arguments.append(' '); |
674 | 0 | joined_arguments.append(arguments.strings[i]); |
675 | 0 | } |
676 | |
|
677 | 0 | auto result = Posix::Parser { TRY(joined_arguments.to_string()) }.parse(); |
678 | 0 | if (!result) |
679 | 0 | return 1; |
680 | | |
681 | 0 | auto value = TRY(result->run(*this)); |
682 | 0 | if (value && value->is_job()) |
683 | 0 | block_on_job(static_cast<AST::JobValue*>(value.ptr())->job()); |
684 | |
|
685 | 0 | return last_return_code.value_or(0); |
686 | 0 | } |
687 | | |
688 | | ErrorOr<int> Shell::builtin_exec(Main::Arguments arguments) |
689 | 0 | { |
690 | 0 | if (arguments.strings.size() < 2) { |
691 | 0 | warnln("Shell: No command given to exec"); |
692 | 0 | return 1; |
693 | 0 | } |
694 | | |
695 | 0 | TRY(execute_process(arguments.strings.slice(1))); |
696 | | // NOTE: Won't get here. |
697 | 0 | return 0; |
698 | 0 | } |
699 | | |
700 | | ErrorOr<int> Shell::builtin_exit(Main::Arguments arguments) |
701 | 0 | { |
702 | 0 | int exit_code = 0; |
703 | 0 | Core::ArgsParser parser; |
704 | 0 | parser.add_positional_argument(exit_code, "Exit code", "code", Core::ArgsParser::Required::No); |
705 | 0 | if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage)) |
706 | 0 | return 1; |
707 | | |
708 | 0 | if (m_is_interactive) { |
709 | 0 | if (!jobs.is_empty()) { |
710 | 0 | if (!m_should_ignore_jobs_on_next_exit) { |
711 | 0 | warnln("Shell: You have {} active job{}, run 'exit' again to really exit.", jobs.size(), jobs.size() > 1 ? "s" : ""); |
712 | 0 | m_should_ignore_jobs_on_next_exit = true; |
713 | 0 | return 1; |
714 | 0 | } |
715 | 0 | } |
716 | 0 | } |
717 | 0 | stop_all_jobs(); |
718 | 0 | if (m_is_interactive) { |
719 | 0 | m_editor->save_history(get_history_path()); |
720 | 0 | printf("Good-bye!\n"); |
721 | 0 | } |
722 | 0 | exit(exit_code); |
723 | 0 | } |
724 | | |
725 | | ErrorOr<int> Shell::builtin_export(Main::Arguments arguments) |
726 | 0 | { |
727 | 0 | Vector<ByteString> vars; |
728 | |
|
729 | 0 | Core::ArgsParser parser; |
730 | 0 | parser.add_positional_argument(vars, "List of variable[=value]'s", "values", Core::ArgsParser::Required::No); |
731 | |
|
732 | 0 | if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage)) |
733 | 0 | return 1; |
734 | | |
735 | 0 | if (vars.is_empty()) { |
736 | 0 | for (auto entry : Core::Environment::entries()) |
737 | 0 | outln("{}", entry.full_entry); |
738 | 0 | return 0; |
739 | 0 | } |
740 | | |
741 | 0 | for (auto& value : vars) { |
742 | 0 | auto parts = value.split_limit('=', 2); |
743 | 0 | if (parts.is_empty()) { |
744 | 0 | warnln("Shell: Invalid export spec '{}', expected `variable=value' or `variable'", value); |
745 | 0 | return 1; |
746 | 0 | } |
747 | | |
748 | 0 | if (parts.size() == 1) { |
749 | 0 | auto value = TRY(look_up_local_variable(parts[0])); |
750 | 0 | if (value) { |
751 | 0 | auto values = TRY(const_cast<AST::Value&>(*value).resolve_as_list(*this)); |
752 | 0 | StringBuilder builder; |
753 | 0 | builder.join(' ', values); |
754 | 0 | parts.append(builder.to_byte_string()); |
755 | 0 | } else { |
756 | | // Ignore the export. |
757 | 0 | continue; |
758 | 0 | } |
759 | 0 | } |
760 | | |
761 | 0 | int setenv_return = setenv(parts[0].characters(), parts[1].characters(), 1); |
762 | |
|
763 | 0 | if (setenv_return != 0) { |
764 | 0 | perror("setenv"); |
765 | 0 | return 1; |
766 | 0 | } |
767 | | |
768 | 0 | if (parts[0] == "PATH") |
769 | 0 | cache_path(); |
770 | 0 | } |
771 | | |
772 | 0 | return 0; |
773 | 0 | } |
774 | | |
775 | | ErrorOr<int> Shell::builtin_glob(Main::Arguments arguments) |
776 | 0 | { |
777 | 0 | Vector<ByteString> globs; |
778 | 0 | Core::ArgsParser parser; |
779 | 0 | parser.add_positional_argument(globs, "Globs to resolve", "glob"); |
780 | |
|
781 | 0 | if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage)) |
782 | 0 | return 1; |
783 | | |
784 | 0 | for (auto& glob : globs) { |
785 | 0 | for (auto& expanded : TRY(expand_globs(glob, cwd))) |
786 | 0 | outln("{}", expanded); |
787 | 0 | } |
788 | |
|
789 | 0 | return 0; |
790 | 0 | } |
791 | | |
792 | | ErrorOr<int> Shell::builtin_fg(Main::Arguments arguments) |
793 | 0 | { |
794 | 0 | int job_id = -1; |
795 | 0 | bool is_pid = false; |
796 | |
|
797 | 0 | Core::ArgsParser parser; |
798 | 0 | parser.add_positional_argument(Core::ArgsParser::Arg { |
799 | 0 | .help_string = "Job ID or Jobspec to bring to foreground", |
800 | 0 | .name = "job-id", |
801 | 0 | .min_values = 0, |
802 | 0 | .max_values = 1, |
803 | 0 | .accept_value = [&](StringView value) -> bool { |
804 | | // Check if it's a pid (i.e. literal integer) |
805 | 0 | if (auto number = value.to_number<unsigned>(); number.has_value()) { |
806 | 0 | job_id = number.value(); |
807 | 0 | is_pid = true; |
808 | 0 | return true; |
809 | 0 | } |
810 | | |
811 | | // Check if it's a jobspec |
812 | 0 | if (auto id = resolve_job_spec(value); id.has_value()) { |
813 | 0 | job_id = id.value(); |
814 | 0 | is_pid = false; |
815 | 0 | return true; |
816 | 0 | } |
817 | | |
818 | 0 | return false; |
819 | 0 | } }); |
820 | |
|
821 | 0 | if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage)) |
822 | 0 | return 1; |
823 | | |
824 | 0 | if (job_id == -1 && !jobs.is_empty()) |
825 | 0 | job_id = find_last_job_id(); |
826 | |
|
827 | 0 | RefPtr<Job> job = find_job(job_id, is_pid); |
828 | |
|
829 | 0 | if (!job) { |
830 | 0 | if (job_id == -1) { |
831 | 0 | warnln("fg: No current job"); |
832 | 0 | } else { |
833 | 0 | warnln("fg: Job with id/pid {} not found", job_id); |
834 | 0 | } |
835 | 0 | return 1; |
836 | 0 | } |
837 | | |
838 | 0 | job->set_running_in_background(false); |
839 | 0 | job->set_shell_did_continue(true); |
840 | |
|
841 | 0 | dbgln("Resuming {} ({})", job->pid(), job->cmd()); |
842 | 0 | warnln("Resuming job {} - {}", job->job_id(), job->cmd()); |
843 | |
|
844 | 0 | tcsetpgrp(STDOUT_FILENO, job->pgid()); |
845 | 0 | tcsetpgrp(STDIN_FILENO, job->pgid()); |
846 | | |
847 | | // Try using the PGID, but if that fails, just use the PID. |
848 | 0 | if (killpg(job->pgid(), SIGCONT) < 0) { |
849 | 0 | if (kill(job->pid(), SIGCONT) < 0) { |
850 | 0 | perror("kill"); |
851 | 0 | return 1; |
852 | 0 | } |
853 | 0 | } |
854 | | |
855 | 0 | block_on_job(job); |
856 | |
|
857 | 0 | if (job->exited()) |
858 | 0 | return job->exit_code(); |
859 | 0 | else |
860 | 0 | return 0; |
861 | 0 | } |
862 | | |
863 | | ErrorOr<int> Shell::builtin_disown(Main::Arguments arguments) |
864 | 0 | { |
865 | 0 | Vector<int> job_ids; |
866 | 0 | Vector<bool> id_is_pid; |
867 | |
|
868 | 0 | Core::ArgsParser parser; |
869 | 0 | parser.add_positional_argument(Core::ArgsParser::Arg { |
870 | 0 | .help_string = "Job IDs or Jobspecs to disown", |
871 | 0 | .name = "job-id", |
872 | 0 | .min_values = 0, |
873 | 0 | .max_values = INT_MAX, |
874 | 0 | .accept_value = [&](StringView value) -> bool { |
875 | | // Check if it's a pid (i.e. literal integer) |
876 | 0 | if (auto number = value.to_number<unsigned>(); number.has_value()) { |
877 | 0 | job_ids.append(number.value()); |
878 | 0 | id_is_pid.append(true); |
879 | 0 | return true; |
880 | 0 | } |
881 | | |
882 | | // Check if it's a jobspec |
883 | 0 | if (auto id = resolve_job_spec(value); id.has_value()) { |
884 | 0 | job_ids.append(id.value()); |
885 | 0 | id_is_pid.append(false); |
886 | 0 | return true; |
887 | 0 | } |
888 | | |
889 | 0 | return false; |
890 | 0 | } }); |
891 | |
|
892 | 0 | if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage)) |
893 | 0 | return 1; |
894 | | |
895 | 0 | if (job_ids.is_empty()) { |
896 | 0 | job_ids.append(find_last_job_id()); |
897 | 0 | id_is_pid.append(false); |
898 | 0 | } |
899 | |
|
900 | 0 | Vector<Job const*> jobs_to_disown; |
901 | |
|
902 | 0 | for (size_t i = 0; i < job_ids.size(); ++i) { |
903 | 0 | auto id = job_ids[i]; |
904 | 0 | auto is_pid = id_is_pid[i]; |
905 | 0 | auto job = find_job(id, is_pid); |
906 | 0 | if (!job) |
907 | 0 | warnln("disown: Job with id/pid {} not found", id); |
908 | 0 | else |
909 | 0 | jobs_to_disown.append(job); |
910 | 0 | } |
911 | |
|
912 | 0 | if (jobs_to_disown.is_empty()) { |
913 | 0 | if (job_ids.is_empty()) |
914 | 0 | warnln("disown: No current job"); |
915 | | // An error message has already been printed about the nonexistence of each listed job. |
916 | 0 | return 1; |
917 | 0 | } |
918 | | |
919 | 0 | for (auto job : jobs_to_disown) { |
920 | 0 | job->deactivate(); |
921 | |
|
922 | 0 | if (!job->is_running_in_background()) |
923 | 0 | warnln("disown warning: Job {} is currently not running, 'kill -{} {}' to make it continue", job->job_id(), SIGCONT, job->pid()); |
924 | |
|
925 | 0 | jobs.remove(job->pid()); |
926 | 0 | } |
927 | |
|
928 | 0 | return 0; |
929 | 0 | } |
930 | | |
931 | | ErrorOr<int> Shell::builtin_history(Main::Arguments) |
932 | 0 | { |
933 | 0 | for (size_t i = 0; i < m_editor->history().size(); ++i) { |
934 | 0 | printf("%6zu %s\n", i + 1, m_editor->history()[i].entry.characters()); |
935 | 0 | } |
936 | 0 | return 0; |
937 | 0 | } |
938 | | |
939 | | ErrorOr<int> Shell::builtin_jobs(Main::Arguments arguments) |
940 | 0 | { |
941 | 0 | bool list = false, show_pid = false; |
942 | |
|
943 | 0 | Core::ArgsParser parser; |
944 | 0 | parser.add_option(list, "List all information about jobs", "list", 'l'); |
945 | 0 | parser.add_option(show_pid, "Display the PID of the jobs", "pid", 'p'); |
946 | |
|
947 | 0 | if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage)) |
948 | 0 | return 1; |
949 | | |
950 | 0 | Job::PrintStatusMode mode = Job::PrintStatusMode::Basic; |
951 | |
|
952 | 0 | if (show_pid) |
953 | 0 | mode = Job::PrintStatusMode::OnlyPID; |
954 | |
|
955 | 0 | if (list) |
956 | 0 | mode = Job::PrintStatusMode::ListAll; |
957 | |
|
958 | 0 | for (auto& it : jobs) { |
959 | 0 | if (!it.value->print_status(mode)) |
960 | 0 | return 1; |
961 | 0 | } |
962 | | |
963 | 0 | return 0; |
964 | 0 | } |
965 | | |
966 | | ErrorOr<int> Shell::builtin_popd(Main::Arguments arguments) |
967 | 0 | { |
968 | 0 | if (directory_stack.size() <= 1) { |
969 | 0 | warnln("Shell: popd: directory stack empty"); |
970 | 0 | return 1; |
971 | 0 | } |
972 | | |
973 | 0 | bool should_not_switch = false; |
974 | 0 | Core::ArgsParser parser; |
975 | 0 | parser.add_option(should_not_switch, "Do not switch dirs", "no-switch", 'n'); |
976 | |
|
977 | 0 | if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage)) |
978 | 0 | return 1; |
979 | | |
980 | 0 | auto popped_path = directory_stack.take_last(); |
981 | |
|
982 | 0 | if (should_not_switch) |
983 | 0 | return 0; |
984 | | |
985 | 0 | auto new_path = LexicalPath::canonicalized_path(popped_path); |
986 | 0 | if (chdir(new_path.characters()) < 0) { |
987 | 0 | warnln("chdir({}) failed: {}", new_path, strerror(errno)); |
988 | 0 | return 1; |
989 | 0 | } |
990 | 0 | cwd = new_path; |
991 | 0 | return 0; |
992 | 0 | } |
993 | | |
994 | | ErrorOr<int> Shell::builtin_pushd(Main::Arguments arguments) |
995 | 0 | { |
996 | 0 | StringBuilder path_builder; |
997 | 0 | bool should_switch = true; |
998 | | |
999 | | // From the BASH reference manual: https://www.gnu.org/software/bash/manual/html_node/Directory-Stack-Builtins.html |
1000 | | // With no arguments, pushd exchanges the top two directories and makes the new top the current directory. |
1001 | 0 | if (arguments.strings.size() == 1) { |
1002 | 0 | if (directory_stack.size() < 2) { |
1003 | 0 | warnln("pushd: no other directory"); |
1004 | 0 | return 1; |
1005 | 0 | } |
1006 | | |
1007 | 0 | ByteString dir1 = directory_stack.take_first(); |
1008 | 0 | ByteString dir2 = directory_stack.take_first(); |
1009 | 0 | directory_stack.insert(0, dir2); |
1010 | 0 | directory_stack.insert(1, dir1); |
1011 | |
|
1012 | 0 | int rc = chdir(dir2.characters()); |
1013 | 0 | if (rc < 0) { |
1014 | 0 | warnln("chdir({}) failed: {}", dir2, strerror(errno)); |
1015 | 0 | return 1; |
1016 | 0 | } |
1017 | | |
1018 | 0 | cwd = dir2; |
1019 | |
|
1020 | 0 | return 0; |
1021 | 0 | } |
1022 | | |
1023 | | // Let's assume the user's typed in 'pushd <dir>' |
1024 | 0 | if (arguments.strings.size() == 2) { |
1025 | 0 | directory_stack.append(cwd.characters()); |
1026 | 0 | if (arguments.strings[1].starts_with('/')) { |
1027 | 0 | path_builder.append(arguments.strings[1]); |
1028 | 0 | } else { |
1029 | 0 | path_builder.appendff("{}/{}", cwd, arguments.strings[1]); |
1030 | 0 | } |
1031 | 0 | } else if (arguments.strings.size() == 3) { |
1032 | 0 | directory_stack.append(cwd.characters()); |
1033 | 0 | for (size_t i = 1; i < arguments.strings.size(); i++) { |
1034 | 0 | auto arg = arguments.strings[i]; |
1035 | |
|
1036 | 0 | if (arg.starts_with('-')) { |
1037 | 0 | if (arg.starts_with('/')) { |
1038 | 0 | path_builder.append(arg); |
1039 | 0 | } else { |
1040 | 0 | path_builder.appendff("{}/{}", cwd, arg); |
1041 | 0 | } |
1042 | 0 | } |
1043 | |
|
1044 | 0 | if (arg == "-n"sv) |
1045 | 0 | should_switch = false; |
1046 | 0 | } |
1047 | 0 | } |
1048 | |
|
1049 | 0 | auto real_path = LexicalPath::canonicalized_path(path_builder.to_byte_string()); |
1050 | |
|
1051 | 0 | struct stat st; |
1052 | 0 | int rc = stat(real_path.characters(), &st); |
1053 | 0 | if (rc < 0) { |
1054 | 0 | warnln("stat({}) failed: {}", real_path, strerror(errno)); |
1055 | 0 | return 1; |
1056 | 0 | } |
1057 | | |
1058 | 0 | if (!S_ISDIR(st.st_mode)) { |
1059 | 0 | warnln("Not a directory: {}", real_path); |
1060 | 0 | return 1; |
1061 | 0 | } |
1062 | | |
1063 | 0 | if (should_switch) { |
1064 | 0 | int rc = chdir(real_path.characters()); |
1065 | 0 | if (rc < 0) { |
1066 | 0 | warnln("chdir({}) failed: {}", real_path, strerror(errno)); |
1067 | 0 | return 1; |
1068 | 0 | } |
1069 | | |
1070 | 0 | cwd = real_path; |
1071 | 0 | } |
1072 | | |
1073 | 0 | return 0; |
1074 | 0 | } |
1075 | | |
1076 | | ErrorOr<int> Shell::builtin_pwd(Main::Arguments) |
1077 | 0 | { |
1078 | 0 | print_path(cwd); |
1079 | 0 | fputc('\n', stdout); |
1080 | 0 | return 0; |
1081 | 0 | } |
1082 | | |
1083 | | ErrorOr<int> Shell::builtin_setopt(Main::Arguments arguments) |
1084 | 0 | { |
1085 | 0 | if (arguments.strings.size() == 1) { |
1086 | 0 | #define __ENUMERATE_SHELL_OPTION(name, default_, description) \ |
1087 | 0 | if (options.name) \ |
1088 | 0 | warnln("{}", #name); |
1089 | |
|
1090 | 0 | ENUMERATE_SHELL_OPTIONS(); |
1091 | |
|
1092 | 0 | #undef __ENUMERATE_SHELL_OPTION |
1093 | 0 | } |
1094 | |
|
1095 | 0 | Core::ArgsParser parser; |
1096 | 0 | #define __ENUMERATE_SHELL_OPTION(name, default_, description) \ |
1097 | 0 | bool name = false; \ |
1098 | 0 | bool not_##name = false; \ |
1099 | 0 | parser.add_option(name, "Enable: " description, #name, '\0'); \ |
1100 | 0 | parser.add_option(not_##name, "Disable: " description, "no_" #name, '\0'); |
1101 | |
|
1102 | 0 | ENUMERATE_SHELL_OPTIONS(); |
1103 | |
|
1104 | 0 | #undef __ENUMERATE_SHELL_OPTION |
1105 | |
|
1106 | 0 | if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage)) |
1107 | 0 | return 1; |
1108 | | |
1109 | 0 | #define __ENUMERATE_SHELL_OPTION(name, default_, description) \ |
1110 | 0 | if (name) \ |
1111 | 0 | options.name = true; \ |
1112 | 0 | if (not_##name) \ |
1113 | 0 | options.name = false; |
1114 | | |
1115 | 0 | ENUMERATE_SHELL_OPTIONS(); |
1116 | |
|
1117 | 0 | #undef __ENUMERATE_SHELL_OPTION |
1118 | |
|
1119 | 0 | return 0; |
1120 | 0 | } |
1121 | | |
1122 | | ErrorOr<int> Shell::builtin_shift(Main::Arguments arguments) |
1123 | 0 | { |
1124 | 0 | int count = 1; |
1125 | |
|
1126 | 0 | Core::ArgsParser parser; |
1127 | 0 | parser.add_positional_argument(count, "Shift count", "count", Core::ArgsParser::Required::No); |
1128 | |
|
1129 | 0 | if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage)) |
1130 | 0 | return 1; |
1131 | | |
1132 | 0 | if (count < 1) |
1133 | 0 | return 0; |
1134 | | |
1135 | 0 | auto argv_ = TRY(look_up_local_variable("ARGV"sv)); |
1136 | 0 | if (!argv_) { |
1137 | 0 | warnln("shift: ARGV is unset"); |
1138 | 0 | return 1; |
1139 | 0 | } |
1140 | | |
1141 | 0 | if (!argv_->is_list()) |
1142 | 0 | argv_ = adopt_ref(*new AST::ListValue({ const_cast<AST::Value&>(*argv_) })); |
1143 | |
|
1144 | 0 | auto& values = const_cast<AST::ListValue*>(static_cast<AST::ListValue const*>(argv_.ptr()))->values(); |
1145 | 0 | if ((size_t)count > values.size()) { |
1146 | 0 | warnln("shift: shift count must not be greater than {}", values.size()); |
1147 | 0 | return 1; |
1148 | 0 | } |
1149 | | |
1150 | 0 | for (auto i = 0; i < count; ++i) |
1151 | 0 | (void)values.take_first(); |
1152 | |
|
1153 | 0 | return 0; |
1154 | 0 | } |
1155 | | |
1156 | | ErrorOr<int> Shell::builtin_source(Main::Arguments arguments) |
1157 | 0 | { |
1158 | 0 | StringView file_to_source; |
1159 | 0 | Vector<StringView> args; |
1160 | |
|
1161 | 0 | Core::ArgsParser parser; |
1162 | 0 | parser.add_positional_argument(file_to_source, "File to read commands from", "path"); |
1163 | 0 | parser.add_positional_argument(args, "ARGV for the sourced file", "args", Core::ArgsParser::Required::No); |
1164 | |
|
1165 | 0 | if (!parser.parse(arguments)) |
1166 | 0 | return 1; |
1167 | | |
1168 | 0 | auto previous_argv = TRY(look_up_local_variable("ARGV"sv)); |
1169 | 0 | ScopeGuard guard { [&] { |
1170 | 0 | if (!args.is_empty()) |
1171 | 0 | set_local_variable("ARGV", const_cast<AST::Value&>(*previous_argv)); |
1172 | 0 | } }; |
1173 | |
|
1174 | 0 | if (!args.is_empty()) { |
1175 | 0 | Vector<String> arguments; |
1176 | 0 | arguments.ensure_capacity(args.size()); |
1177 | 0 | for (auto& arg : args) |
1178 | 0 | arguments.append(TRY(String::from_utf8(arg))); |
1179 | | |
1180 | 0 | set_local_variable("ARGV", AST::make_ref_counted<AST::ListValue>(move(arguments))); |
1181 | 0 | } |
1182 | | |
1183 | 0 | if (!run_file(file_to_source, true)) |
1184 | 0 | return 126; |
1185 | | |
1186 | 0 | return 0; |
1187 | 0 | } |
1188 | | |
1189 | | ErrorOr<int> Shell::builtin_time(Main::Arguments arguments) |
1190 | 0 | { |
1191 | 0 | Vector<StringView> args; |
1192 | |
|
1193 | 0 | int number_of_iterations = 1; |
1194 | |
|
1195 | 0 | Core::ArgsParser parser; |
1196 | 0 | parser.add_option(number_of_iterations, "Number of iterations", "iterations", 'n', "iterations"); |
1197 | 0 | parser.set_stop_on_first_non_option(true); |
1198 | 0 | parser.add_positional_argument(args, "Command to execute with arguments", "command", Core::ArgsParser::Required::Yes); |
1199 | |
|
1200 | 0 | if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage)) |
1201 | 0 | return 1; |
1202 | | |
1203 | 0 | if (number_of_iterations < 1) |
1204 | 0 | return 1; |
1205 | | |
1206 | 0 | AST::Command command; |
1207 | 0 | TRY(command.argv.try_ensure_capacity(args.size())); |
1208 | 0 | for (auto& arg : args) |
1209 | 0 | command.argv.append(TRY(String::from_utf8(arg))); |
1210 | | |
1211 | 0 | auto commands = TRY(expand_aliases({ move(command) })); |
1212 | | |
1213 | 0 | AK::Statistics iteration_times; |
1214 | |
|
1215 | 0 | int exit_code = 1; |
1216 | 0 | for (int i = 0; i < number_of_iterations; ++i) { |
1217 | 0 | auto timer = Core::ElapsedTimer::start_new(); |
1218 | 0 | for (auto& job : run_commands(commands)) { |
1219 | 0 | block_on_job(job); |
1220 | 0 | exit_code = job->exit_code(); |
1221 | 0 | } |
1222 | 0 | iteration_times.add(static_cast<float>(timer.elapsed())); |
1223 | 0 | } |
1224 | |
|
1225 | 0 | warnln(); |
1226 | |
|
1227 | 0 | if (number_of_iterations == 1) { |
1228 | 0 | warnln("Time: {} ms", iteration_times.values().first()); |
1229 | 0 | } else { |
1230 | 0 | AK::Statistics iteration_times_excluding_first; |
1231 | 0 | for (size_t i = 1; i < iteration_times.size(); i++) |
1232 | 0 | iteration_times_excluding_first.add(iteration_times.values()[i]); |
1233 | |
|
1234 | 0 | warnln("Timing report: {} ms", iteration_times.sum()); |
1235 | 0 | warnln("=============="); |
1236 | 0 | warnln("Command: {}", ByteString::join(' ', arguments.strings)); |
1237 | 0 | warnln("Average time: {:.2} ms (median: {}, stddev: {:.2}, min: {}, max: {})", |
1238 | 0 | iteration_times.average(), iteration_times.median(), |
1239 | 0 | iteration_times.standard_deviation(), |
1240 | 0 | iteration_times.min(), iteration_times.max()); |
1241 | 0 | warnln("Excluding first: {:.2} ms (median: {}, stddev: {:.2}, min: {}, max: {})", |
1242 | 0 | iteration_times_excluding_first.average(), iteration_times_excluding_first.median(), |
1243 | 0 | iteration_times_excluding_first.standard_deviation(), |
1244 | 0 | iteration_times_excluding_first.min(), iteration_times_excluding_first.max()); |
1245 | 0 | } |
1246 | |
|
1247 | 0 | return exit_code; |
1248 | 0 | } |
1249 | | |
1250 | | ErrorOr<int> Shell::builtin_umask(Main::Arguments arguments) |
1251 | 0 | { |
1252 | 0 | StringView mask_text; |
1253 | 0 | bool symbolic_output = false; |
1254 | |
|
1255 | 0 | Core::ArgsParser parser; |
1256 | |
|
1257 | 0 | parser.add_option(symbolic_output, "Produce symbolic output", "symbolic", 'S'); |
1258 | 0 | parser.add_positional_argument(mask_text, "New mask (omit to get current mask)", "octal-mask", Core::ArgsParser::Required::No); |
1259 | |
|
1260 | 0 | if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage)) |
1261 | 0 | return 1; |
1262 | | |
1263 | 0 | auto parse_symbolic_digit = [](int digit) -> ErrorOr<String> { |
1264 | 0 | StringBuilder builder; |
1265 | |
|
1266 | 0 | if ((digit & 4) == 0) |
1267 | 0 | TRY(builder.try_append('r')); |
1268 | 0 | if ((digit & 2) == 0) |
1269 | 0 | TRY(builder.try_append('w')); |
1270 | 0 | if ((digit & 1) == 0) |
1271 | 0 | TRY(builder.try_append('x')); |
1272 | 0 | if (builder.is_empty()) |
1273 | 0 | TRY(builder.try_append('-')); |
1274 | | |
1275 | 0 | return builder.to_string(); |
1276 | 0 | }; |
1277 | |
|
1278 | 0 | if (mask_text.is_empty()) { |
1279 | 0 | mode_t old_mask = umask(0); |
1280 | |
|
1281 | 0 | if (symbolic_output) { |
1282 | 0 | StringBuilder builder; |
1283 | |
|
1284 | 0 | TRY(builder.try_append("u="sv)); |
1285 | 0 | TRY(builder.try_append(TRY(parse_symbolic_digit(old_mask >> 6 & 7)).bytes())); |
1286 | | |
1287 | 0 | TRY(builder.try_append(",g="sv)); |
1288 | 0 | TRY(builder.try_append(TRY(parse_symbolic_digit(old_mask >> 3 & 7)).bytes())); |
1289 | | |
1290 | 0 | TRY(builder.try_append(",o="sv)); |
1291 | 0 | TRY(builder.try_append(TRY(parse_symbolic_digit(old_mask >> 0 & 7)).bytes())); |
1292 | | |
1293 | 0 | outln("{}", builder.string_view()); |
1294 | 0 | } else { |
1295 | 0 | outln("{:#o}", old_mask); |
1296 | 0 | } |
1297 | | |
1298 | 0 | umask(old_mask); |
1299 | 0 | return 0; |
1300 | 0 | } |
1301 | | |
1302 | 0 | unsigned mask = 0; |
1303 | 0 | auto matches = true; |
1304 | | |
1305 | | // FIXME: There's currently no way to parse an StringView as an octal integer, |
1306 | | // when that becomes available, replace this code. |
1307 | 0 | for (auto byte : mask_text.bytes()) { |
1308 | 0 | if (isspace(byte)) |
1309 | 0 | continue; |
1310 | 0 | if (!is_ascii_octal_digit(byte)) { |
1311 | 0 | matches = false; |
1312 | 0 | break; |
1313 | 0 | } |
1314 | | |
1315 | 0 | mask = (mask << 3) + (byte - '0'); |
1316 | 0 | } |
1317 | 0 | if (matches) { |
1318 | 0 | umask(mask); |
1319 | 0 | return 0; |
1320 | 0 | } |
1321 | | |
1322 | 0 | warnln("umask: Invalid mask '{}'", mask_text); |
1323 | 0 | return 1; |
1324 | 0 | } |
1325 | | |
1326 | | ErrorOr<int> Shell::builtin_wait(Main::Arguments arguments) |
1327 | 0 | { |
1328 | 0 | Vector<int> job_ids; |
1329 | 0 | Vector<bool> id_is_pid; |
1330 | |
|
1331 | 0 | Core::ArgsParser parser; |
1332 | 0 | parser.add_positional_argument(Core::ArgsParser::Arg { |
1333 | 0 | .help_string = "Job IDs or Jobspecs to wait for", |
1334 | 0 | .name = "job-id", |
1335 | 0 | .min_values = 0, |
1336 | 0 | .max_values = INT_MAX, |
1337 | 0 | .accept_value = [&](StringView value) -> bool { |
1338 | | // Check if it's a pid (i.e. literal integer) |
1339 | 0 | if (auto number = value.to_number<unsigned>(); number.has_value()) { |
1340 | 0 | job_ids.append(number.value()); |
1341 | 0 | id_is_pid.append(true); |
1342 | 0 | return true; |
1343 | 0 | } |
1344 | | |
1345 | | // Check if it's a jobspec |
1346 | 0 | if (auto id = resolve_job_spec(value); id.has_value()) { |
1347 | 0 | job_ids.append(id.value()); |
1348 | 0 | id_is_pid.append(false); |
1349 | 0 | return true; |
1350 | 0 | } |
1351 | | |
1352 | 0 | return false; |
1353 | 0 | } }); |
1354 | |
|
1355 | 0 | if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage)) |
1356 | 0 | return 1; |
1357 | | |
1358 | 0 | Vector<NonnullRefPtr<Job>> jobs_to_wait_for; |
1359 | |
|
1360 | 0 | for (size_t i = 0; i < job_ids.size(); ++i) { |
1361 | 0 | auto id = job_ids[i]; |
1362 | 0 | auto is_pid = id_is_pid[i]; |
1363 | 0 | auto job = find_job(id, is_pid); |
1364 | 0 | if (!job) |
1365 | 0 | warnln("wait: Job with id/pid {} not found", id); |
1366 | 0 | else |
1367 | 0 | jobs_to_wait_for.append(*job); |
1368 | 0 | } |
1369 | |
|
1370 | 0 | if (job_ids.is_empty()) { |
1371 | 0 | for (auto const& it : jobs) |
1372 | 0 | jobs_to_wait_for.append(it.value); |
1373 | 0 | } |
1374 | |
|
1375 | 0 | for (auto& job : jobs_to_wait_for) { |
1376 | 0 | job->set_running_in_background(false); |
1377 | 0 | block_on_job(job); |
1378 | 0 | } |
1379 | |
|
1380 | 0 | return 0; |
1381 | 0 | } |
1382 | | |
1383 | | ErrorOr<int> Shell::builtin_unset(Main::Arguments arguments) |
1384 | 0 | { |
1385 | 0 | Vector<ByteString> vars; |
1386 | 0 | bool unset_only_variables = false; // POSIX only. |
1387 | |
|
1388 | 0 | Core::ArgsParser parser; |
1389 | 0 | parser.add_positional_argument(vars, "List of variables", "variables", Core::ArgsParser::Required::Yes); |
1390 | 0 | if (m_in_posix_mode) |
1391 | 0 | parser.add_option(unset_only_variables, "Unset only variables", "variables", 'v'); |
1392 | |
|
1393 | 0 | if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage)) |
1394 | 0 | return 1; |
1395 | | |
1396 | 0 | bool did_touch_path = false; |
1397 | 0 | for (auto& value : vars) { |
1398 | 0 | if (!did_touch_path && value == "PATH"sv) |
1399 | 0 | did_touch_path = true; |
1400 | |
|
1401 | 0 | if (TRY(look_up_local_variable(value)) != nullptr) { |
1402 | 0 | unset_local_variable(value); |
1403 | 0 | } else if (!unset_only_variables) { |
1404 | 0 | unsetenv(value.characters()); |
1405 | 0 | } |
1406 | 0 | } |
1407 | |
|
1408 | 0 | if (did_touch_path) |
1409 | 0 | cache_path(); |
1410 | |
|
1411 | 0 | return 0; |
1412 | 0 | } |
1413 | | |
1414 | | ErrorOr<int> Shell::builtin_set(Main::Arguments arguments) |
1415 | 0 | { |
1416 | 0 | if (arguments.strings.size() == 1) { |
1417 | 0 | HashMap<String, String> vars; |
1418 | |
|
1419 | 0 | StringBuilder builder; |
1420 | 0 | for (auto& frame : m_local_frames) { |
1421 | 0 | for (auto& var : frame->local_variables) { |
1422 | 0 | builder.join(" "sv, TRY(var.value->resolve_as_list(*this))); |
1423 | 0 | vars.set(TRY(String::from_byte_string(var.key)), TRY(builder.to_string())); |
1424 | 0 | builder.clear(); |
1425 | 0 | } |
1426 | 0 | } |
1427 | | |
1428 | 0 | struct Variable { |
1429 | 0 | StringView name; |
1430 | 0 | String value; |
1431 | 0 | }; |
1432 | |
|
1433 | 0 | Vector<Variable> variables; |
1434 | 0 | variables.ensure_capacity(vars.size()); |
1435 | |
|
1436 | 0 | for (auto& var : vars) |
1437 | 0 | variables.unchecked_append({ var.key, var.value }); |
1438 | |
|
1439 | 0 | Vector<String> functions; |
1440 | 0 | functions.ensure_capacity(m_functions.size()); |
1441 | 0 | for (auto& function : m_functions) |
1442 | 0 | functions.unchecked_append(TRY(serialize_function_definition(function.value))); |
1443 | | |
1444 | 0 | quick_sort(variables, [](auto& a, auto& b) { return a.name < b.name; }); |
1445 | 0 | quick_sort(functions, [](auto& a, auto& b) { return a < b; }); |
1446 | |
|
1447 | 0 | for (auto& var : variables) |
1448 | 0 | outln("{}={}", var.name, escape_token(var.value)); |
1449 | |
|
1450 | 0 | for (auto& fn : functions) |
1451 | 0 | outln("{}", fn); |
1452 | |
|
1453 | 0 | return 0; |
1454 | 0 | } |
1455 | | |
1456 | 0 | Vector<StringView> argv_to_set; |
1457 | |
|
1458 | 0 | Core::ArgsParser parser; |
1459 | 0 | parser.set_stop_on_first_non_option(true); |
1460 | 0 | parser.add_positional_argument(argv_to_set, "List of arguments", "arg", Core::ArgsParser::Required::No); |
1461 | |
|
1462 | 0 | if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage)) |
1463 | 0 | return 1; |
1464 | | |
1465 | 0 | if (!argv_to_set.is_empty() || arguments.strings.last() == "--"sv) { |
1466 | 0 | Vector<String> argv; |
1467 | 0 | argv.ensure_capacity(argv_to_set.size()); |
1468 | 0 | for (auto& arg : argv_to_set) |
1469 | 0 | argv.unchecked_append(TRY(String::from_utf8(arg))); |
1470 | 0 | set_local_variable("ARGV", AST::make_ref_counted<AST::ListValue>(move(argv))); |
1471 | 0 | } |
1472 | | |
1473 | 0 | return 0; |
1474 | 0 | } |
1475 | | |
1476 | | ErrorOr<int> Shell::builtin_not(Main::Arguments arguments) |
1477 | 0 | { |
1478 | 0 | Vector<StringView> args; |
1479 | |
|
1480 | 0 | Core::ArgsParser parser; |
1481 | 0 | parser.set_stop_on_first_non_option(true); |
1482 | 0 | parser.add_positional_argument(args, "Command to run followed by its arguments", "string"); |
1483 | |
|
1484 | 0 | if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::Ignore)) |
1485 | 0 | return 1; |
1486 | | |
1487 | 0 | AST::Command command; |
1488 | 0 | TRY(command.argv.try_ensure_capacity(args.size())); |
1489 | 0 | for (auto& arg : args) |
1490 | 0 | command.argv.unchecked_append(TRY(String::from_utf8(arg))); |
1491 | | |
1492 | 0 | auto commands = TRY(expand_aliases({ move(command) })); |
1493 | 0 | int exit_code = 1; |
1494 | 0 | auto found_a_job = false; |
1495 | 0 | for (auto& job : run_commands(commands)) { |
1496 | 0 | found_a_job = true; |
1497 | 0 | block_on_job(job); |
1498 | 0 | exit_code = job->exit_code(); |
1499 | 0 | } |
1500 | | // In case it was a function. |
1501 | 0 | if (!found_a_job) |
1502 | 0 | exit_code = last_return_code.value_or(0); |
1503 | 0 | return exit_code == 0 ? 1 : 0; |
1504 | 0 | } |
1505 | | |
1506 | | ErrorOr<int> Shell::builtin_kill(Main::Arguments arguments) |
1507 | 0 | { |
1508 | | // Simply translate the arguments and pass them to `kill' |
1509 | 0 | Vector<String> replaced_values; |
1510 | 0 | auto kill_path_or_error = Core::System::resolve_executable_from_environment("kill"sv); |
1511 | 0 | if (kill_path_or_error.is_error()) { |
1512 | 0 | warnln("kill: `kill' not found in PATH"); |
1513 | 0 | return 126; |
1514 | 0 | } |
1515 | | |
1516 | 0 | replaced_values.append(kill_path_or_error.release_value()); |
1517 | 0 | for (size_t i = 1; i < arguments.strings.size(); ++i) { |
1518 | 0 | if (auto job_id = resolve_job_spec(arguments.strings[i]); job_id.has_value()) { |
1519 | 0 | auto job = find_job(job_id.value()); |
1520 | 0 | if (job) { |
1521 | 0 | replaced_values.append(String::number(job->pid())); |
1522 | 0 | } else { |
1523 | 0 | warnln("kill: Job with pid {} not found", job_id.value()); |
1524 | 0 | return 1; |
1525 | 0 | } |
1526 | 0 | } else { |
1527 | 0 | replaced_values.append(TRY(String::from_utf8(arguments.strings[i]))); |
1528 | 0 | } |
1529 | 0 | } |
1530 | | |
1531 | | // Now just run `kill' |
1532 | 0 | AST::Command command; |
1533 | 0 | command.argv = move(replaced_values); |
1534 | 0 | command.position = m_source_position.has_value() ? m_source_position->position : Optional<AST::Position> {}; |
1535 | |
|
1536 | 0 | auto exit_code = 1; |
1537 | 0 | auto job_result = run_command(command); |
1538 | 0 | if (job_result.is_error()) { |
1539 | 0 | warnln("kill: Failed to run {}: {}", command.argv.first(), job_result.error()); |
1540 | 0 | return exit_code; |
1541 | 0 | } |
1542 | | |
1543 | 0 | if (auto job = job_result.release_value()) { |
1544 | 0 | block_on_job(job); |
1545 | 0 | exit_code = job->exit_code(); |
1546 | 0 | } |
1547 | 0 | return exit_code; |
1548 | 0 | } |
1549 | | |
1550 | | ErrorOr<bool> Shell::run_builtin(const AST::Command& command, Vector<NonnullRefPtr<AST::Rewiring>> const& rewirings, int& retval) |
1551 | 0 | { |
1552 | 0 | if (command.argv.is_empty()) |
1553 | 0 | return false; |
1554 | | |
1555 | 0 | if (!has_builtin(command.argv.first())) |
1556 | 0 | return false; |
1557 | | |
1558 | 0 | Vector<StringView> arguments; |
1559 | 0 | TRY(arguments.try_ensure_capacity(command.argv.size())); |
1560 | 0 | for (auto& arg : command.argv) |
1561 | 0 | arguments.unchecked_append(arg); |
1562 | |
|
1563 | 0 | Main::Arguments arguments_object { |
1564 | 0 | .argc = 0, |
1565 | 0 | .argv = nullptr, |
1566 | 0 | .strings = arguments |
1567 | 0 | }; |
1568 | |
|
1569 | 0 | StringView name = command.argv.first(); |
1570 | |
|
1571 | 0 | SavedFileDescriptors fds { rewirings }; |
1572 | |
|
1573 | 0 | for (auto& rewiring : rewirings) { |
1574 | 0 | int rc = dup2(rewiring->old_fd, rewiring->new_fd); |
1575 | 0 | if (rc < 0) { |
1576 | 0 | perror("dup2(run)"); |
1577 | 0 | return false; |
1578 | 0 | } |
1579 | 0 | } |
1580 | | |
1581 | 0 | Core::EventLoop loop; |
1582 | 0 | setup_signals(); |
1583 | |
|
1584 | 0 | if (name == ":"sv) |
1585 | 0 | name = "noop"sv; |
1586 | 0 | else if (m_in_posix_mode && name == "."sv) |
1587 | 0 | name = "source"sv; |
1588 | |
|
1589 | 0 | #define __ENUMERATE_SHELL_BUILTIN(builtin, _mode) \ |
1590 | 0 | if (name == #builtin) { \ |
1591 | 0 | retval = TRY(builtin_##builtin(arguments_object)); \ |
1592 | 0 | if (!has_error(ShellError::None)) \ |
1593 | 0 | raise_error(m_error, m_error_description, command.position); \ |
1594 | 0 | fflush(stdout); \ |
1595 | 0 | fflush(stderr); \ |
1596 | 0 | return true; \ |
1597 | 0 | } |
1598 | |
|
1599 | 0 | ENUMERATE_SHELL_BUILTINS(); |
1600 | |
|
1601 | 0 | #undef __ENUMERATE_SHELL_BUILTIN |
1602 | 0 | return false; |
1603 | 0 | } |
1604 | | |
1605 | | ErrorOr<int> Shell::builtin_argsparser_parse(Main::Arguments arguments) |
1606 | 0 | { |
1607 | | // argsparser_parse |
1608 | | // --add-option variable [--type (bool | string | i32 | u32 | double | size)] --help-string "" --long-name "" --short-name "" [--value-name "" <if not --type bool>] --list |
1609 | | // --add-positional-argument variable [--type (bool | string | i32 | u32 | double | size)] ([--min n] [--max n] | [--required]) --help-string "" --value-name "" |
1610 | | // [--general-help ""] |
1611 | | // [--stop-on-first-non-option] |
1612 | | // -- |
1613 | | // $args_to_parse |
1614 | 0 | Core::ArgsParser parser; |
1615 | |
|
1616 | 0 | Core::ArgsParser user_parser; |
1617 | |
|
1618 | 0 | Vector<StringView> descriptors; |
1619 | 0 | Variant<Core::ArgsParser::Option, Core::ArgsParser::Arg, Empty> current; |
1620 | 0 | Vector<ByteString> help_string_storage; |
1621 | 0 | Vector<ByteString> long_name_storage; |
1622 | 0 | Vector<ByteString> value_name_storage; |
1623 | 0 | Vector<ByteString> name_storage; |
1624 | 0 | ByteString current_variable; |
1625 | | // if max > 1 or min < 1, or explicit `--list`. |
1626 | 0 | bool treat_arg_as_list = false; |
1627 | 0 | enum class Type { |
1628 | 0 | Bool, |
1629 | 0 | String, |
1630 | 0 | I32, |
1631 | 0 | U32, |
1632 | 0 | Double, |
1633 | 0 | Size, |
1634 | 0 | }; |
1635 | |
|
1636 | 0 | auto type = Type::String; |
1637 | |
|
1638 | 0 | auto try_convert = [](StringView value, Type type) -> ErrorOr<Optional<RefPtr<AST::Value>>> { |
1639 | 0 | switch (type) { |
1640 | 0 | case Type::Bool: |
1641 | 0 | return AST::make_ref_counted<AST::StringValue>("true"_string); |
1642 | 0 | case Type::String: |
1643 | 0 | return AST::make_ref_counted<AST::StringValue>(TRY(String::from_utf8(value))); |
1644 | 0 | case Type::I32: |
1645 | 0 | if (auto number = value.to_number<int>(); number.has_value()) |
1646 | 0 | return AST::make_ref_counted<AST::StringValue>(String::number(*number)); |
1647 | | |
1648 | 0 | warnln("Invalid value for type i32: {}", value); |
1649 | 0 | return OptionalNone {}; |
1650 | 0 | case Type::U32: |
1651 | 0 | case Type::Size: |
1652 | 0 | if (auto number = value.to_number<unsigned>(); number.has_value()) |
1653 | 0 | return AST::make_ref_counted<AST::StringValue>(String::number(*number)); |
1654 | | |
1655 | 0 | warnln("Invalid value for type u32|size: {}", value); |
1656 | 0 | return OptionalNone {}; |
1657 | 0 | case Type::Double: { |
1658 | 0 | ByteString string = value; |
1659 | 0 | char* endptr = nullptr; |
1660 | 0 | auto number = strtod(string.characters(), &endptr); |
1661 | 0 | if (endptr != string.characters() + string.length()) { |
1662 | 0 | warnln("Invalid value for type double: {}", value); |
1663 | 0 | return OptionalNone {}; |
1664 | 0 | } |
1665 | | |
1666 | 0 | return AST::make_ref_counted<AST::StringValue>(String::number(number)); |
1667 | 0 | } |
1668 | 0 | default: |
1669 | 0 | VERIFY_NOT_REACHED(); |
1670 | 0 | } |
1671 | 0 | }; |
1672 | |
|
1673 | 0 | auto enlist = [&](auto name, auto value) -> ErrorOr<NonnullRefPtr<AST::Value>> { |
1674 | 0 | auto variable = TRY(look_up_local_variable(name)); |
1675 | 0 | if (variable) { |
1676 | 0 | auto list = TRY(const_cast<AST::Value&>(*variable).resolve_as_list(*this)); |
1677 | 0 | auto new_value = TRY(value->resolve_as_string(*this)); |
1678 | 0 | list.append(move(new_value)); |
1679 | 0 | return try_make_ref_counted<AST::ListValue>(move(list)); |
1680 | 0 | } |
1681 | 0 | return *value; |
1682 | 0 | }; |
1683 | | |
1684 | | // FIXME: We cannot return ErrorOr<T> from Core::ArgsParser::Option::accept_value(), fix the MUST's here whenever that function is ErrorOr-aware. |
1685 | 0 | auto commit = [&] { |
1686 | 0 | return current.visit( |
1687 | 0 | [&](Core::ArgsParser::Option& option) { |
1688 | 0 | if (!option.long_name && !option.short_name) { |
1689 | 0 | warnln("Defined option must have at least one of --long-name or --short-name"); |
1690 | 0 | return false; |
1691 | 0 | } |
1692 | 0 | option.accept_value = [&, current_variable, treat_arg_as_list, type](StringView value) { |
1693 | 0 | auto result = MUST(try_convert(value, type)); |
1694 | 0 | if (result.has_value()) { |
1695 | 0 | auto value = result.release_value(); |
1696 | 0 | if (treat_arg_as_list) |
1697 | 0 | value = MUST(enlist(current_variable, move(value))); |
1698 | 0 | this->set_local_variable(current_variable, move(value), true); |
1699 | 0 | return true; |
1700 | 0 | } |
1701 | | |
1702 | 0 | return false; |
1703 | 0 | }; |
1704 | 0 | user_parser.add_option(move(option)); |
1705 | 0 | type = Type::String; |
1706 | 0 | treat_arg_as_list = false; |
1707 | 0 | return true; |
1708 | 0 | }, |
1709 | 0 | [&](Core::ArgsParser::Arg& arg) { |
1710 | 0 | if (!arg.name) { |
1711 | 0 | warnln("Defined positional argument must have a name"); |
1712 | 0 | return false; |
1713 | 0 | } |
1714 | 0 | arg.accept_value = [&, current_variable, treat_arg_as_list, type](StringView value) { |
1715 | 0 | auto result = MUST(try_convert(value, type)); |
1716 | 0 | if (result.has_value()) { |
1717 | 0 | auto value = result.release_value(); |
1718 | 0 | if (treat_arg_as_list) |
1719 | 0 | value = MUST(enlist(current_variable, move(value))); |
1720 | 0 | this->set_local_variable(current_variable, move(value), true); |
1721 | 0 | return true; |
1722 | 0 | } |
1723 | | |
1724 | 0 | return false; |
1725 | 0 | }; |
1726 | 0 | user_parser.add_positional_argument(move(arg)); |
1727 | 0 | type = Type::String; |
1728 | 0 | treat_arg_as_list = false; |
1729 | 0 | return true; |
1730 | 0 | }, |
1731 | 0 | [&](Empty) { |
1732 | 0 | return true; |
1733 | 0 | }); |
1734 | 0 | }; |
1735 | |
|
1736 | 0 | parser.add_option(Core::ArgsParser::Option { |
1737 | 0 | .argument_mode = Core::ArgsParser::OptionArgumentMode::None, |
1738 | 0 | .help_string = "Stop processing descriptors after a non-argument parameter is seen", |
1739 | 0 | .long_name = "stop-on-first-non-option", |
1740 | 0 | .accept_value = [&](auto) { |
1741 | 0 | user_parser.set_stop_on_first_non_option(true); |
1742 | 0 | return true; |
1743 | 0 | }, |
1744 | 0 | }); |
1745 | 0 | parser.add_option(Core::ArgsParser::Option { |
1746 | 0 | .argument_mode = Core::ArgsParser::OptionArgumentMode::Required, |
1747 | 0 | .help_string = "Set the general help string for the parser", |
1748 | 0 | .long_name = "general-help", |
1749 | 0 | .value_name = "string", |
1750 | 0 | .accept_value = [&](StringView value) { |
1751 | 0 | VERIFY(strlen(value.characters_without_null_termination()) == value.length()); |
1752 | 0 | user_parser.set_general_help(value.characters_without_null_termination()); |
1753 | 0 | return true; |
1754 | 0 | }, |
1755 | 0 | }); |
1756 | 0 | parser.add_option(Core::ArgsParser::Option { |
1757 | 0 | .argument_mode = Core::ArgsParser::OptionArgumentMode::Required, |
1758 | 0 | .help_string = "Start describing an option", |
1759 | 0 | .long_name = "add-option", |
1760 | 0 | .value_name = "variable-name", |
1761 | 0 | .accept_value = [&](auto name) { |
1762 | 0 | if (!commit()) |
1763 | 0 | return false; |
1764 | | |
1765 | 0 | current = Core::ArgsParser::Option {}; |
1766 | 0 | current_variable = name; |
1767 | 0 | if (current_variable.is_empty() || !all_of(current_variable, [](auto ch) { return ch == '_' || isalnum(ch); })) { |
1768 | 0 | warnln("Option variable name must be a valid identifier"); |
1769 | 0 | return false; |
1770 | 0 | } |
1771 | | |
1772 | 0 | return true; |
1773 | 0 | }, |
1774 | 0 | }); |
1775 | 0 | parser.add_option(Core::ArgsParser::Option { |
1776 | 0 | .argument_mode = Core::ArgsParser::OptionArgumentMode::None, |
1777 | 0 | .help_string = "Accept multiple of the current option being given", |
1778 | 0 | .long_name = "list", |
1779 | 0 | .accept_value = [&](auto) { |
1780 | 0 | if (!current.has<Core::ArgsParser::Option>()) { |
1781 | 0 | warnln("Must be defining an option to use --list"); |
1782 | 0 | return false; |
1783 | 0 | } |
1784 | 0 | treat_arg_as_list = true; |
1785 | 0 | return true; |
1786 | 0 | }, |
1787 | 0 | }); |
1788 | 0 | parser.add_option(Core::ArgsParser::Option { |
1789 | 0 | .argument_mode = Core::ArgsParser::OptionArgumentMode::Required, |
1790 | 0 | .help_string = "Define the type of the option or argument being described", |
1791 | 0 | .long_name = "type", |
1792 | 0 | .value_name = "type", |
1793 | 0 | .accept_value = [&](StringView ty) { |
1794 | 0 | if (current.has<Empty>()) { |
1795 | 0 | warnln("Must be defining an argument or option to use --type"); |
1796 | 0 | return false; |
1797 | 0 | } |
1798 | | |
1799 | 0 | if (ty == "bool") { |
1800 | 0 | if (auto option = current.get_pointer<Core::ArgsParser::Option>()) { |
1801 | 0 | if (option->value_name != nullptr) { |
1802 | 0 | warnln("Type 'bool' does not apply to options with a value (value name is set to {})", option->value_name); |
1803 | 0 | return false; |
1804 | 0 | } |
1805 | | |
1806 | 0 | option->argument_mode = Core::ArgsParser::OptionArgumentMode::None; |
1807 | 0 | } |
1808 | 0 | type = Type::Bool; |
1809 | 0 | } else if (ty == "string") { |
1810 | 0 | type = Type::String; |
1811 | 0 | } else if (ty == "i32") { |
1812 | 0 | type = Type::I32; |
1813 | 0 | } else if (ty == "u32") { |
1814 | 0 | type = Type::U32; |
1815 | 0 | } else if (ty == "double") { |
1816 | 0 | type = Type::Double; |
1817 | 0 | } else if (ty == "size") { |
1818 | 0 | type = Type::Size; |
1819 | 0 | } else { |
1820 | 0 | warnln("Invalid type '{}', expected one of bool | string | i32 | u32 | double | size", ty); |
1821 | 0 | return false; |
1822 | 0 | } |
1823 | | |
1824 | 0 | if (type == Type::Bool) { |
1825 | 0 | set_local_variable( |
1826 | 0 | current_variable, |
1827 | 0 | make_ref_counted<AST::StringValue>("false"_string), |
1828 | 0 | true); |
1829 | 0 | } |
1830 | 0 | return true; |
1831 | 0 | }, |
1832 | 0 | }); |
1833 | |
|
1834 | 0 | parser.add_option(Core::ArgsParser::Option { |
1835 | 0 | .argument_mode = Core::ArgsParser::OptionArgumentMode::Required, |
1836 | 0 | .help_string = "Set the help string of the option or argument being defined", |
1837 | 0 | .long_name = "help-string", |
1838 | 0 | .value_name = "string", |
1839 | 0 | .accept_value = [&](StringView value) { |
1840 | 0 | return current.visit( |
1841 | 0 | [](Empty) { |
1842 | 0 | warnln("Must be defining an option or argument to use --help-string"); |
1843 | 0 | return false; |
1844 | 0 | }, |
1845 | 0 | [&](auto& option) { |
1846 | 0 | help_string_storage.append(value); |
1847 | 0 | option.help_string = help_string_storage.last().characters(); |
1848 | 0 | return true; |
1849 | 0 | }); Unexecuted instantiation: Builtin.cpp:auto Shell::Shell::builtin_argsparser_parse(Main::Arguments)::$_6::operator()(AK::StringView) const::{lambda(auto:1&)#1}::operator()<Core::ArgsParser::Option>(Core::ArgsParser::Option&) const Unexecuted instantiation: Builtin.cpp:auto Shell::Shell::builtin_argsparser_parse(Main::Arguments)::$_6::operator()(AK::StringView) const::{lambda(auto:1&)#1}::operator()<Core::ArgsParser::Arg>(Core::ArgsParser::Arg&) const |
1850 | 0 | }, |
1851 | 0 | }); |
1852 | 0 | parser.add_option(Core::ArgsParser::Option { |
1853 | 0 | .argument_mode = Core::ArgsParser::OptionArgumentMode::Required, |
1854 | 0 | .help_string = "Set the long name of the option being defined", |
1855 | 0 | .long_name = "long-name", |
1856 | 0 | .value_name = "name", |
1857 | 0 | .accept_value = [&](StringView value) { |
1858 | 0 | auto option = current.get_pointer<Core::ArgsParser::Option>(); |
1859 | 0 | if (!option) { |
1860 | 0 | warnln("Must be defining an option to use --long-name"); |
1861 | 0 | return false; |
1862 | 0 | } |
1863 | 0 | if (option->long_name) { |
1864 | 0 | warnln("Repeated application of --long-name is not allowed, current option has long name set to \"{}\"", option->long_name); |
1865 | 0 | return false; |
1866 | 0 | } |
1867 | | |
1868 | 0 | long_name_storage.append(value); |
1869 | 0 | option->long_name = long_name_storage.last().characters(); |
1870 | 0 | return true; |
1871 | 0 | }, |
1872 | 0 | }); |
1873 | 0 | parser.add_option(Core::ArgsParser::Option { |
1874 | 0 | .argument_mode = Core::ArgsParser::OptionArgumentMode::Required, |
1875 | 0 | .help_string = "Set the short name of the option being defined", |
1876 | 0 | .long_name = "short-name", |
1877 | 0 | .value_name = "char", |
1878 | 0 | .accept_value = [&](StringView value) { |
1879 | 0 | auto option = current.get_pointer<Core::ArgsParser::Option>(); |
1880 | 0 | if (!option) { |
1881 | 0 | warnln("Must be defining an option to use --short-name"); |
1882 | 0 | return false; |
1883 | 0 | } |
1884 | 0 | if (value.length() != 1) { |
1885 | 0 | warnln("Option short name ('{}') must be exactly one character long", value); |
1886 | 0 | return false; |
1887 | 0 | } |
1888 | 0 | if (option->short_name) { |
1889 | 0 | warnln("Repeated application of --short-name is not allowed, current option has short name set to '{}'", option->short_name); |
1890 | 0 | return false; |
1891 | 0 | } |
1892 | 0 | option->short_name = value[0]; |
1893 | 0 | return true; |
1894 | 0 | }, |
1895 | 0 | }); |
1896 | 0 | parser.add_option(Core::ArgsParser::Option { |
1897 | 0 | .argument_mode = Core::ArgsParser::OptionArgumentMode::Required, |
1898 | 0 | .help_string = "Set the value name of the option being defined", |
1899 | 0 | .long_name = "value-name", |
1900 | 0 | .value_name = "string", |
1901 | 0 | .accept_value = [&](StringView value) { |
1902 | 0 | return current.visit( |
1903 | 0 | [](Empty) { |
1904 | 0 | warnln("Must be defining an option or a positional argument to use --value-name"); |
1905 | 0 | return false; |
1906 | 0 | }, |
1907 | 0 | [&](Core::ArgsParser::Option& option) { |
1908 | 0 | if (option.value_name) { |
1909 | 0 | warnln("Repeated application of --value-name is not allowed, current option has value name set to \"{}\"", option.value_name); |
1910 | 0 | return false; |
1911 | 0 | } |
1912 | 0 | if (type == Type::Bool) { |
1913 | 0 | warnln("Options of type bool cannot have a value name"); |
1914 | 0 | return false; |
1915 | 0 | } |
1916 | | |
1917 | 0 | value_name_storage.append(value); |
1918 | 0 | option.value_name = value_name_storage.last().characters(); |
1919 | 0 | return true; |
1920 | 0 | }, |
1921 | 0 | [&](Core::ArgsParser::Arg& arg) { |
1922 | 0 | if (arg.name) { |
1923 | 0 | warnln("Repeated application of --value-name is not allowed, current argument has value name set to \"{}\"", arg.name); |
1924 | 0 | return false; |
1925 | 0 | } |
1926 | | |
1927 | 0 | name_storage.append(value); |
1928 | 0 | arg.name = name_storage.last().characters(); |
1929 | 0 | return true; |
1930 | 0 | }); |
1931 | 0 | }, |
1932 | 0 | }); |
1933 | 0 | parser.add_option(Core::ArgsParser::Option { |
1934 | 0 | .argument_mode = Core::ArgsParser::OptionArgumentMode::Required, |
1935 | 0 | .help_string = "Start describing a positional argument", |
1936 | 0 | .long_name = "add-positional-argument", |
1937 | 0 | .value_name = "variable", |
1938 | 0 | .accept_value = [&](auto value) { |
1939 | 0 | if (!commit()) |
1940 | 0 | return false; |
1941 | | |
1942 | 0 | current = Core::ArgsParser::Arg {}; |
1943 | 0 | current_variable = value; |
1944 | 0 | if (current_variable.is_empty() || !all_of(current_variable, [](auto ch) { return ch == '_' || isalnum(ch); })) { |
1945 | 0 | warnln("Argument variable name must be a valid identifier"); |
1946 | 0 | return false; |
1947 | 0 | } |
1948 | | |
1949 | 0 | return true; |
1950 | 0 | }, |
1951 | 0 | }); |
1952 | 0 | parser.add_option(Core::ArgsParser::Option { |
1953 | 0 | .argument_mode = Core::ArgsParser::OptionArgumentMode::Required, |
1954 | 0 | .help_string = "Set the minimum required number of positional descriptors for the argument being described", |
1955 | 0 | .long_name = "min", |
1956 | 0 | .value_name = "n", |
1957 | 0 | .accept_value = [&](StringView value) { |
1958 | 0 | auto arg = current.get_pointer<Core::ArgsParser::Arg>(); |
1959 | 0 | if (!arg) { |
1960 | 0 | warnln("Must be describing a positional argument to use --min"); |
1961 | 0 | return false; |
1962 | 0 | } |
1963 | | |
1964 | 0 | auto number = value.to_number<unsigned>(); |
1965 | 0 | if (!number.has_value()) { |
1966 | 0 | warnln("Invalid value for --min: '{}', expected a non-negative number", value); |
1967 | 0 | return false; |
1968 | 0 | } |
1969 | | |
1970 | 0 | if (static_cast<unsigned>(arg->max_values) < *number) { |
1971 | 0 | warnln("Invalid value for --min: {}, min must not be larger than max ({})", *number, arg->max_values); |
1972 | 0 | return false; |
1973 | 0 | } |
1974 | | |
1975 | 0 | arg->min_values = *number; |
1976 | 0 | treat_arg_as_list = arg->max_values > 1 || arg->min_values < 1; |
1977 | 0 | return true; |
1978 | 0 | }, |
1979 | 0 | }); |
1980 | 0 | parser.add_option(Core::ArgsParser::Option { |
1981 | 0 | .argument_mode = Core::ArgsParser::OptionArgumentMode::Required, |
1982 | 0 | .help_string = "Set the maximum required number of positional descriptors for the argument being described", |
1983 | 0 | .long_name = "max", |
1984 | 0 | .value_name = "n", |
1985 | 0 | .accept_value = [&](StringView value) { |
1986 | 0 | auto arg = current.get_pointer<Core::ArgsParser::Arg>(); |
1987 | 0 | if (!arg) { |
1988 | 0 | warnln("Must be describing a positional argument to use --max"); |
1989 | 0 | return false; |
1990 | 0 | } |
1991 | | |
1992 | 0 | auto number = value.to_number<unsigned>(); |
1993 | 0 | if (!number.has_value()) { |
1994 | 0 | warnln("Invalid value for --max: '{}', expected a non-negative number", value); |
1995 | 0 | return false; |
1996 | 0 | } |
1997 | | |
1998 | 0 | if (static_cast<unsigned>(arg->min_values) > *number) { |
1999 | 0 | warnln("Invalid value for --max: {}, max must not be smaller than min ({})", *number, arg->min_values); |
2000 | 0 | return false; |
2001 | 0 | } |
2002 | | |
2003 | 0 | arg->max_values = *number; |
2004 | 0 | treat_arg_as_list = arg->max_values > 1 || arg->min_values < 1; |
2005 | 0 | return true; |
2006 | 0 | }, |
2007 | 0 | }); |
2008 | 0 | parser.add_option(Core::ArgsParser::Option { |
2009 | 0 | .argument_mode = Core::ArgsParser::OptionArgumentMode::None, |
2010 | 0 | .help_string = "Mark the positional argument being described as required (shorthand for --min 1)", |
2011 | 0 | .long_name = "required", |
2012 | 0 | .accept_value = [&](auto) { |
2013 | 0 | auto arg = current.get_pointer<Core::ArgsParser::Arg>(); |
2014 | 0 | if (!arg) { |
2015 | 0 | warnln("Must be describing a positional argument to use --required"); |
2016 | 0 | return false; |
2017 | 0 | } |
2018 | 0 | arg->min_values = 1; |
2019 | 0 | if (arg->max_values < arg->min_values) |
2020 | 0 | arg->max_values = 1; |
2021 | 0 | treat_arg_as_list = arg->max_values > 1 || arg->min_values < 1; |
2022 | 0 | return true; |
2023 | 0 | }, |
2024 | 0 | }); |
2025 | 0 | parser.add_positional_argument(descriptors, "Arguments to parse via the described ArgsParser configuration", "arg", Core::ArgsParser::Required::No); |
2026 | |
|
2027 | 0 | if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::Ignore)) |
2028 | 0 | return 2; |
2029 | | |
2030 | 0 | if (!commit()) |
2031 | 0 | return 2; |
2032 | | |
2033 | 0 | if (!user_parser.parse(descriptors, Core::ArgsParser::FailureBehavior::Ignore)) |
2034 | 0 | return 1; |
2035 | | |
2036 | 0 | return 0; |
2037 | 0 | } |
2038 | | |
2039 | | ErrorOr<int> Shell::builtin_read(Main::Arguments arguments) |
2040 | 0 | { |
2041 | 0 | bool no_escape = false; |
2042 | 0 | Vector<ByteString> variables; |
2043 | |
|
2044 | 0 | Core::ArgsParser parser; |
2045 | 0 | parser.add_option(no_escape, "Do not interpret backslash escapes", "no-escape", 'r'); |
2046 | 0 | parser.add_positional_argument(variables, "Variables to read into", "variable", Core::ArgsParser::Required::Yes); |
2047 | |
|
2048 | 0 | if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::Ignore)) |
2049 | 0 | return 1; |
2050 | | |
2051 | 0 | auto split_by_any_of = " \t\n"_string; |
2052 | |
|
2053 | 0 | if (auto const* value_from_env = getenv("IFS"); value_from_env) |
2054 | 0 | split_by_any_of = TRY(String::from_utf8({ value_from_env, strlen(value_from_env) })); |
2055 | 0 | else if (auto split_by_variable = TRY(look_up_local_variable("IFS"sv)); split_by_variable) |
2056 | 0 | split_by_any_of = TRY(const_cast<AST::Value&>(*split_by_variable).resolve_as_string(*this)); |
2057 | | |
2058 | 0 | auto file = TRY(Core::File::standard_input()); |
2059 | 0 | auto buffered_stream = TRY(Core::InputBufferedFile::create(move(file))); |
2060 | | |
2061 | 0 | StringBuilder builder; |
2062 | 0 | ByteBuffer buffer; |
2063 | |
|
2064 | 0 | enum class LineState { |
2065 | 0 | Done, |
2066 | 0 | EscapedNewline, |
2067 | 0 | }; |
2068 | 0 | auto read_line = [&]() -> ErrorOr<LineState> { |
2069 | 0 | if (m_is_interactive && isatty(STDIN_FILENO)) { |
2070 | | // Show prompt |
2071 | 0 | warn("read: "); |
2072 | 0 | } |
2073 | 0 | size_t attempted_line_size = 32; |
2074 | |
|
2075 | 0 | for (;;) { |
2076 | 0 | auto result = buffered_stream->read_line(TRY(buffer.get_bytes_for_writing(attempted_line_size))); |
2077 | 0 | if (result.is_error() && result.error().is_errno() && result.error().code() == EMSGSIZE) { |
2078 | 0 | attempted_line_size *= 2; |
2079 | 0 | continue; |
2080 | 0 | } |
2081 | | |
2082 | 0 | auto used_bytes = TRY(move(result)); |
2083 | 0 | if (!no_escape && used_bytes.ends_with("\\\n"sv)) { |
2084 | 0 | builder.append(used_bytes.substring_view(0, used_bytes.length() - 2)); |
2085 | 0 | return LineState::EscapedNewline; |
2086 | 0 | } |
2087 | | |
2088 | 0 | if (used_bytes.ends_with("\n"sv)) |
2089 | 0 | used_bytes = used_bytes.substring_view(0, used_bytes.length() - 1); |
2090 | |
|
2091 | 0 | builder.append(used_bytes); |
2092 | 0 | return LineState::Done; |
2093 | 0 | } |
2094 | 0 | }; |
2095 | |
|
2096 | 0 | LineState state; |
2097 | 0 | do { |
2098 | 0 | state = TRY(read_line()); |
2099 | 0 | } while (state == LineState::EscapedNewline); |
2100 | | |
2101 | 0 | auto line = builder.string_view(); |
2102 | 0 | if (variables.size() == 1) { |
2103 | 0 | set_local_variable(variables[0], make_ref_counted<AST::StringValue>(TRY(String::from_utf8(line)))); |
2104 | 0 | return 0; |
2105 | 0 | } |
2106 | | |
2107 | 0 | auto fields = line.split_view_if(is_any_of(split_by_any_of), SplitBehavior::KeepEmpty); |
2108 | |
|
2109 | 0 | for (size_t i = 0; i < variables.size(); ++i) { |
2110 | 0 | auto& variable = variables[i]; |
2111 | 0 | StringView variable_value; |
2112 | 0 | if (i >= fields.size()) |
2113 | 0 | variable_value = ""sv; |
2114 | 0 | else if (i == variables.size() - 1) |
2115 | 0 | variable_value = line.substring_view_starting_from_substring(fields[i]); |
2116 | 0 | else |
2117 | 0 | variable_value = fields[i]; |
2118 | |
|
2119 | 0 | set_local_variable(variable, make_ref_counted<AST::StringValue>(TRY(String::from_utf8(variable_value)))); |
2120 | 0 | } |
2121 | | |
2122 | 0 | return 0; |
2123 | 0 | } |
2124 | | |
2125 | | ErrorOr<int> Shell::builtin_run_with_env(Main::Arguments arguments) |
2126 | 0 | { |
2127 | 0 | Vector<ByteString> environment_variables; |
2128 | 0 | Vector<StringView> command_and_arguments; |
2129 | |
|
2130 | 0 | Core::ArgsParser parser; |
2131 | 0 | parser.add_option(environment_variables, "Environment variables to set", "env", 'e', "NAME=VALUE"); |
2132 | 0 | parser.add_positional_argument(command_and_arguments, "Command and arguments to run", "command", Core::ArgsParser::Required::Yes); |
2133 | 0 | parser.set_stop_on_first_non_option(true); |
2134 | |
|
2135 | 0 | if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::Ignore)) |
2136 | 0 | return 1; |
2137 | | |
2138 | 0 | if (command_and_arguments.is_empty()) { |
2139 | 0 | warnln("run_with_env: No command to run"); |
2140 | 0 | return 1; |
2141 | 0 | } |
2142 | | |
2143 | 0 | AST::Command command; |
2144 | 0 | TRY(command.argv.try_ensure_capacity(command_and_arguments.size())); |
2145 | 0 | for (auto& arg : command_and_arguments) |
2146 | 0 | command.argv.append(TRY(String::from_utf8(arg))); |
2147 | | |
2148 | 0 | auto commands = TRY(expand_aliases({ move(command) })); |
2149 | | |
2150 | 0 | HashMap<ByteString, Optional<ByteString>> old_environment_entries; |
2151 | 0 | for (auto& variable : environment_variables) { |
2152 | 0 | auto parts = variable.split_limit('=', 2, SplitBehavior::KeepEmpty); |
2153 | 0 | if (parts.size() != 2) { |
2154 | 0 | warnln("run_with_env: Invalid environment variable: '{}'", variable); |
2155 | 0 | return 1; |
2156 | 0 | } |
2157 | | |
2158 | 0 | ByteString name = parts[0]; |
2159 | 0 | old_environment_entries.set(name, getenv(name.characters()) ?: Optional<ByteString> {}); |
2160 | |
|
2161 | 0 | ByteString value = parts[1]; |
2162 | 0 | setenv(name.characters(), value.characters(), 1); |
2163 | 0 | } |
2164 | | |
2165 | 0 | int exit_code = 0; |
2166 | 0 | for (auto& job : run_commands(commands)) { |
2167 | 0 | block_on_job(job); |
2168 | 0 | exit_code = job->exit_code(); |
2169 | 0 | } |
2170 | |
|
2171 | 0 | for (auto& entry : old_environment_entries) { |
2172 | 0 | if (entry.value.has_value()) |
2173 | 0 | setenv(entry.key.characters(), entry.value->characters(), 1); |
2174 | 0 | else |
2175 | 0 | unsetenv(entry.key.characters()); |
2176 | 0 | } |
2177 | |
|
2178 | 0 | return exit_code; |
2179 | 0 | } |
2180 | | |
2181 | | ErrorOr<int> Shell::builtin_shell_set_active_prompt(Main::Arguments arguments) |
2182 | 0 | { |
2183 | 0 | StringView new_prompt; |
2184 | |
|
2185 | 0 | Core::ArgsParser parser; |
2186 | 0 | parser.add_positional_argument(new_prompt, "New prompt text", "prompt", Core::ArgsParser::Required::Yes); |
2187 | |
|
2188 | 0 | if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::Ignore)) |
2189 | 0 | return 1; |
2190 | | |
2191 | 0 | if (!m_editor) { |
2192 | 0 | warnln("shell_set_active_prompt: No active prompt"); |
2193 | 0 | return 1; |
2194 | 0 | } |
2195 | | |
2196 | 0 | if (m_editor->is_editing()) |
2197 | 0 | m_editor->set_prompt(new_prompt); |
2198 | 0 | else |
2199 | 0 | m_next_scheduled_prompt_text = new_prompt; |
2200 | 0 | return 0; |
2201 | 0 | } |
2202 | | |
2203 | | ErrorOr<int> Shell::builtin_in_parallel(Main::Arguments arguments) |
2204 | 0 | { |
2205 | 0 | unsigned max_jobs = 1; |
2206 | 0 | Vector<StringView> command_and_arguments; |
2207 | |
|
2208 | 0 | #ifdef _SC_NPROCESSORS_ONLN |
2209 | 0 | max_jobs = sysconf(_SC_NPROCESSORS_ONLN); |
2210 | 0 | #endif |
2211 | |
|
2212 | 0 | Core::ArgsParser parser; |
2213 | 0 | parser.set_general_help("Run the given command in the background, allowing at most <N> jobs running at once."); |
2214 | 0 | parser.add_option(max_jobs, "Maximum number of jobs to run in parallel", "max-jobs", 'j', "N"); |
2215 | 0 | parser.add_positional_argument(command_and_arguments, "Command and arguments to run", "argument", Core::ArgsParser::Required::Yes); |
2216 | 0 | parser.set_stop_on_first_non_option(true); |
2217 | |
|
2218 | 0 | if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::Ignore)) |
2219 | 0 | return 1; |
2220 | | |
2221 | 0 | if (command_and_arguments.is_empty()) { |
2222 | 0 | warnln("in_parallel: No command to run"); |
2223 | 0 | return 1; |
2224 | 0 | } |
2225 | | |
2226 | 0 | AST::Command command; |
2227 | 0 | TRY(command.argv.try_ensure_capacity(command_and_arguments.size())); |
2228 | 0 | for (auto& arg : command_and_arguments) |
2229 | 0 | command.argv.append(TRY(String::from_utf8(arg))); |
2230 | | |
2231 | 0 | auto commands = TRY(expand_aliases({ move(command) })); |
2232 | | |
2233 | 0 | Vector<AST::Command> commands_to_run; |
2234 | 0 | for (auto& command : commands) { |
2235 | 0 | if (command.argv.is_empty()) |
2236 | 0 | continue; |
2237 | 0 | command.should_notify_if_in_background = false; |
2238 | 0 | command.should_wait = false; |
2239 | 0 | commands_to_run.append(move(command)); |
2240 | 0 | } |
2241 | |
|
2242 | 0 | if (commands_to_run.is_empty()) { |
2243 | 0 | warnln("in_parallel: No command to run"); |
2244 | 0 | return 1; |
2245 | 0 | } |
2246 | | |
2247 | 0 | Core::EventLoop loop; |
2248 | 0 | loop.spin_until([&] { return jobs.size() + commands_to_run.size() <= max_jobs; }); |
2249 | 0 | run_commands(commands_to_run); |
2250 | 0 | return 0; |
2251 | 0 | } |
2252 | | |
2253 | | bool Shell::has_builtin(StringView name) const |
2254 | 0 | { |
2255 | 0 | if (name == ":"sv || (m_in_posix_mode && name == "."sv)) |
2256 | 0 | return true; |
2257 | | |
2258 | 0 | #define __ENUMERATE_SHELL_BUILTIN(builtin, mode) \ |
2259 | 0 | if (name == #builtin) { \ |
2260 | 0 | if (POSIXModeRequirement::mode == POSIXModeRequirement::InAllModes) \ |
2261 | 0 | return true; \ |
2262 | 0 | return m_in_posix_mode; \ |
2263 | 0 | } |
2264 | | |
2265 | 0 | ENUMERATE_SHELL_BUILTINS(); |
2266 | |
|
2267 | 0 | #undef __ENUMERATE_SHELL_BUILTIN |
2268 | 0 | return false; |
2269 | 0 | } |
2270 | | } |