gencache.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  1. """Manages the cache of generated Python code.
  2. Description
  3. This file manages the cache of generated Python code. When run from the
  4. command line, it also provides a number of options for managing that cache.
  5. Implementation
  6. Each typelib is generated into a filename of format "{guid}x{lcid}x{major}x{minor}.py"
  7. An external persistant dictionary maps from all known IIDs in all known type libraries
  8. to the type library itself.
  9. Thus, whenever Python code knows the IID of an object, it can find the IID, LCID and version of
  10. the type library which supports it. Given this information, it can find the Python module
  11. with the support.
  12. If necessary, this support can be generated on the fly.
  13. Hacks, to do, etc
  14. Currently just uses a pickled dictionary, but should used some sort of indexed file.
  15. Maybe an OLE2 compound file, or a bsddb file?
  16. """
  17. import pywintypes, os, sys
  18. import pythoncom
  19. import win32com, win32com.client
  20. import glob
  21. import traceback
  22. import CLSIDToClass
  23. import operator
  24. try:
  25. from imp import reload # exported by the imp module in py3k.
  26. except:
  27. pass # a builtin on py2k.
  28. bForDemandDefault = 0 # Default value of bForDemand - toggle this to change the world - see also makepy.py
  29. # The global dictionary
  30. clsidToTypelib = {}
  31. # If we have a different version of the typelib generated, this
  32. # maps the "requested version" to the "generated version".
  33. versionRedirectMap = {}
  34. # There is no reason we *must* be readonly in a .zip, but we are now,
  35. # Rather than check for ".zip" or other tricks, PEP302 defines
  36. # a "__loader__" attribute, so we use that.
  37. # (Later, it may become necessary to check if the __loader__ can update files,
  38. # as a .zip loader potentially could - but punt all that until a need arises)
  39. is_readonly = is_zip = hasattr(win32com, "__loader__") and hasattr(win32com.__loader__, "archive")
  40. # A dictionary of ITypeLibrary objects for demand generation explicitly handed to us
  41. # Keyed by usual clsid, lcid, major, minor
  42. demandGeneratedTypeLibraries = {}
  43. import cPickle as pickle
  44. def __init__():
  45. # Initialize the module. Called once explicitly at module import below.
  46. try:
  47. _LoadDicts()
  48. except IOError:
  49. Rebuild()
  50. pickleVersion = 1
  51. def _SaveDicts():
  52. if is_readonly:
  53. raise RuntimeError("Trying to write to a readonly gencache ('%s')!" \
  54. % win32com.__gen_path__)
  55. f = open(os.path.join(GetGeneratePath(), "dicts.dat"), "wb")
  56. try:
  57. p = pickle.Pickler(f)
  58. p.dump(pickleVersion)
  59. p.dump(clsidToTypelib)
  60. finally:
  61. f.close()
  62. def _LoadDicts():
  63. # Load the dictionary from a .zip file if that is where we live.
  64. if is_zip:
  65. import cStringIO as io
  66. loader = win32com.__loader__
  67. arc_path = loader.archive
  68. dicts_path = os.path.join(win32com.__gen_path__, "dicts.dat")
  69. if dicts_path.startswith(arc_path):
  70. dicts_path = dicts_path[len(arc_path)+1:]
  71. else:
  72. # Hm. See below.
  73. return
  74. try:
  75. data = loader.get_data(dicts_path)
  76. except AttributeError:
  77. # The __loader__ has no get_data method. See below.
  78. return
  79. except IOError:
  80. # Our gencache is in a .zip file (and almost certainly readonly)
  81. # but no dicts file. That actually needn't be fatal for a frozen
  82. # application. Assuming they call "EnsureModule" with the same
  83. # typelib IDs they have been frozen with, that EnsureModule will
  84. # correctly re-build the dicts on the fly. However, objects that
  85. # rely on the gencache but have not done an EnsureModule will
  86. # fail (but their apps are likely to fail running from source
  87. # with a clean gencache anyway, as then they would be getting
  88. # Dynamic objects until the cache is built - so the best answer
  89. # for these apps is to call EnsureModule, rather than freezing
  90. # the dict)
  91. return
  92. f = io.BytesIO(data)
  93. else:
  94. # NOTE: IOError on file open must be caught by caller.
  95. f = open(os.path.join(win32com.__gen_path__, "dicts.dat"), "rb")
  96. try:
  97. p = pickle.Unpickler(f)
  98. version = p.load()
  99. global clsidToTypelib
  100. clsidToTypelib = p.load()
  101. versionRedirectMap.clear()
  102. finally:
  103. f.close()
  104. def GetGeneratedFileName(clsid, lcid, major, minor):
  105. """Given the clsid, lcid, major and minor for a type lib, return
  106. the file name (no extension) providing this support.
  107. """
  108. return str(clsid).upper()[1:-1] + "x%sx%sx%s" % (lcid, major, minor)
  109. def SplitGeneratedFileName(fname):
  110. """Reverse of GetGeneratedFileName()
  111. """
  112. return tuple(fname.split('x',4))
  113. def GetGeneratePath():
  114. """Returns the name of the path to generate to.
  115. Checks the directory is OK.
  116. """
  117. assert not is_readonly, "Why do you want the genpath for a readonly store?"
  118. try:
  119. os.makedirs(win32com.__gen_path__)
  120. #os.mkdir(win32com.__gen_path__)
  121. except os.error:
  122. pass
  123. try:
  124. fname = os.path.join(win32com.__gen_path__, "__init__.py")
  125. os.stat(fname)
  126. except os.error:
  127. f = open(fname,"w")
  128. f.write('# Generated file - this directory may be deleted to reset the COM cache...\n')
  129. f.write('import win32com\n')
  130. f.write('if __path__[:-1] != win32com.__gen_path__: __path__.append(win32com.__gen_path__)\n')
  131. f.close()
  132. return win32com.__gen_path__
  133. #
  134. # The helpers for win32com.client.Dispatch and OCX clients.
  135. #
  136. def GetClassForProgID(progid):
  137. """Get a Python class for a Program ID
  138. Given a Program ID, return a Python class which wraps the COM object
  139. Returns the Python class, or None if no module is available.
  140. Params
  141. progid -- A COM ProgramID or IID (eg, "Word.Application")
  142. """
  143. clsid = pywintypes.IID(progid) # This auto-converts named to IDs.
  144. return GetClassForCLSID(clsid)
  145. def GetClassForCLSID(clsid):
  146. """Get a Python class for a CLSID
  147. Given a CLSID, return a Python class which wraps the COM object
  148. Returns the Python class, or None if no module is available.
  149. Params
  150. clsid -- A COM CLSID (or string repr of one)
  151. """
  152. # first, take a short-cut - we may already have generated support ready-to-roll.
  153. clsid = str(clsid)
  154. if CLSIDToClass.HasClass(clsid):
  155. return CLSIDToClass.GetClass(clsid)
  156. mod = GetModuleForCLSID(clsid)
  157. if mod is None:
  158. return None
  159. try:
  160. return CLSIDToClass.GetClass(clsid)
  161. except KeyError:
  162. return None
  163. def GetModuleForProgID(progid):
  164. """Get a Python module for a Program ID
  165. Given a Program ID, return a Python module which contains the
  166. class which wraps the COM object.
  167. Returns the Python module, or None if no module is available.
  168. Params
  169. progid -- A COM ProgramID or IID (eg, "Word.Application")
  170. """
  171. try:
  172. iid = pywintypes.IID(progid)
  173. except pywintypes.com_error:
  174. return None
  175. return GetModuleForCLSID(iid)
  176. def GetModuleForCLSID(clsid):
  177. """Get a Python module for a CLSID
  178. Given a CLSID, return a Python module which contains the
  179. class which wraps the COM object.
  180. Returns the Python module, or None if no module is available.
  181. Params
  182. progid -- A COM CLSID (ie, not the description)
  183. """
  184. clsid_str = str(clsid)
  185. try:
  186. typelibCLSID, lcid, major, minor = clsidToTypelib[clsid_str]
  187. except KeyError:
  188. return None
  189. try:
  190. mod = GetModuleForTypelib(typelibCLSID, lcid, major, minor)
  191. except ImportError:
  192. mod = None
  193. if mod is not None:
  194. sub_mod = mod.CLSIDToPackageMap.get(clsid_str)
  195. if sub_mod is None:
  196. sub_mod = mod.VTablesToPackageMap.get(clsid_str)
  197. if sub_mod is not None:
  198. sub_mod_name = mod.__name__ + "." + sub_mod
  199. try:
  200. __import__(sub_mod_name)
  201. except ImportError:
  202. info = typelibCLSID, lcid, major, minor
  203. # Force the generation. If this typelibrary has explicitly been added,
  204. # use it (it may not be registered, causing a lookup by clsid to fail)
  205. if info in demandGeneratedTypeLibraries:
  206. info = demandGeneratedTypeLibraries[info]
  207. import makepy
  208. makepy.GenerateChildFromTypeLibSpec(sub_mod, info)
  209. # Generate does an import...
  210. mod = sys.modules[sub_mod_name]
  211. return mod
  212. def GetModuleForTypelib(typelibCLSID, lcid, major, minor):
  213. """Get a Python module for a type library ID
  214. Given the CLSID of a typelibrary, return an imported Python module,
  215. else None
  216. Params
  217. typelibCLSID -- IID of the type library.
  218. major -- Integer major version.
  219. minor -- Integer minor version
  220. lcid -- Integer LCID for the library.
  221. """
  222. modName = GetGeneratedFileName(typelibCLSID, lcid, major, minor)
  223. mod = _GetModule(modName)
  224. # If the import worked, it doesn't mean we have actually added this
  225. # module to our cache though - check that here.
  226. if "_in_gencache_" not in mod.__dict__:
  227. AddModuleToCache(typelibCLSID, lcid, major, minor)
  228. assert "_in_gencache_" in mod.__dict__
  229. return mod
  230. def MakeModuleForTypelib(typelibCLSID, lcid, major, minor, progressInstance = None, bForDemand = bForDemandDefault, bBuildHidden = 1):
  231. """Generate support for a type library.
  232. Given the IID, LCID and version information for a type library, generate
  233. and import the necessary support files.
  234. Returns the Python module. No exceptions are caught.
  235. Params
  236. typelibCLSID -- IID of the type library.
  237. major -- Integer major version.
  238. minor -- Integer minor version.
  239. lcid -- Integer LCID for the library.
  240. progressInstance -- Instance to use as progress indicator, or None to
  241. use the GUI progress bar.
  242. """
  243. import makepy
  244. makepy.GenerateFromTypeLibSpec( (typelibCLSID, lcid, major, minor), progressInstance=progressInstance, bForDemand = bForDemand, bBuildHidden = bBuildHidden)
  245. return GetModuleForTypelib(typelibCLSID, lcid, major, minor)
  246. def MakeModuleForTypelibInterface(typelib_ob, progressInstance = None, bForDemand = bForDemandDefault, bBuildHidden = 1):
  247. """Generate support for a type library.
  248. Given a PyITypeLib interface generate and import the necessary support files. This is useful
  249. for getting makepy support for a typelibrary that is not registered - the caller can locate
  250. and load the type library itself, rather than relying on COM to find it.
  251. Returns the Python module.
  252. Params
  253. typelib_ob -- The type library itself
  254. progressInstance -- Instance to use as progress indicator, or None to
  255. use the GUI progress bar.
  256. """
  257. import makepy
  258. try:
  259. makepy.GenerateFromTypeLibSpec( typelib_ob, progressInstance=progressInstance, bForDemand = bForDemandDefault, bBuildHidden = bBuildHidden)
  260. except pywintypes.com_error:
  261. return None
  262. tla = typelib_ob.GetLibAttr()
  263. guid = tla[0]
  264. lcid = tla[1]
  265. major = tla[3]
  266. minor = tla[4]
  267. return GetModuleForTypelib(guid, lcid, major, minor)
  268. def EnsureModuleForTypelibInterface(typelib_ob, progressInstance = None, bForDemand = bForDemandDefault, bBuildHidden = 1):
  269. """Check we have support for a type library, generating if not.
  270. Given a PyITypeLib interface generate and import the necessary
  271. support files if necessary. This is useful for getting makepy support
  272. for a typelibrary that is not registered - the caller can locate and
  273. load the type library itself, rather than relying on COM to find it.
  274. Returns the Python module.
  275. Params
  276. typelib_ob -- The type library itself
  277. progressInstance -- Instance to use as progress indicator, or None to
  278. use the GUI progress bar.
  279. """
  280. tla = typelib_ob.GetLibAttr()
  281. guid = tla[0]
  282. lcid = tla[1]
  283. major = tla[3]
  284. minor = tla[4]
  285. #If demand generated, save the typelib interface away for later use
  286. if bForDemand:
  287. demandGeneratedTypeLibraries[(str(guid), lcid, major, minor)] = typelib_ob
  288. try:
  289. return GetModuleForTypelib(guid, lcid, major, minor)
  290. except ImportError:
  291. pass
  292. # Generate it.
  293. return MakeModuleForTypelibInterface(typelib_ob, progressInstance, bForDemand, bBuildHidden)
  294. def ForgetAboutTypelibInterface(typelib_ob):
  295. """Drop any references to a typelib previously added with EnsureModuleForTypelibInterface and forDemand"""
  296. tla = typelib_ob.GetLibAttr()
  297. guid = tla[0]
  298. lcid = tla[1]
  299. major = tla[3]
  300. minor = tla[4]
  301. info = str(guid), lcid, major, minor
  302. try:
  303. del demandGeneratedTypeLibraries[info]
  304. except KeyError:
  305. # Not worth raising an exception - maybe they dont know we only remember for demand generated, etc.
  306. print "ForgetAboutTypelibInterface:: Warning - type library with info %s is not being remembered!" % (info,)
  307. # and drop any version redirects to it
  308. for key, val in list(versionRedirectMap.items()):
  309. if val==info:
  310. del versionRedirectMap[key]
  311. def EnsureModule(typelibCLSID, lcid, major, minor, progressInstance = None, bValidateFile=not is_readonly, bForDemand = bForDemandDefault, bBuildHidden = 1):
  312. """Ensure Python support is loaded for a type library, generating if necessary.
  313. Given the IID, LCID and version information for a type library, check and if
  314. necessary (re)generate, then import the necessary support files. If we regenerate the file, there
  315. is no way to totally snuff out all instances of the old module in Python, and thus we will regenerate the file more than necessary,
  316. unless makepy/genpy is modified accordingly.
  317. Returns the Python module. No exceptions are caught during the generate process.
  318. Params
  319. typelibCLSID -- IID of the type library.
  320. major -- Integer major version.
  321. minor -- Integer minor version
  322. lcid -- Integer LCID for the library.
  323. progressInstance -- Instance to use as progress indicator, or None to
  324. use the GUI progress bar.
  325. bValidateFile -- Whether or not to perform cache validation or not
  326. bForDemand -- Should a complete generation happen now, or on demand?
  327. bBuildHidden -- Should hidden members/attributes etc be generated?
  328. """
  329. bReloadNeeded = 0
  330. try:
  331. try:
  332. module = GetModuleForTypelib(typelibCLSID, lcid, major, minor)
  333. except ImportError:
  334. # If we get an ImportError
  335. # We may still find a valid cache file under a different MinorVersion #
  336. # (which windows will search out for us)
  337. #print "Loading reg typelib", typelibCLSID, major, minor, lcid
  338. module = None
  339. try:
  340. tlbAttr = pythoncom.LoadRegTypeLib(typelibCLSID, major, minor, lcid).GetLibAttr()
  341. # if the above line doesn't throw a pythoncom.com_error, check if
  342. # it is actually a different lib than we requested, and if so, suck it in
  343. if tlbAttr[1] != lcid or tlbAttr[4]!=minor:
  344. #print "Trying 2nd minor #", tlbAttr[1], tlbAttr[3], tlbAttr[4]
  345. try:
  346. module = GetModuleForTypelib(typelibCLSID, tlbAttr[1], tlbAttr[3], tlbAttr[4])
  347. except ImportError:
  348. # We don't have a module, but we do have a better minor
  349. # version - remember that.
  350. minor = tlbAttr[4]
  351. # else module remains None
  352. except pythoncom.com_error:
  353. # couldn't load any typelib - mod remains None
  354. pass
  355. if module is not None and bValidateFile:
  356. assert not is_readonly, "Can't validate in a read-only gencache"
  357. try:
  358. typLibPath = pythoncom.QueryPathOfRegTypeLib(typelibCLSID, major, minor, lcid)
  359. # windows seems to add an extra \0 (via the underlying BSTR)
  360. # The mainwin toolkit does not add this erroneous \0
  361. if typLibPath[-1]=='\0':
  362. typLibPath=typLibPath[:-1]
  363. suf = getattr(os.path, "supports_unicode_filenames", 0)
  364. if not suf:
  365. # can't pass unicode filenames directly - convert
  366. try:
  367. typLibPath=typLibPath.encode(sys.getfilesystemencoding())
  368. except AttributeError: # no sys.getfilesystemencoding
  369. typLibPath=str(typLibPath)
  370. tlbAttributes = pythoncom.LoadRegTypeLib(typelibCLSID, major, minor, lcid).GetLibAttr()
  371. except pythoncom.com_error:
  372. # We have a module, but no type lib - we should still
  373. # run with what we have though - the typelib may not be
  374. # deployed here.
  375. bValidateFile = 0
  376. if module is not None and bValidateFile:
  377. assert not is_readonly, "Can't validate in a read-only gencache"
  378. filePathPrefix = "%s\\%s" % (GetGeneratePath(), GetGeneratedFileName(typelibCLSID, lcid, major, minor))
  379. filePath = filePathPrefix + ".py"
  380. filePathPyc = filePathPrefix + ".py"
  381. if __debug__:
  382. filePathPyc = filePathPyc + "c"
  383. else:
  384. filePathPyc = filePathPyc + "o"
  385. # Verify that type library is up to date.
  386. # If we have a differing MinorVersion or genpy has bumped versions, update the file
  387. import genpy
  388. if module.MinorVersion != tlbAttributes[4] or genpy.makepy_version != module.makepy_version:
  389. #print "Version skew: %d, %d" % (module.MinorVersion, tlbAttributes[4])
  390. # try to erase the bad file from the cache
  391. try:
  392. os.unlink(filePath)
  393. except os.error:
  394. pass
  395. try:
  396. os.unlink(filePathPyc)
  397. except os.error:
  398. pass
  399. if os.path.isdir(filePathPrefix):
  400. import shutil
  401. shutil.rmtree(filePathPrefix)
  402. minor = tlbAttributes[4]
  403. module = None
  404. bReloadNeeded = 1
  405. else:
  406. minor = module.MinorVersion
  407. filePathPrefix = "%s\\%s" % (GetGeneratePath(), GetGeneratedFileName(typelibCLSID, lcid, major, minor))
  408. filePath = filePathPrefix + ".py"
  409. filePathPyc = filePathPrefix + ".pyc"
  410. #print "Trying py stat: ", filePath
  411. fModTimeSet = 0
  412. try:
  413. pyModTime = os.stat(filePath)[8]
  414. fModTimeSet = 1
  415. except os.error, e:
  416. # If .py file fails, try .pyc file
  417. #print "Trying pyc stat", filePathPyc
  418. try:
  419. pyModTime = os.stat(filePathPyc)[8]
  420. fModTimeSet = 1
  421. except os.error, e:
  422. pass
  423. #print "Trying stat typelib", pyModTime
  424. #print str(typLibPath)
  425. typLibModTime = os.stat(typLibPath)[8]
  426. if fModTimeSet and (typLibModTime > pyModTime):
  427. bReloadNeeded = 1
  428. module = None
  429. except (ImportError, os.error):
  430. module = None
  431. if module is None:
  432. # We need to build an item. If we are in a read-only cache, we
  433. # can't/don't want to do this - so before giving up, check for
  434. # a different minor version in our cache - according to COM, this is OK
  435. if is_readonly:
  436. key = str(typelibCLSID), lcid, major, minor
  437. # If we have been asked before, get last result.
  438. try:
  439. return versionRedirectMap[key]
  440. except KeyError:
  441. pass
  442. # Find other candidates.
  443. items = []
  444. for desc in GetGeneratedInfos():
  445. if key[0]==desc[0] and key[1]==desc[1] and key[2]==desc[2]:
  446. items.append(desc)
  447. if items:
  448. # Items are all identical, except for last tuple element
  449. # We want the latest minor version we have - so just sort and grab last
  450. items.sort()
  451. new_minor = items[-1][3]
  452. ret = GetModuleForTypelib(typelibCLSID, lcid, major, new_minor)
  453. else:
  454. ret = None
  455. # remember and return
  456. versionRedirectMap[key] = ret
  457. return ret
  458. #print "Rebuilding: ", major, minor
  459. module = MakeModuleForTypelib(typelibCLSID, lcid, major, minor, progressInstance, bForDemand = bForDemand, bBuildHidden = bBuildHidden)
  460. # If we replaced something, reload it
  461. if bReloadNeeded:
  462. module = reload(module)
  463. AddModuleToCache(typelibCLSID, lcid, major, minor)
  464. return module
  465. def EnsureDispatch(prog_id, bForDemand = 1): # New fn, so we default the new demand feature to on!
  466. """Given a COM prog_id, return an object that is using makepy support, building if necessary"""
  467. disp = win32com.client.Dispatch(prog_id)
  468. if not disp.__dict__.get("CLSID"): # Eeek - no makepy support - try and build it.
  469. try:
  470. ti = disp._oleobj_.GetTypeInfo()
  471. disp_clsid = ti.GetTypeAttr()[0]
  472. tlb, index = ti.GetContainingTypeLib()
  473. tla = tlb.GetLibAttr()
  474. mod = EnsureModule(tla[0], tla[1], tla[3], tla[4], bForDemand=bForDemand)
  475. GetModuleForCLSID(disp_clsid)
  476. # Get the class from the module.
  477. import CLSIDToClass
  478. disp_class = CLSIDToClass.GetClass(str(disp_clsid))
  479. disp = disp_class(disp._oleobj_)
  480. except pythoncom.com_error:
  481. raise TypeError("This COM object can not automate the makepy process - please run makepy manually for this object")
  482. return disp
  483. def AddModuleToCache(typelibclsid, lcid, major, minor, verbose = 1, bFlushNow = not is_readonly):
  484. """Add a newly generated file to the cache dictionary.
  485. """
  486. fname = GetGeneratedFileName(typelibclsid, lcid, major, minor)
  487. mod = _GetModule(fname)
  488. # if mod._in_gencache_ is already true, then we are reloading this
  489. # module - this doesn't mean anything special though!
  490. mod._in_gencache_ = 1
  491. dict = mod.CLSIDToClassMap
  492. info = str(typelibclsid), lcid, major, minor
  493. for clsid, cls in dict.iteritems():
  494. clsidToTypelib[clsid] = info
  495. dict = mod.CLSIDToPackageMap
  496. for clsid, name in dict.iteritems():
  497. clsidToTypelib[clsid] = info
  498. dict = mod.VTablesToClassMap
  499. for clsid, cls in dict.iteritems():
  500. clsidToTypelib[clsid] = info
  501. dict = mod.VTablesToPackageMap
  502. for clsid, cls in dict.iteritems():
  503. clsidToTypelib[clsid] = info
  504. # If this lib was previously redirected, drop it
  505. if info in versionRedirectMap:
  506. del versionRedirectMap[info]
  507. if bFlushNow:
  508. _SaveDicts()
  509. def GetGeneratedInfos():
  510. zip_pos = win32com.__gen_path__.find(".zip\\")
  511. if zip_pos >= 0:
  512. import zipfile
  513. zip_file = win32com.__gen_path__[:zip_pos+4]
  514. zip_path = win32com.__gen_path__[zip_pos+5:].replace("\\", "/")
  515. zf = zipfile.ZipFile(zip_file)
  516. infos = {}
  517. for n in zf.namelist():
  518. if not n.startswith(zip_path):
  519. continue
  520. base = n[len(zip_path)+1:].split("/")[0]
  521. try:
  522. iid, lcid, major, minor = base.split("x")
  523. lcid = int(lcid)
  524. major = int(major)
  525. minor = int(minor)
  526. iid = pywintypes.IID("{" + iid + "}")
  527. except ValueError:
  528. continue
  529. except pywintypes.com_error:
  530. # invalid IID
  531. continue
  532. infos[(iid, lcid, major, minor)] = 1
  533. zf.close()
  534. return list(infos.keys())
  535. else:
  536. # on the file system
  537. files = glob.glob(win32com.__gen_path__+ "\\*")
  538. ret = []
  539. for file in files:
  540. if not os.path.isdir(file) and not os.path.splitext(file)[1]==".py":
  541. continue
  542. name = os.path.splitext(os.path.split(file)[1])[0]
  543. try:
  544. iid, lcid, major, minor = name.split("x")
  545. iid = pywintypes.IID("{" + iid + "}")
  546. lcid = int(lcid)
  547. major = int(major)
  548. minor = int(minor)
  549. except ValueError:
  550. continue
  551. except pywintypes.com_error:
  552. # invalid IID
  553. continue
  554. ret.append((iid, lcid, major, minor))
  555. return ret
  556. def _GetModule(fname):
  557. """Given the name of a module in the gen_py directory, import and return it.
  558. """
  559. mod_name = "win32com.gen_py.%s" % fname
  560. mod = __import__(mod_name)
  561. return sys.modules[mod_name]
  562. def Rebuild(verbose = 1):
  563. """Rebuild the cache indexes from the file system.
  564. """
  565. clsidToTypelib.clear()
  566. infos = GetGeneratedInfos()
  567. if verbose and len(infos): # Dont bother reporting this when directory is empty!
  568. print "Rebuilding cache of generated files for COM support..."
  569. for info in infos:
  570. iid, lcid, major, minor = info
  571. if verbose:
  572. print "Checking", GetGeneratedFileName(*info)
  573. try:
  574. AddModuleToCache(iid, lcid, major, minor, verbose, 0)
  575. except:
  576. print "Could not add module %s - %s: %s" % (info, sys.exc_info()[0],sys.exc_info()[1])
  577. if verbose and len(infos): # Dont bother reporting this when directory is empty!
  578. print "Done."
  579. _SaveDicts()
  580. def _Dump():
  581. print "Cache is in directory", win32com.__gen_path__
  582. # Build a unique dir
  583. d = {}
  584. for clsid, (typelibCLSID, lcid, major, minor) in clsidToTypelib.iteritems():
  585. d[typelibCLSID, lcid, major, minor] = None
  586. for typelibCLSID, lcid, major, minor in d.iterkeys():
  587. mod = GetModuleForTypelib(typelibCLSID, lcid, major, minor)
  588. print "%s - %s" % (mod.__doc__, typelibCLSID)
  589. # Boot up
  590. __init__()
  591. def usage():
  592. usageString = """\
  593. Usage: gencache [-q] [-d] [-r]
  594. -q - Quiet
  595. -d - Dump the cache (typelibrary description and filename).
  596. -r - Rebuild the cache dictionary from the existing .py files
  597. """
  598. print usageString
  599. sys.exit(1)
  600. if __name__=='__main__':
  601. import getopt
  602. try:
  603. opts, args = getopt.getopt(sys.argv[1:], "qrd")
  604. except getopt.error, message:
  605. print message
  606. usage()
  607. # we only have options - complain about real args, or none at all!
  608. if len(sys.argv)==1 or args:
  609. print usage()
  610. verbose = 1
  611. for opt, val in opts:
  612. if opt=='-d': # Dump
  613. _Dump()
  614. if opt=='-r':
  615. Rebuild(verbose)
  616. if opt=='-q':
  617. verbose = 0