Skip to content

Instantly share code, notes, and snippets.

@TravisBallard
Created July 11, 2017 18:39
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 TravisBallard/8b28a6db94a1d1861669a45173b004ec to your computer and use it in GitHub Desktop.
Save TravisBallard/8b28a6db94a1d1861669a45173b004ec to your computer and use it in GitHub Desktop.
Search our codebase for certain strings and output a report with the line number and file for each
#!/bin/env python
import os
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-q", "--quiet", dest="verbose", action="store_false", default=True, help="don't print status messages to stdout.")
parser.add_option("-p", "--path", dest="path", type="string", default="/Users/tballard/Sites/csod", help="The path to run the inspection on.")
parser.add_option("-t", "--text", dest="text", type="string", default="", help="The string to search for. Only 1 string at a time.")
parser.add_option("-o", "--output-file", dest="output_file", type="string", default="csodfind-report.txt", help="the output file to save to. default is non-us-report.txt")
parser.add_option("--strip-path", dest="strip_path", action="store_true", default=False, help="Strip path (-p/--path) from file paths in report.")
parser.add_option("-n", "--no-write", dest="nowrite", action="store_true", default=False, help="don't write output to a file.")
(options, args) = parser.parse_args()
found_files = 0
has_found_files = False
if not options.nowrite:
write_file = open(options.output_file, "w")
for root, dir, files in os.walk(options.path):
for file in files:
# open files to inspect for js references
if file.endswith((".php", ".inc", ".theme", ".module", ".info")):
file_to_inspect = os.path.join(root, file)
line_number = 0
has_matches = False
matched_lines = []
with open(file_to_inspect) as searchfile:
for line in searchfile:
line_number += 1
if options.strip_path:
file_to_inspect = file_to_inspect.replace(options.path, "")
if options.text in line:
has_matches = True
has_found_files = True
found_line_output = "\t [L:" + str(line_number) + "] " + line
matched_lines.append(found_line_output)
if has_matches:
found_files += 1
if options.verbose and has_matches:
print("%d: %s" % (found_files, file_to_inspect))
for line in matched_lines:
print(line)
if not options.nowrite and has_matches:
write_file.write("%d: %s\n" % (found_files, file_to_inspect))
for line in matched_lines:
write_file.write(line)
write_file.write("\n")
if not options.nowrite:
write_file.close()
if not has_found_files:
print("Nothing Found.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment