config.py 13 KB

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