diff --git a/app/models/repository.rb b/app/models/repository.rb index 2ffd9558ebc..a67bb7294e6 100644 --- a/app/models/repository.rb +++ b/app/models/repository.rb @@ -938,9 +938,11 @@ class Repository end def search_files_by_name(query, ref) - return [] if empty? || query.blank? + safe_query = Regexp.escape(query.sub(/^\/*/, "")) - args = %W(ls-tree --full-tree -r #{ref || root_ref} --name-status | #{Regexp.escape(query)}) + return [] if empty? || safe_query.blank? + + args = %W(ls-tree --full-tree -r #{ref || root_ref} --name-status | #{safe_query}) run_git(args).first.lines.map(&:strip) end diff --git a/changelogs/unreleased/36571-ignore-root-in-repo.yml b/changelogs/unreleased/36571-ignore-root-in-repo.yml new file mode 100644 index 00000000000..396e82be51b --- /dev/null +++ b/changelogs/unreleased/36571-ignore-root-in-repo.yml @@ -0,0 +1,5 @@ +--- +title: Ignore leading slashes when searching for files within context of repository. +merge_request: +author: Andrew McCallum +type: fixed diff --git a/spec/models/repository_spec.rb b/spec/models/repository_spec.rb index f3456e5b354..d9395ca61d7 100644 --- a/spec/models/repository_spec.rb +++ b/spec/models/repository_spec.rb @@ -668,6 +668,18 @@ describe Repository do expect(results.first).to eq('files/html/500.html') end + it 'ignores leading slashes' do + results = repository.search_files_by_name('/files', 'master') + + expect(results.first).to eq('files/html/500.html') + end + + it 'properly handles when query is only slashes' do + results = repository.search_files_by_name('//', 'master') + + expect(results).to match_array([]) + end + it 'properly handles when query is not present' do results = repository.search_files_by_name('', 'master')