Coverage for sources/appcore/distribution.py: 100%

78 statements  

« prev     ^ index     » next       coverage.py v7.17.0, created at 2026-10-27 19:39 +0000

1# vim: set filetype=python fileencoding=utf-8: 

2# -*- coding: utf-8 -*- 

3 

4#============================================================================# 

5# # 

6# Licensed under the Apache License, Version 2.0 (the "License"); # 

7# you may not use this file except in compliance with the License. # 

8# You may obtain a copy of the License at # 

9# # 

10# http://www.apache.org/licenses/LICENSE-2.0 # 

11# # 

12# Unless required by applicable law or agreed to in writing, software # 

13# distributed under the License is distributed on an "AS IS" BASIS, # 

14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # 

15# See the License for the specific language governing permissions and # 

16# limitations under the License. # 

17# # 

18#============================================================================# 

19 

20 

21''' Information about package distribution. ''' 

22 

23 

24from . import __ 

25from . import exceptions as _exceptions 

26from . import io as _io 

27 

28 

29class Information( __.immut.DataclassObject ): 

30 ''' Information about a package distribution. ''' 

31 

32 name: str 

33 location: __.Path 

34 editable: bool 

35 

36 @classmethod 

37 async def prepare( 

38 selfclass, 

39 exits: __.ctxl.AsyncExitStack, 

40 anchor: __.Absential[ __.Path ] = __.absent, 

41 package: __.Absential[ str ] = __.absent, 

42 ) -> __.typx.Self: 

43 ''' Acquires information about package distribution. ''' 

44 if ( __.is_absent( anchor ) 

45 and getattr( __.sys, 'frozen', False ) 

46 and hasattr( __.sys, '_MEIPASS' ) 

47 ): # pragma: no cover 

48 location, name = await _acquire_pyinstaller_information( ) 

49 return selfclass( 

50 editable = False, location = location, name = name ) 

51 if __.is_absent( package ): 

52 package, _ = _discover_invoker_location( ) 

53 if not __.is_absent( package ): # pragma: no branch 

54 from importlib.metadata import packages_distributions 

55 name = packages_distributions( ).get( package ) 

56 if name: 

57 location = ( 

58 await _acquire_production_location( package, exits ) ) 

59 return selfclass( 

60 editable = False, location = location, name = name[ 0 ] ) 

61 # https://github.com/pypa/packaging-problems/issues/609 

62 # Development sources rather than distribution. 

63 # Implies no use of importlib.resources. 

64 if __.is_absent( anchor ): 

65 _, anchor = _discover_invoker_location( ) 

66 location, name = ( 

67 await _acquire_development_information( anchor = anchor ) ) 

68 return selfclass( 

69 editable = True, location = location, name = name ) 

70 

71 def provide_data_location( self, *appendages: str ) -> __.Path: 

72 ''' Provides location of distribution data. ''' 

73 base = self.location / 'data' 

74 if appendages: return base.joinpath( *appendages ) 

75 return base 

76 

77 

78async def _acquire_development_information( 

79 anchor: __.Path 

80) -> tuple[ __.Path, str ]: 

81 location = _locate_pyproject( anchor ) 

82 pyproject = await _io.acquire_text_file_async( 

83 location / 'pyproject.toml', deserializer = __.tomllib.loads ) 

84 name = pyproject[ 'project' ][ 'name' ] 

85 return location, name 

86 

87 

88async def _acquire_production_location( 

89 package: str, exits: __.ctxl.AsyncExitStack 

90) -> __.Path: 

91 from importlib.resources import as_file, files 

92 # Extract package contents to temporary directory, if necessary. 

93 return exits.enter_context( 

94 as_file( files( package ) ) ) 

95 

96 

97async def _acquire_pyinstaller_information( # pragma: no cover 

98) -> tuple[ __.Path, str ]: 

99 anchor_ = __.Path( 

100 getattr( __.sys, '_MEIPASS' ) ) 

101 # TODO: More rigorously determine package name. 

102 # Currently assumes 'pyproject.toml' is present in distribution. 

103 return await _acquire_development_information( anchor = anchor_ ) 

104 

105 

106def _detect_package_boundary( mname: str ) -> __.Absential[ str ]: 

