code: def rewrite(
      filepath: Union[str, Path], mode: str = "w", **kw: Any
  ) -> Generator[IO, None, None]:
      
      if isinstance(filepath, str):
          base_dir = os.path.dirname(filepath)
          filename = os.path.basename(filepath)
      else:
          base_dir = str(filepath.parent)
          filename = filepath.name
  
      # Change naming format to be more friendly with distributed POSIX
      # filesystems like GlusterFS that hash based on filename
      # GlusterFS ignore '.' at the start of filenames and this avoid rehashing
      with tempfile.NamedTemporaryFile(
          mode=mode, prefix=f".{filename}.", delete=False, dir=base_dir, **kw
      ) as f:
          filepath_tmp = f.name
          yield f
  
      if not os.path.exists(filepath_tmp):
          # Allow our clients to remove the file in case it doesn't want it to be
          # put in place actually but also doesn't want to error out.
          return
      os.chmod(filepath_tmp, 0o100644)
      os.rename(filepath_tmp, filepath)
docs: Rewrite an existing file atomically to avoid programs running in
      parallel to have race conditions while reading.