# Copyright 2015 Canonical Ltd.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, 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, see <http://www.gnu.org/licenses/>.

"""Handle recipe parsing and substitution variables."""

import datetime
from functools import lru_cache
import logging
import os
import subprocess
import sys
from urllib.parse import urlparse

import dateutil.parser
from debian import debian_support


MERGE_INSTRUCTION = "merge"
NEST_PART_INSTRUCTION = "nest-part"
NEST_INSTRUCTION = "nest"
RUN_INSTRUCTION = "run"
USAGE = {
    MERGE_INSTRUCTION: 'merge NAME BRANCH [REVISION]',
    NEST_INSTRUCTION: 'nest NAME BRANCH TARGET-DIR [REVISION]',
    NEST_PART_INSTRUCTION:
        'nest-part NAME BRANCH SUBDIR [TARGET-DIR [REVISION]]',
    RUN_INSTRUCTION: 'run COMMAND',
    }

SAFE_INSTRUCTIONS = [
    MERGE_INSTRUCTION, NEST_PART_INSTRUCTION, NEST_INSTRUCTION]


class FormattedError(Exception):

    def __init__(self, **kwargs):
        super().__init__()
        for key, value in kwargs.items():
            setattr(self, key, value)

    def __str__(self):
        return self._fmt % dict(self.__dict__)

    def __repr__(self):
        return "%s(%s)" % (self.__class__.__name__, str(self))

    def __eq__(self, other):
        if self.__class__ is not other.__class__:
            return NotImplemented
        return self.__dict__ == other.__dict__

    def __ne__(self, other):
        if self.__class__ is not other.__class__:
            return NotImplemented
        return self.__dict__ != other.__dict__

    __hash__ = Exception.__hash__


class SubstitutionUnavailable(FormattedError):

    _fmt = "Substitution for %(name)s not available: %(reason)s"

    def __init__(self, name, reason):
        super().__init__(name=name, reason=reason)


class SubstitutionVariable:
    """A substitution variable for a version string."""

    def replace(self, value):
        """Replace name with value."""
        raise NotImplementedError(self.replace)

    @classmethod
    def available_in(cls, format):
        """Check if this variable is available in a particular format."""
        raise NotImplementedError(cls.available_in)


class SimpleSubstitutionVariable(SubstitutionVariable):

    name = None

    minimum_format = None

    def replace(self, value):
        if not self.name in value:
            return value
        return value.replace(self.name, self.get())

    def get(self):
        raise NotImplementedError(self.value)

    @classmethod
    def available_in(self, format):
        return format >= self.minimum_format


class BranchSubstitutionVariable(SimpleSubstitutionVariable):

    basename = None

    def __init__(self, branch_name=None):
        super().__init__()
        self.branch_name = branch_name

    @classmethod
    def determine_name(cls, branch_name):
        if branch_name is None:
            return "{%s}" % cls.basename
        else:
            return "{%s:%s}" % (cls.basename, branch_name)

    @property
    def name(self):
        return self.determine_name(self.branch_name)


class TimeVariable(SimpleSubstitutionVariable):

    name = "{time}"

    minimum_format = 0.1

    def __init__(self, time):
        self._time = time

    def get(self):
        return self._time.strftime("%Y%m%d%H%M")


class DateVariable(SimpleSubstitutionVariable):

    name = "{date}"

    minimum_format = 0.1

    def __init__(self, time):
        self._time = time

    def get(self):
        return self._time.strftime("%Y%m%d")


class RevisionVariable(BranchSubstitutionVariable):

    minimum_format = 0.1

    def __init__(self, branch):
        super().__init__(branch.name)
        self.branch = branch
        self.commit = branch.commit


class RevnoVariable(RevisionVariable):
    """A {revno} substitution variable.

    This is a distinctly un-git-like bzr-ism, and is therefore a hack.  Most
    users should use {revtime} or {revdate} instead, which is monotonically
    increasing, or perhaps also {git-commit} to ensure uniqueness (but note
    that commit hashes do not increase monotonically, so are not normally
    suitable in version strings).  However, this can result in very long
    version strings, especially if there are multiple branches involved; so
    this may for instance be useful as {revno:packaging} to encode the
    length of the packaging branch.

    This produces an approximation of a bzr revno by taking the length of
    the left-hand history.
    """

    basename = "revno"

    minimum_format = 0.1

    def get(self):
        return self.branch.git_output(
            "rev-list", "--first-parent", "--count", self.commit).rstrip("\n")


class RevtimeVariable(RevisionVariable):

    basename = "revtime"

    minimum_format = 0.4

    def get(self):
        dt = dateutil.parser.parse(self.branch.git_output(
            "log", "-1", "--date=iso", "--format=format:%cd", self.commit))
        return dt.astimezone(datetime.timezone.utc).strftime("%Y%m%d%H%M")


class RevdateVariable(RevisionVariable):

    basename = "revdate"

    minimum_format = 0.4

    def get(self):
        dt = dateutil.parser.parse(self.branch.git_output(
            "log", "-1", "--date=iso", "--format=format:%cd", self.commit))
        return dt.astimezone(datetime.timezone.utc).strftime("%Y%m%d")


class GitCommitVariable(RevisionVariable):

    basename = "git-commit"

    minimum_format = 0.4

    def get(self):
        return self.branch.git_output(
            "rev-parse", "--short", self.commit).rstrip("\n")


class LatestTagVariable(RevisionVariable):

    basename = "latest-tag"

    minimum_format = 0.4

    def get(self):
        # Capture stderr so that exceptions are useful.  We know that git
        # describe does not write to stderr on success.
        return self.branch.git_output(
            "describe", "--tags", "--abbrev=0", self.commit,
            stderr=subprocess.STDOUT).rstrip("\n")


branch_vars = [
    GitCommitVariable,
    LatestTagVariable,
    RevdateVariable,
    RevtimeVariable,
    ]
simple_vars = [
    TimeVariable,
    DateVariable,
    ]


class TargetAlreadyExists(FormattedError):

    _fmt = "%(target)s already exists, but has no .git directory."

    def __init__(self, target):
        super().__init__(target=target)


class GitCommandFailed(FormattedError):

    _fmt = "git %(command)s failed:\n%(output)s"

    def __init__(self, output):
        super().__init__(command=self._cmd, output=output)


class FetchFailed(GitCommandFailed):

    _cmd = "fetch"


class CloneFailed(GitCommandFailed):

    _cmd = "clone"


class CheckoutFailed(GitCommandFailed):

    _cmd = "checkout"


class MergeFailed(GitCommandFailed):

    _cmd = "merge"


# Some default configuration to make writing recipes more pleasant.
insteadof = {
    "lp:": "https://git.launchpad.net/"
    }


def pull_or_clone(base_branch, target_path):
    """Make target_path match base_branch, either by pulling or by cloning."""
    base_branch.path = target_path
    if os.path.exists(target_path) and not os.listdir(target_path):
        os.rmdir(target_path)
    if not os.path.exists(target_path):
        os.makedirs(target_path)
        base_branch.git_call("init")
        for short, base in insteadof.items():
            base_branch.git_call("config", "url.%s.insteadOf" % base, short)
    elif not os.path.exists(os.path.join(target_path, ".git")):
        raise TargetAlreadyExists(target_path)
    try:
        fetch_branches(base_branch)
    except subprocess.CalledProcessError as e:
        raise FetchFailed(e.output)
    try:
        base_branch.resolve_commit()
        # Check out the commit hash directly to detach HEAD and ensure
        # commits (eg. by a merge instruction) don't affect substitution
        # variables.
        # If someone sneakily names a branch after a commit then all
        # hell will break loose (really, git? there's no way to force
        # checkout to interpret its argument as a commit?), but that's
        # their problem.
        base_branch.git_call("checkout", base_branch.commit)
    except subprocess.CalledProcessError as e:
        raise CheckoutFailed(e.output)


def fetch_branches(child_branch):
    url = child_branch.url
    parsed_url = urlparse(url)
    if not parsed_url.scheme and not parsed_url.path.startswith("/"):
        url = os.path.abspath(url)
    # Fetch the remote HEAD.  This may not exist, which is OK as long as the
    # recipe uses explicit branch names.
    try:
        child_branch.git_call(
            "fetch", url,
            "HEAD:refs/remotes/%s/HEAD" % child_branch.remote_name,
            silent=True)
    except subprocess.CalledProcessError as e:
        logging.info(e.output)
        logging.info(
            "Failed to fetch HEAD; recipe instructions for this repository "
            "that do not specify a branch name will fail.")
    # Fetch all remote branches and (implicitly) any tags that reference
    # commits in those refs. Tags that aren't on a branch won't be fetched.
    child_branch.git_call(
        "fetch", url,
        "refs/heads/*:refs/remotes/%s/*" % child_branch.remote_name)


@lru_cache(maxsize=1)
def _git_version():
    raw_git_version = subprocess.check_output(
        ["dpkg-query", "-W", "-f", "${Version}", "git"],
        universal_newlines=True)
    return debian_support.Version(raw_git_version)


def merge_branch(child_branch, target_path):
    """Merge the branch specified by `child_branch`.

    :param child_branch: A `RecipeBranch` identifying the branch and commit
        to merge from.
    :param target_path: The tree to merge into.
    """
    child_branch.path = target_path
    fetch_branches(child_branch)
    try:
        child_branch.resolve_commit()
        cmd = ["merge", "--commit"]
        if _git_version() >= "1:2.9.0":
            cmd.append("--allow-unrelated-histories")
        cmd.extend(["-m", "Merge %s" % child_branch.get_revspec()])
        cmd.append(child_branch.commit)
        child_branch.git_call(*cmd)
    except subprocess.CalledProcessError as e:
        raise MergeFailed(e.output)


