Sha256: 704c751808f4960c180c014b68c2bea50ab838b81f6f9f359ca7e374d539f9d7

Contents?: true

Size: 1.52 KB

Versions: 6

Compression:

Stored size: 1.52 KB

Contents

# encoding: UTF-8

require 'anvil/extensions_manager'
require 'tasks/help_task'

module Anvil
  # Anvil command line interface
  class Cli
    HELP = <<-HELP
Anvil is a tool for making your life easier.

Available tasks:
HELP

    # Runs a task or prints its help if it needs arguments
    #
    # @param argv [Array] Command line arguments
    # @return [Object, nil] Anything the task returns
    def run(argv)
      load_tasks

      if argv.empty?
        print_help
      else
        build_task(argv).run
      end
    end

    def load_tasks
      Anvil::ExtensionsManager.load_tasks
    end

    # Builds a task and prepares it to run
    #
    # @param argv [Array] Command line arguments
    # @return [Anvil::Task] A task ready to run
    def build_task(argv)
      arguments = argv.dup
      task_name = arguments.shift
      klazz     = Task.from_name(task_name)
      klazz.new(*klazz.parse_options!(arguments))
    rescue NameError
      task_not_found(task_name)
      exit(FALSE)
    rescue ArgumentError
      help(task_name)
      exit(FALSE)
    end

    def task_not_found(task_name)
      printf("Task '#{task_name}' not found\n\n")
      print_help
    end

    def help(task_name)
      printf("Wrong number of arguments.\n\n")
      HelpTask.run(task_name)
    end

    def print_help
      printf('%s', HELP)
      tasks = Anvil::ExtensionsManager.tasks_by_name
      tasks.each { |task| print_task_line(task) }
    end

    def print_task_line(task)
      printf("%-20s %s\n", task.task_name, task.description)
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
anvil-core-0.4.2 lib/anvil/cli.rb
anvil-core-0.4.1 lib/anvil/cli.rb
anvil-core-0.4.0 lib/anvil/cli.rb
anvil-core-0.3.2 lib/anvil/cli.rb
anvil-core-0.3.1 lib/anvil/cli.rb
anvil-core-0.3.0 lib/anvil/cli.rb