From 25908ebae46ed9771283d54415421cb711b3b237 Mon Sep 17 00:00:00 2001 From: Andrew Nordman Date: Wed, 20 Feb 2019 22:14:09 -0600 Subject: [PATCH] Improvements to dotenv CLI This replaces the odd file parsing in the Dotenv::CLI with a proper OptionParser implementation that automatically handles converting the comma-separated list into an Array and with proper flag support. This also adds --version and --help flag support to the CLI, since it's practically free with OptionParser. --- lib/dotenv/cli.rb | 53 +++++++++++++++++++++++++++++++++++++---------- 1 file changed, 42 insertions(+), 11 deletions(-) diff --git a/lib/dotenv/cli.rb b/lib/dotenv/cli.rb index 76e0225e..dbe70e69 100644 --- a/lib/dotenv/cli.rb +++ b/lib/dotenv/cli.rb @@ -1,4 +1,6 @@ require "dotenv" +require "dotenv/version" +require "optparse" module Dotenv # The CLI is a class responsible of handling all the command line interface @@ -11,26 +13,55 @@ def initialize(argv = []) end def run - filenames = parse_filenames || [] + parse_argv!(@argv) + begin - Dotenv.load!(*filenames) + Dotenv.load!(*@filenames) rescue Errno::ENOENT => e abort e.message else - exec(*argv) unless argv.empty? + exec(*@argv) unless @argv.empty? end end private - def parse_filenames - pos = argv.index("-f") - return nil unless pos - # drop the -f - argv.delete_at pos - # parse one or more comma-separated .env files - require "csv" - CSV.parse_line argv.delete_at(pos) + def parse_argv!(argv) + @filenames = [] + + OptionParser.new do |parser| + parser.banner = "Usage: dotenv [options]" + parser.separator "" + add_options(parser) + end.parse!(argv) + + @filenames + end + + def add_options(parser) + add_files_option(parser) + add_help_option(parser) + add_version_option(parser) + end + + def add_files_option(parser) + parser.on("-f FILES", Array, "List of env files to parse") do |list| + @filenames = list + end + end + + def add_help_option(parser) + parser.on("-h", "--help", "Display help") do + puts parser + exit + end + end + + def add_version_option(parser) + parser.on("-v", "--version", "Show version") do + puts "dotenv #{Dotenv::VERSION}" + exit + end end end end