Class: Gitlab::Git::AttributesParser

Inherits:
Object
  • Object
show all
Defined in:
lib/gitlab/git/attributes_parser.rb

Overview

Class for parsing Git attribute files and extracting the attributes for file patterns.

Instance Method Summary collapse

Constructor Details

#initialize(attributes_data = "") ⇒ AttributesParser

Returns a new instance of AttributesParser.


8
9
10
# File 'lib/gitlab/git/attributes_parser.rb', line 8

def initialize(attributes_data = "")
  @data = attributes_data || ""
end

Instance Method Details

#attributes(file_path) ⇒ Object

Returns all the Git attributes for the given path.

file_path - A path to a file for which to get the attributes.

Returns a Hash.


17
18
19
20
21
22
23
24
25
# File 'lib/gitlab/git/attributes_parser.rb', line 17

def attributes(file_path)
  absolute_path = File.join('/', file_path)

  patterns.each do |pattern, attrs|
    return attrs if File.fnmatch?(pattern, absolute_path)
  end

  {}
end

#each_lineObject

Iterates over every line in the attributes file.


82
83
84
85
86
87
88
89
90
# File 'lib/gitlab/git/attributes_parser.rb', line 82

def each_line
  @data.each_line do |line|
    break unless line.valid_encoding?

    yield line.strip
  end
# Catch invalid byte sequences
rescue ArgumentError
end

#parse_attributes(string) ⇒ Object

Parses an attribute string.

These strings can be in the following formats:

text      # => { "text" => true }
-text     # => { "text" => false }
key=value # => { "key" => "value" }

string - The string to parse.

Returns a Hash containing the attributes and their values.


43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/gitlab/git/attributes_parser.rb', line 43

def parse_attributes(string)
  values = {}
  dash = '-'
  equal = '='
  binary = 'binary'

  string.split(/\s+/).each do |chunk|
    # Data such as "foo = bar" should be treated as "foo" and "bar" being
    # separate boolean attributes.
    next if chunk == equal

    key = chunk

    # Input: "-foo"
    if chunk.start_with?(dash)
      key = chunk.byteslice(1, chunk.length - 1)
      value = false

    # Input: "foo=bar"
    elsif chunk.include?(equal)
      key, value = chunk.split(equal, 2)

    # Input: "foo"
    else
      value = true
    end

    values[key] = value

    # When the "binary" option is set the "diff" option should be set to
    # the inverse. If "diff" is later set it should overwrite the
    # automatically set value.
    values['diff'] = false if key == binary && value
  end

  values
end

#patternsObject

Returns a Hash containing the file patterns and their attributes.


28
29
30
# File 'lib/gitlab/git/attributes_parser.rb', line 28

def patterns
  @patterns ||= parse_data
end