code: def discover_dataset_trace_to_targets(
      basepath, targetpaths, current_trace, spec, includeds=None
  ):
      """Discover the edges and nodes in a dataset tree to given target paths
  
      Parameters
      ----------
      basepath : path
        Path to a start or top-level dataset. Really has to be a path to a
        dataset!
      targetpaths : list(path)
        Any non-zero number of paths that are termination points for the
        search algorithm. Can be paths to datasets, directories, or files
        (and any combination thereof).
      current_trace : list
        For a top-level call this should probably always be `[]`
      spec : dict
        `content_by_ds`-style dictionary that will receive information about the
        discovered datasets. Specifically, for each discovered dataset there
        will be an item with its path under the key (path) of the respective
        superdataset.
      includeds : sequence, optional
        Any paths given are treated as existing subdatasets, regardless of
        whether they can be found in the filesystem. Such subdatasets will appear
        under the key of the closest existing dataset in the `spec`.
  
      Returns
      -------
      None
        Function calls itself recursively and populates `spec` dict in-place.
        Keys are dataset paths, values are sets of subdataset paths
      """
      # convert to set for faster lookup
      includeds = (
          includeds
          if isinstance(includeds, set)
          else set()
          if includeds is None
          else set(includeds)
      )
      # this beast walks the directory tree from a given `basepath` until
      # it discovers any of the given `targetpaths`
      # if it finds one, it commits any accumulated trace of visited
      # datasets on this edge to the spec
      valid_repo = GitRepo.is_valid_repo(basepath)
      if valid_repo:
          # we are passing into a new dataset, extend the dataset trace
          current_trace = current_trace + [basepath]
      # this edge is not done, we need to try to reach any downstream
      # dataset
      undiscovered_ds = set(t for t in targetpaths)  # if t != basepath)
      # whether anything in this directory matched a targetpath
      filematch = False
      if isdir(basepath):
          for p in listdir(basepath):
              p = ensure_unicode(opj(basepath, p))
              if not isdir(p):
                  if p in targetpaths:
                      filematch = True
                  # we cannot have anything below this one
                  continue
              # OPT listdir might be large and we could have only few items
              # in `targetpaths` -- so traverse only those in spec which have
              # leading dir basepath
              # filter targets matching this downward path
              downward_targets = set(
                  t for t in targetpaths if path_startswith(t, p)
              )
              if not downward_targets:
                  continue
              # remove the matching ones from the "todo" list
              undiscovered_ds.difference_update(downward_targets)
              # go one deeper
              discover_dataset_trace_to_targets(
                  p,
                  downward_targets,
                  current_trace,
                  spec,
                  includeds=includeds
                  if not includeds
                  else includeds.intersection(downward_targets),
              )
      undiscovered_ds = [
          t
          for t in undiscovered_ds
          if includeds
          and path_is_subpath(t, current_trace[-1])
          and t in includeds
      ]
      if filematch or basepath in targetpaths or undiscovered_ds:
          for i, p in enumerate(current_trace[:-1]):
              # TODO RF prepare proper annotated path dicts
              subds = spec.get(p, set())
              subds.add(current_trace[i + 1])
              spec[p] = subds
          if undiscovered_ds:
              spec[current_trace[-1]] = spec.get(
                  current_trace[-1], set()
              ).union(undiscovered_ds)
  
imports: import logging
  import sys
  from time import time
  from os import listdir
  from os.path import join
  from os.path import isdir
  from os.path import relpath
  from os.path import sep
  import json
  from typing import TypeVar
  from datalad.utils import with_pathsep
  from datalad.utils import path_startswith, path_is_subpath, ensure_unicode, getargspec
  from datalad.support.gitrepo import GitRepo
  from datalad.support.exceptions import CapturedException
  from datalad import cfg
  from datalad.dochelpers import single_or_plural
  from datalad.ui import ui
  import datalad.support.ansi_colors
label_desc: Use image node_id 3 for calling a global function with example usage: discover_dataset_trace_to_targets(basepath, targetpaths, current_trace, spec, includeds) without return types