You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

89 lines
2.4 KiB

  1. #! /usr/bin/env python3
  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 as 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 as 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), end=' ')
  59. fp.close()
  60. def processdir(dir, listnames):
  61. try:
  62. names = os.listdir(dir)
  63. except os.error as 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(key=os.path.normcase)
  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())