code: def handle_dirty_dataset(ds, mode, msg=None):
      """Detect and treat unsaved changes as instructed by `mode`
  
      Parameters
      ----------
      ds : Dataset or None
        Dataset to be inspected. Does nothing if `None`.
      mode : {'fail', 'ignore', 'save-before'}
        How to act upon discovering unsaved changes.
      msg : str or None
        Custom message to use for a potential commit.
  
      Returns
      -------
      None
      """
      if ds is None:
          # nothing to be handled
          return
      if msg is None:
          msg = "[DATALAD] auto-saved changes"
  
      # make sure that all pending changes (batched annex operations, etc.)
      # are actually reflected in Git
      if ds.repo:
          ds.repo.precommit()
  
      if mode == "ignore":
          return
      elif mode == "fail":
          if not ds.repo or ds.repo.dirty:
              raise RuntimeError(
                  "dataset {} has unsaved changes".format(ds)
              )
      elif mode == "save-before":
          if not ds.is_installed():
              raise RuntimeError(
                  "dataset {} is not yet installed".format(ds)
              )
          from datalad.core.local.save import Save
  
          Save.__call__(dataset=ds, message=msg, updated=True)
      else:
          raise ValueError("unknown if-dirty mode '{}'".format(mode))
  
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 1 for calling a global function with example usage: handle_dirty_dataset(ds, mode, msg) without return types