78 lines
2.2 KiB
Ruby
Raw Normal View History

require "cmd/search"
2016-09-24 13:52:43 +02:00
module Hbc
class CLI
2017-05-20 19:08:03 +02:00
class Search < AbstractCommand
2017-05-20 03:44:21 +02:00
def run
if args.empty?
2018-04-14 11:32:29 +02:00
puts Formatter.columns(CLI.nice_listing(Cask.map(&:qualified_token)))
else
results = self.class.search(*args)
self.class.render_results(*results)
end
2016-09-24 13:52:43 +02:00
end
2016-08-18 22:11:42 +03:00
2016-09-24 13:52:43 +02:00
def self.extract_regexp(string)
if string =~ %r{^/(.*)/$}
Regexp.last_match[1]
else
false
end
end
2016-08-18 22:11:42 +03:00
2016-09-24 13:52:43 +02:00
def self.search(*arguments)
partial_matches = []
search_term = arguments.join(" ")
search_regexp = extract_regexp arguments.first
2018-04-14 11:32:29 +02:00
all_tokens = CLI.nice_listing(Cask.map(&:qualified_token))
2016-09-24 13:52:43 +02:00
if search_regexp
search_term = arguments.first
partial_matches = all_tokens.grep(/#{search_regexp}/i)
2016-09-24 13:52:43 +02:00
else
simplified_tokens = all_tokens.map { |t| t.sub(%r{^.*\/}, "").gsub(/[^a-z0-9]+/i, "") }
simplified_search_term = search_term.sub(/\.rb$/i, "").gsub(/[^a-z0-9]+/i, "")
partial_matches = simplified_tokens.grep(/#{simplified_search_term}/i) { |t| all_tokens[simplified_tokens.index(t)] }
2016-09-24 13:52:43 +02:00
end
_, remote_matches = Homebrew.search_taps(search_term, silent: true)
[partial_matches, remote_matches, search_term]
2016-09-24 13:52:43 +02:00
end
2016-08-18 22:11:42 +03:00
def self.render_results(partial_matches, remote_matches, search_term)
unless $stdout.tty?
puts [*partial_matches, *remote_matches]
return
end
if partial_matches.empty? && remote_matches.empty?
2016-09-24 13:52:43 +02:00
puts "No Cask found for \"#{search_term}\"."
return
end
2016-10-24 17:07:57 +02:00
unless partial_matches.empty?
if extract_regexp search_term
ohai "Regexp Matches"
else
ohai "Matches"
end
puts Formatter.columns(partial_matches.map(&method(:highlight_installed)))
2016-09-24 13:52:43 +02:00
end
return if remote_matches.empty?
ohai "Remote Matches"
puts Formatter.columns(remote_matches.map(&method(:highlight_installed)))
2016-08-18 22:11:42 +03:00
end
def self.highlight_installed(token)
return token unless Cask.new(token).installed?
pretty_installed token
end
2016-09-24 13:52:43 +02:00
def self.help
"searches all known Casks"
end
end
2016-08-18 22:11:42 +03:00
end
end