Serenity Operating System
at master 62 lines 1.9 kB view raw
1/* 2 * Copyright (c) 2019-2020, Sergey Bugaev <bugaevc@serenityos.org> 3 * 4 * SPDX-License-Identifier: BSD-2-Clause 5 */ 6 7#include <AK/DeprecatedString.h> 8#include <LibCore/ArgsParser.h> 9#include <LibCore/File.h> 10#include <LibCore/System.h> 11#include <LibMain/Main.h> 12#include <LibMarkdown/Document.h> 13#include <sys/ioctl.h> 14#include <unistd.h> 15 16ErrorOr<int> serenity_main(Main::Arguments arguments) 17{ 18 TRY(Core::System::pledge("stdio rpath tty")); 19 20 StringView filename; 21 bool html = false; 22 int view_width = 0; 23 24 Core::ArgsParser args_parser; 25 args_parser.set_general_help("Render Markdown to some other format."); 26 args_parser.add_option(html, "Render to HTML rather than for the terminal", "html", 'H'); 27 args_parser.add_option(view_width, "Viewport width for the terminal (defaults to current terminal width)", "view-width", 0, "width"); 28 args_parser.add_positional_argument(filename, "Path to Markdown file", "path", Core::ArgsParser::Required::No); 29 args_parser.parse(arguments); 30 31 if (!html && view_width == 0) { 32 if (isatty(STDOUT_FILENO)) { 33 struct winsize ws; 34 if (ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) < 0) 35 view_width = 80; 36 else 37 view_width = ws.ws_col; 38 39 } else { 40 view_width = 80; 41 } 42 } 43 44 auto file = TRY(Core::File::open_file_or_standard_stream(filename, Core::File::OpenMode::Read)); 45 46 TRY(Core::System::pledge("stdio")); 47 48 auto buffer = TRY(file->read_until_eof()); 49 dbgln("Read size {}", buffer.size()); 50 51 auto input = DeprecatedString::copy(buffer); 52 auto document = Markdown::Document::parse(input); 53 54 if (!document) { 55 warnln("Error parsing Markdown document"); 56 return 1; 57 } 58 59 DeprecatedString res = html ? document->render_to_html() : document->render_for_terminal(view_width); 60 out("{}", res); 61 return 0; 62}