Sha256: fb8ebf0d5a2073f6ac12f97dbbe36d6b9afb947e868dd0672c514abd36fe27cc

Contents?: true

Size: 1.97 KB

Versions: 1

Compression:

Stored size: 1.97 KB

Contents

require 'logger'
require 'singleton'
require 'paint'

module RCoLi
  
  class ApplicationContext
    
    include Singleton
    
    attr_accessor :debug
    
  end
  
  class Log
    
    include Singleton
    
    def initialize
      @log = Logger.new(STDOUT)
      @log.level = Logger::INFO
      @log.formatter = proc do |severity, datetime, progname, msg|
        case severity
        when "DEBUG"
          color = 'gray27'
        else
          color = :white
        end
        
        if STDOUT.tty?
          Paint["#{msg}\n", color]
        else
          "#{msg}\n"
        end
        
      end
    end
    
    def logger
      @log
    end
    
  end
  
  class SystemExecutor
    
    include Singleton
    
    def initialize
    end
    
    def register(file)
      @source = file
      log.debug("Loading commands from file #{file}")
      @commands = YAML::load(File.open(file))
    end
    
    def execute(command, *args)
      cmnd = @commands[command.to_s]
      if cmnd
        cmnd.scan(/\$\{([^\s]+)\}/).each do |s|
          context = args[0]
          (s[0].split('.').each{|key| context = (context.is_a? Hash) ? context[key] : nil})
          cmnd = cmnd.sub("${#{s[0]}}", context.to_s) if context
        end
        
        # ALTERNATIVE SOLUTION
        # cmnd.to_enum(:scan, /\$\{([^\s]+)\}/).map {[Regexp.last_match[0], Regexp.last_match[1].split('.')]}.each do |m|
        #   context = (context.nil? ? config : context)[m[1].delete_at(0)] until m[1].size == 0
        #   cmnd = cmnd.sub(m[0], context) if context.is_a? String
        # end
        
        
        log.debug("EXEC: #{cmnd}")
        system(cmnd)
      else
        raise ApplicationError, "The command #{command} isn't configured. Check the file #{@source}"
      end
    end
    
  end
  
end

def log
  RCoLi::Log.instance.logger
end

def sysexec(command, *args)
  RCoLi::SystemExecutor.instance.execute(command, args[0])
end

def load_commands(file)
  RCoLi::SystemExecutor.instance.register(file)
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rcoli-0.5.10 lib/rcoli/utils.rb