Builtin.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  1. /*
  2. * Copyright (c) 2020, The SerenityOS developers.
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include "Shell.h"
  27. #include <AK/LexicalPath.h>
  28. #include <LibCore/ArgsParser.h>
  29. #include <LibCore/File.h>
  30. #include <inttypes.h>
  31. #include <signal.h>
  32. #include <sys/wait.h>
  33. #include <unistd.h>
  34. extern char** environ;
  35. extern RefPtr<Line::Editor> editor;
  36. int Shell::builtin_alias(int argc, const char** argv)
  37. {
  38. Vector<const char*> arguments;
  39. Core::ArgsParser parser;
  40. parser.add_positional_argument(arguments, "List of name[=values]'s", "name[=value]", Core::ArgsParser::Required::No);
  41. if (!parser.parse(argc, const_cast<char**>(argv), false))
  42. return 1;
  43. if (arguments.is_empty()) {
  44. for (auto& alias : m_aliases)
  45. printf("%s=%s\n", escape_token(alias.key).characters(), escape_token(alias.value).characters());
  46. return 0;
  47. }
  48. bool fail = false;
  49. for (auto& argument : arguments) {
  50. auto parts = String { argument }.split_limit('=', 2, true);
  51. if (parts.size() == 1) {
  52. auto alias = m_aliases.get(parts[0]);
  53. if (alias.has_value()) {
  54. printf("%s=%s\n", escape_token(parts[0]).characters(), escape_token(alias.value()).characters());
  55. } else {
  56. fail = true;
  57. }
  58. } else {
  59. m_aliases.set(parts[0], parts[1]);
  60. add_entry_to_cache(parts[0]);
  61. }
  62. }
  63. return fail ? 1 : 0;
  64. }
  65. int Shell::builtin_bg(int argc, const char** argv)
  66. {
  67. int job_id = -1;
  68. Core::ArgsParser parser;
  69. parser.add_positional_argument(job_id, "Job ID to run in background", "job-id", Core::ArgsParser::Required::No);
  70. if (!parser.parse(argc, const_cast<char**>(argv), false))
  71. return 1;
  72. if (job_id == -1 && !jobs.is_empty())
  73. job_id = find_last_job_id();
  74. auto* job = const_cast<Job*>(find_job(job_id));
  75. if (!job) {
  76. if (job_id == -1) {
  77. fprintf(stderr, "bg: no current job\n");
  78. } else {
  79. fprintf(stderr, "bg: job with id %d not found\n", job_id);
  80. }
  81. return 1;
  82. }
  83. job->set_running_in_background(true);
  84. job->set_is_suspended(false);
  85. dbg() << "Resuming " << job->pid() << " (" << job->cmd() << ")";
  86. fprintf(stderr, "Resuming job %" PRIu64 " - %s\n", job->job_id(), job->cmd().characters());
  87. if (killpg(job->pgid(), SIGCONT) < 0) {
  88. perror("killpg");
  89. return 1;
  90. }
  91. return 0;
  92. }
  93. int Shell::builtin_cd(int argc, const char** argv)
  94. {
  95. const char* arg_path = nullptr;
  96. Core::ArgsParser parser;
  97. parser.add_positional_argument(arg_path, "Path to change to", "path", Core::ArgsParser::Required::No);
  98. if (!parser.parse(argc, const_cast<char**>(argv), false))
  99. return 1;
  100. String new_path;
  101. if (!arg_path) {
  102. new_path = home;
  103. if (cd_history.is_empty() || cd_history.last() != home)
  104. cd_history.enqueue(home);
  105. } else {
  106. if (cd_history.is_empty() || cd_history.last() != arg_path)
  107. cd_history.enqueue(arg_path);
  108. if (strcmp(arg_path, "-") == 0) {
  109. char* oldpwd = getenv("OLDPWD");
  110. if (oldpwd == nullptr)
  111. return 1;
  112. new_path = oldpwd;
  113. } else if (arg_path[0] == '/') {
  114. new_path = argv[1];
  115. } else {
  116. StringBuilder builder;
  117. builder.append(cwd);
  118. builder.append('/');
  119. builder.append(arg_path);
  120. new_path = builder.to_string();
  121. }
  122. }
  123. auto real_path = Core::File::real_path_for(new_path);
  124. if (real_path.is_empty()) {
  125. fprintf(stderr, "Invalid path '%s'\n", new_path.characters());
  126. return 1;
  127. }
  128. const char* path = real_path.characters();
  129. int rc = chdir(path);
  130. if (rc < 0) {
  131. if (errno == ENOTDIR) {
  132. fprintf(stderr, "Not a directory: %s\n", path);
  133. } else {
  134. fprintf(stderr, "chdir(%s) failed: %s\n", path, strerror(errno));
  135. }
  136. return 1;
  137. }
  138. setenv("OLDPWD", cwd.characters(), 1);
  139. cwd = real_path;
  140. setenv("PWD", cwd.characters(), 1);
  141. return 0;
  142. }
  143. int Shell::builtin_cdh(int argc, const char** argv)
  144. {
  145. int index = -1;
  146. Core::ArgsParser parser;
  147. parser.add_positional_argument(index, "Index of the cd history entry (leave out for a list)", "index", Core::ArgsParser::Required::No);
  148. if (!parser.parse(argc, const_cast<char**>(argv), false))
  149. return 1;
  150. if (index == -1) {
  151. if (cd_history.is_empty()) {
  152. fprintf(stderr, "cdh: no history available\n");
  153. return 0;
  154. }
  155. for (ssize_t i = cd_history.size() - 1; i >= 0; --i)
  156. printf("%lu: %s\n", cd_history.size() - i, cd_history.at(i).characters());
  157. return 0;
  158. }
  159. if (index < 1 || (size_t)index > cd_history.size()) {
  160. fprintf(stderr, "cdh: history index out of bounds: %d not in (0, %zu)\n", index, cd_history.size());
  161. return 1;
  162. }
  163. const char* path = cd_history.at(cd_history.size() - index).characters();
  164. const char* cd_args[] = { "cd", path, nullptr };
  165. return Shell::builtin_cd(2, cd_args);
  166. }
  167. int Shell::builtin_dirs(int argc, const char** argv)
  168. {
  169. // The first directory in the stack is ALWAYS the current directory
  170. directory_stack.at(0) = cwd.characters();
  171. bool clear = false;
  172. bool print = false;
  173. bool number_when_printing = false;
  174. char separator = ' ';
  175. Vector<const char*> paths;
  176. Core::ArgsParser parser;
  177. parser.add_option(clear, "Clear the directory stack", "clear", 'c');
  178. parser.add_option(print, "Print directory entries one per line", "print", 'p');
  179. parser.add_option(number_when_printing, "Number the directories in the stack when printing", "number", 'v');
  180. parser.add_positional_argument(paths, "Extra paths to put on the stack", "path", Core::ArgsParser::Required::No);
  181. if (!parser.parse(argc, const_cast<char**>(argv), false))
  182. return 1;
  183. // -v implies -p
  184. print = print || number_when_printing;
  185. if (print) {
  186. if (!paths.is_empty()) {
  187. fprintf(stderr, "dirs: 'print' and 'number' are not allowed when any path is specified");
  188. return 1;
  189. }
  190. separator = '\n';
  191. }
  192. if (clear) {
  193. for (size_t i = 1; i < directory_stack.size(); i++)
  194. directory_stack.remove(i);
  195. }
  196. for (auto& path : paths)
  197. directory_stack.append(path);
  198. if (print || (!clear && paths.is_empty())) {
  199. int index = 0;
  200. for (auto& directory : directory_stack) {
  201. if (number_when_printing)
  202. printf("%d ", index++);
  203. print_path(directory);
  204. fputc(separator, stdout);
  205. }
  206. }
  207. return 0;
  208. }
  209. int Shell::builtin_exit(int argc, const char** argv)
  210. {
  211. int exit_code = 0;
  212. Core::ArgsParser parser;
  213. parser.add_positional_argument(exit_code, "Exit code", "code", Core::ArgsParser::Required::No);
  214. if (!parser.parse(argc, const_cast<char**>(argv)))
  215. return 1;
  216. if (!jobs.is_empty()) {
  217. if (!m_should_ignore_jobs_on_next_exit) {
  218. fprintf(stderr, "Shell: You have %zu active job%s, run 'exit' again to really exit.\n", jobs.size(), jobs.size() > 1 ? "s" : "");
  219. m_should_ignore_jobs_on_next_exit = true;
  220. return 1;
  221. }
  222. }
  223. stop_all_jobs();
  224. save_history();
  225. if (m_is_interactive)
  226. printf("Good-bye!\n");
  227. exit(exit_code);
  228. return 0;
  229. }
  230. int Shell::builtin_export(int argc, const char** argv)
  231. {
  232. Vector<const char*> vars;
  233. Core::ArgsParser parser;
  234. parser.add_positional_argument(vars, "List of variable[=value]'s", "values", Core::ArgsParser::Required::No);
  235. if (!parser.parse(argc, const_cast<char**>(argv), false))
  236. return 1;
  237. if (vars.is_empty()) {
  238. for (size_t i = 0; environ[i]; ++i)
  239. puts(environ[i]);
  240. return 0;
  241. }
  242. for (auto& value : vars) {
  243. auto parts = String { value }.split_limit('=', 2);
  244. if (parts.size() == 1) {
  245. auto value = lookup_local_variable(parts[0]);
  246. if (value) {
  247. auto values = value->resolve_as_list(*this);
  248. StringBuilder builder;
  249. builder.join(" ", values);
  250. parts.append(builder.to_string());
  251. } else {
  252. // Ignore the export.
  253. continue;
  254. }
  255. }
  256. int setenv_return = setenv(parts[0].characters(), parts[1].characters(), 1);
  257. if (setenv_return != 0) {
  258. perror("setenv");
  259. return 1;
  260. }
  261. if (parts[0] == "PATH")
  262. cache_path();
  263. }
  264. return 0;
  265. }
  266. int Shell::builtin_fg(int argc, const char** argv)
  267. {
  268. int job_id = -1;
  269. Core::ArgsParser parser;
  270. parser.add_positional_argument(job_id, "Job ID to bring to foreground", "job-id", Core::ArgsParser::Required::No);
  271. if (!parser.parse(argc, const_cast<char**>(argv), false))
  272. return 1;
  273. if (job_id == -1 && !jobs.is_empty())
  274. job_id = find_last_job_id();
  275. RefPtr<Job> job = find_job(job_id);
  276. if (!job) {
  277. if (job_id == -1) {
  278. fprintf(stderr, "fg: no current job\n");
  279. } else {
  280. fprintf(stderr, "fg: job with id %d not found\n", job_id);
  281. }
  282. return 1;
  283. }
  284. job->set_running_in_background(false);
  285. job->set_is_suspended(false);
  286. dbg() << "Resuming " << job->pid() << " (" << job->cmd() << ")";
  287. fprintf(stderr, "Resuming job %" PRIu64 " - %s\n", job->job_id(), job->cmd().characters());
  288. tcsetpgrp(STDOUT_FILENO, job->pgid());
  289. tcsetpgrp(STDIN_FILENO, job->pgid());
  290. if (killpg(job->pgid(), SIGCONT) < 0) {
  291. perror("killpg");
  292. return 1;
  293. }
  294. block_on_job(job);
  295. return job->exit_code();
  296. }
  297. int Shell::builtin_disown(int argc, const char** argv)
  298. {
  299. Vector<const char*> str_job_ids;
  300. Core::ArgsParser parser;
  301. parser.add_positional_argument(str_job_ids, "Id of the jobs to disown (omit for current job)", "job_ids", Core::ArgsParser::Required::No);
  302. if (!parser.parse(argc, const_cast<char**>(argv), false))
  303. return 1;
  304. Vector<size_t> job_ids;
  305. for (auto& job_id : str_job_ids) {
  306. auto id = StringView(job_id).to_uint();
  307. if (id.has_value())
  308. job_ids.append(id.value());
  309. else
  310. fprintf(stderr, "disown: Invalid job id %s\n", job_id);
  311. }
  312. if (job_ids.is_empty())
  313. job_ids.append(find_last_job_id());
  314. Vector<const Job*> jobs_to_disown;
  315. for (auto id : job_ids) {
  316. auto job = find_job(id);
  317. if (!job)
  318. fprintf(stderr, "disown: job with id %zu not found\n", id);
  319. else
  320. jobs_to_disown.append(job);
  321. }
  322. if (jobs_to_disown.is_empty()) {
  323. if (str_job_ids.is_empty())
  324. fprintf(stderr, "disown: no current job\n");
  325. // An error message has already been printed about the nonexistence of each listed job.
  326. return 1;
  327. }
  328. for (auto job : jobs_to_disown) {
  329. job->deactivate();
  330. if (!job->is_running_in_background())
  331. fprintf(stderr, "disown warning: job %" PRIu64 " is currently not running, 'kill -%d %d' to make it continue\n", job->job_id(), SIGCONT, job->pid());
  332. jobs.remove(job->pid());
  333. }
  334. return 0;
  335. }
  336. int Shell::builtin_history(int, const char**)
  337. {
  338. for (size_t i = 0; i < editor->history().size(); ++i) {
  339. printf("%6zu %s\n", i, editor->history()[i].characters());
  340. }
  341. return 0;
  342. }
  343. int Shell::builtin_jobs(int argc, const char** argv)
  344. {
  345. bool list = false, show_pid = false;
  346. Core::ArgsParser parser;
  347. parser.add_option(list, "List all information about jobs", "list", 'l');
  348. parser.add_option(show_pid, "Display the PID of the jobs", "pid", 'p');
  349. if (!parser.parse(argc, const_cast<char**>(argv), false))
  350. return 1;
  351. Job::PrintStatusMode mode = Job::PrintStatusMode::Basic;
  352. if (show_pid)
  353. mode = Job::PrintStatusMode::OnlyPID;
  354. if (list)
  355. mode = Job::PrintStatusMode::ListAll;
  356. for (auto& it : jobs) {
  357. if (!it.value->print_status(mode))
  358. return 1;
  359. }
  360. return 0;
  361. }
  362. int Shell::builtin_popd(int argc, const char** argv)
  363. {
  364. if (directory_stack.size() <= 1) {
  365. fprintf(stderr, "Shell: popd: directory stack empty\n");
  366. return 1;
  367. }
  368. bool should_not_switch = false;
  369. String path = directory_stack.take_last();
  370. Core::ArgsParser parser;
  371. parser.add_option(should_not_switch, "Do not switch dirs", "no-switch", 'n');
  372. if (!parser.parse(argc, const_cast<char**>(argv), false))
  373. return 1;
  374. bool should_switch = !should_not_switch;
  375. // When no arguments are given, popd removes the top directory from the stack and performs a cd to the new top directory.
  376. if (argc == 1) {
  377. int rc = chdir(path.characters());
  378. if (rc < 0) {
  379. fprintf(stderr, "chdir(%s) failed: %s\n", path.characters(), strerror(errno));
  380. return 1;
  381. }
  382. cwd = path;
  383. return 0;
  384. }
  385. LexicalPath lexical_path(path.characters());
  386. if (!lexical_path.is_valid()) {
  387. fprintf(stderr, "LexicalPath failed to canonicalize '%s'\n", path.characters());
  388. return 1;
  389. }
  390. const char* real_path = lexical_path.string().characters();
  391. struct stat st;
  392. int rc = stat(real_path, &st);
  393. if (rc < 0) {
  394. fprintf(stderr, "stat(%s) failed: %s\n", real_path, strerror(errno));
  395. return 1;
  396. }
  397. if (!S_ISDIR(st.st_mode)) {
  398. fprintf(stderr, "Not a directory: %s\n", real_path);
  399. return 1;
  400. }
  401. if (should_switch) {
  402. int rc = chdir(real_path);
  403. if (rc < 0) {
  404. fprintf(stderr, "chdir(%s) failed: %s\n", real_path, strerror(errno));
  405. return 1;
  406. }
  407. cwd = lexical_path.string();
  408. }
  409. return 0;
  410. }
  411. int Shell::builtin_pushd(int argc, const char** argv)
  412. {
  413. StringBuilder path_builder;
  414. bool should_switch = true;
  415. // From the BASH reference manual: https://www.gnu.org/software/bash/manual/html_node/Directory-Stack-Builtins.html
  416. // With no arguments, pushd exchanges the top two directories and makes the new top the current directory.
  417. if (argc == 1) {
  418. if (directory_stack.size() < 2) {
  419. fprintf(stderr, "pushd: no other directory\n");
  420. return 1;
  421. }
  422. String dir1 = directory_stack.take_first();
  423. String dir2 = directory_stack.take_first();
  424. directory_stack.insert(0, dir2);
  425. directory_stack.insert(1, dir1);
  426. int rc = chdir(dir2.characters());
  427. if (rc < 0) {
  428. fprintf(stderr, "chdir(%s) failed: %s\n", dir2.characters(), strerror(errno));
  429. return 1;
  430. }
  431. cwd = dir2;
  432. return 0;
  433. }
  434. // Let's assume the user's typed in 'pushd <dir>'
  435. if (argc == 2) {
  436. directory_stack.append(cwd.characters());
  437. if (argv[1][0] == '/') {
  438. path_builder.append(argv[1]);
  439. } else {
  440. path_builder.appendf("%s/%s", cwd.characters(), argv[1]);
  441. }
  442. } else if (argc == 3) {
  443. directory_stack.append(cwd.characters());
  444. for (int i = 1; i < argc; i++) {
  445. const char* arg = argv[i];
  446. if (arg[0] != '-') {
  447. if (arg[0] == '/') {
  448. path_builder.append(arg);
  449. } else
  450. path_builder.appendf("%s/%s", cwd.characters(), arg);
  451. }
  452. if (!strcmp(arg, "-n"))
  453. should_switch = false;
  454. }
  455. }
  456. LexicalPath lexical_path(path_builder.to_string());
  457. if (!lexical_path.is_valid()) {
  458. fprintf(stderr, "LexicalPath failed to canonicalize '%s'\n", path_builder.to_string().characters());
  459. return 1;
  460. }
  461. const char* real_path = lexical_path.string().characters();
  462. struct stat st;
  463. int rc = stat(real_path, &st);
  464. if (rc < 0) {
  465. fprintf(stderr, "stat(%s) failed: %s\n", real_path, strerror(errno));
  466. return 1;
  467. }
  468. if (!S_ISDIR(st.st_mode)) {
  469. fprintf(stderr, "Not a directory: %s\n", real_path);
  470. return 1;
  471. }
  472. if (should_switch) {
  473. int rc = chdir(real_path);
  474. if (rc < 0) {
  475. fprintf(stderr, "chdir(%s) failed: %s\n", real_path, strerror(errno));
  476. return 1;
  477. }
  478. cwd = lexical_path.string();
  479. }
  480. return 0;
  481. }
  482. int Shell::builtin_pwd(int, const char**)
  483. {
  484. print_path(cwd);
  485. fputc('\n', stdout);
  486. return 0;
  487. }
  488. int Shell::builtin_setopt(int argc, const char** argv)
  489. {
  490. if (argc == 1) {
  491. #define __ENUMERATE_SHELL_OPTION(name, default_, description) \
  492. if (options.name) \
  493. fprintf(stderr, #name "\n");
  494. ENUMERATE_SHELL_OPTIONS();
  495. #undef __ENUMERATE_SHELL_OPTION
  496. }
  497. Core::ArgsParser parser;
  498. #define __ENUMERATE_SHELL_OPTION(name, default_, description) \
  499. bool name = false; \
  500. bool not_##name = false; \
  501. parser.add_option(name, "Enable: " description, #name, '\0'); \
  502. parser.add_option(not_##name, "Disable: " description, "no_" #name, '\0');
  503. ENUMERATE_SHELL_OPTIONS();
  504. #undef __ENUMERATE_SHELL_OPTION
  505. if (!parser.parse(argc, const_cast<char**>(argv), false))
  506. return 1;
  507. #define __ENUMERATE_SHELL_OPTION(name, default_, description) \
  508. if (name) \
  509. options.name = true; \
  510. if (not_##name) \
  511. options.name = false;
  512. ENUMERATE_SHELL_OPTIONS();
  513. #undef __ENUMERATE_SHELL_OPTION
  514. return 0;
  515. }
  516. int Shell::builtin_shift(int argc, const char** argv)
  517. {
  518. int count = 1;
  519. Core::ArgsParser parser;
  520. parser.add_positional_argument(count, "Shift count", "count", Core::ArgsParser::Required::No);
  521. if (!parser.parse(argc, const_cast<char**>(argv), false))
  522. return 1;
  523. if (count < 1)
  524. return 0;
  525. auto argv_ = lookup_local_variable("ARGV");
  526. if (!argv_) {
  527. fprintf(stderr, "shift: ARGV is unset\n");
  528. return 1;
  529. }
  530. if (!argv_->is_list())
  531. argv_ = adopt(*new AST::ListValue({ argv_.release_nonnull() }));
  532. auto& values = static_cast<AST::ListValue*>(argv_.ptr())->values();
  533. if ((size_t)count > values.size()) {
  534. fprintf(stderr, "shift: shift count must not be greater than %zu\n", values.size());
  535. return 1;
  536. }
  537. for (auto i = 0; i < count; ++i)
  538. values.take_first();
  539. return 0;
  540. }
  541. int Shell::builtin_time(int argc, const char** argv)
  542. {
  543. Vector<const char*> args;
  544. Core::ArgsParser parser;
  545. parser.add_positional_argument(args, "Command to execute with arguments", "command", Core::ArgsParser::Required::Yes);
  546. if (!parser.parse(argc, const_cast<char**>(argv), false))
  547. return 1;
  548. AST::Command command;
  549. for (auto& arg : args)
  550. command.argv.append(arg);
  551. auto commands = expand_aliases({ move(command) });
  552. Core::ElapsedTimer timer;
  553. int exit_code = 1;
  554. timer.start();
  555. for (auto& job : run_commands(commands)) {
  556. block_on_job(job);
  557. exit_code = job.exit_code();
  558. }
  559. fprintf(stderr, "Time: %d ms\n", timer.elapsed());
  560. return exit_code;
  561. }
  562. int Shell::builtin_umask(int argc, const char** argv)
  563. {
  564. const char* mask_text = nullptr;
  565. Core::ArgsParser parser;
  566. parser.add_positional_argument(mask_text, "New mask (omit to get current mask)", "octal-mask", Core::ArgsParser::Required::No);
  567. if (!parser.parse(argc, const_cast<char**>(argv), false))
  568. return 1;
  569. if (!mask_text) {
  570. mode_t old_mask = umask(0);
  571. printf("%#o\n", old_mask);
  572. umask(old_mask);
  573. return 0;
  574. }
  575. unsigned mask;
  576. int matches = sscanf(mask_text, "%o", &mask);
  577. if (matches == 1) {
  578. umask(mask);
  579. return 0;
  580. }
  581. fprintf(stderr, "umask: Invalid mask '%s'\n", mask_text);
  582. return 1;
  583. }
  584. int Shell::builtin_unset(int argc, const char** argv)
  585. {
  586. Vector<const char*> vars;
  587. Core::ArgsParser parser;
  588. parser.add_positional_argument(vars, "List of variables", "variables", Core::ArgsParser::Required::Yes);
  589. if (!parser.parse(argc, const_cast<char**>(argv), false))
  590. return 1;
  591. for (auto& value : vars) {
  592. if (lookup_local_variable(value)) {
  593. unset_local_variable(value);
  594. } else {
  595. unsetenv(value);
  596. }
  597. }
  598. return 0;
  599. }
  600. bool Shell::run_builtin(int argc, const char** argv, int& retval)
  601. {
  602. if (argc == 0)
  603. return false;
  604. StringView name { argv[0] };
  605. #define __ENUMERATE_SHELL_BUILTIN(builtin) \
  606. if (name == #builtin) { \
  607. retval = builtin_##builtin(argc, argv); \
  608. return true; \
  609. }
  610. ENUMERATE_SHELL_BUILTINS();
  611. #undef __ENUMERATE_SHELL_BUILTIN
  612. return false;
  613. }
  614. bool Shell::has_builtin(const StringView& name) const
  615. {
  616. #define __ENUMERATE_SHELL_BUILTIN(builtin) \
  617. if (name == #builtin) { \
  618. return true; \
  619. }
  620. ENUMERATE_SHELL_BUILTINS();
  621. #undef __ENUMERATE_SHELL_BUILTIN
  622. return false;
  623. }