Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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.

gencache.py 27KB

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