Skip to content

Instantly share code, notes, and snippets.

@eager
Created July 23, 2011 00:54
Show Gist options
  • Save eager/1100788 to your computer and use it in GitHub Desktop.
Save eager/1100788 to your computer and use it in GitHub Desktop.
Toggle git proxies on and off
#!/usr/bin/env ruby -w
require 'fileutils'
module Git
class Setting
attr_reader :key
attr_reader :value
attr_reader :text
def initialize string
@key = nil
@value = nil
@is_commented = false
@text = nil
if string[0] == ?#
@is_commented = true
@text = string[1..-1]
else
@text = string
end
if @text =~ /=/
@key, @value = @text.split("=")
@key.strip!
@value.strip!
end
end
def comment!
@is_commented = true
end
def uncomment!
@is_commented = false
end
def commented?
@is_commented
end
def serialize
# Indent settings below group headings
s = " "
if @is_commented
s = "# "
end
if @key and @value
s << @key << " = " << @value
else
s << @text
end
s
end
end
class SettingGroup
attr_reader :name
def initialize(name)
@name = name
@configs = []
end
def <<(obj)
@configs << obj
end
def [](key)
@configs.select do |config|
config.key == key
end.first
end
def serialize
(["[#{@name}]"] << @configs.map do |config|
config.serialize
end).join("\n")
end
end
class GlobalConfigFile
DEFAULT_PATH = "#{ENV['HOME']}/.gitconfig"
def initialize(path = DEFAULT_PATH)
@groups = []
group = nil
File.foreach(path) do |line|
line.strip!
if line =~ /\S/
if line =~ /^\[(.*)\]$/
group = SettingGroup.new($1)
@groups << group
else
group << Setting.new(line)
end
end
end
end
def [](group_name)
# support config["group.setting"] syntax
if group_name =~ /(.*)\.(.*)/
if self [$1]
return self[$1][$2]
else
return nil
end
end
@groups.select do |group|
group.name == group_name
end.first
end
def save!
write_path = DEFAULT_PATH + ".#{Time.now.to_i}"
File.open(write_path, "w") do |file|
file << serialize
end
FileUtils.mv DEFAULT_PATH, DEFAULT_PATH + ".old"
FileUtils.mv write_path, DEFAULT_PATH
end
def serialize
@groups.map do |group|
group.serialize
end.join("\n")
end
end
end
proxy_settings = [
"http.proxy",
"https.proxy",
"core.gitproxy"
]
config_file = Git::GlobalConfigFile.new
# TODO make this more robust if http.proxy isn't set
method = config_file[proxy_settings.first].commented? ? "uncomment!" : "comment!"
proxy_settings.each do |setting|
config_file[setting].send(method) if config_file[setting]
end
config_file.save!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment