2
 ;é    # Copyright (C) 2017 Breezy Developers
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

from typing import TYPE_CHECKING

from .. import (
    config,
    errors,
    controldir,
    pyutils,
    registry,
    transport as _mod_transport,
    )


if TYPE_CHECKING:
    from .bzrdir import BzrDirFormat


class LineEndingError(errors.BzrError):

    _fmt = ("Line ending corrupted for file: %(file)s; "
            "Maybe your files got corrupted in transport?")

    def __init__(self, file):
        self.file = file


class BzrProber(controldir.Prober):
    """Prober for formats that use a .bzr/ control directory."""

    formats = registry.FormatRegistry["BzrDirFormat"](controldir.network_format_registry)
    """The known .bzr formats."""

    @classmethod
    def priority(klass, transport):
        return 10

    @classmethod
    def probe_transport(klass, transport):
        """Return the .bzrdir style format present in a directory."""
        try:
            format_string = transport.get_bytes(".bzr/branch-format")
        except _mod_transport.NoSuchFile:
            raise errors.NotBranchError(path=transport.base)
        except errors.BadHttpRequest as e:
            if e.reason == 'no such method: .bzr':
                # hgweb
                raise errors.NotBranchError(path=transport.base)
            raise

        try:
            first_line = format_string[:format_string.index(b"\n") + 1]
        except ValueError:
            first_line = format_string
        if (first_line.startswith(b'<!DOCTYPE') or
                first_line.startswith(b'<html')):
            raise errors.NotBranchError(
                path=transport.base, detail="format file looks like HTML")
        try:
            cls = klass.formats.get(first_line)
        except KeyError:
            if first_line.endswith(b"\r\n"):
                raise LineEndingError(file=".bzr/branch-format")
            else:
                raise errors.UnknownFormatError(
                    format=first_line, kind='bzrdir')
        return cls.from_string(format_string)

    @classmethod
    def known_formats(cls):
        result = []
        for name, format in cls.formats.items():
            if callable(format):
                format = format()
            result.append(format)
        return result


controldir.ControlDirFormat.register_prober(BzrProber)


class RemoteBzrProber(controldir.Prober):
    """Prober for remote servers that provide a Bazaar smart server."""

    @classmethod
    def priority(klass, transport):
        return -10

    @classmethod
    def probe_transport(klass, transport):
        """Return a RemoteBzrDirFormat object if it looks possible."""
        try:
            medium = transport.get_smart_medium()
        except (NotImplementedError, AttributeError,
                errors.TransportNotPossible, errors.NoSmartMedium,
                errors.SmartProtocolError):
            # no smart server, so not a branch for this format type.
            raise errors.NotBranchError(path=transport.base)
        else:
            # Decline to open it if the server doesn't support our required
            # version (3) so that the VFS-based transport will do it.
            if medium.should_probe():
                try:
                    server_version = medium.protocol_version()
                except errors.SmartProtocolError:
                    # Apparently there's no usable smar