Sha256: 300dff088d2bcb33da74056a246d62c8941e513152d288d95a6466099f2eafdf

Contents?: true

Size: 1.91 KB

Versions: 3

Compression:

Stored size: 1.91 KB

Contents

require 'fileutils'

module R10K
  module Util

    # Mixin for purging stale directory contents.
    #
    # @abstract Classes using this mixin need to implement {#managed_directory} and
    #   {#desired_contents}
    module Purgeable

      # @!method logger
      #   @abstract Including classes must provide a logger method
      #   @return [Log4r::Logger]

      # @!method desired_contents
      #   @abstract Including classes must implement this method to list the
      #     expected filenames of managed_directory
      #   @return [Array<String>] A list of directory contents that should be present

      # @!method managed_directory
      #   @abstract Including classes must implement this method to return the
      #     path to the directory that can be purged
      #   @return [String] The path to the directory to be purged

      # @return [Array<String>] The present directory entries in `self.managed_directory`
      def current_contents
        dir = self.managed_directory
        glob_exp = File.join(dir, '*')

        Dir.glob(glob_exp).map do |fname|
          File.basename(fname)
        end
      end

      # @return [Array<String>] Directory contents that are expected but not present
      def pending_contents
        desired_contents - current_contents
      end

      # @return [Array<String>] Directory contents that are present but not expected
      def stale_contents
        current_contents - desired_contents
      end

      # Forcibly remove all unmanaged content in `self.managed_directory`
      def purge!
        if stale_contents.empty?
          logger.debug1 "No stale contents in #{managed_directory}, nothing to purge"
        else
          stale_contents.each do |fname|
            fpath = File.join(self.managed_directory, fname)
            logger.debug "Removing stale path #{fpath}"
            FileUtils.rm_rf(fpath, :secure => true)
          end
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
r10k-1.4.2 lib/r10k/util/purgeable.rb
r10k-1.4.1 lib/r10k/util/purgeable.rb
r10k-1.4.0 lib/r10k/util/purgeable.rb