Class: Globby::Glob

Inherits:
Object
  • Object
show all
Defined in:
lib/globby/glob.rb

Constant Summary collapse

GLOB_BRACKET_EXPR =
/
\[ # brackets
  !? # (maybe) negation
  \]? # (maybe) right bracket
  (?: # one or more:
    \[[^\/\]]+\] # named character class, collating symbol or equivalence class
    | [^\/\]] # non-right bracket character (could be part of a range)
  )+
\]/x
GLOB_ESCAPED_CHAR =
/\\./
GLOB_RECURSIVE_WILDCARD =
/\/\*\*(?:\/|\z)/
GLOB_WILDCARD =
/[\?\*]/
GLOB_TOKENIZER =
/(
  #{GLOB_BRACKET_EXPR} |
  #{GLOB_ESCAPED_CHAR} |
  #{GLOB_RECURSIVE_WILDCARD}
)/x

Instance Method Summary collapse

Constructor Details

#initialize(pattern) ⇒ Glob

Returns a new instance of Glob.



3
4
5
6
7
8
9
10
# File 'lib/globby/glob.rb', line 3

def initialize(pattern)
  pattern = pattern.dup
  @inverse = pattern.sub!(/\A!/, '')
  # remove meaningless wildcards
  pattern.sub!(/\A\/?(\*\*\/)+/, '')
  pattern.sub!(/(\/\*\*)+\/\*\z/, '/**')
  @pattern = pattern
end

Instance Method Details

#directory?Boolean

Returns:

  • (Boolean)


21
22
23
# File 'lib/globby/glob.rb', line 21

def directory?
  @pattern =~ /\/\z/
end

#exact_match?Boolean

Returns:

  • (Boolean)


25
26
27
# File 'lib/globby/glob.rb', line 25

def exact_match?
  @pattern =~ /\A\// && @pattern !~ /[\*\?]/
end

#inverse?Boolean

Returns:

  • (Boolean)


17
18
19
# File 'lib/globby/glob.rb', line 17

def inverse?
  @inverse
end

#match(files) ⇒ Object



12
13
14
15
# File 'lib/globby/glob.rb', line 12

def match(files)
  return [] unless files
  files.grep(to_regexp)
end

#to_regexpObject



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/globby/glob.rb', line 49

def to_regexp
  parts = @pattern.split(GLOB_TOKENIZER) - [""]

  result = parts.first.sub!(/\A\//, '') ? '\A' : '(\A|/)'
  parts.each do |part|
    result << part_to_regexp(part)
  end
  if result[-1, 1] == '/'
    result << '\z'
  elsif result[-2, 2] == '.*'
    result.slice!(-2, 2)
  else
    result << '\/?\z'
  end
  Regexp.new result
end