gml-format.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. ErrorOr<bool> format_file(StringView, bool);
  12. ErrorOr<bool> format_file(StringView path, bool inplace)
  13. {
  14. auto read_from_stdin = path == "-";
  15. RefPtr<Core::File> file;
  16. if (read_from_stdin) {
  17. file = Core::File::standard_input();
  18. } else {
  19. auto open_mode = inplace ? Core::OpenMode::ReadWrite : Core::OpenMode::ReadOnly;
  20. file = TRY(Core::File::open(path, open_mode));
  21. }
  22. auto contents = file->read_all();
  23. auto formatted_gml_or_error = GUI::GML::format_gml(contents);
  24. if (formatted_gml_or_error.is_error()) {
  25. warnln("Failed to parse GML: {}", formatted_gml_or_error.error());
  26. return false;
  27. }
  28. auto formatted_gml = formatted_gml_or_error.release_value();
  29. if (inplace && !read_from_stdin) {
  30. if (formatted_gml == contents)
  31. return true;
  32. if (!file->seek(0) || !file->truncate(0)) {
  33. warnln("Could not truncate {}: {}", path, file->error_string());
  34. return false;
  35. }
  36. if (!file->write(formatted_gml)) {
  37. warnln("Could not write to {}: {}", path, file->error_string());
  38. return false;
  39. }
  40. } else {
  41. out("{}", formatted_gml);
  42. }
  43. return formatted_gml == contents;
  44. }
  45. ErrorOr<int> serenity_main(Main::Arguments args)
  46. {
  47. TRY(Core::System::pledge("stdio rpath wpath cpath"));
  48. bool inplace = false;
  49. Vector<String> files;
  50. Core::ArgsParser args_parser;
  51. args_parser.set_general_help("Format GML files.");
  52. args_parser.add_option(inplace, "Write formatted contents back to file rather than standard output", "inplace", 'i');
  53. args_parser.add_positional_argument(files, "File(s) to process", "path", Core::ArgsParser::Required::No);
  54. args_parser.parse(args);
  55. if (!inplace)
  56. TRY(Core::System::pledge("stdio rpath"));
  57. if (files.is_empty())
  58. files.append("-");
  59. auto formatting_changed = false;
  60. for (auto& file : files) {
  61. if (!TRY(format_file(file, inplace)))
  62. formatting_changed = true;
  63. }
  64. if (formatting_changed) {
  65. dbgln("Some GML formatting issues were encountered.");
  66. return 1;
  67. }
  68. return 0;
  69. }