Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/pip/_internal/utils/egg_link.py: 30%

33 statements  

« prev     ^ index     » next       coverage.py v7.4.3, created at 2024-02-26 06:33 +0000

1import os 

2import re 

3import sys 

4from typing import List, Optional 

5 

6from pip._internal.locations import site_packages, user_site 

7from 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 

18def _egg_link_names(raw_name: str) -> List[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 We also look for the raw name (without normalization) as setuptools 69 changed 

25 the way it names .egg-link files (https://github.com/pypa/setuptools/issues/4167). 

26 """ 

27 return [ 

28 re.sub("[^A-Za-z0-9.]+", "-", raw_name) + ".egg-link", 

29 f"{raw_name}.egg-link", 

30 ] 

31 

32 

33def egg_link_path_from_sys_path(raw_name: str) -> Optional[str]: 

34 """ 

35 Look for a .egg-link file for project name, by walking sys.path. 

36 """ 

37 egg_link_names = _egg_link_names(raw_name) 

38 for path_item in sys.path: 

39 for egg_link_name in egg_link_names: 

40 egg_link = os.path.join(path_item, egg_link_name) 

41 if os.path.isfile(egg_link): 

42 return egg_link 

43 return None 

44 

45 

46def egg_link_path_from_location(raw_name: str) -> Optional[str]: 

47 """ 

48 Return the path for the .egg-link file if it exists, otherwise, None. 

49 

50 There's 3 scenarios: 

51 1) not in a virtualenv 

52 try to find in site.USER_SITE, then site_packages 

53 2) in a no-global virtualenv 

54 try to find in site_packages 

55 3) in a yes-global virtualenv 

56 try to find in site_packages, then site.USER_SITE 

57 (don't look in global location) 

58 

59 For #1 and #3, there could be odd cases, where there's an egg-link in 2 

60 locations. 

61 

62 This method will just return the first one found. 

63 """ 

64 sites: List[str] = [] 

65 if running_under_virtualenv(): 

66 sites.append(site_packages) 

67 if not virtualenv_no_global() and user_site: 

68 sites.append(user_site) 

69 else: 

70 if user_site: 

71 sites.append(user_site) 

72 sites.append(site_packages) 

73 

74 egg_link_names = _egg_link_names(raw_name) 

75 for site in sites: 

76 for egg_link_name in egg_link_names: 

77 egglink = os.path.join(site, egg_link_name) 

78 if os.path.isfile(egglink): 

79 return egglink 

80 return None