Skip to content

Commit

Permalink
use git check-ignore instead of git ls-files
Browse files Browse the repository at this point in the history
  • Loading branch information
flyerhzm committed Feb 18, 2024
1 parent 3e403df commit 5b50c45
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 12 deletions.
17 changes: 12 additions & 5 deletions lib/synvert/core/utils.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
require 'net/http'
require 'uri'
require 'open-uri'
require 'open3'

module Synvert::Core
class Utils
Expand Down Expand Up @@ -35,13 +36,19 @@ def load_snippet(snippet_name)
# @return [Array<String>] file paths
def glob(file_patterns)
Dir.chdir(Configuration.root_path) do
all_files = if Configuration.respect_gitignore
`git ls-files --cached --others --exclude-standard #{file_patterns.join(' ')}`.split("\n")
else
file_patterns.flat_map { |file_pattern| Dir.glob(file_pattern) }
all_files = file_patterns.flat_map { |pattern| Dir.glob(pattern) }
ignored_files = []

if Configuration.respect_gitignore
Open3.popen3('git check-ignore --stdin') do |stdin, stdout, stderr, wait_thr|
stdin.puts(all_files.join("\n"))
stdin.close

ignored_files = stdout.read.split("\n")
end
end

filtered_files = filter_only_paths(all_files)
filtered_files = filter_only_paths(all_files - ignored_files)

filtered_files -= get_explicitly_skipped_files
end
Expand Down
21 changes: 14 additions & 7 deletions spec/synvert/core/utils_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -78,14 +78,21 @@ module Synvert::Core
Configuration.respect_gitignore = true
end

it 'gets all files' do
expect(Object).to receive(:`).and_return(
[
'app/models/post.rb',
'app/controllers/posts_controller.rb'
].join("\n")
it 'correctly filters out ignored files' do
file_patterns = ["**/*.rb"]
all_files = ["app/models/post.rb", "app/controllers/posts_controller.rb", "app/controllers/temp.tmp"]
not_ignored_files = ["app/models/post.rb", "app/controllers/posts_controller.rb"]
command_output = "app/controllers/temp.tmp\n"

allow(Open3).to receive(:popen3).with('git check-ignore --stdin').and_yield(
instance_double(IO, puts: nil, close: nil),
StringIO.new(command_output),
StringIO.new(''),
instance_double(Process::Waiter, value: instance_double(Process::Status, success?: true))
)
expect(described_class.glob(['**/*.rb'])).to eq(['app/models/post.rb', 'app/controllers/posts_controller.rb'])
allow(Dir).to receive(:glob).and_return(all_files)

expect(described_class.glob(file_patterns)).to match_array(not_ignored_files)
end
end

Expand Down

0 comments on commit 5b50c45

Please sign in to comment.