Subject: [PATCH] Teach git apply to respect core.fileMode settings

From: "Chandra Pratap via GitGitGadget" <[email-masked]>
Date: Mon, 18 Dec 2023 14:09:28 +0000

From: Chandra Pratap <[email-masked]>

CC: Johannes Schindelin <[email-masked]>
Signed-off-by: Chandra Pratap <[email-masked]>
---
    apply: make git apply respect core.fileMode settings
    
    When applying a patch that adds an executable file, git apply ignores
    the core.fileMode setting (core.fileMode in git config specifies whether
    the executable bit on files in the working tree
    should be honored or not) resulting in warnings like:
    
    warning: script.sh has type 100644, expected 100755
    
    even when core.fileMode is set to false, which is undesired. This is
    extra true for systems like Windows which don't rely on lsat().
    
    Fix this by inferring the correct file mode from the existing index
    entry when core.filemode is set to false. The added test case helps
    verify the change and prevents future regression.
    
    Reviewed-by: Johannes Schindelin [email-masked]
    Signed-off-by: Chandra Pratap [email-masked]

Published-As: https://github.com/gitgitgadget/git/releases/tag/pr-1620%2FChand-ra%2Fdevel-v1
Fetch-It-Via: git fetch https://github.com/gitgitgadget/git pr-1620/Chand-ra/devel-v1
Pull-Request: https://github.com/gitgitgadget/git/pull/1620

 apply.c                   |  7 +++++--
 t/t4129-apply-samemode.sh | 15 +++++++++++++++
 2 files changed, 20 insertions(+), 2 deletions(-)

diff --git a/apply.c b/apply.c
index 3d69fec836d..56790f515e0 100644
--- a/apply.c
+++ b/apply.c
@@ -3778,8 +3778,11 @@ static int check_preimage(struct apply_state *state,
 		return error_errno("%s", old_name);
 	}
 
-	if (!state->cached && !previous)
-		st_mode = ce_mode_from_stat(*ce, st->st_mode);
+	if (!state->cached && !previous) {
+		if (!trust_executable_bit && patch->old_mode)
+			st_mode = patch->old_mode;
+		else st_mode = ce_mode_from_stat(*ce, st->st_mode);
+	}
 
 	if (patch->is_new < 0)
 		patch->is_new = 0;
diff --git a/t/t4129-apply-samemode.sh b/t/t4129-apply-samemode.sh
index e7a7295f1b6..95917fee128 100755
--- a/t/t4129-apply-samemode.sh
+++ b/t/t4129-apply-samemode.sh
@@ -101,4 +101,19 @@ test_expect_success POSIXPERM 'do not use core.sharedRepository for working tree
 	)
 '
 
+test_expect_success FILEMODE 'ensure git apply respects core.fileMode' '
+	test_config core.fileMode false &&
+	echo true >script.sh &&
+	git add --chmod=+x script.sh &&
+	test_tick && git commit -m "Add script" &&
+
+	echo true >>script.sh &&
+	test_tick && git commit -m "Modify script" script.sh &&
+	git format-patch -1 --stdout >patch &&
+
+	git switch -c branch HEAD^ &&
+	git apply patch 2>err &&
+	! test_grep "has type 100644, expected 100755" err
+'
+
 test_done

base-commit: 1a87c842ece327d03d08096395969aca5e0a6996
-- 
gitgitgadget