Beispiel #1
0
def main(cmd, args, options=None):
    """
    Build the documentation, and optionally start the devserver.
    """
    clean_site_dir = 'clean' in options
    if cmd == 'serve':
        config = load_config(options=options)
        serve(config, options=options)
    elif cmd == 'build':
        config = load_config(options=options)
        build(config, clean_site_dir=clean_site_dir)
    elif cmd == 'json':
        config = load_config(options=options)
        build(config, dump_json=True, clean_site_dir=clean_site_dir)
    elif cmd == 'gh-deploy':
        config = load_config(options=options)
        build(config, clean_site_dir=clean_site_dir)
        gh_deploy(config)
    elif cmd == 'new':
        new(args, options)
    else:
        config = load_config(options=options)
        event = events.CLI(config, cmd, args, options)
        event.broadcast()
        if not event.consumed:
            std = ['help', 'new', 'build', 'serve', 'gh-deply', 'json']
            cmds = '|'.join(std + list(events.CLI.commands))
            print('mkdocs [%s] {options}' % cmds)
Beispiel #2
0
    def test_config_option(self):
        """
        Users can explicitly set the config file using the '--config' option.
        Allows users to specify a config other than the default `mkdocs.yml`.
        """
        expected_result = {
            'site_name': 'Example',
            'pages': [{
                'Introduction': 'index.md'
            }],
        }
        file_contents = dedent("""
        site_name: Example
        pages:
        - 'Introduction': 'index.md'
        """)
        with TemporaryDirectory() as temp_path:
            os.mkdir(os.path.join(temp_path, 'docs'))
            config_path = os.path.join(temp_path, 'mkdocs.yml')
            config_file = open(config_path, 'w')

            config_file.write(file_contents)
            config_file.flush()
            config_file.close()

            result = config.load_config(config_file=config_file.name)
            self.assertEqual(result['site_name'], expected_result['site_name'])
            self.assertEqual(result['pages'], expected_result['pages'])
Beispiel #3
0
    def setUpClass(cls) -> None:
        """
        various setup code such as;
            - cloning test repository from GitHub into a temporary directory
            - setting up a basic argparse to test the cli commands
        """

        # cloning the test repository
        try:
            os.chdir(TestEntry.temp_dir_path)
            print('attempting to download test repository', TestEntry.git_repo,
                  'to directory', TestEntry.temp_dir_path)
            subprocess.run(['git', 'clone', TestEntry.git_repo], check=True)
            os.chdir(os.listdir()[0])
        except OSError as e:
            print(e)
            print(
                'failed to change directory. Could be because the temporary directory was not created'
            )
        except Exception as e:
            print(e)
            print('git clone failed')
        else:
            TestEntry.setUpFailed = False

        # failing the test should the setup fail
        if TestEntry.setUpFailed:
            TestEntry.fail(TestEntry, 'setup failed. Stopping tests')

        # loading mkdocs.yml and failing tests if loading fails
        try:
            TestEntry.cfg = config.load_config('mkdocs.yml')
        except Exception as e:
            print(e)
            TestEntry.fail(TestEntry, 'setup failed. Stopping tests')
Beispiel #4
0
    def test_config_option(self):
        """
        Users can explicitly set the config file using the '--config' option.
        Allows users to specify a config other than the default `mkdocs.yml`.
        """
        expected_result = {
            'site_name': 'Example',
            'pages': [
                {'Introduction': 'index.md'}
            ],
        }
        file_contents = dedent("""
        site_name: Example
        pages:
        - ['index.md', 'Introduction']
        """)
        config_file = tempfile.NamedTemporaryFile('w', delete=False)
        try:
            config_file.write(ensure_utf(file_contents))
            config_file.flush()
            config_file.close()

            result = config.load_config(config_file=config_file.name)
            self.assertEqual(result['site_name'], expected_result['site_name'])
            self.assertEqual(result['pages'], expected_result['pages'])
        finally:
            os.remove(config_file.name)
Beispiel #5
0
def run_build(theme_name, output, config_file, quiet):
    """
    Given a theme name and output directory use the configuration
    for the MkDocs documentation and overwrite the site_dir and
    theme. If no output is provided, serve the documentation on
    each theme, one at a time.
    """

    options = {
        'theme': theme_name,
    }

    if config_file is None:
        config_file = open(MKDOCS_CONFIG, 'rb')
        if not quiet:
            print("Using config: {0}".format(config_file.name))

    if not os.path.exists(output):
        os.makedirs(output)
    options['site_dir'] = os.path.join(output, theme_name)

    if not quiet:
        print("Building {0}".format(theme_name))

    try:
        conf = config.load_config(config_file=config_file, **options)
        config_file.close()
        build.build(conf)
        build.build(conf, dump_json=True)
    except Exception:
        print("Error building: {0}".format(theme_name), file=sys.stderr)
        raise
