Sha256: 75f59d68c3c646828bf0d2e52b8a9e259d7a856674a30c19a95ab98701d578ff

Contents?: true

Size: 1.95 KB

Versions: 4

Compression:

Stored size: 1.95 KB

Contents

# frozen_string_literal: true

require 'active_support/encrypted_configuration'

module Workato
  module CLI
    class EditCommand
      def initialize(path:, options:)
        @encrypted_file_path = path
        @key_path = options[:key] || Workato::Connector::Sdk::DEFAULT_MASTER_KEY_PATH
        @encrypted_config ||= ActiveSupport::EncryptedConfiguration.new(
          config_path: encrypted_file_path,
          key_path: @key_path,
          env_key: Workato::Connector::Sdk::DEFAULT_MASTER_KEY_ENV,
          raise_if_missing_key: false
        )
      end

      def call
        ensure_editor_available || return
        ensure_encryption_key_present

        catch_editing_exceptions do
          encrypted_config.change do |tmp_path|
            system("#{ENV['EDITOR']} #{tmp_path}")
          end
        end

        puts 'File encrypted and saved.'
      rescue ActiveSupport::MessageEncryptor::InvalidMessage
        puts "Couldn't decrypt #{encrypted_file_path}. Perhaps you passed the wrong key?"
      end

      private

      attr_reader :key_path,
                  :encrypted_file_path,
                  :encrypted_config

      def ensure_encryption_key_present
        return if encrypted_config.key.present?

        Generators::MasterKeyGenerator.new.call(@key_path)
      end

      def ensure_editor_available
        return true if ENV['EDITOR'].to_s.present?

        puts <<~HELP
          No $EDITOR to open file in. Assign one like this:

          EDITOR="mate --wait" workato edit #{encrypted_file_path}

          For editors that fork and exit immediately, it's important to pass a wait flag,
          otherwise the credentials will be saved immediately with no chance to edit.

        HELP

        false
      end

      def catch_editing_exceptions
        yield
      rescue Interrupt
        puts 'Aborted changing file: nothing saved.'
      rescue ActiveSupport::EncryptedFile::MissingKeyError => e
        puts e.message
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
workato-connector-sdk-0.2.0 lib/workato/cli/edit_command.rb
workato-connector-sdk-0.1.2 lib/workato/cli/edit_command.rb
workato-connector-sdk-0.1.1 lib/workato/cli/edit_command.rb
workato-connector-sdk-0.1.0 lib/workato/cli/edit_command.rb