Sha256: 64527e705353bb2d40eb753d6e4b25a1928be5f38c5b747ec2fcd41b511d64f0

Contents?: true

Size: 1.79 KB

Versions: 1

Compression:

Stored size: 1.79 KB

Contents

require "pathname"
require "geny/error"
require "geny/command"

module Geny
  class Registry
    # The default load path. By default, Geny
    # will search
    LOAD_PATH = [
      File.join(Dir.pwd, ".geny"),
      *ENV.fetch("CODE_HEN_PATH", "").split(":"),
      File.expand_path("../generators", __dir__)
    ]

    # The directories to search for commands in
    # @return [Array<String>]
    attr_reader :load_path

    # Create a new registry
    # @param load_path [Array<String>]
    def initialize(load_path: LOAD_PATH)
      @load_path = load_path
    end

    # Iterate over all load paths and find all commands
    # @return [Array<Command>]
    def scan
      glob = File.join("**", Command::FILENAME)

      commands = load_path.flat_map do |path|
        path = Pathname.new(path)

        path.glob(glob).map do |file|
          root = file.dirname
          name = root.relative_path_from(path)
          name = name.to_s.tr(File::SEPARATOR, ":")
          Command.new(name: name, root: root.to_s)
        end
      end

      commands.sort_by(&:name)
    end

    # Find a command by name
    # @param name [String] name of the command
    # @return [Command,nil]
    def find(name)
      load_path.each do |path|
        file = File.join(path, *name.split(":"), Command::FILENAME)
        root = File.dirname(file)
        return Command.new(name: name, root: root) if File.exist?(file)
      end

      nil
    end

    # Find a command by name or raise an error
    # @param name [String] name of the command
    # @raise [NotFoundError] when the command is not found
    # @return [Command]
    def find!(name)
      find(name) || command_not_found!(name)
    end

    private

    def command_not_found!(name)
      raise NotFoundError, "There doesn't appear to be a generator named '#{name}'"
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
geny-0.1.0 lib/geny/registry.rb