Changeset - 2b6939a77052
[Not reviewed]
beta
0 11 0
Marcin Kuzminski - 13 years ago 2012-08-04 01:20:38
marcin@python-works.com
Bumped mercurial version to 2.3
- fixed issues with compare of two remote repos at particular revisions
- added tests for cases when mercurial update broke code and tests didn't catch this
- removed obsolete EmptyChangeset from the rhodecode code
11 files changed with 175 insertions and 67 deletions:
0 comments (0 inline, 0 general)
rhodecode/controllers/changeset.py
Show inline comments
 
@@ -19,58 +19,59 @@
 
# 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, see <http://www.gnu.org/licenses/>.
 
import logging
 
import traceback
 
from collections import defaultdict
 
from webob.exc import HTTPForbidden
 

	
 
from pylons import tmpl_context as c, url, request, response
 
from pylons.i18n.translation import _
 
from pylons.controllers.util import redirect
 
from pylons.decorators import jsonify
 

	
 
from rhodecode.lib.vcs.exceptions import RepositoryError, ChangesetError, \
 
    ChangesetDoesNotExistError
 
from rhodecode.lib.vcs.nodes import FileNode
 

	
 
import rhodecode.lib.helpers as h
 
from rhodecode.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator
 
from rhodecode.lib.base import BaseRepoController, render
 
from rhodecode.lib.utils import EmptyChangeset, action_logger
 
from rhodecode.lib.utils import action_logger
 
from rhodecode.lib.compat import OrderedDict
 
from rhodecode.lib import diffs
 
from rhodecode.model.db import ChangesetComment, ChangesetStatus
 
from rhodecode.model.comment import ChangesetCommentsModel
 
from rhodecode.model.changeset_status import ChangesetStatusModel
 
from rhodecode.model.meta import Session
 
from rhodecode.lib.diffs import wrapped_diff
 
from rhodecode.model.repo import RepoModel
 
from rhodecode.lib.exceptions import StatusChangeOnClosedPullRequestError
 
from rhodecode.lib.vcs.backends.base import EmptyChangeset
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
def _update_with_GET(params, GET):
 
    for k in ['diff1', 'diff2', 'diff']:
 
        params[k] += GET.getall(k)
 

	
 

	
 
def anchor_url(revision, path, GET):
 
    fid = h.FID(revision, path)
 
    return h.url.current(anchor=fid, **dict(GET))
 

	
 

	
 
def get_ignore_ws(fid, GET):
 
    ig_ws_global = GET.get('ignorews')
 
    ig_ws = filter(lambda k: k.startswith('WS'), GET.getall(fid))
 
    if ig_ws:
 
        try:
 
            return int(ig_ws[0].split(':')[-1])
 
        except:
 
            pass
 
    return ig_ws_global
 

	
rhodecode/controllers/compare.py
Show inline comments
 
@@ -50,48 +50,49 @@ class CompareController(BaseRepoControll
 
                                   'repository.admin')
 
    def __before__(self):
 
        super(CompareController, self).__before__()
 

	
 
    def __get_cs_or_redirect(self, rev, repo, redirect_after=True):
 
        """
 
        Safe way to get changeset if error occur it redirects to changeset with
 
        proper message
 

	
 
        :param rev: revision to fetch
 
        :param repo: repo instance
 
        """
 

	
 
        try:
 
            type_, rev = rev
 
            return repo.scm_instance.get_changeset(rev)
 
        except EmptyRepositoryError, e:
 
            if not redirect_after:
 
                return None
 
            h.flash(h.literal(_('There are no changesets yet')),
 
                    category='warning')
 
            redirect(url('summary_home', repo_name=repo.repo_name))
 

	
 
        except RepositoryError, e:
 
            log.error(traceback.format_exc())
 
            h.flash(str(e), category='warning')
 
            redirect(h.url('summary_home', repo_name=repo.repo_name))
 

	
 
    def index(self, org_ref_type, org_ref, other_ref_type, other_ref):
 

	
 
        org_repo = c.rhodecode_db_repo.repo_name
 
        org_ref = (org_ref_type, org_ref)
 
        other_ref = (other_ref_type, other_ref)
 
        other_repo = request.GET.get('repo', org_repo)
 

	
 
        c.swap_url = h.url('compare_url', repo_name=other_repo,
 
              org_ref_type=other_ref[0], org_ref=other_ref[1],
 
              other_ref_type=org_ref[0], other_ref=org_ref[1],
 
              repo=org_repo)
 

	
 
        c.org_repo = org_repo = Repository.get_by_repo_name(org_repo)
 
        c.other_repo = other_repo = Repository.get_by_repo_name(other_repo)
 

	
 
        if c.org_repo is None or c.other_repo is None:
 
            log.error('Could not found repo %s or %s' % (org_repo, other_repo))
 
            raise HTTPNotFound
 

	
 
        if c.org_repo.scm_instance.alias != 'hg':
 
            log.error('Review not available for GIT REPOS')
rhodecode/controllers/files.py
Show inline comments
 
@@ -19,49 +19,49 @@
 
# 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, see <http://www.gnu.org/licenses/>.
 
from __future__ import with_statement
 
import os
 
import logging
 
import traceback
 
import tempfile
 

	
 
from pylons import request, response, tmpl_context as c, url
 
from pylons.i18n.translation import _
 
from pylons.controllers.util import redirect
 
from pylons.decorators import jsonify
 

	
 
