/Tools/scripts/finddiv.py

http://unladen-swallow.googlecode.com/ · Python · 89 lines · 67 code · 7 blank · 15 comment · 23 complexity · 468e339968a7e3a2dbf873864aec8801 MD5 · raw file

  1. #! /usr/bin/env python
  2. """finddiv - a grep-like tool that looks for division operators.
  3. Usage: finddiv [-l] file_or_directory ...
  4. For directory arguments, all files in the directory whose name ends in
  5. .py are processed, and subdirectories are processed recursively.
  6. This actually tokenizes the files to avoid false hits in comments or
  7. strings literals.
  8. By default, this prints all lines containing a / or /= operator, in
  9. grep -n style. With the -l option specified, it prints the filename
  10. of files that contain at least one / or /= operator.
  11. """
  12. import os
  13. import sys
  14. import getopt
  15. import tokenize
  16. def main():
  17. try:
  18. opts, args = getopt.getopt(sys.argv[1:], "lh")
  19. except getopt.error, msg:
  20. usage(msg)
  21. return 2
  22. if not args:
  23. usage("at least one file argument is required")
  24. return 2
  25. listnames = 0
  26. for o, a in opts:
  27. if o == "-h":
  28. print __doc__
  29. return
  30. if o == "-l":
  31. listnames = 1
  32. exit = None
  33. for filename in args:
  34. x = process(filename, listnames)
  35. exit = exit or x
  36. return exit
  37. def usage(msg):
  38. sys.stderr.write("%s: %s\n" % (sys.argv[0], msg))
  39. sys.stderr.write("Usage: %s [-l] file ...\n" % sys.argv[0])
  40. sys.stderr.write("Try `%s -h' for more information.\n" % sys.argv[0])
  41. def process(filename, listnames):
  42. if os.path.isdir(filename):
  43. return processdir(filename, listnames)
  44. try:
  45. fp = open(filename)
  46. except IOError, msg:
  47. sys.stderr.write("Can't open: %s\n" % msg)
  48. return 1
  49. g = tokenize.generate_tokens(fp.readline)
  50. lastrow = None
  51. for type, token, (row, col), end, line in g:
  52. if token in ("/", "/="):
  53. if listnames:
  54. print filename
  55. break
  56. if row != lastrow:
  57. lastrow = row
  58. print "%s:%d:%s" % (filename, row, line),
  59. fp.close()
  60. def processdir(dir, listnames):
  61. try:
  62. names = os.listdir(dir)
  63. except os.error, msg:
  64. sys.stderr.write("Can't list directory: %s\n" % dir)
  65. return 1
  66. files = []
  67. for name in names:
  68. fn = os.path.join(dir, name)
  69. if os.path.normcase(fn).endswith(".py") or os.path.isdir(fn):
  70. files.append(fn)
  71. files.sort(lambda a, b: cmp(os.path.normcase(a), os.path.normcase(b)))
  72. exit = None
  73. for fn in files:
  74. x = process(fn, listnames)
  75. exit = exit or x
  76. return exit
  77. if __name__ == "__main__":
  78. sys.exit(main())