1from __future__ import annotations
2
3import os
4import re
5import sys
6
7from pip._internal.locations import site_packages, user_site
8from pip._internal.utils.virtualenv import (
9 running_under_virtualenv,
10 virtualenv_no_global,
11)
12
13__all__ = [
14 "egg_link_path_from_sys_path",
15 "egg_link_path_from_location",
16]
17
18
19def _egg_link_names(raw_name: str) -> list[str]:
20 """
21 Convert a Name metadata value to a .egg-link name, by applying
22 the same substitution as pkg_resources's safe_name function.
23 Note: we cannot use canonicalize_name because it has a different logic.
24
25 We also look for the raw name (without normalization) as setuptools 69 changed
26 the way it names .egg-link files (https://github.com/pypa/setuptools/issues/4167).
27 """
28 return [
29 re.sub("[^A-Za-z0-9.]+", "-", raw_name) + ".egg-link",
30 f"{raw_name}.egg-link",
31 ]
32
33
34def egg_link_path_from_sys_path(raw_name: str) -> str | None:
35 """
36 Look for a .egg-link file for project name, by walking sys.path.
37 """
38 egg_link_names = _egg_link_names(raw_name)
39 for path_item in sys.path:
40 for egg_link_name in egg_link_names:
41 egg_link = os.path.join(path_item, egg_link_name)
42 if os.path.isfile(egg_link):
43 return egg_link
44 return None
45
46
47def egg_link_path_from_location(raw_name: str) -> str | None:
48 """
49 Return the path for the .egg-link file if it exists, otherwise, None.
50
51 There's 3 scenarios:
52 1) not in a virtualenv
53 try to find in site.USER_SITE, then site_packages
54 2) in a no-global virtualenv
55 try to find in site_packages
56 3) in a yes-global virtualenv
57 try to find in site_packages, then site.USER_SITE
58 (don't look in global location)
59
60 For #1 and #3, there could be odd cases, where there's an egg-link in 2
61 locations.
62
63 This method will just return the first one found.
64 """
65 sites: list[str] = []
66 if running_under_virtualenv():
67 sites.append(site_packages)
68 if not virtualenv_no_global() and user_site:
69 sites.append(user_site)
70 else:
71 if user_site:
72 sites.append(user_site)
73 sites.append(site_packages)
74
75 egg_link_names = _egg_link_names(raw_name)
76 for site in sites:
77 for egg_link_name in egg_link_names:
78 egglink = os.path.join(site, egg_link_name)
79 if os.path.isfile(egglink):
80 return egglink
81 return None