Class: Fluent::GlobMatchPattern

Inherits:
MatchPattern show all
Defined in:
lib/fluent/match.rb

Instance Method Summary collapse

Methods inherited from MatchPattern

create

Constructor Details

#initialize(pat) ⇒ GlobMatchPattern



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/fluent/match.rb', line 35

def initialize(pat)
  if pat.start_with?('/')
    if pat.end_with?('/')
      @regex = Regexp.new("\\A"+pat[1..-2]+"\\Z")
      return
    else
      raise Fluent::ConfigError,  "invalid match - regex"
    end
  end

  stack = []
  regex = ['']
  escape = false
  dot = false

  i = 0
  while i < pat.length
    c = pat[i,1]

    if escape
      regex.last << Regexp.escape(c)
      escape = false
      i += 1
      next

    elsif pat[i,2] == "**"
      # recursive any
      if dot
        regex.last << "(?![^\\.])"
        dot = false
      end
      if pat[i+2,1] == "."
        regex.last << "(?:.*\\.|\\A)"
        i += 3
      else
        regex.last << ".*"
        i += 2
      end
      next

    elsif dot
      regex.last << "\\."
      dot = false
    end

    if c == "\\"
      escape = true

    elsif c == "."
      dot = true

    elsif c == "*"
      # any
      regex.last << "[^\\.]*"

      # TODO
      #elsif c == "["
      #  # character class
      #  chars = ''
      #  while i < pat.length
      #    c = pat[i,1]
      #    if c == "]"
      #      break
      #    else
      #      chars << c
      #    end
      #    i += 1
      #  end
      #  regex.last << '['+Regexp.escape(chars).gsub("\\-",'-')+']'

    elsif c == "{"
      # or
      stack.push []
      regex.push ''

    elsif c == "}" && !stack.empty?
      stack.last << regex.pop
      regex.last << Regexp.union(*stack.pop.map {|r| Regexp.new(r) }).to_s

    elsif c == "," && !stack.empty?
      stack.last << regex.pop
      regex.push ''

    elsif /[a-zA-Z0-9_]/.match?(c)
      regex.last << c

    else
      regex.last << "\\#{c}"
    end

    i += 1
  end

  until stack.empty?
    stack.last << regex.pop
    regex.last << Regexp.union(*stack.pop).to_s
  end

  @regex = Regexp.new("\\A"+regex.last+"\\Z")
end

Instance Method Details

#match(str) ⇒ Object



136
137
138
# File 'lib/fluent/match.rb', line 136

def match(str)
  @regex.match?(str)
end