Sha256: 96f5b20a2cba729c92cfa5ccdd85fbe4468335d30f3ad58f7811578d87724368

Contents?: true

Size: 1.91 KB

Versions: 3

Compression:

Stored size: 1.91 KB

Contents

require 'repertoire/exceptions/program_not_found'
require 'repertoire/exceptions/command_failed'

module Repertoire
  module Compat
    #
    # Returns the native _platform_.
    #
    #   Compat.arch  #=> "linux"
    #
    def self.platform
      RUBY_PLATFORM.split('-').last
    end

    #
    # Returns an array representing the +PATH+ environment variable.
    # If the +PATH+ environment variable is not setup, an empty array will
    # be returned.
    #
    #   Compat.paths
    #   #=> ["/bin", "/usr/bin"]
    #
    def self.paths
      # return an empty array in case
      # the PATH variable does not exist
      return [] unless ENV['PATH']

      if self.platform =~ /mswin32/
        return ENV['PATH'].split(';')
      else
        return ENV['PATH'].split(':')
      end
    end

    #
    # Finds the program matching _name_ and returns it's full path.
    # If the program was not found, +nil+ will be returned.
    #
    #   Compat.find_program('as')  #=> "/usr/bin/as"
    #
    def self.find_program(name)
      self.paths.each do |dir|
        full_path = File.expand_path(File.join(dir,name))

        return full_path if File.file?(full_path)
      end

      return nil
    end

    #
    # Runs the command specified by _program_ and the given _args_.
    # If _program_ cannot be found on the system, a ProgramNotFound
    # exception will be raised.
    #
    #   Compat.sh('ls','-la','/')
    #
    def Compat.sh(program,*args)
      program = program.to_s

      program_path = Compat.find_program(program)
      unless program_path
        raise(ProgramNotFound,"the program #{program.dump} was not found",caller)
      end

      # stringify the args
      args = args.map { |arg| arg.to_s }

      unless system(program_path,*args)
        command = program_path
        command += ' ' + args.join(' ') unless args.empty?

        raise(CommandFailed,"the command #{command.dump} failed",caller)
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
repertoire-0.2.2 lib/repertoire/compat.rb
repertoire-0.2.1 lib/repertoire/compat.rb
repertoire-0.2.0 lib/repertoire/compat.rb