Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env ruby
- #
- # a perl/ack in ruby
- # (with less features and less good)
- #
- # (license is the MIT one)
- #
- # TODO
- # [ ] -i (ignore case)
- require 'set'
- #
- # USAGE
- def print_usage
- puts %{
- akr [options] {regex} [start_path]
- }
- end
- #
- # COLORS
- def color (colcode, s)
- STDOUT.tty? ? "[#{colcode}m#{s}[0m" : s
- end
- def green (s)
- color(32, s)
- end
- def red (s)
- color(31, s)
- end
- def puts_line (l, reg)
- # TODO : what if regex starts with ^ ?
- i = 0
- loop do
- ll = l[i..-1]
- break unless ll
- if m = reg.match(ll)
- print(red(m[0]))
- i = i + m[0].length
- else
- print(l[i, 1])
- i = i + 1
- end
- end
- #puts
- end
- def scan_file (regex, before, after, path)
- ls = Set.new
- lines = File.readlines(path)
- lines.each_with_index do |line, i|
- if regex.match(line)
- ls << i
- (1..before).to_a.each { |d| ls << (i - d) }
- (1..after).to_a.each { |d| ls << (i + d) }
- end
- end
- return false if ls.size < 1
- puts
- puts(green(path))
- prev = false
- reg = Regexp.compile("^#{regex.to_s}")
- ls.sort.each do |i|
- next if i < 0
- puts '--' if prev && (i - prev > 1)
- prev = (before > 0 || after > 0) ? i : false
- ln = i + 1
- line = lines[i]
- next unless line
- print "#{ln}"
- print regex.match(line) ? ':' : '-'
- print ' '
- print ' ' * (4 - ln.to_s.length)
- puts_line(line, reg)
- end
- true
- end
- #
- # handling params
- offset = 0
- options = {}
- loop do
- a = ARGV[offset]
- break unless a.match(/^-/)
- options[a] = ARGV[offset + 1]
- offset += 2
- end
- before = options['-B'] || 0
- after = options['-A'] || 0
- if c = options['-C']
- before = after = c
- end
- before = before.to_i
- after = after.to_i
- regex = ARGV[offset]
- regex = Regexp.compile(regex)
- #regex = Regexp.compile("^(.*)#{regex}(.*)$")
- spath = ARGV[offset + 1]
- if regex == nil
- print_usage
- exit(1)
- end
- #
- # do it ...
- glob = spath ?
- File.join(spath, '**', '*') :
- File.join('**', '*')
- exit_code = 1
- Dir[glob].each do |path|
- next if File.directory?(path)
- scan_file(regex, before, after, path) && exit_code = 0
- end
- exit(exit_code)
- # 0 if there was a match, 1 else
Add Comment
Please, Sign In to add comment