File: command_map.rb

package info (click to toggle)
ruby-sshkit 1.25.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 712 kB
  • sloc: ruby: 3,749; makefile: 2
file content (73 lines) | stat: -rw-r--r-- 1,410 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
module SSHKit
  class CommandMap
    class CommandHash
      def initialize(defaults = {})
        @storage = {}
        @defaults = defaults
      end

      def [](key)
        @storage[normalize_key(key)] ||= @defaults[key]
      end

      def []=(key, value)
        @storage[normalize_key(key)] = value
      end

      private

      def normalize_key(key)
        key.to_sym
      end
    end

    class PrefixProvider
      def initialize
        @storage = CommandHash.new
      end

      def [](command)
        @storage[command] ||= []
      end
    end

    TO_VALUE = ->(obj) { obj.respond_to?(:call) ? obj.call : obj }

    def initialize(value = nil)
      @map = CommandHash.new(value || defaults)
    end

    def [](command)
      if prefix[command].any?
        prefixes = prefix[command].map(&TO_VALUE)
        prefixes = prefixes.join(" ")

        "#{prefixes} #{command}"
      else
        TO_VALUE.(@map[command])
      end
    end

    def prefix
      @prefix ||= PrefixProvider.new
    end

    def []=(command, new_command)
      @map[command] = new_command
    end

    def clear
      @map = CommandHash.new(defaults)
    end

    def defaults
      Hash.new do |hash, command|
        if %w{if test time exec}.include? command.to_s
          hash[command] = command.to_s
        else
          hash[command] = "/usr/bin/env #{command}"
        end
      end
    end
  end
end