Sha256: 5bb93cf65d97e3d8e1f7adf44214989e84cc728fd20f41c6ea1ab371b58f8ec8

Contents?: true

Size: 1.74 KB

Versions: 3

Compression:

Stored size: 1.74 KB

Contents

module Hookit
  module Resource
    class File < Base

      field :path
      field :content
      field :mode
      field :owner
      field :group

      actions :create, :create_if_missing, :delete, :touch
      default_action :create

      def initialize(name)
        path name unless path
        super
      end

      def run(action)
        case action
        when :create
          create!
          chown!
          chmod!            
        when :create_if_missing
          create_if_missing!
          chown!
          chmod!
        when :delete
          delete!
        when :touch
          touch!
        end
      end

      protected

      def create!
        begin
          ::File.write path, (content || "")
        rescue Exception => e
          unexpected_failure("create file", e.message)
        end
      end

      def create_if_missing!
        if not ::File.exists? path
          create!
        end
      end

      def delete!
        begin
          ::File.delete path
        rescue Exception => e
          unexpected_failure("delete file", e.message)
        end
      end

      def chown!
        return unless owner or group
        if ::File.exists? path
          run_command! "chown #{(group.nil?) ? owner : "#{owner}:#{group}"} #{path}"
        end
      end

      def chmod!
        if ::File.exists? path and mode
          begin
            ::File.chmod(mode, path)
          rescue Exception => e
            unexpected_failure("chmod file", e.message)
          end
        end
      end

      def touch!
        run_command! "touch -c #{path}"
      end

      def unexpected_failure(message, reason)
        print_error(message, {
          path: path,
          reason: reason
        })
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
micro-hookit-0.12.13 lib/hookit/resource/file.rb
micro-hookit-0.12.12 lib/hookit/resource/file.rb
micro-hookit-0.12.11 lib/hookit/resource/file.rb