Commit 9c7e56c3 authored by Mark Chao's avatar Mark Chao Committed by Bob Van Landuyt

Refactor logic

parent 2b0f880a
......@@ -3,8 +3,6 @@
module Gitlab
module CodeOwners
class File
ROOT_DIR_PATTERN = '/*'
def initialize(blob)
@blob = blob
end
......@@ -18,6 +16,8 @@ module Gitlab
end
def owners_for_path(path)
path = "/#{path}" unless path.start_with?('/')
matching_pattern = parsed_data.keys.reverse.detect do |pattern|
path_matches?(pattern, path)
end
......@@ -54,46 +54,31 @@ module Gitlab
end
def normalize_pattern(pattern)
return ROOT_DIR_PATTERN if pattern == ROOT_DIR_PATTERN
# Remove `\` when escaping `\#`
pattern = pattern.sub(/\A\\#/, '#')
# Replace all whitespace preceded by a \ with a regular whitespace
pattern = pattern.gsub(/\\\s+/, ' ')
if pattern.starts_with?('/')
# Remove the leading slash when only matching root directory as the
# paths that we will be matching will always be passed in starting
# from the root of the repsitory.
pattern = pattern.sub(%r{\A/}, '')
elsif !pattern.starts_with?('*')
# If the pattern is a regular match, prepend it with ** so we match
# nested in every directory
pattern = "**#{pattern}"
return '/**/*' if pattern == '*'
unless pattern.starts_with?('/')
pattern = "/**/#{pattern}"
end
if pattern.end_with?('/')
pattern = "#{pattern}**/*"
end
pattern
end
def path_matches?(pattern, path)
flags = ::File::FNM_DOTMATCH
if pattern == ROOT_DIR_PATTERN
# Matching everyting on the root, but only one level deep
flags |= ::File::FNM_PATHNAME
::File.fnmatch?('*', path, flags)
elsif pattern.ends_with?('/*')
# Then the pattern ends in a wildcard, we only want to go one level deep
# setting `::File::FNM_PATHNAME` makes the `*` not match directory
# separators
flags |= ::File::FNM_PATHNAME
::File.fnmatch?(pattern, path, flags)
else
# Replace a pattern ending with `/` to `/*` to match everything within
# that directory
nested_pattern = pattern.sub(%r{/\z}, '/*')
::File.fnmatch?(nested_pattern, path, flags)
end
flags = ::File::FNM_DOTMATCH | ::File::FNM_PATHNAME
# Then the pattern ends in a wildcard, we only want to go one level deep
# setting `::File::FNM_PATHNAME` makes the `*` not match directory
# separators
::File.fnmatch?(pattern, path, flags)
end
end
end
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment