Skip to content

Instantly share code, notes, and snippets.

@dhconnelly
Created October 23, 2013 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dhconnelly/7119532 to your computer and use it in GitHub Desktop.
Save dhconnelly/7119532 to your computer and use it in GitHub Desktop.
find a string in a file's include set
#!/usr/bin/env python2.7
import itertools
import sys
def contains(filename, string):
'''Determine whether a file contains a string.'''
with open(filename) as f:
for num, line in zip(itertools.count(1), f.readlines()):
if string in line:
return filename, num, line
return False
def includes(filename):
'''Generate the relative includes of a file.'''
with open(filename) as f:
for line in f:
if line.startswith('#include "'):
yield line[line.index('"')+1:line.rindex('"')]
def explore(filename, string):
'''Find the first ocurrence of a string in a file's includes.'''
try:
result = contains(filename, string)
if result:
return result
for include in includes(filename):
found = explore(include, string)
if found:
return found
except:
pass
return False
if __name__ == '__main__':
try:
filename, string = sys.argv[1], sys.argv[2]
except:
print 'Usage: finddecl.py filename string'
sys.exit(1)
found = explore(filename, string)
if found:
print '%s:%d %s' % found
sys.exit(0 if found else 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment