diff --git a/spec/parser_spec.cr b/spec/parser_spec.cr index e49df1a..3a09138 100644 --- a/spec/parser_spec.cr +++ b/spec/parser_spec.cr @@ -17,12 +17,4 @@ describe Muse::Dl::Parser do parser.output.should eq "tempfilename.pdf" parser.url.should eq "https://muse.jhu.edu/book/68534" end - - it "should raise error on missing options" do - begin - parser = Muse::Dl::Parser.new([] of String) - rescue e : Exception - e.class.should eq Muse::Dl::Errors::MissingLink - end - end end diff --git a/src/errors/missing_link.cr b/src/errors/missing_link.cr deleted file mode 100644 index 6bd550f..0000000 --- a/src/errors/missing_link.cr +++ /dev/null @@ -1,4 +0,0 @@ -module Muse::Dl::Errors - class MissingLink < Exception - end -end diff --git a/src/parser.cr b/src/parser.cr index fec1fec..e447952 100644 --- a/src/parser.cr +++ b/src/parser.cr @@ -1,11 +1,12 @@ -require "./errors/missing_link.cr" +require "option_parser" +require "dir" module Muse::Dl class Parser - @bookmarks : Bool + @bookmarks = true @tmp : String - @cleanup : Bool - @output : String + @cleanup = true + @output = "tempfilename.pdf" @url = "INVALID_URL" getter :bookmarks, :tmp, :cleanup, :output, :url @@ -20,16 +21,31 @@ module Muse::Dl end def initialize(arg : Array(String) = [] of String) - @bookmarks = !arg.index "--no-bookmarks" - @cleanup = !arg.index "--no-cleanup" - @tmp = find_next(arg, "--tmp-dir", "/tmp") - @output = find_next(arg, "--output", "tempfilename.pdf") - begin - @url = arg[-1] - rescue e : Exception - @url = "" - raise Errors::MissingLink.new + @tmp = Dir.tempdir + + parser = OptionParser.new + parser.banner = "Usage: muse-dl [--flags] URL" + parser.on(long_flag = "--no-cleanup", description = "Don't cleanup temporary files") { @cleanup = false } + parser.on(long_flag = "--tmp-dir PATH", description = "Temporary Directory to use") { |path| @tmp = path } + parser.on(long_flag = "--output FILE", description = "Output Filename") { |file| @output = file } + parser.on(long_flag = "--no-bookmarks", description = "Don't add bookmarks in the PDF") { @bookmarks = false } + parser.on("-h", "--help", "Show this help") { puts parser } + + parser.unknown_args do |args| + if args.size != 1 + puts parser + exit 1 + end + @url = args[0] end + + parser.invalid_option do |flag| + STDERR.puts "ERROR: #{flag} is not a valid option." + STDERR.puts parser + exit(1) + end + + parser.parse(arg) end end end diff --git a/src/pdftk.cr b/src/pdftk.cr index 5b7695b..885cbb8 100644 --- a/src/pdftk.cr +++ b/src/pdftk.cr @@ -2,6 +2,7 @@ require "process" require "file" require "./fetch" require "./errors/*" +require "dir" module Muse::Dl class Pdftk @@ -11,7 +12,7 @@ module Muse::Dl getter :binary - def initialize(tmp_file_path : String) + def initialize(tmp_file_path : String = Dir.tempdir) @tmp_file_path = tmp_file_path possible_binary = Process.find_executable(Pdftk::PDFTK_BINARY_NAME)