def nest_part_branch(child_branch, target_path, subpath, target_subdir=None):
    """Nest the branch subdirectory specified by `child_branch`.

    :param child_branch: A `RecipeBranch` identifying the branch and commit
        to merge from.
    :param target_path: The tree to merge into.
    :param subpath: Only merge files from `child_branch` that are from this
        path.  For example, subpath="/debian" will only merge changes from
        that directory.
    :param target_subdir: Optional directory in `target_path` to merge that
        subpath into.  Defaults to the basename of `subpath`.
    """
    subpath = subpath.lstrip("/")
    if target_subdir is None:
        target_subdir = os.path.basename(subpath)
    # XXX should handle updating as well
    assert not os.path.exists(target_subdir)
    child_branch.path = target_path
    fetch_branches(child_branch)
    child_branch.resolve_commit()
    child_branch.git_call(
        "read-tree", "--prefix", target_subdir, "-u",
        child_branch.commit + ":" + subpath)


def _build_inner_tree(base_branch, target_path):
    revision_of = ""
    if base_branch.revspec is not None:
        revision_of = "revision '%s' of " % base_branch.revspec
    logging.info(
        "Retrieving %s'%s' to put at '%s'." %
        (revision_of, base_branch.url, target_path))
    pull_or_clone(base_branch, target_path)
    base_branch.resolve_commit()
    for instruction in base_branch.child_branches:
        instruction.apply(target_path)


def _resolve_revisions_recurse(new_branch, substitute_branch_vars,
                               if_changed_from=None):
    changed = False
    if substitute_branch_vars is not None:
        # XXX need to make sure new_branch has been fetched
        new_branch.resolve_commit()
        substitute_branch_vars(new_branch)
    if (if_changed_from is not None and
        (new_branch.revspec is not None or
         if_changed_from.revspec is not None)):
        if if_changed_from.revspec is not None:
            # XXX resolve revspec
            changed_commit = if_changed_from.revspec
        else:
            changed_commit = new_branch.commit
        if new_branch.commit != changed_commit:
            changed = True
    for index, instruction in enumerate(new_branch.child_branches):
        child_branch = instruction.recipe_branch
        if_changed_child = None
        if if_changed_from is not None:
            if_changed_child = (
                if_changed_from.child_branches[index].recipe_branch)
        if child_branch is not None:
            child_changed = _resolve_revisions_recurse(
                child_branch, substitute_branch_vars,
                if_changed_from=if_changed_child)
            if child_changed:
                changed = child_changed
    return changed


def resolve_revisions(base_branch, if_changed_from=None,
                      substitute_branch_vars=None):
    """Resolve all the unknowns in `base_branch`.

    This walks the `RecipeBranch` and calls `substitute_branch_vars` for
    each child branch.

    If `if_changed_from` is not None then it should be a second
    `RecipeBranch` to compare `base_branch` against.  If the shape or the
    commit IDs differ then the function will return True.

    :param base_branch: The `RecipeBranch` we plan to build.
    :param if_changed_from: The `RecipeBranch` that we want to compare
        against.
    :param substitute_branch_vars: Callable called for each `RecipeBranch`.
    :return: False if `if_changed_from` is not None, and the shape and
        commits of the two branches are the same.  True otherwise.
    """
    changed = False
    if if_changed_from is not None:
        changed = base_branch.different_shape_to(if_changed_from)
    if_changed_from_revisions = None if changed else if_changed_from

    if substitute_branch_vars is not None:
        real_substitute_branch_vars = (
            lambda child_branch: substitute_branch_vars(
                base_branch, child_branch))
    else:
        real_substitute_branch_vars = None
    changed_revisions = _resolve_revisions_recurse(
        base_branch, real_substitute_branch_vars,
        if_changed_from=if_changed_from_revisions)
    if not changed:
        changed = changed_revisions
    if if_changed_from is not None and not changed:
        return False
    return True


def build_tree(base_branch, target_path):
    logging.info("Building tree.")
    _build_inner_tree(base_branch, target_path)


class ChildBranch:
    """A child branch in a recipe.

    If the nest path is not None it is the path relative to the recipe
    branch where the child branch should be placed.  If it is None then the
    child branch should be merged instead of nested.
    """

    can_have_children = False

    def __init__(self, recipe_branch, nest_path=None):
        self.recipe_branch = recipe_branch
        self.nest_path = nest_path

    def apply(self, target_path):
        raise NotImplementedError(self.apply)

    def as_tuple(self):
        return (self.recipe_branch, self.nest_path)

    def _get_commit_part(self):
        if self.recipe_branch.commit is not None:
            return " git-commit:%s" % self.recipe_branch.commit
        elif self.recipe_branch.revspec is not None:
            return " %s" % self.recipe_branch.revspec
        else:
            return ""

    def __repr__(self):
        return "<%s %r>" % (self.__class__.__name__, self.nest_path)


class CommandInstruction(ChildBranch):

    def apply(self, target_path):
        # it's a command
        logging.info("Running '%s' in '%s'." % (self.nest_path, target_path))
        subprocess.check_call(
            self.nest_path, cwd=target_path, shell=True, stdin=subprocess.PIPE)

    def as_text(self):
        return "%s %s" % (RUN_INSTRUCTION, self.nest_path)


class MergeInstruction(ChildBranch):

    def apply(self, target_path):
        revision_of = ""
        if self.recipe_branch.revspec is not None:
            revision_of = "revision '%s' of " % self.recipe_branch.revspec
        logging.info(
            "Merging %s'%s' in to '%s'." %
            (revision_of, self.recipe_branch.url, target_path))
        merge_branch(self.recipe_branch, target_path)

    def as_text(self):
        commit_part = self._get_commit_part()
        return "%s %s %s%s" % (
            MERGE_INSTRUCTION, self.recipe_branch.name,
            self.recipe_branch.url, commit_part)

    def __repr__(self):
        return "<%s %r>" % (self.__class__.__name__, self.recipe_branch.name)


class NestPartInstruction(ChildBranch):

    def __init__(self, recipe_branch, subpath, target_subdir):
        ChildBranch.__init__(self, recipe_branch)
        self.subpath = subpath
        self.target_subdir = target_subdir

    def apply(self, target_path):
        nest_part_branch(
            self.recipe_branch, target_path, self.subpath,
            target_subdir=self.target_subdir)

    def as_text(self):
        commit_part = self._get_commit_part()
        if commit_part:
            target_subdir = self.target_subdir
            if target_subdir is None:
                target_subdir = self.subpath
            target_commit_part = " %s%s" % (target_subdir, commit_part)
        elif self.target_subdir is not None:
            target_commit_part = " %s" % self.target_subdir
        else:
            target_commit_part = ""
        return "%s %s %s %s%s" % (
            NEST_PART_INSTRUCTION, self.recipe_branch.name,
            self.recipe_branch.url, self.subpath, target_commit_part)


class NestInstruction(ChildBranch):

    can_have_children = True

    def apply(self, target_path):
        _build_inner_tree(
            self.recipe_branch,
            target_path=os.path.join(target_path, self.nest_path))

    def as_text(self):
        commit_part = self._get_commit_part()
        return "%s %s %s %s%s" % (
            NEST_INSTRUCTION, self.recipe_branch.name,
            self.recipe_branch.url, self.nest_path, commit_part)

    def __repr__(self):
        return "<%s %r>" % (self.__class__.__name__,
            self.recipe_branch.name)


class RecipeBranch:
    """A nested structure that represents a Recipe.

    A RecipeBranch has a name and a url (the name can be None for the root
    branch), and optionally child branches that are either merged or nested.

    The `child_branches` attribute is a list of tuples of `ChildBranch`
    objects.  The commit attribute records the commit that the `url` and
    `revspec` resolved to when the `RecipeBranch` was built, or None if it
    has not been built.

    :ivar commit: After this recipe branch has been built, this is set to
        the commit object name that was merged/nested from the branch at
        `self.url`.
    """

    def __init__(self, name, url, revspec=None):
        """Create a `RecipeBranch`.

        :param name: The name for the branch, or None if it is the root.
        :param url: The URL from which to retrieve the branch.
        :param revspec: A revision (as in `git rev-parse`) for the commit to
            use, or None (the default) to use `HEAD`.
        """
        self.name = name
        self.url = url
        self.revspec = revspec
        self.child_branches = []
        self.commit = None
        self.path = None

    @property
    def remote_name(self):
        if self.name is None:
            return 'source'
        return 'source-%s' % self.name

    def _get_git_path(self):
        if self.path is not None:
            return self.path
        elif not urlparse(self.url).scheme:
            return self.url
        else:
            # XXX more specific exception type
            raise Exception(
                "Repository at %s has not been cloned yet" % self.url)

    def git_call(self, *args, **kwargs):
        cmd = ["git", "-C", self._get_git_path()] + list(args)
        silent = kwargs.pop("silent", False)
        # This allows any raised CalledProcessError to contain the output.
        # Writing to stdout/stderr depending on return code is an
        # approximation, but preserves interleaving and should do the job
        # well enough.
        try:
            output = subprocess.check_output(
                cmd, stderr=subprocess.STDOUT, universal_newlines=True,
                **kwargs)
            if not silent:
                sys.stdout.write(output)
        except subprocess.CalledProcessError as e:
            if not silent:
                sys.stderr.write(e.output)
            raise

    def git_output(self, *args, **kwargs):
        return subprocess.check_output(
            ["git", "-C", self._get_git_path()] + list(args),
            universal_newlines=True, **kwargs)

    def get_revspec(self):
        return self.revspec if self.revspec is not None else "HEAD"

    def resolve_commit(self):
        """Resolve the commit for this branch."""
        # Capturing stderr is a bit dodgy, but it's the most convenient way
        # to capture it for any exceptions.  We know that git rev-parse does
        # not write to stderr on success.
        try:
            self.commit = self.git_output(
                "rev-parse", "%s/%s" % (self.remote_name, self.get_revspec()),
                stderr=subprocess.STDOUT).rstrip("\n")
            return
        except subprocess.CalledProcessError:
            pass
        # Not a remote-prefixed ref. Try a global search.
        # XXX: This allows cross-branch pollution, but we don't have
        # much choice without reimplementing rev-parse ourselves.
        self.commit = self.git_output(
            "rev-parse", self.get_revspec(),
            stderr=subprocess.STDOUT).rstrip("\n")

    def merge_branch(self, branch):
        """Merge a child branch into this one.

        :param branch: The `RecipeBranch` to merge.
        """
        self.child_branches.append(MergeInstruction(branch))

    def nest_part_branch(self, branch, subpath=None, target_subdir=None):
        """Merge subdir of a child branch into this one.

        :param branch: The `RecipeBranch` to merge.
        :param subpath: Only merge files from `branch` that are from this
            path.  For example, subpath="/debian" will only merge changes
            from that directory.
        :param target_subdir: Optional directory in the target tree to merge
            that subpath into.  Defaults to the basename of `subpath`.
        """
        self.child_branches.append(
            NestPartInstruction(branch, subpath, target_subdir))

    def nest_branch(self, location, branch):
        """Nest a child branch into this one.

        :param location: The relative path at which this branch should be
            nested.
        :param branch: The `RecipeBranch` to nest.
        """
        if any(location == b.nest_path for b in self.child_branches):
            raise AssertionError(
                "%s already has a branch nested there" % location)
        self.child_branches.append(NestInstruction(branch, location))

    def run_command(self, command):
        """Set a command to be run.

        :param command: The command to be run.
        """
        self.child_branches.append(CommandInstruction(None, command))

    def different_shape_to(self, other_branch):
        """Test whether the name, url, and child_branches are the same."""
        if self.name != other_branch.name:
            return True
        if self.url != other_branch.url:
            return True
        if len(self.child_branches) != len(other_branch.child_branches):
            return True
        for index, instruction in enumerate(self.child_branches):
            child_branch = instruction.recipe_branch
            nest_location = instruction.nest_path
            other_instruction = other_branch.child_branches[index]
            other_child_branch = other_instruction.recipe_branch
            other_nest_location = other_instruction.nest_path
            if nest_location != other_nest_location:
                return True
            if ((child_branch is None and other_child_branch is not None) or
                    (child_branch is not None and other_child_branch is None)):
                return True
            # If child_branch is None then other_child_branch must be None
            # too, meaning that they are both run instructions.  We would
            # compare their nest locations (commands), but that has already
            # been done, so just guard.
            if (child_branch is not None and
                    child_branch.different_shape_to(other_child_branch)):
                return True
        return False

    def iter_all_instructions(self):
        """Iter over all instructions under this branch."""
        for instruction in self.child_branches:
            yield instruction
            child_branch = instruction.recipe_branch
            if child_branch is None:
                continue
            for instruction in child_branch.iter_all_instructions():
                yield instruction

    def iter_all_branches(self):
        """Iterate over all branches."""
        yield self
        for instruction in self.child_branches:
            child_branch = instruction.recipe_branch
            if child_branch is None:
                continue
            for subbranch in child_branch.iter_all_branches():
                yield subbranch

    def lookup_branch(self, name):
        """Look up a branch by its name."""
        for branch in self.iter_all_branches():
            if branch.name == name:
                return branch
        else:
            raise KeyError(name)

    def list_branch_names(self):
        """List all of the branch names under this one.

        :return: A list of the branch names.
        :rtype: list(str)
        """
        return [
            branch.name for branch in self.iter_all_branches()
            if branch.name is not None]

    def __repr__(self):
        return "<%s %r>" % (self.__class__.__name__, self.name)


