检测 git 是否安装的独立于平台的方式
这就是我在 ruby 中检测 git 的方法:
`which git 2>/dev/null` and $?.success?
但是,这不是跨平台的。它在非 UNIX 系统或没有 which
命令的系统上失败(尽管我不确定这些是什么)。
我需要一种方法来检测满足这些条件的 git:
- 跨平台可靠工作,即使在 Windows 上
- 也不向 $stdout 或 $stderr 输出任何内容
- 少量代码
更新: 解决方案是避免在 Windows 上完全使用 which
并将输出重定向到 NUL
。
require 'rbconfig'
void = RbConfig::CONFIG['host_os'] =~ /msdos|mswin|djgpp|mingw/ ? 'NUL' : '/dev/null'
system "git --version >>#{void} 2>&1"
system
命令在成功时返回 true,在失败时返回 false,从而避免了使用反引号时需要使用 $?.success?
的情况。
This is how I detect git in ruby:
`which git 2>/dev/null` and $?.success?
However, this is not cross-platform. It fails on non-unix systems or those without the which
command (although I'm not sure what those are).
I need a way to detect git that satisfies these conditions:
- works reliably cross-platform, even on Windows
- doesn't output anything to $stdout or $stderr
- small amount of code
Update: the solution is to avoid using which
altogether and to redirect output to NUL
on Windows.
require 'rbconfig'
void = RbConfig::CONFIG['host_os'] =~ /msdos|mswin|djgpp|mingw/ ? 'NUL' : '/dev/null'
system "git --version >>#{void} 2>&1"
The system
command returns true on success and false on failure, saving us the trip to $?.success?
which is needed when using backticks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Windows 上没有
/dev/null
这样的东西。我们在不同项目中采用的一种方法是基于
RbConfig::CONFIG['host_os']
定义NULL
然后使用它将 STDOUT 和 STDERR 重定向到它。
至于这一点,我在 我的博客
但是,如果您只想检查 git 的存在而不是位置,则无需执行以下操作,只需使用简单的系统调用并检查生成的
$?
即可足够的。希望这有帮助
There is not such thing as
/dev/null
on Windows.One approach we have been taking in different projects is define
NULL
based onRbConfig::CONFIG['host_os']
Then use that to redirect both STDOUT and STDERR to it.
As for which, I made a trivial reference on my blog
But, if you just want to check git presence and not location, no need to do which, with a simple system call and check of the resulting in
$?
will be enough.Hope this helps
这是一种解决方案,可以避免花费大量时间来检测可执行文件,并且还能够可靠地检测可执行文件所在的位置。它是
which
的替代方案。用法:
This is a solution which avoids shelling out to detect executables and is also able to reliably detect where the executable is located. It's an alternative to
which
.Usage:
也许在 JRuby 上运行并使用 JGit 可能是真正独立于平台的一个选择。
Perhaps running on JRuby and using JGit could be an option to really go platform-independent.
我想,你需要这样做:
which
I think, you will need to do this:
which