misc_util.py 83 KB

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