Sha256: cda43df16d220fecac0662afed71aff62fda7fc928d9eff9836835df6c970969

Contents?: true

Size: 1.87 KB

Versions: 6

Compression:

Stored size: 1.87 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
        raise "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.'
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
workato-connector-sdk-1.0.1 lib/workato/cli/edit_command.rb
workato-connector-sdk-1.0.0 lib/workato/cli/edit_command.rb
workato-connector-sdk-0.5.0 lib/workato/cli/edit_command.rb
workato-connector-sdk-0.4.1 lib/workato/cli/edit_command.rb
workato-connector-sdk-0.4.0 lib/workato/cli/edit_command.rb
workato-connector-sdk-0.3.0 lib/workato/cli/edit_command.rb