Sha256: 370746475557682342d2a5ce1295a665d47c588058fc48aa9dab97b6ba6c83cf

Contents?: true

Size: 1.8 KB

Versions: 1

Compression:

Stored size: 1.8 KB

Contents

require "brash/version"

require File.expand_path "../brash/command", __FILE__

module Brash
  def self.build(*args, &block)
    CommandContext.surround(*args, &block).command
  end
  class CommandContext
    attr_reader :command, :depth
    def method_missing(method, *args, &block)
      @command = Command.new(method, *args, &block).tap{|c| c.context = self}
    end
    def initialize(depth=0)
      @depth = depth
    end
    def self.surround(*args, &block)
      context = CommandContext.new(*args)
      context.instance_eval(&block) if block_given?
      context
    end
  end
  class Command
    attr_accessor :context
    def method_missing(method, *args, &block)
      @compound_command = Command.new(method, *args, &block).tap{|c| c.context = context}
    end
    def initialize(command, *args)
      @command = command
      @args = Array(args).join("")
    end
    def pipe_to(&block)
      command = Brash.build(&block)
      @args += " | " + command.to_bash
    end
    def dash(*args)
      @args += "-#{args.first}" if args.length > 0
      @args += " " + args[1..-1].map{|arg| escape_arg(arg)}.join(" ") if args.length > 1
      self
    end
    def arg(arg)
      @args += " " + escape_arg(arg)
      self
    end
    def escape_arg(arg)
      if arg.is_a?(Proc)
        CommandContext.surround(context.depth + 1, &arg).command.to_bash
      elsif arg.is_a?(String) && arg.include?(" ")
        escape(arg, context.depth+1)
      else arg
      end
    end
    def escape(bash, depth=context.depth)
      escaped = bash
      escaped = "\\"*(depth-1) + "\"" + "#{escaped}" + "\\"*(depth-1) + "\"" if depth > 0
      escaped 
    end
    def to_bash
      bash = @command.to_s
      bash += " " + @args unless @args == ""
      bash += " " + @compound_command.to_bash if @compound_command
      escape(bash)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
brash-0.0.1 lib/brash.rb