aboutsummaryrefslogtreecommitdiffstats
path: root/lib/bundler/vendor/thor/lib/thor/line_editor/readline.rb
blob: dd39cff35dce2d0d52b2c8e7b3947c4acffc2c3c (plain)
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
begin
  require "readline"
rescue LoadError
end

class Bundler::Thor
  module LineEditor
    class Readline < Basic
      def self.available?
        Object.const_defined?(:Readline)
      end

      def readline
        if echo?
          ::Readline.completion_append_character = nil
          # Ruby 1.8.7 does not allow Readline.completion_proc= to receive nil.
          if complete = completion_proc
            ::Readline.completion_proc = complete
          end
          ::Readline.readline(prompt, add_to_history?)
        else
          super
        end
      end

    private

      def add_to_history?
        options.fetch(:add_to_history, true)
      end

      def completion_proc
        if use_path_completion?
          proc { |text| PathCompletion.new(text).matches }
        elsif completion_options.any?
          proc do |text|
            completion_options.select { |option| option.start_with?(text) }
          end
        end
      end

      def completion_options
        options.fetch(:limited_to, [])
      end

      def use_path_completion?
        options.fetch(:path, false)
      end

      class PathCompletion
        attr_reader :text
        private :text

        def initialize(text)
          @text = text
        end

        def matches
          relative_matches
        end

      private

        def relative_matches
          absolute_matches.map { |path| path.sub(base_path, "") }
        end

        def absolute_matches
          Dir[glob_pattern].map do |path|
            if File.directory?(path)
              "#{path}/"
            else
              path
            end
          end
        end

        def glob_pattern
          "#{base_path}#{text}*"
        end

        def base_path
          "#{Dir.pwd}/"
        end
      end
    end
  end
end