install_scripts.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. from __future__ import annotations
  2. import os
  3. import sys
  4. from .._path import ensure_directory
  5. from ..dist import Distribution
  6. import distutils.command.install_scripts as orig
  7. from distutils import log
  8. class install_scripts(orig.install_scripts):
  9. """Do normal script install, plus any egg_info wrapper scripts"""
  10. distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution
  11. def initialize_options(self) -> None:
  12. orig.install_scripts.initialize_options(self)
  13. self.no_ep = False
  14. def run(self) -> None:
  15. self.run_command("egg_info")
  16. if self.distribution.scripts:
  17. orig.install_scripts.run(self) # run first to set up self.outfiles
  18. else:
  19. self.outfiles: list[str] = []
  20. if self.no_ep:
  21. # don't install entry point scripts into .egg file!
  22. return
  23. self._install_ep_scripts()
  24. def _install_ep_scripts(self):
  25. # Delay import side-effects
  26. from .. import _scripts
  27. from .._importlib import metadata
  28. ei_cmd = self.get_finalized_command("egg_info")
  29. dist = metadata.Distribution.at(path=ei_cmd.egg_info)
  30. bs_cmd = self.get_finalized_command('build_scripts')
  31. exec_param = getattr(bs_cmd, 'executable', None)
  32. writer = _scripts.ScriptWriter
  33. if exec_param == sys.executable:
  34. # In case the path to the Python executable contains a space, wrap
  35. # it so it's not split up.
  36. exec_param = [exec_param]
  37. # resolve the writer to the environment
  38. writer = writer.best()
  39. cmd = writer.command_spec_class.best().from_param(exec_param)
  40. for args in writer.get_args(dist, cmd.as_header()):
  41. self.write_script(*args)
  42. def write_script(self, script_name, contents, mode: str = "t", *ignored) -> None:
  43. """Write an executable file to the scripts directory"""
  44. from .._shutil import attempt_chmod_verbose as chmod, current_umask
  45. log.info("Installing %s script to %s", script_name, self.install_dir)
  46. target = os.path.join(self.install_dir, script_name)
  47. self.outfiles.append(target)
  48. encoding = None if "b" in mode else "utf-8"
  49. mask = current_umask()
  50. ensure_directory(target)
  51. with open(target, "w" + mode, encoding=encoding) as f:
  52. f.write(contents)
  53. chmod(target, 0o777 - mask)