GitCommitLexer.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. * Copyright (c) 2022, Brian Gianforcaro <bgianf@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/CharacterTypes.h>
  7. #include <AK/Vector.h>
  8. #include <LibGUI/GitCommitLexer.h>
  9. namespace GUI {
  10. GitCommitLexer::GitCommitLexer(StringView input)
  11. : m_input(input)
  12. {
  13. }
  14. char GitCommitLexer::peek(size_t offset) const
  15. {
  16. if ((m_index + offset) >= m_input.length())
  17. return 0;
  18. return m_input[m_index + offset];
  19. }
  20. char GitCommitLexer::consume()
  21. {
  22. VERIFY(m_index < m_input.length());
  23. char ch = m_input[m_index++];
  24. if (ch == '\n') {
  25. m_position.line++;
  26. m_position.column = 0;
  27. } else {
  28. m_position.column++;
  29. }
  30. return ch;
  31. }
  32. Vector<GitCommitToken> GitCommitLexer::lex()
  33. {
  34. Vector<GitCommitToken> tokens;
  35. size_t token_start_index = 0;
  36. GitCommitPosition token_start_position;
  37. auto begin_token = [&] {
  38. token_start_index = m_index;
  39. token_start_position = m_position;
  40. };
  41. auto commit_token = [&](auto type) {
  42. GitCommitToken token;
  43. token.m_view = m_input.substring_view(token_start_index, m_index - token_start_index);
  44. token.m_type = type;
  45. token.m_start = token_start_position;
  46. token.m_end = m_position;
  47. tokens.append(token);
  48. };
  49. while (m_index < m_input.length()) {
  50. if (is_ascii_space(peek(0))) {
  51. begin_token();
  52. while (is_ascii_space(peek()))
  53. consume();
  54. continue;
  55. }
  56. // Commit comments
  57. if (peek(0) && peek(0) == '#') {
  58. begin_token();
  59. while (peek() && peek() != '\n')
  60. consume();
  61. commit_token(GitCommitToken::Type::Comment);
  62. continue;
  63. }
  64. consume();
  65. commit_token(GitCommitToken::Type::Unknown);
  66. }
  67. return tokens;
  68. }
  69. }