Module: Hosts::Lib::Commands

Defined in:
lib/Hosts/Lib/autoload.rb,
lib/Hosts/Lib/Commands/Rm.rb,
lib/Hosts/Lib/Commands/Add.rb,
lib/Hosts/Lib/Commands/Help.rb,
lib/Hosts/Lib/Commands/List.rb,
lib/Hosts/Lib/Commands/Flush.rb,
lib/Hosts/Lib/Commands/Version.rb

Constant Summary collapse

Rm =
SubCommand.new(
  'rm', # Name of the sub command
  "Remove entry. Removes all entries to a 'dest' if no alias is defined. Requires 'sudo'",
  options_obj
) { |options, args|
  # Must be right number of arguments
  unless (args.length > 0 && args.length <= 2)
    puts options_obj
    next
  end

  hosts_file = HostsFile.new Hosts.hosts_file

  if (args[1] != nil)
    # rm alias
    hosts_file.rm_alias(args[0], args[1])
  else
    # Remove all entries
    # to 'dest' if alias
    # is not defined
    hosts_file.rm_dest_entries(args[0])
  end

  # Write changes to hosts file
  begin
    hosts_file.flush()
  rescue Errno::EACCES
    puts "Permission error: 'hosts rm' requires 'sudo'"
  end
}
Add =
SubCommand.new(
  'add', # Name of the sub command
  'Add a hosts entry. requires \'sudo\'',
  options_obj
) { |options, args|
  unless (args.length >= 2)
    puts options_obj.banner
    next
  end

  hosts_file = HostsFile.new Hosts.hosts_file

  hosts_file.add_entry(args[0], args[1])


  # Write changes to hosts file
  begin
    hosts_file.flush
    puts "Added entry: #{args[0]} => #{args[1]}"
  rescue Errno::EACCES
    puts "Permission error: 'hosts add' requires 'sudo'"
  end
}
Help =
SubCommand.new(
  'help', # Name of the command
  'Print the help message', # Description
  options_obj, # Has no options
  false
) do |_options, _args|
  Hosts.sub_commands.each do |_key, cmd|
    cmd.print_help_message
  end
end
List =
SubCommand.new(
  'list', # Name of the sub command
  'List all host entries',
  options_obj,
  false
) { |options, args|
  hosts_file = HostsFile.new Hosts.hosts_file
  hosts_entries = hosts_file.get_all_entries
  
  longest_dest_name = 0

  hosts_entries.each do |dest, hostnames|
    if (dest.length > longest_dest_name)
      longest_dest_name = dest.length
    end
  end

  hosts_entries.each do |dest, hostnames|
    hostname_f = hostnames * ", "

    print "%-#{longest_dest_name}.#{longest_dest_name}s" % dest
    print " "
    puts "<= #{hostname_f}"
  end
}
Flush =
SubCommand.new(
  'flush', # Name of the sub command
  'Flush the DNS cache',
  options_obj,
  false
) { |options, args|
  `dscacheutil -flushcache; sudo killall -HUP mDNSResponder &> /dev/null`
  puts "Flushed DNS cache"
}
Version =
SubCommand.new(
  'version', # Name of the sub command
  'Print the version',
  options_obj,
  false
) { |options, args|
  puts Hosts::VERSION
}