from rhodecode.lib import diffs
 
from rhodecode.lib import helpers as h
 

	
 
from rhodecode.lib.compat import OrderedDict
 
from rhodecode.lib.utils2 import convert_line_endings, detect_mode, safe_str
 
from rhodecode.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator
 
from rhodecode.lib.base import BaseRepoController, render
 
from rhodecode.lib.utils import EmptyChangeset
 
from rhodecode.lib.vcs.backends.base import EmptyChangeset
 
from rhodecode.lib.vcs.conf import settings
 
from rhodecode.lib.vcs.exceptions import RepositoryError, \
 
    ChangesetDoesNotExistError, EmptyRepositoryError, \
 
    ImproperArchiveTypeError, VCSError, NodeAlreadyExistsError
 
from rhodecode.lib.vcs.nodes import FileNode
 

	
 
from rhodecode.model.repo import RepoModel
 
from rhodecode.model.scm import ScmModel
 
from rhodecode.model.db import Repository
 

	
 
from rhodecode.controllers.changeset import anchor_url, _ignorews_url,\
 
    _context_url, get_line_ctx, get_ignore_ws
 

	
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class FilesController(BaseRepoController):
 

	
 
    def __before__(self):
 
        super(FilesController, self).__before__()
 
        c.cut_off_limit = self.cut_off_limit
 

	
 
    def __get_cs_or_redirect(self, rev, repo_name, redirect_after=True):
rhodecode/controllers/summary.py
Show inline comments
 
@@ -24,49 +24,49 @@
 
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 

	
 
import traceback
 
import calendar
 
import logging
 
import urllib
 
from time import mktime
 
from datetime import timedelta, date
 
from urlparse import urlparse
 
from rhodecode.lib.compat import product
 

	
 
from rhodecode.lib.vcs.exceptions import ChangesetError, EmptyRepositoryError, \
 
    NodeDoesNotExistError
 

	
 
from pylons import tmpl_context as c, request, url, config
 
from pylons.i18n.translation import _
 

	
 
from beaker.cache import cache_region, region_invalidate
 

	
 
from rhodecode.config.conf import ALL_READMES, ALL_EXTS, LANGUAGES_EXTENSIONS_MAP
 
from rhodecode.model.db import Statistics, CacheInvalidation
 
from rhodecode.lib.utils2 import safe_unicode
 
from rhodecode.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator
 
from rhodecode.lib.base import BaseRepoController, render
 
from rhodecode.lib.utils import EmptyChangeset
 
from rhodecode.lib.vcs.backends.base import EmptyChangeset
 
from rhodecode.lib.markup_renderer import MarkupRenderer
 
from rhodecode.lib.celerylib import run_task
 
from rhodecode.lib.celerylib.tasks import get_commits_stats
 
from rhodecode.lib.helpers import RepoPage
 
from rhodecode.lib.compat import json, OrderedDict
 
from rhodecode.lib.vcs.nodes import FileNode
 

	
 
log = logging.getLogger(__name__)
 

	
 
README_FILES = [''.join([x[0][0], x[1][0]]) for x in
 
                    sorted(list(product(ALL_READMES, ALL_EXTS)),
 
                           key=lambda y:y[0][1] + y[1][1])]
 

	
 

	
 
class SummaryController(BaseRepoController):
 

	
 
    @LoginRequired()
 
    @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
 
                                   'repository.admin')
 
    def __before__(self):
 
        super(SummaryController, self).__before__()
 

	
 
    def index(self, repo_name):
 
        c.dbrepo = dbrepo = c.rhodecode_db_repo
rhodecode/lib/diffs.py
Show inline comments
 
@@ -13,57 +13,58 @@
 
    :license: GPLv3, see COPYING for more details.
 
