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