I'm working on a search utility that searches through source files. It's only the beginning of the project. It lacks a lot of features, but a backbone of the project works and it would be great if you can take a look at it.
path, keyword = ARGV if ARGV.length == 2
if ARGV.length != 2
puts "Not enough argumetns. Type 'finder --help' for help"
abort if ARGV.length != 2
end
IGNORED_DIRS = ['..', '.', '.git', 'blib', '_build', '.bzr', '.cdv', 'cover_db',
'__pycache', 'CVS', '_darcs', '~.dep', '~.dot', '.hg', '~.nib', '.pc', '~.plst', 'RCS', 'SCCS',
'_sgbak', '.svn', '.tox','.metadata', '.cover']
# colorize output
class String
def black; "\033[30m#{self}\033[0m" end
def red; "\033[31m#{self}\033[0m" end
def green; "\033[32m#{self}\033[0m" end
def brown; "\033[33m#{self}\033[0m" end
def blue; "\033[34m#{self}\033[0m" end
def magenta; "\033[35m#{self}\033[0m" end
def cyan; "\033[36m#{self}\033[0m" end
def gray; "\033[37m#{self}\033[0m" end
def bg_black; "\033[40m#{self}\033[0m" end
def bg_red; "\033[41m#{self}\033[0m" end
def bg_green; "\033[42m#{self}\033[0m" end
def bg_brown; "\033[43m#{self}\033[0m" end
def bg_blue; "\033[44m#{self}\033[0m" end
def bg_magenta; "\033[45m#{self}\033[0m" end
def bg_cyan; "\033[46m#{self}\033[0m" end
def bg_gray; "\033[47m#{self}\033[0m" end
def bold; "\033[1m#{self}\033[22m" end
def reverse_color; "\033[7m#{self}\033[27m" end
end
# convert given path to full path
# which can be used in 'Dir.chdir()'
def expand_path(path)
case path
when '.'
Dir.pwd
when /~(\/[a-zA-Z\w]*)+/
File.expand_path(path, __FILE__)
when /\.\/[a-z]*/
Dir.pwd + path[1..-1]
when /\/[a-z]*/
Dir.pwd + path
else
puts "Wrong path name"
end
end
def search_in_file(path_to_file, keyword)
f = open(path_to_file)
flag = true
f.each_with_index do |line, i|
if line.include? keyword
# print file name and path
if flag
puts ""
puts path_to_file.bold.blue
flag = false
end
puts "#{i+1}:".bold.gray + " #{line}".sub(keyword, keyword.bg_red)
end
end
end
def file_finder(path, keyword)
Dir.chdir(path)
entries = Dir.entries('.')
entries.each do |item|
unless IGNORED_DIRS.include?(item)
if File.file?(path + "/" + item)
search_in_file(path + "/" + item, keyword)
else
file_finder(path + "/" + item, keyword)
end
end
end
end
file_finder(expand_path(path), keyword)