Sha256: 99f0ef9e1ba15139900cd2e88c6db5e9b2e26820615fbd9a8f92cd4eb8941faa

Contents?: true

Size: 1.59 KB

Versions: 8

Compression:

Stored size: 1.59 KB

Contents

require "open3"

module Bard
  class Command < Struct.new(:command, :on, :home)
    class Error < RuntimeError; end

    def self.run! command, on: :local, home: false, verbose: false, quiet: false
      new(command, on, home).run! verbose:, quiet:
    end

    def self.run command, on: :local, home: false, verbose: false, quiet: false
      new(command, on, home).run verbose:, quiet:
    end

    def self.exec! command, on: :local, home: false
      new(command, on, home).exec!
    end

    def run! verbose: false, quiet: false
      if !run(verbose:, quiet:)
        raise Error.new(full_command)
      end
    end

    def run verbose: false, quiet: false
      if verbose
        system full_command(quiet: quiet)
      else
        stdout, stderr, status = Open3.capture3(full_command)
        failed = status.to_i.nonzero?
        if failed && !quiet
          $stdout.puts stdout
          $stderr.puts stderr
        end
        !failed && stdout
      end
    end

    def exec!
      exec full_command
    end

    private

    def full_command quiet: false
      if on.to_sym == :local
        command
      else
        remote_command quiet: false
      end
    end

    def remote_command quiet: false
      cmd = command
      if on.env
        cmd = "#{on.env} #{command}"
      end
      unless home
        cmd = "cd #{on.path} && #{cmd}"
      end
      ssh_key = on.ssh_key ? "-i #{on.ssh_key} " : ""
      cmd = "ssh -tt #{ssh_key} #{on.ssh_uri} '#{cmd}'"
      if on.gateway
        cmd = "ssh -tt #{on.ssh_uri(:gateway)} \"#{cmd}\""
      end
      cmd += " 2>&1" if quiet
      cmd
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
bard-1.1.2 lib/bard/command.rb
bard-1.1.1 lib/bard/command.rb
bard-1.1.0 lib/bard/command.rb
bard-1.0.8 lib/bard/command.rb
bard-1.0.7 lib/bard/command.rb
bard-1.0.6 lib/bard/command.rb
bard-1.0.5 lib/bard/command.rb
bard-1.0.4 lib/bard/command.rb