难题: git 的 Unicode 输出在 PowerShell 中可以显示,却不能保存到变量,是怎么回事?

2021-08-24 06:28:53 +08:00
 AndyAO

为了解决 git 的 Unicode 显示问题,已经更改了能够想到的配置和环境变量(具体见文末)。

直接显示是没有问题的,但是如果将流传入管道中或保存到变量里面,编码就会出错。

# 错误流,没有捕捉直接显示则不会有任何问题;标准输出流被传入管道之后,就会产生错误,将“①”显示为“鈶?”
PS>git rev-parse '①' | Out-String
fatal: ambiguous argument '①': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'
鈶?

还有个奇怪的现象:如果用的是 vscode 里面的 PowerShell Integrated Console,则一切正常。

到底是哪里出了问题?


配置和环境变量

[gui]
	encoding = utf-8
	recentrepo = D:/GitRepository/PowerShell
[i18n "commit"]
	encoding = utf-8
[i18n]
	logoutputencoding = utf-8

LESSCHARSET = "utf-8"

620 次点击
所在节点    问与答
3 条回复
AndyAO
2021-08-24 06:43:42 +08:00
补充版本信息

* * *

PS>$PSVersionTable

Name Value
---- -----
PSVersion 7.1.3
PSEdition Core
GitCommitId 7.1.3
OS Microsoft Windows 10.0.18363
Platform Win32NT
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
WSManStackVersion 3.0

PS>git --version
git version 2.29.2.windows.2
AndyAO
2021-08-24 09:21:38 +08:00
原因是如果直接使用 git 命令,那么输出的内容其实并不经过 PowerShell,而是直接传递到终端。

但如果使用任何其他的 PowerShell 机制,那么则会处理。

PowerShell 会对输入的内容的编码进行判断,如果判断失败了就会出现那种情况。

可以通过更改 Console 类的属性来指定输入输出编码。

[Console]::OutputEncoding = [Console]::InputEncoding = $OutputEncoding = [Text.UTF8Encoding]::new($false)

具体效果如下 ↓


PS>git rev-parse '①' | Out-String
fatal: ambiguous argument '①': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'



不得不说当前 PowerShell 在字符串编码方面做得还不够好。

* * *

上述内容来自 reddit

https://www.reddit.com/r/PowerShell/comments/paauvs/problem_the_unicode_output_of_git_can_be/ha3gnma?utm_source=share&utm_medium=web2x&context=3
geelaw
2021-09-09 08:37:31 +08:00
因为当命令行是原生命令时,PowerShell 直接让原生命令写入它自己的 stdin/stdout/stderr 。
当原生命令是表达式的一部分时,例如赋值给变量,PowerShell 会开启一系列糟糕的操作,见 https://geelaw.blog/entries/powershell-use-rawpipeline/

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/797588

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX