-
Notifications
You must be signed in to change notification settings - Fork 5
/
elman
executable file
·211 lines (180 loc) · 6.55 KB
/
elman
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
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
200
201
202
203
204
205
206
207
208
209
210
211
#!/usr/bin/env ruby
#
# MIT License
#
# Copyright (c) 2018 Lazarus Lazaridis
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
require 'yaml'
require 'fileutils'
require 'elasticsearch'
require 'optparse'
CONFIGURATION_FILE = File.expand_path('~/.elman.yml')
INDEX_NAME = 'elman'
APROPOS_REGEX = /(.*)\s\(\d*.*\)\s*-\s*(.*)/
# Creates the configuration file in user's home directory
def create_default_configuration_file
puts 'Creating the default configuration'
FileUtils.touch(CONFIGURATION_FILE)
configuration = YAML::load_file(CONFIGURATION_FILE) || {}
configuration[:elasticsearch] = { host: 'localhost',
port: '9200',
search_results_size: 10 }
File.write(CONFIGURATION_FILE, configuration.to_yaml)
end
# Deletes the index
def delete_index
client.indices.delete index: INDEX_NAME rescue false
end
# Creates the index
def create_index
return if client.indices.exists? index: INDEX_NAME
puts "Creating index: #{INDEX_NAME}"
client.indices.create index: INDEX_NAME,
body: {
mappings: {
document: {
properties: {
command: {
type: :text
},
description: {
type: :text,
analyzer: :english
},
manpage: {
type: :text,
analyzer: :english
}
}
}
}
}
end
# Loads the man pages
def load_manpages
all_pages = `apropos .`.split "\n"
all_pages.each do |line|
matches = APROPOS_REGEX.match line
command = matches[1]
description = matches[2]
manpage = `man #{command}`
client.index index: INDEX_NAME,
type: :document,
body: {
command: command,
description: description,
manpage: manpage
}
end
end
# Searches the index
def search(term)
result = client.search index: INDEX_NAME,
size: @elasticseach_search_results_size,
body: {
query: {
multi_match: {
query: term,
type: :cross_fields,
fields: ['command', 'description^3', 'manpage^3'],
operator: :or,
tie_breaker: 0.1,
minimum_should_match: '40%',
cutoff_frequency: 0.1
}
}
}
result['hits']['hits'].map{ |hit| { command: hit['_source']['command'],
description: hit['_source']['description'],
manpage: hit['_source']['manpage'] } }
end
# Displays the man page of a selection
def display_manpage_for_selection(selection, query)
IO.popen('less', 'w') do |f|
f.puts @results[selection][:manpage]
end
prompt_for_selection(query)
end
def truncate(str)
if str.length > 70
"#{str[0..67]}..."
else
str
end
end
# Displays the current matches and prompts for user selection
def prompt_for_selection(query)
puts @results.map.with_index { |result, index| "#{index}: #{result[:command].ljust(15)} #{truncate(result[:description])}" } unless query.empty?
if query.empty?
puts "Type a query or q to exit:"
elsif @results.size == 0
puts "No man pages found matching your query. Type a new query or q to exit:"
else
puts "Type a number for the corresponding manpage, q to exit or a new query:"
end
@selected = $stdin.gets.chop
exit 0 if @selected == 'q'
begin
@selected = Integer(@selected)
raise 'invalid command number' if @selected < 0 || @selected > @results.size - 1
display_manpage_for_selection @selected, query
rescue ArgumentError => e
# New query
handle_search @selected
rescue StandardError => e
puts "Invalid selection - #{e.message}"
prompt_for_selection(query)
end
end
# Utility method to access the elasticseach client
def client
@client ||= Elasticsearch::Client.new host: @elasticsearch_host,
port: @elasticsearch_port
end
def load_configuration
configuration = YAML::load_file(CONFIGURATION_FILE)
@elasticsearch_host = configuration[:elasticsearch][:host]
@elasticsearch_port = configuration[:elasticsearch][:port]
@elasticseach_search_results_size = configuration[:elasticsearch][:search_results_size]
end
create_default_configuration_file unless File.exists?(CONFIGURATION_FILE)
load_configuration
# Use option parser to display info
OptionParser.new do |opts|
opts.banner = "Usage: elman [options] query"
opts.separator ""
opts.separator "Specific options:"
opts.on('-s', '--setup', 'Setup elman - (re)creates the index and loads all man pages') do
delete_index
create_index
load_manpages
exit 0
end
opts.on_tail('-h', '--help', 'Show this message') do
puts opts
exit 0
end
end.parse!
# Searches the given query
def handle_search(query)
@results = search query unless query.empty?
prompt_for_selection(query)
end
handle_search ARGV.join ' '