Skip to content

Commit c8a77db

Browse files
committed
Fix Git::Base#status on an empty repo
1 parent 712fdad commit c8a77db

File tree

4 files changed

+49
-3
lines changed

4 files changed

+49
-3
lines changed

lib/git/lib.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -707,6 +707,19 @@ def rm(path = '.', opts = {})
707707
command('rm', *arr_opts)
708708
end
709709

710+
# Returns true if the repository is empty (meaning it has no commits)
711+
#
712+
# @return [Boolean]
713+
#
714+
def empty?
715+
command('rev-parse', '--verify', 'HEAD')
716+
false
717+
rescue Git::FailedError => e
718+
raise unless e.result.status.exitstatus == 128 &&
719+
e.result.stderr == 'fatal: Needed a single revision'
720+
true
721+
end
722+
710723
# Takes the commit message with the options and executes the commit command
711724
#
712725
# accepts options:

lib/git/status.rb

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -183,9 +183,11 @@ def fetch_modified
183183
end
184184

185185
def fetch_added
186-
# find added but not committed - new files
187-
@base.lib.diff_index('HEAD').each do |path, data|
188-
@files[path] ? @files[path].merge!(data) : @files[path] = data
186+
unless @base.lib.empty?
187+
# find added but not committed - new files
188+
@base.lib.diff_index('HEAD').each do |path, data|
189+
@files[path] ? @files[path].merge!(data) : @files[path] = data
190+
end
189191
end
190192
end
191193
end

tests/units/test_lib.rb

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -318,4 +318,25 @@ def test_compare_version_to
318318
assert lib.compare_version_to(2, 43, 0) == -1
319319
assert lib.compare_version_to(3, 0, 0) == -1
320320
end
321+
322+
def test_empty_when_not_empty
323+
in_temp_dir do |path|
324+
`git init`
325+
`touch file1`
326+
`git add file1`
327+
`git commit -m "my commit message"`
328+
329+
git = Git.open('.')
330+
assert_false(git.lib.empty?)
331+
end
332+
end
333+
334+
def test_empty_when_empty
335+
in_temp_dir do |path|
336+
`git init`
337+
338+
git = Git.open('.')
339+
assert_true(git.lib.empty?)
340+
end
341+
end
321342
end

tests/units/test_status.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,16 @@ def test_status_pretty
2525
end
2626
end
2727

28+
def test_on_empty_repo
29+
in_temp_dir do |path|
30+
`git init`
31+
git = Git.open('.')
32+
assert_nothing_raised do
33+
git.status
34+
end
35+
end
36+
end
37+
2838
def test_dot_files_status
2939
in_temp_dir do |path|
3040
git = Git.clone(@wdir, 'test_dot_files_status')

0 commit comments

Comments
 (0)