|
38 | 38 | import time |
39 | 39 | import zlib |
40 | 40 | import base64 |
| 41 | +try: |
| 42 | + import importlib.metadata |
| 43 | + HAVE_IMPLIB_METADATA = True |
| 44 | +except ImportError: |
| 45 | + HAVE_IMPLIB_METADATA = False |
41 | 46 |
|
42 | 47 | from osgeo import gdal |
43 | 48 |
|
@@ -176,14 +181,57 @@ def makeAutomaticFields(): |
176 | 181 | moduleVersionDict[toplevelModname] = "Unknown" |
177 | 182 |
|
178 | 183 | if len(moduleVersionDict) > 0: |
179 | | - for modname in moduleVersionDict: |
| 184 | + moduleVersionDictKeys = list(moduleVersionDict.keys()) |
| 185 | + for modname in moduleVersionDictKeys: |
180 | 186 | if hasattr(sys.modules[modname], '__version__'): |
181 | 187 | moduleVersionDict[modname] = str(sys.modules[modname].__version__) |
| 188 | + else: |
| 189 | + (distributionName, verStr) = versionFromDistribution(modname) |
| 190 | + if None not in (distributionName, verStr): |
| 191 | + moduleVersionDict[distributionName] = verStr |
| 192 | + # If distribution name is different, remove modname |
| 193 | + if modname != distributionName: |
| 194 | + moduleVersionDict.pop(modname) |
| 195 | + |
182 | 196 | dictn['package_version_dict'] = json.dumps(moduleVersionDict) |
183 | 197 |
|
184 | 198 | return dictn |
185 | 199 |
|
186 | 200 |
|
| 201 | +def versionFromDistribution(modname): |
| 202 | + """ |
| 203 | + If possible, deduce a package version number for the given |
| 204 | + module/package name, using distribution metadata. |
| 205 | +
|
| 206 | + If available, return a tuple of (distributionName, versionStr) |
| 207 | + Note that the distribution name may not be the same as the |
| 208 | + module or package name. |
| 209 | +
|
| 210 | + If unavailable for any reason, return (None, None). |
| 211 | +
|
| 212 | + """ |
| 213 | + nullReturn = (None, None) |
| 214 | + |
| 215 | + # The importlib.metadata module was only introduced in Python 3.8 |
| 216 | + if not HAVE_IMPLIB_METADATA: |
| 217 | + return nullReturn |
| 218 | + pkgs = importlib.metadata.packages_distributions() |
| 219 | + distNameList = pkgs.get(modname) |
| 220 | + if distNameList is None: |
| 221 | + return nullReturn |
| 222 | + if len(distNameList) == 0: |
| 223 | + return nullReturn |
| 224 | + distName = distNameList[0] |
| 225 | + try: |
| 226 | + verStr = importlib.metadata.version(distName) |
| 227 | + except importlib.metadata.PackageNotFoundError: |
| 228 | + verStr = None |
| 229 | + if verStr is None: |
| 230 | + return nullReturn |
| 231 | + |
| 232 | + return (distName, verStr) |
| 233 | + |
| 234 | + |
187 | 235 | def writeHistoryToFile(userDict={}, parents=[], *, filename=None, gdalDS=None): |
188 | 236 | """ |
189 | 237 | Make the full processing history and save to the given file. |
|
0 commit comments