|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +require 'singleton' |
| 4 | +require 'fileutils' |
| 5 | +require 'shellwords' |
| 6 | +require 'sfl' if Specinfra.ruby_is_older_than?(1, 9, 0) |
| 7 | + |
| 8 | +module Specinfra |
| 9 | + module Backend |
| 10 | + # LXD transport |
| 11 | + class Lxd < Exec |
| 12 | + def initialize(config = {}) |
| 13 | + super |
| 14 | + |
| 15 | + raise 'Please specify lxd_instance' unless (@instance = get_config(:lxd_instance)) |
| 16 | + raise 'Please specify lxd_remote' unless (@remote = get_config(:lxd_remote)) |
| 17 | + |
| 18 | + @remote_instance = [@remote, @instance].compact.join(':') |
| 19 | + end |
| 20 | + |
| 21 | + class << self |
| 22 | + protected |
| 23 | + |
| 24 | + def run_command(cmd, opts = {}) |
| 25 | + cmd = build_command(cmd) |
| 26 | + run_pre_command(opts) |
| 27 | + stdout, stderr, exit_status = with_env do |
| 28 | + spawn_command(cmd) |
| 29 | + end |
| 30 | + |
| 31 | + if @example |
| 32 | + @example.metadata[:command] = cmd |
| 33 | + @example.metadata[:stdout] = stdout |
| 34 | + end |
| 35 | + |
| 36 | + CommandResult.new :stdout => stdout, :stderr => stderr, :exit_status => exit_status |
| 37 | + end |
| 38 | + |
| 39 | + def build_command(cmd) |
| 40 | + cmd = super(cmd) |
| 41 | + "lxc exec #{@remote_instance} -- #{cmd}" |
| 42 | + end |
| 43 | + |
| 44 | + def send_file(source, destination) |
| 45 | + flags = %w[--create-dirs] |
| 46 | + if File.directory?(source) |
| 47 | + flags << '--recursive' |
| 48 | + destination = Pathname.new(destination).dirname.to_s |
| 49 | + end |
| 50 | + cmd = %W[lxc file push #{source} #{@remote_instance}#{destination}] + flags |
| 51 | + spawn_command(cmd.join(' ')) |
| 52 | + end |
| 53 | + |
| 54 | + private |
| 55 | + |
| 56 | + def run_pre_command(_opts) |
| 57 | + return unless get_config(:pre_command) |
| 58 | + |
| 59 | + cmd = build_command(get_config(:pre_command)) |
| 60 | + spawn_command(cmd) |
| 61 | + end |
| 62 | + end |
| 63 | + end |
| 64 | + end |
| 65 | +end |
0 commit comments