Sha256: ad0e8c1c2b87cd1ed51fab9f23ef3cafb1f3b652f08bfcbe2559aefe2bc8fc02

Contents?: true

Size: 1.32 KB

Versions: 3

Compression:

Stored size: 1.32 KB

Contents

module Shellject
  module Tasks
    # Encrypts and saves a file as a shelljection.
    class Save
      attr_reader :save_directory, :input_path, :name

      def initialize(save_directory, input_path, name = nil)
        @save_directory = save_directory
        @input_path = input_path
        @name = name
      end

      def call
        ensure_readable
        ensure_writable
        with_files do |from, to|
          crypto.encrypt from, output: to
        end
      end

      private

      def with_files
        from = File.open(input_path)
        to = File.open(output_path, 'wb')
        yield from, to
      ensure
        from.close if from
        to.close if to
      end

      def ensure_writable
        FileUtils.mkdir_p(output_path.parent)
        fail ShelljectError, "Cannot save to #{output_path}" unless writable?
      end

      def writable?
        output_path.parent.writable?
      end

      def ensure_readable
        fail ShelljectError, "Cannot read file #{input_path}" unless readable?
      end

      def readable?
        File.readable? input_path
      end

      def output_path
        @output_path ||= save_directory.path_for name
      end

      def name
        @name ||= File.basename(input_path)
      end

      def crypto
        GPGME::Crypto.new always_trust: true
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
shellject-0.3.0 lib/shellject/tasks/save.rb
shellject-0.2.0 lib/shellject/tasks/save.rb
shellject-0.1.0 lib/shellject/tasks/save.rb