Beispiel #6
0
    def test_deploy_no_cname(self, mock_isfile, mock_import, get_remote,
                             get_sha, is_repo):

        config = load_config(
            remote_branch='test',
        )
        gh_deploy.gh_deploy(config)
Beispiel #7
0
    def test_deploy_no_cname(self, mock_isfile, mock_import, get_remote,
                             get_sha, is_repo):

        config = load_config(
            remote_branch='test',
        )
        gh_deploy.gh_deploy(config)
Beispiel #8
0
    def builder(lang):
        log.info(f'Building {lang}...')
        pre_build(lang, docs_dir)

        lang_path = os.path.join(docs_dir, lang)

        config = load_config(config_file=os.path.join(lang_path, 'mkdocs.yml'),
                             dev_addr=f'{host}:{port}',
                             strict=True,
                             site_dir=os.path.join(site_dir, lang))

        config['site_url'] = f'http://{host}:{port}/{lang}/'

        # mkdocs is usually launched from the docs root directory, so it doesn't resolve relative paths smart enough,
        # leading to some bugs when launched from another place.
        # For example, custom_icons don't work without this dirty hack, and our neat Flipper buttons fail to load :(
        # I could've filled an issue to mkdocs-material-extensions regarding this, but I believe it's more reliable
        # to just switch the working directory, cause there might be other features that rely on it.
        #
        # It was kinda hard to figure this out, and it's actually 9 AM right now and I haven't slept yet, so please
        # satisfy my praise kink by saying 'good girl' telepathically
        cwd = os.getcwd()
        os.chdir(lang_path)

        build(config, live_server=True, dirty=False)

        os.chdir(cwd)
Beispiel #9
0
    def get_plugin_config_from_mkdocs(
        self, mkdocs_yml_filepath: Path, plugin_name: str
    ) -> Config:
        """Load a mkdocs.yml and returns the configuration for the specified plugin.

        :param mkdocs_yml_filepath: path to MkDocs configuration file
        :type mkdocs_yml_filepath: Path
        :param plugin_name: plugin name (as mentionned into the mkdocs.yml)
        :type plugin_name: str

        :return: plugin configuration loaded by MkDocs. Empty if specified plugin is \
        not enabled into the mkdocs.yml.
        :rtype: Config
        """
        # instanciate plugin
        cfg_mkdocs = load_config(str(mkdocs_yml_filepath.resolve()))

        plugins = cfg_mkdocs.get("plugins")
        if "rss" not in plugins:
            logging.warning(
                f"Plugin {plugin_name} is not part of enabled plugin in the MkDocs "
                "configuration file: {mkdocs_yml_filepath}"
            )
            return {}
        plugin_loaded = plugins.get("rss")

        cfg = plugin_loaded.on_config(cfg_mkdocs)
        logging.info("Fixture configuration loaded: " + str(cfg))

        return plugin_loaded.config
Beispiel #10
0
    def builder():
        log.info("Building documentation...")
        config = load_config(
            config_file=config_file,
            dev_addr=dev_addr,
            strict=strict,
            theme=theme,
            theme_dir=theme_dir,
            site_dir=site_dir,
            **kwargs
        )

        # combine CLI watch arguments with config file values
        if config["watch"] is None:
            config["watch"] = watch
        else:
            config["watch"].extend(watch)

        # Override a few config settings after validation
        config['site_url'] = 'http://{}{}'.format(config['dev_addr'], mount_path(config))

        live_server = livereload in ['dirty', 'livereload']
        dirty = livereload == 'dirty'
        build(config, live_server=live_server, dirty=dirty)
        return config
Beispiel #11
0
def gh_deploy_command(config_file, clean):
    """Deply your documentation to GitHub Pages"""
    config = load_config(
        config_file=config_file
    )
    build.build(config, clean_site_dir=clean)
    gh_deploy.gh_deploy(config)
Beispiel #12
0
def HandleYaml(confFile):
    '''
    从YAML文件,处理课程目录
    '''
    conf = config.load_config(config_file=confFile)
    pages = conf["pages"]
    for category in pages:
        for categoryName, values in category.items():
            for item in values:
                for level1_key, level1_value in item.items():
                    title1 = level1_key
                    if isinstance(level1_value, unicode):
                        title = " - ".join([categoryName, level1_key])
                        HandleSingle(title, level1_value)

                    elif isinstance(level1_value, list):
                        for item in level1_value:
                            for level2_key, level2_value in item.items():
                                if isinstance(level2_value, list):
                                    for item in level2_value:
                                        for level3_key, level3_value in item.items(
                                        ):
                                            title = " - ".join([
                                                categoryName, level1_key,
                                                level2_key, level3_key
                                            ])
                                            HandleSingle(title, level3_value)
                                else:
                                    title = " - ".join(
                                        [categoryName, level1_key, level2_key])
                                    HandleSingle(title, level2_value)

                    else:
                        # None
                        pp.pprint("Fatal Error")
Beispiel #13
0
 def test_config_option(self):
     """
     Users can explicitly set the config file using the '--config' option.
     Allows users to specify a config other than the default `mkdocs.yml`.
     """
     expected_result = {
         'site_name': 'Example',
         'pages': [['index.md', 'Introduction']],
     }
     file_contents = dedent("""
     site_name: Example
     pages:
     - ['index.md', 'Introduction']
     """)
     config_file = tempfile.NamedTemporaryFile('w', delete=False)
     try:
         config_file.write(ensure_utf(file_contents))
         config_file.flush()
         options = {'config': config_file.name}
         result = config.load_config(options=options)
         self.assertEqual(result['site_name'], expected_result['site_name'])
         self.assertEqual(result['pages'], expected_result['pages'])
         config_file.close()
     finally:
         os.remove(config_file.name)
Beispiel #14
0
def render_content(input_content, pre_article_id, next_article_id):
    input_content = input_content.replace('\r\n', '    \r\n')
    config = load_config(
        config_file=settings.BASE_DIR + '/blog_django/utils/mkdocs.yml',
        docs_dir=settings.BASE_DIR + '/blog_django/utils/docs',
    )
    site_navigation = nav.SiteNavigation(config['pages'],
                                         config['use_directory_urls'])
    for page in site_navigation.walk_pages():
        pass
    # Process the markdown text
    html_content, table_of_contents, meta = convert_markdown(
        markdown_source=input_content,
        config=config,
        site_navigation=site_navigation)

    html_content = html_content.replace('src="./', 'src="/')
    # 添加视频

    html_content = re.sub("(?P<video><p>@video_start@.*?@video_end@</p>)",
                          sub_video, html_content)

    context = get_global_context(site_navigation, config)
    context['base_url'] = '/static/mk_docs'
    context.update(
        get_page_context(page, html_content, table_of_contents, meta, config))
    context['page'].next_article_id = next_article_id
    context['page'].pre_article_id = pre_article_id

    return context
Beispiel #15
0
def sync(args):
    """
    Pulls the previously built pages from github pages

    Args:
        args (argparse.Namespace): A Namespace object contaning all the command line arguments

    Raises:
        exceptions.ConfigurationError
    """

    cfg = config.load_config(config_file=args.config_file)
    with tempfile.TemporaryDirectory() as tempdir:
        # clone gh-pages branch into a temp dir
        os.chdir(tempdir)
        subprocess.run(
            ['git', 'clone', '-b', cfg['remote_branch'], cfg['repo_url']])
        # noinspection PyArgumentList
        os.chdir(os.listdir()[0])

        # remove old site folder
        try:
            shutil.rmtree(cfg['site_dir'])
            os.mkdir(cfg['site_dir']
                     )  # rmtree deletes folder so you need to recreate folder
        except FileNotFoundError as identifier:
            print(identifier)
            print('no site directory')

        # copy files into site directory
        with os.scandir(os.getcwd()) as files:
            for i in files:
                print(i.name, i.path)
                shutil.move(i.path, cfg['site_dir'])
Beispiel #16
0
def mkdocs_site(tmpdir):
    mkdocs_root = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                               'test_data')

    cfg = config.load_config(os.path.join(mkdocs_root, 'mkdocs.yml'))
    cfg['site_dir'] = tmpdir
    build.build(cfg)
Beispiel #17
0
    def test_config_option(self):
        """
        Users can explicitly set the config file using the '--config' option.
        Allows users to specify a config other than the default `mkdocs.yml`.
        """
        expected_result = {
            'site_name': 'Example',
            'pages': [
                {'Introduction': 'index.md'}
            ],
        }
        file_contents = dedent("""
        site_name: Example
        pages:
        - 'Introduction': 'index.md'
        """)
        with TemporaryDirectory() as temp_path:
            os.mkdir(os.path.join(temp_path, 'docs'))
            config_path = os.path.join(temp_path, 'mkdocs.yml')
            config_file = open(config_path, 'w')

            config_file.write(ensure_utf(file_contents))
            config_file.flush()
            config_file.close()

            result = config.load_config(config_file=config_file.name)
            self.assertEqual(result['site_name'], expected_result['site_name'])
            self.assertEqual(result['pages'], expected_result['pages'])
Beispiel #18
0
 def on_any_event(self, event):
     if not isinstance(event, events.DirModifiedEvent):
         time.sleep(0.05)
         print 'Rebuilding documentation...',
         config = load_config(options=self.options)
         build(config, live_server=True)
         print ' done'
