m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

80 lines
2.4 KiB

6 months ago
  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_names(raw_name: str) -> List[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. We also look for the raw name (without normalization) as setuptools 69 changed
  20. the way it names .egg-link files (https://github.com/pypa/setuptools/issues/4167).
  21. """
  22. return [
  23. re.sub("[^A-Za-z0-9.]+", "-", raw_name) + ".egg-link",
  24. f"{raw_name}.egg-link",
  25. ]
  26. def egg_link_path_from_sys_path(raw_name: str) -> Optional[str]:
  27. """
  28. Look for a .egg-link file for project name, by walking sys.path.
  29. """
  30. egg_link_names = _egg_link_names(raw_name)
  31. for path_item in sys.path:
  32. for egg_link_name in egg_link_names:
  33. egg_link = os.path.join(path_item, egg_link_name)
  34. if os.path.isfile(egg_link):
  35. return egg_link
  36. return None
  37. def egg_link_path_from_location(raw_name: str) -> Optional[str]:
  38. """
  39. Return the path for the .egg-link file if it exists, otherwise, None.
  40. There's 3 scenarios:
  41. 1) not in a virtualenv
  42. try to find in site.USER_SITE, then site_packages
  43. 2) in a no-global virtualenv
  44. try to find in site_packages
  45. 3) in a yes-global virtualenv
  46. try to find in site_packages, then site.USER_SITE
  47. (don't look in global location)
  48. For #1 and #3, there could be odd cases, where there's an egg-link in 2
  49. locations.
  50. This method will just return the first one found.
  51. """
  52. sites: List[str] = []
  53. if running_under_virtualenv():
  54. sites.append(site_packages)
  55. if not virtualenv_no_global() and user_site:
  56. sites.append(user_site)
  57. else:
  58. if user_site:
  59. sites.append(user_site)
  60. sites.append(site_packages)
  61. egg_link_names = _egg_link_names(raw_name)
  62. for site in sites:
  63. for egg_link_name in egg_link_names:
  64. egglink = os.path.join(site, egg_link_name)
  65. if os.path.isfile(egglink):
  66. return egglink
  67. return None