Builtin.cpp 23 KB

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