gtkdoc.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. # Copyright (C) 2011 Igalia S.L.
  2. #
  3. # This library is free software; you can redistribute it and/or
  4. # modify it under the terms of the GNU Lesser General Public
  5. # License as published by the Free Software Foundation; either
  6. # version 2 of the License, or (at your option) any later version.
  7. #
  8. # This library is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. # Lesser General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU Lesser General Public
  14. # License along with this library; if not, write to the Free Software
  15. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  16. import errno
  17. import logging
  18. import os
  19. import os.path
  20. import subprocess
  21. import sys
  22. class GTKDoc(object):
  23. """Class that controls a gtkdoc run.
  24. Each instance of this class represents one gtkdoc configuration
  25. and set of documentation. The gtkdoc package is a series of tools
  26. run consecutively which converts inline C/C++ documentation into
  27. docbook files and then into HTML. This class is suitable for
  28. generating documentation or simply verifying correctness.
  29. Keyword arguments:
  30. output_dir -- The path where gtkdoc output should be placed. Generation
  31. may overwrite file in this directory. Required.
  32. module_name -- The name of the documentation module. For libraries this
  33. is typically the library name. Required if not library path
  34. is given.
  35. source_dirs -- A list of paths to the source code to be scanned. Required.
  36. ignored_files -- A list of filenames to ignore in the source directory. It is
  37. only necessary to provide the basenames of these files.
  38. Typically it is important to provide an updated list of
  39. ignored files to prevent warnings about undocumented symbols.
  40. decorator -- If a decorator is used to unhide certain symbols in header
  41. files this parameter is required for successful scanning.
  42. (default '')
  43. deprecation_guard -- gtkdoc tries to ensure that symbols marked as deprecated
  44. are encased in this C preprocessor define. This is required
  45. to avoid gtkdoc warnings. (default '')
  46. cflags -- This parameter specifies any preprocessor flags necessary for
  47. building the scanner binary during gtkdoc-scanobj. Typically
  48. this includes all absolute include paths necessary to resolve
  49. all header dependencies. (default '')
  50. ldflags -- This parameter specifies any linker flags necessary for
  51. building the scanner binary during gtkdoc-scanobj. Typically
  52. this includes "-lyourlibraryname". (default '')
  53. library_path -- This parameter specifies the path to the directory where you
  54. library resides used for building the scanner binary during
  55. gtkdoc-scanobj. (default '')
  56. doc_dir -- The path to other documentation files necessary to build
  57. the documentation. This files in this directory as well as
  58. the files in the 'html' subdirectory will be copied
  59. recursively into the output directory. (default '')
  60. main_sgml_file -- The path or name (if a doc_dir is given) of the SGML file
  61. that is the considered the main page of your documentation.
  62. (default: <module_name>-docs.sgml)
  63. version -- The version number of the module. If this is provided,
  64. a version.xml file containing the version will be created
  65. in the output directory during documentation generation.
  66. interactive -- Whether or not errors or warnings should prompt the user
  67. to continue or not. When this value is false, generation
  68. will continue despite warnings. (default False)
  69. virtual_root -- A temporary installation directory which is used as the root
  70. where the actual installation prefix lives; this is mostly
  71. useful for packagers, and should be set to what is given to
  72. make install as DESTDIR.
  73. """
  74. def __init__(self, args):
  75. # Parameters specific to scanning.
  76. self.module_name = ''
  77. self.source_dirs = []
  78. self.ignored_files = []
  79. self.decorator = ''
  80. self.deprecation_guard = ''
  81. # Parameters specific to gtkdoc-scanobj.
  82. self.cflags = ''
  83. self.ldflags = ''
  84. self.library_path = ''
  85. # Parameters specific to generation.
  86. self.output_dir = ''
  87. self.doc_dir = ''
  88. self.main_sgml_file = ''
  89. # Parameters specific to gtkdoc-fixxref.
  90. self.cross_reference_deps = []
  91. self.interactive = False
  92. self.logger = logging.getLogger('gtkdoc')
  93. for key, value in iter(args.items()):
  94. setattr(self, key, value)
  95. def raise_error_if_not_specified(key):
  96. if not getattr(self, key):
  97. raise Exception('%s not specified.' % key)
  98. raise_error_if_not_specified('output_dir')
  99. raise_error_if_not_specified('source_dirs')
  100. raise_error_if_not_specified('module_name')
  101. # Make all paths absolute in case we were passed relative paths, since
  102. # we change the current working directory when executing subcommands.
  103. self.output_dir = os.path.abspath(self.output_dir)
  104. self.source_dirs = [os.path.abspath(x) for x in self.source_dirs]
  105. if self.library_path:
  106. self.library_path = os.path.abspath(self.library_path)
  107. if not self.main_sgml_file:
  108. self.main_sgml_file = self.module_name + "-docs.sgml"
  109. def generate(self, html=True):
  110. self.saw_warnings = False
  111. self._copy_doc_files_to_output_dir(html)
  112. self._write_version_xml()
  113. self._run_gtkdoc_scan()
  114. self._run_gtkdoc_scangobj()
  115. self._run_gtkdoc_mktmpl()
  116. self._run_gtkdoc_mkdb()
  117. if not html:
  118. return
  119. self._run_gtkdoc_mkhtml()
  120. self._run_gtkdoc_fixxref()
  121. def _delete_file_if_exists(self, path):
  122. if not os.access(path, os.F_OK | os.R_OK):
  123. return
  124. self.logger.debug('deleting %s', path)
  125. os.unlink(path)
  126. def _create_directory_if_nonexistent(self, path):
  127. try:
  128. os.makedirs(path)
  129. except OSError as error:
  130. if error.errno != errno.EEXIST:
  131. raise
  132. def _raise_exception_if_file_inaccessible(self, path):
  133. if not os.path.exists(path) or not os.access(path, os.R_OK):
  134. raise Exception("Could not access file at: %s" % path)
  135. def _output_has_warnings(self, outputs):
  136. for output in outputs:
  137. if output and output.find('warning'):
  138. return True
  139. return False
  140. def _ask_yes_or_no_question(self, question):
  141. if not self.interactive:
  142. return True
  143. question += ' [y/N] '
  144. answer = None
  145. while answer != 'y' and answer != 'n' and answer != '':
  146. answer = raw_input(question).lower()
  147. return answer == 'y'
  148. def _run_command(self, args, env=None, cwd=None, print_output=True, ignore_warnings=False):
  149. if print_output:
  150. self.logger.info("Running %s", args[0])
  151. self.logger.debug("Full command args: %s", str(args))
  152. process = subprocess.Popen(args, env=env, cwd=cwd,
  153. stdout=subprocess.PIPE,
  154. stderr=subprocess.PIPE)
  155. stdout, stderr = [b.decode("utf-8") for b in process.communicate()]
  156. if print_output:
  157. if stdout:
  158. sys.stdout.write(stdout)
  159. if stderr:
  160. sys.stderr.write(stderr)
  161. if process.returncode != 0:
  162. raise Exception('%s produced a non-zero return code %i'
  163. % (args[0], process.returncode))
  164. if not ignore_warnings and ('warning' in stderr or 'warning' in stdout):
  165. self.saw_warnings = True
  166. if not self._ask_yes_or_no_question('%s produced warnings, '
  167. 'try to continue?' % args[0]):
  168. raise Exception('%s step failed' % args[0])
  169. return stdout.strip()
  170. def _copy_doc_files_to_output_dir(self, html=True):
  171. if not self.doc_dir:
  172. self.logger.info('Not copying any files from doc directory,'
  173. ' because no doc directory given.')
  174. return
  175. def copy_file_replacing_existing(src, dest):
  176. if os.path.isdir(src):
  177. self.logger.debug('skipped directory %s', src)
  178. return
  179. if not os.access(src, os.F_OK | os.R_OK):
  180. self.logger.debug('skipped unreadable %s', src)
  181. return
  182. self._delete_file_if_exists(dest)
  183. self.logger.debug('created %s', dest)
  184. os.link(src, dest)
  185. def copy_all_files_in_directory(src, dest):
  186. for path in os.listdir(src):
  187. copy_file_replacing_existing(os.path.join(src, path),
  188. os.path.join(dest, path))
  189. self.logger.info('Copying template files to output directory...')
  190. self._create_directory_if_nonexistent(self.output_dir)
  191. copy_all_files_in_directory(self.doc_dir, self.output_dir)
  192. if not html:
  193. return
  194. self.logger.info('Copying HTML files to output directory...')
  195. html_src_dir = os.path.join(self.doc_dir, 'html')
  196. html_dest_dir = os.path.join(self.output_dir, 'html')
  197. self._create_directory_if_nonexistent(html_dest_dir)
  198. if os.path.exists(html_src_dir):
  199. copy_all_files_in_directory(html_src_dir, html_dest_dir)
  200. def _write_version_xml(self):
  201. if not self.version:
  202. self.logger.info('No version specified, so not writing version.xml')
  203. return
  204. version_xml_path = os.path.join(self.output_dir, 'version.xml')
  205. src_version_xml_path = os.path.join(self.doc_dir, 'version.xml')
  206. # Don't overwrite version.xml if it was in the doc directory.
  207. if os.path.exists(version_xml_path) and \
  208. os.path.exists(src_version_xml_path):
  209. return
  210. output_file = open(version_xml_path, 'w')
  211. output_file.write(self.version)
  212. output_file.close()
  213. def _ignored_files_basenames(self):
  214. return ' '.join([os.path.basename(x) for x in self.ignored_files])
  215. def _run_gtkdoc_scan(self):
  216. args = ['gtkdoc-scan',
  217. '--module=%s' % self.module_name,
  218. '--rebuild-types']
  219. # Each source directory should be have its own "--source-dir=" prefix.
  220. args.extend(['--source-dir=%s' % path for path in self.source_dirs])
  221. if self.decorator:
  222. args.append('--ignore-decorators=%s' % self.decorator)
  223. if self.deprecation_guard:
  224. args.append('--deprecated-guards=%s' % self.deprecation_guard)
  225. if self.output_dir:
  226. args.append('--output-dir=%s' % self.output_dir)
  227. # gtkdoc-scan wants the basenames of ignored headers, so strip the
  228. # dirname. Different from "--source-dir", the headers should be
  229. # specified as one long string.
  230. ignored_files_basenames = self._ignored_files_basenames()
  231. if ignored_files_basenames:
  232. args.append('--ignore-headers=%s' % ignored_files_basenames)
  233. self._run_command(args)
  234. def _run_gtkdoc_scangobj(self):
  235. env = os.environ
  236. ldflags = self.ldflags
  237. if self.library_path:
  238. ldflags = ' "-L%s" ' % self.library_path + ldflags
  239. current_ld_library_path = env.get('LD_LIBRARY_PATH')
  240. if current_ld_library_path:
  241. env['RUN'] = 'LD_LIBRARY_PATH="%s:%s" ' % (self.library_path, current_ld_library_path)
  242. else:
  243. env['RUN'] = 'LD_LIBRARY_PATH="%s" ' % self.library_path
  244. if ldflags:
  245. env['LDFLAGS'] = '%s %s' % (ldflags, env.get('LDFLAGS', ''))
  246. if self.cflags:
  247. env['CFLAGS'] = '%s %s' % (self.cflags, env.get('CFLAGS', ''))
  248. if 'CFLAGS' in env:
  249. self.logger.debug('CFLAGS=%s', env['CFLAGS'])
  250. if 'LDFLAGS' in env:
  251. self.logger.debug('LDFLAGS %s', env['LDFLAGS'])
  252. if 'RUN' in env:
  253. self.logger.debug('RUN=%s', env['RUN'])
  254. self._run_command(['gtkdoc-scangobj', '--module=%s' % self.module_name],
  255. env=env, cwd=self.output_dir)
  256. def _run_gtkdoc_mktmpl(self):
  257. args = ['gtkdoc-mktmpl', '--module=%s' % self.module_name]
  258. self._run_command(args, cwd=self.output_dir)
  259. def _run_gtkdoc_mkdb(self):
  260. sgml_file = os.path.join(self.output_dir, self.main_sgml_file)
  261. self._raise_exception_if_file_inaccessible(sgml_file)
  262. args = ['gtkdoc-mkdb',
  263. '--module=%s' % self.module_name,
  264. '--main-sgml-file=%s' % sgml_file,
  265. '--source-suffixes=h,c,cpp,cc',
  266. '--output-format=xml',
  267. '--sgml-mode']
  268. ignored_files_basenames = self._ignored_files_basenames()
  269. if ignored_files_basenames:
  270. args.append('--ignore-files=%s' % ignored_files_basenames)
  271. # Each directory should be have its own "--source-dir=" prefix.
  272. args.extend(['--source-dir=%s' % path for path in self.source_dirs])
  273. self._run_command(args, cwd=self.output_dir)
  274. def _run_gtkdoc_mkhtml(self):
  275. html_dest_dir = os.path.join(self.output_dir, 'html')
  276. if not os.path.isdir(html_dest_dir):
  277. raise Exception("%s is not a directory, could not generate HTML"
  278. % html_dest_dir)
  279. elif not os.access(html_dest_dir, os.X_OK | os.R_OK | os.W_OK):
  280. raise Exception("Could not access %s to generate HTML"
  281. % html_dest_dir)
  282. # gtkdoc-mkhtml expects the SGML path to be absolute.
  283. sgml_file = os.path.join(os.path.abspath(self.output_dir),
  284. self.main_sgml_file)
  285. self._raise_exception_if_file_inaccessible(sgml_file)
  286. self._run_command(['gtkdoc-mkhtml', self.module_name, sgml_file],
  287. cwd=html_dest_dir)
  288. def _run_gtkdoc_fixxref(self):
  289. args = ['gtkdoc-fixxref',
  290. '--module-dir=html',
  291. '--html-dir=html']
  292. args.extend(['--extra-dir=%s' % extra_dir for extra_dir in self.cross_reference_deps])
  293. self._run_command(args, cwd=self.output_dir, ignore_warnings=True)
  294. def rebase_installed_docs(self):
  295. if not os.path.isdir(self.output_dir):
  296. raise Exception("Tried to rebase documentation before generating it.")
  297. html_dir = os.path.join(self.virtual_root + self.prefix, 'share', 'gtk-doc', 'html', self.module_name)
  298. if not os.path.isdir(html_dir):
  299. return
  300. args = ['gtkdoc-rebase',
  301. '--relative',
  302. '--html-dir=%s' % html_dir]
  303. args.extend(['--other-dir=%s' % extra_dir for extra_dir in self.cross_reference_deps])
  304. if self.virtual_root:
  305. args.extend(['--dest-dir=%s' % self.virtual_root])
  306. self._run_command(args, cwd=self.output_dir)
  307. def api_missing_documentation(self):
  308. unused_doc_file = os.path.join(self.output_dir, self.module_name + "-unused.txt")
  309. if not os.path.exists(unused_doc_file) or not os.access(unused_doc_file, os.R_OK):
  310. return []
  311. return open(unused_doc_file).read().splitlines()
  312. class PkgConfigGTKDoc(GTKDoc):
  313. """Class reads a library's pkgconfig file to guess gtkdoc parameters.
  314. Some gtkdoc parameters can be guessed by reading a library's pkgconfig
  315. file, including the cflags, ldflags and version parameters. If you
  316. provide these parameters as well, they will be appended to the ones
  317. guessed via the pkgconfig file.
  318. Keyword arguments:
  319. pkg_config_path -- Path to the pkgconfig file for the library. Required.
  320. """
  321. def __init__(self, pkg_config_path, args):
  322. super(PkgConfigGTKDoc, self).__init__(args)
  323. pkg_config = os.environ.get('PKG_CONFIG', 'pkg-config')
  324. if not os.path.exists(pkg_config_path):
  325. raise Exception('Could not find pkg-config file at: %s'
  326. % pkg_config_path)
  327. self.cflags += " " + self._run_command([pkg_config,
  328. pkg_config_path,
  329. '--cflags'], print_output=False)
  330. self.ldflags += " " + self._run_command([pkg_config,
  331. pkg_config_path,
  332. '--libs'], print_output=False)
  333. self.version = self._run_command([pkg_config,
  334. pkg_config_path,
  335. '--modversion'], print_output=False)
  336. self.prefix = self._run_command([pkg_config,
  337. pkg_config_path,
  338. '--variable=prefix'], print_output=False)