Skip to content

Commit afdebb3

Browse files
committed
Gracefully handle binary files in LineEndings pre-commit hook
The hook would fail when attempting to read some binary files. Gracefully fail by reporting a warning instead. Fixes sds#492
1 parent 363475b commit afdebb3

File tree

3 files changed

+35
-9
lines changed

3 files changed

+35
-9
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
* Add [`hadolint`](https://github.com/lukasmartinelli/hadolint) pre-commit hook
77
* Add [`license_finder`](https://github.com/pivotal/LicenseFinder) pre-commit hook
88
* Use the `core.hooksPath` Git configuration option when installing hooks
9+
* Gracefully handle binary files in `LineEndings` pre-commit hook
910

1011
## 0.39.1
1112

lib/overcommit/hook/pre_commit/line_endings.rb

+28-9
Original file line numberDiff line numberDiff line change
@@ -8,18 +8,16 @@ def run
88

99
offending_files.map do |file_name|
1010
file = File.open(file_name)
11-
file.each_line do |line|
12-
# remove configured line-ending
13-
line.gsub!(/#{config['eol']}/, '')
14-
15-
# detect any left over line-ending characters
16-
next unless line.end_with?("\n", "\r")
17-
11+
begin
12+
messages += check_file(file, file_name)
13+
rescue ArgumentError => ex
14+
# File is likely a binary file which this check should ignore, but
15+
# print a warning just in case
1816
messages << Overcommit::Hook::Message.new(
19-
:error,
17+
:warning,
2018
file_name,
2119
file.lineno,
22-
"#{file_name}:#{file.lineno}:#{line.inspect}"
20+
"#{file_name}:#{file.lineno}:#{ex.message}"
2321
)
2422
end
2523
end
@@ -29,6 +27,27 @@ def run
2927

3028
private
3129

30+
def check_file(file, file_name)
31+
messages_for_file = []
32+
33+
file.each_line do |line|
34+
# Remove configured line-ending
35+
line.gsub!(/#{config['eol']}/, '')
36+
37+
# Detect any left over line-ending characters
38+
next unless line.end_with?("\n", "\r")
39+
40+
messages_for_file << Overcommit::Hook::Message.new(
41+
:error,
42+
file_name,
43+
file.lineno,
44+
"#{file_name}:#{file.lineno}:#{line.inspect}"
45+
)
46+
end
47+
48+
messages_for_file
49+
end
50+
3251
def offending_files
3352
result = execute(%w[git ls-files --eol -z --], args: applicable_files)
3453
raise 'Unable to access git tree' unless result.success?

spec/overcommit/hook/pre_commit/line_endings_spec.rb

+6
Original file line numberDiff line numberDiff line change
@@ -60,4 +60,10 @@
6060
it { should fail_hook }
6161
end
6262
end
63+
64+
context 'when attempting to check a binary file' do
65+
let(:contents) { "\xFF\xD8\xFF\xE0\u0000\u0010JFIF" }
66+
67+
it { should warn }
68+
end
6369
end

0 commit comments

Comments
 (0)