Class: Vagrant::Alias

Inherits:
Object
  • Object
show all
Defined in:
lib/vagrant/alias.rb

Overview

This class imports and processes CLI aliases stored in ~/.vagrant.d/aliases

Instance Method Summary collapse

Constructor Details

#initialize(env) ⇒ Alias

Returns a new instance of Alias.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/vagrant/alias.rb', line 9

def initialize(env)
  @aliases = Registry.new
  @env = env

  if env.aliases_path.file?
    env.aliases_path.readlines.each do |line|
      # separate keyword-command pairs
      keyword, command = interpret(line)

      if keyword && command
        register(keyword, command)
      end
    end
  end
end

Instance Method Details

#commandsObject

This returns all the registered alias commands.



26
27
28
# File 'lib/vagrant/alias.rb', line 26

def commands
  @aliases
end

#interpret(line) ⇒ Object

This interprets a raw line from the aliases file.



31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/vagrant/alias.rb', line 31

def interpret(line)
  # is it a comment?
  return nil if line.strip.start_with?("#")

  keyword, command = line.split("=", 2).collect(&:strip)

  # validate the keyword
  if keyword.match(/\s/i)
    raise Errors::AliasInvalidError, alias: line, message: "Alias keywords must not contain any whitespace."
  end

  [keyword, command]
end

#register(keyword, command) ⇒ Object

This registers an alias.



46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/vagrant/alias.rb', line 46

def register(keyword, command)
  @aliases.register(keyword.to_sym) do
    lambda do |args|
      # directly execute shell commands
      if command.start_with?("!")
        return Util::SafeExec.exec "#{command[1..-1]} #{args.join(" ")}".strip
      end

      return CLI.new(command.split.concat(args), @env).execute
    end
  end
end