git - git 分支名称中的 Powershell 和德语变音符号

标签 git powershell batch-file encoding

我编写了一个批处理文件,它使用 powershell 命令删除所有本地 git 分支,但要保留的分支除外。如果分支名称中使用了德语变音,则不起作用。

Switched to branch 'master'

Your branch is up-to-date with 'origin/master'.

Deleted branch DEV_API_StartenDesWorkers (was 61bec6d883b).

error: branch 'DEV_Üersicht_Drucken' not found.

error: branch 'test_pr├�fung' not found.


正确的名称是 DEV_Übersicht_druckentest_prüfung .
我怎样才能实现删除这些分支?
这是脚本:
@echo off
set KEEP=%1
IF [%KEEP%] == [] (goto eof)

git checkout %KEEP%

powershell "git branch -D @(git branch | select-string -NotMatch %KEEP% | ForEach-Object {$_.Line.Trim() })"

:eof

最佳答案

Disclaimer: I'm by no means an expert in this stuff - the answer below fixes the symptoms for me, but your mileage may vary. Someone else with deeper knowledge of Windows codepages and the like might be able to give a better answer...



从我读到的内容来看,问题的核心是 git 将其输出写入 utf8 中,正如@lorek 和 @LeGEC 在评论中所指出的那样,但它被命令提示符使用的 Windows 代码页所破坏。

无论是否使用 PowerShell,您都可以重现该行为:
c:\repo> git status
On branch test_prüfung
nothing to commit, working tree clean

c:\repo> git branch
* test_pr<C3><BC>fung

c:\repo> git branch | more
* test_pr├╝fung

c:\repo> powershell "$x = git branch; write-host $x"
* test_pr├╝fung

c:\repo> powershell "git branch -D @(git branch | select-string -NotMatch master | ForEach-Object {$_.Line.Trim() })"
error: branch '* test_pr├╝fung' not found.

发生的事情是 git 将其输出编码为 utf8 字节,然后 shell 使用不同的编码对其进行解码 - 如下所示:
$branch = "test_prüfung";
$utf8 = [System.Text.Encoding]::Utf8.GetBytes($branch);
$mangled = [System.Text.Encoding]::GetEncoding(437).GetString($utf8);
write-host $mangled

输出:
test_pr├╝fung

就我而言,神奇的“编码 437”是通过调用 chcp 确定的。获取 shell 的当前代码页:
C:\> chcp
Active code page: 437

documentation for chcp告诉我 437 是 United States 的代码页.

对我来说似乎可以解决问题的是使用 codepage 65001 (即UTF8)然后你得到:
C:\repo> chcp 65001
Active code page: 65001

c:\repo> powershell "$x = git branch; write-host $x"
* test_prüfung

这现在也可以正常工作:
c:\repo> powershell "git branch -D @(git branch | select-string -NotMatch master | ForEach-Object {$_.Line.Trim() })"
Deleted branch test_prüfung (was 1e9bc02).

希望这会有所帮助...

关于git - git 分支名称中的 Powershell 和德语变音符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58948011/

相关文章:

powershell - Powershell v .bat Call在Soundplayer上有区别吗?

Git 似乎不想保留对 origin/master 的本地引用

php - 如何在我的工作流程中使用 Git

git pull 必须被调用两次——获取后停止,然后只执行 merge

powershell - 参数,如果存在开关,则不允许使用其他参数

regex - 使用 powershell 捕获数组中的正则表达式匹配

powershell - 从AD获取SamAccountName

batch-file - xp批处理文件中的行长度限制?

java - 使用 Netbeans 的多个本地和远程 git 存储库

powershell - 如何查询某些关键字的多个文本文件并以文本形式输出结果?