Example #1
0
def test_quickstart_defaults(tempdir):
    answers = {
        'Root path': tempdir,
        'Project name': 'Sphinx Test',
        'Author name': 'Georg Brandl',
        'Project version': '0.1',
    }
    qs.term_input = mock_input(answers)
    d = {}
    qs.ask_user(d)
    qs.generate(d)

    conffile = tempdir / 'conf.py'
    assert conffile.isfile()
    ns = {}
    execfile_(conffile, ns)
    assert ns['extensions'] == []
    assert ns['templates_path'] == ['_templates']
    assert ns['source_suffix'] == '.rst'
    assert ns['master_doc'] == 'index'
    assert ns['project'] == 'Sphinx Test'
    assert ns['copyright'] == '%s, Georg Brandl' % time.strftime('%Y')
    assert ns['version'] == '0.1'
    assert ns['release'] == '0.1'
    assert ns['html_static_path'] == ['_static']
    assert ns['latex_documents'] == [
        ('index', 'SphinxTest.tex', 'Sphinx Test Documentation',
         'Georg Brandl', 'manual')]

    assert (tempdir / '_static').isdir()
    assert (tempdir / '_templates').isdir()
    assert (tempdir / 'index.rst').isfile()
    assert (tempdir / 'Makefile').isfile()
    assert (tempdir / 'make.bat').isfile()
Example #2
0
def test_quickstart_defaults(tempdir):
    answers = {
        'Root path': tempdir,
        'Project name': 'Sphinx Test',
        'Author name': 'Georg Brandl',
        'Project version': '0.1',
    }
    qs.term_input = mock_input(answers)
    d = {}
    qs.ask_user(d)
    qs.generate(d)

    conffile = tempdir / 'conf.py'
    assert conffile.isfile()
    ns = {}
    exec(conffile.read_text(), ns)
    assert ns['extensions'] == []
    assert ns['templates_path'] == ['_templates']
    assert ns['project'] == 'Sphinx Test'
    assert ns['copyright'] == '%s, Georg Brandl' % time.strftime('%Y')
    assert ns['version'] == '0.1'
    assert ns['release'] == '0.1'
    assert ns['html_static_path'] == ['_static']

    assert (tempdir / '_static').isdir()
    assert (tempdir / '_templates').isdir()
    assert (tempdir / 'index.rst').isfile()
    assert (tempdir / 'Makefile').isfile()
    assert (tempdir / 'make.bat').isfile()
Example #3
0
 def generate_pro(self):
     if self.pushButton.isEnabled():
         path = self.lineEdit.text()
         name = self.lineEdit_2.text()
         author = self.lineEdit_3.text()
         version = self.lineEdit_4.text()
         language = self.comboBox.currentText()
         if not path or not name or not author or not language:
             msg_box = QMessageBox(QMessageBox.Warning, '警告', '请填写基本信息')
             msg_box.exec_()
         else:
             info = {'path': path , 'dot': '_', 'version': '', 'suffix': '.rst', 'master': 'index', 'epub': False,
                     'makefile': True, 'batchfile': True, 'make_mode': True, 'extensions': [], 'sep': True,
                     'project': name , 'author': author , 'release': version, 'language': language}
             from sphinx.cmd import quickstart
             try:
                 quickstart.generate(info)
                 msg_box = QMessageBox(QMessageBox.Warning, '提示', '创建成功')
                 msg_box.exec_()
                 record = path + ' ;'
                 with open("sphinx_program.txt", "a") as f:
                     f.write(record)
             except:
                 msg_box = QMessageBox(QMessageBox.Warning, '提示', '创建成功')
                 msg_box.exec_()
Example #4
0
def test_quickstart_all_answers(tempdir):
    answers = {
        'Root path': tempdir,
        'Separate source and build': 'y',
        'Name prefix for templates': '.',
        'Project name': u'STASI™'.encode('utf-8'),
        'Author name': u'Wolfgang Schäuble & G\'Beckstein'.encode('utf-8'),
        'Project version': '2.0',
        'Project release': '2.0.1',
        'Project language': 'de',
        'Source file suffix': '.txt',
        'Name of your master document': 'contents',
        'autodoc': 'y',
        'doctest': 'yes',
        'intersphinx': 'no',
        'todo': 'y',
        'coverage': 'no',
        'imgmath': 'N',
        'mathjax': 'no',
        'ifconfig': 'no',
        'viewcode': 'no',
        'githubpages': 'no',
        'Create Makefile': 'no',
        'Create Windows command file': 'no',
        'Do you want to use the epub builder': 'yes',
    }
    qs.term_input = mock_input(answers, needanswer=True)
    qs.TERM_ENCODING = 'utf-8'
    d = {}
    qs.ask_user(d)
    qs.generate(d)

    conffile = tempdir / 'source' / 'conf.py'
    assert conffile.isfile()
    ns = {}
    execfile_(conffile, ns)
    assert ns['extensions'] == [
        'sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.todo'
    ]
    assert ns['templates_path'] == ['.templates']
    assert ns['source_suffix'] == '.txt'
    assert ns['master_doc'] == 'contents'
    assert ns['project'] == u'STASI™'
    assert ns['copyright'] == u'%s, Wolfgang Schäuble & G\'Beckstein' % \
        time.strftime('%Y')
    assert ns['version'] == '2.0'
    assert ns['release'] == '2.0.1'
    assert ns['todo_include_todos'] is True
    assert ns['html_static_path'] == ['.static']
    assert ns['latex_documents'] == [
        ('contents', 'STASI.tex', u'STASI™ Documentation',
         u'Wolfgang Schäuble \\& G\'Beckstein', 'manual')
    ]

    assert (tempdir / 'build').isdir()
    assert (tempdir / 'source' / '.static').isdir()
    assert (tempdir / 'source' / '.templates').isdir()
    assert (tempdir / 'source' / 'contents.txt').isfile()
