/Lib/distutils/command/config.py

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