"""
 
# 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 3 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, see <http://www.gnu.org/licenses/>.
 

	
 
import re
 
import difflib
 
import markupsafe
 

	
 
from itertools import tee, imap
 

	
 
from mercurial import patch
 
from mercurial.mdiff import diffopts
 
from mercurial.bundlerepo import bundlerepository
 
from mercurial import localrepo
 

	
 
from pylons.i18n.translation import _
 

	
 
from rhodecode.lib.compat import BytesIO
 
from rhodecode.lib.vcs.utils.hgcompat import localrepo
 
from rhodecode.lib.vcs.exceptions import VCSError
 
from rhodecode.lib.vcs.nodes import FileNode, SubModuleNode
 
from rhodecode.lib.vcs.backends.base import EmptyChangeset
 
from rhodecode.lib.helpers import escape
 
from rhodecode.lib.utils import EmptyChangeset, make_ui
 
from rhodecode.lib.utils import make_ui
 

	
 

	
 
def wrap_to_table(str_):
 
    return '''<table class="code-difftable">
 
                <tr class="line no-comment">
 
                <td class="lineno new"></td>
 
                <td class="code no-comment"><pre>%s</pre></td>
 
                </tr>
 
              </table>''' % str_
 

	
 

	
 
def wrapped_diff(filenode_old, filenode_new, cut_off_limit=None,
 
                ignore_whitespace=True, line_context=3,
 
                enable_comments=False):
 
    """
 
    returns a wrapped diff into a table, checks for cut_off_limit and presents
 
    proper message
 
    """
 

	
 
    if filenode_old is None:
 
        filenode_old = FileNode(filenode_new.path, '', EmptyChangeset())
 

	
 
    if filenode_old.is_binary or filenode_new.is_binary:
 
        diff = wrap_to_table(_('binary file'))
 
@@ -578,51 +579,51 @@ def differ(org_repo, org_ref, other_repo
 
    repositories
 

	
 
    :param org_repo:
 
    :type org_repo:
 
    :param org_ref:
 
    :type org_ref:
 
    :param other_repo:
 
    :type other_repo:
 
    :param other_ref:
 
    :type other_ref:
 
    """
 

	
 
    bundlerepo = None
 
    ignore_whitespace = False
 
    context = 3
 
    org_repo = org_repo.scm_instance._repo
 
    other_repo = other_repo.scm_instance._repo
 
    opts = diffopts(git=True, ignorews=ignore_whitespace, context=context)
 
    org_ref = org_ref[1]
 
    other_ref = other_ref[1]
 

	
 
    if org_repo != other_repo:
 

	
 
        common, incoming, rheads = discovery_data
 

	
 
        other_repo_peer = localrepo.locallegacypeer(other_repo.local())
 
        # create a bundle (uncompressed if other repo is not local)
 
        if other_repo.capable('getbundle') and incoming:
 
        if other_repo_peer.capable('getbundle') and incoming:
 
            # disable repo hooks here since it's just bundle !
 
            # patch and reset hooks section of UI config to not run any
 
            # hooks on fetching archives with subrepos
 
            for k, _ in other_repo.ui.configitems('hooks'):
 
                other_repo.ui.setconfig('hooks', k, None)
 

	
 
            unbundle = other_repo.getbundle('incoming', common=common,
 
                                            heads=rheads)
 

	
 
            buf = BytesIO()
 
            while True:
 
                chunk = unbundle._stream.read(1024 * 4)
 
                if not chunk:
 
                    break
 
                buf.write(chunk)
 

	
 
            buf.seek(0)
 
            # replace chunked _stream with data that can do tell() and seek()
 
            unbundle._stream = buf
 

	
 
            ui = make_ui('db')
 
            bundlerepo = InMemoryBundleRepo(ui, path=org_repo.root,
 
                                            bundlestream=unbundle)
 

	
rhodecode/lib/utils.py
Show inline comments
 
@@ -325,92 +325,48 @@ def set_rhodecode_config(config):
 
    """
 
    Updates pylons config with new settings from database
 

	
 
    :param config:
 
    """
 
    hgsettings = RhodeCodeSetting.get_app_settings()
 

	
 
    for k, v in hgsettings.items():
 
        config[k] = v
 

	
 

	
 
def invalidate_cache(cache_key, *args):
 
    """
 
    Puts cache invalidation task into db for
 
    further global cache invalidation
 
    """
 

	
 
    from rhodecode.model.scm import ScmModel
 

	
 
    if cache_key.startswith('get_repo_cached_'):
 
        name = cache_key.split('get_repo_cached_')[-1]
 
        ScmModel().mark_for_invalidation(name)
 

	
 

	
 
class EmptyChangeset(BaseChangeset):
 
    """
 
    An dummy empty changeset. It's possible to pass hash when creating
 
    an EmptyChangeset
 
    """
 

	
 
    def __init__(self, cs='0' * 40, repo=None, requested_revision=None,
 
                 alias=None):
 
        self._empty_cs = cs
 
        self.revision = -1
 
        self.message = ''
 
        self.author = ''
 
        self.date = ''
 
        self.repository = repo
 
        self.requested_revision = requested_revision
 
        self.alias = alias
 

	
 
    @LazyProperty
 
    def raw_id(self):
 
        """
 
        Returns raw string identifying this changeset, useful for web
 
        representation.
 
        """
 

	
 
        return self._empty_cs
 

	
 
    @LazyProperty
 
    def branch(self):
 
        return get_backend(self.alias).DEFAULT_BRANCH_NAME
 

	
 
    @LazyProperty
 
    def short_id(self):
 
        return self.raw_id[:12]
 

	
 
    def get_file_changeset(self, path):
 
        return self
 

	
 
    def get_file_content(self, path):
 
        return u''
 

	
 
    def get_file_size(self, path):
 
        return 0
 

	
 

	
 
def map_groups(path):
 
    """
 
    Given a full path to a repository, create all nested groups that this
 
    repo is inside. This function creates parent-child relationships between
 
    groups and creates default perms for all new groups.
 

	
 
    :param paths: full path to repository
 
    """
 
    sa = meta.Session()
 
    groups = path.split(Repository.url_sep())
 
    parent = None
 
    group = None
 

	
 
    # last element is repo in nested groups structure
 
    groups = groups[:-1]
 
    rgm = ReposGroupModel(sa)
 
    for lvl, group_name in enumerate(groups):
 
        group_name = '/'.join(groups[:lvl] + [group_name])
 
        group = RepoGroup.get_by_group_name(group_name)
 
        desc = '%s group' % group_name
 

	
 
        # skip folders that are now removed repos
 
        if REMOVED_REPO_PAT.match(group_name):
 
            break
rhodecode/lib/utils2.py
Show inline comments
 
@@ -396,56 +396,56 @@ def credentials_filter(uri):
 
    """
 
    Returns a url with removed credentials
 

	
 
    :param uri:
 
    """
 

	
 
    uri = uri_filter(uri)
 
    #check if we have port
 
    if len(uri) > 2 and uri[2]:
 
        uri[2] = ':' + uri[2]
 

	
 
    return ''.join(uri)
 

	
 

	
 
