Commit Diff


commit - 939d3016601d8c21e69a605f10838024335f3b1a
commit + 04a87797cb37c4787fdc83040ba75f0ddd60e46d
blob - 8a971703968041dd421027fa38cfe23a737b0dee
blob + 6bf274adf88e73b93de4344f929dd503dc20aa24
--- lib/patch.c
+++ lib/patch.c
@@ -417,15 +417,18 @@ locate_hunk(FILE *orig, struct got_patch_hunk *h, off_
 	int mangled = 0, match_lineno = -1;
 
 	for (;;) {
+		(*lineno)++;
 		linelen = getline(&line, &linesize, orig);
 		if (linelen == -1) {
 			if (ferror(orig))
 				err = got_error_from_errno("getline");
-			else if (match == -1)
+			/* An EOF is fine iff the target file is empty. */
+			if (feof(orig) && match == -1 && h->old_lines != 0)
 				err = got_error(GOT_ERR_HUNK_FAILED);
+			match = 0;
+			match_lineno = (*lineno)-1;
 			break;
 		}
-		(*lineno)++;
 
 		if ((mode == ' ' && lines_eq(l, line, linelen, &mangled)) ||
 		    (mode == '-' && lines_eq(l, line, linelen, &mangled)) ||
blob - 705adb527c252d6e5694bcd07fc8aa74e35632de
blob + 48cb8593b6e8b312d7e33d3d1f606ab4ae17d423
--- regress/cmdline/patch.sh
+++ regress/cmdline/patch.sh
@@ -801,8 +801,43 @@ EOF
 M  numbers
 @@ -47,7 +47,7 @@ applied with offset -10
 @@ -87,7 +87,7 @@ applied with offset 10
+EOF
+
+	cmp -s $testroot/stdout.expected $testroot/stdout
+	ret=$?
+	if [ $ret -ne 0 ]; then
+		diff -u $testroot/stdout.expected $testroot/stdout
+	fi
+	test_done $testroot $ret
+}
+
+test_patch_empty_file() {
+	local testroot=`test_init patch_empty_file`
+
+	got checkout $testroot/repo $testroot/wt > /dev/null
+	ret=$?
+	if [ $ret -ne 0 ]; then
+		test_done $testroot $ret
+		return 1
+	fi
+
+	echo -n > $testroot/wt/alpha
+	(cd "$testroot/wt" && got commit -m 'edit alpha' alpha) >/dev/null
+	cat <<EOF >$testroot/wt/patch
+--- alpha
++++ alpha
+@@ -0,0 +1 @@
++alpha
 EOF
 
+	(cd $testroot/wt && got patch patch) > $testroot/stdout
+	ret=$?
+	if [ $ret -ne 0 ]; then
+		test_done $testroot $ret
+		return 1
+	fi
+
+	echo 'M  alpha' > $testroot/stdout.expected
 	cmp -s $testroot/stdout.expected $testroot/stdout
 	ret=$?
 	if [ $ret -ne 0 ]; then
@@ -2052,6 +2087,7 @@ run_test test_patch_nop
 run_test test_patch_preserve_perm
 run_test test_patch_create_dirs
 run_test test_patch_with_offset
+run_test test_patch_empty_file
 run_test test_patch_prefer_new_path
 run_test test_patch_no_newline
 run_test test_patch_strip