Class: Djinni

Inherits:
Object
  • Object
show all
Defined in:
lib/djinni.rb

Defined Under Namespace

Classes: Error, Wish

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(interactive = false) ⇒ Djinni

Returns a new instance of Djinni.



201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
# File 'lib/djinni.rb', line 201

def initialize(interactive = false)
    @fallback = nil
    @hist_index = nil
    @history = Array.new
    @interactive = interactive
    @loaded_from = Array.new
    @width = %x(tput cols).to_i
    @wishes = Hash.new

    Signal.trap(
        "WINCH",
        proc do
            @width = %x(tput cols).to_i
        end
    )

    load_wishes("#{File.dirname(__FILE__)}/djinni/wish")
end

Instance Attribute Details

#fallbackObject

Returns the value of attribute fallback.



5
6
7
# File 'lib/djinni.rb', line 5

def fallback
  @fallback
end

Instance Method Details

#grant_wish(input, djinni_env = {}) ⇒ Object



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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/djinni.rb', line 7

def grant_wish(input, djinni_env = {})
    return "" if (input.nil? || input.empty?)

    djinni_env["djinni"] = self
    djinni_env["djinni_history"] = @history
    djinni_env["djinni_wishes"] = @wishes
    space = 4

    case input[-1]
    when "\x03" # ^C
        puts if (@interactive)
        return ""
    when "\x04" # ^D
        return "\x04"
    when "\x7F", "\b" # Backspace or ^H
        return input[0..-3]
    when "\f" # ^L
        system("clear") if (@interactive)
        return input[0..-2]
    when "\t" # Tab
        input = input[0..-2]
        if (input.include?(" "))
            name, args = input.split(" ", 2)
            return input if (!@wishes.has_key?(name))

            begin
                wish = @wishes[name]
                djinni_env["djinni_input"] = name
                completions, replace, append = wish.tab_complete(
                    args,
                    djinni_env
                )
            rescue SystemExit => e
                raise e
            rescue Exception => e
                puts
                puts e.message
            ensure
                append ||= " "
                completions ||= Hash.new
                replace ||= ""
            end

            return input if (completions.empty?)

            if (completions.length == 1)
                return input.gsub(
                    /#{replace}$/,
                    "#{completions.first.first}#{append}"
                )
            end

            max = completions.keys.max_by(&:length).length
            nlfill = ""
            nlfill = " " * (max + space) if ((max + space) > 0)
            width = @width - (max + space) - 2

            puts
            completions.each do |item, desc|
                desc ||= ""
                fill = ""
                if ((max + space - item.length) > 0)
                    fill = " " * (max + space - item.length)
                end
                lines = desc.scan(
                    /\S.{0,#{width}}\S(?=\s|$)|\S+/
                )

                if (lines.empty?)
                    puts item
                else
                    start = lines.delete_at(0)
                    puts "#{item}#{fill}#{start}"
                    lines.each do |line|
                        puts "#{nlfill}#{line}"
                    end
                end
            end

            longest = longest_common_substring(completions.keys)
            return input if (longest.empty?)
            return input.gsub(/#{replace}$/, longest)
        else
            wishes = @wishes.select do |aliaz, w|
                aliaz.start_with?(input)
            end

            return input if (wishes.empty?)

            if (wishes.length == 1)
                return "#{wishes.first.first} "
            end

            max = wishes.keys.max_by(&:length).length
            nlfill = ""
            nlfill = " " * (max + space) if ((max + space) > 0)
            width = @width - (max + space) - 2

            puts
            wishes.sort do |a, b|
                a.first.downcase <=> b.first.downcase
            end.each do |aliaz, w|
                fill = ""
                if ((max + space - aliaz.length) > 0)
                    fill = " " * (max + space - aliaz.length)
                end
                lines = w.description.scan(
                    /\S.{0,#{width}}\S(?=\s|$)|\S+/
                )

                if (lines.empty?)
                    puts aliaz
                else
                    start = lines.delete_at(0)
                    puts "#{aliaz}#{fill}#{start}"
                    lines.each do |line|
                        puts "#{nlfill}#{line}"
                    end
                end
            end

            return longest_common_substring(wishes.keys)
        end
    when /\r|\n/ # Enter
        input.strip!
        puts if (@interactive)
        return "" if (input.empty?)

        # "".split(" ", 2) => [] aka [nil, nil]
        # " ".split(" ", 2) => [""] aka ["", nil]
        # The above 2 would return before getting here
        # "string".split(" ", 2) => ["string"] aka ["string", nil]
        # "string ".split(" ", 2) => ["string", ""]
        name, args = input.split(" ", 2)
        args ||= ""

        @wishes.select do |aliaz, w|
            aliaz == name
        end.each do |aliaz, w|
            begin
                djinni_env["djinni_input"] = name
                w.execute(args, djinni_env)
            rescue SystemExit => e
                raise e
            rescue Exception => e
                puts e.message
            end

            if (w.class.to_s != "Djinni::Wish::History")
                store_history(input)
            end

            return ""
        end
        store_history(input)
        return nil
    when "\e" # Arrow keys
        code = "\e"
        t = Thread.new do
            code += STDIN.getch + STDIN.getch
        end
        t.join(0.001) if (t)
        t.kill if (t)

        case code
        when /\e[\[O]A/ # Up arrow
            return "" if (@history.empty?)
            @hist_index = @history.size if (@hist_index.nil?)
            @hist_index = 1 if (@hist_index == 0)
            @hist_index -= 1
            return @history[@hist_index]
        when /\e[\[O]B/ # Down arrow
            @hist_index = @history.size if (@hist_index.nil?)
            @hist_index += 1
            if (@hist_index < @history.size)
                return @history[@hist_index]
            else
                @hist_index = @history.size
                return ""
            end
        when /\e[\[O]C/ # Right arrow
            # TODO maybe implement right arrow
            return input[0..-2]
        when /\e[\[O]D/ # Left arrow
            # TODO maybe implement left arrow
            return input[0..-2]
        else
            return input[0..-2]
        end
    else
        return input
    end
end

#load_wishes(dir) ⇒ Object



220
221
222
223
224
225
226
227
228
229
230
231
232
# File 'lib/djinni.rb', line 220

def load_wishes(dir)
    return if @loaded_from.include?(dir)

    classes = Fagin.find_children("Djinni::Wish", dir)
    classes.each do |clas, wish|
        w = wish.new
        w.aliases.each do |aliaz|
            @wishes[aliaz] = w
        end
    end

    @loaded_from.push(dir)
end

#prompt(djinni_env = {}, djinni_prompt = "$ ") ⇒ Object



249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
# File 'lib/djinni.rb', line 249

def prompt(djinni_env = {}, djinni_prompt = "$ ")
    @interactive = true

    djinni_env["djinni_prompt"] = djinni_prompt
    prev_len = 0
    buff = ""
    loop do
        djinni_prompt = djinni_env["djinni_prompt"]
        blank_line = ""
        blank_line = " " * @width if (@width > 0)

        # Handle long lines that get wrapped
        buff_len = remove_colors(djinni_prompt).length + prev_len
        lines = buff_len / @width
        lines -= 1 if ((buff_len % @width) == 0)
        lines.times do
            print "\r#{blank_line}"
            print "\e[F"
        end

        # Redisplay prompt
        print "\r#{blank_line}"
        print "\r#{djinni_prompt}#{buff}"

        # Process input
        input = nil
        system("stty raw -echo")
        while (input.nil?)
            begin
                input = STDIN.getch
            rescue
                puts if (@interactive)
            end
        end
        system("stty -raw echo")
        prev_len = remove_colors(buff).length
        save = buff
        buff = grant_wish(buff + input, djinni_env)

        if (buff.nil? && !@fallback.nil? && !@fallback.empty?)
            puts "\e[2A"
            buff = grant_wish(
                @fallback + " " + save + input, djinni_env
            )
        end

        if (buff.nil?)
            puts "Command not found!"
            buff = ""
        end

        # Exit on ^D
        if (buff == "\x04")
            return
        end
    end
end