Skip to content

Commit 25908eb

Browse files
author
Andrew Nordman
committed
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.
1 parent 4168b83 commit 25908eb

File tree

1 file changed

+42
-11
lines changed

1 file changed

+42
-11
lines changed

lib/dotenv/cli.rb

Lines changed: 42 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
require "dotenv"
2+
require "dotenv/version"
3+
require "optparse"
24

35
module Dotenv
46
# The CLI is a class responsible of handling all the command line interface
@@ -11,26 +13,55 @@ def initialize(argv = [])
1113
end
1214

1315
def run
14-
filenames = parse_filenames || []
16+
parse_argv!(@argv)
17+
1518
begin
16-
Dotenv.load!(*filenames)
19+
Dotenv.load!(*@filenames)
1720
rescue Errno::ENOENT => e
1821
abort e.message
1922
else
20-
exec(*argv) unless argv.empty?
23+
exec(*@argv) unless @argv.empty?
2124
end
2225
end
2326

2427
private
2528

26-
def parse_filenames
27-
pos = argv.index("-f")
28-
return nil unless pos
29-
# drop the -f
30-
argv.delete_at pos
31-
# parse one or more comma-separated .env files
32-
require "csv"
33-
CSV.parse_line argv.delete_at(pos)
29+
def parse_argv!(argv)
30+
@filenames = []
31+
32+
OptionParser.new do |parser|
33+
parser.banner = "Usage: dotenv [options]"
34+
parser.separator ""
35+
add_options(parser)
36+
end.parse!(argv)
37+
38+
@filenames
39+
end
40+
41+
def add_options(parser)
42+
add_files_option(parser)
43+
add_help_option(parser)
44+
add_version_option(parser)
45+
end
46+
47+
def add_files_option(parser)
48+
parser.on("-f FILES", Array, "List of env files to parse") do |list|
49+
@filenames = list
50+
end
51+
end
52+
53+
def add_help_option(parser)
54+
parser.on("-h", "--help", "Display help") do
55+
puts parser
56+
exit
57+
end
58+
end
59+
60+
def add_version_option(parser)
61+
parser.on("-v", "--version", "Show version") do
62+
puts "dotenv #{Dotenv::VERSION}"
63+
exit
64+
end
3465
end
3566
end
3667
end

0 commit comments

Comments
 (0)