Class: GitignoreParser

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

Constant Summary collapse

DEFAULT_IGNORES =
".git\n"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(gitpath) ⇒ GitignoreParser

Returns a new instance of GitignoreParser.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/gitignore_parser.rb', line 10

def initialize(gitpath)
  @gitpath = gitpath
  
  ignore_file = File.join(@gitpath, '.gitignore')
  gitignore = DEFAULT_IGNORES
  gitignore += File.read(ignore_file) if File.exist?(ignore_file)
  
  @globs = []
  rx = gitignore.split("\n").map do |i|
    i.strip!
    if i == '' or i.slice(0,1) == '#'
      nil
    elsif not i.include?('*')
      if i.slice(-1,1) == '/'
        i
      else
        "^#{i}|\/#{i}"
      end
    else
      @globs << i
      nil
    end
  end.compact.join("|")
  @regex = (rx == '' ? nil : Regexp.new(rx))
end

Class Method Details

.parse(gitpath) ⇒ Object



5
6
7
# File 'lib/gitignore_parser.rb', line 5

def parse(gitpath)
  new(gitpath)
end

Instance Method Details

#ignore?(path) ⇒ Boolean

Returns:

  • (Boolean)

Raises:



36
37
38
39
40
# File 'lib/gitignore_parser.rb', line 36

def ignore?(path)
  raise NotAbsolutePathError unless path.slice(0, 1) == '/'
  relpath = path.gsub %r{^#{Regexp.escape(@gitpath)}\/}, ''
  @regex =~ relpath || @globs.any? {|g| File.fnmatch(g, relpath) }
end