Skip to content

Instantly share code, notes, and snippets.

@bitaxis
Last active September 16, 2018 14:40
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 bitaxis/c0affd6377f02105742de7ee8998e659 to your computer and use it in GitHub Desktop.
Save bitaxis/c0affd6377f02105742de7ee8998e659 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require "optparse"
require "uuidtools"
DEFAULT_COUNT = 20
RANDOM_FUNC = -> { $options[:count].times { puts UUIDTools::UUID.random_create } }
$options = {
count: DEFAULT_COUNT,
func: RANDOM_FUNC,
namespace: UUIDTools::UUID_X500_NAMESPACE
}
OptionParser.new do |opts|
opts.banner = "Generates various UUIDs using SecureRandom and UUIDTools modules."
opts.separator "Usage:
#{opts.program_name} [options] [count]
Examples:
uuids Generates #{DEFAULT_COUNT} random UUIDs
uuids N Generates N random UUIDs
uuids -t N Generates N timestamp UUIDs
uuids -m STRING Generates MD5 hash for STRING as UUID
uuids -s STRING Generates SHA1 hash for STRING as UUID
Options:
"
opts.on("-m", "--md5 NAME", "Generate UUID using MD5 hash (version 3)") do |something|
$options[:func] = -> { puts UUIDTools::UUID.md5_create($options[:namespace], something) }
end
opts.on("-n", "--namespace name-or-uuid", "Specify DNS, OID, URL, X500 (default), or custom UUID namespace") do |something|
$options[:namespace] = case something.downcase
when "d", "dns"
UUIDTools::UUID_DNS_NAMESPACE
when "o", "oid"
UUIDTools::UUID_OID_NAMESPACE
when "u", "url"
UUIDTools::UUID_URL_NAMESPACE
when "x", "x500"
UUIDTools::UUID_X500_NAMESPACE
else
begin
UUIDTools::UUID.parse(something)
rescue ArgumentError
puts "\"#{something}\" is not a valid UUID string suitable for use as custom namespace"
exit
end
end
end
opts.on("-r", "--random [count]", "Generate some random UUIDs (default: #{DEFAULT_COUNT})") do |count|
$options[:count] = count.to_i if count
$options[:func] = RANDOM_FUNC
end
opts.on("-s", "--sha1 NAME", "Generate UUID using SHA1 hash") do |something|
$options[:func] = -> { puts UUIDTools::UUID.sha1_create($options[:namespace], something) }
end
opts.on("-t", "--timestamp [count]", "Generate some timestamp-based UUIDs (default: #{DEFAULT_COUNT})") do |count|
$options[:count] = count.to_i if count
$options[:func] = -> { $options[:count].times { puts UUIDTools::UUID.timestamp_create } }
end
end.parse!
# If we are generating random UUIDs and some argument is present, then convert it to a number, and we will then
# generate as many random UUIDs as is specified
$options[:count] = ARGV.first.to_i if !ARGV.empty? && $options[:func] == RANDOM_FUNC
# Genrate UUID(s)
$options[:func].call
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment