Guest User

Untitled

a guest
Jan 3rd, 2013
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.51 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- encoding: utf-8 -*-
  3. # file: unusedCodeSearch.py
  4.  
  5. '''
  6.    all the imports
  7. '''
  8. import os, sys, fnmatch
  9.  
  10.  
  11. '''
  12.    all defines
  13. '''
  14. headers="--hxx"
  15. sources="--cxx"
  16.  
  17.  
  18. '''
  19.    all the functions
  20. '''
  21. # always return a list with 3 objects: extension, type, and path
  22. def validParameters():
  23.     nParam = len(sys.argv)-1
  24.     sourceExtensions = ['any','c','h','cxx','hxx','java','mm']
  25.     typeExtensions   = ['macros','classes']
  26.     paramReceived = []
  27.  
  28.     if not nParam or nParam > 3:
  29.         print ("Invalid syntax. Try --help")
  30.         sys.exit(1)
  31.  
  32.  
  33.     # new code
  34.     if nParam == 1:
  35.         if str(sys.argv[1]) == "-h" or str(sys.argv[1]) == "--help":
  36.             helpMessage()
  37.         else:
  38.             print ("Invalid syntax. Try --help ")
  39.             sys.exit(1)
  40.  
  41.     elif nParam == 2:
  42.         paramA = sys.argv[1].split('=')
  43.         paramB = sys.argv[2].split('=')
  44.         if str(sys.argv[1]) == "-h" or str(sys.argv[1]) == "--help":
  45.             print ("For help inform only --help or -h")
  46.             sys.exit(1)
  47.  
  48.         if len(paramA) != 2:
  49.             print ("Unrecognized option: " + paramA + ", try --help")
  50.             sys.exit(1)
  51.         if len(paramB) != 2:
  52.             print ("Unrecognized option: " + paramB + ", try --help")
  53.             sys.exit(1)
  54.  
  55.         # validate the first options, -s, --source, -t and --type
  56.         if paramA[0] != "-s" and paramA[0] != "--source":
  57.             print ("Unrecognized option: " + sys.argv[1] + ", try --help")
  58.             sys.exit(1)
  59.  
  60.         elif paramB[0] != "-t" and paramB[0] != "--type":
  61.             print ("Unrecognized option: " + sys.argv[2] + ", try --help")
  62.             sys.exit(1)
  63.  
  64.         # validate the extension received
  65.         try:
  66.             index = sourceExtensions.index(paramA[1])
  67.         except ValueError:
  68.             index = -1
  69.         if index == -1:
  70.             print ("Unrecognized extension: " + paramA[1] + ", try --help")
  71.             sys.exit(1)
  72.  
  73.         # validate the type received
  74.         try:
  75.             index = typeExtensions.index(paramB[1])
  76.         except ValueError:
  77.             index = -1
  78.         if index == -1:
  79.             print ("Unrecognized type: " + paramB[1] + ", try --help")
  80.             sys.exit(1)
  81.        
  82.         paramReceived.append(paramA[1])
  83.         paramReceived.append(paramB[1])
  84.         paramReceived.append(getPath())
  85.         return paramReceived
  86.  
  87.     elif nParam == 3:
  88.         paramA = sys.argv[1].split('=')
  89.         paramB = sys.argv[2].split('=')
  90.         paramC = sys.argv[3].split('=')
  91.         if str(sys.argv[1]) == "-h" or str(sys.argv[1]) == "--help":
  92.             print ("For help inform only --help or -h")
  93.             sys.exit(1)
  94.  
  95.         if len(paramA) != 2:
  96.             print ("Unrecognized option: " + str(sys.argv[1]) + ", try --help")
  97.             sys.exit(1)
  98.         if len(paramB) != 2:
  99.             print ("Unrecognized option: " + str(sys.argv[2]) + ", try --help")
  100.             sys.exit(1)
  101.         if len(paramC) != 2:
  102.             print ("Unrecognized option: " + str(sys.argv[3]) + ", try --help")
  103.             sys.exit(1)
  104.  
  105.         if paramA[0] != "-s" and paramA[0] != "--source":
  106.             print ("Unrecognized option: " + sys.argv[1] + ", try --help")
  107.             sys.exit(1)
  108.  
  109.         elif paramB[0] != "-t" and paramB[0] != "--type":
  110.             print ("Unrecognized option: " + sys.argv[2] + ", try --help")
  111.             sys.exit(1)
  112.  
  113.         elif paramC[0] != "-p" and paramC[0] != "--path":
  114.             print ("Unrecognized option: " + sys.argv[3] + ", try --help")
  115.             sys.exit(1)
  116.  
  117.         elif paramA[0] == "-s" or paramA[0] == "--source" and paramB[0] == "-t" or paramB[0] == "--type" and paramC[0] == "-p" or paramC[0] == "--path":
  118.  
  119.             # validate the extension received
  120.             try:
  121.                 index = sourceExtensions.index(paramA[1])
  122.             except ValueError:
  123.                 index = -1
  124.             if index == -1:
  125.                 print ("Unrecognized source extension: " + paramA[1] + ", try --help")
  126.                 sys.exit(1)
  127.  
  128.             # validate the type received
  129.             try:
  130.                 index = typeExtensions.index(paramB[1])
  131.             except ValueError:
  132.                 index = -1
  133.             if index == -1:
  134.                 print ("Unrecognized type: " + paramB[1] + ", try --help")
  135.                 sys.exit(1)
  136.  
  137.             # validate the path received
  138.             if not os.path.isdir(paramC[1]):
  139.                 print ("Invalid path: " + str(paramC[1]))
  140.                 sys.exit(1)
  141.                
  142.             paramReceived.append(paramA[1])
  143.             paramReceived.append(paramB[1])
  144.             paramReceived.append(paramC[1])
  145.             return paramReceived
  146.  
  147.  
  148. def getPath():
  149.     path = os.getcwd()
  150.     return path
  151.  
  152. def createList(directory, pattern):
  153.     # code and credits by http://stackoverflow.com/questions/2186525/use-a-glob-to-find-files-recursively-in-python
  154.     def find_files(directory, pattern):
  155.         for root, dirs, files in os.walk(directory):
  156.             for basename in files:
  157.                 if fnmatch.fnmatch(basename, pattern):
  158.                     filename = os.path.join(root, basename)
  159.                     yield filename
  160.     fullList = []
  161.     for filename in find_files(directory, pattern):
  162.         fullList.append(filename)
  163.  
  164.     return fullList
  165.  
  166. def helpMessage():
  167.     print ("Usage:\n")
  168.     print ("python unusedCodeSearch.py --source=x --type=x --path=x\n")
  169.     print ("Sources: Any extension file")
  170.     print (" -s  or  --source=cxx        - Search in cxx files only")
  171.     print (" -s  or  --source=hxx        - Search in hxx files only")
  172.     print (" -s  or  --source=java       - Search in java files only")
  173.     print (" -s  or  --source=any        - Search in any file")
  174.     print (" PS: By now, valid extensions can be: any, c, h, cxx, hxx, java, mm\n")
  175.     print ("Types: Can be macro or method by now")
  176.     print (" -t  or  --type=macros       - Search for macros")
  177.     print (" -t  or  --type=classes      - Search for methods\n")
  178.     print ("Path: the path where you want looking for")
  179.     print (" PS 1: Works fine for relative or absolut path.")
  180.     print (" PS 2: If no path was informed, current folder will be used instead.\n")
  181.     print (" -p  or  --path=$HOME        - Search from $HOME\n")
  182.     print (" -h  or  --help              - Show this message.\n")
  183.     sys.exit(0)
  184.    
  185.  
  186. def removeEmpty(fullList, sourceType):
  187.     if sourceType == "macros":
  188.         lookFor = "#define"
  189.     elif sourceType == "classes":
  190.         lookFor = "class"
  191.  
  192.     for eachFile in fullList:
  193.         aFile = open(eachFile, "r")
  194.         index = []
  195.         count = 0
  196.         for line in aFile:
  197.             if line.startswith( lookFor ):
  198.                 index.append(count)
  199.             count += 1
  200.  
  201.         # verify until 3 lines before the #define line if there is an line starting with #if (#ifdef, #ifndef)
  202.         aFile.seek(0)
  203.         count = 0
  204.         index2 = []
  205.         for position in index:
  206.             count = position - 3
  207.             read = 0
  208.             while read < count:
  209.                 t = aFile.readline()
  210.                 read += 1
  211.             if "#if" in aFile.readline():
  212.                 index2.append("it's on line 1")
  213.             elif "#if" in aFile.readline():
  214.                 index2.append("it's on line 2")
  215.             elif "#if" in aFile.readline():
  216.                 index2.append("it's on line 3")
  217.  
  218.         # if index2 is empty, there is any #if before #define, and if not, ... miss code here :P
  219.  
  220.  
  221.  
  222. '''
  223.    script begin
  224. '''
  225. # validate the input parameters and inform a message
  226. paramReceived = validParameters()
  227. searchIn      = paramReceived[0]
  228. searchFor     = paramReceived[1]
  229. searchWhere   = paramReceived[2]
  230. print ("Search in "  + str(searchIn)    + " files.")
  231. print ("Search for " + str(searchFor))
  232. print ("Search in "  + str(searchWhere) + " folder.\n")
  233.  
  234. if searchIn == "any":
  235.     searchIn = "*.*"
  236. else:
  237.     searchIn = "*." + searchIn
  238.  
  239. fullList = createList(searchWhere, searchIn)
  240.  
  241. if not len(fullList):
  242.     print (" No files found!")
  243.     tStop = False
  244. else:
  245.     print (str(len(fullList)) + " files found!")
  246.     tStop = True
  247.  
  248.  
  249. if searchFor == "macros" and tStop:
  250.     print ("Now looking for macros.")
  251.     # remove files which don't have #defines
  252.     newList = removeEmpty(fullList, searchFor)
  253.  
  254. elif searchFor == "classes" and tStop:
  255.     print ("Now looking for methods.")
  256.     # remove files which don't have classes
  257.     newList = removeEmpty(fullList, searchFor)
  258.    
  259. '''  Test line '''
Advertisement
Add Comment
Please, Sign In to add comment