require 'delegate'
require 'tempfile'

module Voodoo
  # Utility functions for classes that use commands to postprocess
  # generator output.
  module CommandPostProcessor
    module_function

    # Encodes a string so that it is safe for use as a shell argument
    def shell_encode string
      '"' + string.gsub(/([\\`"$\n])/, "\\\\\\1") + '"'
    end

    # Creates a temporary file and returns its name
    def tempfile extension, base = nil
      base = self.class.name unless base
      file = Tempfile.open(basename + extension)
      name = file.path
      file.close
      name
    end

    # Writes the contents of the named file to an IO handle
    def write_file_to_io filename, io
      File.open(filename) { |file| io.write(file.read) }
    end

  end
end
