#!/usr/bin/env ruby
# -*- ruby -*-
#
# Does a google command line search
#
# See file for options
#
# Created: Thu May 10 07:00:52 2007
#
require 'net/http'
require 'cgi'
def scan(page, re, host)
h = Net::HTTP.new(host, 80)
resp, data = h.get(page, nil)
if resp.message == "OK"
lines = data.split /
]+>/, "")
res = res.gsub(/&[^;]+;/, "")
return res
end
########## Main ##########
# intro
puts "Welcome to Loogle, please type in a query or 'q' to quit!"
# save links and titles here
titles = []
links = []
# prompt
while true do
if ARGV.empty?
print "> "
STDOUT.flush
line = STDIN.readline
else
line = ARGV.shift
end
line = line.gsub(/^\s+/,"")
line = line.gsub(/\s+$/,"")
break if line == 'q'
# maybe this is a number
if (/\d+/.match(line) && links.length > 0) then
title = titles[line.to_i]
link = links[line.to_i]
puts "opening " + title + "..."
system "open", link
next
end
# make the request
host = "www.google.com"
page = "/search?q=" + CGI.escape(line)
i = 1
scan(page, /
]*>(.*)<\/a><\/h2>.*([^\s]+)\s+-[^<]*<\/span>/mi, host) { |x|
title = no_tags x[0]
link = no_tags x[1]
print " " if i < 10
small_link = link.gsub(/http.?:\/\//,"")
small_link = link.gsub(/\/.*/,"")
space = " "
space += " " if i < 10
puts "[" + i.to_s + "] " + title + "\n" + space + "- " + small_link + ""
titles.push title
link = "http://" + link if !/^http.*/.match(link)
links.push link
i += 1
}
end
# we're done
puts "bye!"