Skip to content

Instantly share code, notes, and snippets.

@namnv609
Created July 20, 2021 06: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 namnv609/9820be29719346abd2ab1ad865746270 to your computer and use it in GitHub Desktop.
Save namnv609/9820be29719346abd2ab1ad865746270 to your computer and use it in GitHub Desktop.
Simple hosts file parser

Simple hosts file parser

HostsParser.new(os: :mac).parse

Result:

{"127.0.0.1"=>
  ["localhost",
   "kubernetes.docker.internal"],
 "255.255.255.255"=>["broadcasthost"],
 "::1"=>["localhost"]}
class UnknowOSError < StandardError
def initialize msg
super(msg)
end
end
class HostsParser
OPERATING_SYSTEMS = %i(mac linux win)
def initialize os:, keep_comment: false
@os = os.downcase.to_sym
raise ::UnknowOSError.new "Unknow OS #{@os}. OS list are: #{OPERATING_SYSTEMS}" unless
OPERATING_SYSTEMS.include?(@os)
@keep_comment = keep_comment
end
def parse
hosts_content_by_os
end
private
attr_reader :os, :keep_comment
def hosts_content_by_os raw_content: false
hosts_file_path = case os
when :mac, :linux
"/etc/hosts"
when :win
"C:\\Windows\\System32\\etc\\drivers\\hosts"
end
hosts_content = ::File.read(hosts_file_path)
return hosts_content if raw_content
hosts_content.split("\n").each_with_object({}) do |line, obj|
line = line.strip
if (line.present? && line !~ /^\#/ && line != "\n")
line = line.split(/\s+/)
hosts_ip = line.shift
(obj[hosts_ip] ||= []).concat(line)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment