misc_util.py 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417
  1. import os
  2. import re
  3. import sys
  4. import copy
  5. import glob
  6. import atexit
  7. import tempfile
  8. import subprocess
  9. import shutil
  10. import multiprocessing
  11. import textwrap
  12. import importlib.util
  13. from threading import local as tlocal
  14. import distutils
  15. from distutils.errors import DistutilsError
  16. # stores temporary directory of each thread to only create one per thread
  17. _tdata = tlocal()
  18. # store all created temporary directories so they can be deleted on exit
  19. _tmpdirs = []
  20. def clean_up_temporary_directory():
  21. if _tmpdirs is not None:
  22. for d in _tmpdirs:
  23. try:
  24. shutil.rmtree(d)
  25. except OSError:
  26. pass
  27. atexit.register(clean_up_temporary_directory)
  28. from numpy.compat import npy_load_module
  29. __all__ = ['Configuration', 'get_numpy_include_dirs', 'default_config_dict',
  30. 'dict_append', 'appendpath', 'generate_config_py',
  31. 'get_cmd', 'allpath', 'get_mathlibs',
  32. 'terminal_has_colors', 'red_text', 'green_text', 'yellow_text',
  33. 'blue_text', 'cyan_text', 'cyg2win32', 'mingw32', 'all_strings',
  34. 'has_f_sources', 'has_cxx_sources', 'filter_sources',
  35. 'get_dependencies', 'is_local_src_dir', 'get_ext_source_files',
  36. 'get_script_files', 'get_lib_source_files', 'get_data_files',
  37. 'dot_join', 'get_frame', 'minrelpath', 'njoin',
  38. 'is_sequence', 'is_string', 'as_list', 'gpaths', 'get_language',
  39. 'quote_args', 'get_build_architecture', 'get_info', 'get_pkg_info',
  40. 'get_num_build_jobs']
  41. class InstallableLib:
  42. """
  43. Container to hold information on an installable library.
  44. Parameters
  45. ----------
  46. name : str
  47. Name of the installed library.
  48. build_info : dict
  49. Dictionary holding build information.
  50. target_dir : str
  51. Absolute path specifying where to install the library.
  52. See Also
  53. --------
  54. Configuration.add_installed_library
  55. Notes
  56. -----
  57. The three parameters are stored as attributes with the same names.
  58. """
  59. def __init__(self, name, build_info, target_dir):
  60. self.name = name
  61. self.build_info = build_info
  62. self.target_dir = target_dir
  63. def get_num_build_jobs():
  64. """
  65. Get number of parallel build jobs set by the --parallel command line
  66. argument of setup.py
  67. If the command did not receive a setting the environment variable
  68. NPY_NUM_BUILD_JOBS is checked. If that is unset, return the number of
  69. processors on the system, with a maximum of 8 (to prevent
  70. overloading the system if there a lot of CPUs).
  71. Returns
  72. -------
  73. out : int
  74. number of parallel jobs that can be run
  75. """
  76. from numpy.distutils.core import get_distribution
  77. try:
  78. cpu_count = len(os.sched_getaffinity(0))
  79. except AttributeError:
  80. cpu_count = multiprocessing.cpu_count()
  81. cpu_count = min(cpu_count, 8)
  82. envjobs = int(os.environ.get("NPY_NUM_BUILD_JOBS", cpu_count))
  83. dist = get_distribution()
  84. # may be None during configuration
  85. if dist is None:
  86. return envjobs
  87. # any of these three may have the job set, take the largest
  88. cmdattr = (getattr(dist.get_command_obj('build'), 'parallel', None),
  89. getattr(dist.get_command_obj('build_ext'), 'parallel', None),
  90. getattr(dist.get_command_obj('build_clib'), 'parallel', None))
  91. if all(x is None for x in cmdattr):
  92. return envjobs
  93. else:
  94. return max(x for x in cmdattr if x is not None)
  95. def quote_args(args):
  96. # don't used _nt_quote_args as it does not check if
  97. # args items already have quotes or not.
  98. args = list(args)
  99. for i in range(len(args)):
  100. a = args[i]
  101. if ' ' in a and a[0] not in '"\'':
  102. args[i] = '"%s"' % (a)
  103. return args
  104. def allpath(name):
  105. "Convert a /-separated pathname to one using the OS's path separator."
  106. splitted = name.split('/')
  107. return os.path.join(*splitted)
  108. def rel_path(path, parent_path):
  109. """Return path relative to parent_path."""
  110. # Use realpath to avoid issues with symlinked dirs (see gh-7707)
  111. pd = os.path.realpath(os.path.abspath(parent_path))
  112. apath = os.path.realpath(os.path.abspath(path))
  113. if len(apath) < len(pd):
  114. return path
  115. if apath == pd:
  116. return ''
  117. if pd == apath[:len(pd)]:
  118. assert apath[len(pd)] in [os.sep], repr((path, apath[len(pd)]))
  119. path = apath[len(pd)+1:]
  120. return path
  121. def get_path_from_frame(frame, parent_path=None):
  122. """Return path of the module given a frame object from the call stack.
  123. Returned path is relative to parent_path when given,
  124. otherwise it is absolute path.
  125. """
  126. # First, try to find if the file name is in the frame.
  127. try:
  128. caller_file = eval('__file__', frame.f_globals, frame.f_locals)
  129. d = os.path.dirname(os.path.abspath(caller_file))
  130. except NameError:
  131. # __file__ is not defined, so let's try __name__. We try this second
  132. # because setuptools spoofs __name__ to be '__main__' even though
  133. # sys.modules['__main__'] might be something else, like easy_install(1).
  134. caller_name = eval('__name__', frame.f_globals, frame.f_locals)
  135. __import__(caller_name)
  136. mod = sys.modules[caller_name]
  137. if hasattr(mod, '__file__'):
  138. d = os.path.dirname(os.path.abspath(mod.__file__))
  139. else:
  140. # we're probably running setup.py as execfile("setup.py")
  141. # (likely we're building an egg)
  142. d = os.path.abspath('.')
  143. if parent_path is not None:
  144. d = rel_path(d, parent_path)
  145. return d or '.'
  146. def njoin(*path):
  147. """Join two or more pathname components +
  148. - convert a /-separated pathname to one using the OS's path separator.
  149. - resolve `..` and `.` from path.
  150. Either passing n arguments as in njoin('a','b'), or a sequence
  151. of n names as in njoin(['a','b']) is handled, or a mixture of such arguments.
  152. """
  153. paths = []
  154. for p in path:
  155. if is_sequence(p):
  156. # njoin(['a', 'b'], 'c')
  157. paths.append(njoin(*p))
  158. else:
  159. assert is_string(p)
  160. paths.append(p)
  161. path = paths
  162. if not path:
  163. # njoin()
  164. joined = ''
  165. else:
  166. # njoin('a', 'b')
  167. joined = os.path.join(*path)
  168. if os.path.sep != '/':
  169. joined = joined.replace('/', os.path.sep)
  170. return minrelpath(joined)
  171. def get_mathlibs(path=None):
  172. """Return the MATHLIB line from numpyconfig.h
  173. """
  174. if path is not None:
  175. config_file = os.path.join(path, '_numpyconfig.h')
  176. else:
  177. # Look for the file in each of the numpy include directories.
  178. dirs = get_numpy_include_dirs()
  179. for path in dirs:
  180. fn = os.path.join(path, '_numpyconfig.h')
  181. if os.path.exists(fn):
  182. config_file = fn
  183. break
  184. else:
  185. raise DistutilsError('_numpyconfig.h not found in numpy include '
  186. 'dirs %r' % (dirs,))
  187. with open(config_file) as fid:
  188. mathlibs = []
  189. s = '#define MATHLIB'
  190. for line in fid:
  191. if line.startswith(s):
  192. value = line[len(s):].strip()
  193. if value:
  194. mathlibs.extend(value.split(','))
  195. return mathlibs
  196. def minrelpath(path):
  197. """Resolve `..` and '.' from path.
  198. """
  199. if not is_string(path):
  200. return path
  201. if '.' not in path:
  202. return path
  203. l = path.split(os.sep)
  204. while l:
  205. try:
  206. i = l.index('.', 1)
  207. except ValueError:
  208. break
  209. del l[i]
  210. j = 1
  211. while l:
  212. try:
  213. i = l.index('..', j)
  214. except ValueError:
  215. break
  216. if l[i-1]=='..':
  217. j += 1
  218. else:
  219. del l[i], l[i-1]
  220. j = 1
  221. if not l:
  222. return ''
  223. return os.sep.join(l)
  224. def sorted_glob(fileglob):
  225. """sorts output of python glob for https://bugs.python.org/issue30461
  226. to allow extensions to have reproducible build results"""
  227. return sorted(glob.glob(fileglob))
  228. def _fix_paths(paths, local_path, include_non_existing):
  229. assert is_sequence(paths), repr(type(paths))
  230. new_paths = []
  231. assert not is_string(paths), repr(paths)
  232. for n in paths:
  233. if is_string(n):
  234. if '*' in n or '?' in n:
  235. p = sorted_glob(n)
  236. p2 = sorted_glob(njoin(local_path, n))
  237. if p2:
  238. new_paths.extend(p2)
  239. elif p:
  240. new_paths.extend(p)
  241. else:
  242. if include_non_existing:
  243. new_paths.append(n)
  244. print('could not resolve pattern in %r: %r' %
  245. (local_path, n))
  246. else:
  247. n2 = njoin(local_path, n)
  248. if os.path.exists(n2):
  249. new_paths.append(n2)
  250. else:
  251. if os.path.exists(n):
  252. new_paths.append(n)
  253. elif include_non_existing:
  254. new_paths.append(n)
  255. if not os.path.exists(n):
  256. print('non-existing path in %r: %r' %
  257. (local_path, n))
  258. elif is_sequence(n):
  259. new_paths.extend(_fix_paths(n, local_path, include_non_existing))
  260. else:
  261. new_paths.append(n)
  262. return [minrelpath(p) for p in new_paths]
  263. def gpaths(paths, local_path='', include_non_existing=True):
  264. """Apply glob to paths and prepend local_path if needed.
  265. """
  266. if is_string(paths):
  267. paths = (paths,)
  268. return _fix_paths(paths, local_path, include_non_existing)
  269. def make_temp_file(suffix='', prefix='', text=True):
  270. if not hasattr(_tdata, 'tempdir'):
  271. _tdata.tempdir = tempfile.mkdtemp()
  272. _tmpdirs.append(_tdata.tempdir)
  273. fid, name = tempfile.mkstemp(suffix=suffix,
  274. prefix=prefix,
  275. dir=_tdata.tempdir,
  276. text=text)
  277. fo = os.fdopen(fid, 'w')
  278. return fo, name
  279. # Hooks for colored terminal output.
  280. # See also https://web.archive.org/web/20100314204946/http://www.livinglogic.de/Python/ansistyle
  281. def terminal_has_colors():
  282. if sys.platform=='cygwin' and 'USE_COLOR' not in os.environ:
  283. # Avoid importing curses that causes illegal operation
  284. # with a message:
  285. # PYTHON2 caused an invalid page fault in
  286. # module CYGNURSES7.DLL as 015f:18bbfc28
  287. # Details: Python 2.3.3 [GCC 3.3.1 (cygming special)]
  288. # ssh to Win32 machine from debian
  289. # curses.version is 2.2
  290. # CYGWIN_98-4.10, release 1.5.7(0.109/3/2))
  291. return 0
  292. if hasattr(sys.stdout, 'isatty') and sys.stdout.isatty():
  293. try:
  294. import curses
  295. curses.setupterm()
  296. if (curses.tigetnum("colors") >= 0
  297. and curses.tigetnum("pairs") >= 0
  298. and ((curses.tigetstr("setf") is not None
  299. and curses.tigetstr("setb") is not None)
  300. or (curses.tigetstr("setaf") is not None
  301. and curses.tigetstr("setab") is not None)
  302. or curses.tigetstr("scp") is not None)):
  303. return 1
  304. except Exception:
  305. pass
  306. return 0
  307. if terminal_has_colors():
  308. _colour_codes = dict(black=0, red=1, green=2, yellow=3,
  309. blue=4, magenta=5, cyan=6, white=7, default=9)
  310. def colour_text(s, fg=None, bg=None, bold=False):
  311. seq = []
  312. if bold:
  313. seq.append('1')
  314. if fg:
  315. fgcode = 30 + _colour_codes.get(fg.lower(), 0)
  316. seq.append(str(fgcode))
  317. if bg:
  318. bgcode = 40 + _colour_codes.get(fg.lower(), 7)
  319. seq.append(str(bgcode))
  320. if seq:
  321. return '\x1b[%sm%s\x1b[0m' % (';'.join(seq), s)
  322. else:
  323. return s
  324. else:
  325. def colour_text(s, fg=None, bg=None):
  326. return s
  327. def default_text(s):
  328. return colour_text(s, 'default')
  329. def red_text(s):
  330. return colour_text(s, 'red')
  331. def green_text(s):
  332. return colour_text(s, 'green')
  333. def yellow_text(s):
  334. return colour_text(s, 'yellow')
  335. def cyan_text(s):
  336. return colour_text(s, 'cyan')
  337. def blue_text(s):
  338. return colour_text(s, 'blue')
  339. #########################
  340. def cyg2win32(path):
  341. if sys.platform=='cygwin' and path.startswith('/cygdrive'):
  342. path = path[10] + ':' + os.path.normcase(path[11:])
  343. return path
  344. def mingw32():
  345. """Return true when using mingw32 environment.
  346. """
  347. if sys.platform=='win32':
  348. if os.environ.get('OSTYPE', '')=='msys':
  349. return True
  350. if os.environ.get('MSYSTEM', '')=='MINGW32':
  351. return True
  352. return False
  353. def msvc_runtime_version():
  354. "Return version of MSVC runtime library, as defined by __MSC_VER__ macro"
  355. msc_pos = sys.version.find('MSC v.')
  356. if msc_pos != -1:
  357. msc_ver = int(sys.version[msc_pos+6:msc_pos+10])
  358. else:
  359. msc_ver = None
  360. return msc_ver
  361. def msvc_runtime_library():
  362. "Return name of MSVC runtime library if Python was built with MSVC >= 7"
  363. ver = msvc_runtime_major ()
  364. if ver:
  365. if ver < 140:
  366. return "msvcr%i" % ver
  367. else:
  368. return "vcruntime%i" % ver
  369. else:
  370. return None
  371. def msvc_runtime_major():
  372. "Return major version of MSVC runtime coded like get_build_msvc_version"
  373. major = {1300: 70, # MSVC 7.0
  374. 1310: 71, # MSVC 7.1
  375. 1400: 80, # MSVC 8
  376. 1500: 90, # MSVC 9 (aka 2008)
  377. 1600: 100, # MSVC 10 (aka 2010)
  378. 1900: 140, # MSVC 14 (aka 2015)
  379. }.get(msvc_runtime_version(), None)
  380. return major
  381. #########################
  382. #XXX need support for .C that is also C++
  383. cxx_ext_match = re.compile(r'.*\.(cpp|cxx|cc)\Z', re.I).match
  384. fortran_ext_match = re.compile(r'.*\.(f90|f95|f77|for|ftn|f)\Z', re.I).match
  385. f90_ext_match = re.compile(r'.*\.(f90|f95)\Z', re.I).match
  386. f90_module_name_match = re.compile(r'\s*module\s*(?P<name>[\w_]+)', re.I).match
  387. def _get_f90_modules(source):
  388. """Return a list of Fortran f90 module names that
  389. given source file defines.
  390. """
  391. if not f90_ext_match(source):
  392. return []
  393. modules = []
  394. with open(source, 'r') as f:
  395. for line in f:
  396. m = f90_module_name_match(line)
  397. if m:
  398. name = m.group('name')
  399. modules.append(name)
  400. # break # XXX can we assume that there is one module per file?
  401. return modules
  402. def is_string(s):
  403. return isinstance(s, str)
  404. def all_strings(lst):
  405. """Return True if all items in lst are string objects. """
  406. for item in lst:
  407. if not is_string(item):
  408. return False
  409. return True
  410. def is_sequence(seq):
  411. if is_string(seq):
  412. return False
  413. try:
  414. len(seq)
  415. except Exception:
  416. return False
  417. return True
  418. def is_glob_pattern(s):
  419. return is_string(s) and ('*' in s or '?' in s)
  420. def as_list(seq):
  421. if is_sequence(seq):
  422. return list(seq)
  423. else:
  424. return [seq]
  425. def get_language(sources):
  426. # not used in numpy/scipy packages, use build_ext.detect_language instead
  427. """Determine language value (c,f77,f90) from sources """
  428. language = None
  429. for source in sources:
  430. if isinstance(source, str):
  431. if f90_ext_match(source):
  432. language = 'f90'
  433. break
  434. elif fortran_ext_match(source):
  435. language = 'f77'
  436. return language
  437. def has_f_sources(sources):
  438. """Return True if sources contains Fortran files """
  439. for source in sources:
  440. if fortran_ext_match(source):
  441. return True
  442. return False
  443. def has_cxx_sources(sources):
  444. """Return True if sources contains C++ files """
  445. for source in sources:
  446. if cxx_ext_match(source):
  447. return True
  448. return False
  449. def filter_sources(sources):
  450. """Return four lists of filenames containing
  451. C, C++, Fortran, and Fortran 90 module sources,
  452. respectively.
  453. """
  454. c_sources = []
  455. cxx_sources = []
  456. f_sources = []
  457. fmodule_sources = []
  458. for source in sources:
  459. if fortran_ext_match(source):
  460. modules = _get_f90_modules(source)
  461. if modules:
  462. fmodule_sources.append(source)
  463. else:
  464. f_sources.append(source)
  465. elif cxx_ext_match(source):
  466. cxx_sources.append(source)
  467. else:
  468. c_sources.append(source)
  469. return c_sources, cxx_sources, f_sources, fmodule_sources
  470. def _get_headers(directory_list):
  471. # get *.h files from list of directories
  472. headers = []
  473. for d in directory_list:
  474. head = sorted_glob(os.path.join(d, "*.h")) #XXX: *.hpp files??
  475. headers.extend(head)
  476. return headers
  477. def _get_directories(list_of_sources):
  478. # get unique directories from list of sources.
  479. direcs = []
  480. for f in list_of_sources:
  481. d = os.path.split(f)
  482. if d[0] != '' and not d[0] in direcs:
  483. direcs.append(d[0])
  484. return direcs
  485. def _commandline_dep_string(cc_args, extra_postargs, pp_opts):
  486. """
  487. Return commandline representation used to determine if a file needs
  488. to be recompiled
  489. """
  490. cmdline = 'commandline: '
  491. cmdline += ' '.join(cc_args)
  492. cmdline += ' '.join(extra_postargs)
  493. cmdline += ' '.join(pp_opts) + '\n'
  494. return cmdline
  495. def get_dependencies(sources):
  496. #XXX scan sources for include statements
  497. return _get_headers(_get_directories(sources))
  498. def is_local_src_dir(directory):
  499. """Return true if directory is local directory.
  500. """
  501. if not is_string(directory):
  502. return False
  503. abs_dir = os.path.abspath(directory)
  504. c = os.path.commonprefix([os.getcwd(), abs_dir])
  505. new_dir = abs_dir[len(c):].split(os.sep)
  506. if new_dir and not new_dir[0]:
  507. new_dir = new_dir[1:]
  508. if new_dir and new_dir[0]=='build':
  509. return False
  510. new_dir = os.sep.join(new_dir)
  511. return os.path.isdir(new_dir)
  512. def general_source_files(top_path):
  513. pruned_directories = {'CVS':1, '.svn':1, 'build':1}
  514. prune_file_pat = re.compile(r'(?:[~#]|\.py[co]|\.o)$')
  515. for dirpath, dirnames, filenames in os.walk(top_path, topdown=True):
  516. pruned = [ d for d in dirnames if d not in pruned_directories ]
  517. dirnames[:] = pruned
  518. for f in filenames:
  519. if not prune_file_pat.search(f):
  520. yield os.path.join(dirpath, f)
  521. def general_source_directories_files(top_path):
  522. """Return a directory name relative to top_path and
  523. files contained.
  524. """
  525. pruned_directories = ['CVS', '.svn', 'build']
  526. prune_file_pat = re.compile(r'(?:[~#]|\.py[co]|\.o)$')
  527. for dirpath, dirnames, filenames in os.walk(top_path, topdown=True):
  528. pruned = [ d for d in dirnames if d not in pruned_directories ]
  529. dirnames[:] = pruned
  530. for d in dirnames:
  531. dpath = os.path.join(dirpath, d)
  532. rpath = rel_path(dpath, top_path)
  533. files = []
  534. for f in os.listdir(dpath):
  535. fn = os.path.join(dpath, f)
  536. if os.path.isfile(fn) and not prune_file_pat.search(fn):
  537. files.append(fn)
  538. yield rpath, files
  539. dpath = top_path
  540. rpath = rel_path(dpath, top_path)
  541. filenames = [os.path.join(dpath, f) for f in os.listdir(dpath) \
  542. if not prune_file_pat.search(f)]
  543. files = [f for f in filenames if os.path.isfile(f)]
  544. yield rpath, files
  545. def get_ext_source_files(ext):
  546. # Get sources and any include files in the same directory.
  547. filenames = []
  548. sources = [_m for _m in ext.sources if is_string(_m)]
  549. filenames.extend(sources)
  550. filenames.extend(get_dependencies(sources))
  551. for d in ext.depends:
  552. if is_local_src_dir(d):
  553. filenames.extend(list(general_source_files(d)))
  554. elif os.path.isfile(d):
  555. filenames.append(d)
  556. return filenames
  557. def get_script_files(scripts):
  558. scripts = [_m for _m in scripts if is_string(_m)]
  559. return scripts
  560. def get_lib_source_files(lib):
  561. filenames = []
  562. sources = lib[1].get('sources', [])
  563. sources = [_m for _m in sources if is_string(_m)]
  564. filenames.extend(sources)
  565. filenames.extend(get_dependencies(sources))
  566. depends = lib[1].get('depends', [])
  567. for d in depends:
  568. if is_local_src_dir(d):
  569. filenames.extend(list(general_source_files(d)))
  570. elif os.path.isfile(d):
  571. filenames.append(d)
  572. return filenames
  573. def get_shared_lib_extension(is_python_ext=False):
  574. """Return the correct file extension for shared libraries.
  575. Parameters
  576. ----------
  577. is_python_ext : bool, optional
  578. Whether the shared library is a Python extension. Default is False.
  579. Returns
  580. -------
  581. so_ext : str
  582. The shared library extension.
  583. Notes
  584. -----
  585. For Python shared libs, `so_ext` will typically be '.so' on Linux and OS X,
  586. and '.pyd' on Windows. For Python >= 3.2 `so_ext` has a tag prepended on
  587. POSIX systems according to PEP 3149. For Python 3.2 this is implemented on
  588. Linux, but not on OS X.
  589. """
  590. confvars = distutils.sysconfig.get_config_vars()
  591. # SO is deprecated in 3.3.1, use EXT_SUFFIX instead
  592. so_ext = confvars.get('EXT_SUFFIX', None)
  593. if so_ext is None:
  594. so_ext = confvars.get('SO', '')
  595. if not is_python_ext:
  596. # hardcode known values, config vars (including SHLIB_SUFFIX) are
  597. # unreliable (see #3182)
  598. # darwin, windows and debug linux are wrong in 3.3.1 and older
  599. if (sys.platform.startswith('linux') or
  600. sys.platform.startswith('gnukfreebsd')):
  601. so_ext = '.so'
  602. elif sys.platform.startswith('darwin'):
  603. so_ext = '.dylib'
  604. elif sys.platform.startswith('win'):
  605. so_ext = '.dll'
  606. else:
  607. # fall back to config vars for unknown platforms
  608. # fix long extension for Python >=3.2, see PEP 3149.
  609. if 'SOABI' in confvars:
  610. # Does nothing unless SOABI config var exists
  611. so_ext = so_ext.replace('.' + confvars.get('SOABI'), '', 1)
  612. return so_ext
  613. def get_data_files(data):
  614. if is_string(data):
  615. return [data]
  616. sources = data[1]
  617. filenames = []
  618. for s in sources:
  619. if hasattr(s, '__call__'):
  620. continue
  621. if is_local_src_dir(s):
  622. filenames.extend(list(general_source_files(s)))
  623. elif is_string(s):
  624. if os.path.isfile(s):
  625. filenames.append(s)
  626. else:
  627. print('Not existing data file:', s)
  628. else:
  629. raise TypeError(repr(s))
  630. return filenames
  631. def dot_join(*args):
  632. return '.'.join([a for a in args if a])
  633. def get_frame(level=0):
  634. """Return frame object from call stack with given level.
  635. """
  636. try:
  637. return sys._getframe(level+1)
  638. except AttributeError:
  639. frame = sys.exc_info()[2].tb_frame
  640. for _ in range(level+1):
  641. frame = frame.f_back
  642. return frame
  643. ######################
  644. class Configuration:
  645. _list_keys = ['packages', 'ext_modules', 'data_files', 'include_dirs',
  646. 'libraries', 'headers', 'scripts', 'py_modules',
  647. 'installed_libraries', 'define_macros']
  648. _dict_keys = ['package_dir', 'installed_pkg_config']
  649. _extra_keys = ['name', 'version']
  650. numpy_include_dirs = []
  651. def __init__(self,
  652. package_name=None,
  653. parent_name=None,
  654. top_path=None,
  655. package_path=None,
  656. caller_level=1,
  657. setup_name='setup.py',
  658. **attrs):
  659. """Construct configuration instance of a package.
  660. package_name -- name of the package
  661. Ex.: 'distutils'
  662. parent_name -- name of the parent package
  663. Ex.: 'numpy'
  664. top_path -- directory of the toplevel package
  665. Ex.: the directory where the numpy package source sits
  666. package_path -- directory of package. Will be computed by magic from the
  667. directory of the caller module if not specified
  668. Ex.: the directory where numpy.distutils is
  669. caller_level -- frame level to caller namespace, internal parameter.
  670. """
  671. self.name = dot_join(parent_name, package_name)
  672. self.version = None
  673. caller_frame = get_frame(caller_level)
  674. self.local_path = get_path_from_frame(caller_frame, top_path)
  675. # local_path -- directory of a file (usually setup.py) that
  676. # defines a configuration() function.
  677. # local_path -- directory of a file (usually setup.py) that
  678. # defines a configuration() function.
  679. if top_path is None:
  680. top_path = self.local_path
  681. self.local_path = ''
  682. if package_path is None:
  683. package_path = self.local_path
  684. elif os.path.isdir(njoin(self.local_path, package_path)):
  685. package_path = njoin(self.local_path, package_path)
  686. if not os.path.isdir(package_path or '.'):
  687. raise ValueError("%r is not a directory" % (package_path,))
  688. self.top_path = top_path
  689. self.package_path = package_path
  690. # this is the relative path in the installed package
  691. self.path_in_package = os.path.join(*self.name.split('.'))
  692. self.list_keys = self._list_keys[:]
  693. self.dict_keys = self._dict_keys[:]
  694. for n in self.list_keys:
  695. v = copy.copy(attrs.get(n, []))
  696. setattr(self, n, as_list(v))
  697. for n in self.dict_keys:
  698. v = copy.copy(attrs.get(n, {}))
  699. setattr(self, n, v)
  700. known_keys = self.list_keys + self.dict_keys
  701. self.extra_keys = self._extra_keys[:]
  702. for n in attrs.keys():
  703. if n in known_keys:
  704. continue
  705. a = attrs[n]
  706. setattr(self, n, a)
  707. if isinstance(a, list):
  708. self.list_keys.append(n)
  709. elif isinstance(a, dict):
  710. self.dict_keys.append(n)
  711. else:
  712. self.extra_keys.append(n)
  713. if os.path.exists(njoin(package_path, '__init__.py')):
  714. self.packages.append(self.name)
  715. self.package_dir[self.name] = package_path
  716. self.options = dict(
  717. ignore_setup_xxx_py = False,
  718. assume_default_configuration = False,
  719. delegate_options_to_subpackages = False,
  720. quiet = False,
  721. )
  722. caller_instance = None
  723. for i in range(1, 3):
  724. try:
  725. f = get_frame(i)
  726. except ValueError:
  727. break
  728. try:
  729. caller_instance = eval('self', f.f_globals, f.f_locals)
  730. break
  731. except NameError:
  732. pass
  733. if isinstance(caller_instance, self.__class__):
  734. if caller_instance.options['delegate_options_to_subpackages']:
  735. self.set_options(**caller_instance.options)
  736. self.setup_name = setup_name
  737. def todict(self):
  738. """
  739. Return a dictionary compatible with the keyword arguments of distutils
  740. setup function.
  741. Examples
  742. --------
  743. >>> setup(**config.todict()) #doctest: +SKIP
  744. """
  745. self._optimize_data_files()
  746. d = {}
  747. known_keys = self.list_keys + self.dict_keys + self.extra_keys
  748. for n in known_keys:
  749. a = getattr(self, n)
  750. if a:
  751. d[n] = a
  752. return d
  753. def info(self, message):
  754. if not self.options['quiet']:
  755. print(message)
  756. def warn(self, message):
  757. sys.stderr.write('Warning: %s\n' % (message,))
  758. def set_options(self, **options):
  759. """
  760. Configure Configuration instance.
  761. The following options are available:
  762. - ignore_setup_xxx_py
  763. - assume_default_configuration
  764. - delegate_options_to_subpackages
  765. - quiet
  766. """
  767. for key, value in options.items():
  768. if key in self.options:
  769. self.options[key] = value
  770. else:
  771. raise ValueError('Unknown option: '+key)
  772. def get_distribution(self):
  773. """Return the distutils distribution object for self."""
  774. from numpy.distutils.core import get_distribution
  775. return get_distribution()
  776. def _wildcard_get_subpackage(self, subpackage_name,
  777. parent_name,
  778. caller_level = 1):
  779. l = subpackage_name.split('.')
  780. subpackage_path = njoin([self.local_path]+l)
  781. dirs = [_m for _m in sorted_glob(subpackage_path) if os.path.isdir(_m)]
  782. config_list = []
  783. for d in dirs:
  784. if not os.path.isfile(njoin(d, '__init__.py')):
  785. continue
  786. if 'build' in d.split(os.sep):
  787. continue
  788. n = '.'.join(d.split(os.sep)[-len(l):])
  789. c = self.get_subpackage(n,
  790. parent_name = parent_name,
  791. caller_level = caller_level+1)
  792. config_list.extend(c)
  793. return config_list
  794. def _get_configuration_from_setup_py(self, setup_py,
  795. subpackage_name,
  796. subpackage_path,
  797. parent_name,
  798. caller_level = 1):
  799. # In case setup_py imports local modules:
  800. sys.path.insert(0, os.path.dirname(setup_py))
  801. try:
  802. setup_name = os.path.splitext(os.path.basename(setup_py))[0]
  803. n = dot_join(self.name, subpackage_name, setup_name)
  804. setup_module = npy_load_module('_'.join(n.split('.')),
  805. setup_py,
  806. ('.py', 'U', 1))
  807. if not hasattr(setup_module, 'configuration'):
  808. if not self.options['assume_default_configuration']:
  809. self.warn('Assuming default configuration '\
  810. '(%s does not define configuration())'\
  811. % (setup_module))
  812. config = Configuration(subpackage_name, parent_name,
  813. self.top_path, subpackage_path,
  814. caller_level = caller_level + 1)
  815. else:
  816. pn = dot_join(*([parent_name] + subpackage_name.split('.')[:-1]))
  817. args = (pn,)
  818. if setup_module.configuration.__code__.co_argcount > 1:
  819. args = args + (self.top_path,)
  820. config = setup_module.configuration(*args)
  821. if config.name!=dot_join(parent_name, subpackage_name):
  822. self.warn('Subpackage %r configuration returned as %r' % \
  823. (dot_join(parent_name, subpackage_name), config.name))
  824. finally:
  825. del sys.path[0]
  826. return config
  827. def get_subpackage(self,subpackage_name,
  828. subpackage_path=None,
  829. parent_name=None,
  830. caller_level = 1):
  831. """Return list of subpackage configurations.
  832. Parameters
  833. ----------
  834. subpackage_name : str or None
  835. Name of the subpackage to get the configuration. '*' in
  836. subpackage_name is handled as a wildcard.
  837. subpackage_path : str
  838. If None, then the path is assumed to be the local path plus the
  839. subpackage_name. If a setup.py file is not found in the
  840. subpackage_path, then a default configuration is used.
  841. parent_name : str
  842. Parent name.
  843. """
  844. if subpackage_name is None:
  845. if subpackage_path is None:
  846. raise ValueError(
  847. "either subpackage_name or subpackage_path must be specified")
  848. subpackage_name = os.path.basename(subpackage_path)
  849. # handle wildcards
  850. l = subpackage_name.split('.')
  851. if subpackage_path is None and '*' in subpackage_name:
  852. return self._wildcard_get_subpackage(subpackage_name,
  853. parent_name,
  854. caller_level = caller_level+1)
  855. assert '*' not in subpackage_name, repr((subpackage_name, subpackage_path, parent_name))
  856. if subpackage_path is None:
  857. subpackage_path = njoin([self.local_path] + l)
  858. else:
  859. subpackage_path = njoin([subpackage_path] + l[:-1])
  860. subpackage_path = self.paths([subpackage_path])[0]
  861. setup_py = njoin(subpackage_path, self.setup_name)
  862. if not self.options['ignore_setup_xxx_py']:
  863. if not os.path.isfile(setup_py):
  864. setup_py = njoin(subpackage_path,
  865. 'setup_%s.py' % (subpackage_name))
  866. if not os.path.isfile(setup_py):
  867. if not self.options['assume_default_configuration']:
  868. self.warn('Assuming default configuration '\
  869. '(%s/{setup_%s,setup}.py was not found)' \
  870. % (os.path.dirname(setup_py), subpackage_name))
  871. config = Configuration(subpackage_name, parent_name,
  872. self.top_path, subpackage_path,
  873. caller_level = caller_level+1)
  874. else:
  875. config = self._get_configuration_from_setup_py(
  876. setup_py,
  877. subpackage_name,
  878. subpackage_path,
  879. parent_name,
  880. caller_level = caller_level + 1)
  881. if config:
  882. return [config]
  883. else:
  884. return []
  885. def add_subpackage(self,subpackage_name,
  886. subpackage_path=None,
  887. standalone = False):
  888. """Add a sub-package to the current Configuration instance.
  889. This is useful in a setup.py script for adding sub-packages to a
  890. package.
  891. Parameters
  892. ----------
  893. subpackage_name : str
  894. name of the subpackage
  895. subpackage_path : str
  896. if given, the subpackage path such as the subpackage is in
  897. subpackage_path / subpackage_name. If None,the subpackage is
  898. assumed to be located in the local path / subpackage_name.
  899. standalone : bool
  900. """
  901. if standalone:
  902. parent_name = None
  903. else:
  904. parent_name = self.name
  905. config_list = self.get_subpackage(subpackage_name, subpackage_path,
  906. parent_name = parent_name,
  907. caller_level = 2)
  908. if not config_list:
  909. self.warn('No configuration returned, assuming unavailable.')
  910. for config in config_list:
  911. d = config
  912. if isinstance(config, Configuration):
  913. d = config.todict()
  914. assert isinstance(d, dict), repr(type(d))
  915. self.info('Appending %s configuration to %s' \
  916. % (d.get('name'), self.name))
  917. self.dict_append(**d)
  918. dist = self.get_distribution()
  919. if dist is not None:
  920. self.warn('distutils distribution has been initialized,'\
  921. ' it may be too late to add a subpackage '+ subpackage_name)
  922. def add_data_dir(self, data_path):
  923. """Recursively add files under data_path to data_files list.
  924. Recursively add files under data_path to the list of data_files to be
  925. installed (and distributed). The data_path can be either a relative
  926. path-name, or an absolute path-name, or a 2-tuple where the first
  927. argument shows where in the install directory the data directory
  928. should be installed to.
  929. Parameters
  930. ----------
  931. data_path : seq or str
  932. Argument can be either
  933. * 2-sequence (<datadir suffix>, <path to data directory>)
  934. * path to data directory where python datadir suffix defaults
  935. to package dir.
  936. Notes
  937. -----
  938. Rules for installation paths::
  939. foo/bar -> (foo/bar, foo/bar) -> parent/foo/bar
  940. (gun, foo/bar) -> parent/gun
  941. foo/* -> (foo/a, foo/a), (foo/b, foo/b) -> parent/foo/a, parent/foo/b
  942. (gun, foo/*) -> (gun, foo/a), (gun, foo/b) -> gun
  943. (gun/*, foo/*) -> parent/gun/a, parent/gun/b
  944. /foo/bar -> (bar, /foo/bar) -> parent/bar
  945. (gun, /foo/bar) -> parent/gun
  946. (fun/*/gun/*, sun/foo/bar) -> parent/fun/foo/gun/bar
  947. Examples
  948. --------
  949. For example suppose the source directory contains fun/foo.dat and
  950. fun/bar/car.dat:
  951. >>> self.add_data_dir('fun') #doctest: +SKIP
  952. >>> self.add_data_dir(('sun', 'fun')) #doctest: +SKIP
  953. >>> self.add_data_dir(('gun', '/full/path/to/fun'))#doctest: +SKIP
  954. Will install data-files to the locations::
  955. <package install directory>/
  956. fun/
  957. foo.dat
  958. bar/
  959. car.dat
  960. sun/
  961. foo.dat
  962. bar/
  963. car.dat
  964. gun/
  965. foo.dat
  966. car.dat
  967. """
  968. if is_sequence(data_path):
  969. d, data_path = data_path
  970. else:
  971. d = None
  972. if is_sequence(data_path):
  973. [self.add_data_dir((d, p)) for p in data_path]
  974. return
  975. if not is_string(data_path):
  976. raise TypeError("not a string: %r" % (data_path,))
  977. if d is None:
  978. if os.path.isabs(data_path):
  979. return self.add_data_dir((os.path.basename(data_path), data_path))
  980. return self.add_data_dir((data_path, data_path))
  981. paths = self.paths(data_path, include_non_existing=False)
  982. if is_glob_pattern(data_path):
  983. if is_glob_pattern(d):
  984. pattern_list = allpath(d).split(os.sep)
  985. pattern_list.reverse()
  986. # /a/*//b/ -> /a/*/b
  987. rl = list(range(len(pattern_list)-1)); rl.reverse()
  988. for i in rl:
  989. if not pattern_list[i]:
  990. del pattern_list[i]
  991. #
  992. for path in paths:
  993. if not os.path.isdir(path):
  994. print('Not a directory, skipping', path)
  995. continue
  996. rpath = rel_path(path, self.local_path)
  997. path_list = rpath.split(os.sep)
  998. path_list.reverse()
  999. target_list = []
  1000. i = 0
  1001. for s in pattern_list:
  1002. if is_glob_pattern(s):
  1003. if i>=len(path_list):
  1004. raise ValueError('cannot fill pattern %r with %r' \
  1005. % (d, path))
  1006. target_list.append(path_list[i])
  1007. else:
  1008. assert s==path_list[i], repr((s, path_list[i], data_path, d, path, rpath))
  1009. target_list.append(s)
  1010. i += 1
  1011. if path_list[i:]:
  1012. self.warn('mismatch of pattern_list=%s and path_list=%s'\
  1013. % (pattern_list, path_list))
  1014. target_list.reverse()
  1015. self.add_data_dir((os.sep.join(target_list), path))
  1016. else:
  1017. for path in paths:
  1018. self.add_data_dir((d, path))
  1019. return
  1020. assert not is_glob_pattern(d), repr(d)
  1021. dist = self.get_distribution()
  1022. if dist is not None and dist.data_files is not None:
  1023. data_files = dist.data_files
  1024. else:
  1025. data_files = self.data_files
  1026. for path in paths:
  1027. for d1, f in list(general_source_directories_files(path)):
  1028. target_path = os.path.join(self.path_in_package, d, d1)
  1029. data_files.append((target_path, f))
  1030. def _optimize_data_files(self):
  1031. data_dict = {}
  1032. for p, files in self.data_files:
  1033. if p not in data_dict:
  1034. data_dict[p] = set()
  1035. for f in files:
  1036. data_dict[p].add(f)
  1037. self.data_files[:] = [(p, list(files)) for p, files in data_dict.items()]
  1038. def add_data_files(self,*files):
  1039. """Add data files to configuration data_files.
  1040. Parameters
  1041. ----------
  1042. files : sequence
  1043. Argument(s) can be either
  1044. * 2-sequence (<datadir prefix>,<path to data file(s)>)
  1045. * paths to data files where python datadir prefix defaults
  1046. to package dir.
  1047. Notes
  1048. -----
  1049. The form of each element of the files sequence is very flexible
  1050. allowing many combinations of where to get the files from the package
  1051. and where they should ultimately be installed on the system. The most
  1052. basic usage is for an element of the files argument sequence to be a
  1053. simple filename. This will cause that file from the local path to be
  1054. installed to the installation path of the self.name package (package
  1055. path). The file argument can also be a relative path in which case the
  1056. entire relative path will be installed into the package directory.
  1057. Finally, the file can be an absolute path name in which case the file
  1058. will be found at the absolute path name but installed to the package
  1059. path.
  1060. This basic behavior can be augmented by passing a 2-tuple in as the
  1061. file argument. The first element of the tuple should specify the
  1062. relative path (under the package install directory) where the
  1063. remaining sequence of files should be installed to (it has nothing to
  1064. do with the file-names in the source distribution). The second element
  1065. of the tuple is the sequence of files that should be installed. The
  1066. files in this sequence can be filenames, relative paths, or absolute
  1067. paths. For absolute paths the file will be installed in the top-level
  1068. package installation directory (regardless of the first argument).
  1069. Filenames and relative path names will be installed in the package
  1070. install directory under the path name given as the first element of
  1071. the tuple.
  1072. Rules for installation paths:
  1073. #. file.txt -> (., file.txt)-> parent/file.txt
  1074. #. foo/file.txt -> (foo, foo/file.txt) -> parent/foo/file.txt
  1075. #. /foo/bar/file.txt -> (., /foo/bar/file.txt) -> parent/file.txt
  1076. #. ``*``.txt -> parent/a.txt, parent/b.txt
  1077. #. foo/``*``.txt`` -> parent/foo/a.txt, parent/foo/b.txt
  1078. #. ``*/*.txt`` -> (``*``, ``*``/``*``.txt) -> parent/c/a.txt, parent/d/b.txt
  1079. #. (sun, file.txt) -> parent/sun/file.txt
  1080. #. (sun, bar/file.txt) -> parent/sun/file.txt
  1081. #. (sun, /foo/bar/file.txt) -> parent/sun/file.txt
  1082. #. (sun, ``*``.txt) -> parent/sun/a.txt, parent/sun/b.txt
  1083. #. (sun, bar/``*``.txt) -> parent/sun/a.txt, parent/sun/b.txt
  1084. #. (sun/``*``, ``*``/``*``.txt) -> parent/sun/c/a.txt, parent/d/b.txt
  1085. An additional feature is that the path to a data-file can actually be
  1086. a function that takes no arguments and returns the actual path(s) to
  1087. the data-files. This is useful when the data files are generated while
  1088. building the package.
  1089. Examples
  1090. --------
  1091. Add files to the list of data_files to be included with the package.
  1092. >>> self.add_data_files('foo.dat',
  1093. ... ('fun', ['gun.dat', 'nun/pun.dat', '/tmp/sun.dat']),
  1094. ... 'bar/cat.dat',
  1095. ... '/full/path/to/can.dat') #doctest: +SKIP
  1096. will install these data files to::
  1097. <package install directory>/
  1098. foo.dat
  1099. fun/
  1100. gun.dat
  1101. nun/
  1102. pun.dat
  1103. sun.dat
  1104. bar/
  1105. car.dat
  1106. can.dat
  1107. where <package install directory> is the package (or sub-package)
  1108. directory such as '/usr/lib/python2.4/site-packages/mypackage' ('C:
  1109. \\Python2.4 \\Lib \\site-packages \\mypackage') or
  1110. '/usr/lib/python2.4/site- packages/mypackage/mysubpackage' ('C:
  1111. \\Python2.4 \\Lib \\site-packages \\mypackage \\mysubpackage').
  1112. """
  1113. if len(files)>1:
  1114. for f in files:
  1115. self.add_data_files(f)
  1116. return
  1117. assert len(files)==1
  1118. if is_sequence(files[0]):
  1119. d, files = files[0]
  1120. else:
  1121. d = None
  1122. if is_string(files):
  1123. filepat = files
  1124. elif is_sequence(files):
  1125. if len(files)==1:
  1126. filepat = files[0]
  1127. else:
  1128. for f in files:
  1129. self.add_data_files((d, f))
  1130. return
  1131. else:
  1132. raise TypeError(repr(type(files)))
  1133. if d is None:
  1134. if hasattr(filepat, '__call__'):
  1135. d = ''
  1136. elif os.path.isabs(filepat):
  1137. d = ''
  1138. else:
  1139. d = os.path.dirname(filepat)
  1140. self.add_data_files((d, files))
  1141. return
  1142. paths = self.paths(filepat, include_non_existing=False)
  1143. if is_glob_pattern(filepat):
  1144. if is_glob_pattern(d):
  1145. pattern_list = d.split(os.sep)
  1146. pattern_list.reverse()
  1147. for path in paths:
  1148. path_list = path.split(os.sep)
  1149. path_list.reverse()
  1150. path_list.pop() # filename
  1151. target_list = []
  1152. i = 0
  1153. for s in pattern_list:
  1154. if is_glob_pattern(s):
  1155. target_list.append(path_list[i])
  1156. i += 1
  1157. else:
  1158. target_list.append(s)
  1159. target_list.reverse()
  1160. self.add_data_files((os.sep.join(target_list), path))
  1161. else:
  1162. self.add_data_files((d, paths))
  1163. return
  1164. assert not is_glob_pattern(d), repr((d, filepat))
  1165. dist = self.get_distribution()
  1166. if dist is not None and dist.data_files is not None:
  1167. data_files = dist.data_files
  1168. else:
  1169. data_files = self.data_files
  1170. data_files.append((os.path.join(self.path_in_package, d), paths))
  1171. ### XXX Implement add_py_modules
  1172. def add_define_macros(self, macros):
  1173. """Add define macros to configuration
  1174. Add the given sequence of macro name and value duples to the beginning
  1175. of the define_macros list This list will be visible to all extension
  1176. modules of the current package.
  1177. """
  1178. dist = self.get_distribution()
  1179. if dist is not None:
  1180. if not hasattr(dist, 'define_macros'):
  1181. dist.define_macros = []
  1182. dist.define_macros.extend(macros)
  1183. else:
  1184. self.define_macros.extend(macros)
  1185. def add_include_dirs(self,*paths):
  1186. """Add paths to configuration include directories.
  1187. Add the given sequence of paths to the beginning of the include_dirs
  1188. list. This list will be visible to all extension modules of the
  1189. current package.
  1190. """
  1191. include_dirs = self.paths(paths)
  1192. dist = self.get_distribution()
  1193. if dist is not None:
  1194. if dist.include_dirs is None:
  1195. dist.include_dirs = []
  1196. dist.include_dirs.extend(include_dirs)
  1197. else:
  1198. self.include_dirs.extend(include_dirs)
  1199. def add_headers(self,*files):
  1200. """Add installable headers to configuration.
  1201. Add the given sequence of files to the beginning of the headers list.
  1202. By default, headers will be installed under <python-
  1203. include>/<self.name.replace('.','/')>/ directory. If an item of files
  1204. is a tuple, then its first argument specifies the actual installation
  1205. location relative to the <python-include> path.
  1206. Parameters
  1207. ----------
  1208. files : str or seq
  1209. Argument(s) can be either:
  1210. * 2-sequence (<includedir suffix>,<path to header file(s)>)
  1211. * path(s) to header file(s) where python includedir suffix will
  1212. default to package name.
  1213. """
  1214. headers = []
  1215. for path in files:
  1216. if is_string(path):
  1217. [headers.append((self.name, p)) for p in self.paths(path)]
  1218. else:
  1219. if not isinstance(path, (tuple, list)) or len(path) != 2:
  1220. raise TypeError(repr(path))
  1221. [headers.append((path[0], p)) for p in self.paths(path[1])]
  1222. dist = self.get_distribution()
  1223. if dist is not None:
  1224. if dist.headers is None:
  1225. dist.headers = []
  1226. dist.headers.extend(headers)
  1227. else:
  1228. self.headers.extend(headers)
  1229. def paths(self,*paths,**kws):
  1230. """Apply glob to paths and prepend local_path if needed.
  1231. Applies glob.glob(...) to each path in the sequence (if needed) and
  1232. pre-pends the local_path if needed. Because this is called on all
  1233. source lists, this allows wildcard characters to be specified in lists
  1234. of sources for extension modules and libraries and scripts and allows
  1235. path-names be relative to the source directory.
  1236. """
  1237. include_non_existing = kws.get('include_non_existing', True)
  1238. return gpaths(paths,
  1239. local_path = self.local_path,
  1240. include_non_existing=include_non_existing)
  1241. def _fix_paths_dict(self, kw):
  1242. for k in kw.keys():
  1243. v = kw[k]
  1244. if k in ['sources', 'depends', 'include_dirs', 'library_dirs',
  1245. 'module_dirs', 'extra_objects']:
  1246. new_v = self.paths(v)
  1247. kw[k] = new_v
  1248. def add_extension(self,name,sources,**kw):
  1249. """Add extension to configuration.
  1250. Create and add an Extension instance to the ext_modules list. This
  1251. method also takes the following optional keyword arguments that are
  1252. passed on to the Extension constructor.
  1253. Parameters
  1254. ----------
  1255. name : str
  1256. name of the extension
  1257. sources : seq
  1258. list of the sources. The list of sources may contain functions
  1259. (called source generators) which must take an extension instance
  1260. and a build directory as inputs and return a source file or list of
  1261. source files or None. If None is returned then no sources are
  1262. generated. If the Extension instance has no sources after
  1263. processing all source generators, then no extension module is
  1264. built.
  1265. include_dirs :
  1266. define_macros :
  1267. undef_macros :
  1268. library_dirs :
  1269. libraries :
  1270. runtime_library_dirs :
  1271. extra_objects :
  1272. extra_compile_args :
  1273. extra_link_args :
  1274. extra_f77_compile_args :
  1275. extra_f90_compile_args :
  1276. export_symbols :
  1277. swig_opts :
  1278. depends :
  1279. The depends list contains paths to files or directories that the
  1280. sources of the extension module depend on. If any path in the
  1281. depends list is newer than the extension module, then the module
  1282. will be rebuilt.
  1283. language :
  1284. f2py_options :
  1285. module_dirs :
  1286. extra_info : dict or list
  1287. dict or list of dict of keywords to be appended to keywords.
  1288. Notes
  1289. -----
  1290. The self.paths(...) method is applied to all lists that may contain
  1291. paths.
  1292. """
  1293. ext_args = copy.copy(kw)
  1294. ext_args['name'] = dot_join(self.name, name)
  1295. ext_args['sources'] = sources
  1296. if 'extra_info' in ext_args:
  1297. extra_info = ext_args['extra_info']
  1298. del ext_args['extra_info']
  1299. if isinstance(extra_info, dict):
  1300. extra_info = [extra_info]
  1301. for info in extra_info:
  1302. assert isinstance(info, dict), repr(info)
  1303. dict_append(ext_args,**info)
  1304. self._fix_paths_dict(ext_args)
  1305. # Resolve out-of-tree dependencies
  1306. libraries = ext_args.get('libraries', [])
  1307. libnames = []
  1308. ext_args['libraries'] = []
  1309. for libname in libraries:
  1310. if isinstance(libname, tuple):
  1311. self._fix_paths_dict(libname[1])
  1312. # Handle library names of the form libname@relative/path/to/library
  1313. if '@' in libname:
  1314. lname, lpath = libname.split('@', 1)
  1315. lpath = os.path.abspath(njoin(self.local_path, lpath))
  1316. if os.path.isdir(lpath):
  1317. c = self.get_subpackage(None, lpath,
  1318. caller_level = 2)
  1319. if isinstance(c, Configuration):
  1320. c = c.todict()
  1321. for l in [l[0] for l in c.get('libraries', [])]:
  1322. llname = l.split('__OF__', 1)[0]
  1323. if llname == lname:
  1324. c.pop('name', None)
  1325. dict_append(ext_args,**c)
  1326. break
  1327. continue
  1328. libnames.append(libname)
  1329. ext_args['libraries'] = libnames + ext_args['libraries']
  1330. ext_args['define_macros'] = \
  1331. self.define_macros + ext_args.get('define_macros', [])
  1332. from numpy.distutils.core import Extension
  1333. ext = Extension(**ext_args)
  1334. self.ext_modules.append(ext)
  1335. dist = self.get_distribution()
  1336. if dist is not None:
  1337. self.warn('distutils distribution has been initialized,'\
  1338. ' it may be too late to add an extension '+name)
  1339. return ext
  1340. def add_library(self,name,sources,**build_info):
  1341. """
  1342. Add library to configuration.
  1343. Parameters
  1344. ----------
  1345. name : str
  1346. Name of the extension.
  1347. sources : sequence
  1348. List of the sources. The list of sources may contain functions
  1349. (called source generators) which must take an extension instance
  1350. and a build directory as inputs and return a source file or list of
  1351. source files or None. If None is returned then no sources are
  1352. generated. If the Extension instance has no sources after
  1353. processing all source generators, then no extension module is
  1354. built.
  1355. build_info : dict, optional
  1356. The following keys are allowed:
  1357. * depends
  1358. * macros
  1359. * include_dirs
  1360. * extra_compiler_args
  1361. * extra_f77_compile_args
  1362. * extra_f90_compile_args
  1363. * f2py_options
  1364. * language
  1365. """
  1366. self._add_library(name, sources, None, build_info)
  1367. dist = self.get_distribution()
  1368. if dist is not None:
  1369. self.warn('distutils distribution has been initialized,'\
  1370. ' it may be too late to add a library '+ name)
  1371. def _add_library(self, name, sources, install_dir, build_info):
  1372. """Common implementation for add_library and add_installed_library. Do
  1373. not use directly"""
  1374. build_info = copy.copy(build_info)
  1375. build_info['sources'] = sources
  1376. # Sometimes, depends is not set up to an empty list by default, and if
  1377. # depends is not given to add_library, distutils barfs (#1134)
  1378. if not 'depends' in build_info:
  1379. build_info['depends'] = []
  1380. self._fix_paths_dict(build_info)
  1381. # Add to libraries list so that it is build with build_clib
  1382. self.libraries.append((name, build_info))
  1383. def add_installed_library(self, name, sources, install_dir, build_info=None):
  1384. """
  1385. Similar to add_library, but the specified library is installed.
  1386. Most C libraries used with `distutils` are only used to build python
  1387. extensions, but libraries built through this method will be installed
  1388. so that they can be reused by third-party packages.
  1389. Parameters
  1390. ----------
  1391. name : str
  1392. Name of the installed library.
  1393. sources : sequence
  1394. List of the library's source files. See `add_library` for details.
  1395. install_dir : str
  1396. Path to install the library, relative to the current sub-package.
  1397. build_info : dict, optional
  1398. The following keys are allowed:
  1399. * depends
  1400. * macros
  1401. * include_dirs
  1402. * extra_compiler_args
  1403. * extra_f77_compile_args
  1404. * extra_f90_compile_args
  1405. * f2py_options
  1406. * language
  1407. Returns
  1408. -------
  1409. None
  1410. See Also
  1411. --------
  1412. add_library, add_npy_pkg_config, get_info
  1413. Notes
  1414. -----
  1415. The best way to encode the options required to link against the specified
  1416. C libraries is to use a "libname.ini" file, and use `get_info` to
  1417. retrieve the required options (see `add_npy_pkg_config` for more
  1418. information).
  1419. """
  1420. if not build_info:
  1421. build_info = {}
  1422. install_dir = os.path.join(self.package_path, install_dir)
  1423. self._add_library(name, sources, install_dir, build_info)
  1424. self.installed_libraries.append(InstallableLib(name, build_info, install_dir))
  1425. def add_npy_pkg_config(self, template, install_dir, subst_dict=None):
  1426. """
  1427. Generate and install a npy-pkg config file from a template.
  1428. The config file generated from `template` is installed in the
  1429. given install directory, using `subst_dict` for variable substitution.
  1430. Parameters
  1431. ----------
  1432. template : str
  1433. The path of the template, relatively to the current package path.
  1434. install_dir : str
  1435. Where to install the npy-pkg config file, relatively to the current
  1436. package path.
  1437. subst_dict : dict, optional
  1438. If given, any string of the form ``@key@`` will be replaced by
  1439. ``subst_dict[key]`` in the template file when installed. The install
  1440. prefix is always available through the variable ``@prefix@``, since the
  1441. install prefix is not easy to get reliably from setup.py.
  1442. See also
  1443. --------
  1444. add_installed_library, get_info
  1445. Notes
  1446. -----
  1447. This works for both standard installs and in-place builds, i.e. the
  1448. ``@prefix@`` refer to the source directory for in-place builds.
  1449. Examples
  1450. --------
  1451. ::
  1452. config.add_npy_pkg_config('foo.ini.in', 'lib', {'foo': bar})
  1453. Assuming the foo.ini.in file has the following content::
  1454. [meta]
  1455. Name=@foo@
  1456. Version=1.0
  1457. Description=dummy description
  1458. [default]
  1459. Cflags=-I@prefix@/include
  1460. Libs=
  1461. The generated file will have the following content::
  1462. [meta]
  1463. Name=bar
  1464. Version=1.0
  1465. Description=dummy description
  1466. [default]
  1467. Cflags=-Iprefix_dir/include
  1468. Libs=
  1469. and will be installed as foo.ini in the 'lib' subpath.
  1470. When cross-compiling with numpy distutils, it might be necessary to
  1471. use modified npy-pkg-config files. Using the default/generated files
  1472. will link with the host libraries (i.e. libnpymath.a). For
  1473. cross-compilation you of-course need to link with target libraries,
  1474. while using the host Python installation.
  1475. You can copy out the numpy/core/lib/npy-pkg-config directory, add a
  1476. pkgdir value to the .ini files and set NPY_PKG_CONFIG_PATH environment
  1477. variable to point to the directory with the modified npy-pkg-config
  1478. files.
  1479. Example npymath.ini modified for cross-compilation::
  1480. [meta]
  1481. Name=npymath
  1482. Description=Portable, core math library implementing C99 standard
  1483. Version=0.1
  1484. [variables]
  1485. pkgname=numpy.core
  1486. pkgdir=/build/arm-linux-gnueabi/sysroot/usr/lib/python3.7/site-packages/numpy/core
  1487. prefix=${pkgdir}
  1488. libdir=${prefix}/lib
  1489. includedir=${prefix}/include
  1490. [default]
  1491. Libs=-L${libdir} -lnpymath
  1492. Cflags=-I${includedir}
  1493. Requires=mlib
  1494. [msvc]
  1495. Libs=/LIBPATH:${libdir} npymath.lib
  1496. Cflags=/INCLUDE:${includedir}
  1497. Requires=mlib
  1498. """
  1499. if subst_dict is None:
  1500. subst_dict = {}
  1501. template = os.path.join(self.package_path, template)
  1502. if self.name in self.installed_pkg_config:
  1503. self.installed_pkg_config[self.name].append((template, install_dir,
  1504. subst_dict))
  1505. else:
  1506. self.installed_pkg_config[self.name] = [(template, install_dir,
  1507. subst_dict)]
  1508. def add_scripts(self,*files):
  1509. """Add scripts to configuration.
  1510. Add the sequence of files to the beginning of the scripts list.
  1511. Scripts will be installed under the <prefix>/bin/ directory.
  1512. """
  1513. scripts = self.paths(files)
  1514. dist = self.get_distribution()
  1515. if dist is not None:
  1516. if dist.scripts is None:
  1517. dist.scripts = []
  1518. dist.scripts.extend(scripts)
  1519. else:
  1520. self.scripts.extend(scripts)
  1521. def dict_append(self,**dict):
  1522. for key in self.list_keys:
  1523. a = getattr(self, key)
  1524. a.extend(dict.get(key, []))
  1525. for key in self.dict_keys:
  1526. a = getattr(self, key)
  1527. a.update(dict.get(key, {}))
  1528. known_keys = self.list_keys + self.dict_keys + self.extra_keys
  1529. for key in dict.keys():
  1530. if key not in known_keys:
  1531. a = getattr(self, key, None)
  1532. if a and a==dict[key]: continue
  1533. self.warn('Inheriting attribute %r=%r from %r' \
  1534. % (key, dict[key], dict.get('name', '?')))
  1535. setattr(self, key, dict[key])
  1536. self.extra_keys.append(key)
  1537. elif key in self.extra_keys:
  1538. self.info('Ignoring attempt to set %r (from %r to %r)' \
  1539. % (key, getattr(self, key), dict[key]))
  1540. elif key in known_keys:
  1541. # key is already processed above
  1542. pass
  1543. else:
  1544. raise ValueError("Don't know about key=%r" % (key))
  1545. def __str__(self):
  1546. from pprint import pformat
  1547. known_keys = self.list_keys + self.dict_keys + self.extra_keys
  1548. s = '<'+5*'-' + '\n'
  1549. s += 'Configuration of '+self.name+':\n'
  1550. known_keys.sort()
  1551. for k in known_keys:
  1552. a = getattr(self, k, None)
  1553. if a:
  1554. s += '%s = %s\n' % (k, pformat(a))
  1555. s += 5*'-' + '>'
  1556. return s
  1557. def get_config_cmd(self):
  1558. """
  1559. Returns the numpy.distutils config command instance.
  1560. """
  1561. cmd = get_cmd('config')
  1562. cmd.ensure_finalized()
  1563. cmd.dump_source = 0
  1564. cmd.noisy = 0
  1565. old_path = os.environ.get('PATH')
  1566. if old_path:
  1567. path = os.pathsep.join(['.', old_path])
  1568. os.environ['PATH'] = path
  1569. return cmd
  1570. def get_build_temp_dir(self):
  1571. """
  1572. Return a path to a temporary directory where temporary files should be
  1573. placed.
  1574. """
  1575. cmd = get_cmd('build')
  1576. cmd.ensure_finalized()
  1577. return cmd.build_temp
  1578. def have_f77c(self):
  1579. """Check for availability of Fortran 77 compiler.
  1580. Use it inside source generating function to ensure that
  1581. setup distribution instance has been initialized.
  1582. Notes
  1583. -----
  1584. True if a Fortran 77 compiler is available (because a simple Fortran 77
  1585. code was able to be compiled successfully).
  1586. """
  1587. simple_fortran_subroutine = '''
  1588. subroutine simple
  1589. end
  1590. '''
  1591. config_cmd = self.get_config_cmd()
  1592. flag = config_cmd.try_compile(simple_fortran_subroutine, lang='f77')
  1593. return flag
  1594. def have_f90c(self):
  1595. """Check for availability of Fortran 90 compiler.
  1596. Use it inside source generating function to ensure that
  1597. setup distribution instance has been initialized.
  1598. Notes
  1599. -----
  1600. True if a Fortran 90 compiler is available (because a simple Fortran
  1601. 90 code was able to be compiled successfully)
  1602. """
  1603. simple_fortran_subroutine = '''
  1604. subroutine simple
  1605. end
  1606. '''
  1607. config_cmd = self.get_config_cmd()
  1608. flag = config_cmd.try_compile(simple_fortran_subroutine, lang='f90')
  1609. return flag
  1610. def append_to(self, extlib):
  1611. """Append libraries, include_dirs to extension or library item.
  1612. """
  1613. if is_sequence(extlib):
  1614. lib_name, build_info = extlib
  1615. dict_append(build_info,
  1616. libraries=self.libraries,
  1617. include_dirs=self.include_dirs)
  1618. else:
  1619. from numpy.distutils.core import Extension
  1620. assert isinstance(extlib, Extension), repr(extlib)
  1621. extlib.libraries.extend(self.libraries)
  1622. extlib.include_dirs.extend(self.include_dirs)
  1623. def _get_svn_revision(self, path):
  1624. """Return path's SVN revision number.
  1625. """
  1626. try:
  1627. output = subprocess.check_output(['svnversion'], cwd=path)
  1628. except (subprocess.CalledProcessError, OSError):
  1629. pass
  1630. else:
  1631. m = re.match(rb'(?P<revision>\d+)', output)
  1632. if m:
  1633. return int(m.group('revision'))
  1634. if sys.platform=='win32' and os.environ.get('SVN_ASP_DOT_NET_HACK', None):
  1635. entries = njoin(path, '_svn', 'entries')
  1636. else:
  1637. entries = njoin(path, '.svn', 'entries')
  1638. if os.path.isfile(entries):
  1639. with open(entries) as f:
  1640. fstr = f.read()
  1641. if fstr[:5] == '<?xml': # pre 1.4
  1642. m = re.search(r'revision="(?P<revision>\d+)"', fstr)
  1643. if m:
  1644. return int(m.group('revision'))
  1645. else: # non-xml entries file --- check to be sure that
  1646. m = re.search(r'dir[\n\r]+(?P<revision>\d+)', fstr)
  1647. if m:
  1648. return int(m.group('revision'))
  1649. return None
  1650. def _get_hg_revision(self, path):
  1651. """Return path's Mercurial revision number.
  1652. """
  1653. try:
  1654. output = subprocess.check_output(
  1655. ['hg', 'identify', '--num'], cwd=path)
  1656. except (subprocess.CalledProcessError, OSError):
  1657. pass
  1658. else:
  1659. m = re.match(rb'(?P<revision>\d+)', output)
  1660. if m:
  1661. return int(m.group('revision'))
  1662. branch_fn = njoin(path, '.hg', 'branch')
  1663. branch_cache_fn = njoin(path, '.hg', 'branch.cache')
  1664. if os.path.isfile(branch_fn):
  1665. branch0 = None
  1666. with open(branch_fn) as f:
  1667. revision0 = f.read().strip()
  1668. branch_map = {}
  1669. with open(branch_cache_fn, 'r') as f:
  1670. for line in f:
  1671. branch1, revision1 = line.split()[:2]
  1672. if revision1==revision0:
  1673. branch0 = branch1
  1674. try:
  1675. revision1 = int(revision1)
  1676. except ValueError:
  1677. continue
  1678. branch_map[branch1] = revision1
  1679. return branch_map.get(branch0)
  1680. return None
  1681. def get_version(self, version_file=None, version_variable=None):
  1682. """Try to get version string of a package.
  1683. Return a version string of the current package or None if the version
  1684. information could not be detected.
  1685. Notes
  1686. -----
  1687. This method scans files named
  1688. __version__.py, <packagename>_version.py, version.py, and
  1689. __svn_version__.py for string variables version, __version__, and
  1690. <packagename>_version, until a version number is found.
  1691. """
  1692. version = getattr(self, 'version', None)
  1693. if version is not None:
  1694. return version
  1695. # Get version from version file.
  1696. if version_file is None:
  1697. files = ['__version__.py',
  1698. self.name.split('.')[-1]+'_version.py',
  1699. 'version.py',
  1700. '__svn_version__.py',
  1701. '__hg_version__.py']
  1702. else:
  1703. files = [version_file]
  1704. if version_variable is None:
  1705. version_vars = ['version',
  1706. '__version__',
  1707. self.name.split('.')[-1]+'_version']
  1708. else:
  1709. version_vars = [version_variable]
  1710. for f in files:
  1711. fn = njoin(self.local_path, f)
  1712. if os.path.isfile(fn):
  1713. info = ('.py', 'U', 1)
  1714. name = os.path.splitext(os.path.basename(fn))[0]
  1715. n = dot_join(self.name, name)
  1716. try:
  1717. version_module = npy_load_module('_'.join(n.split('.')),
  1718. fn, info)
  1719. except ImportError as e:
  1720. self.warn(str(e))
  1721. version_module = None
  1722. if version_module is None:
  1723. continue
  1724. for a in version_vars:
  1725. version = getattr(version_module, a, None)
  1726. if version is not None:
  1727. break
  1728. # Try if versioneer module
  1729. try:
  1730. version = version_module.get_versions()['version']
  1731. except AttributeError:
  1732. pass
  1733. if version is not None:
  1734. break
  1735. if version is not None:
  1736. self.version = version
  1737. return version
  1738. # Get version as SVN or Mercurial revision number
  1739. revision = self._get_svn_revision(self.local_path)
  1740. if revision is None:
  1741. revision = self._get_hg_revision(self.local_path)
  1742. if revision is not None:
  1743. version = str(revision)
  1744. self.version = version
  1745. return version
  1746. def make_svn_version_py(self, delete=True):
  1747. """Appends a data function to the data_files list that will generate
  1748. __svn_version__.py file to the current package directory.
  1749. Generate package __svn_version__.py file from SVN revision number,
  1750. it will be removed after python exits but will be available
  1751. when sdist, etc commands are executed.
  1752. Notes
  1753. -----
  1754. If __svn_version__.py existed before, nothing is done.
  1755. This is
  1756. intended for working with source directories that are in an SVN
  1757. repository.
  1758. """
  1759. target = njoin(self.local_path, '__svn_version__.py')
  1760. revision = self._get_svn_revision(self.local_path)
  1761. if os.path.isfile(target) or revision is None:
  1762. return
  1763. else:
  1764. def generate_svn_version_py():
  1765. if not os.path.isfile(target):
  1766. version = str(revision)
  1767. self.info('Creating %s (version=%r)' % (target, version))
  1768. with open(target, 'w') as f:
  1769. f.write('version = %r\n' % (version))
  1770. def rm_file(f=target,p=self.info):
  1771. if delete:
  1772. try: os.remove(f); p('removed '+f)
  1773. except OSError: pass
  1774. try: os.remove(f+'c'); p('removed '+f+'c')
  1775. except OSError: pass
  1776. atexit.register(rm_file)
  1777. return target
  1778. self.add_data_files(('', generate_svn_version_py()))
  1779. def make_hg_version_py(self, delete=True):
  1780. """Appends a data function to the data_files list that will generate
  1781. __hg_version__.py file to the current package directory.
  1782. Generate package __hg_version__.py file from Mercurial revision,
  1783. it will be removed after python exits but will be available
  1784. when sdist, etc commands are executed.
  1785. Notes
  1786. -----
  1787. If __hg_version__.py existed before, nothing is done.
  1788. This is intended for working with source directories that are
  1789. in an Mercurial repository.
  1790. """
  1791. target = njoin(self.local_path, '__hg_version__.py')
  1792. revision = self._get_hg_revision(self.local_path)
  1793. if os.path.isfile(target) or revision is None:
  1794. return
  1795. else:
  1796. def generate_hg_version_py():
  1797. if not os.path.isfile(target):
  1798. version = str(revision)
  1799. self.info('Creating %s (version=%r)' % (target, version))
  1800. with open(target, 'w') as f:
  1801. f.write('version = %r\n' % (version))
  1802. def rm_file(f=target,p=self.info):
  1803. if delete:
  1804. try: os.remove(f); p('removed '+f)
  1805. except OSError: pass
  1806. try: os.remove(f+'c'); p('removed '+f+'c')
  1807. except OSError: pass
  1808. atexit.register(rm_file)
  1809. return target
  1810. self.add_data_files(('', generate_hg_version_py()))
  1811. def make_config_py(self,name='__config__'):
  1812. """Generate package __config__.py file containing system_info
  1813. information used during building the package.
  1814. This file is installed to the
  1815. package installation directory.
  1816. """
  1817. self.py_modules.append((self.name, name, generate_config_py))
  1818. def get_info(self,*names):
  1819. """Get resources information.
  1820. Return information (from system_info.get_info) for all of the names in
  1821. the argument list in a single dictionary.
  1822. """
  1823. from .system_info import get_info, dict_append
  1824. info_dict = {}
  1825. for a in names:
  1826. dict_append(info_dict,**get_info(a))
  1827. return info_dict
  1828. def get_cmd(cmdname, _cache={}):
  1829. if cmdname not in _cache:
  1830. import distutils.core
  1831. dist = distutils.core._setup_distribution
  1832. if dist is None:
  1833. from distutils.errors import DistutilsInternalError
  1834. raise DistutilsInternalError(
  1835. 'setup distribution instance not initialized')
  1836. cmd = dist.get_command_obj(cmdname)
  1837. _cache[cmdname] = cmd
  1838. return _cache[cmdname]
  1839. def get_numpy_include_dirs():
  1840. # numpy_include_dirs are set by numpy/core/setup.py, otherwise []
  1841. include_dirs = Configuration.numpy_include_dirs[:]
  1842. if not include_dirs:
  1843. import numpy
  1844. include_dirs = [ numpy.get_include() ]
  1845. # else running numpy/core/setup.py
  1846. return include_dirs
  1847. def get_npy_pkg_dir():
  1848. """Return the path where to find the npy-pkg-config directory.
  1849. If the NPY_PKG_CONFIG_PATH environment variable is set, the value of that
  1850. is returned. Otherwise, a path inside the location of the numpy module is
  1851. returned.
  1852. The NPY_PKG_CONFIG_PATH can be useful when cross-compiling, maintaining
  1853. customized npy-pkg-config .ini files for the cross-compilation
  1854. environment, and using them when cross-compiling.
  1855. """
  1856. d = os.environ.get('NPY_PKG_CONFIG_PATH')
  1857. if d is not None:
  1858. return d
  1859. spec = importlib.util.find_spec('numpy')
  1860. d = os.path.join(os.path.dirname(spec.origin),
  1861. 'core', 'lib', 'npy-pkg-config')
  1862. return d
  1863. def get_pkg_info(pkgname, dirs=None):
  1864. """
  1865. Return library info for the given package.
  1866. Parameters
  1867. ----------
  1868. pkgname : str
  1869. Name of the package (should match the name of the .ini file, without
  1870. the extension, e.g. foo for the file foo.ini).
  1871. dirs : sequence, optional
  1872. If given, should be a sequence of additional directories where to look
  1873. for npy-pkg-config files. Those directories are searched prior to the
  1874. NumPy directory.
  1875. Returns
  1876. -------
  1877. pkginfo : class instance
  1878. The `LibraryInfo` instance containing the build information.
  1879. Raises
  1880. ------
  1881. PkgNotFound
  1882. If the package is not found.
  1883. See Also
  1884. --------
  1885. Configuration.add_npy_pkg_config, Configuration.add_installed_library,
  1886. get_info
  1887. """
  1888. from numpy.distutils.npy_pkg_config import read_config
  1889. if dirs:
  1890. dirs.append(get_npy_pkg_dir())
  1891. else:
  1892. dirs = [get_npy_pkg_dir()]
  1893. return read_config(pkgname, dirs)
  1894. def get_info(pkgname, dirs=None):
  1895. """
  1896. Return an info dict for a given C library.
  1897. The info dict contains the necessary options to use the C library.
  1898. Parameters
  1899. ----------
  1900. pkgname : str
  1901. Name of the package (should match the name of the .ini file, without
  1902. the extension, e.g. foo for the file foo.ini).
  1903. dirs : sequence, optional
  1904. If given, should be a sequence of additional directories where to look
  1905. for npy-pkg-config files. Those directories are searched prior to the
  1906. NumPy directory.
  1907. Returns
  1908. -------
  1909. info : dict
  1910. The dictionary with build information.
  1911. Raises
  1912. ------
  1913. PkgNotFound
  1914. If the package is not found.
  1915. See Also
  1916. --------
  1917. Configuration.add_npy_pkg_config, Configuration.add_installed_library,
  1918. get_pkg_info
  1919. Examples
  1920. --------
  1921. To get the necessary information for the npymath library from NumPy:
  1922. >>> npymath_info = np.distutils.misc_util.get_info('npymath')
  1923. >>> npymath_info #doctest: +SKIP
  1924. {'define_macros': [], 'libraries': ['npymath'], 'library_dirs':
  1925. ['.../numpy/core/lib'], 'include_dirs': ['.../numpy/core/include']}
  1926. This info dict can then be used as input to a `Configuration` instance::
  1927. config.add_extension('foo', sources=['foo.c'], extra_info=npymath_info)
  1928. """
  1929. from numpy.distutils.npy_pkg_config import parse_flags
  1930. pkg_info = get_pkg_info(pkgname, dirs)
  1931. # Translate LibraryInfo instance into a build_info dict
  1932. info = parse_flags(pkg_info.cflags())
  1933. for k, v in parse_flags(pkg_info.libs()).items():
  1934. info[k].extend(v)
  1935. # add_extension extra_info argument is ANAL
  1936. info['define_macros'] = info['macros']
  1937. del info['macros']
  1938. del info['ignored']
  1939. return info
  1940. def is_bootstrapping():
  1941. import builtins
  1942. try:
  1943. builtins.__NUMPY_SETUP__
  1944. return True
  1945. except AttributeError:
  1946. return False
  1947. #########################
  1948. def default_config_dict(name = None, parent_name = None, local_path=None):
  1949. """Return a configuration dictionary for usage in
  1950. configuration() function defined in file setup_<name>.py.
  1951. """
  1952. import warnings
  1953. warnings.warn('Use Configuration(%r,%r,top_path=%r) instead of '\
  1954. 'deprecated default_config_dict(%r,%r,%r)'
  1955. % (name, parent_name, local_path,
  1956. name, parent_name, local_path,
  1957. ), stacklevel=2)
  1958. c = Configuration(name, parent_name, local_path)
  1959. return c.todict()
  1960. def dict_append(d, **kws):
  1961. for k, v in kws.items():
  1962. if k in d:
  1963. ov = d[k]
  1964. if isinstance(ov, str):
  1965. d[k] = v
  1966. else:
  1967. d[k].extend(v)
  1968. else:
  1969. d[k] = v
  1970. def appendpath(prefix, path):
  1971. if os.path.sep != '/':
  1972. prefix = prefix.replace('/', os.path.sep)
  1973. path = path.replace('/', os.path.sep)
  1974. drive = ''
  1975. if os.path.isabs(path):
  1976. drive = os.path.splitdrive(prefix)[0]
  1977. absprefix = os.path.splitdrive(os.path.abspath(prefix))[1]
  1978. pathdrive, path = os.path.splitdrive(path)
  1979. d = os.path.commonprefix([absprefix, path])
  1980. if os.path.join(absprefix[:len(d)], absprefix[len(d):]) != absprefix \
  1981. or os.path.join(path[:len(d)], path[len(d):]) != path:
  1982. # Handle invalid paths
  1983. d = os.path.dirname(d)
  1984. subpath = path[len(d):]
  1985. if os.path.isabs(subpath):
  1986. subpath = subpath[1:]
  1987. else:
  1988. subpath = path
  1989. return os.path.normpath(njoin(drive + prefix, subpath))
  1990. def generate_config_py(target):
  1991. """Generate config.py file containing system_info information
  1992. used during building the package.
  1993. Usage:
  1994. config['py_modules'].append((packagename, '__config__',generate_config_py))
  1995. """
  1996. from numpy.distutils.system_info import system_info
  1997. from distutils.dir_util import mkpath
  1998. mkpath(os.path.dirname(target))
  1999. with open(target, 'w') as f:
  2000. f.write('# This file is generated by numpy\'s %s\n' % (os.path.basename(sys.argv[0])))
  2001. f.write('# It contains system_info results at the time of building this package.\n')
  2002. f.write('__all__ = ["get_info","show"]\n\n')
  2003. # For gfortran+msvc combination, extra shared libraries may exist
  2004. f.write(textwrap.dedent("""
  2005. import os
  2006. import sys
  2007. extra_dll_dir = os.path.join(os.path.dirname(__file__), '.libs')
  2008. if sys.platform == 'win32' and os.path.isdir(extra_dll_dir):
  2009. if sys.version_info >= (3, 8):
  2010. os.add_dll_directory(extra_dll_dir)
  2011. else:
  2012. os.environ.setdefault('PATH', '')
  2013. os.environ['PATH'] += os.pathsep + extra_dll_dir
  2014. """))
  2015. for k, i in system_info.saved_results.items():
  2016. f.write('%s=%r\n' % (k, i))
  2017. f.write(textwrap.dedent(r'''
  2018. def get_info(name):
  2019. g = globals()
  2020. return g.get(name, g.get(name + "_info", {}))
  2021. def show():
  2022. """
  2023. Show libraries in the system on which NumPy was built.
  2024. Print information about various resources (libraries, library
  2025. directories, include directories, etc.) in the system on which
  2026. NumPy was built.
  2027. See Also
  2028. --------
  2029. get_include : Returns the directory containing NumPy C
  2030. header files.
  2031. Notes
  2032. -----
  2033. Classes specifying the information to be printed are defined
  2034. in the `numpy.distutils.system_info` module.
  2035. Information may include:
  2036. * ``language``: language used to write the libraries (mostly
  2037. C or f77)
  2038. * ``libraries``: names of libraries found in the system
  2039. * ``library_dirs``: directories containing the libraries
  2040. * ``include_dirs``: directories containing library header files
  2041. * ``src_dirs``: directories containing library source files
  2042. * ``define_macros``: preprocessor macros used by
  2043. ``distutils.setup``
  2044. * ``baseline``: minimum CPU features required
  2045. * ``found``: dispatched features supported in the system
  2046. * ``not found``: dispatched features that are not supported
  2047. in the system
  2048. Examples
  2049. --------
  2050. >>> import numpy as np
  2051. >>> np.show_config()
  2052. blas_opt_info:
  2053. language = c
  2054. define_macros = [('HAVE_CBLAS', None)]
  2055. libraries = ['openblas', 'openblas']
  2056. library_dirs = ['/usr/local/lib']
  2057. """
  2058. from numpy.core._multiarray_umath import (
  2059. __cpu_features__, __cpu_baseline__, __cpu_dispatch__
  2060. )
  2061. for name,info_dict in globals().items():
  2062. if name[0] == "_" or type(info_dict) is not type({}): continue
  2063. print(name + ":")
  2064. if not info_dict:
  2065. print(" NOT AVAILABLE")
  2066. for k,v in info_dict.items():
  2067. v = str(v)
  2068. if k == "sources" and len(v) > 200:
  2069. v = v[:60] + " ...\n... " + v[-60:]
  2070. print(" %s = %s" % (k,v))
  2071. features_found, features_not_found = [], []
  2072. for feature in __cpu_dispatch__:
  2073. if __cpu_features__[feature]:
  2074. features_found.append(feature)
  2075. else:
  2076. features_not_found.append(feature)
  2077. print("Supported SIMD extensions in this NumPy install:")
  2078. print(" baseline = %s" % (','.join(__cpu_baseline__)))
  2079. print(" found = %s" % (','.join(features_found)))
  2080. print(" not found = %s" % (','.join(features_not_found)))
  2081. '''))
  2082. return target
  2083. def msvc_version(compiler):
  2084. """Return version major and minor of compiler instance if it is
  2085. MSVC, raise an exception otherwise."""
  2086. if not compiler.compiler_type == "msvc":
  2087. raise ValueError("Compiler instance is not msvc (%s)"\
  2088. % compiler.compiler_type)
  2089. return compiler._MSVCCompiler__version
  2090. def get_build_architecture():
  2091. # Importing distutils.msvccompiler triggers a warning on non-Windows
  2092. # systems, so delay the import to here.
  2093. from distutils.msvccompiler import get_build_architecture
  2094. return get_build_architecture()