def test_quickstart_all_answers(tempdir):
    answers = {
        'Root path': tempdir,
        'Separate source and build': 'y',
        'Name prefix for templates': '.',
        'Project name': u'STASI™'.encode('utf-8'),
        'Author name': u'Wolfgang Schäuble & G\'Beckstein'.encode('utf-8'),
        'Project version': '2.0',
        'Project release': '2.0.1',
        'Project language': 'de',
        'Source file suffix': '.txt',
        'Name of your master document': 'contents',
        'autodoc': 'y',
        'doctest': 'yes',
        'intersphinx': 'no',
        'todo': 'y',
        'coverage': 'no',
        'imgmath': 'N',
        'mathjax': 'no',
        'ifconfig': 'no',
        'viewcode': 'no',
        'githubpages': 'no',
        'Create Makefile': 'no',
        'Create Windows command file': 'no',
        'Do you want to use the epub builder': 'yes',
    }
    qs.term_input = mock_input(answers, needanswer=True)
    qs.TERM_ENCODING = 'utf-8'
    d = {}
    qs.ask_user(d)
    qs.generate(d)

    conffile = tempdir / 'source' / 'conf.py'
    assert conffile.isfile()
    ns = {}
    execfile_(conffile, ns)
    assert ns['extensions'] == [
        'sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.todo'
    ]
    assert ns['templates_path'] == ['.templates']
    assert ns['source_suffix'] == '.txt'
    assert ns['master_doc'] == 'contents'
    assert ns['project'] == u'STASI™'
    assert ns['copyright'] == u'%s, Wolfgang Schäuble & G\'Beckstein' % \
        time.strftime('%Y')
    assert ns['version'] == '2.0'
    assert ns['release'] == '2.0.1'
    assert ns['todo_include_todos'] is True
    assert ns['html_static_path'] == ['.static']
    assert ns['latex_documents'] == [
        ('contents', 'STASI.tex', u'STASI™ Documentation',
         u'Wolfgang Schäuble \\& G\'Beckstein', 'manual')]

    assert (tempdir / 'build').isdir()
    assert (tempdir / 'source' / '.static').isdir()
    assert (tempdir / 'source' / '.templates').isdir()
    assert (tempdir / 'source' / 'contents.txt').isfile()
Example #6
0
def quickstart(path=None):

    templatedir = os.path.join(os.path.dirname(__file__), 'templates')

    d = sphinx_quickstart.DEFAULTS.copy()
    d['extensions'] = ['hieroglyph']
    d.update(
        dict(("ext_" + ext, False) for ext in sphinx_quickstart.EXTENSIONS))
    if path:
        d['path'] = path

    ask_user(d)
    sphinx_quickstart.generate(d, templatedir=templatedir)
Example #7
0
def test_default_filename(tempdir):
    answers = {
        'Root path': tempdir,
        'Project name': '\u30c9\u30a4\u30c4',  # Fullwidth characters only
        'Author name': 'Georg Brandl',
        'Project version': '0.1',
    }
    qs.term_input = mock_input(answers)
    d = {}
    qs.ask_user(d)
    qs.generate(d)

    conffile = tempdir / 'conf.py'
    assert conffile.isfile()
    ns = {}
    exec(conffile.read_text(), ns)
def test_default_filename(tempdir):
    answers = {
        'Root path': tempdir,
        'Project name': u'\u30c9\u30a4\u30c4',  # Fullwidth characters only
        'Author name': 'Georg Brandl',
        'Project version': '0.1',
    }
    qs.term_input = mock_input(answers)
    d = {}
    qs.ask_user(d)
    qs.generate(d)

    conffile = tempdir / 'conf.py'
    assert conffile.isfile()
    ns = {}
    execfile_(conffile, ns)
    assert ns['latex_documents'][0][1] == 'sphinx.tex'
Example #9
0
def test_default_filename(tempdir):
    answers = {
        'Root path': tempdir,
        'Project name': '\u30c9\u30a4\u30c4',  # Fullwidth characters only
        'Author name': 'Georg Brandl',
        'Project version': '0.1',
    }
    qs.term_input = mock_input(answers)
    d = {}
    qs.ask_user(d)
    qs.generate(d)

    conffile = tempdir / 'conf.py'
    assert conffile.isfile()
    ns = {}
    execfile_(conffile, ns)
    assert ns['latex_documents'][0][1] == 'sphinx.tex'