Beispiel #19
0
    def test_invalid_config(self):
        file_contents = dedent("""
        - ['index.md', 'Introduction']
        - ['index.md', 'Introduction']
        - ['index.md', 'Introduction']
        """)
        config_file = tempfile.NamedTemporaryFile('w', delete=False)
        try:
            config_file.write(file_contents)
            config_file.flush()
            config_file.close()

            with self.assertRaises(ConfigurationError):
                config.load_config(config_file=open(config_file.name, 'rb'))
        finally:
            os.remove(config_file.name)
Beispiel #20
0
def publish(context, skip_update_ipns):
    Printer.start("Publishing your site to IPFS...")
    with cd(DEFAULT_SITE_DIR):
        Printer.info("Building site...")
        build(load_config(config_file='./mkdocs.yml'))

    if not os.path.exists(IPFS_BIN):
        Printer.error("Please run 'hfs2018 init' first")
        context.abort()

    Printer.info(
        'Uploading to IPFS and updating IPNS record (optional). This may take some time...'
    )
    with ipfs_daemon(IPFS_BIN):
        site_output_dir = os.path.join(DEFAULT_SITE_DIR, "site")
        Printer.info("We are uploading the site to IPFS now...")
        site_hash = add_to_ipfs(site_output_dir)
        Printer.info(
            f"The site is available at https://gateway.ipfs.io/ipfs/{site_hash}"
        )

        if not skip_update_ipns:
            Printer.info("We are updating the IPNS record now...")
            ipns_hash = update_ipns_record(site_hash)

            Printer.ready(
                f'Your site is available on IPNS! You can reach it via:'
                f' https://gateway.ipfs.io/ipns/{ipns_hash}')
Beispiel #21
0
def json_command(clean, config_file, strict, site_dir):
    """Build the MkDocs documentation to JSON files

    Rather than building your documentation to HTML pages, this
    outputs each page in a simple JSON format. This command is
    useful if you want to index your documentation in an external
    search engine.
    """

    log.warning("The json command is deprecated and will be removed in a "
                "future MkDocs release. For details on updating: "
                "http://www.mkdocs.org/about/release-notes/")

    # Don't override config value if user did not specify --strict flag
    # Conveniently, load_config drops None values
    strict = strict or None

    try:
        build.build(config.load_config(
            config_file=config_file,
            strict=strict,
            site_dir=site_dir
        ), dump_json=True, dirty=not clean)
    except exceptions.ConfigurationError as e:
        # Avoid ugly, unhelpful traceback
        raise SystemExit('\n' + str(e))
Beispiel #22
0
def build_command(clean, config_file, strict, theme):
    """Build the MkDocs documentation"""
    build.build(load_config(
        config_file=config_file,
        strict=strict,
        theme=theme
    ), clean_site_dir=clean)
Beispiel #23
0
def run_build(theme_name, output, config_file, quiet):
    """
    Given a theme name and output directory use the configuration
    for the MkDocs documentation and overwrite the site_dir and
    theme. If no output is provided, serve the documentation on
    each theme, one at a time.
    """

    options = {
        'theme': theme_name,
    }

    if config_file is None:
        config_file = open(MKDOCS_CONFIG, 'rb')
        if not quiet:
            print("Using config: {0}".format(config_file.name))

    if not os.path.exists(output):
        os.makedirs(output)
    options['site_dir'] = os.path.join(output, theme_name)

    if not quiet:
        print("Building {0}".format(theme_name))

    try:
        conf = config.load_config(config_file=config_file, **options)
        config_file.close()
        build.build(conf)
        build.build(conf, dump_json=True)
    except Exception:
        print("Error building: {0}".format(theme_name), file=sys.stderr)
        raise
Beispiel #24
0
def json_command(clean, config_file, strict, site_dir):
    """Build the MkDocs documentation to JSON files

    Rather than building your documentation to HTML pages, this
    outputs each page in a simple JSON format. This command is
    useful if you want to index your documentation in an external
    search engine.
    """

    log.warning("The json command is deprecated and will be removed in a "
                "future MkDocs release. For details on updating: "
                "http://www.mkdocs.org/about/release-notes/")

    # Don't override config value if user did not specify --strict flag
    # Conveniently, load_config drops None values
    strict = strict or None

    try:
        build.build(config.load_config(
            config_file=config_file,
            strict=strict,
            site_dir=site_dir
        ), dump_json=True, dirty=not clean)
    except exceptions.ConfigurationError as e:  # pragma: no cover
        # Avoid ugly, unhelpful traceback
        raise SystemExit('\n' + str(e))
