Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 
 
 

263 řádky
9.7 KiB

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. sphinx-autopackage-script
  5. This script parses a directory tree looking for python modules and packages and
  6. creates ReST files appropriately to create code documentation with Sphinx.
  7. It also creates a modules index (named modules.<suffix>).
  8. """
  9. # Copyright 2008 Société des arts technologiques (SAT), http://www.sat.qc.ca/
  10. # Copyright 2010 Thomas Waldmann <tw AT waldmann-edv DOT de>
  11. # All rights reserved.
  12. #
  13. # This program is free software: you can redistribute it and/or modify
  14. # it under the terms of the GNU General Public License as published by
  15. # the Free Software Foundation, either version 2 of the License, or
  16. # (at your option) any later version.
  17. #
  18. # This program is distributed in the hope that it will be useful,
  19. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. # GNU General Public License for more details.
  22. #
  23. # You should have received a copy of the GNU General Public License
  24. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  25. import os
  26. import optparse
  27. # automodule options
  28. OPTIONS = ['members',
  29. 'undoc-members',
  30. # 'inherited-members', # disabled because there's a bug in sphinx
  31. 'show-inheritance',
  32. ]
  33. INIT = '__init__.py'
  34. def makename(package, module):
  35. """Join package and module with a dot."""
  36. # Both package and module can be None/empty.
  37. if package:
  38. name = package
  39. if module:
  40. name += '.' + module
  41. else:
  42. name = module
  43. return name
  44. def write_file(name, text, opts):
  45. """Write the output file for module/package <name>."""
  46. if opts.dryrun:
  47. return
  48. fname = os.path.join(opts.destdir, "%s.%s" % (name, opts.suffix))
  49. if not opts.force and os.path.isfile(fname):
  50. print 'File %s already exists, skipping.' % fname
  51. else:
  52. print 'Creating file %s.' % fname
  53. f = open(fname, 'w')
  54. f.write(text)
  55. f.close()
  56. def format_heading(level, text):
  57. """Create a heading of <level> [1, 2 or 3 supported]."""
  58. underlining = ['=', '-', '~', ][level-1] * len(text)
  59. return '%s\n%s\n\n' % (text, underlining)
  60. def format_directive(module, package=None):
  61. """Create the automodule directive and add the options."""
  62. directive = '.. automodule:: %s\n' % makename(package, module)
  63. for option in OPTIONS:
  64. directive += ' :%s:\n' % option
  65. return directive
  66. def create_module_file(package, module, opts):
  67. """Build the text of the file and write the file."""
  68. text = format_heading(1, '%s Module' % module)
  69. text += format_heading(2, ':mod:`%s` Module' % module)
  70. text += format_directive(module, package)
  71. write_file(makename(package, module), text, opts)
  72. def create_package_file(root, master_package, subroot, py_files, opts, subs):
  73. """Build the text of the file and write the file."""
  74. package = os.path.split(root)[-1]
  75. text = format_heading(1, '%s Package' % package)
  76. # add each package's module
  77. for py_file in py_files:
  78. if shall_skip(os.path.join(root, py_file)):
  79. continue
  80. is_package = py_file == INIT
  81. py_file = os.path.splitext(py_file)[0]
  82. py_path = makename(subroot, py_file)
  83. if is_package:
  84. heading = ':mod:`%s` Package' % package
  85. else:
  86. heading = ':mod:`%s` Module' % py_file
  87. text += format_heading(2, heading)
  88. text += format_directive(is_package and subroot or py_path, master_package)
  89. text += '\n'
  90. # build a list of directories that are packages (they contain an INIT file)
  91. subs = [sub for sub in subs if os.path.isfile(os.path.join(root, sub, INIT))]
  92. # if there are some package directories, add a TOC for theses subpackages
  93. if subs:
  94. text += format_heading(2, 'Subpackages')
  95. text += '.. toctree::\n\n'
  96. for sub in subs:
  97. text += ' %s.%s\n' % (makename(master_package, subroot), sub)
  98. text += '\n'
  99. write_file(makename(master_package, subroot), text, opts)
  100. def create_modules_toc_file(master_package, modules, opts, name='modules'):
  101. """
  102. Create the module's index.
  103. """
  104. text = format_heading(1, '%s Modules' % opts.header)
  105. text += '.. toctree::\n'
  106. text += ' :maxdepth: %s\n\n' % opts.maxdepth
  107. modules.sort()
  108. prev_module = ''
  109. for module in modules:
  110. # look if the module is a subpackage and, if yes, ignore it
  111. if module.startswith(prev_module + '.'):
  112. continue
  113. prev_module = module
  114. text += ' %s\n' % module
  115. write_file(name, text, opts)
  116. def shall_skip(module):
  117. """
  118. Check if we want to skip this module.
  119. """
  120. # skip it, if there is nothing (or just \n or \r\n) in the file
  121. return os.path.getsize(module) < 3
  122. def recurse_tree(path, excludes, opts):
  123. """
  124. Look for every file in the directory tree and create the corresponding
  125. ReST files.
  126. """
  127. # use absolute path for root, as relative paths like '../../foo' cause
  128. # 'if "/." in root ...' to filter out *all* modules otherwise
  129. path = os.path.abspath(path)
  130. # check if the base directory is a package and get is name
  131. if INIT in os.listdir(path):
  132. package_name = path.split(os.path.sep)[-1]
  133. else:
  134. package_name = None
  135. toc = []
  136. tree = os.walk(path, False)
  137. for root, subs, files in tree:
  138. # keep only the Python script files
  139. py_files = sorted([f for f in files if os.path.splitext(f)[1] == '.py'])
  140. if INIT in py_files:
  141. py_files.remove(INIT)
  142. py_files.insert(0, INIT)
  143. # remove hidden ('.') and private ('_') directories
  144. subs = sorted([sub for sub in subs if sub[0] not in ['.', '_']])
  145. # check if there are valid files to process
  146. # TODO: could add check for windows hidden files
  147. if "/." in root or "/_" in root \
  148. or not py_files \
  149. or is_excluded(root, excludes):
  150. continue
  151. if INIT in py_files:
  152. # we are in package ...
  153. if (# ... with subpackage(s)
  154. subs
  155. or
  156. # ... with some module(s)
  157. len(py_files) > 1
  158. or
  159. # ... with a not-to-be-skipped INIT file
  160. not shall_skip(os.path.join(root, INIT))
  161. ):
  162. subroot = root[len(path):].lstrip(os.path.sep).replace(os.path.sep, '.')
  163. create_package_file(root, package_name, subroot, py_files, opts, subs)
  164. toc.append(makename(package_name, subroot))
  165. elif root == path:
  166. # if we are at the root level, we don't require it to be a package
  167. for py_file in py_files:
  168. if not shall_skip(os.path.join(path, py_file)):
  169. module = os.path.splitext(py_file)[0]
  170. create_module_file(package_name, module, opts)
  171. toc.append(makename(package_name, module))
  172. # create the module's index
  173. if not opts.notoc:
  174. create_modules_toc_file(package_name, toc, opts)
  175. def normalize_excludes(rootpath, excludes):
  176. """
  177. Normalize the excluded directory list:
  178. * must be either an absolute path or start with rootpath,
  179. * otherwise it is joined with rootpath
  180. * with trailing slash
  181. """
  182. sep = os.path.sep
  183. f_excludes = []
  184. for exclude in excludes:
  185. if not os.path.isabs(exclude) and not exclude.startswith(rootpath):
  186. exclude = os.path.join(rootpath, exclude)
  187. if not exclude.endswith(sep):
  188. exclude += sep
  189. f_excludes.append(exclude)
  190. return f_excludes
  191. def is_excluded(root, excludes):
  192. """
  193. Check if the directory is in the exclude list.
  194. Note: by having trailing slashes, we avoid common prefix issues, like
  195. e.g. an exlude "foo" also accidentally excluding "foobar".
  196. """
  197. sep = os.path.sep
  198. if not root.endswith(sep):
  199. root += sep
  200. for exclude in excludes:
  201. if root.startswith(exclude):
  202. return True
  203. return False
  204. def main():
  205. """
  206. Parse and check the command line arguments.
  207. """
  208. parser = optparse.OptionParser(usage="""usage: %prog [options] <package path> [exclude paths, ...]
  209. Note: By default this script will not overwrite already created files.""")
  210. parser.add_option("-n", "--doc-header", action="store", dest="header", help="Documentation Header (default=Project)", default="Project")
  211. parser.add_option("-d", "--dest-dir", action="store", dest="destdir", help="Output destination directory", default="")
  212. parser.add_option("-s", "--suffix", action="store", dest="suffix", help="module suffix (default=txt)", default="txt")
  213. parser.add_option("-m", "--maxdepth", action="store", dest="maxdepth", help="Maximum depth of submodules to show in the TOC (default=4)", type="int", default=4)
  214. parser.add_option("-r", "--dry-run", action="store_true", dest="dryrun", help="Run the script without creating the files")
  215. parser.add_option("-f", "--force", action="store_true", dest="force", help="Overwrite all the files")
  216. parser.add_option("-t", "--no-toc", action="store_true", dest="notoc", help="Don't create the table of content file")
  217. (opts, args) = parser.parse_args()
  218. if not args:
  219. parser.error("package path is required.")
  220. else:
  221. rootpath, excludes = args[0], args[1:]
  222. if os.path.isdir(rootpath):
  223. # check if the output destination is a valid directory
  224. if opts.destdir and os.path.isdir(opts.destdir):
  225. excludes = normalize_excludes(rootpath, excludes)
  226. recurse_tree(rootpath, excludes, opts)
  227. else:
  228. print '%s is not a valid output destination directory.' % opts.destdir
  229. else:
  230. print '%s is not a valid directory.' % rootpath
  231. if __name__ == '__main__':
  232. main()