Sha256: 918191dd047fb85e9ddac3417e9316998085bb01eb7d6ea8ff71cd3a512207b7

Contents?: true

Size: 1.63 KB

Versions: 25

Compression:

Stored size: 1.63 KB

Contents

# frozen_string_literal: true
require "open3"

module Licensed
  module Shell
    # Executes a command, returning its standard output on success.
    # On failure it raises an exception that contains the error output, unless
    # `allow_failure` is true.
    def self.execute(cmd, *args, allow_failure: false, env: {})
      stdout, stderr, status = Open3.capture3(env, cmd, *args)

      if status.success? || allow_failure
        stdout.strip
      else
        raise Error.new([cmd, *args], status.exitstatus, stderr)
      end
    end

    # Executes a command and returns a boolean value indicating if the command
    # was succesful
    def self.success?(cmd, *args)
      _, _, status = Open3.capture3(cmd, *args)
      status.success?
    end

    # Returns a boolean indicating whether a CLI tool is available in the
    # current environment
    def self.tool_available?(tool)
      output, err, status = Open3.capture3("which", tool)
      status.success? && !output.strip.empty? && err.strip.empty?
    end

    class Error < RuntimeError
      attr_reader :cmd, :status, :stderr
      def initialize(cmd, status, stderr)
        super()
        @cmd = cmd
        @exitstatus = status
        @stderr = stderr.to_s.strip
      end

      def message
        extra = @stderr.empty?? "" : "#{@stderr.gsub(/^/, "        ")}"
        "'#{escape_cmd}' exited with status #{@exitstatus}\n#{extra}"
      end

      def escape_cmd
        @cmd.map do |arg|
          if arg =~ /[\s'"]/
            escaped = arg.gsub(/([\\"])/, '\\\\\1')
            %("#{escaped}")
          else
            arg
          end
        end.join(" ")
      end
    end
  end
end

Version data entries

25 entries across 25 versions & 1 rubygems

Version Path
licensed-2.14.0 lib/licensed/shell.rb
licensed-2.13.0 lib/licensed/shell.rb
licensed-2.12.2 lib/licensed/shell.rb
licensed-2.12.1 lib/licensed/shell.rb
licensed-2.12.0 lib/licensed/shell.rb
licensed-2.11.1 lib/licensed/shell.rb
licensed-2.11.0 lib/licensed/shell.rb
licensed-2.10.0 lib/licensed/shell.rb
licensed-2.9.2 lib/licensed/shell.rb
licensed-2.9.1 lib/licensed/shell.rb
licensed-2.9.0 lib/licensed/shell.rb
licensed-2.8.0 lib/licensed/shell.rb
licensed-2.7.0 lib/licensed/shell.rb
licensed-2.6.2 lib/licensed/shell.rb
licensed-2.6.1 lib/licensed/shell.rb
licensed-2.6.0 lib/licensed/shell.rb
licensed-2.5.0 lib/licensed/shell.rb
licensed-2.4.0 lib/licensed/shell.rb
licensed-2.3.2 lib/licensed/shell.rb
licensed-2.3.1 lib/licensed/shell.rb