# This file is part of Buildbot.  Buildbot 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, version 2.
#
# 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.
#
# Copyright Buildbot Team Members


from warnings import warn
from email.Utils import formatdate
from twisted.python import log
from twisted.internet import defer
from zope.interface import implements
from buildbot.process.buildstep import RemoteCommand
from buildbot.interfaces import BuildSlaveTooOldError, IRenderable
from buildbot.steps.source.base import Source

class _ComputeRepositoryURL(object):
    implements(IRenderable)

    def __init__(self, step, repository):
        self.step = step
        self.repository = repository

    def getRenderingFor(self, props):
        '''
        Helper function that the repository URL based on the parameter the
        source step took and the Change 'repository' property
        '''

        build = props.getBuild()
        assert build is not None, "Build should be available *during* a build?"
        s = build.getSourceStamp(self.step.codebase)

        repository = self.repository

        if not repository:
            return str(s.repository)
        else:
            if callable(repository):
                d = props.render(repository(s.repository))
            elif isinstance(repository, dict):
                d = props.render(repository.get(s.repository))
            elif isinstance(repository, str) or isinstance(repository, unicode):
                try:
                    return str(repository % s.repository)
                except TypeError:
                    # that's the backward compatibility case
                    d = props.render(repository)
            else:
                d = props.render(repository)

        d.addCallback(str)
        return d

class SlaveSource(Source):

    def __init__(self, mode='update', retry=None, **kwargs):
        """
        @type  mode: string
        @param mode: the kind of VC operation that is desired:
           - 'update': specifies that the checkout/update should be
             performed directly into the workdir. Each build is performed
             in the same directory, allowing for incremental builds. This
             minimizes disk space, bandwidth, and CPU time. However, it
             may encounter problems if the build process does not handle
             dependencies properly (if you must sometimes do a 'clean
             build' to make sure everything gets compiled), or if source
             files are deleted but generated files can influence test
             behavior (e.g. python's .pyc files), or when source
             directories are deleted but generated files prevent CVS from
             removing them. When used with a patched checkout, from a
             previous buildbot try for instance, it will try to "revert"
             the changes first and will do a clobber if it is unable to
             get a clean checkout. The behavior is SCM-dependent.

           - 'copy': specifies that the source-controlled workspace
             should be maintained in a separate directory (called the
             'copydir'), using checkout or update as necessary. For each
             build, a new workdir is created with a copy of the source
             tree (rm -rf workdir; cp -R -P -p copydir workdir). This
             doubles the disk space required, but keeps the bandwidth low
             (update instead of a full checkout). A full 'clean' build
             is performed each time.  This avoids any generated-file
             build problems, but is still occasionally vulnerable to
             problems such as a CVS repository being manually rearranged
             (causing CVS errors on update) which are not an issue with
             a full checkout.

           - 'clobber': specifies that the working directory should be
             deleted each time, necessitating a full checkout for each
             build. This insures a clean build off a complete checkout,
             avoiding any of the problems described above, but is
             bandwidth intensive, as the whole source tree must be
             pulled down for each build.

           - 'export': is like 'clobber', except that e.g. the 'cvs
             export' command is used to create the working directory.
             This command removes all VC metadata files (the
             CVS/.svn/{arch} directories) from the tree, which is
             sometimes useful for creating source tarballs (to avoid
             including the metadata in the tar file). Not all VC systems
             support export.

        @type  retry: tuple of ints (delay, repeats) (or None)
        @param retry: if provided, VC update failures are re-attempted up
                      to REPEATS times, with DELAY seconds between each
                      attempt. Some users have slaves with poor connectivity
                      to their VC repository, and they say that up to 80% of
                      their build failures are due to transient network
                      failures that could be handled by simply retrying a
                      couple times.
        """
        Source.__init__(self, **kwargs)

        assert mode in ("update", "copy", "clobber", "export")
        if retry:
            delay, repeats = retry
            assert isinstance(repeats, int)
            assert repeats > 0
        self.args = {'mode': mode,
                     'retry': retry,
                     }

    def start(self):
        self.args['workdir'] = self.workdir
        self.args['logEnviron'] = self.logEnviron
        self.args['env'] = self.env
        self.args['timeout'] = self.timeout
        Source.start(self)

    def commandComplete(self, cmd):
        if not cmd.updates.has_key("got_revision"):
            return
        got_revision = cmd.updates["got_revision"][-1]
        if got_revision is None:
            return

        self.updateSourceProperty('got_revision', str(got_revision))


