summaryrefslogtreecommitdiff
path: root/lib/gitlab/ci/pipeline/expression/statement.rb
blob: 2f2a647086262c9678f288c69d7c335724f25227 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# frozen_string_literal: true

module Gitlab
  module Ci
    module Pipeline
      module Expression
        class Statement
          StatementError = Class.new(Expression::ExpressionError)

          GRAMMAR = [
            %w[variable],
            %w[variable equals string],
            %w[variable equals variable],
            %w[variable equals null],
            %w[string equals variable],
            %w[null equals variable],
            %w[variable matches pattern]
          ].freeze

          def initialize(statement, variables = {})
            @lexer = Expression::Lexer.new(statement)
            @variables = variables.with_indifferent_access
          end

          def parse_tree
            raise StatementError if @lexer.lexemes.empty?

            unless GRAMMAR.find { |syntax| syntax == @lexer.lexemes }
              raise StatementError, _('Unknown pipeline expression!')
            end

            Expression::Parser.new(@lexer.tokens).tree
          end

          def evaluate
            parse_tree.evaluate(@variables.to_h)
          end

          def truthful?
            evaluate.present?
          rescue Expression::ExpressionError
            false
          end

          def valid?
            parse_tree.is_a?(Lexeme::Base)
          rescue Expression::ExpressionError
            false
          end
        end
      end
    end
  end
end