def get_changeset_safe(repo, rev):
 
    """
 
    Safe version of get_changeset if this changeset doesn't exists for a
 
    repo it returns a Dummy one instead
 

	
 
    :param repo:
 
    :param rev:
 
    """
 
    from rhodecode.lib.vcs.backends.base import BaseRepository
 
    from rhodecode.lib.vcs.exceptions import RepositoryError
 
    from rhodecode.lib.vcs.backends.base import EmptyChangeset
 
    if not isinstance(repo, BaseRepository):
 
        raise Exception('You must pass an Repository '
 
                        'object as first argument got %s', type(repo))
 

	
 
    try:
 
        cs = repo.get_changeset(rev)
 
    except RepositoryError:
 
        from rhodecode.lib.utils import EmptyChangeset
 
        cs = EmptyChangeset(requested_revision=rev)
 
    return cs
 

	
 

	
 
MENTIONS_REGEX = r'(?:^@|\s@)([a-zA-Z0-9]{1}[a-zA-Z0-9\-\_\.]+)(?:\s{1})'
 

	
 

	
 
def extract_mentioned_users(s):
 
    """
 
    Returns unique usernames from given string s that have @mention
 

	
 
    :param s: string to get mentions
 
    """
 
    usrs = set()
 
    for username in re.findall(MENTIONS_REGEX, s):
 
        usrs.add(username)
 

	
 
    return sorted(list(usrs), key=lambda k: k.lower())
 

	
 
class AttributeDict(dict):
 
    def __getattr__(self, attr):
 
        return self.get(attr, None)
 
    __setattr__ = dict.__setitem__
 
    __delattr__ = dict.__delitem__
rhodecode/lib/vcs/utils/hgcompat.py
Show inline comments
 
"""
 
Mercurial libs compatibility
 
"""
 

	
 
from mercurial import archival, merge as hg_merge, patch, ui
 
from mercurial.commands import clone, nullid, pull
 
from mercurial.context import memctx, memfilectx
 
from mercurial.error import RepoError, RepoLookupError, Abort
 
from mercurial.hgweb.common import get_contact
 
from mercurial.localrepo import localrepository
 
from mercurial.match import match
 
from mercurial.mdiff import diffopts
 
from mercurial.node import hex
 
from mercurial.encoding import tolocal
 
from mercurial import discovery
 
from mercurial import localrepo
 
from mercurial import scmutil
 
\ No newline at end of file
rhodecode/model/pull_request.py
Show inline comments
 
@@ -15,49 +15,49 @@
 
# the Free Software Foundation, either version 3 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, see <http://www.gnu.org/licenses/>.
 

	
 
import logging
 
import binascii
 
import datetime
 

	
 
from pylons.i18n.translation import _
 

	
 
from rhodecode.model.meta import Session
 
from rhodecode.lib import helpers as h
 
from rhodecode.model import BaseModel
 
from rhodecode.model.db import PullRequest, PullRequestReviewers, Notification
 
from rhodecode.model.notification import NotificationModel
 
from rhodecode.lib.utils2 import safe_unicode
 

	
 
from rhodecode.lib.vcs.utils.hgcompat import discovery
 
from rhodecode.lib.vcs.utils.hgcompat import discovery, localrepo, scmutil
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class PullRequestModel(BaseModel):
 

	
 
    cls = PullRequest
 

	
 
    def __get_pull_request(self, pull_request):
 
        return self._get_instance(PullRequest, pull_request)
 

	
 
    def get_all(self, repo):
 
        repo = self._get_repo(repo)
 
        return PullRequest.query().filter(PullRequest.other_repo == repo).all()
 

	
 
    def create(self, created_by, org_repo, org_ref, other_repo,
 
               other_ref, revisions, reviewers, title, description=None):
 

	
 
        created_by_user = self._get_user(created_by)
 
        org_repo = self._get_repo(org_repo)
 
        other_repo = self._get_repo(other_repo)
 

	
 
        new = PullRequest()
 
        new.org_repo = org_repo
 
