egg_link.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import os
  2. import re
  3. import sys
  4. from typing import List, Optional
  5. from pip._internal.locations import site_packages, user_site
  6. from pip._internal.utils.virtualenv import (
  7. running_under_virtualenv,
  8. virtualenv_no_global,
  9. )
  10. __all__ = [
  11. "egg_link_path_from_sys_path",
  12. "egg_link_path_from_location",
  13. ]
  14. def _egg_link_name(raw_name: str) -> str:
  15. """
  16. Convert a Name metadata value to a .egg-link name, by applying
  17. the same substitution as pkg_resources's safe_name function.
  18. Note: we cannot use canonicalize_name because it has a different logic.
  19. """
  20. return re.sub("[^A-Za-z0-9.]+", "-", raw_name) + ".egg-link"
  21. def egg_link_path_from_sys_path(raw_name: str) -> Optional[str]:
  22. """
  23. Look for a .egg-link file for project name, by walking sys.path.
  24. """
  25. egg_link_name = _egg_link_name(raw_name)
  26. for path_item in sys.path:
  27. egg_link = os.path.join(path_item, egg_link_name)
  28. if os.path.isfile(egg_link):
  29. return egg_link
  30. return None
  31. def egg_link_path_from_location(raw_name: str) -> Optional[str]:
  32. """
  33. Return the path for the .egg-link file if it exists, otherwise, None.
  34. There's 3 scenarios:
  35. 1) not in a virtualenv
  36. try to find in site.USER_SITE, then site_packages
  37. 2) in a no-global virtualenv
  38. try to find in site_packages
  39. 3) in a yes-global virtualenv
  40. try to find in site_packages, then site.USER_SITE
  41. (don't look in global location)
  42. For #1 and #3, there could be odd cases, where there's an egg-link in 2
  43. locations.
  44. This method will just return the first one found.
  45. """
  46. sites: List[str] = []
  47. if running_under_virtualenv():
  48. sites.append(site_packages)
  49. if not virtualenv_no_global() and user_site:
  50. sites.append(user_site)
  51. else:
  52. if user_site:
  53. sites.append(user_site)
  54. sites.append(site_packages)
  55. egg_link_name = _egg_link_name(raw_name)
  56. for site in sites:
  57. egglink = os.path.join(site, egg_link_name)
  58. if os.path.isfile(egglink):
  59. return egglink
  60. return None