ix: str) -> str:
        """
        PEP 517 requires that the .dist-info directory be placed in the
        metadata_directory. To comply, we MUST copy the directory to the root.

        Returns the basename of the info directory, e.g. `proj-0.0.0.dist-info`.
        """
        info_dir = self._find_info_directory(metadata_directory, suffix)
        if not same_path(info_dir.parent, metadata_directory):
            shutil.move(str(info_dir), metadata_directory)
            # PEP 517 allow other files and dirs to exist in metadata_directory
        return info_dir.name

    def _find_info_directory(self, metadata_directory: str, suffix: str) -> Path:
        for parent, dirs, _ in os.walk(metadata_directory):
            candidates = [f for f in dirs if f.endswith(suffix)]

            if len(candidates) != 0 or len(dirs) != 1:
                assert len(candidates) == 1, f"Multiple {suffix} directories found"
                return Path(parent, candidates[0])

        msg = f"No {suffix} directory found in {metadata_directory}"
        raise errors.InternalError(msg)

    def prepare_metadata_for_build_wheel(self, metadata_directory,
                                         config_settings=None):
        sys.argv = [
            *sys.argv[:1],
            *self._global_args(config_settings),
            "dist_info",
            "--output-dir", metadata_directory,
            "--keep-egg-info",
        ]
        with no_install_setup_requires():
            self.run_setup()

        self._bubble_up_info_directory(metadata_directory, ".egg-info")
        return self._bubble_up_info_directory(metadata_directory, ".dist-info")

    def _build_with_temp_dir(self, setup_command, result_extension,
                             result_directory, config_settings):
        result_directory = os.path.abspath(result_directory)

        # Build in a temporary directory, then copy to the target.
        os.makedirs(result_directory, exist_ok=True)
        with tempfile.TemporaryDirectory(dir=result_directory) as tmp_dist_dir:
            sys.argv = [
                *sys.argv[:1],
                *self._global_args(config_settings),
                *setup_command,
                "--dist-dir", tmp_dist_dir,
                *self._arbitrary_args(config_settings),
            ]
            with no_install_setup_requires():
                self.run_setup()

            result_basename = _file_with_extension(
                tmp_dist_dir, result_extension)
            result_path = os.path.join(result_directory, result_basename)
            if os.path.exists(result_path):
                # os.rename will fail overwriting on non-Unix.
                os.remove(result_path)
            os.rename(os.path.join(tmp_dist_dir, result_basename), result_path)

        return result_basename

    def build_wheel(self, wheel_directory, config_settings=None,
                    metadata_directory=None):
        with suppress_known_deprecation():
            return self._build_with_temp_dir(['bdist_wheel'], '.whl',
                                             wheel_directory, config_settings)

    def build_sdist(self, sdist_directory, config_settings=None):
        return self._build_with_temp_dir(['sdist', '--formats', 'gztar'],
                                         '.tar.gz', sdist_directory,
                                         config_settings)

    def _get_dist_info_dir(self, metadata_directory: Optional[str]) -> Optional[str]:
        if not metadata_directory:
            return None
        dist_info_candidates = list(Path(metadata_directory).glob("*.dist-info"))
        assert len(dist_info_candidates) <= 1
        return str(dist_info_candidates[0]) if dist_info_candidates else None

    if not LEGACY_EDITABLE:

        # PEP660 hooks:
        # build_editable
        # get_requires_for_build_editable
        # prepare_metadata_for_build_editable
        def build_editable(
            self, wheel_directory, config_settings=None, metadata_directory=None
        ):
            # XXX can or should we hide our editable_wheel command normally?
            info_dir = self._get_dist_info_dir(metadata_directory)
            opts = ["--dist-info-dir", info_dir] if info_dir else []
            cmd = ["editable_wheel", *opts, *self._editable_args(config_settings)]
            with suppress_known_deprecation():
                return self._build_with_temp_dir(
                    cmd, ".whl", wheel_directory, config_settings
                )

        def get_requires_for_build_editable(self, config_settings=None):
            return self.get_requires_for_build_wheel(config_settings)

        def prepare_metadata_for_build_editable(self, metadata_directory,
                                                config_settings=None):
            return self.prepare_metadata_for_build_wheel(
                metadata_directory, config_settings
            )


class _BuildMetaLegacyBackend(_BuildMetaBackend):
    """Compatibility backend for setuptools

    This is a version of setuptools.build_meta that endeavors
    to maintain backwards
    compatibility with pre-PEP 517 modes of invocation. It
    exists as a temporary
    bridge between the old packaging mechanism and the new
    packaging mechanism,
    and will eventually be removed.
    """
    def run_setup(self, setup_script='setup.py'):
        # In order to maintain compatibility with scripts assuming that
        # the setup.py script is in a directory on the PYTHONPATH, inject
        # '' into sys.path. (pypa/setuptools#1642)
        sys_path = list(sys.path)           # Save the original path

        script_dir = os.path.dirname(os.path.abspath(setup_script))
        if script_dir not in sys.path:
            sys.path.insert(0, script_dir)

        # Some setup.py scripts (e.g. in pygame and numpy) use sys.argv[0] to
        # get the directory of the source code. They expect it to refer to the
        # setup.py script.
        sys_argv_0 = sys.argv[0]
        sys.argv[0] = setup_script

        try:
            super(_BuildMetaLegacyBackend,
                  self).run_setup(setup_script=setup_script)
        finally:
            # While PEP 517 frontends should be calling each hook in a fresh
            # subprocess according to the standard (and thus it should not be
            # strictly necessary to restore the old sys.path), we'll restore
            # the original path so that the path manipulation does not persist
            # within the hook after run_setup is called.
            sys.path[:] = sys_path
            sys.argv[0] = sys_argv_0


# The primary backend
_BACKEND = _BuildMetaBackend()

get_requires_for_build_wheel = _BACKEND.get_requires_for_build_wheel
get_requires_for_build_sdist = _BACKEND.get_requires_for_build_sdist
prepare_metadata_for_build_wheel = _BACKEND.prepare_metadata_for_build_wheel
build_wheel = _BACKEND.build_wheel
build_sdist = _BACKEND.build_sdist

if not LEGACY_EDITABLE:
    get_requires_for_build_editable = _BACKEND.get_requires_for_build_editable
    prepare_metadata_for_build_editable = _BACKEND.prepare_metadata_for_build_editable
    build_editable = _BACKEND.build_editable


# The legacy backend
__legacy__ = _BuildMetaLegacyBackend()
