index.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import hashlib
  2. import os
  3. from operator import attrgetter
  4. from meta.common import polymc_path
  5. from meta.model import MetaVersion, MetaPackage
  6. from meta.model.index import MetaPackageIndex, MetaVersionIndex, MetaVersionIndexEntry, MetaPackageIndexEntry
  7. PMC_DIR = polymc_path()
  8. # take the hash type (like hashlib.md5) and filename, return hex string of hash
  9. def hash_file(hash_fn, file_name):
  10. hash_instance = hash_fn()
  11. with open(file_name, "rb") as f:
  12. for chunk in iter(lambda: f.read(4096), b""):
  13. hash_instance.update(chunk)
  14. return hash_instance.hexdigest()
  15. # ignore these files when indexing versions
  16. ignore = {"index.json", "package.json", ".git", ".github"}
  17. # initialize output structures - package list level
  18. packages = MetaPackageIndex()
  19. # walk thorugh all the package folders
  20. for package in sorted(os.listdir(PMC_DIR)):
  21. if package in ignore:
  22. continue
  23. sharedData = MetaPackage.parse_file(os.path.join(PMC_DIR, package, "package.json"))
  24. recommendedVersions = set()
  25. if sharedData.recommended:
  26. recommendedVersions = set(sharedData.recommended)
  27. # initialize output structures - version list level
  28. versionList = MetaVersionIndex(uid=package, name=sharedData.name)
  29. # walk through all the versions of the package
  30. for filename in os.listdir(PMC_DIR + "/%s" % package):
  31. if filename in ignore:
  32. continue
  33. # parse and hash the version file
  34. filepath = PMC_DIR + "/%s/%s" % (package, filename)
  35. filehash = hash_file(hashlib.sha256, filepath)
  36. versionFile = MetaVersion.parse_file(filepath)
  37. is_recommended = versionFile.version in recommendedVersions
  38. versionEntry = MetaVersionIndexEntry.from_meta_version(versionFile, is_recommended, filehash)
  39. versionList.versions.append(versionEntry)
  40. # sort the versions in descending order by time of release
  41. versionList.versions = sorted(versionList.versions, key=attrgetter('release_time'), reverse=True)
  42. # write the version index for the package
  43. outFilePath = PMC_DIR + "/%s/index.json" % package
  44. versionList.write(outFilePath)
  45. # insert entry into the package index
  46. packageEntry = MetaPackageIndexEntry(
  47. uid=package,
  48. name=sharedData.name,
  49. sha256=hash_file(hashlib.sha256, outFilePath)
  50. )
  51. packages.packages.append(packageEntry)
  52. packages.write(os.path.join(PMC_DIR, "index.json"))