Git to auto-detect the system proxy settings

2019-06-27 10:03发布

问题:

I am often changing places that have different proxy settings, or simply changing from WiFi to cable connection with a different proxy.

As I am using OsX, it is easy to switch from a network configuration to another. But git has its own setting in the .gitconfig file and I am tired modifying that file every time.

Is there a way to pass the proxy (maybe from a system variable?) to the .gitconfig file, or have a setting such as auto-detect, system-proxy or similar?

回答1:

I'm in the same situation, it's a pity that Git does not use the system proxy settings on OS X. To make this easier, I've created a couple of Bash functions that allow me to enable/disable the proxy configuration for tools like ssh, npm and the proxy environment variables.

You can see the code (as part of my Bash-it fork) here: https://github.com/nwinkler/bash-it/blob/master/plugins/available/proxy.plugin.bash

Here's how it works:

  • My bash profile contains variables like BASH_IT_HTTP_PROXY.
  • I have defined some functions including enable_proxy and disable_proxy that set or unset the environment variables when called. In addition to that, they update my ~/.npmrc file and some other locations.

When working from the office (where I have to use a proxy), I simply call enable_proxy, and when working from home, I call disable_proxy.

A similar set of functionality could be implemented as single scripts instead of functions, but the Bash-it framework has a really nice way of defining things like this. It works really well, and I never have to fiddle with environment variables manually.



回答2:

According to the git-config(1) man page, git already uses the standard http_proxy environment variable by default:

   http.proxy
       Override the HTTP proxy, normally configured using the http_proxy, https_proxy, and all_proxy environment variables (see
       curl(1)). This can be overridden on a per-remote basis; see remote.<name>.proxy

So if you set http_proxy appropriately in your environment, you should be all set.

Update (for lingceng)

You can verify that git respects the http_proxy environment variable like this:

$ export http_proxy=http://proxy.example.com:3128
$ export GIT_CURL_VERBOSE=1
$ git clone http://git.kernel.org/pub/scm/boot/syslinux/syslinux.git
Cloning into 'syslinux'...
* Couldn't find host git.kernel.org in the .netrc file; using defaults
*   Trying 10.11.5.35...
* Connected to proxy.example.com (10.11.5.35) port 3128 (#0)
> GET http://git.kernel.org/pub/scm/boot/syslinux/syslinux.git/info/refs?service=git-upload-pack HTTP/1.1

You can see there in the penultimate line where git connects to the proxy rather than directly connecting to git.kernel.org.



标签: git proxy