Class: IOStreams::Paths::Matcher

Inherits:
Object
  • Object
show all
Defined in:
lib/io_streams/paths/matcher.rb

Overview

Implement fnmatch logic for any path iterator

Constant Summary collapse

MATCH_START_CHARS =

Characters indicating that pattern matching is required

/[*?\[{]/

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path, pattern, case_sensitive: false, hidden: false) ⇒ Matcher

If the supplied pattern contains sub-directories without wildcards, navigate down to that directory first before applying wildcard lookups from that point on.

Examples: If the current path is “/path/work”

"a/b/c/**/*"  => "/path/work/a/b/c"
"a/b/c?/**/*" => "/path/work/a/b"
"**/*"        => "/path/work"

Note: Absolute paths in the pattern are not supported.



19
20
21
22
23
24
25
# File 'lib/io_streams/paths/matcher.rb', line 19

def initialize(path, pattern, case_sensitive: false, hidden: false)
  extract_optimized_path(path, pattern)

  @flags = ::File::FNM_EXTGLOB | ::File::FNM_PATHNAME
  @flags |= ::File::FNM_CASEFOLD unless case_sensitive
  @flags |= ::File::FNM_DOTMATCH if hidden
end

Instance Attribute Details

#flagsObject (readonly)

Returns the value of attribute flags.



8
9
10
# File 'lib/io_streams/paths/matcher.rb', line 8

def flags
  @flags
end

#pathObject (readonly)

Returns the value of attribute path.



8
9
10
# File 'lib/io_streams/paths/matcher.rb', line 8

def path
  @path
end

#patternObject (readonly)

Returns the value of attribute pattern.



8
9
10
# File 'lib/io_streams/paths/matcher.rb', line 8

def pattern
  @pattern
end

Instance Method Details

#match?(file_name) ⇒ Boolean

Returns whether the relative ‘file_name` matches

Returns:

  • (Boolean)


28
29
30
31
# File 'lib/io_streams/paths/matcher.rb', line 28

def match?(file_name)
  relative_file_name = file_name.sub(path.to_s, '').sub(%r{\A/}, '')
  ::File.fnmatch?(pattern, relative_file_name, flags)
end

#recursive?Boolean

Whether this pattern includes a recursive match. I.e. Includes ‘**` anywhere in the path

Returns:

  • (Boolean)


35
36
37
# File 'lib/io_streams/paths/matcher.rb', line 35

def recursive?
  @recursive ||= pattern.nil? ? false : pattern.include?("**")
end