Skip to content

Instantly share code, notes, and snippets.

@voostindie
Created October 25, 2015 10:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save voostindie/68c7442ec51fa63ba45d to your computer and use it in GitHub Desktop.
Save voostindie/68c7442ec51fa63ba45d to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
#
# Downloads a new version of the MVPS hosts file and merges it into the local
# hosts file.
#
# Only lines starting with `0.0.0.0` are merged; all other lines are skipped.
#
# All entries from the MVPS hosts file are put between markers. If the markers
# are already present in the hosts file, everything between them is replaced
# with the contents of the MVPS hosts file.
require 'net/http'
MVPS_BEGIN = '# [[ MVPS BEGIN ]]'
MVPS_END = '# [[ MVPS END ]]'
def load_local
puts 'Loading /etc/hosts'
IO.read("/etc/hosts")
end
def load_mvps
puts 'Downloading MVPS hosts file'
Net::HTTP.get(URI('http://winhelp2002.mvps.org/hosts.txt'))
end
def merge_hosts(local, mvps)
puts 'Merging /etc/hosts with MVPS hosts file'
result = []
# Copy from local from start to `MVPS_BEGIN` (or EOF)
result << local.lines.take_while { | line | !line.start_with? MVPS_BEGIN }
result << "#{MVPS_BEGIN}\n"
# Copy from MVPS if it starts with `0.0.0.0`
mvps.lines.each { | line | result << line if line.start_with? '0.0.0.0' }
# Copy from local from `MVPS_END` to EOF (if present)
size = result.size
result << local.lines.drop_while { | line | !line.start_with? MVPS_END }
result << "#{MVPS_END}\n" if result.size == size
result
end
def write_hosts(hosts)
puts 'Writing new hosts file in /etc/hosts'
IO.write('/etc/hosts', hosts.join)
end
def reload_dns
puts 'Flushing DNS cache'
system('killall -HUP mDNSResponder')
end
write_hosts(merge_hosts(load_local, load_mvps))
reload_dns
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment