Sha256: 6030b85ef04f44deee34beced98d020dd27a493db9f902c5c9d08b9a4939b89b

Contents?: true

Size: 1.83 KB

Versions: 1

Compression:

Stored size: 1.83 KB

Contents

#!/usr/bin/env ruby

require "rubygems"
require "thor"
require "hosts"

class HostsCLI < Thor
  
  desc "list [SEARCH]", "List host names"
  def list(search="")
    Hosts.read
    results = Hosts.search(search)
    width_col_1 = results.collect{|entry| entry[0].size}.max
    width_col_2 = results.collect{|entry| entry[1].size}.max
    results.each do |entry|
      puts "%s%s %s%s %s" % [
        entry[0], " "*(width_col_1-entry[0].size),
        entry[1], " "*(width_col_2-entry[1].size),
        (entry[2] ? "" : "(locked)")]
    end
  end
  
  desc "add HOSTNAME [ADDRESS]", "Add a hostname"
  def add(hostname, address="127.0.0.1")
    Hosts.read
    if Hosts.exists?(hostname, address)
      puts "There already is an entry for this hostname and address!"
      exit(0)
    end
    if Hosts.editable?(hostname, address)
      Hosts.add(hostname, address) 
      Hosts.write
      puts "Added: #{address} #{hostname}"
    else
      puts "#{address} #{hostname} is locked!"
    end
  end
  
  desc "remove HOSTNAME [ADDRESS]", "Remove a hostname"
  def remove(hostname, address=nil)
    Hosts.read
    if Hosts.hostname(hostname).size > 1 and address.nil?
      puts "Please specify an address!"
      list(hostname)
      exit(1)
    end
    address ||= "127.0.0.1"
    unless Hosts.exists?(hostname, address)
      puts "There is no entry for this hostname and address!"
      exit(0)
    end
    if Hosts.editable?(hostname, address)
      Hosts.remove(hostname, address) 
      Hosts.write
      puts "Removed: #{address} #{hostname}"
    else
      puts "#{address} #{hostname} is locked!"
    end
  end
  
  alias_method :l, :list
  alias_method :a, :add
  alias_method :r, :remove
  alias_method :h, :help
  
end

begin
  File.open('/etc/hosts', 'a+') {|f|}
rescue
  system "sudo #{$0} #{ARGV.join(' ')}"
  exit(0)
end

ARGV << "list" if ARGV.empty?
HostsCLI.start

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
simonmenke-hosts-0.0.5 bin/hosts