@@ -129,116 +129,117 @@ class PullRequestModel(BaseModel):
 
        pull_request = self.__get_pull_request(pull_request)
 
        pull_request.status = PullRequest.STATUS_CLOSED
 
        pull_request.updated_on = datetime.datetime.now()
 
        self.sa.add(pull_request)
 

	
 
    def _get_changesets(self, org_repo, org_ref, other_repo, other_ref,
 
                        discovery_data):
 
        """
 
        Returns a list of changesets that are incoming from org_repo@org_ref
 
        to other_repo@other_ref
 

	
 
        :param org_repo:
 
        :type org_repo:
 
        :param org_ref:
 
        :type org_ref:
 
        :param other_repo:
 
        :type other_repo:
 
        :param other_ref:
 
        :type other_ref:
 
        :param tmp:
 
        :type tmp:
 
        """
 
        changesets = []
 
        #case two independent repos
 
        if org_repo != other_repo:
 
            common, incoming, rheads = discovery_data
 

	
 
            if not incoming:
 
                revs = []
 
            else:
 
        if org_repo != other_repo and incoming:
 
                revs = org_repo._repo.changelog.findmissing(common, rheads)
 

	
 
            for cs in reversed(map(binascii.hexlify, revs)):
 
                changesets.append(org_repo.get_changeset(cs))
 
        else:
 
            _revset_predicates = {
 
                    'branch': 'branch',
 
                    'book': 'bookmark',
 
                    'tag': 'tag',
 
                    'rev': 'id',
 
                }
 

	
 
            revs = [
 
                "ancestors(%s('%s')) and not ancestors(%s('%s'))" % (
 
                    _revset_predicates[org_ref[0]], org_ref[1],
 
                    _revset_predicates[other_ref[0]], other_ref[1]
 
               )
 
            ]
 

	
 
            from mercurial import scmutil
 
            out = scmutil.revrange(org_repo._repo, revs)
 
            for cs in reversed(out):
 
                changesets.append(org_repo.get_changeset(cs))
 

	
 
        return changesets
 

	
 
    def _get_discovery(self, org_repo, org_ref, other_repo, other_ref):
 
        """
 
        Get's mercurial discovery data used to calculate difference between
 
        repos and refs
 

	
 
        :param org_repo:
 
        :type org_repo:
 
        :param org_ref:
 
        :type org_ref:
 
        :param other_repo:
 
        :type other_repo:
 
        :param other_ref:
 
        :type other_ref:
 
        """
 

	
 
        other = org_repo._repo
 
        repo = other_repo._repo
 
        tip = other[org_ref[1]]
 
        _org_repo = org_repo._repo
 
        org_rev_type, org_rev = org_ref
 

	
 
        _other_repo = other_repo._repo
 
        other_rev_type, other_rev = other_ref
 

	
 
        log.debug('Doing discovery for %s@%s vs %s@%s' % (
 
                        org_repo, org_ref, other_repo, other_ref)
 
        )
 
        log.debug('Filter heads are %s[%s]' % (tip, org_ref[1]))
 
        #log.debug('Filter heads are %s[%s]' % ('', org_ref[1]))
 
        org_peer = localrepo.locallegacypeer(_org_repo.local())
 
        tmp = discovery.findcommonincoming(
 
                  repo=repo,  # other_repo we check for incoming
 
                  remote=other,  # org_repo source for incoming
 
                  heads=[tip.node()],
 
                  repo=_other_repo,  # other_repo we check for incoming
 
                  remote=org_peer,  # org_repo source for incoming
 
                  heads=[_other_repo[other_rev].node(),
 
                         _org_repo[org_rev].node()],
 
                  force=False
 
        )
 
        return tmp
 

	
 
    def get_compare_data(self, org_repo, org_ref, other_repo, other_ref):
 
        """
 
        Returns a tuple of incomming changesets, and discoverydata cache
 

	
 
        :param org_repo:
 
        :type org_repo:
 
        :param org_ref:
 
        :type org_ref:
 
        :param other_repo:
 
        :type other_repo:
 
        :param other_ref:
 
        :type other_ref:
 
        """
 

	
 
        if len(org_ref) != 2 or not isinstance(org_ref, (list, tuple)):
 
            raise Exception('org_ref must be a two element list/tuple')
 

	
 
        if len(other_ref) != 2 or not isinstance(org_ref, (list, tuple)):
 
            raise Exception('other_ref must be a two element list/tuple')
 

	
 
        discovery_data = self._get_discovery(org_repo.scm_instance,
 
                                           org_ref,
 
                                           other_repo.scm_instance,
 
                                           other_ref)
 
        cs_ranges = self._get_changesets(org_repo.scm_instance,
 
                                           org_ref,
 
                                           other_repo.scm_instance,
 
                                           other_ref,
 
                                           discovery_data)
 

	
 
        return cs_ranges, discovery_data
rhodecode/model/scm.py
Show inline comments
 
@@ -19,55 +19,56 @@
 
# 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, see <http://www.gnu.org/licenses/>.
 
from __future__ import with_statement
 
import os
 
import re
 
import time
 
import traceback
 
import logging
 
import cStringIO
 
import pkg_resources
 
from os.path import dirname as dn, join as jn
 

	
 
from sqlalchemy import func
 
from pylons.i18n.translation import _
 

	
 
import rhodecode
 
from rhodecode.lib.vcs import get_backend
 
from rhodecode.lib.vcs.exceptions import RepositoryError
 
from rhodecode.lib.vcs.utils.lazy import LazyProperty
 
from rhodecode.lib.vcs.nodes import FileNode
 
from rhodecode.lib.vcs.backends.base import EmptyChangeset
 

	
 
from rhodecode import BACKENDS
 
from rhodecode.lib import helpers as h
 
from rhodecode.lib.utils2 import safe_str, safe_unicode
 
from rhodecode.lib.auth import HasRepoPermissionAny, HasReposGroupPermissionAny
 
from rhodecode.lib.utils import get_repos as get_filesystem_repos, make_ui, \
 
    action_logger, EmptyChangeset, REMOVED_REPO_PAT
 
    action_logger, REMOVED_REPO_PAT
 
from rhodecode.model import BaseModel
 
from rhodecode.model.db import Repository, RhodeCodeUi, CacheInvalidation, \
 
    UserFollowing, UserLog, User, RepoGroup, PullRequest
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class UserTemp(object):
 
    def __init__(self, user_id):
 
        self.user_id = user_id
 

	
 
    def __repr__(self):
 
        return "<%s('id:%s')>" % (self.__class__.__name__, self.user_id)
 

	
 

	
 
class RepoTemp(object):
 
    def __init__(self, repo_id):
 
        self.repo_id = repo_id
 

	
 
    def __repr__(self):
 
        return "<%s('id:%s')>" % (self.__class__.__name__, self.repo_id)
 

	
 

	
 
