misc_util.py 84 KB

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