Create back-links in all found needs.
    But do this only once, as all needs are already collected and this sorting is for all
    needs and not only for the ones of the current document.

    :param env: sphinx enviroment
    :return: None
760294
def create_back_links(env):
    
    if env.needs_workflow['backlink_creation']:
        return

    needs = env.needs_all_needs
    for key, need in needs.items():
        for link in need["links"]:
            link_main = link.split('.')[0]
            try:
                link_part = link.split('.')[1]
            except IndexError:
                link_part = None

            if link_main in needs:
                if key not in needs[link_main]["links_back"]:
                    needs[link_main]["links_back"].append(key)

                # Handling of links to need_parts inside a need
                if link_part is not None:
                    if link_part in needs[link_main]['parts']:
                        if 'links_back' not in needs[link_main]['parts'][link_part].keys():
                            needs[link_main]['parts'][link_part]['links_back'] = []
                        needs[link_main]['parts'][link_part]['links_back'].append(key)

    env.needs_workflow['backlink_creation'] = True
808535
def _with_env(self, env):
        """"""
        res = self._browse(env, self._ids)
        return res
774463
def prepare_env(cls):
        
        os.environ['PATH'] = cls.get_env_path()
        return os.path.basename(Finder.python())
590532
def envs(ignore_cache=False):
    '''
    
    '''
    if not ignore_cache:
        env_cache = os.path.join(__opts__['cachedir'], 'hgfs/envs.p')
        cache_match = salt.fileserver.check_env_cache(__opts__, env_cache)
        if cache_match is not None:
            return cache_match
    ret = set()
    for repo in init():
        repo['repo'].open()
        if repo['branch_method'] in ('branches', 'mixed'):
            for branch in _all_branches(repo['repo']):
                branch_name = branch[0]
                if branch_name == repo['base']:
                    branch_name = 'base'
                ret.add(branch_name)
        if repo['branch_method'] in ('bookmarks', 'mixed'):
            for bookmark in _all_bookmarks(repo['repo']):
                bookmark_name = bookmark[0]
                if bookmark_name == repo['base']:
                    bookmark_name = 'base'
                ret.add(bookmark_name)
        ret.update([x[0] for x in _all_tags(repo['repo'])])
        repo['repo'].close()
    return [x for x in sorted(ret) if _env_is_exposed(x)]
1022257
def list_projects(root, backend=os.listdir):
    
    projects = list()
    for project in sorted(backend(root)):
        abspath = os.path.join(root, project)
        if not isproject(abspath):
            continue
        projects.append(project)
    return projects
567309
def _build_menu(docs):
    

    paths = []
    current = docs.filename
    while current != docs.root:
        current = current.parent
        paths.append(current)

    for path in reversed(paths):
        docs.add_menu(path.stem.title(), link=path / 'index.html')

    if docs.filename.stem != 'index':
        docs.add_menu(docs.title, link=docs.filename)

    docs.end_menu()
83964
def apply_tools(self, env):
        
        for t in self.tools:
            tool = SCons.Tool.Tool(t)
            if tool.exists(env):
                env.Tool(tool)
                return
699031
def addEnvPath(env, name, value):
    
    try:
        oldval = env[name]
        if not oldval.endswith(';'):
            oldval = oldval + ';'
    except KeyError:
        oldval = ""
    if not value.endswith(';'):
        value = value + ';'
    env[name] = oldval + value
411843
def enumerate_scope(ast_rootpath, root_env=None, include_default_builtins=False):
  
  with util.LogTime('enumerate_scope'):
    scope = {}
    for node in reversed(ast_rootpath):
      if is_tuple_node(node):
        for member in node.members:
          if member.name not in scope:
            scope[member.name] = Completion(member.name, False, member.comment.as_string(), member.location)

    if include_default_builtins:  # Backwards compat flag
      root_env = gcl.default_env

    if root_env:
      for k in root_env.keys():
        if k not in scope and not hide_from_autocomplete(root_env[k]):
          v = root_env[k]
          scope[k] = Completion(k, True, dedent(v.__doc__ or ''), None)

    return scope
773061
def add_backend(self, backend):
        ""
        if backend in self.get_backends():
            return
        backend_link, created = BackendLink.all_tenants.get_or_create(backend=backend)
        self.backendlink_set.add(backend_link)
427370
def add_directives(kb_app: kb,
                   sphinx_app: Sphinx,
                   sphinx_env: BuildEnvironment,
                   docnames=List[str],
                   ):
    

    for k, v in list(kb_app.config.resources.items()):
        sphinx_app.add_directive(k, ResourceDirective)
345967
def build_urls(self: NodeVisitor, node: inheritance_diagram) -> Mapping[str, str]:
    
    current_filename = self.builder.current_docname + self.builder.out_suffix
    urls = {}
    for child in node:
        # Another document
        if child.get("refuri") is not None:
            uri = child.get("refuri")
            package_path = child["reftitle"]
            if uri.startswith("http"):
                _, _, package_path = uri.partition("#")
            else:
                uri = (
                    pathlib.Path("..")
                    / pathlib.Path(current_filename).parent
                    / pathlib.Path(uri)
                )
                uri = str(uri).replace(os.path.sep, "/")
            urls[package_path] = uri
        # Same document
        elif child.get("refid") is not None:
            urls[child["reftitle"]] = (
                "../" + current_filename + "#" + child.get("refid")
            )
    return urls
843283
def read_sphinx_environment(pth):
    """"""

    with open(pth, 'rb') as fo:
        env = pickle.load(fo)
    return env
1013116
def get_links(self, request=None):
        
        links = LinkNode()

        # Generate (path, method, view) given (path, method, callback).
        paths = []
        view_endpoints = []
        for path, method, callback in self.endpoints:
            view = self.create_view(callback, method, request)
            if getattr(view, 'exclude_from_schema', False):
                continue
            path = self.coerce_path(path, method, view)
            paths.append(path)
            view_endpoints.append((path, method, view))

        # Only generate the path prefix for paths that will be included
        if not paths:
            return None
        prefix = self.determine_path_prefix(paths)

        for path, method, view in view_endpoints:
            if not self.has_view_permissions(path, method, view):
                continue
            link = self.get_link(path, method, view, version=getattr(request, 'version', None))
            subpath = path[len(prefix):]
            keys = self.get_keys(subpath, method, view)
            try:
                insert_into(links, keys, link)
            except Exception:
                continue
        return links
227784
def generate(env):
    
    link.generate(env)

    env['SMARTLINKFLAGS'] = smart_linkflags
    env['LINKFLAGS']      = SCons.Util.CLVar('$SMARTLINKFLAGS')
    env['SHLINKFLAGS']    = SCons.Util.CLVar('$LINKFLAGS -qmkshrobj -qsuppress=1501-218')
    env['SHLIBSUFFIX']    = '.a'
486809
def call_purge_doc(cls, kb_app, sphinx_app: Sphinx,
                       sphinx_env: BuildEnvironment,
                       docname: str):
        

        for callback in EventAction.get_callbacks(kb_app, SphinxEvent.EPD):
            callback(kb_app, sphinx_app, sphinx_env, docname)
899140
def create_path_env_var(new_entries, env=None, env_var='PATH', delimiter=':', prepend=False):
  """"""
  if env is None:
    env = {}

  prev_path = env.get(env_var, None)
  if prev_path is None:
    path_dirs = list()
  else:
    path_dirs = list(prev_path.split(delimiter))

  new_entries_list = list(new_entries)

  if prepend:
    path_dirs = new_entries_list + path_dirs
  else:
    path_dirs += new_entries_list

  return delimiter.join(path_dirs)