man.cpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. /*
  2. * Copyright (c) 2019-2020, Sergey Bugaev <bugaevc@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Assertions.h>
  7. #include <AK/ByteBuffer.h>
  8. #include <AK/String.h>
  9. #include <LibCore/ArgsParser.h>
  10. #include <LibCore/File.h>
  11. #include <LibMarkdown/Document.h>
  12. #include <stdio.h>
  13. #include <sys/ioctl.h>
  14. #include <unistd.h>
  15. int main(int argc, char* argv[])
  16. {
  17. int view_width = 0;
  18. if (isatty(STDOUT_FILENO)) {
  19. struct winsize ws;
  20. if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0)
  21. view_width = ws.ws_col;
  22. }
  23. if (view_width == 0)
  24. view_width = 80;
  25. if (pledge("stdio rpath", nullptr) < 0) {
  26. perror("pledge");
  27. return 1;
  28. }
  29. if (unveil("/usr/share/man", "r") < 0) {
  30. perror("unveil");
  31. return 1;
  32. }
  33. unveil(nullptr, nullptr);
  34. const char* section = nullptr;
  35. const char* name = nullptr;
  36. Core::ArgsParser args_parser;
  37. args_parser.set_general_help("Read manual pages. Try 'man man' to get started.");
  38. args_parser.add_positional_argument(section, "Section of the man page", "section", Core::ArgsParser::Required::No);
  39. args_parser.add_positional_argument(name, "Name of the man page", "name");
  40. args_parser.parse(argc, argv);
  41. auto make_path = [name](const char* section) {
  42. return String::formatted("/usr/share/man/man{}/{}.md", section, name);
  43. };
  44. if (!section) {
  45. const char* sections[] = {
  46. "1",
  47. "2",
  48. "3",
  49. "4",
  50. "5",
  51. "6",
  52. "7",
  53. "8"
  54. };
  55. for (auto s : sections) {
  56. String path = make_path(s);
  57. if (access(path.characters(), R_OK) == 0) {
  58. section = s;
  59. break;
  60. }
  61. }
  62. if (!section) {
  63. fprintf(stderr, "No man page for %s\n", name);
  64. exit(1);
  65. }
  66. }
  67. auto file = Core::File::construct();
  68. file->set_filename(make_path(section));
  69. if (!file->open(Core::OpenMode::ReadOnly)) {
  70. perror("Failed to open man page file");
  71. exit(1);
  72. }
  73. if (pledge("stdio", nullptr) < 0) {
  74. perror("pledge");
  75. return 1;
  76. }
  77. dbgln("Loading man page from {}", file->filename());
  78. auto buffer = file->read_all();
  79. auto source = String::copy(buffer);
  80. printf("%s(%s)\t\tSerenityOS manual\n", name, section);
  81. auto document = Markdown::Document::parse(source);
  82. VERIFY(document);
  83. String rendered = document->render_for_terminal(view_width);
  84. printf("%s", rendered.characters());
  85. }