Beispiel #25
0
def gh_deploy_command(config_file, clean, message, remote_branch):
    """Deply your documentation to GitHub Pages"""
    config = load_config(
        config_file=config_file,
        remote_branch=remote_branch
    )
    build.build(config, clean_site_dir=clean)
    gh_deploy.gh_deploy(config, message=message)
Beispiel #26
0
def serve_command(dev_addr, config_file, strict, theme):
    """Run the builtin development server"""
    serve.serve(load_config(
        config_file=config_file,
        dev_addr=dev_addr,
        strict=strict,
        theme=theme,
    ))
Beispiel #27
0
def buildTo(branch):
    print 'Building doc pages for: %s...' % (branch)
    branchCfg = config.load_config()
    if branchCfg['extra']['version'] != branch:
        updateConfigVersion(branch)
    sh.mkdocs('build', '--site-dir', 'site/%s' % (branch))
    if branchCfg['extra']['version'] != branch:
        sh.git('checkout', '--', 'mkdocs.yml')
Beispiel #28
0
def handle_mkdocs_ghdeploy():
    delete_branch('gh-pages')
    cfg = config.load_config(
        config_file=os.path.join(CWD, "docs/mkdocs.yml"),
        repo_url='[email protected]:sumeetpatil/TravisTest.git')
    build.build(cfg)
    print('Deploying {} Github Pages to {}#gh-pages')
    gh_deploy.gh_deploy(cfg, force=True)
Beispiel #29
0
def buildTo(branch):
    print 'Building doc pages for: %s...' % (branch)
    branchCfg = config.load_config()
    if branchCfg['extra']['version'] != branch:
        updateConfigVersion(branch)
    sh.mkdocs('build', '--site-dir', 'site/%s' % (branch))
    if branchCfg['extra']['version'] != branch:
        sh.git('checkout', '--', 'mkdocs.yml')
Beispiel #30
0
def build_command(clean, **kwargs):
    """Build the MkDocs documentation"""

    try:
        build.build(config.load_config(**kwargs), dirty=not clean)
    except exceptions.ConfigurationError as e:  # pragma: no cover
        # Avoid ugly, unhelpful traceback
        raise SystemExit('\n' + str(e))
def handle_mkdocs_ghdeploy(to_ghdeploy, kind, remote):
    if to_ghdeploy:
        delete_branch('gh-pages')
        cfg = config.load_config(config_file=os.path.join(
            CWD, select_config(kind)),
                                 remote_name=remote)
        build.build(cfg)
        print('Deploying {} Github Pages to {}#gh-pages'.format(kind, remote))
        gh_deploy.gh_deploy(cfg, force=True)
Beispiel #32
0
def main(cmd, args, options=None):
    """
    Build the documentation, and optionally start the devserver.
    """
    if cmd == 'serve':
        config = load_config(options=options)
        serve(config, options=options)
    elif cmd == 'build':
        config = load_config(options=options)
        build(config)
    elif cmd == 'gh-deploy':
        config = load_config(options=options)
        build(config)
        gh_deploy(config)
    elif cmd == 'new':
        new(args, options)
    else:
        print('mkdocs [help|new|build|serve|gh-deploy] {options}')
Beispiel #33
0
def gh_deploy_command(clean, message, remote_branch, remote_name, force, ignore_version, shell, **kwargs):
    """Deploy your documentation to GitHub Pages"""
    cfg = config.load_config(
        remote_branch=remote_branch,
        remote_name=remote_name,
        **kwargs
    )
    build.build(cfg, dirty=not clean)
    gh_deploy.gh_deploy(cfg, message=message, force=force, ignore_version=ignore_version, shell=shell)
Beispiel #34
0
    def test_deploy_error(self, mock_log, mock_import):
        error_string = 'TestError123'
        mock_import.return_value = (False, error_string)

        config = load_config(remote_branch='test', )

        self.assertRaises(SystemExit, gh_deploy.gh_deploy, config)
        mock_log.error.assert_called_once_with(
            'Failed to deploy to GitHub with error: \n%s', error_string)
Beispiel #35
0
def buildForTest():
    print "Building site pages..."
    updateConfigVersion('develop')
    sh.rm('-rf', 'site')
    sh.mkdocs('build', '--clean')
    sh.git('checkout', '--', 'mkdocs.yml')

    cfg = config.load_config()
    for version in cfg['extra']['versions']:
        deployVersion(version)
Beispiel #36
0
def buildForTest():
    print "Building site pages..."
    updateConfigVersion('develop')
    sh.rm('-rf', 'site')
    sh.mkdocs('build', '--clean')
    sh.git('checkout', '--', 'mkdocs.yml')

    cfg = config.load_config()
    for version in cfg['extra']['versions']:
        deployVersion(version)
