# hx/path - path selectors # # Copyright (c) 2009-2010 MenTaLguY # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. module Hx module Path module Selector def accept_path?(path) raise NotImplementedError, "#{self.class}#accept_path? not implemented" end def |(other) Disjunction.build(self, other) end def &(other) Conjunction.build(self, other) end def ~() Negation.new(self) end end class All include Selector def accept_path?(path) ; true ; end end ALL = All.new class Pattern include Selector def initialize(tokens) @regexp = Regexp.new("^#{tokens.map { |token| case token when :doublestar; '.*' when :star; '[^/]*' else; Regexp.quote(token) end }}$") end def accept_path?(path) ; !!(path =~ @regexp) ; end end def self.parse_pattern(pattern_string) tokens = [] pattern_string.scan(/(\*\*?|[^*]+)/) do |token,| tokens << case token when "**"; :doublestar when "*"; :star else; token end end Pattern.new(tokens) end def self.literal(literal_string) Pattern.new([literal_string]) end module Connective include Selector def initialize(*selectors) @selectors = selectors end end class Conjunction include Connective def self.build(*selectors) if selectors.any? { |s| All === s } selectors.reject! { |s| All === s } case selectors.size when 0; return ALL when 1; return selectors.first end end new(*selectors) end def accept_path?(path) @selectors.all? { |s| s.accept_path? path } end end class Disjunction include Connective def self.build(*selectors) return ALL if selectors.any? { |s| All === s } new(*selectors) end def accept_path?(path) @selectors.any? { |s| s.accept_path? path } end end class Negation include Selector def initialize(selector) @selector = selector end def accept_path?(path) not @selector.accept_path?(path) end end end end