misc_util.py 83 KB

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