PageRenderTime 51ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/distutils/command/config.py

https://bitbucket.org/evelyn559/pypy
Python | 357 lines | 322 code | 10 blank | 25 comment | 11 complexity | 844e3135f2c8e542b01116c5ab1b4a70 MD5 | raw file
  1. """distutils.command.config
  2. Implements the Distutils 'config' command, a (mostly) empty command class
  3. that exists mainly to be sub-classed by specific module distributions and
  4. applications. The idea is that while every "config" command is different,
  5. at least they're all named the same, and users always see "config" in the
  6. list of standard commands. Also, this is a good place to put common
  7. configure-like tasks: "try to compile this C code", or "figure out where
  8. this header file lives".
  9. """
  10. __revision__ = "$Id$"
  11. import os
  12. import re
  13. from distutils.core import Command
  14. from distutils.errors import DistutilsExecError
  15. from distutils.ccompiler import customize_compiler
  16. from distutils import log
  17. LANG_EXT = {'c': '.c', 'c++': '.cxx'}
  18. class config(Command):
  19. description = "prepare to build"
  20. user_options = [
  21. ('compiler=', None,
  22. "specify the compiler type"),
  23. ('cc=', None,
  24. "specify the compiler executable"),
  25. ('include-dirs=', 'I',
  26. "list of directories to search for header files"),
  27. ('define=', 'D',
  28. "C preprocessor macros to define"),
  29. ('undef=', 'U',
  30. "C preprocessor macros to undefine"),
  31. ('libraries=', 'l',
  32. "external C libraries to link with"),
  33. ('library-dirs=', 'L',
  34. "directories to search for external C libraries"),
  35. ('noisy', None,
  36. "show every action (compile, link, run, ...) taken"),
  37. ('dump-source', None,
  38. "dump generated source files before attempting to compile them"),
  39. ]
  40. # The three standard command methods: since the "config" command
  41. # does nothing by default, these are empty.
  42. def initialize_options(self):
  43. self.compiler = None
  44. self.cc = None
  45. self.include_dirs = None
  46. self.libraries = None
  47. self.library_dirs = None
  48. # maximal output for now
  49. self.noisy = 1
  50. self.dump_source = 1
  51. # list of temporary files generated along-the-way that we have
  52. # to clean at some point
  53. self.temp_files = []
  54. def finalize_options(self):
  55. if self.include_dirs is None:
  56. self.include_dirs = self.distribution.include_dirs or []
  57. elif isinstance(self.include_dirs, str):
  58. self.include_dirs = self.include_dirs.split(os.pathsep)
  59. if self.libraries is None:
  60. self.libraries = []
  61. elif isinstance(self.libraries, str):
  62. self.libraries = [self.libraries]
  63. if self.library_dirs is None:
  64. self.library_dirs = []
  65. elif isinstance(self.library_dirs, str):
  66. self.library_dirs = self.library_dirs.split(os.pathsep)
  67. def run(self):
  68. pass
  69. # Utility methods for actual "config" commands. The interfaces are
  70. # loosely based on Autoconf macros of similar names. Sub-classes
  71. # may use these freely.
  72. def _check_compiler(self):
  73. """Check that 'self.compiler' really is a CCompiler object;
  74. if not, make it one.
  75. """
  76. # We do this late, and only on-demand, because this is an expensive
  77. # import.
  78. from distutils.ccompiler import CCompiler, new_compiler
  79. if not isinstance(self.compiler, CCompiler):
  80. self.compiler = new_compiler(compiler=self.compiler,
  81. dry_run=self.dry_run, force=1)
  82. customize_compiler(self.compiler)
  83. if self.include_dirs:
  84. self.compiler.set_include_dirs(self.include_dirs)
  85. if self.libraries:
  86. self.compiler.set_libraries(self.libraries)
  87. if self.library_dirs:
  88. self.compiler.set_library_dirs(self.library_dirs)
  89. def _gen_temp_sourcefile(self, body, headers, lang):
  90. filename = "_configtest" + LANG_EXT[lang]
  91. file = open(filename, "w")
  92. if headers:
  93. for header in headers:
  94. file.write("#include <%s>\n" % header)
  95. file.write("\n")
  96. file.write(body)
  97. if body[-1] != "\n":
  98. file.write("\n")
  99. file.close()
  100. return filename
  101. def _preprocess(self, body, headers, include_dirs, lang):
  102. src = self._gen_temp_sourcefile(body, headers, lang)
  103. out = "_configtest.i"
  104. self.temp_files.extend([src, out])
  105. self.compiler.preprocess(src, out, include_dirs=include_dirs)
  106. return (src, out)
  107. def _compile(self, body, headers, include_dirs, lang):
  108. src = self._gen_temp_sourcefile(body, headers, lang)
  109. if self.dump_source:
  110. dump_file(src, "compiling '%s':" % src)
  111. (obj,) = self.compiler.object_filenames([src])
  112. self.temp_files.extend([src, obj])
  113. self.compiler.compile([src], include_dirs=include_dirs)
  114. return (src, obj)
  115. def _link(self, body, headers, include_dirs, libraries, library_dirs,
  116. lang):
  117. (src, obj) = self._compile(body, headers, include_dirs, lang)
  118. prog = os.path.splitext(os.path.basename(src))[0]
  119. self.compiler.link_executable([obj], prog,
  120. libraries=libraries,
  121. library_dirs=library_dirs,
  122. target_lang=lang)
  123. if self.compiler.exe_extension is not None:
  124. prog = prog + self.compiler.exe_extension
  125. self.temp_files.append(prog)
  126. return (src, obj, prog)
  127. def _clean(self, *filenames):
  128. if not filenames:
  129. filenames = self.temp_files
  130. self.temp_files = []
  131. log.info("removing: %s", ' '.join(filenames))
  132. for filename in filenames:
  133. try:
  134. os.remove(filename)
  135. except OSError:
  136. pass
  137. # XXX these ignore the dry-run flag: what to do, what to do? even if
  138. # you want a dry-run build, you still need some sort of configuration
  139. # info. My inclination is to make it up to the real config command to
  140. # consult 'dry_run', and assume a default (minimal) configuration if
  141. # true. The problem with trying to do it here is that you'd have to
  142. # return either true or false from all the 'try' methods, neither of
  143. # which is correct.
  144. # XXX need access to the header search path and maybe default macros.
  145. def try_cpp(self, body=None, headers=None, include_dirs=None, lang="c"):
  146. """Construct a source file from 'body' (a string containing lines
  147. of C/C++ code) and 'headers' (a list of header files to include)
  148. and run it through the preprocessor. Return true if the
  149. preprocessor succeeded, false if there were any errors.
  150. ('body' probably isn't of much use, but what the heck.)
  151. """
  152. from distutils.ccompiler import CompileError
  153. self._check_compiler()
  154. ok = 1
  155. try:
  156. self._preprocess(body, headers, include_dirs, lang)
  157. except CompileError:
  158. ok = 0
  159. self._clean()
  160. return ok
  161. def search_cpp(self, pattern, body=None, headers=None, include_dirs=None,
  162. lang="c"):
  163. """Construct a source file (just like 'try_cpp()'), run it through
  164. the preprocessor, and return true if any line of the output matches
  165. 'pattern'. 'pattern' should either be a compiled regex object or a
  166. string containing a regex. If both 'body' and 'headers' are None,
  167. preprocesses an empty file -- which can be useful to determine the
  168. symbols the preprocessor and compiler set by default.
  169. """
  170. self._check_compiler()
  171. src, out = self._preprocess(body, headers, include_dirs, lang)
  172. if isinstance(pattern, str):
  173. pattern = re.compile(pattern)
  174. file = open(out)
  175. match = 0
  176. while 1:
  177. line = file.readline()
  178. if line == '':
  179. break
  180. if pattern.search(line):
  181. match = 1
  182. break
  183. file.close()
  184. self._clean()
  185. return match
  186. def try_compile(self, body, headers=None, include_dirs=None, lang="c"):
  187. """Try to compile a source file built from 'body' and 'headers'.
  188. Return true on success, false otherwise.
  189. """
  190. from distutils.ccompiler import CompileError
  191. self._check_compiler()
  192. try:
  193. self._compile(body, headers, include_dirs, lang)
  194. ok = 1
  195. except CompileError:
  196. ok = 0
  197. log.info(ok and "success!" or "failure.")
  198. self._clean()
  199. return ok
  200. def try_link(self, body, headers=None, include_dirs=None, libraries=None,
  201. library_dirs=None, lang="c"):
  202. """Try to compile and link a source file, built from 'body' and
  203. 'headers', to executable form. Return true on success, false
  204. otherwise.
  205. """
  206. from distutils.ccompiler import CompileError, LinkError
  207. self._check_compiler()
  208. try:
  209. self._link(body, headers, include_dirs,
  210. libraries, library_dirs, lang)
  211. ok = 1
  212. except (CompileError, LinkError):
  213. ok = 0
  214. log.info(ok and "success!" or "failure.")
  215. self._clean()
  216. return ok
  217. def try_run(self, body, headers=None, include_dirs=None, libraries=None,
  218. library_dirs=None, lang="c"):
  219. """Try to compile, link to an executable, and run a program
  220. built from 'body' and 'headers'. Return true on success, false
  221. otherwise.
  222. """
  223. from distutils.ccompiler import CompileError, LinkError
  224. self._check_compiler()
  225. try:
  226. src, obj, exe = self._link(body, headers, include_dirs,
  227. libraries, library_dirs, lang)
  228. self.spawn([exe])
  229. ok = 1
  230. except (CompileError, LinkError, DistutilsExecError):
  231. ok = 0
  232. log.info(ok and "success!" or "failure.")
  233. self._clean()
  234. return ok
  235. # -- High-level methods --------------------------------------------
  236. # (these are the ones that are actually likely to be useful
  237. # when implementing a real-world config command!)
  238. def check_func(self, func, headers=None, include_dirs=None,
  239. libraries=None, library_dirs=None, decl=0, call=0):
  240. """Determine if function 'func' is available by constructing a
  241. source file that refers to 'func', and compiles and links it.
  242. If everything succeeds, returns true; otherwise returns false.
  243. The constructed source file starts out by including the header
  244. files listed in 'headers'. If 'decl' is true, it then declares
  245. 'func' (as "int func()"); you probably shouldn't supply 'headers'
  246. and set 'decl' true in the same call, or you might get errors about
  247. a conflicting declarations for 'func'. Finally, the constructed
  248. 'main()' function either references 'func' or (if 'call' is true)
  249. calls it. 'libraries' and 'library_dirs' are used when
  250. linking.
  251. """
  252. self._check_compiler()
  253. body = []
  254. if decl:
  255. body.append("int %s ();" % func)
  256. body.append("int main () {")
  257. if call:
  258. body.append(" %s();" % func)
  259. else:
  260. body.append(" %s;" % func)
  261. body.append("}")
  262. body = "\n".join(body) + "\n"
  263. return self.try_link(body, headers, include_dirs,
  264. libraries, library_dirs)
  265. # check_func ()
  266. def check_lib(self, library, library_dirs=None, headers=None,
  267. include_dirs=None, other_libraries=[]):
  268. """Determine if 'library' is available to be linked against,
  269. without actually checking that any particular symbols are provided
  270. by it. 'headers' will be used in constructing the source file to
  271. be compiled, but the only effect of this is to check if all the
  272. header files listed are available. Any libraries listed in
  273. 'other_libraries' will be included in the link, in case 'library'
  274. has symbols that depend on other libraries.
  275. """
  276. self._check_compiler()
  277. return self.try_link("int main (void) { }",
  278. headers, include_dirs,
  279. [library]+other_libraries, library_dirs)
  280. def check_header(self, header, include_dirs=None, library_dirs=None,
  281. lang="c"):
  282. """Determine if the system header file named by 'header_file'
  283. exists and can be found by the preprocessor; return true if so,
  284. false otherwise.
  285. """
  286. return self.try_cpp(body="/* No body */", headers=[header],
  287. include_dirs=include_dirs)
  288. def dump_file(filename, head=None):
  289. """Dumps a file content into log.info.
  290. If head is not None, will be dumped before the file content.
  291. """
  292. if head is None:
  293. log.info('%s' % filename)
  294. else:
  295. log.info(head)
  296. file = open(filename)
  297. try:
  298. log.info(file.read())
  299. finally:
  300. file.close()