Example #10
0
def test_generated_files_eol(tempdir):
    answers = {
        'Root path': tempdir,
        'Project name': 'Sphinx Test',
        'Author name': 'Georg Brandl',
        'Project version': '0.1',
    }
    qs.term_input = mock_input(answers)
    d = {}
    qs.ask_user(d)
    qs.generate(d)

    def assert_eol(filename, eol):
        content = filename.bytes().decode('unicode-escape')
        assert all([l[-len(eol):] == eol for l in content.splitlines(True)])

    assert_eol(tempdir / 'make.bat', '\r\n')
    assert_eol(tempdir / 'Makefile', '\n')
Example #11
0
def test_generated_files_eol(tempdir):
    answers = {
        'Root path': tempdir,
        'Project name': 'Sphinx Test',
        'Author name': 'Georg Brandl',
        'Project version': '0.1',
    }
    qs.term_input = mock_input(answers)
    d = {}
    qs.ask_user(d)
    qs.generate(d)

    def assert_eol(filename, eol):
        content = filename.read_bytes().decode()
        assert all([l[-len(eol):] == eol for l in content.splitlines(True)])

    assert_eol(tempdir / 'make.bat', '\r\n')
    assert_eol(tempdir / 'Makefile', '\n')
Example #12
0
def test_quickstart_and_build(tempdir):
    answers = {
        'Root path': tempdir,
        'Project name': 'Fullwidth characters: \u30c9\u30a4\u30c4',
        'Author name': 'Georg Brandl',
        'Project version': '0.1',
    }
    qs.term_input = mock_input(answers)
    d = {}
    qs.ask_user(d)
    qs.generate(d)

    app = application.Sphinx(
        tempdir,  # srcdir
        tempdir,  # confdir
        (tempdir / '_build' / 'html'),  # outdir
        (tempdir / '_build' / '.doctree'),  # doctreedir
        'html',  # buildername
        status=StringIO(),
        warning=warnfile)
    app.builder.build_all()
    warnings = warnfile.getvalue()
    assert not warnings
Example #13
0
def test_quickstart_and_build(tempdir):
    answers = {
        'Root path': tempdir,
        'Project name': u'Fullwidth characters: \u30c9\u30a4\u30c4',
        'Author name': 'Georg Brandl',
        'Project version': '0.1',
    }
    qs.term_input = mock_input(answers)
    d = {}
    qs.ask_user(d)
    qs.generate(d)

    app = application.Sphinx(
        tempdir,  # srcdir
        tempdir,  # confdir
        (tempdir / '_build' / 'html'),  # outdir
        (tempdir / '_build' / '.doctree'),  # doctreedir
        'html',  # buildername
        status=StringIO(),
        warning=warnfile)
    app.builder.build_all()
    warnings = warnfile.getvalue()
    assert not warnings
Example #14
0
def main(argv: List[str] = sys.argv[1:]) -> int:
    """Parse and check the command line arguments."""
    sphinx.locale.setlocale(locale.LC_ALL, '')
    sphinx.locale.init_console(os.path.join(package_dir, 'locale'), 'sphinx')

    parser = get_parser()
    args = parser.parse_args(argv)

    rootpath = path.abspath(args.module_path)

    # normalize opts

    if args.header is None:
        args.header = rootpath.split(path.sep)[-1]
    if args.suffix.startswith('.'):
        args.suffix = args.suffix[1:]
    if not path.isdir(rootpath):
        print(__('%s is not a directory.') % rootpath, file=sys.stderr)
        sys.exit(1)
    if not args.dryrun:
        ensuredir(args.destdir)
    excludes = [path.abspath(exclude) for exclude in args.exclude_pattern]
    modules = recurse_tree(rootpath, excludes, args, args.templatedir)

    if args.full:
        from sphinx.cmd import quickstart as qs
        modules.sort()
        prev_module = ''
        text = ''
        for module in modules:
            if module.startswith(prev_module + '.'):
                continue
            prev_module = module
            text += '   %s\n' % module
        d = {
            'path':
            args.destdir,
            'sep':
            False,
            'dot':
            '_',
            'project':
            args.header,
            'author':
            args.author or 'Author',
            'version':
            args.version or '',
            'release':
            args.release or args.version or '',
            'suffix':
            '.' + args.suffix,
            'master':
            'index',
            'epub':
            True,
            'extensions':
            ['sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.todo'],
            'makefile':
            True,
            'batchfile':
            True,
            'make_mode':
            True,
            'mastertocmaxdepth':
            args.maxdepth,
            'mastertoctree':
            text,
            'language':
            'en',
            'module_path':
            rootpath,
            'append_syspath':
            args.append_syspath,
        }
        if args.extensions:
            d['extensions'].extend(args.extensions)

        for ext in d['extensions'][:]:
            if ',' in ext:
                d['extensions'].remove(ext)
                d['extensions'].extend(ext.split(','))

        if not args.dryrun:
            qs.generate(d,
                        silent=True,
                        overwrite=args.force,
                        templatedir=args.templatedir)
    elif args.tocfile:
        create_modules_toc_file(modules, args, args.tocfile, args.templatedir)

    return 0
Example #15
0
def quickstart(
        project: Optional[str] = typer.Option(
            None,
            '-p',
            '--project',
            metavar='PROJECT_NAME',
            help="project name. \ndefault is basename of PROJECT_DIR."),
        author: str = typer.Option(SphinxExpress.default_user,
                                   '-a',
                                   '--author',
                                   metavar='AUTHOR_NAME',
                                   help='author name. default is "{}"'.format(
                                       SphinxExpress.default_user)),
        ver: str = typer.Option('0.0.1',
                                '-v',
                                '--ver',
                                metavar='VERSION',
                                help="version of project."),
        lang: str = typer.Option('ja',
                                 '-l',
                                 '--lang',
                                 metavar='LANG',
                                 help="document language."),
        templatedir: Optional[pathlib.
                              Path] = typer.Option(
                                  SphinxExpress.default_templatedir,
                                  '-t',
                                  '--templatedir',
                                  metavar='TEMPLATE_DIR',
                                  file_okay=False,
                                  resolve_path=True,
                                  exists=True,
                                  help="template directory for template files."
                              ),
        define_value: List[
            str] = typer.Option(None,
                                '-d',
                                '--define',
                                metavar='NAE=VALUE',
                                help="define a template variable."),
        configfile: Optional[pathlib.
                             Path] = typer.Option(
                                 SphinxExpress.default_configfile,
                                 '-c',
                                 '--configfile',
                                 metavar='CONFIG_FILEPATH',
                                 dir_okay=False,
                                 exists=True,
                                 help="sphinx-express configfile."),
        new: bool = typer.Option(False,
                                 '-N',
                                 '--new',
                                 help="Ignore least configures."),
        setup: bool = typer.Option(False,
                                   '--setup',
                                   callback=startup_callback,
                                   help="Copy templates and exit."),
        project_dir: str = typer.Argument(...),
        version: bool = typer.Option(False,
                                     '--version',
                                     callback=version_callback,
                                     is_eager=True,
                                     help="Show version and exit."),
        debug: bool = typer.Option(False, '--debug', hidden=True),
):
    def parse_variables(variable_list):
        dummy = dict()
        for variable in variable_list:
            try:
                name, value = variable.split('=')
                dummy[name] = value
            except ValueError:
                typer.echo(f'Invalid template variable: {variable}')
        return [f'{k}={v}' for k, v in dummy.items()]

    try:
        dir = pathlib.Path(project_dir)
    except TypeError:
        click.echo("\nError: Missing argument 'PROJECT_DIR'.\n\n", err=True)
        raise typer.Exit()

    if not dir.exists():
        dir.mkdir()
    elif dir.is_dir() is not True:
        click.echo(
            "\nError: Your select  project root is already exists. file: {}".
            format(project_dir),
            err=True)
        raise typer.Exit()

    d = DEFAULTS.copy()
    d["path"] = project_dir
    d["project"] = project or pathlib.Path(project_dir).parent

    if lang not in ['en', 'ja']:
        try:
            test_import = f"from sphinx.locale import {lang}"
            eval(test_import)
        except ImportError:
            click.echo(
                f"{lang} is not supported language, using 'en' instead.")
            lang = 'en'

    if new:
        templatedir = None
        d["author"] = author
        d["version"] = ver
        d["lang"] = lang
        d["variables"] = parse_variables(list(define_value))
    else:
        config = SphinxExpress(configfile)
        least_config = config.load_config()
        least_variable = set(d.get("variables", []))
        define_value = set(define_value)
        d["variables"] = parse_variables(list(least_variable | define_value))
        d.update(**least_config)

    ask_user(d)

    generate(d, templatedir=templatedir)

    config.save_config(d)
Example #16
0
def main(argv=sys.argv[1:]):
    # type: (List[str]) -> int
    """Parse and check the command line arguments."""
    parser = get_parser()
    args = parser.parse_args(argv)

    rootpath = path.abspath(args.module_path)

    # normalize opts

    if args.header is None:
        args.header = rootpath.split(path.sep)[-1]
    if args.suffix.startswith('.'):
        args.suffix = args.suffix[1:]
    if not path.isdir(rootpath):
        print('%s is not a directory.' % rootpath, file=sys.stderr)
        sys.exit(1)
    if not path.isdir(args.destdir) and not args.dryrun:
        os.makedirs(args.destdir)
    excludes = [path.abspath(exclude) for exclude in args.exclude_pattern]
    modules = recurse_tree(rootpath, excludes, args)

    if args.full:
        from sphinx.cmd import quickstart as qs
        modules.sort()
        prev_module = ''  # type: unicode
        text = ''
        for module in modules:
            if module.startswith(prev_module + '.'):
                continue
            prev_module = module
            text += '   %s\n' % module
        d = dict(
            path = args.destdir,
            sep = False,
            dot = '_',
            project = args.header,
            author = args.author or 'Author',
            version = args.version or '',
            release = args.release or args.version or '',
            suffix = '.' + args.suffix,
            master = 'index',
            epub = True,
            ext_autodoc = True,
            ext_viewcode = True,
            ext_todo = True,
            makefile = True,
            batchfile = True,
            make_mode = True,
            mastertocmaxdepth = args.maxdepth,
            mastertoctree = text,
            language = 'en',
            module_path = rootpath,
            append_syspath = args.append_syspath,
        )
        enabled_exts = {'ext_' + ext: getattr(args, 'ext_' + ext)
                        for ext in EXTENSIONS if getattr(args, 'ext_' + ext)}
        d.update(enabled_exts)

        if isinstance(args.header, binary_type):
            d['project'] = d['project'].decode('utf-8')
        if isinstance(args.author, binary_type):
            d['author'] = d['author'].decode('utf-8')
        if isinstance(args.version, binary_type):
            d['version'] = d['version'].decode('utf-8')
        if isinstance(args.release, binary_type):
            d['release'] = d['release'].decode('utf-8')

        if not args.dryrun:
            qs.generate(d, silent=True, overwrite=args.force)
    elif not args.notoc:
        create_modules_toc_file(modules, args)

    return 0
