misc_util.py 87 KB

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