class BK(SlaveSource):
    """I perform BitKeeper checkout/update operations."""

    name = 'bk'

    renderables = [ 'bkurl', 'baseURL' ]

    def __init__(self, bkurl=None, baseURL=None,
                 directory=None, extra_args=None, **kwargs):
        """
        @type  bkurl: string
        @param bkurl: the URL which points to the BitKeeper server.

        @type  baseURL: string
        @param baseURL: if branches are enabled, this is the base URL to
                        which a branch name will be appended. It should
                        probably end in a slash. Use exactly one of
                        C{bkurl} and C{baseURL}.
        """

        self.bkurl = _ComputeRepositoryURL(bkurl)
        self.baseURL = _ComputeRepositoryURL(baseURL)
        self.extra_args = extra_args

        Source.__init__(self, **kwargs)

        if bkurl and baseURL:
            raise ValueError("you must use exactly one of bkurl and baseURL")


    def computeSourceRevision(self, changes):
        return changes.revision


    def startVC(self, branch, revision, patch):

        warnings = []
        slavever = self.slaveVersion("bk")
        if not slavever:
            m = "slave does not have the 'bk' command"
            raise BuildSlaveTooOldError(m)

        if self.bkurl:
            assert not branch # we need baseURL= to use branches
            self.args['bkurl'] = self.bkurl
        else:
            self.args['bkurl'] = self.baseURL + branch
        self.args['revision'] = revision
        self.args['patch'] = patch
        self.args['branch'] = branch
        if self.extra_args is not None:
            self.args['extra_args'] = self.extra_args

        revstuff = []
        revstuff.append("[branch]")
        if revision is not None:
            revstuff.append("r%s" % revision)
        if patch is not None:
            revstuff.append("[patch]")
        self.description.extend(revstuff)
        self.descriptionDone.extend(revstuff)

        cmd = RemoteCommand("bk", self.args)
        self.startCommand(cmd, warnings)



