packer.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. # Copyright (c) 2014-present PlatformIO <contact@platformio.org>
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import base64
  15. import io
  16. import os
  17. import re
  18. import shutil
  19. import subprocess
  20. import tempfile
  21. import zipfile
  22. from pioinstaller import util
  23. def create_wheels(package_dir, dest_dir):
  24. subprocess.call(["pip", "wheel", "--wheel-dir", dest_dir, "."], cwd=package_dir)
  25. def pack(target):
  26. assert isinstance(target, str)
  27. if os.path.isdir(target):
  28. target = os.path.join(target, "get-platformio.py")
  29. if not os.path.isdir(os.path.dirname(target)):
  30. os.makedirs(os.path.dirname(target))
  31. tmp_dir = tempfile.mkdtemp()
  32. create_wheels(os.path.dirname(util.get_source_dir()), tmp_dir)
  33. new_data = io.BytesIO()
  34. for whl in os.listdir(tmp_dir):
  35. with zipfile.ZipFile(os.path.join(tmp_dir, whl)) as existing_zip:
  36. with zipfile.ZipFile(new_data, mode="a") as new_zip:
  37. for zinfo in existing_zip.infolist():
  38. if re.search(r"\.dist-info/", zinfo.filename):
  39. continue
  40. new_zip.writestr(zinfo, existing_zip.read(zinfo))
  41. zipdata = base64.b64encode(new_data.getvalue()).decode("utf8")
  42. with open(target, "w") as fp:
  43. with open(os.path.join(util.get_source_dir(), "pack", "template.py")) as fptlp:
  44. fp.write(fptlp.read().format(zipfile_content=zipdata))
  45. # Ensure the permissions on the newly created file
  46. oldmode = os.stat(target).st_mode & 0o7777
  47. newmode = (oldmode | 0o555) & 0o7777
  48. os.chmod(target, newmode)
  49. # Clearing up
  50. shutil.rmtree(tmp_dir)
  51. return target