Beispiel #37
0
def build(cwd, site_dir):

    cfg = config.load_config()

    # sanity check - the version dirs exist as named
    for version in cfg['extra']['versions']:
        if not 'separate' in version or not version['separate']:
            d = os.path.join('versions', version['dir'])
            print('Verifying dir %s' % (d))
            if not os.path.isdir(d):
                print("The directory %s does not exist" % (d))
                return

    # sanity check - dependent_repos exist in '..'
    for repo in dependent_repos:
        d = os.path.join(cwd, '..', repo)
        print('Verifying repo dependency in %s' % (d))
        if not os.path.isdir(d):
            print("The directory %s does not exist" % (d))
            return

    # sanity check - only one latest
    latest = False
    for version in cfg['extra']['versions']:
        if not latest and 'latest' in version and version['latest']:
            print('Latest is %s' % (version['dir']))
            latest = True
        elif latest and 'latest' in version and version['latest']:
            print('ERROR: More than one version is latest.')
            print('Only one version can be latest: True.')
            print('Check mkdocs.yml.')
            return

    print("Building site pages")
    sh.rm('-rf', site_dir)
    sh.mkdocs('build', '--clean', '--site-dir', site_dir)

    for version in cfg['extra']['versions']:
        print("Building doc pages for: %s" % (version['dir']))
        if not 'separate' in version or not version['separate']:
            sh.mkdocs('build',
                      '--site-dir',
                      os.path.join(site_dir, version['dir']),
                      _cwd=os.path.join("versions", version['dir']))
        else:
            repo_dir = os.path.join(cwd, '..', 'mynewt-documentation')
            if version['dir'] != 'master':
                repo_dir = os.path.join(repo_dir, 'versions', version['dir'],
                                        'mynewt-documentation')
            sh.make('clean', _cwd=repo_dir)
            sh.make('docs', _cwd=repo_dir)
            sh.mv(os.path.join(repo_dir, '_build', 'html'),
                  os.path.join(site_dir, version['dir']))
        if 'latest' in version and version['latest']:
            sh.ln('-s', version['dir'], 'latest', _cwd=site_dir)
Beispiel #38
0
    def test_deploy_error(self, mock_log, mock_import):
        error_string = 'TestError123'
        mock_import.return_value = (False, error_string)

        config = load_config(
            remote_branch='test',
        )

        self.assertRaises(SystemExit, gh_deploy.gh_deploy, config)
        mock_log.error.assert_called_once_with('Failed to deploy to GitHub with error: \n%s',
                                               error_string)
Beispiel #39
0
 def builder():
     log.info("Building documentation...")
     config = load_config(
         config_file=config_file,
         dev_addr=dev_addr,
         strict=strict,
         theme=theme,
     )
     config['site_dir'] = tempdir
     build(config, live_server=True)
     return config
Beispiel #40
0
def gh_deploy_command(config_file, clean, message, remote_branch, remote_name):
    """Deploy your documentation to GitHub Pages"""
    try:
        config = load_config(config_file=config_file,
                             remote_branch=remote_branch,
                             remote_name=remote_name)
        build.build(config, clean_site_dir=clean)
        gh_deploy.gh_deploy(config, message=message)
    except exceptions.ConfigurationError as e:
        # Avoid ugly, unhelpful traceback
        raise SystemExit('\n' + str(e))
Beispiel #41
0
def build_command(clean, config_file, strict, theme, site_dir):
    """Build the MkDocs documentation"""
    try:
        build.build(load_config(
            config_file=config_file,
            strict=strict,
            theme=theme,
            site_dir=site_dir
        ), clean_site_dir=clean)
    except exceptions.ConfigurationError as e:
        # Avoid ugly, unhelpful traceback
        raise SystemExit('\n' + str(e))
Beispiel #42
0
def main(cmd, args, options=None):
    """
    Build the documentation, and optionally start the devserver.
    """
    if cmd == 'serve':
        config = load_config(options=options)
        serve(config, options=options)
    elif cmd == 'build':
        config = load_config(options=options)
        build(config)
    elif cmd == 'json':
        config = load_config(options=options)
        build(config, dump_json=True)
    elif cmd == 'gh-deploy':
        config = load_config(options=options)
        build(config)
        gh_deploy(config)
    elif cmd == 'new':
        new(args, options)
    else:
        print('mkdocs [help|new|build|serve|gh-deploy|json] {options}')
