File: mapping_interaction_handler.rb

package info (click to toggle)
ruby-sshkit 1.21.2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 700 kB
  • sloc: ruby: 3,522; makefile: 2
file content (48 lines) | stat: -rw-r--r-- 1,448 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
module SSHKit

  class MappingInteractionHandler

    def initialize(mapping, log_level=nil)
      @log_level = log_level
      @mapping_proc = \
        case mapping
        when Hash
          lambda do |server_output|
            first_matching_key_value = mapping.find { |k, _v| k === server_output }
            first_matching_key_value.nil? ? nil : first_matching_key_value.last
          end
        when Proc
          mapping
        else
          raise "Unsupported mapping type: #{mapping.class} - only Hash and Proc mappings are supported"
        end
    end

    def on_data(_command, stream_name, data, channel)
      log("Looking up response for #{stream_name} message #{data.inspect}")

      response_data = @mapping_proc.call(data)

      if response_data.nil?
        log("Unable to find interaction handler mapping for #{stream_name}: #{data.inspect} so no response was sent")
      else
        log("Sending #{response_data.inspect}")
        if channel.respond_to?(:send_data) # Net SSH Channel
          channel.send_data(response_data)
        elsif channel.respond_to?(:write) # Local IO
          channel.write(response_data)
        else
          raise "Unable to write response data to channel #{channel.inspect} - does not support 'send_data' or 'write'"
        end
      end
    end

    private

    def log(message)
      SSHKit.config.output.send(@log_level, message) unless @log_level.nil?
    end

  end

end