Skip to content
Kward Search API index

Class: Kward::NativeShell::Pattern

Inherits:
Object
  • Object
show all
Defined in:
lib/kward/shell/native_pattern.rb

Overview

Shell patterns for case and parameter trimming, not filesystem globbing. Wildcards match slashes and leading dots here. Only a single-character bracket expression uses Regexp; arbitrary shell text is always escaped.

Defined Under Namespace

Classes: Bracket, LimitError

Constant Summary collapse

CLASSES =
%w[alnum alpha blank cntrl digit graph lower print punct space upper xdigit].freeze
MAX_MATCH_STEPS =
1_000_000
MAX_MATCH_BYTES =
16 * 1024 * 1024

Instance Method Summary collapse

Constructor Details

#initialize(source, locale: nil) ⇒ Pattern

Returns a new instance of Pattern.



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/kward/shell/native_pattern.rb', line 54

def initialize(source, locale: nil)
  @locale = locale
  @source = locale ? locale.text(source) : source
  @index = 0
  @tokens = []
  while (character = @source[@index])
    @index += 1
    @tokens << case character
    when "*" then :star
    when "?" then :any
    when "\\"
      escaped = @source[@index]
      @index += 1 if escaped
      escaped || "\\"
    when "[" then bracket || "["
    else character
    end
  end
end

Instance Method Details

#match?(value) ⇒ Boolean

Returns:

  • (Boolean)


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
# File 'lib/kward/shell/native_pattern.rb', line 78

def match?(value)
  characters = (@locale ? @locale.text(value) : value).chars
  return match_collating(characters) if @locale&.multichar && @tokens.any? { |token| token.is_a?(Bracket) }
  token_index = 0
  value_index = 0
  star_index = nil
  retry_index = 0
  while value_index < characters.length
    token = @tokens[token_index]
    if token == :star
      star_index = token_index
      token_index += 1
      retry_index = value_index
    elsif token == :any || (token.is_a?(Regexp) || token.is_a?(Bracket)) && token.match?(characters[value_index]) || token == characters[value_index]
      token_index += 1
      value_index += 1
    elsif star_index
      token_index = star_index + 1
      retry_index += 1
      value_index = retry_index
    else
      return false
    end
  end
  token_index += 1 while @tokens[token_index] == :star
  token_index == @tokens.length
end

#wildcards? ⇒ Boolean

Returns:

  • (Boolean)


74
75
76
# File 'lib/kward/shell/native_pattern.rb', line 74

def wildcards?
  @tokens.any? { |token| token == :star || token == :any || token.is_a?(Regexp) || token.is_a?(Bracket) }
end