Builtin.cpp 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704
  1. /*
  2. * Copyright (c) 2020-2021, the SerenityOS developers.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "AST.h"
  7. #include "Formatter.h"
  8. #include "PosixParser.h"
  9. #include "Shell.h"
  10. #include <AK/DeprecatedString.h>
  11. #include <AK/LexicalPath.h>
  12. #include <AK/ScopeGuard.h>
  13. #include <AK/Statistics.h>
  14. #include <LibCore/ArgsParser.h>
  15. #include <LibCore/DeprecatedFile.h>
  16. #include <LibCore/EventLoop.h>
  17. #include <errno.h>
  18. #include <inttypes.h>
  19. #include <limits.h>
  20. #include <signal.h>
  21. #include <sys/wait.h>
  22. #include <unistd.h>
  23. extern char** environ;
  24. namespace Shell {
  25. int Shell::builtin_noop(int, char const**)
  26. {
  27. return 0;
  28. }
  29. int Shell::builtin_dump(int argc, char const** argv)
  30. {
  31. bool posix = false;
  32. StringView source;
  33. Core::ArgsParser parser;
  34. parser.add_positional_argument(source, "Shell code to parse and dump", "source");
  35. parser.add_option(posix, "Use the POSIX parser", "posix", 'p');
  36. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  37. return 1;
  38. (posix ? Posix::Parser { source }.parse() : Parser { source }.parse())->dump(0);
  39. return 0;
  40. }
  41. enum FollowSymlinks {
  42. Yes,
  43. No
  44. };
  45. static Vector<DeprecatedString> find_matching_executables_in_path(StringView filename, FollowSymlinks follow_symlinks = FollowSymlinks::No)
  46. {
  47. // Edge cases in which there are guaranteed no solutions
  48. if (filename.is_empty() || filename.contains('/'))
  49. return {};
  50. char const* path_str = getenv("PATH");
  51. auto path = DEFAULT_PATH_SV;
  52. if (path_str != nullptr) // maybe && *path_str
  53. path = { path_str, strlen(path_str) };
  54. Vector<DeprecatedString> executables;
  55. auto directories = path.split_view(':');
  56. for (auto directory : directories) {
  57. auto file = DeprecatedString::formatted("{}/{}", directory, filename);
  58. if (follow_symlinks == FollowSymlinks::Yes) {
  59. auto path_or_error = Core::DeprecatedFile::read_link(file);
  60. if (!path_or_error.is_error())
  61. file = path_or_error.release_value();
  62. }
  63. if (access(file.characters(), X_OK) == 0)
  64. executables.append(move(file));
  65. }
  66. return executables;
  67. }
  68. int Shell::builtin_where(int argc, char const** argv)
  69. {
  70. Vector<StringView> arguments;
  71. bool do_only_path_search { false };
  72. bool do_follow_symlinks { false };
  73. bool do_print_only_type { false };
  74. Core::ArgsParser parser;
  75. parser.add_positional_argument(arguments, "List of shell builtins, aliases or executables", "arguments");
  76. parser.add_option(do_only_path_search, "Search only for executables in the PATH environment variable", "path-only", 'p');
  77. parser.add_option(do_follow_symlinks, "Follow symlinks and print the symlink free path", "follow-symlink", 's');
  78. parser.add_option(do_print_only_type, "Print the argument type instead of a human readable description", "type", 'w');
  79. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  80. return 1;
  81. auto const lookup_alias = [do_only_path_search, &m_aliases = this->m_aliases](StringView alias) -> Optional<DeprecatedString> {
  82. if (do_only_path_search)
  83. return {};
  84. return m_aliases.get(alias);
  85. };
  86. auto const lookup_builtin = [do_only_path_search](StringView builtin) -> Optional<DeprecatedString> {
  87. if (do_only_path_search)
  88. return {};
  89. for (auto const& _builtin : builtin_names) {
  90. if (_builtin == builtin) {
  91. return builtin;
  92. }
  93. }
  94. return {};
  95. };
  96. bool at_least_one_succeded { false };
  97. for (auto const& argument : arguments) {
  98. auto const alias = lookup_alias(argument);
  99. if (alias.has_value()) {
  100. if (do_print_only_type)
  101. outln("{}: alias", argument);
  102. else
  103. outln("{}: aliased to {}", argument, alias.value());
  104. at_least_one_succeded = true;
  105. }
  106. auto const builtin = lookup_builtin(argument);
  107. if (builtin.has_value()) {
  108. if (do_print_only_type)
  109. outln("{}: builtin", builtin.value());
  110. else
  111. outln("{}: shell built-in command", builtin.value());
  112. at_least_one_succeded = true;
  113. }
  114. auto const executables = find_matching_executables_in_path(argument, do_follow_symlinks ? FollowSymlinks::Yes : FollowSymlinks::No);
  115. for (auto const& path : executables) {
  116. if (do_print_only_type)
  117. outln("{}: command", argument);
  118. else
  119. outln(path);
  120. at_least_one_succeded = true;
  121. }
  122. if (!at_least_one_succeded)
  123. warnln("{} not found", argument);
  124. }
  125. return at_least_one_succeded ? 0 : 1;
  126. }
  127. int Shell::builtin_alias(int argc, char const** argv)
  128. {
  129. Vector<DeprecatedString> arguments;
  130. Core::ArgsParser parser;
  131. parser.add_positional_argument(arguments, "List of name[=values]'s", "name[=value]", Core::ArgsParser::Required::No);
  132. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  133. return 1;
  134. if (arguments.is_empty()) {
  135. for (auto& alias : m_aliases)
  136. printf("%s=%s\n", escape_token(alias.key).characters(), escape_token(alias.value).characters());
  137. return 0;
  138. }
  139. bool fail = false;
  140. for (auto& argument : arguments) {
  141. auto parts = argument.split_limit('=', 2, SplitBehavior::KeepEmpty);
  142. if (parts.size() == 1) {
  143. auto alias = m_aliases.get(parts[0]);
  144. if (alias.has_value()) {
  145. printf("%s=%s\n", escape_token(parts[0]).characters(), escape_token(alias.value()).characters());
  146. } else {
  147. fail = true;
  148. }
  149. } else {
  150. m_aliases.set(parts[0], parts[1]);
  151. add_entry_to_cache({ RunnablePath::Kind::Alias, parts[0] });
  152. }
  153. }
  154. return fail ? 1 : 0;
  155. }
  156. int Shell::builtin_unalias(int argc, char const** argv)
  157. {
  158. bool remove_all { false };
  159. Vector<DeprecatedString> arguments;
  160. Core::ArgsParser parser;
  161. parser.set_general_help("Remove alias from the list of aliases");
  162. parser.add_option(remove_all, "Remove all aliases", nullptr, 'a');
  163. parser.add_positional_argument(arguments, "List of aliases to remove", "alias", Core::ArgsParser::Required::No);
  164. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  165. return 1;
  166. if (remove_all) {
  167. m_aliases.clear();
  168. cache_path();
  169. return 0;
  170. }
  171. if (arguments.is_empty()) {
  172. warnln("unalias: not enough arguments");
  173. parser.print_usage(stderr, argv[0]);
  174. return 1;
  175. }
  176. bool failed { false };
  177. for (auto& argument : arguments) {
  178. if (!m_aliases.contains(argument)) {
  179. warnln("unalias: {}: alias not found", argument);
  180. failed = true;
  181. continue;
  182. }
  183. m_aliases.remove(argument);
  184. remove_entry_from_cache(argument);
  185. }
  186. return failed ? 1 : 0;
  187. }
  188. int Shell::builtin_bg(int argc, char const** argv)
  189. {
  190. int job_id = -1;
  191. bool is_pid = false;
  192. Core::ArgsParser parser;
  193. parser.add_positional_argument(Core::ArgsParser::Arg {
  194. .help_string = "Job ID or Jobspec to run in background",
  195. .name = "job-id",
  196. .min_values = 0,
  197. .max_values = 1,
  198. .accept_value = [&](auto value_ptr) -> bool {
  199. StringView value { value_ptr, strlen(value_ptr) };
  200. // Check if it's a pid (i.e. literal integer)
  201. if (auto number = value.to_uint(); number.has_value()) {
  202. job_id = number.value();
  203. is_pid = true;
  204. return true;
  205. }
  206. // Check if it's a jobspec
  207. if (auto id = resolve_job_spec(value); id.has_value()) {
  208. job_id = id.value();
  209. is_pid = false;
  210. return true;
  211. }
  212. return false;
  213. } });
  214. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  215. return 1;
  216. if (job_id == -1 && !jobs.is_empty())
  217. job_id = find_last_job_id();
  218. auto* job = const_cast<Job*>(find_job(job_id, is_pid));
  219. if (!job) {
  220. if (job_id == -1) {
  221. warnln("bg: No current job");
  222. } else {
  223. warnln("bg: Job with id/pid {} not found", job_id);
  224. }
  225. return 1;
  226. }
  227. job->set_running_in_background(true);
  228. job->set_should_announce_exit(true);
  229. job->set_shell_did_continue(true);
  230. dbgln("Resuming {} ({})", job->pid(), job->cmd());
  231. warnln("Resuming job {} - {}", job->job_id(), job->cmd());
  232. // Try using the PGID, but if that fails, just use the PID.
  233. if (killpg(job->pgid(), SIGCONT) < 0) {
  234. if (kill(job->pid(), SIGCONT) < 0) {
  235. perror("kill");
  236. return 1;
  237. }
  238. }
  239. return 0;
  240. }
  241. int Shell::builtin_type(int argc, char const** argv)
  242. {
  243. Vector<DeprecatedString> commands;
  244. bool dont_show_function_source = false;
  245. Core::ArgsParser parser;
  246. parser.set_general_help("Display information about commands.");
  247. parser.add_positional_argument(commands, "Command(s) to list info about", "command");
  248. parser.add_option(dont_show_function_source, "Do not show functions source.", "no-fn-source", 'f');
  249. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  250. return 1;
  251. bool something_not_found = false;
  252. for (auto& command : commands) {
  253. // check if it is an alias
  254. if (auto alias = m_aliases.get(command); alias.has_value()) {
  255. printf("%s is aliased to `%s`\n", escape_token(command).characters(), escape_token(alias.value()).characters());
  256. continue;
  257. }
  258. // check if it is a function
  259. if (auto function = m_functions.get(command); function.has_value()) {
  260. auto fn = function.value();
  261. printf("%s is a function\n", command.characters());
  262. if (!dont_show_function_source) {
  263. StringBuilder builder;
  264. builder.append(fn.name);
  265. builder.append('(');
  266. for (size_t i = 0; i < fn.arguments.size(); i++) {
  267. builder.append(fn.arguments[i]);
  268. if (!(i == fn.arguments.size() - 1))
  269. builder.append(' ');
  270. }
  271. builder.append(") {\n"sv);
  272. if (fn.body) {
  273. auto formatter = Formatter(*fn.body);
  274. builder.append(formatter.format());
  275. printf("%s\n}\n", builder.to_deprecated_string().characters());
  276. } else {
  277. printf("%s\n}\n", builder.to_deprecated_string().characters());
  278. }
  279. }
  280. continue;
  281. }
  282. // check if its a builtin
  283. if (has_builtin(command)) {
  284. printf("%s is a shell builtin\n", command.characters());
  285. continue;
  286. }
  287. // check if its an executable in PATH
  288. auto fullpath = Core::DeprecatedFile::resolve_executable_from_environment(command);
  289. if (fullpath.has_value()) {
  290. printf("%s is %s\n", command.characters(), escape_token(fullpath.release_value()).characters());
  291. continue;
  292. }
  293. something_not_found = true;
  294. printf("type: %s not found\n", command.characters());
  295. }
  296. if (something_not_found)
  297. return 1;
  298. else
  299. return 0;
  300. }
  301. int Shell::builtin_cd(int argc, char const** argv)
  302. {
  303. char const* arg_path = nullptr;
  304. Core::ArgsParser parser;
  305. parser.add_positional_argument(arg_path, "Path to change to", "path", Core::ArgsParser::Required::No);
  306. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  307. return 1;
  308. DeprecatedString new_path;
  309. if (!arg_path) {
  310. new_path = home;
  311. } else {
  312. if (strcmp(arg_path, "-") == 0) {
  313. char* oldpwd = getenv("OLDPWD");
  314. if (oldpwd == nullptr)
  315. return 1;
  316. new_path = oldpwd;
  317. } else {
  318. new_path = arg_path;
  319. }
  320. }
  321. auto real_path = Core::DeprecatedFile::real_path_for(new_path);
  322. if (real_path.is_empty()) {
  323. warnln("Invalid path '{}'", new_path);
  324. return 1;
  325. }
  326. if (cd_history.is_empty() || cd_history.last() != real_path)
  327. cd_history.enqueue(real_path);
  328. auto path_relative_to_current_directory = LexicalPath::relative_path(real_path, cwd);
  329. if (path_relative_to_current_directory.is_empty())
  330. path_relative_to_current_directory = real_path;
  331. char const* path = path_relative_to_current_directory.characters();
  332. int rc = chdir(path);
  333. if (rc < 0) {
  334. if (errno == ENOTDIR) {
  335. warnln("Not a directory: {}", path);
  336. } else {
  337. warnln("chdir({}) failed: {}", path, strerror(errno));
  338. }
  339. return 1;
  340. }
  341. setenv("OLDPWD", cwd.characters(), 1);
  342. cwd = move(real_path);
  343. setenv("PWD", cwd.characters(), 1);
  344. return 0;
  345. }
  346. int Shell::builtin_cdh(int argc, char const** argv)
  347. {
  348. int index = -1;
  349. Core::ArgsParser parser;
  350. parser.add_positional_argument(index, "Index of the cd history entry (leave out for a list)", "index", Core::ArgsParser::Required::No);
  351. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  352. return 1;
  353. if (index == -1) {
  354. if (cd_history.is_empty()) {
  355. warnln("cdh: no history available");
  356. return 0;
  357. }
  358. for (ssize_t i = cd_history.size() - 1; i >= 0; --i)
  359. printf("%zu: %s\n", cd_history.size() - i, cd_history.at(i).characters());
  360. return 0;
  361. }
  362. if (index < 1 || (size_t)index > cd_history.size()) {
  363. warnln("cdh: history index out of bounds: {} not in (0, {})", index, cd_history.size());
  364. return 1;
  365. }
  366. char const* path = cd_history.at(cd_history.size() - index).characters();
  367. char const* cd_args[] = { "cd", path, nullptr };
  368. return Shell::builtin_cd(2, cd_args);
  369. }
  370. int Shell::builtin_dirs(int argc, char const** argv)
  371. {
  372. // The first directory in the stack is ALWAYS the current directory
  373. directory_stack.at(0) = cwd.characters();
  374. bool clear = false;
  375. bool print = false;
  376. bool number_when_printing = false;
  377. char separator = ' ';
  378. Vector<DeprecatedString> paths;
  379. Core::ArgsParser parser;
  380. parser.add_option(clear, "Clear the directory stack", "clear", 'c');
  381. parser.add_option(print, "Print directory entries one per line", "print", 'p');
  382. parser.add_option(number_when_printing, "Number the directories in the stack when printing", "number", 'v');
  383. parser.add_positional_argument(paths, "Extra paths to put on the stack", "path", Core::ArgsParser::Required::No);
  384. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  385. return 1;
  386. // -v implies -p
  387. print = print || number_when_printing;
  388. if (print) {
  389. if (!paths.is_empty()) {
  390. warnln("dirs: 'print' and 'number' are not allowed when any path is specified");
  391. return 1;
  392. }
  393. separator = '\n';
  394. }
  395. if (clear) {
  396. for (size_t i = 1; i < directory_stack.size(); i++)
  397. directory_stack.remove(i);
  398. }
  399. for (auto& path : paths)
  400. directory_stack.append(path);
  401. if (print || (!clear && paths.is_empty())) {
  402. int index = 0;
  403. for (auto& directory : directory_stack) {
  404. if (number_when_printing)
  405. printf("%d ", index++);
  406. print_path(directory);
  407. fputc(separator, stdout);
  408. }
  409. }
  410. return 0;
  411. }
  412. int Shell::builtin_exec(int argc, char const** argv)
  413. {
  414. if (argc < 2) {
  415. warnln("Shell: No command given to exec");
  416. return 1;
  417. }
  418. Vector<char const*> argv_vector;
  419. argv_vector.append(argv + 1, argc - 1);
  420. argv_vector.append(nullptr);
  421. execute_process(move(argv_vector));
  422. }
  423. int Shell::builtin_exit(int argc, char const** argv)
  424. {
  425. int exit_code = 0;
  426. Core::ArgsParser parser;
  427. parser.add_positional_argument(exit_code, "Exit code", "code", Core::ArgsParser::Required::No);
  428. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  429. return 1;
  430. if (m_is_interactive) {
  431. if (!jobs.is_empty()) {
  432. if (!m_should_ignore_jobs_on_next_exit) {
  433. warnln("Shell: You have {} active job{}, run 'exit' again to really exit.", jobs.size(), jobs.size() > 1 ? "s" : "");
  434. m_should_ignore_jobs_on_next_exit = true;
  435. return 1;
  436. }
  437. }
  438. }
  439. stop_all_jobs();
  440. if (m_is_interactive) {
  441. m_editor->save_history(get_history_path());
  442. printf("Good-bye!\n");
  443. }
  444. exit(exit_code);
  445. }
  446. int Shell::builtin_export(int argc, char const** argv)
  447. {
  448. Vector<DeprecatedString> vars;
  449. Core::ArgsParser parser;
  450. parser.add_positional_argument(vars, "List of variable[=value]'s", "values", Core::ArgsParser::Required::No);
  451. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  452. return 1;
  453. if (vars.is_empty()) {
  454. for (size_t i = 0; environ[i]; ++i)
  455. puts(environ[i]);
  456. return 0;
  457. }
  458. for (auto& value : vars) {
  459. auto parts = value.split_limit('=', 2);
  460. if (parts.size() == 1) {
  461. auto value = lookup_local_variable(parts[0]);
  462. if (value) {
  463. auto values = const_cast<AST::Value&>(*value).resolve_as_list(*this);
  464. StringBuilder builder;
  465. builder.join(' ', values);
  466. parts.append(builder.to_deprecated_string());
  467. } else {
  468. // Ignore the export.
  469. continue;
  470. }
  471. }
  472. int setenv_return = setenv(parts[0].characters(), parts[1].characters(), 1);
  473. if (setenv_return != 0) {
  474. perror("setenv");
  475. return 1;
  476. }
  477. if (parts[0] == "PATH")
  478. cache_path();
  479. }
  480. return 0;
  481. }
  482. int Shell::builtin_glob(int argc, char const** argv)
  483. {
  484. Vector<DeprecatedString> globs;
  485. Core::ArgsParser parser;
  486. parser.add_positional_argument(globs, "Globs to resolve", "glob");
  487. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  488. return 1;
  489. for (auto& glob : globs) {
  490. for (auto& expanded : expand_globs(glob, cwd))
  491. outln("{}", expanded);
  492. }
  493. return 0;
  494. }
  495. int Shell::builtin_fg(int argc, char const** argv)
  496. {
  497. int job_id = -1;
  498. bool is_pid = false;
  499. Core::ArgsParser parser;
  500. parser.add_positional_argument(Core::ArgsParser::Arg {
  501. .help_string = "Job ID or Jobspec to bring to foreground",
  502. .name = "job-id",
  503. .min_values = 0,
  504. .max_values = 1,
  505. .accept_value = [&](auto const* value_ptr) -> bool {
  506. StringView value { value_ptr, strlen(value_ptr) };
  507. // Check if it's a pid (i.e. literal integer)
  508. if (auto number = value.to_uint(); number.has_value()) {
  509. job_id = number.value();
  510. is_pid = true;
  511. return true;
  512. }
  513. // Check if it's a jobspec
  514. if (auto id = resolve_job_spec(value); id.has_value()) {
  515. job_id = id.value();
  516. is_pid = false;
  517. return true;
  518. }
  519. return false;
  520. } });
  521. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  522. return 1;
  523. if (job_id == -1 && !jobs.is_empty())
  524. job_id = find_last_job_id();
  525. RefPtr<Job> job = find_job(job_id, is_pid);
  526. if (!job) {
  527. if (job_id == -1) {
  528. warnln("fg: No current job");
  529. } else {
  530. warnln("fg: Job with id/pid {} not found", job_id);
  531. }
  532. return 1;
  533. }
  534. job->set_running_in_background(false);
  535. job->set_shell_did_continue(true);
  536. dbgln("Resuming {} ({})", job->pid(), job->cmd());
  537. warnln("Resuming job {} - {}", job->job_id(), job->cmd());
  538. tcsetpgrp(STDOUT_FILENO, job->pgid());
  539. tcsetpgrp(STDIN_FILENO, job->pgid());
  540. // Try using the PGID, but if that fails, just use the PID.
  541. if (killpg(job->pgid(), SIGCONT) < 0) {
  542. if (kill(job->pid(), SIGCONT) < 0) {
  543. perror("kill");
  544. return 1;
  545. }
  546. }
  547. block_on_job(job);
  548. if (job->exited())
  549. return job->exit_code();
  550. else
  551. return 0;
  552. }
  553. int Shell::builtin_disown(int argc, char const** argv)
  554. {
  555. Vector<int> job_ids;
  556. Vector<bool> id_is_pid;
  557. Core::ArgsParser parser;
  558. parser.add_positional_argument(Core::ArgsParser::Arg {
  559. .help_string = "Job IDs or Jobspecs to disown",
  560. .name = "job-id",
  561. .min_values = 0,
  562. .max_values = INT_MAX,
  563. .accept_value = [&](auto const* value_ptr) -> bool {
  564. StringView value { value_ptr, strlen(value_ptr) };
  565. // Check if it's a pid (i.e. literal integer)
  566. if (auto number = value.to_uint(); number.has_value()) {
  567. job_ids.append(number.value());
  568. id_is_pid.append(true);
  569. return true;
  570. }
  571. // Check if it's a jobspec
  572. if (auto id = resolve_job_spec(value); id.has_value()) {
  573. job_ids.append(id.value());
  574. id_is_pid.append(false);
  575. return true;
  576. }
  577. return false;
  578. } });
  579. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  580. return 1;
  581. if (job_ids.is_empty()) {
  582. job_ids.append(find_last_job_id());
  583. id_is_pid.append(false);
  584. }
  585. Vector<Job const*> jobs_to_disown;
  586. for (size_t i = 0; i < job_ids.size(); ++i) {
  587. auto id = job_ids[i];
  588. auto is_pid = id_is_pid[i];
  589. auto job = find_job(id, is_pid);
  590. if (!job)
  591. warnln("disown: Job with id/pid {} not found", id);
  592. else
  593. jobs_to_disown.append(job);
  594. }
  595. if (jobs_to_disown.is_empty()) {
  596. if (job_ids.is_empty())
  597. warnln("disown: No current job");
  598. // An error message has already been printed about the nonexistence of each listed job.
  599. return 1;
  600. }
  601. for (auto job : jobs_to_disown) {
  602. job->deactivate();
  603. if (!job->is_running_in_background())
  604. warnln("disown warning: Job {} is currently not running, 'kill -{} {}' to make it continue", job->job_id(), SIGCONT, job->pid());
  605. jobs.remove(job->pid());
  606. }
  607. return 0;
  608. }
  609. int Shell::builtin_history(int, char const**)
  610. {
  611. for (size_t i = 0; i < m_editor->history().size(); ++i) {
  612. printf("%6zu %s\n", i + 1, m_editor->history()[i].entry.characters());
  613. }
  614. return 0;
  615. }
  616. int Shell::builtin_jobs(int argc, char const** argv)
  617. {
  618. bool list = false, show_pid = false;
  619. Core::ArgsParser parser;
  620. parser.add_option(list, "List all information about jobs", "list", 'l');
  621. parser.add_option(show_pid, "Display the PID of the jobs", "pid", 'p');
  622. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  623. return 1;
  624. Job::PrintStatusMode mode = Job::PrintStatusMode::Basic;
  625. if (show_pid)
  626. mode = Job::PrintStatusMode::OnlyPID;
  627. if (list)
  628. mode = Job::PrintStatusMode::ListAll;
  629. for (auto& it : jobs) {
  630. if (!it.value->print_status(mode))
  631. return 1;
  632. }
  633. return 0;
  634. }
  635. int Shell::builtin_popd(int argc, char const** argv)
  636. {
  637. if (directory_stack.size() <= 1) {
  638. warnln("Shell: popd: directory stack empty");
  639. return 1;
  640. }
  641. bool should_not_switch = false;
  642. Core::ArgsParser parser;
  643. parser.add_option(should_not_switch, "Do not switch dirs", "no-switch", 'n');
  644. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  645. return 1;
  646. auto popped_path = directory_stack.take_last();
  647. if (should_not_switch)
  648. return 0;
  649. auto new_path = LexicalPath::canonicalized_path(popped_path);
  650. if (chdir(new_path.characters()) < 0) {
  651. warnln("chdir({}) failed: {}", new_path, strerror(errno));
  652. return 1;
  653. }
  654. cwd = new_path;
  655. return 0;
  656. }
  657. int Shell::builtin_pushd(int argc, char const** argv)
  658. {
  659. StringBuilder path_builder;
  660. bool should_switch = true;
  661. // From the BASH reference manual: https://www.gnu.org/software/bash/manual/html_node/Directory-Stack-Builtins.html
  662. // With no arguments, pushd exchanges the top two directories and makes the new top the current directory.
  663. if (argc == 1) {
  664. if (directory_stack.size() < 2) {
  665. warnln("pushd: no other directory");
  666. return 1;
  667. }
  668. DeprecatedString dir1 = directory_stack.take_first();
  669. DeprecatedString dir2 = directory_stack.take_first();
  670. directory_stack.insert(0, dir2);
  671. directory_stack.insert(1, dir1);
  672. int rc = chdir(dir2.characters());
  673. if (rc < 0) {
  674. warnln("chdir({}) failed: {}", dir2, strerror(errno));
  675. return 1;
  676. }
  677. cwd = dir2;
  678. return 0;
  679. }
  680. // Let's assume the user's typed in 'pushd <dir>'
  681. if (argc == 2) {
  682. directory_stack.append(cwd.characters());
  683. if (argv[1][0] == '/') {
  684. path_builder.append({ argv[1], strlen(argv[1]) });
  685. } else {
  686. path_builder.appendff("{}/{}", cwd, argv[1]);
  687. }
  688. } else if (argc == 3) {
  689. directory_stack.append(cwd.characters());
  690. for (int i = 1; i < argc; i++) {
  691. char const* arg = argv[i];
  692. if (arg[0] != '-') {
  693. if (arg[0] == '/') {
  694. path_builder.append({ arg, strlen(arg) });
  695. } else
  696. path_builder.appendff("{}/{}", cwd, arg);
  697. }
  698. if (!strcmp(arg, "-n"))
  699. should_switch = false;
  700. }
  701. }
  702. auto real_path = LexicalPath::canonicalized_path(path_builder.to_deprecated_string());
  703. struct stat st;
  704. int rc = stat(real_path.characters(), &st);
  705. if (rc < 0) {
  706. warnln("stat({}) failed: {}", real_path, strerror(errno));
  707. return 1;
  708. }
  709. if (!S_ISDIR(st.st_mode)) {
  710. warnln("Not a directory: {}", real_path);
  711. return 1;
  712. }
  713. if (should_switch) {
  714. int rc = chdir(real_path.characters());
  715. if (rc < 0) {
  716. warnln("chdir({}) failed: {}", real_path, strerror(errno));
  717. return 1;
  718. }
  719. cwd = real_path;
  720. }
  721. return 0;
  722. }
  723. int Shell::builtin_pwd(int, char const**)
  724. {
  725. print_path(cwd);
  726. fputc('\n', stdout);
  727. return 0;
  728. }
  729. int Shell::builtin_setopt(int argc, char const** argv)
  730. {
  731. if (argc == 1) {
  732. #define __ENUMERATE_SHELL_OPTION(name, default_, description) \
  733. if (options.name) \
  734. warnln("{}", #name);
  735. ENUMERATE_SHELL_OPTIONS();
  736. #undef __ENUMERATE_SHELL_OPTION
  737. }
  738. Core::ArgsParser parser;
  739. #define __ENUMERATE_SHELL_OPTION(name, default_, description) \
  740. bool name = false; \
  741. bool not_##name = false; \
  742. parser.add_option(name, "Enable: " description, #name, '\0'); \
  743. parser.add_option(not_##name, "Disable: " description, "no_" #name, '\0');
  744. ENUMERATE_SHELL_OPTIONS();
  745. #undef __ENUMERATE_SHELL_OPTION
  746. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  747. return 1;
  748. #define __ENUMERATE_SHELL_OPTION(name, default_, description) \
  749. if (name) \
  750. options.name = true; \
  751. if (not_##name) \
  752. options.name = false;
  753. ENUMERATE_SHELL_OPTIONS();
  754. #undef __ENUMERATE_SHELL_OPTION
  755. return 0;
  756. }
  757. int Shell::builtin_shift(int argc, char const** argv)
  758. {
  759. int count = 1;
  760. Core::ArgsParser parser;
  761. parser.add_positional_argument(count, "Shift count", "count", Core::ArgsParser::Required::No);
  762. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  763. return 1;
  764. if (count < 1)
  765. return 0;
  766. auto argv_ = lookup_local_variable("ARGV"sv);
  767. if (!argv_) {
  768. warnln("shift: ARGV is unset");
  769. return 1;
  770. }
  771. if (!argv_->is_list())
  772. argv_ = adopt_ref(*new AST::ListValue({ const_cast<AST::Value&>(*argv_) }));
  773. auto& values = const_cast<AST::ListValue*>(static_cast<AST::ListValue const*>(argv_.ptr()))->values();
  774. if ((size_t)count > values.size()) {
  775. warnln("shift: shift count must not be greater than {}", values.size());
  776. return 1;
  777. }
  778. for (auto i = 0; i < count; ++i)
  779. (void)values.take_first();
  780. return 0;
  781. }
  782. int Shell::builtin_source(int argc, char const** argv)
  783. {
  784. char const* file_to_source = nullptr;
  785. Vector<DeprecatedString> args;
  786. Core::ArgsParser parser;
  787. parser.add_positional_argument(file_to_source, "File to read commands from", "path");
  788. parser.add_positional_argument(args, "ARGV for the sourced file", "args", Core::ArgsParser::Required::No);
  789. if (!parser.parse(argc, const_cast<char**>(argv)))
  790. return 1;
  791. auto previous_argv = lookup_local_variable("ARGV"sv);
  792. ScopeGuard guard { [&] {
  793. if (!args.is_empty())
  794. set_local_variable("ARGV", const_cast<AST::Value&>(*previous_argv));
  795. } };
  796. if (!args.is_empty())
  797. set_local_variable("ARGV", AST::make_ref_counted<AST::ListValue>(move(args)));
  798. if (!run_file(file_to_source, true))
  799. return 126;
  800. return 0;
  801. }
  802. int Shell::builtin_time(int argc, char const** argv)
  803. {
  804. AST::Command command;
  805. int number_of_iterations = 1;
  806. Core::ArgsParser parser;
  807. parser.add_option(number_of_iterations, "Number of iterations", "iterations", 'n', "iterations");
  808. parser.set_stop_on_first_non_option(true);
  809. parser.add_positional_argument(command.argv, "Command to execute with arguments", "command", Core::ArgsParser::Required::Yes);
  810. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  811. return 1;
  812. if (number_of_iterations < 1)
  813. return 1;
  814. auto commands = expand_aliases({ move(command) });
  815. AK::Statistics iteration_times;
  816. int exit_code = 1;
  817. for (int i = 0; i < number_of_iterations; ++i) {
  818. auto timer = Core::ElapsedTimer::start_new();
  819. for (auto& job : run_commands(commands)) {
  820. block_on_job(job);
  821. exit_code = job.exit_code();
  822. }
  823. iteration_times.add(static_cast<float>(timer.elapsed()));
  824. }
  825. if (number_of_iterations == 1) {
  826. warnln("Time: {} ms", iteration_times.values().first());
  827. } else {
  828. AK::Statistics iteration_times_excluding_first;
  829. for (size_t i = 1; i < iteration_times.size(); i++)
  830. iteration_times_excluding_first.add(iteration_times.values()[i]);
  831. warnln("Timing report: {} ms", iteration_times.sum());
  832. warnln("==============");
  833. warnln("Command: {}", DeprecatedString::join(' ', Span<char const*>(argv, argc)));
  834. warnln("Average time: {:.2} ms (median: {}, stddev: {:.2}, min: {}, max:{})",
  835. iteration_times.average(), iteration_times.median(),
  836. iteration_times.standard_deviation(),
  837. iteration_times.min(), iteration_times.max());
  838. warnln("Excluding first: {:.2} ms (median: {}, stddev: {:.2}, min: {}, max:{})",
  839. iteration_times_excluding_first.average(), iteration_times_excluding_first.median(),
  840. iteration_times_excluding_first.standard_deviation(),
  841. iteration_times_excluding_first.min(), iteration_times_excluding_first.max());
  842. }
  843. return exit_code;
  844. }
  845. int Shell::builtin_umask(int argc, char const** argv)
  846. {
  847. char const* mask_text = nullptr;
  848. Core::ArgsParser parser;
  849. parser.add_positional_argument(mask_text, "New mask (omit to get current mask)", "octal-mask", Core::ArgsParser::Required::No);
  850. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  851. return 1;
  852. if (!mask_text) {
  853. mode_t old_mask = umask(0);
  854. printf("%#o\n", old_mask);
  855. umask(old_mask);
  856. return 0;
  857. }
  858. unsigned mask;
  859. int matches = sscanf(mask_text, "%o", &mask);
  860. if (matches == 1) {
  861. umask(mask);
  862. return 0;
  863. }
  864. warnln("umask: Invalid mask '{}'", mask_text);
  865. return 1;
  866. }
  867. int Shell::builtin_wait(int argc, char const** argv)
  868. {
  869. Vector<int> job_ids;
  870. Vector<bool> id_is_pid;
  871. Core::ArgsParser parser;
  872. parser.add_positional_argument(Core::ArgsParser::Arg {
  873. .help_string = "Job IDs or Jobspecs to wait for",
  874. .name = "job-id",
  875. .min_values = 0,
  876. .max_values = INT_MAX,
  877. .accept_value = [&](auto const* value_ptr) -> bool {
  878. StringView value { value_ptr, strlen(value_ptr) };
  879. // Check if it's a pid (i.e. literal integer)
  880. if (auto number = value.to_uint(); number.has_value()) {
  881. job_ids.append(number.value());
  882. id_is_pid.append(true);
  883. return true;
  884. }
  885. // Check if it's a jobspec
  886. if (auto id = resolve_job_spec(value); id.has_value()) {
  887. job_ids.append(id.value());
  888. id_is_pid.append(false);
  889. return true;
  890. }
  891. return false;
  892. } });
  893. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  894. return 1;
  895. Vector<NonnullRefPtr<Job>> jobs_to_wait_for;
  896. for (size_t i = 0; i < job_ids.size(); ++i) {
  897. auto id = job_ids[i];
  898. auto is_pid = id_is_pid[i];
  899. auto job = find_job(id, is_pid);
  900. if (!job)
  901. warnln("wait: Job with id/pid {} not found", id);
  902. else
  903. jobs_to_wait_for.append(*job);
  904. }
  905. if (job_ids.is_empty()) {
  906. for (auto const& it : jobs)
  907. jobs_to_wait_for.append(it.value);
  908. }
  909. for (auto& job : jobs_to_wait_for) {
  910. job->set_running_in_background(false);
  911. block_on_job(job);
  912. }
  913. return 0;
  914. }
  915. int Shell::builtin_unset(int argc, char const** argv)
  916. {
  917. Vector<DeprecatedString> vars;
  918. Core::ArgsParser parser;
  919. parser.add_positional_argument(vars, "List of variables", "variables", Core::ArgsParser::Required::Yes);
  920. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  921. return 1;
  922. bool did_touch_path = false;
  923. for (auto& value : vars) {
  924. if (!did_touch_path && value == "PATH"sv)
  925. did_touch_path = true;
  926. if (lookup_local_variable(value)) {
  927. unset_local_variable(value);
  928. } else {
  929. unsetenv(value.characters());
  930. }
  931. }
  932. if (did_touch_path)
  933. cache_path();
  934. return 0;
  935. }
  936. int Shell::builtin_not(int argc, char const** argv)
  937. {
  938. // FIXME: Use ArgsParser when it can collect unrelated -arguments too.
  939. if (argc == 1)
  940. return 1;
  941. AST::Command command;
  942. for (size_t i = 1; i < (size_t)argc; ++i)
  943. command.argv.append(argv[i]);
  944. auto commands = expand_aliases({ move(command) });
  945. int exit_code = 1;
  946. auto found_a_job = false;
  947. for (auto& job : run_commands(commands)) {
  948. found_a_job = true;
  949. block_on_job(job);
  950. exit_code = job.exit_code();
  951. }
  952. // In case it was a function.
  953. if (!found_a_job)
  954. exit_code = last_return_code.value_or(0);
  955. return exit_code == 0 ? 1 : 0;
  956. }
  957. int Shell::builtin_kill(int argc, char const** argv)
  958. {
  959. // Simply translate the arguments and pass them to `kill'
  960. Vector<DeprecatedString> replaced_values;
  961. auto kill_path = Core::DeprecatedFile::resolve_executable_from_environment("kill"sv);
  962. if (!kill_path.has_value()) {
  963. warnln("kill: `kill' not found in PATH");
  964. return 126;
  965. }
  966. replaced_values.append(kill_path.release_value());
  967. for (auto i = 1; i < argc; ++i) {
  968. if (auto job_id = resolve_job_spec({ argv[i], strlen(argv[1]) }); job_id.has_value()) {
  969. auto job = find_job(job_id.value());
  970. if (job) {
  971. replaced_values.append(DeprecatedString::number(job->pid()));
  972. } else {
  973. warnln("kill: Job with pid {} not found", job_id.value());
  974. return 1;
  975. }
  976. } else {
  977. replaced_values.append(argv[i]);
  978. }
  979. }
  980. // Now just run `kill'
  981. AST::Command command;
  982. command.argv = move(replaced_values);
  983. command.position = m_source_position.has_value() ? m_source_position->position : Optional<AST::Position> {};
  984. auto exit_code = 1;
  985. auto job_result = run_command(command);
  986. if (job_result.is_error()) {
  987. warnln("kill: Failed to run {}: {}", command.argv.first(), job_result.error());
  988. return exit_code;
  989. }
  990. if (auto job = job_result.release_value()) {
  991. block_on_job(job);
  992. exit_code = job->exit_code();
  993. }
  994. return exit_code;
  995. }
  996. bool Shell::run_builtin(const AST::Command& command, NonnullRefPtrVector<AST::Rewiring> const& rewirings, int& retval)
  997. {
  998. if (command.argv.is_empty())
  999. return false;
  1000. if (!has_builtin(command.argv.first()))
  1001. return false;
  1002. Vector<char const*> argv;
  1003. for (auto& arg : command.argv)
  1004. argv.append(arg.characters());
  1005. argv.append(nullptr);
  1006. StringView name = command.argv.first();
  1007. SavedFileDescriptors fds { rewirings };
  1008. for (auto& rewiring : rewirings) {
  1009. int rc = dup2(rewiring.old_fd, rewiring.new_fd);
  1010. if (rc < 0) {
  1011. perror("dup2(run)");
  1012. return false;
  1013. }
  1014. }
  1015. Core::EventLoop loop;
  1016. setup_signals();
  1017. if (name == ":"sv)
  1018. name = "noop"sv;
  1019. #define __ENUMERATE_SHELL_BUILTIN(builtin) \
  1020. if (name == #builtin) { \
  1021. retval = builtin_##builtin(argv.size() - 1, argv.data()); \
  1022. if (!has_error(ShellError::None)) \
  1023. raise_error(m_error, m_error_description, command.position); \
  1024. fflush(stdout); \
  1025. fflush(stderr); \
  1026. return true; \
  1027. }
  1028. ENUMERATE_SHELL_BUILTINS();
  1029. #undef __ENUMERATE_SHELL_BUILTIN
  1030. return false;
  1031. }
  1032. int Shell::builtin_argsparser_parse(int argc, char const** argv)
  1033. {
  1034. // argsparser_parse
  1035. // --add-option variable [--type (bool | string | i32 | u32 | double | size)] --help-string "" --long-name "" --short-name "" [--value-name "" <if not --type bool>] --list
  1036. // --add-positional-argument variable [--type (bool | string | i32 | u32 | double | size)] ([--min n] [--max n] | [--required]) --help-string "" --value-name ""
  1037. // [--general-help ""]
  1038. // [--stop-on-first-non-option]
  1039. // --
  1040. // $args_to_parse
  1041. Core::ArgsParser parser;
  1042. Core::ArgsParser user_parser;
  1043. Vector<char const*> arguments;
  1044. Variant<Core::ArgsParser::Option, Core::ArgsParser::Arg, Empty> current;
  1045. DeprecatedString current_variable;
  1046. // if max > 1 or min < 1, or explicit `--list`.
  1047. bool treat_arg_as_list = false;
  1048. enum class Type {
  1049. Bool,
  1050. String,
  1051. I32,
  1052. U32,
  1053. Double,
  1054. Size,
  1055. };
  1056. auto type = Type::String;
  1057. auto try_convert = [](StringView value, Type type) -> Optional<RefPtr<AST::Value>> {
  1058. switch (type) {
  1059. case Type::Bool:
  1060. return AST::make_ref_counted<AST::StringValue>("true");
  1061. case Type::String:
  1062. return AST::make_ref_counted<AST::StringValue>(value);
  1063. case Type::I32:
  1064. if (auto number = value.to_int(); number.has_value())
  1065. return AST::make_ref_counted<AST::StringValue>(DeprecatedString::number(*number));
  1066. warnln("Invalid value for type i32: {}", value);
  1067. return {};
  1068. case Type::U32:
  1069. case Type::Size:
  1070. if (auto number = value.to_uint(); number.has_value())
  1071. return AST::make_ref_counted<AST::StringValue>(DeprecatedString::number(*number));
  1072. warnln("Invalid value for type u32|size: {}", value);
  1073. return {};
  1074. case Type::Double: {
  1075. DeprecatedString string = value;
  1076. char* endptr = nullptr;
  1077. auto number = strtod(string.characters(), &endptr);
  1078. if (endptr != string.characters() + string.length()) {
  1079. warnln("Invalid value for type double: {}", value);
  1080. return {};
  1081. }
  1082. return AST::make_ref_counted<AST::StringValue>(DeprecatedString::number(number));
  1083. }
  1084. default:
  1085. VERIFY_NOT_REACHED();
  1086. }
  1087. };
  1088. auto enlist = [&](auto name, auto value) -> NonnullRefPtr<AST::Value> {
  1089. auto variable = lookup_local_variable(name);
  1090. if (variable) {
  1091. auto list = const_cast<AST::Value&>(*variable).resolve_as_list(*this);
  1092. auto new_value = value->resolve_as_string(*this);
  1093. list.append(move(new_value));
  1094. return make_ref_counted<AST::ListValue>(move(list));
  1095. }
  1096. return *value;
  1097. };
  1098. auto commit = [&] {
  1099. return current.visit(
  1100. [&](Core::ArgsParser::Option& option) {
  1101. if (!option.long_name && !option.short_name) {
  1102. warnln("Defined option must have at least one of --long-name or --short-name");
  1103. return false;
  1104. }
  1105. option.accept_value = [&, current_variable, treat_arg_as_list, type](auto value) {
  1106. auto result = try_convert({ value, strlen(value) }, type);
  1107. if (result.has_value()) {
  1108. auto value = result.release_value();
  1109. if (treat_arg_as_list)
  1110. value = enlist(current_variable, move(value));
  1111. this->set_local_variable(current_variable, move(value), true);
  1112. return true;
  1113. }
  1114. return false;
  1115. };
  1116. user_parser.add_option(move(option));
  1117. type = Type::String;
  1118. treat_arg_as_list = false;
  1119. return true;
  1120. },
  1121. [&](Core::ArgsParser::Arg& arg) {
  1122. if (!arg.name) {
  1123. warnln("Defined positional argument must have a name");
  1124. return false;
  1125. }
  1126. arg.accept_value = [&, current_variable, treat_arg_as_list, type](auto value) {
  1127. auto result = try_convert({ value, strlen(value) }, type);
  1128. if (result.has_value()) {
  1129. auto value = result.release_value();
  1130. if (treat_arg_as_list)
  1131. value = enlist(current_variable, move(value));
  1132. this->set_local_variable(current_variable, move(value), true);
  1133. return true;
  1134. }
  1135. return false;
  1136. };
  1137. user_parser.add_positional_argument(move(arg));
  1138. type = Type::String;
  1139. treat_arg_as_list = false;
  1140. return true;
  1141. },
  1142. [&](Empty) {
  1143. return true;
  1144. });
  1145. };
  1146. parser.add_option(Core::ArgsParser::Option {
  1147. .argument_mode = Core::ArgsParser::OptionArgumentMode::None,
  1148. .help_string = "Stop processing arguments after a non-argument parameter is seen",
  1149. .long_name = "stop-on-first-non-option",
  1150. .accept_value = [&](auto) {
  1151. user_parser.set_stop_on_first_non_option(true);
  1152. return true;
  1153. },
  1154. });
  1155. parser.add_option(Core::ArgsParser::Option {
  1156. .argument_mode = Core::ArgsParser::OptionArgumentMode::Required,
  1157. .help_string = "Set the general help string for the parser",
  1158. .long_name = "general-help",
  1159. .value_name = "string",
  1160. .accept_value = [&](auto value) {
  1161. user_parser.set_general_help(value);
  1162. return true;
  1163. },
  1164. });
  1165. parser.add_option(Core::ArgsParser::Option {
  1166. .argument_mode = Core::ArgsParser::OptionArgumentMode::Required,
  1167. .help_string = "Start describing an option",
  1168. .long_name = "add-option",
  1169. .value_name = "variable-name",
  1170. .accept_value = [&](auto name) {
  1171. if (!commit())
  1172. return false;
  1173. current = Core::ArgsParser::Option {};
  1174. current_variable = name;
  1175. if (current_variable.is_empty() || !all_of(current_variable, [](auto ch) { return ch == '_' || isalnum(ch); })) {
  1176. warnln("Option variable name must be a valid identifier");
  1177. return false;
  1178. }
  1179. return true;
  1180. },
  1181. });
  1182. parser.add_option(Core::ArgsParser::Option {
  1183. .argument_mode = Core::ArgsParser::OptionArgumentMode::None,
  1184. .help_string = "Accept multiple of the current option being given",
  1185. .long_name = "list",
  1186. .accept_value = [&](auto) {
  1187. if (!current.has<Core::ArgsParser::Option>()) {
  1188. warnln("Must be defining an option to use --list");
  1189. return false;
  1190. }
  1191. treat_arg_as_list = true;
  1192. return true;
  1193. },
  1194. });
  1195. parser.add_option(Core::ArgsParser::Option {
  1196. .argument_mode = Core::ArgsParser::OptionArgumentMode::Required,
  1197. .help_string = "Define the type of the option or argument being described",
  1198. .long_name = "type",
  1199. .value_name = "type",
  1200. .accept_value = [&](auto name) {
  1201. if (current.has<Empty>()) {
  1202. warnln("Must be defining an argument or option to use --type");
  1203. return false;
  1204. }
  1205. StringView ty { name, strlen(name) };
  1206. if (ty == "bool") {
  1207. if (auto option = current.get_pointer<Core::ArgsParser::Option>()) {
  1208. if (option->value_name != nullptr) {
  1209. warnln("Type 'bool' does not apply to options with a value (value name is set to {})", option->value_name);
  1210. return false;
  1211. }
  1212. }
  1213. type = Type::Bool;
  1214. } else if (ty == "string") {
  1215. type = Type::String;
  1216. } else if (ty == "i32") {
  1217. type = Type::I32;
  1218. } else if (ty == "u32") {
  1219. type = Type::U32;
  1220. } else if (ty == "double") {
  1221. type = Type::Double;
  1222. } else if (ty == "size") {
  1223. type = Type::Size;
  1224. } else {
  1225. warnln("Invalid type '{}', expected one of bool | string | i32 | u32 | double | size", ty);
  1226. return false;
  1227. }
  1228. if (type == Type::Bool)
  1229. set_local_variable(current_variable, make_ref_counted<AST::StringValue>("false"), true);
  1230. return true;
  1231. },
  1232. });
  1233. parser.add_option(Core::ArgsParser::Option {
  1234. .argument_mode = Core::ArgsParser::OptionArgumentMode::Required,
  1235. .help_string = "Set the help string of the option or argument being defined",
  1236. .long_name = "help-string",
  1237. .value_name = "string",
  1238. .accept_value = [&](auto value) {
  1239. return current.visit(
  1240. [](Empty) {
  1241. warnln("Must be defining an option or argument to use --help-string");
  1242. return false;
  1243. },
  1244. [&](auto& option) {
  1245. option.help_string = value;
  1246. return true;
  1247. });
  1248. },
  1249. });
  1250. parser.add_option(Core::ArgsParser::Option {
  1251. .argument_mode = Core::ArgsParser::OptionArgumentMode::Required,
  1252. .help_string = "Set the long name of the option being defined",
  1253. .long_name = "long-name",
  1254. .value_name = "name",
  1255. .accept_value = [&](auto value) {
  1256. auto option = current.get_pointer<Core::ArgsParser::Option>();
  1257. if (!option) {
  1258. warnln("Must be defining an option to use --long-name");
  1259. return false;
  1260. }
  1261. if (option->long_name) {
  1262. warnln("Repeated application of --long-name is not allowed, current option has long name set to \"{}\"", option->long_name);
  1263. return false;
  1264. }
  1265. option->long_name = value;
  1266. return true;
  1267. },
  1268. });
  1269. parser.add_option(Core::ArgsParser::Option {
  1270. .argument_mode = Core::ArgsParser::OptionArgumentMode::Required,
  1271. .help_string = "Set the short name of the option being defined",
  1272. .long_name = "short-name",
  1273. .value_name = "char",
  1274. .accept_value = [&](auto value) {
  1275. auto option = current.get_pointer<Core::ArgsParser::Option>();
  1276. if (!option) {
  1277. warnln("Must be defining an option to use --short-name");
  1278. return false;
  1279. }
  1280. if (strlen(value) != 1) {
  1281. warnln("Option short name ('{}') must be exactly one character long", value);
  1282. return false;
  1283. }
  1284. if (option->short_name) {
  1285. warnln("Repeated application of --short-name is not allowed, current option has short name set to '{}'", option->short_name);
  1286. return false;
  1287. }
  1288. option->short_name = value[0];
  1289. return true;
  1290. },
  1291. });
  1292. parser.add_option(Core::ArgsParser::Option {
  1293. .argument_mode = Core::ArgsParser::OptionArgumentMode::Required,
  1294. .help_string = "Set the value name of the option being defined",
  1295. .long_name = "value-name",
  1296. .value_name = "string",
  1297. .accept_value = [&](auto value) {
  1298. return current.visit(
  1299. [](Empty) {
  1300. warnln("Must be defining an option or a positional argument to use --value-name");
  1301. return false;
  1302. },
  1303. [&](Core::ArgsParser::Option& option) {
  1304. if (option.value_name) {
  1305. warnln("Repeated application of --value-name is not allowed, current option has value name set to \"{}\"", option.value_name);
  1306. return false;
  1307. }
  1308. if (type == Type::Bool) {
  1309. warnln("Options of type bool cannot have a value name");
  1310. return false;
  1311. }
  1312. option.value_name = value;
  1313. return true;
  1314. },
  1315. [&](Core::ArgsParser::Arg& arg) {
  1316. if (arg.name) {
  1317. warnln("Repeated application of --value-name is not allowed, current argument has value name set to \"{}\"", arg.name);
  1318. return false;
  1319. }
  1320. arg.name = value;
  1321. return true;
  1322. });
  1323. },
  1324. });
  1325. parser.add_option(Core::ArgsParser::Option {
  1326. .argument_mode = Core::ArgsParser::OptionArgumentMode::Required,
  1327. .help_string = "Start describing a positional argument",
  1328. .long_name = "add-positional-argument",
  1329. .value_name = "variable",
  1330. .accept_value = [&](auto value) {
  1331. if (!commit())
  1332. return false;
  1333. current = Core::ArgsParser::Arg {};
  1334. current_variable = value;
  1335. if (current_variable.is_empty() || !all_of(current_variable, [](auto ch) { return ch == '_' || isalnum(ch); })) {
  1336. warnln("Argument variable name must be a valid identifier");
  1337. return false;
  1338. }
  1339. return true;
  1340. },
  1341. });
  1342. parser.add_option(Core::ArgsParser::Option {
  1343. .argument_mode = Core::ArgsParser::OptionArgumentMode::Required,
  1344. .help_string = "Set the minimum required number of positional arguments for the argument being described",
  1345. .long_name = "min",
  1346. .value_name = "n",
  1347. .accept_value = [&](auto value) {
  1348. auto arg = current.get_pointer<Core::ArgsParser::Arg>();
  1349. if (!arg) {
  1350. warnln("Must be describing a positional argument to use --min");
  1351. return false;
  1352. }
  1353. auto number = StringView { value, strlen(value) }.to_uint();
  1354. if (!number.has_value()) {
  1355. warnln("Invalid value for --min: '{}', expected a non-negative number", value);
  1356. return false;
  1357. }
  1358. if (static_cast<unsigned>(arg->max_values) < *number) {
  1359. warnln("Invalid value for --min: {}, min must not be larger than max ({})", *number, arg->max_values);
  1360. return false;
  1361. }
  1362. arg->min_values = *number;
  1363. treat_arg_as_list = arg->max_values > 1 || arg->min_values < 1;
  1364. return true;
  1365. },
  1366. });
  1367. parser.add_option(Core::ArgsParser::Option {
  1368. .argument_mode = Core::ArgsParser::OptionArgumentMode::Required,
  1369. .help_string = "Set the maximum required number of positional arguments for the argument being described",
  1370. .long_name = "max",
  1371. .value_name = "n",
  1372. .accept_value = [&](auto value) {
  1373. auto arg = current.get_pointer<Core::ArgsParser::Arg>();
  1374. if (!arg) {
  1375. warnln("Must be describing a positional argument to use --max");
  1376. return false;
  1377. }
  1378. auto number = StringView { value, strlen(value) }.to_uint();
  1379. if (!number.has_value()) {
  1380. warnln("Invalid value for --max: '{}', expected a non-negative number", value);
  1381. return false;
  1382. }
  1383. if (static_cast<unsigned>(arg->min_values) > *number) {
  1384. warnln("Invalid value for --max: {}, max must not be smaller than min ({})", *number, arg->min_values);
  1385. return false;
  1386. }
  1387. arg->max_values = *number;
  1388. treat_arg_as_list = arg->max_values > 1 || arg->min_values < 1;
  1389. return true;
  1390. },
  1391. });
  1392. parser.add_option(Core::ArgsParser::Option {
  1393. .argument_mode = Core::ArgsParser::OptionArgumentMode::None,
  1394. .help_string = "Mark the positional argument being described as required (shorthand for --min 1)",
  1395. .long_name = "required",
  1396. .accept_value = [&](auto) {
  1397. auto arg = current.get_pointer<Core::ArgsParser::Arg>();
  1398. if (!arg) {
  1399. warnln("Must be describing a positional argument to use --required");
  1400. return false;
  1401. }
  1402. arg->min_values = 1;
  1403. if (arg->max_values < arg->min_values)
  1404. arg->max_values = 1;
  1405. treat_arg_as_list = arg->max_values > 1 || arg->min_values < 1;
  1406. return true;
  1407. },
  1408. });
  1409. parser.add_positional_argument(arguments, "Arguments to parse via the described ArgsParser configuration", "arg", Core::ArgsParser::Required::No);
  1410. if (!parser.parse(argc, const_cast<char* const*>(argv), Core::ArgsParser::FailureBehavior::Ignore))
  1411. return 2;
  1412. if (!commit())
  1413. return 2;
  1414. if (!user_parser.parse(static_cast<int>(arguments.size()), const_cast<char* const*>(arguments.data()), Core::ArgsParser::FailureBehavior::Ignore))
  1415. return 1;
  1416. return 0;
  1417. }
  1418. bool Shell::has_builtin(StringView name) const
  1419. {
  1420. if (name == ":"sv)
  1421. return true;
  1422. #define __ENUMERATE_SHELL_BUILTIN(builtin) \
  1423. if (name == #builtin) { \
  1424. return true; \
  1425. }
  1426. ENUMERATE_SHELL_BUILTINS();
  1427. #undef __ENUMERATE_SHELL_BUILTIN
  1428. return false;
  1429. }
  1430. }