Serenity Operating System
1/*
2 * Copyright (c) 2021, Linus Groh <linusg@serenityos.org>
3 *
4 * SPDX-License-Identifier: BSD-2-Clause
5 */
6
7#include <LibCore/ArgsParser.h>
8#include <LibCore/File.h>
9#include <LibCore/System.h>
10#include <LibGUI/GML/Formatter.h>
11#include <LibMain/Main.h>
12
13static ErrorOr<bool> format_file(StringView path, bool inplace)
14{
15 auto read_from_stdin = path == "-";
16 auto open_mode = (inplace && !read_from_stdin) ? Core::File::OpenMode::ReadWrite : Core::File::OpenMode::Read;
17 auto file = TRY(Core::File::open_file_or_standard_stream(path, open_mode));
18
19 auto contents = TRY(file->read_until_eof());
20 auto formatted_gml_or_error = GUI::GML::format_gml(contents);
21 if (formatted_gml_or_error.is_error()) {
22 warnln("Failed to parse GML: {}", formatted_gml_or_error.error());
23 return false;
24 }
25 auto formatted_gml = formatted_gml_or_error.release_value();
26 if (inplace && !read_from_stdin) {
27 if (formatted_gml == contents)
28 return true;
29 TRY(file->seek(0, SeekMode::SetPosition));
30 TRY(file->truncate(0));
31 TRY(file->write_until_depleted(formatted_gml.bytes()));
32 } else {
33 out("{}", formatted_gml);
34 }
35 return formatted_gml == contents;
36}
37
38ErrorOr<int> serenity_main(Main::Arguments args)
39{
40 TRY(Core::System::pledge("stdio rpath wpath cpath"));
41
42 bool inplace = false;
43 Vector<DeprecatedString> files;
44
45 Core::ArgsParser args_parser;
46 args_parser.set_general_help("Format GML files.");
47 args_parser.add_option(inplace, "Write formatted contents back to file rather than standard output", "inplace", 'i');
48 args_parser.add_positional_argument(files, "File(s) to process", "path", Core::ArgsParser::Required::No);
49 args_parser.parse(args);
50
51 if (!inplace)
52 TRY(Core::System::pledge("stdio rpath"));
53
54 if (files.is_empty())
55 files.append("-");
56
57 auto formatting_changed = false;
58 for (auto& file : files) {
59 if (!TRY(format_file(file, inplace)))
60 formatting_changed = true;
61 }
62
63 if (formatting_changed) {
64 dbgln("Some GML formatting issues were encountered.");
65 return 1;
66 }
67
68 return 0;
69}