class CVS(SlaveSource):
    """I do CVS checkout/update operations.

    Note: if you are doing anonymous/pserver CVS operations, you will need
    to manually do a 'cvs login' on each buildslave before the slave has any
    hope of success. XXX: fix then, take a cvs password as an argument and
    figure out how to do a 'cvs login' on each build
    """

    name = "cvs"

    renderables = [ "cvsroot" ]

    #progressMetrics = ('output',)
    #
    # additional things to track: update gives one stderr line per directory
    # (starting with 'cvs server: Updating ') (and is fairly stable if files
    # is empty), export gives one line per directory (starting with 'cvs
    # export: Updating ') and another line per file (starting with U). Would
    # be nice to track these, requires grepping LogFile data for lines,
    # parsing each line. Might be handy to have a hook in LogFile that gets
    # called with each complete line.

    def __init__(self, cvsroot=None, cvsmodule="",
                 global_options=[], branch=None, checkoutDelay=None,
                 checkout_options=[], export_options=[], extra_options=[],
                 login=None,
                 **kwargs):

        """
        @type  cvsroot: string
        @param cvsroot: CVS Repository from which the source tree should
                        be obtained. '/home/warner/Repository' for local
                        or NFS-reachable repositories,
                        ':pserver:anon@foo.com:/cvs' for anonymous CVS,
                        'user@host.com:/cvs' for non-anonymous CVS or
                        CVS over ssh. Lots of possibilities, check the
                        CVS documentation for more.

        @type  cvsmodule: string
        @param cvsmodule: subdirectory of CVS repository that should be
                          retrieved

        @type  login: string or None
        @param login: if not None, a string which will be provided as a
                      password to the 'cvs login' command, used when a
                      :pserver: method is used to access the repository.
                      This login is only needed once, but must be run
                      each time (just before the CVS operation) because
                      there is no way for the buildslave to tell whether
                      it was previously performed or not.

        @type  branch: string
        @param branch: the default branch name, will be used in a '-r'
                       argument to specify which branch of the source tree
                       should be used for this checkout. Defaults to None,
                       which means to use 'HEAD'.

        @type  checkoutDelay: int or None
        @param checkoutDelay: if not None, the number of seconds to put
                              between the last known Change and the
                              timestamp given to the -D argument. This
                              defaults to exactly half of the parent
                              Build's .treeStableTimer, but it could be
                              set to something else if your CVS change
                              notification has particularly weird
                              latency characteristics.

        @type  global_options: list of strings
        @param global_options: these arguments are inserted in the cvs
                               command line, before the
                               'checkout'/'update' command word. See
                               'cvs --help-options' for a list of what
                               may be accepted here.  ['-r'] will make
                               the checked out files read only. ['-r',
                               '-R'] will also assume the repository is
                               read-only (I assume this means it won't
                               use locks to insure atomic access to the
                               ,v files).

        @type  checkout_options: list of strings
        @param checkout_options: these arguments are inserted in the cvs
                               command line, after 'checkout' but before
                               branch or revision specifiers.

        @type  export_options: list of strings
        @param export_options: these arguments are inserted in the cvs
                               command line, after 'export' but before
                               branch or revision specifiers.

        @type  extra_options: list of strings
        @param extra_options: these arguments are inserted in the cvs
                               command line, after 'checkout' or 'export' but before
                               branch or revision specifiers.
                               """

        self.checkoutDelay = checkoutDelay
        self.branch = branch
        self.cvsroot = _ComputeRepositoryURL(self, cvsroot)

        SlaveSource.__init__(self, **kwargs)

        self.args.update({'cvsmodule': cvsmodule,
                          'global_options': global_options,
                          'checkout_options':checkout_options,
                          'export_options':export_options,
                          'extra_options':extra_options,
                          'login': login,
                          })

    def computeSourceRevision(self, changes):
        if not changes:
            return None
        lastChange = max([c.when for c in changes])
        if self.checkoutDelay is not None:
            when = lastChange + self.checkoutDelay
        else:
            lastSubmit = max([br.submittedAt for br in self.build.requests])
            when = (lastChange + lastSubmit) / 2
        return formatdate(when)

    def startVC(self, branch, revision, patch):
        if self.slaveVersionIsOlderThan("cvs", "1.39"):
            # the slave doesn't know to avoid re-using the same sourcedir
            # when the branch changes. We have no way of knowing which branch
            # the last build used, so if we're using a non-default branch and
            # either 'update' or 'copy' modes, it is safer to refuse to
            # build, and tell the user they need to upgrade the buildslave.
            if (branch != self.branch
                and self.args['mode'] in ("update", "copy")):
                m = ("This buildslave (%s) does not know about multiple "
                     "branches, and using mode=%s would probably build the "
                     "wrong tree. "
                     "Refusing to build. Please upgrade the buildslave to "
                     "buildbot-0.7.0 or newer." % (self.build.slavename,
                                                   self.args['mode']))
                log.msg(m)
                raise BuildSlaveTooOldError(m)

        if self.slaveVersionIsOlderThan("cvs", "2.10"):
            if self.args['extra_options'] or self.args['export_options']:
                m = ("This buildslave (%s) does not support export_options "
                     "or extra_options arguments to the CVS step."
                     % (self.build.slavename))
                log.msg(m)
                raise BuildSlaveTooOldError(m)
            # the unwanted args are empty, and will probably be ignored by
            # the slave, but delete them just to be safe
            del self.args['export_options']
            del self.args['extra_options']

        if branch is None:
            branch = "HEAD"
        self.args['cvsroot'] = self.cvsroot
        self.args['branch'] = branch
        self.args['revision'] = revision
        self.args['patch'] = patch

        if self.args['branch'] == "HEAD" and self.args['revision']:
            # special case. 'cvs update -r HEAD -D today' gives no files
            # TODO: figure out why, see if it applies to -r BRANCH
            self.args['branch'] = None

        # deal with old slaves
        warnings = []
        slavever = self.slaveVersion("cvs", "old")

        if slavever == "old":
            # 0.5.0
            if self.args['mode'] == "export":
                self.args['export'] = 1
            elif self.args['mode'] == "clobber":
                self.args['clobber'] = 1
            elif self.args['mode'] == "copy":
                self.args['copydir'] = "source"
            self.args['tag'] = self.args['branch']
            assert not self.args['patch'] # 0.5.0 slave can't do patch

        cmd = RemoteCommand("cvs", self.args)
        self.startCommand(cmd, warnings)


class SVN(SlaveSource):
    """I perform Subversion checkout/update operations."""

    name = 'svn'
    branch_placeholder = '%%BRANCH%%'

    renderables = [ 'svnurl', 'baseURL' ]

    def __init__(self, svnurl=None, baseURL=None, defaultBranch=None,
                 directory=None, username=None, password=None,
                 extra_args=None, keep_on_purge=None, ignore_ignores=None,
                 always_purge=None, depth=None, **kwargs):
        """
        @type  svnurl: string
        @param svnurl: the URL which points to the Subversion server,
                       combining the access method (HTTP, ssh, local file),
                       the repository host/port, the repository path, the
                       sub-tree within the repository, and the branch to
                       check out. Use exactly one of C{svnurl} and C{baseURL}.

        @param baseURL: if branches are enabled, this is the base URL to
                        which a branch name will be appended. It should
                        probably end in a slash. Use exactly one of
                        C{svnurl} and C{baseURL}.

        @param defaultBranch: if branches are enabled, this is the branch
                              to use if the Build does not specify one
                              explicitly. It will simply be appended
                              to C{baseURL} and the result handed to