Class: Buff::Ignore::IgnoreFile

Inherits:
Object
  • Object
show all
Defined in:
lib/buff/ignore/ignore_file.rb

Overview

A Ruby representation of an ignore file

Constant Summary collapse

COMMENT_OR_WHITESPACE =

Regular expression to match comments or plain whitespace

Returns:

  • (Regexp)
/^\s*(?:#.*)?$/.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(filepath, options = {}) ⇒ IgnoreFile

Create a new ignore file from the given filepath

Parameters:

  • filepath (String, Pathname)

    the path to the ignore file

  • options (Hash) (defaults to: {})

    a list of options to pass to the ignore file

  • [#to_s] (Hash)

    a customizable set of options

Raises:


27
28
29
30
31
32
33
34
35
# File 'lib/buff/ignore/ignore_file.rb', line 27

def initialize(filepath, options = {})
  raise IgnoreFileNotFound.new(filepath) unless filepath && File.exists?(filepath)

  @filepath = File.expand_path(filepath)
  @options  = options
  if @options[:base].nil?
    @options[:base] = File.directory?(filepath) ? filepath : File.dirname(filepath)
  end
end

Instance Attribute Details

#filepathString (readonly)

The path to the ignore file

Returns:

  • (String)

13
14
15
# File 'lib/buff/ignore/ignore_file.rb', line 13

def filepath
  @filepath
end

Instance Method Details

#apply(list) ⇒ Array

Apply the ignore to the list, returning a new list of filtered files

Examples:

files = ['Gemfile', 'Gemfile.lock', 'bacon', 'eggs']
ignore.apply(files) #=> ['bacon', 'eggs']

Parameters:

  • list (Array)

    the list of files to apply the ignore to

Returns:

  • (Array)

    the sanitized file list

See Also:


50
51
52
53
54
# File 'lib/buff/ignore/ignore_file.rb', line 50

def apply(list)
  tmp = list.dup
  apply!(tmp)
  tmp
end

#apply!(list) ⇒ Array?

Destructively remove all files from the given list

Parameters:

  • list (Array)

    the list of files to apply the ignore to

Returns:

  • (Array, nil)

    the elements removed, or nil if none were removed


63
64
65
66
67
# File 'lib/buff/ignore/ignore_file.rb', line 63

def apply!(list)
  list.reject! do |item|
    item.strip.empty? || ignored?(item)
  end
end

#ignored?(filename) ⇒ Boolean

Determine if a given filename should be ignored

Parameters:

  • filename (String)

    the file to match

Returns:

  • (Boolean)

    true if the file should be ignored, false otherwise


76
77
78
79
80
81
# File 'lib/buff/ignore/ignore_file.rb', line 76

def ignored?(filename)
  base = File.expand_path(options[:base] || File.dirname(filepath))
  basename = filename.sub(base + File::SEPARATOR, '')

  ignores.any? { |ignore| File.fnmatch?(ignore, basename) }
end