Beispiel #43
0
def serve(config, options=None):
    """
    Start the devserver, and rebuild the docs whenever any changes take effect.
    """
    # Create a temporary build directory, and set some options to serve it
    tempdir = tempfile.mkdtemp()
    options['site_dir'] = tempdir

    # Only use user-friendly URLs when running the live server
    options['use_directory_urls'] = True

    # Perform the initial build
    config = load_config(options=options)
    build(config, live_server=True)

    # Note: We pass any command-line options through so that we
    #       can re-apply them if the config file is reloaded.
    event_handler = BuildEventHandler(options)
    config_event_handler = ConfigEventHandler(options)

    # We could have used `Observer()`, which can be faster, but
    # `PollingObserver()` works more universally.
    observer = PollingObserver()
    observer.schedule(event_handler, config['docs_dir'], recursive=True)
    for theme_dir in config['theme_dir']:
        if not os.path.exists(theme_dir):
            continue
        observer.schedule(event_handler, theme_dir, recursive=True)
    observer.schedule(config_event_handler, '.')
    observer.start()

    class TCPServer(socketserver.TCPServer):
        allow_reuse_address = True

    class DocsDirectoryHandler(FixedDirectoryHandler):
        base_dir = config['site_dir']

    host, port = config['dev_addr'].split(':', 1)
    server = TCPServer((host, int(port)), DocsDirectoryHandler)

    print('Running at: http://%s:%s/' % (host, port))
    print('Live reload enabled.')
    print('Hold ctrl+c to quit.')
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        print('Stopping server...')

    # Clean up
    observer.stop()
    observer.join()
    shutil.rmtree(tempdir)
    print('Quit complete')
Beispiel #44
0
def gh_deploy_command(config_file, clean, message, remote_branch):
    """Deply your documentation to GitHub Pages"""
    try:
        config = load_config(
            config_file=config_file,
            remote_branch=remote_branch
        )
        build.build(config, clean_site_dir=clean)
        gh_deploy.gh_deploy(config, message=message)
    except exceptions.ConfigurationError as e:
        # Avoid ugly, unhelpful traceback
        raise SystemExit('\n' + str(e))
Beispiel #45
0
def json_command(clean, config_file, strict):
    """Build the MkDocs documentation to JSON files

    Rather than building your documentation to HTML pages, this
    outputs each page in a simple JSON format. This command is
    useful if you want to index your documentation in an external
    search engine.
    """
    build.build(load_config(
        config_file=config_file,
        strict=strict
    ), dump_json=True, clean_site_dir=clean)
Beispiel #46
0
def gh_deploy_command(config_file, clean, message, remote_branch, remote_name, force):
    """Deploy your documentation to GitHub Pages"""
    try:
        cfg = config.load_config(
            config_file=config_file,
            remote_branch=remote_branch,
            remote_name=remote_name
        )
        build.build(cfg, dirty=not clean)
        gh_deploy.gh_deploy(cfg, message=message, force=force)
    except exceptions.ConfigurationError as e:  # pragma: no cover
        # Avoid ugly, unhelpful traceback
        raise SystemExit('\n' + str(e))
Beispiel #47
0
def main(cmd, args, options=None):
    """
    Build the documentation, and optionally start the devserver.
    """
    clean_site_dir = 'clean' in options
    if cmd == 'serve':
        config = load_config(options=options)
        serve(config, options=options)
    elif cmd == 'build':
        config = load_config(options=options)
        build(config, clean_site_dir=clean_site_dir)
    elif cmd == 'json':
        config = load_config(options=options)
        build(config, dump_json=True, clean_site_dir=clean_site_dir)
    elif cmd == 'gh-deploy':
        config = load_config(options=options)
        build(config, clean_site_dir=clean_site_dir)
        gh_deploy(config)
    elif cmd == 'new':
        new(args, options)
    else:
        print('MkDocs (version {0})'.format(__version__))
        print('mkdocs [help|new|build|serve|gh-deploy|json] {options}')
Beispiel #48
0
 def builder():
     log.info("Building documentation...")
     config = load_config(
         config_file=config_file,
         dev_addr=dev_addr,
         strict=strict,
         theme=theme,
         theme_dir=theme_dir
     )
     config['site_dir'] = tempdir
     live_server = livereload in ['dirty', 'livereload']
     dirty = livereload == 'dirty'
     build(config, live_server=live_server, dirty=dirty)
     return config
Beispiel #49
0
def _load_config(config_file, strict, site_dir):
    cfg = config.load_config(
        config_file=config_file,
        strict=strict,
        site_dir=site_dir,
        theme='mkdocs'
    )

    # TODO: We should not need to manually update settings like this.
    version_assets = os.path.join(os.path.dirname(__file__), 'assets')

    # Add the assets for the version switcher
    cfg['theme_dir'].append(version_assets)
    cfg['extra_javascript'].append('mkdocs_versioned/js/version_picker.js')
    return cfg
Beispiel #50
0
def docs_deploy(DOCS_ROOT=None, **ctx):
    """ """
    import mkdocs
    from mkdocs.config import load_config
    from mkdocs.gh_deploy import gh_deploy
    mkdocs_config = os.path.join(DOCS_ROOT, 'mkdocs.yml')
    assert os.path.exists(mkdocs_config)
    os.chdir(DOCS_ROOT)
    try:
        config = load_config(
            config_file=mkdocs_config,
        )
        gh_deploy(config)
    except mkdocs.exceptions.ConfigurationError as e:
        # Avoid ugly, unhelpful traceback
        raise SystemExit('\n' + str(e))
Beispiel #51
0
    def builder():
        log.info("Building documentation...")
        config = load_config(
            config_file=config_file,
            dev_addr=dev_addr,
            strict=strict,
            theme=theme,
            theme_dir=theme_dir,
            site_dir=site_dir
        )
        # Override a few config settings after validation
        config['site_url'] = 'http://{0}/'.format(config['dev_addr'])

        live_server = livereload in ['dirty', 'livereload']
        dirty = livereload == 'dirty'
        build(config, live_server=live_server, dirty=dirty)
        return config
Beispiel #52
0
def json_command(clean, config_file, strict):
    """Build the MkDocs documentation to JSON files

    Rather than building your documentation to HTML pages, this
    outputs each page in a simple JSON format. This command is
    useful if you want to index your documentation in an external
    search engine.
    """

    log.warning("The json command is deprcated and will be removed in a future "
                "MkDocs release. For details on updating: "
                "http://www.mkdocs.org/about/release-notes/")

    build.build(load_config(
        config_file=config_file,
        strict=strict
    ), dump_json=True, clean_site_dir=clean)
Beispiel #53
0
def run_build(theme_name, output=None, config_file=None, quiet=False):
    """
    Given a theme name and output directory use the configuration
    for the MkDocs documentation and overwrite the site_dir and
    theme. If no output is provided, serve the documentation on
    each theme, one at a time.
    """

    should_serve = output is None
    options = {}

    if not serve:
        if not os.path.exists(output):
            os.makedirs(output)
        options['site_dir'] = os.path.join(output, theme_name)

    if config_file is None:
        config_file = open(MKDOCS_CONFIG, 'rb')

    if not quiet:
        print("Using config: {0}".format(config_file))

    cli.configure_logging()
    conf = config.load_config(config_file=config_file, theme=theme_name)

    if should_serve:
        if not quiet:
            print("Serving {0}".format(theme_name))
        try:
            serve.serve(conf)
        except KeyboardInterrupt:
            return
    else:
        if not quiet:
            print("Building {0}".format(theme_name))

        try:
            with capture_stdout() as out:
                build.build(conf)
                build.build(conf, dump_json=True)
        except Exception:
            print("Failed building {0}".format(theme_name), file=sys.stderr)
            raise

        if not quiet:
            print(''.join(out))
Beispiel #54
0
def build_command(clean, config_file, strict, theme, theme_dir, site_dir):
    """Build the MkDocs documentation"""

    # Don't override config value if user did not specify --strict flag
    # Conveniently, load_config drops None values
    strict = strict or None

    try:
        build.build(config.load_config(
            config_file=config_file,
            strict=strict,
            theme=theme,
            theme_dir=theme_dir,
            site_dir=site_dir
        ), dirty=not clean)
    except exceptions.ConfigurationError as e:
        # Avoid ugly, unhelpful traceback
        raise SystemExit('\n' + str(e))
Beispiel #55
0
def serve(config, options=None):
    """
    Start the devserver, and rebuild the docs whenever any changes take effect.
    """
    # Create a temporary build directory, and set some options to serve it
    tempdir = tempfile.mkdtemp()
    options['site_dir'] = tempdir

    # Only use user-friendly URLs when running the live server
    options['use_directory_urls'] = True

    # Perform the initial build
    config = load_config(options=options)
    build(config, live_server=True)

    # Note: We pass any command-line options through so that we
    #       can re-apply them if the config file is reloaded.
    event_handler = BuildEventHandler(options)
    config_event_handler = ConfigEventHandler(options)
    observer = observers.Observer()
    observer.schedule(event_handler, config['docs_dir'], recursive=True)
    observer.schedule(event_handler, config['theme_dir'], recursive=True)
    observer.schedule(config_event_handler, '.')
    observer.start()

    class TCPServer(socketserver.TCPServer):
        allow_reuse_address = True

    class DocsDirectoryHandler(FixedDirectoryHandler):
        base_dir = config['site_dir']

    host, port = config['dev_addr'].split(':', 1)
    server = TCPServer((host, int(port)), DocsDirectoryHandler)

    print('Running at: http://%s:%s/' % (host, port))
    print('Live reload enabled.')
    print('Hold ctrl+c to quit.')
    server.serve_forever()

    # Clean up
    observer.stop()
    observer.join()
    shutil.rmtree(tempdir)