Skip to content

Instantly share code, notes, and snippets.

@havenwood
Created November 23, 2020 18:49
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 havenwood/d43aae6f4116314cbf00f9e46f340d80 to your computer and use it in GitHub Desktop.
Save havenwood/d43aae6f4116314cbf00f9e46f340d80 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# frozen_string_literal: true
require 'json'
require 'optionparser'
KEYWORDS = %i[color metadata glow_in_the_dark coats].freeze
DEFAULTS = {coats: 3, glow_in_the_dark: true}.freeze
Paint = Struct.new *KEYWORDS, keyword_init: true
paint = Paint[DEFAULTS]
options = ARGV.options do |x|
x.banner = "Usage: #{x.program_name} [options] color [metadata]"
x.version = '0.0.1'
x.accept JSON do |json|
JSON.parse json
rescue JSON::ParserError => e
raise OptionParser::InvalidArgument, e.message
end
PositiveInteger = /\A\d+(?:_\d+)*\z/
x.accept PositiveInteger, PositiveInteger, &:to_i
x.on '-m', '--metadata=JSON', JSON, 'JSON metadata'
x.on '-c', '--coats=COUNT', PositiveInteger, "Number of coats of paint (default: #{paint.coats})"
x.on '--[no-]glow_in_the_dark', "Glow in the dark paint (default: #{paint.glow_in_the_dark})"
end.freeze
options.permute! into: paint
paint.color = ARGV.shift
raise ArgumentError, "missing argument: color\n#{options.banner}" unless paint.color
paint.metadata ||= JSON.parse ARGV.shift if ARGV.any?
paint.metadata ||= JSON.parse STDIN.gets unless STDIN.tty?
paint.metadata ||= JSON.parse ENV.fetch 'METADATA' if ENV.key? 'METADATA'
paint.metadata ||= JSON.parse File.read 'metadata.json' if File.exist? 'metadata.json'
p paint
paint -v
# paint 0.0.1
paint -h
# Usage: paint [options] color [metadata]
# -m, --metadata=JSON JSON metadata
# -c, --coats=COUNT Number of coats of paint (default: 3)
# --[no-]glow_in_the_dark Glow in the dark paint (default: true)
paint
# Traceback (most recent call last):
# ./paint:34:in `<main>': missing argument: color (ArgumentError)
# Usage: paint [options] color [metadata]
paint red
# #<struct Paint color="red", metadata=nil, glow_in_the_dark=true, coats=3>
paint green -c1 --no-glow
# #<struct Paint color="green", metadata=nil, glow_in_the_dark=false, coats=1>
paint --metadata="[1,2,3]" red
# #<struct Paint color="red", metadata=[1, 2, 3], glow_in_the_dark=true, coats=3>
paint red "[1,2,3]"
# #<struct Paint color="red", metadata=[1, 2, 3], glow_in_the_dark=true, coats=3>
echo "[1,2,3]" | paint red
# #<struct Paint color="red", metadata=[1, 2, 3], glow_in_the_dark=true, coats=3>
METADATA="[1,2,3]" paint red
# #<struct Paint color="red", metadata=[1, 2, 3], glow_in_the_dark=true, coats=3>
echo "[1,2,3]" > metadata.json
paint red
# #<struct Paint color="red", metadata=[1, 2, 3], glow_in_the_dark=true, coats=3>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment