Builtin.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823
  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. auto* job = const_cast<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. if (killpg(job->pgid(), SIGCONT) < 0) {
  289. perror("killpg");
  290. return 1;
  291. }
  292. block_on_job(job);
  293. return job->exit_code();
  294. }
  295. int Shell::builtin_disown(int argc, const char** argv)
  296. {
  297. Vector<const char*> str_job_ids;
  298. Core::ArgsParser parser;
  299. parser.add_positional_argument(str_job_ids, "Id of the jobs to disown (omit for current job)", "job_ids", Core::ArgsParser::Required::No);
  300. if (!parser.parse(argc, const_cast<char**>(argv), false))
  301. return 1;
  302. Vector<size_t> job_ids;
  303. for (auto& job_id : str_job_ids) {
  304. auto id = StringView(job_id).to_uint();
  305. if (id.has_value())
  306. job_ids.append(id.value());
  307. else
  308. fprintf(stderr, "disown: Invalid job id %s\n", job_id);
  309. }
  310. if (job_ids.is_empty())
  311. job_ids.append(find_last_job_id());
  312. Vector<const Job*> jobs_to_disown;
  313. for (auto id : job_ids) {
  314. auto job = find_job(id);
  315. if (!job)
  316. fprintf(stderr, "disown: job with id %zu not found\n", id);
  317. else
  318. jobs_to_disown.append(job);
  319. }
  320. if (jobs_to_disown.is_empty()) {
  321. if (str_job_ids.is_empty())
  322. fprintf(stderr, "disown: no current job\n");
  323. // An error message has already been printed about the nonexistence of each listed job.
  324. return 1;
  325. }
  326. for (auto job : jobs_to_disown) {
  327. job->deactivate();
  328. if (!job->is_running_in_background())
  329. fprintf(stderr, "disown warning: job %" PRIu64 " is currently not running, 'kill -%d %d' to make it continue\n", job->job_id(), SIGCONT, job->pid());
  330. jobs.remove(job->pid());
  331. }
  332. return 0;
  333. }
  334. int Shell::builtin_history(int, const char**)
  335. {
  336. for (size_t i = 0; i < editor->history().size(); ++i) {
  337. printf("%6zu %s\n", i, editor->history()[i].characters());
  338. }
  339. return 0;
  340. }
  341. int Shell::builtin_jobs(int argc, const char** argv)
  342. {
  343. bool list = false, show_pid = false;
  344. Core::ArgsParser parser;
  345. parser.add_option(list, "List all information about jobs", "list", 'l');
  346. parser.add_option(show_pid, "Display the PID of the jobs", "pid", 'p');
  347. if (!parser.parse(argc, const_cast<char**>(argv), false))
  348. return 1;
  349. enum {
  350. Basic,
  351. OnlyPID,
  352. ListAll,
  353. } mode { Basic };
  354. if (show_pid)
  355. mode = OnlyPID;
  356. if (list)
  357. mode = ListAll;
  358. for (auto& job : jobs) {
  359. auto pid = job.value->pid();
  360. int wstatus;
  361. auto rc = waitpid(pid, &wstatus, WNOHANG);
  362. if (rc == -1) {
  363. perror("waitpid");
  364. return 1;
  365. }
  366. auto status = "running";
  367. if (rc != 0) {
  368. if (WIFEXITED(wstatus))
  369. status = "exited";
  370. if (WIFSTOPPED(wstatus))
  371. status = "stopped";
  372. if (WIFSIGNALED(wstatus))
  373. status = "signaled";
  374. }
  375. char background_indicator = '-';
  376. if (job.value->is_running_in_background())
  377. background_indicator = '+';
  378. switch (mode) {
  379. case Basic:
  380. printf("[%" PRIu64 "] %c %s %s\n", job.value->job_id(), background_indicator, status, job.value->cmd().characters());
  381. break;
  382. case OnlyPID:
  383. printf("[%" PRIu64 "] %c %d %s %s\n", job.value->job_id(), background_indicator, pid, status, job.value->cmd().characters());
  384. break;
  385. case ListAll:
  386. printf("[%" PRIu64 "] %c %d %d %s %s\n", job.value->job_id(), background_indicator, pid, job.value->pgid(), status, job.value->cmd().characters());
  387. break;
  388. }
  389. }
  390. return 0;
  391. }
  392. int Shell::builtin_popd(int argc, const char** argv)
  393. {
  394. if (directory_stack.size() <= 1) {
  395. fprintf(stderr, "Shell: popd: directory stack empty\n");
  396. return 1;
  397. }
  398. bool should_not_switch = false;
  399. String path = directory_stack.take_last();
  400. Core::ArgsParser parser;
  401. parser.add_option(should_not_switch, "Do not switch dirs", "no-switch", 'n');
  402. if (!parser.parse(argc, const_cast<char**>(argv), false))
  403. return 1;
  404. bool should_switch = !should_not_switch;
  405. // When no arguments are given, popd removes the top directory from the stack and performs a cd to the new top directory.
  406. if (argc == 1) {
  407. int rc = chdir(path.characters());
  408. if (rc < 0) {
  409. fprintf(stderr, "chdir(%s) failed: %s\n", path.characters(), strerror(errno));
  410. return 1;
  411. }
  412. cwd = path;
  413. return 0;
  414. }
  415. LexicalPath lexical_path(path.characters());
  416. if (!lexical_path.is_valid()) {
  417. fprintf(stderr, "LexicalPath failed to canonicalize '%s'\n", path.characters());
  418. return 1;
  419. }
  420. const char* real_path = lexical_path.string().characters();
  421. struct stat st;
  422. int rc = stat(real_path, &st);
  423. if (rc < 0) {
  424. fprintf(stderr, "stat(%s) failed: %s\n", real_path, strerror(errno));
  425. return 1;
  426. }
  427. if (!S_ISDIR(st.st_mode)) {
  428. fprintf(stderr, "Not a directory: %s\n", real_path);
  429. return 1;
  430. }
  431. if (should_switch) {
  432. int rc = chdir(real_path);
  433. if (rc < 0) {
  434. fprintf(stderr, "chdir(%s) failed: %s\n", real_path, strerror(errno));
  435. return 1;
  436. }
  437. cwd = lexical_path.string();
  438. }
  439. return 0;
  440. }
  441. int Shell::builtin_pushd(int argc, const char** argv)
  442. {
  443. StringBuilder path_builder;
  444. bool should_switch = true;
  445. // From the BASH reference manual: https://www.gnu.org/software/bash/manual/html_node/Directory-Stack-Builtins.html
  446. // With no arguments, pushd exchanges the top two directories and makes the new top the current directory.
  447. if (argc == 1) {
  448. if (directory_stack.size() < 2) {
  449. fprintf(stderr, "pushd: no other directory\n");
  450. return 1;
  451. }
  452. String dir1 = directory_stack.take_first();
  453. String dir2 = directory_stack.take_first();
  454. directory_stack.insert(0, dir2);
  455. directory_stack.insert(1, dir1);
  456. int rc = chdir(dir2.characters());
  457. if (rc < 0) {
  458. fprintf(stderr, "chdir(%s) failed: %s\n", dir2.characters(), strerror(errno));
  459. return 1;
  460. }
  461. cwd = dir2;
  462. return 0;
  463. }
  464. // Let's assume the user's typed in 'pushd <dir>'
  465. if (argc == 2) {
  466. directory_stack.append(cwd.characters());
  467. if (argv[1][0] == '/') {
  468. path_builder.append(argv[1]);
  469. } else {
  470. path_builder.appendf("%s/%s", cwd.characters(), argv[1]);
  471. }
  472. } else if (argc == 3) {
  473. directory_stack.append(cwd.characters());
  474. for (int i = 1; i < argc; i++) {
  475. const char* arg = argv[i];
  476. if (arg[0] != '-') {
  477. if (arg[0] == '/') {
  478. path_builder.append(arg);
  479. } else
  480. path_builder.appendf("%s/%s", cwd.characters(), arg);
  481. }
  482. if (!strcmp(arg, "-n"))
  483. should_switch = false;
  484. }
  485. }
  486. LexicalPath lexical_path(path_builder.to_string());
  487. if (!lexical_path.is_valid()) {
  488. fprintf(stderr, "LexicalPath failed to canonicalize '%s'\n", path_builder.to_string().characters());
  489. return 1;
  490. }
  491. const char* real_path = lexical_path.string().characters();
  492. struct stat st;
  493. int rc = stat(real_path, &st);
  494. if (rc < 0) {
  495. fprintf(stderr, "stat(%s) failed: %s\n", real_path, strerror(errno));
  496. return 1;
  497. }
  498. if (!S_ISDIR(st.st_mode)) {
  499. fprintf(stderr, "Not a directory: %s\n", real_path);
  500. return 1;
  501. }
  502. if (should_switch) {
  503. int rc = chdir(real_path);
  504. if (rc < 0) {
  505. fprintf(stderr, "chdir(%s) failed: %s\n", real_path, strerror(errno));
  506. return 1;
  507. }
  508. cwd = lexical_path.string();
  509. }
  510. return 0;
  511. }
  512. int Shell::builtin_pwd(int, const char**)
  513. {
  514. print_path(cwd);
  515. fputc('\n', stdout);
  516. return 0;
  517. }
  518. int Shell::builtin_setopt(int argc, const char** argv)
  519. {
  520. if (argc == 1) {
  521. #define __ENUMERATE_SHELL_OPTION(name, default_, description) \
  522. if (options.name) \
  523. fprintf(stderr, #name "\n");
  524. ENUMERATE_SHELL_OPTIONS();
  525. #undef __ENUMERATE_SHELL_OPTION
  526. }
  527. Core::ArgsParser parser;
  528. #define __ENUMERATE_SHELL_OPTION(name, default_, description) \
  529. bool name = false; \
  530. bool not_##name = false; \
  531. parser.add_option(name, "Enable: " description, #name, '\0'); \
  532. parser.add_option(not_##name, "Disable: " description, "no_" #name, '\0');
  533. ENUMERATE_SHELL_OPTIONS();
  534. #undef __ENUMERATE_SHELL_OPTION
  535. if (!parser.parse(argc, const_cast<char**>(argv), false))
  536. return 1;
  537. #define __ENUMERATE_SHELL_OPTION(name, default_, description) \
  538. if (name) \
  539. options.name = true; \
  540. if (not_##name) \
  541. options.name = false;
  542. ENUMERATE_SHELL_OPTIONS();
  543. #undef __ENUMERATE_SHELL_OPTION
  544. return 0;
  545. }
  546. int Shell::builtin_shift(int argc, const char** argv)
  547. {
  548. int count = 1;
  549. Core::ArgsParser parser;
  550. parser.add_positional_argument(count, "Shift count", "count", Core::ArgsParser::Required::No);
  551. if (!parser.parse(argc, const_cast<char**>(argv), false))
  552. return 1;
  553. if (count < 1)
  554. return 0;
  555. auto argv_ = lookup_local_variable("ARGV");
  556. if (!argv_) {
  557. fprintf(stderr, "shift: ARGV is unset\n");
  558. return 1;
  559. }
  560. if (!argv_->is_list())
  561. argv_ = adopt(*new AST::ListValue({ argv_ }));
  562. auto& values = static_cast<AST::ListValue*>(argv_.ptr())->values();
  563. if ((size_t)count > values.size()) {
  564. fprintf(stderr, "shift: shift count must not be greater than %zu\n", values.size());
  565. return 1;
  566. }
  567. for (auto i = 0; i < count; ++i)
  568. values.take_first();
  569. return 0;
  570. }
  571. int Shell::builtin_time(int argc, const char** argv)
  572. {
  573. Vector<const char*> args;
  574. Core::ArgsParser parser;
  575. parser.add_positional_argument(args, "Command to execute with arguments", "command", Core::ArgsParser::Required::Yes);
  576. if (!parser.parse(argc, const_cast<char**>(argv), false))
  577. return 1;
  578. AST::Command command;
  579. for (auto& arg : args)
  580. command.argv.append(arg);
  581. auto commands = expand_aliases({ move(command) });
  582. Core::ElapsedTimer timer;
  583. int exit_code = 1;
  584. timer.start();
  585. for (auto& job : run_commands(commands)) {
  586. block_on_job(job);
  587. exit_code = job->exit_code();
  588. }
  589. fprintf(stderr, "Time: %d ms\n", timer.elapsed());
  590. return exit_code;
  591. }
  592. int Shell::builtin_umask(int argc, const char** argv)
  593. {
  594. const char* mask_text = nullptr;
  595. Core::ArgsParser parser;
  596. parser.add_positional_argument(mask_text, "New mask (omit to get current mask)", "octal-mask", Core::ArgsParser::Required::No);
  597. if (!parser.parse(argc, const_cast<char**>(argv), false))
  598. return 1;
  599. if (!mask_text) {
  600. mode_t old_mask = umask(0);
  601. printf("%#o\n", old_mask);
  602. umask(old_mask);
  603. return 0;
  604. }
  605. unsigned mask;
  606. int matches = sscanf(mask_text, "%o", &mask);
  607. if (matches == 1) {
  608. umask(mask);
  609. return 0;
  610. }
  611. fprintf(stderr, "umask: Invalid mask '%s'\n", mask_text);
  612. return 1;
  613. }
  614. int Shell::builtin_unset(int argc, const char** argv)
  615. {
  616. Vector<const char*> vars;
  617. Core::ArgsParser parser;
  618. parser.add_positional_argument(vars, "List of variables", "variables", Core::ArgsParser::Required::Yes);
  619. if (!parser.parse(argc, const_cast<char**>(argv), false))
  620. return 1;
  621. for (auto& value : vars) {
  622. if (lookup_local_variable(value)) {
  623. unset_local_variable(value);
  624. } else {
  625. unsetenv(value);
  626. }
  627. }
  628. return 0;
  629. }
  630. bool Shell::run_builtin(int argc, const char** argv, int& retval)
  631. {
  632. if (argc == 0)
  633. return false;
  634. StringView name { argv[0] };
  635. #define __ENUMERATE_SHELL_BUILTIN(builtin) \
  636. if (name == #builtin) { \
  637. retval = builtin_##builtin(argc, argv); \
  638. return true; \
  639. }
  640. ENUMERATE_SHELL_BUILTINS();
  641. #undef __ENUMERATE_SHELL_BUILTIN
  642. return false;
  643. }
  644. bool Shell::has_builtin(const StringView& name) const
  645. {
  646. #define __ENUMERATE_SHELL_BUILTIN(builtin) \
  647. if (name == #builtin) { \
  648. return true; \
  649. }
  650. ENUMERATE_SHELL_BUILTINS();
  651. #undef __ENUMERATE_SHELL_BUILTIN
  652. return false;
  653. }