Example #17
0
def main(argv=sys.argv[1:]):
    # type: (List[str]) -> int
    """Parse and check the command line arguments."""
    parser = get_parser()
    args = parser.parse_args(argv)

    rootpath = path.abspath(args.module_path)

    # normalize opts

    if args.header is None:
        args.header = rootpath.split(path.sep)[-1]
    if args.suffix.startswith('.'):
        args.suffix = args.suffix[1:]
    if not path.isdir(rootpath):
        print('%s is not a directory.' % rootpath, file=sys.stderr)
        sys.exit(1)
    if not path.isdir(args.destdir) and not args.dryrun:
        os.makedirs(args.destdir)
    excludes = [path.abspath(exclude) for exclude in args.exclude_pattern]
    modules = recurse_tree(rootpath, excludes, args)

    if args.full:
        from sphinx.cmd import quickstart as qs
        modules.sort()
        prev_module = ''  # type: unicode
        text = ''
        for module in modules:
            if module.startswith(prev_module + '.'):
                continue
            prev_module = module
            text += '   %s\n' % module
        d = dict(
            path = args.destdir,
            sep = False,
            dot = '_',
            project = args.header,
            author = args.author or 'Author',
            version = args.version or '',
            release = args.release or args.version or '',
            suffix = '.' + args.suffix,
            master = 'index',
            epub = True,
            extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode',
                          'sphinx.ext.todo'],
            makefile = True,
            batchfile = True,
            make_mode = True,
            mastertocmaxdepth = args.maxdepth,
            mastertoctree = text,
            language = 'en',
            module_path = rootpath,
            append_syspath = args.append_syspath,
        )
        if args.extensions:
            d['extensions'].extend(args.extensions)

        if isinstance(args.header, binary_type):
            d['project'] = d['project'].decode('utf-8')
        if isinstance(args.author, binary_type):
            d['author'] = d['author'].decode('utf-8')
        if isinstance(args.version, binary_type):
            d['version'] = d['version'].decode('utf-8')
        if isinstance(args.release, binary_type):
            d['release'] = d['release'].decode('utf-8')

        if not args.dryrun:
            qs.generate(d, silent=True, overwrite=args.force)
    elif not args.notoc:
        create_modules_toc_file(modules, args)

    return 0
Example #18
0
def main(argv=sys.argv[1:]):
    # type: (List[str]) -> int
    """Parse and check the command line arguments."""
    locale.setlocale(locale.LC_ALL, '')
    sphinx.locale.init_console(os.path.join(package_dir, 'locale'), 'sphinx')

    parser = get_parser()
    args = parser.parse_args(argv)

    rootpath = path.abspath(args.module_path)

    # normalize opts

    if args.header is None:
        args.header = rootpath.split(path.sep)[-1]
    if args.suffix.startswith('.'):
        args.suffix = args.suffix[1:]
    if not path.isdir(rootpath):
        print(__('%s is not a directory.') % rootpath, file=sys.stderr)
        sys.exit(1)
    if not args.dryrun:
        ensuredir(args.destdir)
    excludes = [path.abspath(exclude) for exclude in args.exclude_pattern]
    modules = recurse_tree(rootpath, excludes, args)

    if args.full:
        from sphinx.cmd import quickstart as qs
        modules.sort()
        prev_module = ''  # type: unicode
        text = ''
        for module in modules:
            if module.startswith(prev_module + '.'):
                continue
            prev_module = module
            text += '   %s\n' % module
        d = dict(
            path = args.destdir,
            sep = False,
            dot = '_',
            project = args.header,
            author = args.author or 'Author',
            version = args.version or '',
            release = args.release or args.version or '',
            suffix = '.' + args.suffix,
            master = 'index',
            epub = True,
            extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode',
                          'sphinx.ext.todo'],
            makefile = True,
            batchfile = True,
            make_mode = True,
            mastertocmaxdepth = args.maxdepth,
            mastertoctree = text,
            language = 'en',
            module_path = rootpath,
            append_syspath = args.append_syspath,
        )
        if args.extensions:
            d['extensions'].extend(args.extensions)

        if isinstance(args.header, binary_type):
            d['project'] = d['project'].decode('utf-8')
        if isinstance(args.author, binary_type):
            d['author'] = d['author'].decode('utf-8')
        if isinstance(args.version, binary_type):
            d['version'] = d['version'].decode('utf-8')
        if isinstance(args.release, binary_type):
            d['release'] = d['release'].decode('utf-8')

        if not args.dryrun:
            qs.generate(d, silent=True, overwrite=args.force)
    elif not args.notoc:
        create_modules_toc_file(modules, args)

    return 0
