gml-format.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 (!file->seek(0) || !file->truncate(0)) {
  31. warnln("Could not truncate {}: {}", path, file->error_string());
  32. return false;
  33. }
  34. if (!file->write(formatted_gml)) {
  35. warnln("Could not write to {}: {}", path, file->error_string());
  36. return false;
  37. }
  38. } else {
  39. out("{}", formatted_gml);
  40. }
  41. return true;
  42. }
  43. ErrorOr<int> serenity_main(Main::Arguments args)
  44. {
  45. #ifdef __serenity__
  46. TRY(Core::System::pledge("stdio rpath wpath cpath", nullptr));
  47. #endif
  48. bool inplace = false;
  49. Vector<const char*> 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. #ifdef __serenity__
  56. if (!inplace)
  57. TRY(Core::System::pledge("stdio rpath", nullptr));
  58. #endif
  59. unsigned exit_code = 0;
  60. if (files.is_empty())
  61. files.append("-");
  62. for (auto& file : files) {
  63. if (!TRY(format_file(file, inplace)))
  64. exit_code = 1;
  65. }
  66. return exit_code;
  67. }