misc_util.py 87 KB

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