Example #19
0
def main(argv=sys.argv[1:]):
    # type: (List[str]) -> int
    """Parse and check the command line arguments."""
    parser = optparse.OptionParser(
        usage="""\
usage: %prog [options] -o <output_path> <module_path> [exclude_pattern, ...]

Look recursively in <module_path> for Python modules and packages and create
one reST file with automodule directives per package in the <output_path>.

The <exclude_pattern>s can be file and/or directory patterns that will be
excluded from generation.

Note: By default this script will not overwrite already created files.""")

    parser.add_option('-o', '--output-dir', action='store', dest='destdir',
                      help='Directory to place all output', default='')
    parser.add_option('-d', '--maxdepth', action='store', dest='maxdepth',
                      help='Maximum depth of submodules to show in the TOC '
                      '(default: 4)', type='int', default=4)
    parser.add_option('-f', '--force', action='store_true', dest='force',
                      help='Overwrite existing files')
    parser.add_option('-l', '--follow-links', action='store_true',
                      dest='followlinks', default=False,
                      help='Follow symbolic links. Powerful when combined '
                      'with collective.recipe.omelette.')
    parser.add_option('-n', '--dry-run', action='store_true', dest='dryrun',
                      help='Run the script without creating files')
    parser.add_option('-e', '--separate', action='store_true',
                      dest='separatemodules',
                      help='Put documentation for each module on its own page')
    parser.add_option('-P', '--private', action='store_true',
                      dest='includeprivate',
                      help='Include "_private" modules')
    parser.add_option('-T', '--no-toc', action='store_true', dest='notoc',
                      help='Don\'t create a table of contents file')
    parser.add_option('-E', '--no-headings', action='store_true',
                      dest='noheadings',
                      help='Don\'t create headings for the module/package '
                           'packages (e.g. when the docstrings already contain '
                           'them)')
    parser.add_option('-M', '--module-first', action='store_true',
                      dest='modulefirst',
                      help='Put module documentation before submodule '
                      'documentation')
    parser.add_option('--implicit-namespaces', action='store_true',
                      dest='implicit_namespaces',
                      help='Interpret module paths according to PEP-0420 '
                           'implicit namespaces specification')
    parser.add_option('-s', '--suffix', action='store', dest='suffix',
                      help='file suffix (default: rst)', default='rst')
    parser.add_option('-F', '--full', action='store_true', dest='full',
                      help='Generate a full project with sphinx-quickstart')
    parser.add_option('-a', '--append-syspath', action='store_true',
                      dest='append_syspath',
                      help='Append module_path to sys.path, used when --full is given')
    parser.add_option('-H', '--doc-project', action='store', dest='header',
                      help='Project name (default: root module name)')
    parser.add_option('-A', '--doc-author', action='store', dest='author',
                      type='str',
                      help='Project author(s), used when --full is given')
    parser.add_option('-V', '--doc-version', action='store', dest='version',
                      help='Project version, used when --full is given')
    parser.add_option('-R', '--doc-release', action='store', dest='release',
                      help='Project release, used when --full is given, '
                      'defaults to --doc-version')
    parser.add_option('--version', action='store_true', dest='show_version',
                      help='Show version information and exit')
    group = parser.add_option_group('Extension options')
    for ext in EXTENSIONS:
        group.add_option('--ext-' + ext, action='store_true',
                         dest='ext_' + ext, default=False,
                         help='enable %s extension' % ext)

    (opts, args) = parser.parse_args(argv)

    if opts.show_version:
        print('Sphinx (sphinx-apidoc) %s' % __display_version__)
        return 0

    if not args:
        parser.error('A package path is required.')

    rootpath, excludes = args[0], args[1:]
    if not opts.destdir:
        parser.error('An output directory is required.')
    if opts.header is None:
        opts.header = path.abspath(rootpath).split(path.sep)[-1]
    if opts.suffix.startswith('.'):
        opts.suffix = opts.suffix[1:]
    if not path.isdir(rootpath):
        print('%s is not a directory.' % rootpath, file=sys.stderr)
        sys.exit(1)
    if not path.isdir(opts.destdir):
        if not opts.dryrun:
            os.makedirs(opts.destdir)
    rootpath = path.abspath(rootpath)
    excludes = normalize_excludes(rootpath, excludes)
    modules = recurse_tree(rootpath, excludes, opts)
    if opts.full:
        from sphinx.cmd import quickstart as qs
        modules.sort()
        prev_module = ''  # type: unicode
        text = ''
        for module in modules:
            if module.startswith(prev_module + '.'):
                continue
            prev_module = module
            text += '   %s\n' % module
        d = dict(
            path = opts.destdir,
            sep = False,
            dot = '_',
            project = opts.header,
            author = opts.author or 'Author',
            version = opts.version or '',
            release = opts.release or opts.version or '',
            suffix = '.' + opts.suffix,
            master = 'index',
            epub = True,
            ext_autodoc = True,
            ext_viewcode = True,
            ext_todo = True,
            makefile = True,
            batchfile = True,
            mastertocmaxdepth = opts.maxdepth,
            mastertoctree = text,
            language = 'en',
            module_path = rootpath,
            append_syspath = opts.append_syspath,
        )
        enabled_exts = {'ext_' + ext: getattr(opts, 'ext_' + ext)
                        for ext in EXTENSIONS if getattr(opts, 'ext_' + ext)}
        d.update(enabled_exts)

        if isinstance(opts.header, binary_type):
            d['project'] = d['project'].decode('utf-8')
        if isinstance(opts.author, binary_type):
            d['author'] = d['author'].decode('utf-8')
        if isinstance(opts.version, binary_type):
            d['version'] = d['version'].decode('utf-8')
        if isinstance(opts.release, binary_type):
            d['release'] = d['release'].decode('utf-8')

        if not opts.dryrun:
            qs.generate(d, silent=True, overwrite=opts.force)
    elif not opts.notoc:
        create_modules_toc_file(modules, opts)
    return 0