class BaseRecipeBranch(RecipeBranch):
    """The `RecipeBranch` that is at the root of a recipe."""

    def __init__(self, url, deb_version, format_version, revspec=None):
        """Create a `BaseRecipeBranch`.

        :param deb_version: The template to use for the version number.
            Should be None for anything except the root branch.
        """
        super().__init__(None, url, revspec=revspec)
        self.deb_version = deb_version
        self.format_version = format_version
        if not urlparse(url).scheme:
            self.path = url

    def _add_child_branches_to_manifest(self, child_branches, indent_level):
        manifest = ""
        for instruction in child_branches:
            manifest += "%s%s\n" % ("  " * indent_level, instruction.as_text())
            if instruction.can_have_children:
                manifest += self._add_child_branches_to_manifest(
                    instruction.recipe_branch.child_branches, indent_level + 1)
        return manifest

    def __str__(self):
        return self.get_recipe_text(validate=True)

    def get_recipe_text(self, validate=False):
        manifest = "# git-build-recipe format %s" % str(self.format_version)
        if self.deb_version is not None:
            # TODO: should we store the expanded version that was used?
            manifest += " deb-version %s" % self.deb_version
        manifest += "\n"
        if self.commit is not None:
            manifest += "%s git-commit:%s\n" % (self.url, self.commit)
        elif self.revspec is not None:
            manifest += "%s %s\n" % (self.url, self.revspec)
        else:
            manifest += "%s\n" % self.url
        manifest += self._add_child_branches_to_manifest(
            self.child_branches, 0)
        if validate:
            # Ensure that the recipe can be parsed.
            # TODO: write a function that compares the result of this parse
            # with the branch that we built it from.
            RecipeParser(manifest).parse()
        return manifest


class RecipeParseError(FormattedError):

    _fmt = "Error parsing %(filename)s:%(line)s:%(char)s: %(problem)s."

    def __init__(self, filename, line, char, problem):
        super().__init__(
            filename=filename, line=line, char=char, problem=problem)


class InstructionParseError(RecipeParseError):

    _fmt = RecipeParseError._fmt + "\nUsage: %(usage)s"

    def __init__(self, filename, line, char, problem, instruction):
        super().__init__(filename, line, char, problem)
        self.usage = USAGE[instruction]


