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.


6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/vagrant/alias.rb', line 6

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.


23
24
25
# File 'lib/vagrant/alias.rb', line 23

def commands
  @aliases
end

#interpret(line) ⇒ Object

This interprets a raw line from the aliases file.


28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/vagrant/alias.rb', line 28

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.


43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/vagrant/alias.rb', line 43

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