Class: Vagrant::Templated::Command::Init

Inherits:
Object
  • Object
show all
Defined in:
lib/vagrant-templated/command/init.rb

Instance Method Summary collapse

Instance Method Details

#executeObject



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/vagrant-templated/command/init.rb', line 6

def execute
  template, version, options = setup
  return if template.nil?
  @env.ui.info "vagrant-templated detected #{template} template", new_line: true
  if version.nil? || version.empty?
    version = Catalog.patch template, version
    @env.ui.info "vagrant-templated didn't received a version, using largest available #{version}"
  else
    @env.ui.info "vagrant-templated detected #{version} version"
  end

  vagrantfile = Catalog.vagrantfile_for template, version
  berksfile = Catalog.berksfile_for template, version

  if options[:cat]
    @env.ui.output vagrantfile
    @env.ui.output berksfile
  else
    files_root = @env.cwd
    if options[:output]
      @env.ui.info "vagrant-templated received output path #{options[:output]}"
      output_path = Pathname.new options[:output]
      files_root =  if output_path.relative?
        output_path.expand_path files_root
      else
        output_path
      end
      @env.ui.info "vagrant-templated will write the files in: #{files_root}"
    end

    vagrantfile_save_path = Pathname.new('Vagrantfile').expand_path files_root
    vagrantfile_save_path.delete if vagrantfile_save_path.exist? && options[:force]
    raise Vagrant::Templated::Errors::VagrantfileExistsError if vagrantfile_save_path.exist?

    berksfile_save_path = Pathname.new('Berksfile').expand_path files_root
    berksfile_save_path.delete if berksfile_save_path.exist? && options[:force]
    raise Vagrant::Templated::Errors::BerksfileExistsError if berksfile_save_path.exist?

    begin
      vagrantfile_save_path.open('w+') do |f|
        f.write vagrantfile
      end
      @env.ui.info "vagrant-templated created #{vagrantfile_save_path}"
    rescue Errno::EACCES
      raise Vagrant::Templated::Errors::VagrantfileWriteError
    end

    begin
      berksfile_save_path.open('w+') do |f|
        f.write berksfile
      end
      @env.ui.info "vagrant-templated created #{berksfile_save_path}"
    rescue Errno::EACCES
      raise Vagrant::Templated::Errors::BerksfileWriteError
    end
  end

  @env.ui.success 'vagrant-templated finished successfully'
  0
end