class ForbiddenInstructionError(RecipeParseError):

    def __init__(self, filename, line, char, problem, instruction_name=None):
        super().__init__(filename, line, char, problem)
        self.instruction_name = instruction_name


class RecipeParser:
    """Parse a recipe.

    The parse() method is probably the only one that interests you.
    """

    whitespace_chars = " \t"
    eol_char = "\n"
    digit_chars = ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9")

    NEWEST_VERSION = 0.4

    def __init__(self, f):
        """Create a `RecipeParser`.

        :param f: Either the recipe as a string, or a file-like object to
            take it from.
        """
        if getattr(f, "read", None) is not None:
            self.text = f.read()
        else:
            self.text = f
        self.filename = None
        if hasattr(f, "name"):
            self.filename = f.name
        if self.filename is None:
            self.filename = "recipe"

    def parse(self, permitted_instructions=None):
        """Parse the recipe.

        :param permitted_instructions: A list of instructions that you want
            to allow.  Defaults to None allowing them all.
        :type permitted_instructions: list(str) or None
        :return: A `RecipeBranch` representing the recipe.
        """
        self.lines = self.text.split("\n")
        self.index = 0
        self.line_index = 0
        self.current_line = self.lines[self.line_index]
        self.current_indent_level = 0
        self.seen_nicks = set()
        self.seen_paths = {".": 1}
        version, deb_version = self.parse_header()
        self.version = version
        last_instruction = None
        active_branches = []
        last_branch = None
        while self.line_index < len(self.lines):
            if self.is_blankline():
                self.new_line()
                continue
            comment = self.parse_comment_line()
            if comment is not None:
                self.new_line()
                continue
            old_indent_level = self.parse_indent()
            if old_indent_level is not None:
                if (old_indent_level < self.current_indent_level
                    and last_instruction != NEST_INSTRUCTION):
                    self.throw_parse_error(
                        "Not allowed to indent unless after a '%s' line" %
                        NEST_INSTRUCTION)
                if old_indent_level < self.current_indent_level:
                    active_branches.append(last_branch)
                else:
                    unindent = self.current_indent_level - old_indent_level
                    active_branches = active_branches[:unindent]
            if last_instruction is None:
                url = self.take_to_whitespace("branch to start from")
                revspec = self.parse_optional_revspec()
                self.new_line()
                last_branch = BaseRecipeBranch(
                    url, deb_version, self.version, revspec=revspec)
                active_branches = [last_branch]
                last_instruction = ""
            else:
                instruction = self.parse_instruction(
                    permitted_instructions=permitted_instructions)
                if instruction == RUN_INSTRUCTION:
                    self.parse_whitespace(
                        "the command", instruction=instruction)
                    command = self.take_to_newline().strip()
                    self.new_line()
                    active_branches[-1].run_command(command)
                else:
                    branch_id = self.parse_branch_id(instruction)
                    url = self.parse_branch_url(instruction)
                    if instruction == NEST_INSTRUCTION:
                        location = self.parse_branch_location(instruction)
                    if instruction == NEST_PART_INSTRUCTION:
                        path = self.parse_subpath(instruction)
                        target_subdir = self.parse_optional_path()
                        if target_subdir == "":
                            target_subdir = None
                            revspec = None
                        else:
                            revspec = self.parse_optional_revspec()
                    else:
                        revspec = self.parse_optional_revspec()
                    self.new_line(instruction)
                    last_branch = RecipeBranch(branch_id, url, revspec=revspec)
                    if instruction == NEST_INSTRUCTION:
                        active_branches[-1].nest_branch(location, last_branch)
                    elif instruction == MERGE_INSTRUCTION:
                        active_branches[-1].merge_branch(last_branch)
                    elif instruction == NEST_PART_INSTRUCTION:
                        active_branches[-1].nest_part_branch(
                            last_branch, path, target_subdir)
                last_instruction = instruction
        if len(active_branches) == 0:
            self.throw_parse_error("Empty recipe")
        return active_branches[0]

    def parse_header(self):
        self.parse_char("#")
        # Try git-build-recipe last even though it's now the preferred form,
        # in order that user-visible error messages look sensible.
        try:
            self.parse_word("bzr-builder", require_whitespace=False)
        except RecipeParseError:
            self.parse_word("git-build-recipe", require_whitespace=False)
        self.parse_word("format")
        version, version_str = self.peek_float("format version")
        if version > self.NEWEST_VERSION:
            self.throw_parse_error("Unknown format: '%s'" % str(version))
        self.take_chars(len(version_str))
        deb_version = self.parse_optional_deb_version()
        self.new_line()
        return version, deb_version

    def parse_instruction(self, permitted_instructions=None):
        if self.version < 0.2:
            options = (MERGE_INSTRUCTION, NEST_INSTRUCTION)
            options_str = "'%s' or '%s'" % options
        elif self.version < 0.3:
            options = (MERGE_INSTRUCTION, NEST_INSTRUCTION, RUN_INSTRUCTION)
            options_str = "'%s', '%s', or '%s'" % options
        else:
            options = (
                MERGE_INSTRUCTION, NEST_INSTRUCTION, NEST_PART_INSTRUCTION,
                RUN_INSTRUCTION)
            options_str = "'%s', '%s', '%s', or '%s'" % options
        instruction = self.peek_to_whitespace()
        if instruction is None:
            self.throw_parse_error(
                "End of line while looking for %s" % options_str)
        if instruction in options:
            if permitted_instructions is not None:
                if instruction not in permitted_instructions:
                    self.throw_parse_error(
                        "The '%s' instruction is forbidden" % instruction,
                        cls=ForbiddenInstructionError,
                        instruction_name=instruction)
            self.take_chars(len(instruction))
            return instruction
        self.throw_parse_error(
            "Expecting %s, got '%s'" % (options_str, instruction))

    def parse_branch_id(self, instruction):
        self.parse_whitespace("the branch id", instruction=instruction)
        branch_id = self.peek_to_whitespace()
        if branch_id is None:
            self.throw_parse_error(
                "End of line while looking for the branch id",
                cls=InstructionParseError, instruction=instruction)
        if branch_id in self.seen_nicks:
            self.throw_parse_error(
                "'%s' was already used to identify a branch." % branch_id)
        self.take_chars(len(branch_id))
        self.seen_nicks.add(branch_id)
        return branch_id

    def parse_branch_url(self, instruction):
        self.parse_whitespace("the branch url", instruction=instruction)
        return self.take_to_whitespace("the branch url", instruction)

    def parse_branch_location(self, instruction):
        # FIXME: Needs a better term
        self.parse_whitespace("the location to nest")
        location = self.peek_to_whitespace()
        if location is None:
            self.throw_parse_error(
                "End of line while looking for the location to nest",
                cls=InstructionParseError, instruction=instruction)
        norm_location = os.path.normpath(location)
        if norm_location in self.seen_paths:
            self.throw_parse_error(
                "The path '%s' is a duplicate of the one used on line %d." % (
                    location, self.seen_paths[norm_location]),
                cls=InstructionParseError, instruction=instruction)
        if os.path.isabs(norm_location):
            self.throw_parse_error(
                "Absolute paths are not allowed: %s" % location,
                cls=InstructionParseError, instruction=instruction)
        if norm_location.startswith(".."):
            self.throw_parse_error(
                "Paths outside the current directory are not allowed: %s" % (
                    location),
                cls=InstructionParseError, instruction=instruction)
        self.take_chars(len(location))
        self.seen_paths[norm_location] = self.line_index + 1
        return location

    def parse_subpath(self, instruction):
        self.parse_whitespace("the subpath to merge", instruction=instruction)
        return self.take_to_whitespace("the subpath to merge", instruction)

    def parse_revspec(self):
        self.parse_whitespace("the revspec")
        return self.take_to_whitespace("the revspec")

    def parse_optional_deb_version(self):
        self.parse_whitespace("'deb-version'", require=False)
        actual = self.peek_to_whitespace()
        if actual is None:
            # End of line, no version
            return None
        if actual != "deb-version":
            self.throw_expecting_error("deb-version", actual)
        self.take_chars(len("deb-version"))
        self.parse_whitespace("a value for 'deb-version'")
        return self.take_to_whitespace("a value for 'deb-version'")

    def parse_optional_revspec(self):
        self.parse_whitespace(None, require=False)
        revspec = self.peek_to_whitespace()
        if revspec is not None:
            self.take_chars(len(revspec))
        return revspec

    def parse_optional_path(self):
        self.parse_whitespace(None, require=False)
        path = self.peek_to_whitespace()
        if path is not None:
            self.take_chars(len(path))
        return path

    def throw_parse_error(self, problem, cls=None, **kwargs):
        if cls is None:
            cls = RecipeParseError
        raise cls(
            self.filename, self.line_index + 1, self.index + 1, problem,
            **kwargs)

    def throw_expecting_error(self, expected, actual):
        self.throw_parse_error("Expecting '%s', got '%s'" % (expected, actual))

    def throw_eol(self, expected):
        self.throw_parse_error("End of line while looking for '%s'" % expected)

    def new_line(self, instruction=None):
        # Jump over any whitespace
        self.parse_whitespace(None, require=False)
        remaining = self.peek_to_whitespace()
        if remaining is not None:
            kwargs = {}
            if instruction is not None:
                kwargs = {
                    "cls": InstructionParseError,
                    "instruction": instruction,
                    }
            self.throw_parse_error(
                "Expecting the end of the line, got '%s'" % remaining,
                **kwargs)
        self.index = 0
        self.line_index += 1
        if self.line_index >= len(self.lines):
            self.current_line = None
        else:
            self.current_line = self.lines[self.line_index]

    def is_blankline(self):
        whitespace = self.peek_whitespace()
        if whitespace is None:
            return True
        return self.peek_char(skip=len(whitespace)) is None

    def take_char(self):
        if self.index >= len(self.current_line):
            return None
        self.index += 1
        return self.current_line[self.index-1]

    def take_chars(self, num):
        ret = ""
        for i in range(num):
            char = self.take_char()
            if char is None:
                return None
            ret += char
        return ret

    def peek_char(self, skip=0):
        if self.index + skip >= len(self.current_line):
            return None
        return self.current_line[self.index + skip]

    def parse_char(self, char):
        actual = self.peek_char()
        if actual is None:
            self.throw_eol(char)
        if actual == char:
            self.take_char()
            return char
        self.throw_expecting_error(char, actual)

    def parse_indent(self):
        """Parse the indent from the start of the line."""
        # FIXME: should just peek the whitespace
        new_indent = self.parse_whitespace(None, require=False)
        # FIXME: These checks should probably come after we check whether
        # any change in indent is legal at this point:
        # "Indents of 3 spaces aren't allowed" -> make it 2 spaces
        # -> "oh, you aren't allowed to indent at that point anyway"
        if "\t" in new_indent:
            self.throw_parse_error("Indents may not be done by tabs")
        if (len(new_indent) % 2 != 0):
            self.throw_parse_error("Indent not a multiple of two spaces")
        new_indent_level = len(new_indent) // 2
        if new_indent_level != self.current_indent_level:
            old_indent_level = self.current_indent_level
            self.current_indent_level = new_indent_level
            if (new_indent_level > old_indent_level and
                    new_indent_level - old_indent_level != 1):
               self.throw_parse_error(
                    "Indented by more than two spaces at once")
            return old_indent_level
        return None

    def parse_whitespace(self, looking_for, require=True, instruction=None):
        if require:
            actual = self.peek_char()
            if actual is None:
                kwargs = {}
                if instruction is not None:
                    kwargs = {
                        "cls": InstructionParseError,
                        "instruction": instruction,
                        }
                self.throw_parse_error(
                    "End of line while looking for %s" % looking_for, **kwargs)
            if actual not in self.whitespace_chars:
                self.throw_parse_error(
                    "Expecting whitespace before %s, got '%s'." %
                    (looking_for, actual))
        ret = ""
        actual = self.peek_char()
        while actual is not None and actual in self.whitespace_chars:
            self.take_char()
            ret += actual
            actual = self.peek_char()
        return ret

    def peek_whitespace(self):
        ret = ""
        char = self.peek_char()
        if char is None:
            return char
        count = 0
        while char is not None and char in self.whitespace_chars:
            ret += char
            count += 1
            char = self.peek_char(skip=count)
        return ret

    def parse_word(self, expected, require_whitespace=True):
        self.parse_whitespace("'%s'" % expected, require=require_whitespace)
        length = len(expected)
        actual = self.peek_to_whitespace()
        if actual == expected:
            self.take_chars(length)
            return expected
        if actual is None:
            self.throw_eol(expected)
        self.throw_expecting_error(expected, actual)

    def peek_to_whitespace(self):
        ret = ""
        char = self.peek_char()
        if char is None:
            return char
        count = 0
        while char is not None and char not in self.whitespace_chars:
            ret += char
            count += 1
            char = self.peek_char(skip=count)
        return ret

    def take_to_whitespace(self, looking_for, instruction=None):
        text = self.peek_to_whitespace()
        if text is None:
            kwargs = {}
            if instruction is not None:
                kwargs = {
                    "cls": InstructionParseError,
                    "instruction": instruction,
                    }
            self.throw_parse_error(
                "End of line while looking for %s" % looking_for, **kwargs)
        self.take_chars(len(text))
        return text

    def peek_float(self, looking_for):
        self.parse_whitespace(looking_for)
        ret = self._parse_integer()
        conv_fn = int
        if ret == "":
            self.throw_parse_error(
                "Expecting a float, got '%s'" % self.peek_to_whitespace())
        if self.peek_char(skip=len(ret)) == ".":
            conv_fn = float
            ret2 = self._parse_integer(skip=(len(ret) + 1))
            if ret2 == "":
                self.throw_parse_error(
                    "Expecting a float, got '%s'" % self.peek_to_whitespace())
            ret += "." + ret2
        try:
            fl = conv_fn(ret)
        except ValueError:
            self.throw_parse_error("Expecting a float, got '%s'" % ret)
        return (fl, ret)

    def _parse_integer(self, skip=0):
        i = skip
        ret = ""
        while True:
            char = self.peek_char(skip=i)
            if char not in self.digit_chars:
                break
            ret += char
            i += 1
        return ret

    def parse_integer(self):
        ret = self._parse_integer()
        if ret == "":
            self.throw_parse_error(
                "Expected an integer, found %s" % self.peek_to_whitespace())
        self.take_chars(len(ret))
        return ret

    def take_to_newline(self):
        text = self.current_line[self.index:]
        self.index += len(text)
        return text

    def parse_comment_line(self):
        whitespace = self.peek_whitespace()
        if whitespace is None:
            return ""
        if self.peek_char(skip=len(whitespace)) is None:
            return ""
        if self.peek_char(skip=len(whitespace)) != "#":
            return None
        self.parse_whitespace(None, require=False)
        comment = self.current_line[self.index:]
        self.index += len(comment)
        return comment


def parse_recipe(recipe_file, safe=False):
    parser = RecipeParser(recipe_file)
    if safe:
        permitted_instructions = SAFE_INSTRUCTIONS
    else:
        permitted_instructions = None
    return parser.parse(permitted_instructions=permitted_instructions)
