Sha256: 5f42c23e633e5d9557d29643b384b738c34a2fd81757f55498cb69e527b3983d

Contents?: true

Size: 1.97 KB

Versions: 3

Compression:

Stored size: 1.97 KB

Contents

module ConfigCurator
  # A config file is a file that should be copied.
  class ConfigFile < Unit
    attr_accessor :fmode, :owner, :group

    # Will use files of the form `filename.hostname.ext` if found.
    # (see Unit#source)
    def source
      path = super
      host_specific_file = search_for_host_specific_file path if path

      if host_specific_file
        return host_specific_file
      else
        return path
      end
    end

    # (see Unit#destination)
    # @note Use {Unit#source} by default.
    def destination
      super
      @destination ||= @source
    end

    # (see Unit#install)
    def install
      s = super
      return s unless s
      install_file
      set_mode
      set_owner
      true
    end

    # (see Unit#install?)
    def install?
      s = super
      return s unless s
      fail InstallFailed, 'No file source path specified.' if source_path.nil?
      fail InstallFailed, "Source path does not exist: #{source}" unless File.exist? source_path
      true
    end

    private

    # Recursively creates the necessary directories and install the file.
    def install_file
      FileUtils.mkdir_p File.dirname(destination_path)
      FileUtils.copy source_path, destination_path, preserve: true
    end

    # Sets file mode.
    def set_mode
      FileUtils.chmod fmode, destination_path unless fmode.nil?
    end

    # Sets file owner and group.
    def set_owner
      FileUtils.chown owner, group, destination_path
    end

    private

    # Will look for files with the naming pattern `filename.hostname.ext`.
    # @param path [String] path to the non-host-specific file
    def search_for_host_specific_file(path)
      directory = File.dirname path
      extension = File.extname path
      basename = File.basename path.chomp(extension)
      if Dir.exist? directory
        file = Dir.entries(directory).grep(/^#{basename}.#{hostname.downcase}/).first
        return File.join directory, file unless file.nil?
      end
      nil
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
config_curator-0.2.3 lib/config_curator/units/config_file.rb
config_curator-0.2.2 lib/config_curator/units/config_file.rb
config_curator-0.2.1 lib/config_curator/units/config_file.rb