gml-format.cpp 2.2 KB

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