Example #20
0
def main(argv=sys.argv[1:]):
    # type: (List[str]) -> int
    """Parse and check the command line arguments."""
    parser = optparse.OptionParser(usage="""\
usage: %prog [options] -o <output_path> <module_path> [exclude_pattern, ...]

Look recursively in <module_path> for Python modules and packages and create
one reST file with automodule directives per package in the <output_path>.

The <exclude_pattern>s can be file and/or directory patterns that will be
excluded from generation.

Note: By default this script will not overwrite already created files.""")

    parser.add_option('-o',
                      '--output-dir',
                      action='store',
                      dest='destdir',
                      help='Directory to place all output',
                      default='')
    parser.add_option('-d',
                      '--maxdepth',
                      action='store',
                      dest='maxdepth',
                      help='Maximum depth of submodules to show in the TOC '
                      '(default: 4)',
                      type='int',
                      default=4)
    parser.add_option('-f',
                      '--force',
                      action='store_true',
                      dest='force',
                      help='Overwrite existing files')
    parser.add_option('-l',
                      '--follow-links',
                      action='store_true',
                      dest='followlinks',
                      default=False,
                      help='Follow symbolic links. Powerful when combined '
                      'with collective.recipe.omelette.')
    parser.add_option('-n',
                      '--dry-run',
                      action='store_true',
                      dest='dryrun',
                      help='Run the script without creating files')
    parser.add_option('-e',
                      '--separate',
                      action='store_true',
                      dest='separatemodules',
                      help='Put documentation for each module on its own page')
    parser.add_option('-P',
                      '--private',
                      action='store_true',
                      dest='includeprivate',
                      help='Include "_private" modules')
    parser.add_option('-T',
                      '--no-toc',
                      action='store_true',
                      dest='notoc',
                      help='Don\'t create a table of contents file')
    parser.add_option('-E',
                      '--no-headings',
                      action='store_true',
                      dest='noheadings',
                      help='Don\'t create headings for the module/package '
                      'packages (e.g. when the docstrings already contain '
                      'them)')
    parser.add_option('-M',
                      '--module-first',
                      action='store_true',
                      dest='modulefirst',
                      help='Put module documentation before submodule '
                      'documentation')
    parser.add_option('--implicit-namespaces',
                      action='store_true',
                      dest='implicit_namespaces',
                      help='Interpret module paths according to PEP-0420 '
                      'implicit namespaces specification')
    parser.add_option('-s',
                      '--suffix',
                      action='store',
                      dest='suffix',
                      help='file suffix (default: rst)',
                      default='rst')
    parser.add_option('-F',
                      '--full',
                      action='store_true',
                      dest='full',
                      help='Generate a full project with sphinx-quickstart')
    parser.add_option(
        '-a',
        '--append-syspath',
        action='store_true',
        dest='append_syspath',
        help='Append module_path to sys.path, used when --full is given')
    parser.add_option('-H',
                      '--doc-project',
                      action='store',
                      dest='header',
                      help='Project name (default: root module name)')
    parser.add_option('-A',
                      '--doc-author',
                      action='store',
                      dest='author',
                      type='str',
                      help='Project author(s), used when --full is given')
    parser.add_option('-V',
                      '--doc-version',
                      action='store',
                      dest='version',
                      help='Project version, used when --full is given')
    parser.add_option('-R',
                      '--doc-release',
                      action='store',
                      dest='release',
                      help='Project release, used when --full is given, '
                      'defaults to --doc-version')
    parser.add_option('--version',
                      action='store_true',
                      dest='show_version',
                      help='Show version information and exit')
    group = parser.add_option_group('Extension options')
    for ext in EXTENSIONS:
        group.add_option('--ext-' + ext,
                         action='store_true',
                         dest='ext_' + ext,
                         default=False,
                         help='enable %s extension' % ext)

    (opts, args) = parser.parse_args(argv)

    if opts.show_version:
        print('Sphinx (sphinx-apidoc) %s' % __display_version__)
        return 0

    if not args:
        parser.error('A package path is required.')

    rootpath, excludes = args[0], args[1:]
    if not opts.destdir:
        parser.error('An output directory is required.')
    if opts.header is None:
        opts.header = path.abspath(rootpath).split(path.sep)[-1]
    if opts.suffix.startswith('.'):
        opts.suffix = opts.suffix[1:]
    if not path.isdir(rootpath):
        print('%s is not a directory.' % rootpath, file=sys.stderr)
        sys.exit(1)
    if not path.isdir(opts.destdir):
        if not opts.dryrun:
            os.makedirs(opts.destdir)
    rootpath = path.abspath(rootpath)
    excludes = normalize_excludes(rootpath, excludes)
    modules = recurse_tree(rootpath, excludes, opts)
    if opts.full:
        from sphinx.cmd import quickstart as qs
        modules.sort()
        prev_module = ''  # type: unicode
        text = ''
        for module in modules:
            if module.startswith(prev_module + '.'):
                continue
            prev_module = module
            text += '   %s\n' % module
        d = dict(
            path=opts.destdir,
            sep=False,
            dot='_',
            project=opts.header,
            author=opts.author or 'Author',
            version=opts.version or '',
            release=opts.release or opts.version or '',
            suffix='.' + opts.suffix,
            master='index',
            epub=True,
            ext_autodoc=True,
            ext_viewcode=True,
            ext_todo=True,
            makefile=True,
            batchfile=True,
            mastertocmaxdepth=opts.maxdepth,
            mastertoctree=text,
            language='en',
            module_path=rootpath,
            append_syspath=opts.append_syspath,
        )
        enabled_exts = {
            'ext_' + ext: getattr(opts, 'ext_' + ext)
            for ext in EXTENSIONS if getattr(opts, 'ext_' + ext)
        }
        d.update(enabled_exts)

        if isinstance(opts.header, binary_type):
            d['project'] = d['project'].decode('utf-8')
        if isinstance(opts.author, binary_type):
            d['author'] = d['author'].decode('utf-8')
        if isinstance(opts.version, binary_type):
            d['version'] = d['version'].decode('utf-8')
        if isinstance(opts.release, binary_type):
            d['release'] = d['release'].decode('utf-8')

        if not opts.dryrun:
            qs.generate(d, silent=True, overwrite=opts.force)
    elif not opts.notoc:
        create_modules_toc_file(modules, opts)
    return 0