class CachedRepoList(object):
 
@@ -393,111 +394,119 @@ class ScmModel(BaseModel):
 
            raise Exception("This repository doesn't have a clone uri")
 

	
 
        repo = dbrepo.scm_instance
 
        try:
 
            extras = {
 
                'ip': '',
 
                'username': username,
 
                'action': 'push_remote',
 
                'repository': dbrepo.repo_name,
 
                'scm': repo.alias,
 
            }
 
            Repository.inject_ui(repo, extras=extras)
 

	
 
            if repo.alias == 'git':
 
                repo.fetch(clone_uri)
 
            else:
 
                repo.pull(clone_uri)
 
            self.mark_for_invalidation(dbrepo.repo_name)
 
        except:
 
            log.error(traceback.format_exc())
 
            raise
 

	
 
    def commit_change(self, repo, repo_name, cs, user, author, message,
 
                      content, f_path):
 
        """
 
        Commits changes
 

	
 
        :param repo: SCM instance
 

	
 
        """
 

	
 
        if repo.alias == 'hg':
 
            from rhodecode.lib.vcs.backends.hg import \
 
                MercurialInMemoryChangeset as IMC
 
        elif repo.alias == 'git':
 
            from rhodecode.lib.vcs.backends.git import \
 
                GitInMemoryChangeset as IMC
 

	
 
        # decoding here will force that we have proper encoded values
 
        # in any other case this will throw exceptions and deny commit
 
        content = safe_str(content)
 
        path = safe_str(f_path)
 
        # message and author needs to be unicode
 
        # proper backend should then translate that into required type
 
        message = safe_unicode(message)
 
        author = safe_unicode(author)
 
        m = IMC(repo)
 
        m.change(FileNode(path, content))
 
        tip = m.commit(message=message,
 
                       author=author,
 
                       parents=[cs], branch=cs.branch)
 

	
 
        action = 'push_local:%s' % tip.raw_id
 
        action_logger(user, action, repo_name)
 
        self.mark_for_invalidation(repo_name)
 
        return tip
 

	
 
    def create_node(self, repo, repo_name, cs, user, author, message, content,
 
                      f_path):
 
        if repo.alias == 'hg':
 
            from rhodecode.lib.vcs.backends.hg import MercurialInMemoryChangeset as IMC
 
        elif repo.alias == 'git':
 
            from rhodecode.lib.vcs.backends.git import GitInMemoryChangeset as IMC
 
        # decoding here will force that we have proper encoded values
 
        # in any other case this will throw exceptions and deny commit
 

	
 
        if isinstance(content, (basestring,)):
 
            content = safe_str(content)
 
        elif isinstance(content, (file, cStringIO.OutputType,)):
 
            content = content.read()
 
        else:
 
            raise Exception('Content is of unrecognized type %s' % (
 
                type(content)
 
            ))
 

	
 
        message = safe_unicode(message)
 
        author = safe_unicode(author)
 
        path = safe_str(f_path)
 
        m = IMC(repo)
 

	
 
        if isinstance(cs, EmptyChangeset):
 
            # EmptyChangeset means we we're editing empty repository
 
            parents = None
 
        else:
 
            parents = [cs]
 

	
 
        m.add(FileNode(path, content=content))
 
        tip = m.commit(message=message,
 
                       author=author,
 
                       parents=parents, branch=cs.branch)
 

	
 
        action = 'push_local:%s' % tip.raw_id
 
        action_logger(user, action, repo_name)
 
        self.mark_for_invalidation(repo_name)
 
        return tip
 

	
 
    def get_nodes(self, repo_name, revision, root_path='/', flat=True):
 
        """
 
        recursive walk in root dir and return a set of all path in that dir
 
        based on repository walk function
 

	
 
        :param repo_name: name of repository
 
        :param revision: revision for which to list nodes
 
        :param root_path: root path to list
 
        :param flat: return as a list, if False returns a dict with decription
 

	
 
        """
 
        _files = list()
 
        _dirs = list()
 
        try:
 
            _repo = self.__get_repo(repo_name)
 
            changeset = _repo.scm_instance.get_changeset(revision)
 
            root_path = root_path.lstrip('/')
 
            for topnode, dirs, files in changeset.walk(root_path):
 
                for f in files:
 
                    _files.append(f.path if flat else {"name": f.path,
 
                                                       "type": "file"})
 
                for d in dirs:
 
                    _dirs.append(d.path if flat else {"name": d.path,
rhodecode/tests/functional/test_compare.py
Show inline comments
 
from rhodecode.tests import *
 
from rhodecode.model.repo import RepoModel
 
from rhodecode.model.meta import Session
 
from rhodecode.model.db import Repository
 
from rhodecode.model.scm import ScmModel
 
from rhodecode.lib.vcs.backends.base import EmptyChangeset
 

	
 

	
 
class TestCompareController(TestController):
 

	
 
    def test_index_tag(self):
 
        self.log_user()
 
        tag1='0.1.3'
 
        tag2='0.1.2'
 
        response = self.app.get(url(controller='compare', action='index',
 
                                    repo_name=HG_REPO,
 
                                    org_ref_type="tag",
 
                                    org_ref=tag1,
 
                                    other_ref_type="tag",
 
                                    other_ref=tag2,
 
                                    ))
 
        response.mustcontain('%s@%s -> %s@%s' % (HG_REPO, tag1, HG_REPO, tag2))
 
        ## outgoing changesets between tags
 
        response.mustcontain('''<a href="/%s/changeset/17544fbfcd33ffb439e2b728b5d526b1ef30bfcf">r120:17544fbfcd33</a>''' % HG_REPO)
 
        response.mustcontain('''<a href="/%s/changeset/36e0fc9d2808c5022a24f49d6658330383ed8666">r119:36e0fc9d2808</a>''' % HG_REPO)
 
        response.mustcontain('''<a href="/%s/changeset/bb1a3ab98cc45cb934a77dcabf87a5a598b59e97">r118:bb1a3ab98cc4</a>''' % HG_REPO)
 
        response.mustcontain('''<a href="/%s/changeset/41fda979f02fda216374bf8edac4e83f69e7581c">r117:41fda979f02f</a>''' % HG_REPO)
 
        response.mustcontain('''<a href="/%s/changeset/9749bfbfc0d2eba208d7947de266303b67c87cda">r116:9749bfbfc0d2</a>''' % HG_REPO)
 
        response.mustcontain('''<a href="/%s/changeset/70d4cef8a37657ee4cf5aabb3bd9f68879769816">r115:70d4cef8a376</a>''' % HG_REPO)
 
        response.mustcontain('''<a href="/%s/changeset/c5ddebc06eaaba3010c2d66ea6ec9d074eb0f678">r112:c5ddebc06eaa</a>''' % HG_REPO)
 
@@ -29,24 +34,156 @@ class TestCompareController(TestControll
 
        response.mustcontain('''<div class="node"><a href="/%s/compare/tag@%s...tag@%s#C--e3305437df55">test_and_report.sh</a></div>''' % (HG_REPO, tag1,  tag2))
 
        response.mustcontain('''<div class="node"><a href="/%s/compare/tag@%s...tag@%s#C--c8e92ef85cd1">.hgignore</a></div>''' % (HG_REPO, tag1,  tag2))
 
        response.mustcontain('''<div class="node"><a href="/%s/compare/tag@%s...tag@%s#C--6e08b694d687">.hgtags</a></div>''' % (HG_REPO, tag1,  tag2))
 
        response.mustcontain('''<div class="node"><a href="/%s/compare/tag@%s...tag@%s#C--2c14b00f3393">docs/api/index.rst</a></div>''' % (HG_REPO, tag1,  tag2))
 
        response.mustcontain('''<div class="node"><a href="/%s/compare/tag@%s...tag@%s#C--430ccbc82bdf">vcs/__init__.py</a></div>''' % (HG_REPO, tag1,  tag2))
 
        response.mustcontain('''<div class="node"><a href="/%s/compare/tag@%s...tag@%s#C--9c390eb52cd6">vcs/backends/hg.py</a></div>''' % (HG_REPO, tag1,  tag2))
 
        response.mustcontain('''<div class="node"><a href="/%s/compare/tag@%s...tag@%s#C--ebb592c595c0">vcs/utils/__init__.py</a></div>''' % (HG_REPO, tag1,  tag2))
 
        response.mustcontain('''<div class="node"><a href="/%s/compare/tag@%s...tag@%s#C--7abc741b5052">vcs/utils/annotate.py</a></div>''' % (HG_REPO, tag1,  tag2))
 
        response.mustcontain('''<div class="node"><a href="/%s/compare/tag@%s...tag@%s#C--2ef0ef106c56">vcs/utils/diffs.py</a></div>''' % (HG_REPO, tag1,  tag2))
 
        response.mustcontain('''<div class="node"><a href="/%s/compare/tag@%s...tag@%s#C--3150cb87d4b7">vcs/utils/lazy.py</a></div>''' % (HG_REPO, tag1,  tag2))
 

	
 
    def test_index_branch(self):
 
        self.log_user()
 
        response = self.app.get(url(controller='compare', action='index',
 
                                    repo_name=HG_REPO,
 
                                    org_ref_type="branch",
 
                                    org_ref='default',
 
                                    other_ref_type="branch",
 
                                    other_ref='default',
 
                                    ))
 

	
 
        response.mustcontain('%s@default -> %s@default' % (HG_REPO, HG_REPO))
 
        # branch are equal
 
        response.mustcontain('<tr><td>No changesets</td></tr>')
 

	
 
    def test_compare_revisions(self):
 
        self.log_user()
 
        rev1 = '3d8f361e72ab'
 
        rev2 = 'b986218ba1c9'
 
        response = self.app.get(url(controller='compare', action='index',
 
                                    repo_name=HG_REPO,
 
                                    org_ref_type="rev",
 
                                    org_ref=rev1,
 
                                    other_ref_type="rev",
 
                                    other_ref=rev2,
 
                                    ))
 
        response.mustcontain('%s@%s -> %s@%s' % (HG_REPO, rev1, HG_REPO, rev2))
 
        ## outgoing changesets between those revisions
 
        response.mustcontain("""<a href="/%s/changeset/3d8f361e72ab303da48d799ff1ac40d5ac37c67e">r1:%s</a>""" % (HG_REPO, rev1))
 

	
 
        ## files
 
        response.mustcontain("""<a href="/%s/compare/rev@%s...rev@%s#C--c8e92ef85cd1">.hgignore</a>""" % (HG_REPO, rev1, rev2))
 

	
 
    def test_compare_remote_repos(self):
 
        self.log_user()
 

	
 
        form_data = dict(
 
            repo_name=HG_FORK,
 
            repo_name_full=HG_FORK,
 
            repo_group=None,
 
            repo_type='hg',
 
            description='',
 
            private=False,
 
            copy_permissions=False,
 
            landing_rev='tip',
 
            update_after_clone=False,
 
            fork_parent_id=Repository.get_by_repo_name(HG_REPO),
 
        )
 
        RepoModel().create_fork(form_data, cur_user=TEST_USER_ADMIN_LOGIN)
 

	
 
        Session().commit()
 

	
 
        rev1 = '7d4bc8ec6be5'
 
        rev2 = '56349e29c2af'
 

	
 
        response = self.app.get(url(controller='compare', action='index',
 
                                    repo_name=HG_REPO,
 
                                    org_ref_type="rev",
 
                                    org_ref=rev1,
 
                                    other_ref_type="rev",
 
                                    other_ref=rev2,
 
                                    repo=HG_FORK
 
                                    ))
 

	
 
        try:
 
            response.mustcontain('%s@%s -> %s@%s' % (HG_REPO, rev1, HG_FORK, rev2))
 
            ## outgoing changesets between those revisions
 

	
 
            response.mustcontain("""<a href="/%s/changeset/7d4bc8ec6be56c0f10425afb40b6fc315a4c25e7">r6:%s</a>""" % (HG_REPO, rev1))
 
            response.mustcontain("""<a href="/%s/changeset/6fff84722075f1607a30f436523403845f84cd9e">r5:6fff84722075</a>""" % (HG_REPO))
 
            response.mustcontain("""<a href="/%s/changeset/2dda4e345facb0ccff1a191052dd1606dba6781d">r4:2dda4e345fac</a>""" % (HG_REPO))
 

	
 
            ## files
 
            response.mustcontain("""<a href="/%s/compare/rev@%s...rev@%s#C--9c390eb52cd6">vcs/backends/hg.py</a>""" % (HG_REPO, rev1, rev2))
 
            response.mustcontain("""<a href="/%s/compare/rev@%s...rev@%s#C--41b41c1f2796">vcs/backends/__init__.py</a>""" % (HG_REPO, rev1, rev2))
 
            response.mustcontain("""<a href="/%s/compare/rev@%s...rev@%s#C--2f574d260608">vcs/backends/base.py</a>""" % (HG_REPO, rev1, rev2))
 
        finally:
 
            RepoModel().delete(HG_FORK)
 

	
 
    def test_compare_extra_commits(self):
 
        self.log_user()
 

	
 
        repo1 = RepoModel().create_repo(repo_name='one', repo_type='hg',
 
                                        description='diff-test',
 
                                        owner=TEST_USER_ADMIN_LOGIN)
 

	
 
        repo2 = RepoModel().create_repo(repo_name='one-fork', repo_type='hg',
 
                                        description='diff-test',
 
                                        owner=TEST_USER_ADMIN_LOGIN)
 

	
 
        Session().commit()
 
        r1_id = repo1.repo_id
 
        r1_name = repo1.repo_name
 
        r2_id = repo2.repo_id
 
        r2_name = repo2.repo_name
 

	
 
        #commit something !
 
        cs0 = ScmModel().create_node(
 
            repo=repo1.scm_instance, repo_name=r1_name,
 
            cs=EmptyChangeset(alias='hg'), user=TEST_USER_ADMIN_LOGIN,
 
            author=TEST_USER_ADMIN_LOGIN,
 
            message='commit1',
 
            content='line1',
 
            f_path='file1'
 
        )
 

	
 
        cs0_prim = ScmModel().create_node(
 
            repo=repo2.scm_instance, repo_name=r2_name,
 
            cs=EmptyChangeset(alias='hg'), user=TEST_USER_ADMIN_LOGIN,
 
            author=TEST_USER_ADMIN_LOGIN,
 
            message='commit1',
 
            content='line1',
 
            f_path='file1'
 
        )
 

	
 
        cs1 = ScmModel().commit_change(
 
            repo=repo2.scm_instance, repo_name=r2_name,
 
            cs=cs0_prim, user=TEST_USER_ADMIN_LOGIN, author=TEST_USER_ADMIN_LOGIN,
 
            message='commit2',
 
            content='line1\nline2',
 
            f_path='file1'
 
        )
 

	
 
        rev1 = 'default'
 
        rev2 = 'default'
 
        response = self.app.get(url(controller='compare', action='index',
 
                                    repo_name=r2_name,
 
                                    org_ref_type="branch",
 
                                    org_ref=rev1,
 
                                    other_ref_type="branch",
 
                                    other_ref=rev2,
 
                                    repo=r1_name
 
                                    ))
 

	
 
        try:
 
            response.mustcontain('%s@%s -> %s@%s' % (r2_name, rev1, r1_name, rev2))
 

	
 
            response.mustcontain("""<div class="message">commit2</div>""")
 
            response.mustcontain("""<a href="/%s/changeset/%s">r1:%s</a>""" % (r2_name, cs1.raw_id, cs1.short_id))
 
            ## files
 
            response.mustcontain("""<a href="/%s/compare/branch@%s...branch@%s#C--826e8142e6ba">file1</a>""" % (r2_name, rev1, rev2))
 

	
 

	
 
        finally:
 
            RepoModel().delete(r1_id)
 
            RepoModel().delete(r2_id)
0 comments (0 inline, 0 general)