Skip to content

Instantly share code, notes, and snippets.

@billdueber
Created February 5, 2016 15:25
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 billdueber/506b2eaad9005283e9be to your computer and use it in GitHub Desktop.
Save billdueber/506b2eaad9005283e9be to your computer and use it in GitHub Desktop.
Modification to taghosts to list available tags
#!/usr/bin/env ruby
require 'optparse'
ACTIVE_SERVERS = '/l/local/active-servers'
def alltags
alltags = []
File.open(ACTIVE_SERVERS).each do |line|
tokens = line.split(/\s+/)
alltags += tokens.drop(1)
end
puts alltags.sort.uniq.join("\n")
exit
end
# extend Array with methods to compare to other arrays
class Array
# returns true if this array contains all the elements in other_array
def contains_all(other_array)
self & other_array == other_array
end
# returns true if this array contains any of the elements in other_array
def contains_any(other_array)
!(self & other_array).empty?
end
end
def handle_alltags_option(opts)
opts.on('-a', '--all-tags', 'show all tags') do
alltags
end
opts.on('-l', '--list-tags', 'list available tags') do
list_tags
exit
end
end
def list_tags
taglist = File.open(ACTIVE_SERVERS).map{|x| x.split(/\s+/)[1..-1]}.flatten.uniq.sort
quartertags = taglist.size / 4
columns = []
columns << taglist.slice!(0..quartertags) until taglist.empty?
puts "\nAll available tags:"
columns.map(&:size).max.times do |i|
puts '%-15s %-15s %-15s %-15s' % columns.map{|x| x[i]}
end
end
def handle_prohibited_tags_option(opts, prohibited_tags)
opts.on('-v', '--invert-match TAG', 'select hosts with tag') do |tag|
prohibited_tags.push(tag)
end
end
def parse_options
prohibited_tags = []
OptionParser.new do |opts|
opts.banner = 'Usage: taghosts [tag1 tag2 ...] [-v notag1 notag2 ...]'
handle_prohibited_tags_option(opts, prohibited_tags)
handle_alltags_option(opts)
end.parse!
# remaining arguments are required tags
[ARGV, prohibited_tags]
end
def servers_with_tags(required_tags, prohibited_tags)
required_tags.sort!
prohibited_tags.sort!
servers = []
File.foreach(ACTIVE_SERVERS) do |line|
tags = line.split(/\s+/)
host = tags.shift
tags.sort!
if tags.contains_all(required_tags) && !tags.contains_any(prohibited_tags)
servers.push(host)
end
end
servers
end
puts servers_with_tags(*parse_options) if __FILE__ == $PROGRAM_NAME
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment