Initialize Kaybee as a Sphinx extension
437417
def setup(app: Sphinx):
    

    # Scan for directives, first in the system, second in the docs project
    importscan.scan(plugins)
    dectate.commit(kb)

    app.add_config_value('kaybee_settings', KaybeeSettings(), 'html')
    bridge = 'kaybee.plugins.postrenderer.config.KaybeeBridge'
    app.config.template_bridge = bridge

    app.connect('env-updated', flush_everything)
    app.connect(SphinxEvent.BI.value,
                # pragma nocover
                lambda sphinx_app: EventAction.call_builder_init(
                    kb, sphinx_app)
                )
    app.connect(SphinxEvent.EPD.value,
                # pragma nocover
                lambda sphinx_app, sphinx_env,
                       docname: EventAction.call_purge_doc(
                    kb, sphinx_app, sphinx_env, docname)
                )

    app.connect(SphinxEvent.EBRD.value,
                # pragma nocover
                lambda sphinx_app, sphinx_env,
                       docnames: EventAction.call_env_before_read_docs(
                    kb, sphinx_app, sphinx_env, docnames)
                )

    app.connect(SphinxEvent.DREAD.value,
                # pragma nocover
                lambda sphinx_app,
                       doctree: EventAction.call_env_doctree_read(
                    kb, sphinx_app, doctree)
                )

    app.connect(SphinxEvent.DRES.value,
                # pragma nocover
                lambda sphinx_app, doctree,
                       fromdocname: EventAction.call_doctree_resolved(
                    kb, sphinx_app, doctree, fromdocname)
                )

    app.connect(SphinxEvent.EU.value,
                # pragma nocover
                lambda sphinx_app, sphinx_env: EventAction.call_env_updated(
                    kb, sphinx_app, sphinx_env)
                )

    app.connect(SphinxEvent.HCP.value,
                # pragma nocover
                lambda sphinx_app: EventAction.call_html_collect_pages(
                    kb, sphinx_app)
                )

    app.connect(SphinxEvent.ECC.value,
                # pragma nocover
                lambda sphinx_builder,
                       sphinx_env: EventAction.call_env_check_consistency(
                    kb, sphinx_builder, sphinx_env)
                )

    app.connect(SphinxEvent.MR.value,
                # pragma nocover
                lambda sphinx_app, sphinx_env, node,
                       contnode: EventAction.call_missing_reference(
                    kb, sphinx_app, sphinx_env, node, contnode)
                )

    app.connect(SphinxEvent.HPC.value,
                # pragma nocover
                lambda sphinx_app, pagename, templatename, context,
                       doctree: EventAction.call_html_page_context(
                    kb, sphinx_app, pagename, templatename, context, doctree)
                )

    return dict(
        version=__version__,
        parallel_read_safe=False
    )
1038643
def sphinx_extension(app, exception):
    ""
    if not app.builder.name in ("html", "dirhtml"):
        return

    if not app.config.sphinx_to_github:
        if app.config.sphinx_to_github_verbose:
            print("Sphinx-to-github: Disabled, doing nothing.")
        return

    if exception:
        if app.config.sphinx_to_github_verbose:
            print("Sphinx-to-github: Exception raised in main build, doing nothing.")
        return

    dir_helper = DirHelper(
            os.path.isdir,
            os.listdir,
            os.walk,
            shutil.rmtree
            )

    file_helper = FileSystemHelper(
            open,
            os.path.join,
            shutil.move,
            os.path.exists
            )

    operations_factory = OperationsFactory()
    handler_factory = HandlerFactory()

    layout_factory = LayoutFactory(
            operations_factory,
            handler_factory,
            file_helper,
            dir_helper,
            app.config.sphinx_to_github_verbose,
            sys.stdout,
            force=True
            )

    layout = layout_factory.create_layout(app.outdir)
    layout.process()
232019
def initialize_extensions(shell, extensions):
    
    try:
        iter(extensions)
    except TypeError:
        pass  # no extensions found
    else:
        for ext in extensions:
            try:
                shell.extension_manager.load_extension(ext)
            except:
                ipy_utils.warn.warn(
                    "Error in loading extension: %s" % ext +
                    "\nCheck your config files in %s" % ipy_utils.path.get_ipython_dir())
                shell.showtraceback()
1278667
def on_builder_inited(app):
    
    app.cache_db_path = ":memory:"
    if app.config["uqbar_book_use_cache"]:
        logger.info(bold("[uqbar-book]"), nonl=True)
        logger.info(" initializing cache db")
        app.connection = uqbar.book.sphinx.create_cache_db(app.cache_db_path)
619911
def init_extension(self, app):
        """"""
        app.config.setdefault('CACHE_VERSION', '0')
        app.config.setdefault('CACHE_PREFIX', 'r')
        app.config.setdefault('CACHE_BACKEND', 'rio.exts.flask_cache.NullBackend')
        app.config.setdefault('CACHE_BACKEND_OPTIONS', {})
896193
def init(args):
    
    # working directory
    dir_path = Path().absolute()

    if not args.project_name or args.project_name.find("/") >= 0:
        print(
            "{}You should specify a valid project name{}".format(
                utils.colors.FAIL, utils.colors.ENDC
            )
        )
        return

    project_path = dir_path / args.project_name

    # Create the Home Documentation's directory
    if not project_path.exists():
        project_path.mkdir()
    else:
        print(
            "{}This project already exists{}".format(
                utils.colors.FAIL, utils.colors.ENDC
            )
        )
        return

    # Directory with the Home Documentation's source code
    home_doc_path = project_path / "docs"
    home_doc_path.mkdir()
    help_doc_path = home_doc_path / "help"
    help_doc_path.mkdir()

    file_path = Path(__file__).resolve().parent / "include"

    # Add initial files
    copyfile(file_path / "index.md", home_doc_path / "index.md")
    copyfile(file_path / "How_To_Use_Mkinx.md", help_doc_path / "How_To_Use_Mkinx.md")
    copyfile(
        file_path / "Writing_Sphinx_Documentation.md",
        help_doc_path / "Writing_Sphinx_Documentation.md",
    )

    with open(file_path / "mkdocs.yml", "r") as f:
        lines = f.readlines()

    input_text = "What is your Documentation's name"
    input_text += " (it can be changed later in mkdocs.yml)?\n"
    input_text += "[Default: {} - Home Documentation]\n"

    site_name = input(input_text.format(args.project_name.capitalize()))
    if not site_name:
        site_name = "{} - Home Documentation".format(args.project_name.capitalize())

    lines[0] = "site_name: {}\n".format(site_name)

    with open(project_path / "mkdocs.yml", "w") as f:
        f.writelines(lines)

    example_project_path = project_path / "example_project" / "example_project"

    windows = "y" if sys.platform in {"win32", "cygwin"} else "n"

    copytree(file_path / "example_project", example_project_path)
    move(str(example_project_path / "source"), str(project_path / "example_project"))
    move(
        str(project_path / "example_project" / "example_project" / "Makefile"),
        str(project_path / "example_project"),
    )
    if windows == "y":
        move(
            str(project_path / "example_project" / "example_project" / "make.bat"),
            str(project_path / "example_project"),
        )
    else:
        os.remove(
            str(project_path / "example_project" / "example_project" / "make.bat")
        )

    static = project_path / "example_project" / "source"
    static /= "_static"
    if not static.exists():
        static.mkdir()

    _ = subprocess.check_output(
        "cd {} && mkinx build -F -A > /dev/null".format(args.project_name), shell=True
    )

    print(
        "\n\n",
        utils.colors.OKBLUE,
        "{}/{} created as a showcase of how mkinx works".format(
            args.project_name, "example_project"
        ),
        utils.colors.ENDC,
    )

    print(
        "\n",
        utils.colors.OKGREEN,
        "Success!",
        utils.colors.ENDC,
        "You can now start your Docs in ./{}\n".format(args.project_name),
        utils.colors.HEADER,
        "$ cd ./{}".format(args.project_name),
        utils.colors.ENDC,
    )
    print(
        "  Start the server from within your Docs to see them \n  (default",
        "port is 8443 but you can change it with the -s flag):",
    )
    print(
        utils.colors.HEADER,
        " {} $ mkinx serve\n".format(args.project_name),
        utils.colors.ENDC,
    )
584190
def tree(c):
    
    ignore = ".git|*.pyc|*.swp|dist|*.egg-info|_static|_build|_templates"
    c.run('tree -Ca -I "{0}" {1}'.format(ignore, c.sphinx.source))
1150313
def run(self):
        
        self.assert_has_content()
        env = self.state.document.settings.env

        node = nodes.container()
        node['classes'] = ['sphinx-tabs']

        if 'next_tabs_id' not in env.temp_data:
            env.temp_data['next_tabs_id'] = 0
        if 'tabs_stack' not in env.temp_data:
            env.temp_data['tabs_stack'] = []

        tabs_id = env.temp_data['next_tabs_id']
        tabs_key = 'tabs_%d' % tabs_id
        env.temp_data['next_tabs_id'] += 1
        env.temp_data['tabs_stack'].append(tabs_id)

        env.temp_data[tabs_key] = {}
        env.temp_data[tabs_key]['tab_ids'] = []
        env.temp_data[tabs_key]['tab_titles'] = []
        env.temp_data[tabs_key]['is_first_tab'] = True

        self.state.nested_parse(self.content, self.content_offset, node)

        if env.app.builder.name in get_compatible_builders(env.app):
            tabs_node = nodes.container()
            tabs_node.tagname = 'div'

            classes = 'ui top attached tabular menu sphinx-menu'
            tabs_node['classes'] = classes.split(' ')

            tab_titles = env.temp_data[tabs_key]['tab_titles']
            for idx, [data_tab, tab_name] in enumerate(tab_titles):
                tab = nodes.container()
                tab.tagname = 'a'
                tab['classes'] = ['item'] if idx > 0 else ['active', 'item']
                tab['classes'].append(data_tab)
                tab += tab_name
                tabs_node += tab

            node.children.insert(0, tabs_node)

        env.temp_data['tabs_stack'].pop()
        return [node]
102310
def ignore_sphinx():
    """"""
    (directives, roles) = _get_directives_and_roles_from_sphinx()

    directives += [
        'centered',
        'include',
        'deprecated',
        'index',
        'no-code-block',
        'literalinclude',
        'hlist',
        'seealso',
        'toctree',
        'todo',
        'versionadded',
        'versionchanged']

    ext_autosummary = [
        'autosummary',
        'currentmodule',
    ]

    ignore_directives_and_roles(directives + ext_autosummary,
                                roles + ['ctype'])
768634
def run(self):
        '''
        
        '''
        # Loading yaml
        self.load_yaml()

        # Print paths from schema
        section_title = '**API Paths**'
        self.write(section_title)
        self.write('=' * len(section_title))
        self.print_paths()

        # Print models
        section_title = '**Schemas Description**'
        self.write(section_title)
        self.write('=' * len(section_title))
        self.print_schemas()

        # Render by sphinx
        node = nodes.section()
        node.document = self.state.document
        nested_parse_with_titles(self.state, self.__view_list, node)
        return node.children
372921
def prepare_env(app, env, docname):
    
    if not hasattr(env, 'needs_all_needs'):
        # Used to store all needed information about all needs in document
        env.needs_all_needs = {}

    if not hasattr(env, 'needs_functions'):
        # Used to store all registered functions for supporting dynamic need values.
        env.needs_functions = {}

        # needs_functions = getattr(app.config, 'needs_functions', [])
        needs_functions = app.needs_functions
        if needs_functions is None:
            needs_functions = []
        if not isinstance(needs_functions, list):
            raise SphinxError('Config parameter needs_functions must be a list!')

        # Register built-in functions
        for need_common_func in needs_common_functions:
            register_func(env, need_common_func)

        # Register functions configured by user
        for needs_func in needs_functions:
            register_func(env, needs_func)

    app.config.needs_hide_options += ['hidden']
    app.config.needs_extra_options['hidden'] = directives.unchanged

    if not hasattr(env, 'needs_workflow'):
        # Used to store workflow status information for already executed tasks.
        # Some tasks like backlink_creation need be be performed only once.
        # But most sphinx-events get called several times (for each single document file), which would also
        # execute our code several times...
        env.needs_workflow = {
            'backlink_creation': False,
            'dynamic_values_resolved': False
        }
665465
def init():
    '''
    
    '''
    bp_ = os.path.join(__opts__['cachedir'], 'hgfs')
    new_remote = False
    repos = []

    per_remote_defaults = {}
    for param in PER_REMOTE_OVERRIDES:
        per_remote_defaults[param] = \
            six.text_type(__opts__['hgfs_{0}'.format(param)])

    for remote in __opts__['hgfs_remotes']:
        repo_conf = copy.deepcopy(per_remote_defaults)
        if isinstance(remote, dict):
            repo_url = next(iter(remote))
            per_remote_conf = dict(
                [(key, six.text_type(val)) for key, val in
                 six.iteritems(salt.utils.data.repack_dictlist(remote[repo_url]))]
            )
            if not per_remote_conf:
                log.error(
                    'Invalid per-remote configuration for hgfs remote %s. If '
                    'no per-remote parameters are being specified, there may '
                    'be a trailing colon after the URL, which should be '
                    'removed. Check the master configuration file.', repo_url
                )
                _failhard()

            branch_method = \
                per_remote_conf.get('branch_method',
                                    per_remote_defaults['branch_method'])
            if branch_method not in VALID_BRANCH_METHODS:
                log.error(
                    'Invalid branch_method \'%s\' for remote %s. Valid '
                    'branch methods are: %s. This remote will be ignored.',
                    branch_method, repo_url, ', '.join(VALID_BRANCH_METHODS)
                )
                _failhard()

            per_remote_errors = False
            for param in (x for x in per_remote_conf
                          if x not in PER_REMOTE_OVERRIDES):
                log.error(
                    'Invalid configuration parameter \'%s\' for remote %s. '
                    'Valid parameters are: %s. See the documentation for '
                    'further information.',
                    param, repo_url, ', '.join(PER_REMOTE_OVERRIDES)
                )
                per_remote_errors = True
            if per_remote_errors:
                _failhard()

            repo_conf.update(per_remote_conf)
        else:
            repo_url = remote

        if not isinstance(repo_url, six.string_types):
            log.error(
                'Invalid hgfs remote %s. Remotes must be strings, you may '
                'need to enclose the URL in quotes', repo_url
            )
            _failhard()

        try:
            repo_conf['mountpoint'] = salt.utils.url.strip_proto(
                repo_conf['mountpoint']
            )
        except TypeError:
            # mountpoint not specified
            pass

        hash_type = getattr(hashlib, __opts__.get('hash_type', 'md5'))
        repo_hash = hash_type(repo_url).hexdigest()
        rp_ = os.path.join(bp_, repo_hash)
        if not os.path.isdir(rp_):
            os.makedirs(rp_)

        if not os.listdir(rp_):
            # Only init if the directory is empty.
            hglib.init(rp_)
            new_remote = True
        try:
            repo = hglib.open(rp_)
        except hglib.error.ServerError:
            log.error(
                'Cache path %s (corresponding remote: %s) exists but is not '
                'a valid mercurial repository. You will need to manually '
                'delete this directory on the master to continue to use this '
                'hgfs remote.', rp_, repo_url
            )
            _failhard()
        except Exception as exc:
            log.error(
                'Exception \'%s\' encountered while initializing hgfs '
                'remote %s', exc, repo_url
            )
            _failhard()

        try:
            refs = repo.config(names='paths')
        except hglib.error.CommandError:
            refs = None

        # Do NOT put this if statement inside the except block above. Earlier
        # versions of hglib did not raise an exception, so we need to do it
        # this way to support both older and newer hglib.
        if not refs:
            # Write an hgrc defining the remote URL
            hgconfpath = os.path.join(rp_, '.hg', 'hgrc')
            with salt.utils.files.fopen(hgconfpath, 'w+') as hgconfig:
                hgconfig.write('[paths]\n')
                hgconfig.write(
                    salt.utils.stringutils.to_str(
                        'default = {0}\n'.format(repo_url)
                    )
                )

        repo_conf.update({
            'repo': repo,
            'url': repo_url,
            'hash': repo_hash,
            'cachedir': rp_,
            'lockfile': os.path.join(__opts__['cachedir'],
                                     'hgfs',
                                     '{0}.update.lk'.format(repo_hash))
        })
        repos.append(repo_conf)
        repo.close()

    if new_remote:
        remote_map = os.path.join(__opts__['cachedir'], 'hgfs/remote_map.txt')
        try:
            with salt.utils.files.fopen(remote_map, 'w+') as fp_:
                timestamp = datetime.now().strftime('%d %b %Y %H:%M:%S.%f')
                fp_.write('# hgfs_remote map as of {0}\n'.format(timestamp))
                for repo in repos:
                    fp_.write(
                        salt.utils.stringutils.to_str(
                            '{0} = {1}\n'.format(repo['hash'], repo['url'])
                        )
                    )
        except OSError:
            pass
        else:
            log.info('Wrote new hgfs_remote map to %s', remote_map)

    return repos
1153791
def setup(sphinx):
    
    create_auto_documentation()

    # add the py3status lexer (for code blocks)
    from sphinx.highlighting import lexers
    lexers['py3status'] = Py3statusLexer()

    # enable screenshot directive for dynamic screenshots
    sphinx.add_directive('screenshot', ScreenshotDirective)
1349917
def on_config_inited(app, config):
    
    extension_paths = config["uqbar_book_extensions"] or [
        "uqbar.book.extensions.GraphExtension"
    ]
    app.uqbar_book_extensions = []
    for extension_path in extension_paths:
        module_name, _, class_name = extension_path.rpartition(".")
        module = importlib.import_module(module_name)
        extension_class = getattr(module, class_name)
        extension_class.setup_sphinx(app)
        app.uqbar_book_extensions.append(extension_class)
225779
def init():
    
    yass_conf = os.path.join(CWD, "yass.yml")
    if os.path.isfile(yass_conf):
        print("::ALERT::")
        print("It seems like Yass is already initialized here.")
        print("If it's a mistake, delete 'yass.yml' in this directory")
    else:
        print("Init Yass in %s ..." % CWD)
        copy_resource("skel/", CWD)
        stamp_yass_current_version(CWD)
        print("Yass init successfully!")
        print("Run 'yass serve' to view the site")

    footer()
745077
def create_initialize(repo, atts)
      @repo = repo
      atts.each do |k, v|
        instance_variable_set("@#{k}".to_sym, v)
      end
      self
    end
40358
def build(ctx):
    
    return_code = run_sphinx(ctx.obj['root_dir'])
    if return_code > 0:
        sys.exit(return_code)