misc_util.py 81 KB

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