107 ''' Finds package boundary, including for namespace packages. ''' 

108 if not mname or mname == '__main__': return __.absent 

109 components = mname.split( '.' ) 

110 # Work backwards through dotted name to find deepest package. 

111 for i in range( len( components ), 0, -1 ): 

112 candidate = '.'.join( components[ : i ] ) 

113 if candidate not in __.sys.modules: continue 

114 module = __.sys.modules[ candidate ] 

115 if hasattr( module, '__path__' ): # Is it a package? 

116 return candidate 

117 # Fallback to first component for edge cases. 

118 return components[ 0 ] 

119 

120 

121def _discover_invoker_location( ) -> tuple[ __.Absential[ str ], __.Path ]: 

122 ''' Discovers file path of caller for project root detection. ''' 

123 package_location = __.Path( __file__ ).parent.resolve( ) 

124 stdlib_locations, sp_locations = _provide_standard_locations( ) 

125 frame = __.inspect.currentframe( ) 

126 if frame is None: return __.absent, __.Path.cwd( ) 

127 # Walk up the call stack to find frame outside of this package. 

128 while True: 

129 frame = frame.f_back 

130 if frame is None: break # pragma: no cover 

131 location = __.Path( frame.f_code.co_filename).resolve( ) 

132 # Skip frames within this package 

133 if location.is_relative_to( package_location ): # pragma: no cover 

134 continue 

135 in_site_packages = any( 

136 location.is_relative_to( sp_location ) 

137 for sp_location in sp_locations ) 

138 in_stdlib_locations = any( 

139 location.is_relative_to( stdlib_location ) 

140 for stdlib_location in stdlib_locations ) 

141 # Skip standard library paths, unless in site-packages. 

142 if not in_site_packages and in_stdlib_locations: continue 

143 mname = frame.f_globals.get( '__name__' ) 

144 if not mname or mname == '__main__': continue 

145 pname = _detect_package_boundary( mname ) 

146 if not __.is_absent( pname ): 

147 return pname, location.parent 

148 continue # pragma: no cover 

149 # Fallback location is current working directory. 

150 return __.absent, __.Path.cwd( ) # pragma: no cover 

151 

152 

153def _locate_pyproject( project_anchor: __.Path ) -> __.Path: 

154 ''' Finds project manifest, if it exists. Errors otherwise. ''' 

155 initial = project_anchor.resolve( ) 

156 current = initial if initial.is_dir( ) else initial.parent 

157 limits: set[ __.Path ] = set( ) 

158 for limits_variable in ( 'GIT_CEILING_DIRECTORIES', ): 

159 limits_value = __.os.environ.get( limits_variable ) 

160 if not limits_value: continue # pragma: no cover 

161 limits.update( # pragma: no cover 

162 __.Path( limit ).resolve( ) 

163 for limit in limits_value.split( ':' ) if limit.strip( ) ) 

164 while current != current.parent: # Not at filesystem root 

165 if ( current / 'pyproject.toml' ).exists( ): 

166 return current 

167 if current in limits: 

168 raise _exceptions.FileLocateFailure( # noqa: TRY003 # pragma: no cover 

169 'project root discovery', 'pyproject.toml' ) 

170 current = current.parent 

171 raise _exceptions.FileLocateFailure( # noqa: TRY003 # pragma: no cover 

172 'project root discovery', 'pyproject.toml' ) 

173 

174 

175def _provide_standard_locations( ) -> tuple[ 

176 frozenset[ __.Path ], frozenset[ __.Path ] 

177]: 

178 stdlib_locations = frozenset( ( 

179 __.Path( __.syscfg.get_path( 'stdlib' ) ).resolve( ), 

180 __.Path( __.syscfg.get_path( 'platstdlib' ) ).resolve( ) ) ) 

181 sp_locations: set[ __.Path ] = set( ) 

182 for path in __.site.getsitepackages( ): 

183 sp_locations.add( __.Path( path ).resolve( ) ) 

184 with __.ctxl.suppress( AttributeError ): 

185 sp_locations.add( 

186 __.Path( __.site.getusersitepackages( ) ).resolve( ) ) 

187 return frozenset( stdlib_locations ), frozenset( sp_locations )