Example #21
0
def main(argv=sys.argv[1:]):
    # type: (List[str]) -> int
    """Parse and check the command line arguments."""
    locale.setlocale(locale.LC_ALL, '')
    sphinx.locale.init_console(os.path.join(package_dir, 'locale'), 'sphinx')

    parser = get_parser()
    args = parser.parse_args(argv)

    rootpath = path.abspath(args.module_path)

    # normalize opts

    if args.header is None:
        args.header = rootpath.split(path.sep)[-1]
    if args.suffix.startswith('.'):
        args.suffix = args.suffix[1:]
    if not path.isdir(rootpath):
        print(__('%s is not a directory.') % rootpath, file=sys.stderr)
        sys.exit(1)
    if not args.dryrun:
        ensuredir(args.destdir)
    excludes = [path.abspath(exclude) for exclude in args.exclude_pattern]
    modules = recurse_tree(rootpath, excludes, args)

    if args.full:
        from sphinx.cmd import quickstart as qs
        modules.sort()
        prev_module = ''
        text = ''
        for module in modules:
            if module.startswith(prev_module + '.'):
                continue
            prev_module = module
            text += '   %s\n' % module
        d = {
            'path': args.destdir,
            'sep': False,
            'dot': '_',
            'project': args.header,
            'author': args.author or 'Author',
            'version': args.version or '',
            'release': args.release or args.version or '',
            'suffix': '.' + args.suffix,
            'master': 'index',
            'epub': True,
            'extensions': ['sphinx.ext.autodoc', 'sphinx.ext.viewcode',
                           'sphinx.ext.todo'],
            'makefile': True,
            'batchfile': True,
            'make_mode': True,
            'mastertocmaxdepth': args.maxdepth,
            'mastertoctree': text,
            'language': 'en',
            'module_path': rootpath,
            'append_syspath': args.append_syspath,
        }
        if args.extensions:
            d['extensions'].extend(args.extensions)

        if not args.dryrun:
            qs.generate(d, silent=True, overwrite=args.force)
    elif args.tocfile:
        create_modules_toc_file(modules, args, args.tocfile)

    return 0