# -*- encoding: utf-8 -*- module Bookshelf class Cli < Thor FORMATS = %w[pdf html epub mobi txt] check_unknown_options! def self.exit_on_failure? true end def initialize(args = [], options = {}, config = {}) if (config[:current_task] || config[:current_command]).name == "new" && args.empty? raise Error, "The e-Book path is required. For details run: bookshelf help new" end super end desc "new EBOOK_PATH", "Generate a new e-book structure" def new(path) generator = Generator.new generator.destination_root = path generator.invoke_all end desc "export [OPTIONS]", "Export e-book" method_option :only, :type => :string, :desc => "Can be one of: #{FORMATS.join(", ")}" def export if options[:only] && !FORMATS.include?(options[:only]) raise Error, "The --only option need to be one of: #{FORMATS.join(", ")}" end book_dirs = if options[:book] [Bookshelf.root_dir.join("books/#{options[:book]}")] else Dir.glob(Bookshelf.root_dir.join("books/*")).map{|book_dir| Pathname.new(book_dir) } end book_dirs.each do |book_dir| Bookshelf::Exporter.run(book_dir, options) end end desc "version", "Prints the Bookshelf's version information" map %w(-v --version) => :version def version say "Bookshelf version #{Version::STRING}" end desc "check", "Check if all external dependencies are installed" def check result = [] result << { :description => "Prince XML: Converts HTML files into PDF files.", :installed => Bookshelf::Dependency.prince? } result << { :description => "KindleGen: Converts ePub e-books into .mobi files.", :installed => Bookshelf::Dependency.kindlegen? } result << { :description => "html2text: Converts HTML documents into plain text.", :installed => Bookshelf::Dependency.html2text? } result.each do |result| text = color(result[:name], :blue) text << "\n" << result[:description] text << "\n" << (result[:installed] ? color("Installed.", :green) : color("Not installed.", :red)) text << "\n" say(text) end end desc "permalinks", "List title permalinks" def permalinks html = Bookshelf::Parser::HTML.new(Bookshelf.root_dir).content toc = Bookshelf::TOC::HTML.generate(html) toc.toc.each do |options| level = options[:level] - 1 title = " #{options[:text]}: " permalink = "##{options[:permalink]}" text = "*" * level text << color(title, :blue) text << color(permalink, :yellow) say(text) end end desc "stats", "Display some stats about your e-book" def stats stats = Bookshelf::Stats.new(Bookshelf.root_dir) say [ "Chapters: #{stats.chapters}", "Words: #{stats.words}", "Images: #{stats.images}", "Links: #{stats.links}", "Footnotes: #{stats.footnotes}", "Code blocks: #{stats.code_blocks}" ].join("\n") end private def color(text, color) color? ? shell.set_color(text, color) : text end def color? shell.instance_of?(Thor::Shell::Color) end end end