Team Fortress 2 Source Code as on 22/4/2020
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.

83 lines
2.5 KiB

  1. import os
  2. import re
  3. STOP_RECURSING = 23452
  4. class VisitFiles:
  5. """
  6. This is a helper class to visit a bunch of files in a tree given
  7. the regular expressions that will match the filenames you're interested in.
  8. Create this class like a function, and pass in these parameters:
  9. baseDir - a string for the root directory in the search. This must not end in a slash.
  10. fileMasks - a list of strings that contain regular expressions for filenames you want to match.
  11. fileCB - This function is called for each filename matched. It takes these parameters:
  12. - short filename ("blah.txt")
  13. - relative filename ("a/b/c/blah.txt")
  14. - long filename ("c:/basedir/a/b/c/blah.txt")
  15. dirCB - a function called for each directory name. This can be None. If it returns STOP_RECURSING,
  16. then it won't do callbacks for the files and directories under this one.
  17. - relative dirName ("./a/b")
  18. - full dirname (from the baseDir you pass into __init__) ("d:/a/b")
  19. bRecurse - a boolean telling whether or not to recurse into other directories.
  20. Example: This would visit all files recursively (.+ matches any non-zero-length string).
  21. VisitFiles( ".", [".+"], MyCallback )
  22. """
  23. def __init__( self, baseDir, fileMasks, fileCB, dirCB, bRecurse=1 ):
  24. # Handle it appropriately whether they pass 1 filemask or a list of them.
  25. if isinstance( fileMasks, list ):
  26. self.fileMasks = [re.compile( x, re.IGNORECASE ) for x in fileMasks]
  27. else:
  28. self.fileMasks = [re.compile( fileMasks, re.IGNORECASE )]
  29. self.fileCB = fileCB
  30. self.dirCB = dirCB
  31. self.bRecurse = bRecurse
  32. self.__VisitFiles_R( ".", baseDir )
  33. def __RemoveDotSlash( self, name ):
  34. if name[0:2] == '.\\':
  35. return name[2:]
  36. else:
  37. return name
  38. def __VisitFiles_R( self, relativeDirName, baseDirName ):
  39. if self.dirCB:
  40. if self.dirCB( relativeDirName, baseDirName ) == 0:
  41. return
  42. files = os.listdir( baseDirName )
  43. for filename in files:
  44. upperFilename = filename.upper()
  45. fullFilename = self.__RemoveDotSlash( baseDirName + "\\" + filename )
  46. relativeName = self.__RemoveDotSlash( relativeDirName + "\\" + filename )
  47. stats = os.stat( fullFilename )
  48. if stats[0] & (1<<15):
  49. matched = 0
  50. for curRE in self.fileMasks:
  51. if curRE.search( upperFilename ):
  52. matched = 1
  53. break
  54. if matched:
  55. self.fileCB( filename, relativeName, fullFilename )
  56. else:
  57. # It's a directory.
  58. if self.bRecurse:
  59. self.__VisitFiles_R( relativeName, fullFilename )