以编程方式(而非手动方式)查找Windows系统上Git的安装路径 [英] Programmatically (not manually) finding the path where Git is installed on a Windows system

查看:73
本文介绍了以编程方式(而非手动方式)查找Windows系统上Git的安装路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个小的构建帮助器工具,该工具将读取当前Git工作目录的某些属性,例如最后的提交哈希,是否有已修改的文件等等.我发现使用已安装的Git二进制文件比读取带有未知格式压缩文件的.git目录要容易得多.但是我的工具必须尽可能地便携.它用于.NET应用程序,因此唯一的要求应该是.NET 2.0或更高版本.

I'd like to write a small build helper tool that shall read some properties of the current Git working directory, like the last commit hash, whether there's modified files and so on. I found that it is easier to use the installed Git binaries instead of reading the .git directory with its compressed files in an unknown format. But my tools must be as portable as possible. It's intended for .NET applications, so the only requirement should be .NET 2.0 or newer.

现在如何找到Git的安装路径?如果用户刚刚通过Git安装程序单击,则使用默认值.但这可能有所不同.当我在git/bin中看到所有程序文件时,我真的不希望它出现在我的%PATH%中(其他类似TortoiseGit的工具似乎也不需要).我没有在注册表中找到任何路径线索.

Now how can I find the path where Git is installed? There's a default one that is used if the user has just clicked through the Git installer. But it may be different. And when I see all the programme files in git/bin, I really don't want that to be in my %PATH% (which other tools like TortoiseGit don't seem to require, too). I haven't found any path clues in the registry.

我可以使用什么算法来查找Git,这不是完整的文件系统扫描? (我已经说过要快吗?)

What algorithm could I use to find Git, that is not a full file system scan? (Did I already say it needs to be fast?)

推荐答案

我正在使用以下批处理文件来查找Git for Windows的安装位置:

I'm using the following batch file to find out where Git for Windows has been installed:

@echo off

setlocal enabledelayedexpansion

rem Read the Git for Windows installation path from the Registry.
for %%k in (HKCU HKLM) do (
    for %%w in (\ \Wow6432Node\) do (
        for /f "skip=2 delims=: tokens=1*" %%a in ('reg query "%%k\SOFTWARE%%wMicrosoft\Windows\CurrentVersion\Uninstall\Git_is1" /v InstallLocation 2^> nul') do (
            for /f "tokens=3" %%z in ("%%a") do (
                set GIT=%%z:%%b
                echo Found Git at "!GIT!".
                goto FOUND
            )
        )
    )
)

goto NOT_FOUND

:FOUND

rem Make sure Bash is in PATH (for running scripts).
set PATH=%GIT%bin;%PATH%

rem Do something with Git ...

:NOT_FOUND

我应该直接在.NET中做类似的事情.请记住,如果您使用的是64位Windows,则必须显式检查注册表的32位分支.

I should be straight forward to do something similar in .NET. Just remember that you have to explicitly check the 32-bit branch of the Registry if you're on a 64-bit Windows.

编辑:适用于Windows 2.6.1的Git现在

Git for Windows 2.6.1 now additionally writes the CurrentVersion, InstallPath and LibexecPath values to the HKEY_LOCAL_MACHINE\Software\GitForWindows key.

这篇关于以编程方式(而非手动方式)查找Windows系统上Git的安装路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