require_relative "empty_directory"

class Bundler::Thor
  module Actions
    # Create a new file relative to the destination root with the given data,
    # which is the return value of a block or a data string.
    #
    # ==== Parameters
    # destination<String>:: the relative path to the destination root.
    # data<String|NilClass>:: the data to append to the file.
    # config<Hash>:: give :verbose => false to not log the status.
    #
    # ==== Examples
    #
    #   create_file "lib/fun_party.rb" do
    #     hostname = ask("What is the virtual hostname I should use?")
    #     "vhost.name = #{hostname}"
    #   end
    #
    #   create_file "config/apache.conf", "your apache config"
    #
    def create_file(destination, *args, &block)
      config = args.last.is_a?(Hash) ? args.pop : {}
      data = args.first
      action CreateFile.new(self, destination, block || data.to_s, config)
    end
    alias_method :add_file, :create_file

    # CreateFile is a subset of Template, which instead of rendering a file with
    # ERB, it gets the content from the user.
    #
    class CreateFile < EmptyDirectory #:nodoc:
      attr_reader :data

      def initialize(base, destination, data, config = {})
        @data = data
        super(base, destination, config)
      end

      # Checks if the content of the file at the destination is identical to the rendered result.
      #
      # ==== Returns
      # Boolean:: true if it is identical, false otherwise.
      #
      def identical?
        # binread uses ASCII-8BIT, so to avoid false negatives, the string must use the same
        exists? && File.binread(destination) == String.new(render).force_encoding("ASCII-8BIT")
      end

      # Holds the content to be added to the file.
