Skip to content

Commit ba9a8b8

Browse files
fix: suppress CRLF warnings in auto-commit.ps1 (#2258)
* fix: suppress CRLF warnings in auto-commit.ps1 (#2253) Replace 2> with 2>&1 redirection and assignment to properly suppress stderr output including CRLF warnings on Windows. Exit code logic preserved for change detection. Fixes #2253 * fix: use SilentlyContinue for CRLF stderr handling, add tests The 2>&1 approach still raises terminating errors under $ErrorActionPreference='Stop'. Instead, temporarily set SilentlyContinue around all native git calls that may emit CRLF warnings to stderr (rev-parse, diff, ls-files, add, commit). Adds 5 pytest tests (TestAutoCommitPowerShellCRLF) that set core.autocrlf=true with LF-ending files. On Windows runners this triggers actual CRLF warnings; on other platforms the tests pass trivially. Fixes #2253 * refactor: address Copilot review feedback - Use 'Continue' instead of 'SilentlyContinue' so error output is still captured in $out for diagnostics on real git failures. - Wrap all three EAP save/restore blocks in try/finally to guarantee restoration even on unexpected exceptions. - Fix CRLF test to commit a tracked LF file first, then modify it, so git diff --quiet HEAD actually inspects the tracked change and triggers the CRLF warning on Windows. * test: assert CRLF warning fires on Windows On Windows, probe git diff stderr before running the script to verify the test setup actually produces the expected CRLF warning. This makes the regression test deterministic on the Windows runner. On non-Windows the probe is skipped (warnings don't fire there). --------- Co-authored-by: Manfred Riem <15701806+mnriem@users.noreply.github.com>
1 parent dedcae7 commit ba9a8b8

File tree

2 files changed

+176
-5
lines changed

2 files changed

+176
-5
lines changed

extensions/git/scripts/powershell/auto-commit.ps1

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -36,10 +36,17 @@ if (-not (Get-Command git -ErrorAction SilentlyContinue)) {
3636
exit 0
3737
}
3838

39+
# Temporarily relax ErrorActionPreference so git stderr warnings
40+
# (e.g. CRLF notices on Windows) do not become terminating errors.
41+
$savedEAP = $ErrorActionPreference
42+
$ErrorActionPreference = 'Continue'
3943
try {
4044
git rev-parse --is-inside-work-tree 2>$null | Out-Null
41-
if ($LASTEXITCODE -ne 0) { throw "not a repo" }
42-
} catch {
45+
$isRepo = $LASTEXITCODE -eq 0
46+
} finally {
47+
$ErrorActionPreference = $savedEAP
48+
}
49+
if (-not $isRepo) {
4350
Write-Warning "[specify] Warning: Not a Git repository; skipped auto-commit"
4451
exit 0
4552
}
@@ -117,9 +124,16 @@ if (-not $enabled) {
117124
}
118125

119126
# Check if there are changes to commit
120-
$diffHead = git diff --quiet HEAD 2>$null; $d1 = $LASTEXITCODE
121-
$diffCached = git diff --cached --quiet 2>$null; $d2 = $LASTEXITCODE
122-
$untracked = git ls-files --others --exclude-standard 2>$null
127+
# Relax ErrorActionPreference so CRLF warnings on stderr do not terminate.
128+
$savedEAP = $ErrorActionPreference
129+
$ErrorActionPreference = 'Continue'
130+
try {
131+
git diff --quiet HEAD 2>$null; $d1 = $LASTEXITCODE
132+
git diff --cached --quiet 2>$null; $d2 = $LASTEXITCODE
133+
$untracked = git ls-files --others --exclude-standard 2>$null
134+
} finally {
135+
$ErrorActionPreference = $savedEAP
136+
}
123137

124138
if ($d1 -eq 0 -and $d2 -eq 0 -and -not $untracked) {
125139
Write-Host "[specify] No changes to commit after $EventName" -ForegroundColor DarkGray
@@ -136,6 +150,10 @@ if (-not $commitMsg) {
136150
}
137151

138152
# Stage and commit
153+
# Relax ErrorActionPreference so CRLF warnings on stderr do not terminate,
154+
# while still allowing redirected error output to be captured for diagnostics.
155+
$savedEAP = $ErrorActionPreference
156+
$ErrorActionPreference = 'Continue'
139157
try {
140158
$out = git add . 2>&1 | Out-String
141159
if ($LASTEXITCODE -ne 0) { throw "git add failed: $out" }
@@ -144,6 +162,8 @@ try {
144162
} catch {
145163
Write-Warning "[specify] Error: $_"
146164
exit 1
165+
} finally {
166+
$ErrorActionPreference = $savedEAP
147167
}
148168

149169
Write-Host "[OK] Changes committed $phase $commandName"

tests/extensions/git/test_git_extension.py

Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
import re
1515
import shutil
1616
import subprocess
17+
import sys
1718
from pathlib import Path
1819

1920
import pytest
@@ -585,6 +586,156 @@ def test_success_message_no_unicode_checkmark(self, tmp_path: Path):
585586
assert "\u2713" not in result.stdout, "Must not use Unicode checkmark"
586587

587588

589+
# ── auto-commit.ps1 CRLF warning tests (issue #2253) ────────────────────────
590+
591+
592+
@pytest.mark.skipif(not HAS_PWSH, reason="pwsh not available")
593+
class TestAutoCommitPowerShellCRLF:
594+
"""Tests for CRLF warning handling in auto-commit.ps1 (issue #2253).
595+
596+
On Windows, git emits CRLF warnings to stderr when core.autocrlf=true
597+
and files use LF line endings. PowerShell's $ErrorActionPreference='Stop'
598+
converts stderr output into terminating errors, crashing the script.
599+
600+
These tests use core.autocrlf=true + explicit LF-ending files. On Windows
601+
the CRLF warnings fire and exercise the fix; on other platforms the tests
602+
still run (they just won't produce stderr warnings, so they pass trivially).
603+
"""
604+
605+
# -- positive tests (fix works) ----------------------------------------
606+
607+
def test_commit_succeeds_with_autocrlf(self, tmp_path: Path):
608+
"""auto-commit.ps1 creates a commit when core.autocrlf=true (CRLF
609+
warnings on stderr must not crash the script)."""
610+
project = _setup_project(tmp_path)
611+
_write_config(project, (
612+
"auto_commit:\n"
613+
" default: false\n"
614+
" after_specify:\n"
615+
" enabled: true\n"
616+
' message: "crlf commit"\n'
617+
))
618+
# Create and commit a tracked LF-ending file first so the script's
619+
# `git diff --quiet HEAD` checks inspect a tracked modification.
620+
tracked = project / "crlf-test.txt"
621+
tracked.write_bytes(b"line one\nline two\nline three\n")
622+
subprocess.run(["git", "add", "crlf-test.txt"], cwd=project, check=True)
623+
subprocess.run(
624+
["git", "commit", "-m", "seed tracked file"],
625+
cwd=project, check=True, env={**os.environ, **_GIT_ENV},
626+
)
627+
subprocess.run(
628+
["git", "config", "core.autocrlf", "true"],
629+
cwd=project, check=True,
630+
)
631+
# Modify the tracked file with explicit LF endings to trigger the
632+
# CRLF warning during diff/status checks on Windows.
633+
tracked.write_bytes(b"line one\nline two changed\nline three\n")
634+
635+
# On Windows, verify the test setup actually produces a CRLF warning.
636+
if sys.platform == "win32":
637+
probe = subprocess.run(
638+
["git", "diff", "--quiet", "HEAD"],
639+
cwd=project, capture_output=True, text=True,
640+
)
641+
assert "LF will be replaced by CRLF" in probe.stderr, (
642+
"Expected CRLF warning from git on Windows; test setup may be wrong"
643+
)
644+
645+
result = _run_pwsh("auto-commit.ps1", project, "after_specify")
646+
647+
assert result.returncode == 0, (
648+
f"Script crashed (likely CRLF stderr); stderr:\n{result.stderr}"
649+
)
650+
assert "[OK] Changes committed" in result.stdout
651+
652+
log = subprocess.run(
653+
["git", "log", "--oneline", "-1"],
654+
cwd=project, capture_output=True, text=True,
655+
)
656+
assert "crlf commit" in log.stdout
657+
658+
def test_custom_message_not_corrupted_by_crlf(self, tmp_path: Path):
659+
"""Commit message is the configured value, not a CRLF warning."""
660+
project = _setup_project(tmp_path)
661+
_write_config(project, (
662+
"auto_commit:\n"
663+
" default: false\n"
664+
" after_plan:\n"
665+
" enabled: true\n"
666+
' message: "[Project] Plan done"\n'
667+
))
668+
subprocess.run(
669+
["git", "config", "core.autocrlf", "true"],
670+
cwd=project, check=True,
671+
)
672+
(project / "plan.txt").write_bytes(b"plan\ncontent\n")
673+
674+
result = _run_pwsh("auto-commit.ps1", project, "after_plan")
675+
assert result.returncode == 0
676+
677+
log = subprocess.run(
678+
["git", "log", "--format=%s", "-1"],
679+
cwd=project, capture_output=True, text=True,
680+
)
681+
assert "[Project] Plan done" in log.stdout.strip()
682+
683+
def test_no_changes_still_skips_with_autocrlf(self, tmp_path: Path):
684+
"""Script correctly detects 'no changes' even with core.autocrlf=true."""
685+
project = _setup_project(tmp_path)
686+
_write_config(project, (
687+
"auto_commit:\n"
688+
" default: false\n"
689+
" after_specify:\n"
690+
" enabled: true\n"
691+
))
692+
subprocess.run(
693+
["git", "config", "core.autocrlf", "true"],
694+
cwd=project, check=True,
695+
)
696+
# Stage and commit everything so the working tree is clean.
697+
subprocess.run(["git", "add", "."], cwd=project, check=True,
698+
env={**os.environ, **_GIT_ENV})
699+
subprocess.run(["git", "commit", "-m", "setup", "-q"], cwd=project,
700+
check=True, env={**os.environ, **_GIT_ENV})
701+
702+
result = _run_pwsh("auto-commit.ps1", project, "after_specify")
703+
assert result.returncode == 0
704+
assert "[OK]" not in result.stdout, "Should not have committed anything"
705+
706+
# -- negative tests (real errors still surface) ------------------------
707+
708+
def test_not_a_repo_still_detected_with_autocrlf(self, tmp_path: Path):
709+
"""Script still exits gracefully when not in a git repo, even though
710+
ErrorActionPreference is relaxed around the rev-parse call."""
711+
project = _setup_project(tmp_path, git=False)
712+
_write_config(project, "auto_commit:\n default: true\n")
713+
714+
result = _run_pwsh("auto-commit.ps1", project, "after_specify")
715+
assert result.returncode == 0
716+
combined = result.stdout + result.stderr
717+
assert "not a git repository" in combined.lower() or "warning" in combined.lower()
718+
719+
def test_missing_config_still_exits_cleanly_with_autocrlf(self, tmp_path: Path):
720+
"""Script exits 0 when git-config.yml is absent (no over-suppression)."""
721+
project = _setup_project(tmp_path)
722+
subprocess.run(
723+
["git", "config", "core.autocrlf", "true"],
724+
cwd=project, check=True,
725+
)
726+
config = project / ".specify" / "extensions" / "git" / "git-config.yml"
727+
config.unlink(missing_ok=True)
728+
729+
result = _run_pwsh("auto-commit.ps1", project, "after_specify")
730+
assert result.returncode == 0
731+
# Should not have committed anything — config file missing means disabled.
732+
log = subprocess.run(
733+
["git", "log", "--oneline"],
734+
cwd=project, capture_output=True, text=True,
735+
)
736+
assert log.stdout.strip().count("\n") == 0 # only the seed commit
737+
738+
588739
# ── git-common.sh Tests ──────────────────────────────────────────────────────
589740

590741

0 commit comments

Comments
 (0)