#!/usr/local/bin/python2.7
############################################################################
#                                                                          #
#                          DSA-HELPERS                                     #
#                                                                          #
#                  Copyright (C) 2008 - 2011 AdaCore                       #
#                                                                          #
# This program is free software: you can redistribute it and/or modify     #
# it under the terms of the GNU General Public License as published by     #
# the Free Software Foundation, either version 3 of the License, or        #
# (at your option) any later version.                                      #
#                                                                          #
# This program is distributed in the hope that it will be useful,          #
# but WITHOUT ANY WARRANTY; without even the implied warranty of           #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            #
# GNU General Public License for more details.                             #
#                                                                          #
# You should have received a copy of the GNU General Public License        #
# along with this program.  If not, see <http://www.gnu.org/licenses/>     #
#                                                                          #
############################################################################

"""Usage: timed_grep <regexp> <file>

Repeatedly runs the specified grep command until either it returns some
data or a timeout occurs.
"""

import re
import sys
import time

regexp = re.compile(sys.argv[1])
filename = sys.argv[2]

delay = 20
matched = False
while delay > 0:
    delay = delay - 1
    with open(filename) as f:
        for line in f:
            if regexp.search(line):
                print line.rstrip()
                matched = True
        if matched:
            sys.exit(0)
        else:
            time.sleep(1)

sys.stderr.write("grep %s %s timed out, file contents:\n" % (
    sys.argv[1], filename))
with open(filename) as f:
    for line in f:
        sys.stderr.write(line)
