当前位置: 首页>>代码示例>>Python>>正文


Python RepositoryManager.get_repository方法代码示例

本文整理汇总了Python中trac.versioncontrol.api.RepositoryManager.get_repository方法的典型用法代码示例。如果您正苦于以下问题:Python RepositoryManager.get_repository方法的具体用法?Python RepositoryManager.get_repository怎么用?Python RepositoryManager.get_repository使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在trac.versioncontrol.api.RepositoryManager的用法示例。


在下文中一共展示了RepositoryManager.get_repository方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: pre_process_request

# 需要导入模块: from trac.versioncontrol.api import RepositoryManager [as 别名]
# 或者: from trac.versioncontrol.api.RepositoryManager import get_repository [as 别名]
    def pre_process_request(self, req, handler):
        """
        Pre-process the request by adding 'Zip Archive' link into alternative format links
        The link is constructed from first and latest revision number, taken from the default
        repository.

        :param Request req: Trac request
        :param object handler: existing handler
        :returns: Handler, modified or not
        """
        # Add link only in /browser or /browser/?rev= pages
        if (self.browser_regx.match(req.path_info)
            and 'BROWSER_VIEW' in req.perm and 'FILE_VIEW' in req.perm):
            # Get default repository and its type
            rm = RepositoryManager(self.env)
            repo = rm.get_repository('')
            repo_type = rm.repository_type

            # Construct the export urls for each format and based on revision info
            latest_rev = plaintext(str(req.args.get('rev', repo.get_youngest_rev())))

            # Use Trac's internal implementation
            if repo_type == 'svn':
                return handler

            # For other types, iterate supported formats
            for format, info in self.formats.items():
                add_link(req, 'alternate', req.href('export/archive', rev=latest_rev, format=format), _(info['desc']),
                    info['mime'], info['ext'])

        return handler
开发者ID:juhamust,项目名称:multiproject,代码行数:33,代码来源:archive.py

示例2: _format_link

# 需要导入模块: from trac.versioncontrol.api import RepositoryManager [as 别名]
# 或者: from trac.versioncontrol.api.RepositoryManager import get_repository [as 别名]
    def _format_link(self, formatter, ns, match, label, fullmatch=None):
        if ns == 'log1':
            groups = fullmatch.groupdict()
            it_log = groups.get('it_log')
            revs = groups.get('log_revs')
            path = groups.get('log_path') or '/'
            target = '%s%[email protected]%s' % (it_log, path, revs)
            # prepending it_log is needed, as the helper expects it there
            intertrac = formatter.shorthand_intertrac_helper(
                'log', target, label, fullmatch)
            if intertrac:
                return intertrac
            path, query, fragment = formatter.split_link(path)
        else:
            assert ns in ('log', 'log2')
            if ns == 'log':
                match, query, fragment = formatter.split_link(match)
            else:
                query = fragment = ''
                match = ''.join(reversed(match.split('/', 1)))
            path = match
            revs = ''
            if self.LOG_LINK_RE.match(match):
                indexes = [sep in match and match.index(sep) for sep in ':@']
                idx = min([i for i in indexes if i is not False])
                path, revs = match[:idx], match[idx+1:]

        rm = RepositoryManager(self.env)
        try:
            reponame, repos, path = rm.get_repository_by_path(path)
            if not reponame:
                reponame = rm.get_default_repository(formatter.context)
                if reponame is not None:
                    repos = rm.get_repository(reponame)

            if repos:
                if 'LOG_VIEW' in formatter.perm:
                    reponame = repos.reponame or None
                    path = path or '/'
                    revranges = RevRanges(repos, revs)
                    if revranges.has_ranges():
                        href = formatter.href.log(reponame, path,
                                                  revs=unicode(revranges))
                    else:
                        # try to resolve if single rev
                        repos.normalize_rev(revs)
                        href = formatter.href.log(reponame, path,
                                                  rev=revs or None)
                    if query and '?' in href:
                        query = '&' + query[1:]
                    return tag.a(label, class_='source',
                                 href=href + query + fragment)
                errmsg = _("No permission to view change log")
            elif reponame:
                errmsg = _("Repository '%(repo)s' not found", repo=reponame)
            else:
                errmsg = _("No default repository defined")
        except TracError, e:
            errmsg = to_unicode(e)
开发者ID:exocad,项目名称:exotrac,代码行数:61,代码来源:log.py

示例3: _render_repository_index

# 需要导入模块: from trac.versioncontrol.api import RepositoryManager [as 别名]
# 或者: from trac.versioncontrol.api.RepositoryManager import get_repository [as 别名]
    def _render_repository_index(self, context, all_repositories, order, desc):
        # Color scale for the age column
        timerange = custom_colorizer = None
        if self.color_scale:
            custom_colorizer = self.get_custom_colorizer()

        rm = RepositoryManager(self.env)
        repositories = []
        for reponame, repoinfo in all_repositories.iteritems():
            if not reponame or as_bool(repoinfo.get("hidden")):
                continue
            try:
                repos = rm.get_repository(reponame)
            except TracError as err:
                entry = (reponame, repoinfo, None, None, exception_to_unicode(err), None)
            else:
                if repos:
                    if not repos.is_viewable(context.perm):
                        continue
                    try:
                        youngest = repos.get_changeset(repos.youngest_rev)
                    except NoSuchChangeset:
                        youngest = None
                    if self.color_scale and youngest:
                        if not timerange:
                            timerange = TimeRange(youngest.date)
                        else:
                            timerange.insert(youngest.date)
                    raw_href = self._get_download_href(context.href, repos, None, None)
                    entry = (reponame, repoinfo, repos, youngest, None, raw_href)
                else:
                    entry = (reponame, repoinfo, None, None, u"\u2013", None)
            if entry[4] is not None:  # Check permission in case of error
                root = Resource("repository", reponame).child(self.realm, "/")
                if "BROWSER_VIEW" not in context.perm(root):
                    continue
            repositories.append(entry)

        # Ordering of repositories
        if order == "date":

            def repo_order((reponame, repoinfo, repos, youngest, err, href)):
                return (youngest.date if youngest else to_datetime(0), embedded_numbers(reponame.lower()))

        elif order == "author":

            def repo_order((reponame, repoinfo, repos, youngest, err, href)):
                return (youngest.author.lower() if youngest else "", embedded_numbers(reponame.lower()))

        else:

            def repo_order((reponame, repoinfo, repos, youngest, err, href)):
                return embedded_numbers(reponame.lower())

        repositories = sorted(repositories, key=repo_order, reverse=desc)

        return {"repositories": repositories, "timerange": timerange, "colorize_age": custom_colorizer}
开发者ID:pkdevbox,项目名称:trac,代码行数:59,代码来源:browser.py

示例4: check_permission

# 需要导入模块: from trac.versioncontrol.api import RepositoryManager [as 别名]
# 或者: from trac.versioncontrol.api.RepositoryManager import get_repository [as 别名]
    def check_permission(self, action, username, resource, perm):
        realm = resource.realm if resource else None
        if (realm, action) in self._handled_perms:
            authz, users = self._get_authz_info()
            if authz is None:
                return False

            if username == 'anonymous':
                usernames = ('$anonymous', '*')
            else:
                usernames = (username, '$authenticated', '*')
            if resource is None:
                return True if users & set(usernames) else None

            rm = RepositoryManager(self.env)
            try:
                repos = rm.get_repository(resource.parent.id)
            except TracError:
                return True # Allow error to be displayed in the repo index
            if repos is None:
                return True
            modules = [resource.parent.id or self.authz_module_name]
            if modules[0]:
                modules.append('')

            def check_path(path):
                path = '/' + join(repos.scope, path)
                if path != '/':
                    path += '/'

                # Allow access to parent directories of allowed resources
                if any(section.get(user) is True
                       for module in modules
                       for spath, section in authz.get(module, {}).iteritems()
                       if spath.startswith(path)
                       for user in usernames):
                    return True

                # Walk from resource up parent directories
                for spath in parent_iter(path):
                    for module in modules:
                        section = authz.get(module, {}).get(spath)
                        if section:
                            for user in usernames:
                                result = section.get(user)
                                if result is not None:
                                    return result

            if realm == 'source':
                return check_path(resource.id)

            elif realm == 'changeset':
                changes = list(repos.get_changeset(resource.id).get_changes())
                if not changes or any(check_path(change[0])
                                      for change in changes):
                    return True
开发者ID:pkdevbox,项目名称:trac,代码行数:58,代码来源:svn_authz.py

示例5: _format_link

# 需要导入模块: from trac.versioncontrol.api import RepositoryManager [as 别名]
# 或者: from trac.versioncontrol.api.RepositoryManager import get_repository [as 别名]
    def _format_link(self, formatter, ns, match, label, fullmatch=None):
        if ns == "log1":
            groups = fullmatch.groupdict()
            it_log = groups.get("it_log")
            revs = groups.get("log_revs")
            path = groups.get("log_path") or "/"
            target = "%s%[email protected]%s" % (it_log, path, revs)
            # prepending it_log is needed, as the helper expects it there
            intertrac = formatter.shorthand_intertrac_helper("log", target, label, fullmatch)
            if intertrac:
                return intertrac
            path, query, fragment = formatter.split_link(path)
        else:
            assert ns in ("log", "log2")
            if ns == "log":
                match, query, fragment = formatter.split_link(match)
            else:
                query = fragment = ""
                match = "".join(reversed(match.split("/", 1)))
            path = match
            revs = ""
            if self.LOG_LINK_RE.match(match):
                indexes = [sep in match and match.index(sep) for sep in ":@"]
                idx = min([i for i in indexes if i is not False])
                path, revs = match[:idx], match[idx + 1 :]

        rm = RepositoryManager(self.env)
        try:
            reponame, repos, path = rm.get_repository_by_path(path)
            if not reponame:
                reponame = rm.get_default_repository(formatter.context)
                if reponame is not None:
                    repos = rm.get_repository(reponame)

            if repos:
                if "LOG_VIEW" in formatter.perm:
                    reponame = repos.reponame or None
                    path = path or "/"
                    revranges = RevRanges(repos, revs)
                    if revranges.has_ranges():
                        href = formatter.href.log(reponame, path, revs=unicode(revranges))
                    else:
                        # try to resolve if single rev
                        repos.normalize_rev(revs)
                        href = formatter.href.log(reponame, path, rev=revs or None)
                    if query and "?" in href:
                        query = "&" + query[1:]
                    return tag.a(label, class_="source", href=href + query + fragment)
                errmsg = _("No permission to view change log")
            elif reponame:
                errmsg = _("Repository '%(repo)s' not found", repo=reponame)
            else:
                errmsg = _("No default repository defined")
        except TracError as e:
            errmsg = to_unicode(e)
        return tag.a(label, class_="missing source", title=errmsg)
开发者ID:pkdevbox,项目名称:trac,代码行数:58,代码来源:log.py

示例6: __init__

# 需要导入模块: from trac.versioncontrol.api import RepositoryManager [as 别名]
# 或者: from trac.versioncontrol.api.RepositoryManager import get_repository [as 别名]
 def __init__(self, env, context):
     self.env = env
     self.context = context
     rm = RepositoryManager(self.env)
     self.repos = rm.get_repository(context.resource.parent.id)
     self.path = context.resource.id
     self.rev = context.resource.version
     # maintain state
     self.prev_chgset = None
     self.chgset_data = {}
     add_script(context.req, 'common/js/blame.js')
     add_stylesheet(context.req, 'common/css/changeset.css')
     add_stylesheet(context.req, 'common/css/diff.css')
     self.reset()
开发者ID:zjj,项目名称:trac_hack,代码行数:16,代码来源:browser.py

示例7: get_timeline_events

# 需要导入模块: from trac.versioncontrol.api import RepositoryManager [as 别名]
# 或者: from trac.versioncontrol.api.RepositoryManager import get_repository [as 别名]
 def get_timeline_events(self, req, start, stop, filters):
     rm = RepositoryManager(self.env)
     events = super(GitHubBrowser, self).get_timeline_events(req, start, stop, filters)
     for event in events:
         if event[0] != 'changeset':
             yield event
             continue
         allow = True
         for changeset in event[3][0]:
             reponame = changeset[2][0]
             repos = rm.get_repository(reponame)
             key = 'branches' if is_default(reponame) else '%s.branches' % reponame
             branches = self.config.getlist('github', key, sep=' ')
             if branches:
                 allow = allow and allow_revision(changeset[0].rev, repos, branches)
         if allow:
             yield event
开发者ID:uruz,项目名称:trac-github,代码行数:19,代码来源:github.py

示例8: register_repository

# 需要导入模块: from trac.versioncontrol.api import RepositoryManager [as 别名]
# 或者: from trac.versioncontrol.api.RepositoryManager import get_repository [as 别名]
    def register_repository(self, repository, name=None):
        """Register a repository with trac"""

        project = repository.project
        tracname = name if name is not None else repository.name

        if repository.name in project.data.get('plugins', {}).get('trac', {}).get(repository.type, {}):
            logger.error("Repository %s:%s is already registered in project %s",
                        repository.type, repository.name, project.name)
            return False

        if repository.type not in self.typemap:
            logger.error("Repository type %s is not supported in Trac", repository.type)
            return False

        if not self.has_env(project):
            logger.warning("Tried to add repository %s:%s to Trac of project %s, but there is no environment",
                        repository.type, repository.name, project.name)
            return False

        try:
            env = Environment(self.get_env_path(project))

            DbRepositoryProvider(env).add_repository(tracname, repository.path, self.typemap[repository.type])

            # save mapping in project
            project.data.setdefault('plugins', {}).setdefault('trac', {}).setdefault(repository.type, {})[repository.name] = tracname
            project.save()

            # Synchronise repository
            rm = RepositoryManager(env)
            repos = rm.get_repository(tracname)
            repos.sync(lambda rev: logger.debug("Synced revision: %s", rev), clean=True)

            return True
        except Exception as e:
            logger.exception("Exception occured while addingrepository %s:%s to Trac of project %s",
                        repository.type, repository.name, project.name)
            return False
开发者ID:akuendig,项目名称:cydra,代码行数:41,代码来源:__init__.py

示例9: _render_repository_index

# 需要导入模块: from trac.versioncontrol.api import RepositoryManager [as 别名]
# 或者: from trac.versioncontrol.api.RepositoryManager import get_repository [as 别名]
    def _render_repository_index(self, context, all_repositories, order, desc):
        # Color scale for the age column
        timerange = custom_colorizer = None
        if self.color_scale:
            custom_colorizer = self.get_custom_colorizer()

        rm = RepositoryManager(self.env)
        repositories = []
        for reponame, repoinfo in all_repositories.iteritems():
            if not reponame or as_bool(repoinfo.get('hidden')):
                continue
            try:
                repos = rm.get_repository(reponame)
                if repos:
                    if not repos.can_view(context.perm):
                        continue
                    try:
                        youngest = repos.get_changeset(repos.youngest_rev)
                    except NoSuchChangeset:
                        youngest = None
                    if self.color_scale and youngest:
                        if not timerange:
                            timerange = TimeRange(youngest.date)
                        else:
                            timerange.insert(youngest.date)
                    entry = (reponame, repoinfo, repos, youngest, None)
                else:
                    entry = (reponame, repoinfo, None, None, u"\u2013")
            except TracError, err:
                entry = (reponame, repoinfo, None, None,
                         exception_to_unicode(err))
            if entry[-1] is not None:   # Check permission in case of error
                root = Resource('repository', reponame).child('source', '/')
                if 'BROWSER_VIEW' not in context.perm(root):
                    continue
            repositories.append(entry)
开发者ID:zjj,项目名称:trac_hack,代码行数:38,代码来源:browser.py

示例10: render_property_diff

# 需要导入模块: from trac.versioncontrol.api import RepositoryManager [as 别名]
# 或者: from trac.versioncontrol.api.RepositoryManager import get_repository [as 别名]
 def render_property_diff(self, name, old_context, old_props,
                          new_context, new_props, options):
     # Build 5 columns table showing modifications on merge sources
     # || source || added || removed || added (ni) || removed (ni) ||
     # || source || removed                                        ||
     rm = RepositoryManager(self.env)
     repos = rm.get_repository(old_context.resource.parent.id)
     def parse_sources(props):
         sources = {}
         for line in props[name].splitlines():
             path, revs = line.split(':', 1)
             spath = _path_within_scope(repos.scope, path)
             if spath is not None:
                 inheritable, non_inheritable = _partition_inheritable(revs)
                 sources[spath] = (set(Ranges(inheritable)),
                                   set(Ranges(non_inheritable)))
         return sources
     old_sources = parse_sources(old_props)
     new_sources = parse_sources(new_props)
     # Go through new sources, detect modified ones or added ones
     blocked = name.endswith('blocked')
     added_label = [_("merged: "), _("blocked: ")][blocked]
     removed_label = [_("reverse-merged: "), _("un-blocked: ")][blocked]
     added_ni_label = _("marked as non-inheritable: ")
     removed_ni_label = _("unmarked as non-inheritable: ")
     def revs_link(revs, context):
         if revs:
             revs = to_ranges(revs)
             return _get_revs_link(revs.replace(',', u',\u200b'),
                                   context, spath, revs)
     modified_sources = []
     for spath, (new_revs, new_revs_ni) in new_sources.iteritems():
         if spath in old_sources:
             (old_revs, old_revs_ni), status = old_sources.pop(spath), None
         else:
             old_revs = old_revs_ni = set()
             status = _(' (added)')
         added = new_revs - old_revs
         removed = old_revs - new_revs
         added_ni = new_revs_ni - old_revs_ni
         removed_ni = old_revs_ni - new_revs_ni
         try:
             all_revs = set(repos._get_node_revs(spath))
             # TODO: also pass first_rev here, for getting smaller a set
             #       (this is an optmization fix, result is already correct)
             added &= all_revs
             removed &= all_revs
             added_ni &= all_revs
             removed_ni &= all_revs
         except NoSuchNode:
             pass
         if added or removed:
             modified_sources.append((
                 spath, [_get_source_link(spath, new_context), status],
                 added and tag(added_label, revs_link(added, new_context)),
                 removed and tag(removed_label,
                                 revs_link(removed, old_context)),
                 added_ni and tag(added_ni_label, 
                                  revs_link(added_ni, new_context)),
                 removed_ni and tag(removed_ni_label,
                                    revs_link(removed_ni, old_context))
                 ))
     # Go through remaining old sources, those were deleted
     removed_sources = []
     for spath, old_revs in old_sources.iteritems():
         removed_sources.append((spath,
                                 _get_source_link(spath, old_context)))
     if modified_sources or removed_sources:
         modified_sources.sort()
         removed_sources.sort()
         changes = tag.table(tag.tbody(
             [tag.tr(tag.td(c) for c in cols[1:]) 
              for cols in modified_sources],
             [tag.tr(tag.td(src), tag.td(_('removed'), colspan=4))
              for spath, src in removed_sources]), class_='props')
     else:
         changes = tag.em(_(' (with no actual effect on merging)'))
     return tag.li(tag_('Property %(prop)s changed', prop=tag.strong(name)),
                   changes)
开发者ID:wiraqutra,项目名称:photrackjp,代码行数:81,代码来源:svn_prop.py

示例11: render_property_diff

# 需要导入模块: from trac.versioncontrol.api import RepositoryManager [as 别名]
# 或者: from trac.versioncontrol.api.RepositoryManager import get_repository [as 别名]
    def render_property_diff(self, name, old_context, old_props,
                             new_context, new_props, options):
        # Build 5 columns table showing modifications on merge sources
        # || source || added || removed || added (ni) || removed (ni) ||
        # || source || removed                                        ||
        rm = RepositoryManager(self.env)
        repos = rm.get_repository(old_context.resource.parent.id)
        def parse_sources(props):
            sources = {}
            for line in props[name].splitlines():
                path, revs = line.split(':', 1)
                spath = _path_within_scope(repos.scope, path)
                if spath is not None:
                    inheritable, non_inheritable = _partition_inheritable(revs)
                    sources[spath] = (set(Ranges(inheritable)),
                                      set(Ranges(non_inheritable)))
            return sources
        old_sources = parse_sources(old_props)
        new_sources = parse_sources(new_props)
        # Go through new sources, detect modified ones or added ones
        blocked = name.endswith('blocked')
        added_label = [_("merged: "), _("blocked: ")][blocked]
        removed_label = [_("reverse-merged: "), _("un-blocked: ")][blocked]
        added_ni_label = _("marked as non-inheritable: ")
        removed_ni_label = _("unmarked as non-inheritable: ")

        sources = []
        changed_revs = {}
        changed_nodes = []
        for spath, (new_revs, new_revs_ni) in new_sources.iteritems():
            new_spath = spath not in old_sources
            if new_spath:
                old_revs = old_revs_ni = set()
            else:
                old_revs, old_revs_ni = old_sources.pop(spath)
            added = new_revs - old_revs
            removed = old_revs - new_revs
            # unless new revisions differ from old revisions
            if not added and not removed:
                continue
            added_ni = new_revs_ni - old_revs_ni
            removed_ni = old_revs_ni - new_revs_ni
            revs = sorted(added | removed | added_ni | removed_ni)
            try:
                node = repos.get_node(spath, revs[-1])
                changed_nodes.append((node, revs[0]))
            except NoSuchNode:
                pass
            sources.append((spath, new_spath, added, removed, added_ni,
                            removed_ni))
        if changed_nodes:
            changed_revs = repos._get_changed_revs(changed_nodes)

        def revs_link(revs, context):
            if revs:
                revs = to_ranges(revs)
                return _get_revs_link(revs.replace(',', u',\u200b'),
                                      context, spath, revs)
        modified_sources = []
        for spath, new_spath, added, removed, added_ni, removed_ni in sources:
            if spath in changed_revs:
                revs = set(changed_revs[spath])
                added &= revs
                removed &= revs
                added_ni &= revs
                removed_ni &= revs
            if added or removed:
                if new_spath:
                    status = _(" (added)")
                else:
                    status = None
                modified_sources.append((
                    spath, [_get_source_link(spath, new_context), status],
                    added and tag(added_label, revs_link(added, new_context)),
                    removed and tag(removed_label,
                                    revs_link(removed, old_context)),
                    added_ni and tag(added_ni_label,
                                     revs_link(added_ni, new_context)),
                    removed_ni and tag(removed_ni_label,
                                       revs_link(removed_ni, old_context))
                    ))
        # Go through remaining old sources, those were deleted
        removed_sources = []
        for spath, old_revs in old_sources.iteritems():
            removed_sources.append((spath,
                                    _get_source_link(spath, old_context)))
        if modified_sources or removed_sources:
            modified_sources.sort()
            removed_sources.sort()
            changes = tag.table(tag.tbody(
                [tag.tr(tag.td(c) for c in cols[1:])
                 for cols in modified_sources],
                [tag.tr(tag.td(src), tag.td(_('removed'), colspan=4))
                 for spath, src in removed_sources]), class_='props')
        else:
            changes = tag.em(_(' (with no actual effect on merging)'))
        return tag.li(tag_('Property %(prop)s changed', prop=tag.strong(name)),
                      changes)
开发者ID:exocad,项目名称:exotrac,代码行数:100,代码来源:svn_prop.py

示例12: _read_source_from_repos

# 需要导入模块: from trac.versioncontrol.api import RepositoryManager [as 别名]
# 或者: from trac.versioncontrol.api.RepositoryManager import get_repository [as 别名]
 def _read_source_from_repos(self, formatter, src_path):
     repos_mgr = RepositoryManager(self.env)
     try: #0.12+
         repos_name, repos, source_obj = repos_mgr.get_repository_by_path(src_path)
     except AttributeError, e: #0.11
         repos = repos_mgr.get_repository(formatter.req.authname)
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:8,代码来源:macro.py

示例13: _get_source

# 需要导入模块: from trac.versioncontrol.api import RepositoryManager [as 别名]
# 或者: from trac.versioncontrol.api.RepositoryManager import get_repository [as 别名]
 def _get_source(self, formatter, source_obj, dest_format):
     repos_mgr = RepositoryManager(self.env)
     try:  # 0.12+
         repos_name, repos, source_obj = repos_mgr.get_repository_by_path(source_obj)
     except AttributeError, e:  # 0.11
         repos = repos_mgr.get_repository(formatter.req.authname)
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:8,代码来源:macros.py

示例14: process_request

# 需要导入模块: from trac.versioncontrol.api import RepositoryManager [as 别名]
# 或者: from trac.versioncontrol.api.RepositoryManager import get_repository [as 别名]
    def process_request(self, req):
        """
        Handle the export requests

        :raises: TracError in case of failure
        """
        req.perm.require('BROWSER_VIEW')
        req.perm.require('FILE_VIEW')

        # Get default repository and its type
        rm = RepositoryManager(self.env)
        repo = rm.get_repository('')
        repo_type = rm.repository_type
        svn_path = 'trunk'
        format = plaintext(req.args.get('format', 'zip'))

        # Get revision info. For svn it's in format: <revnum>/<path>
        revision = plaintext(str(req.args.get('rev', repo.get_youngest_rev())))
        if repo_type == 'svn':
            revision = repo.get_youngest_rev()
            svn_path = req.args.get('rev', svn_path)

        # Validate if given revision really exists
        try:
            revision = repo.normalize_rev(revision)
        except NoSuchChangeset:
            raise HTTPNotFound('No such changeset')

        # Validate format
        if format not in self.formats:
            raise TracError('Format is not supported')

        # Load project object based on current environment
        env_name = conf.resolveProjectName(self.env)
        repo_type = self.env.config.get('trac', 'repository_type')
        repo_dir = conf.getEnvironmentVcsPath(env_name)
        project = Project.get(env_name=env_name)

        if repo_type not in conf.supported_scm_systems:
            raise TracError('Non-supported VCS type')

        # Create temporary directory with appropriate subdirectory where to export repository
        tempfd = tempfile.NamedTemporaryFile(delete=False)

        # Dump the repository per type, into defined location
        try:
            if repo_type == 'git':
                # Use short revision format
                revision = revision[:6]
                prefix = '%s-%s' % (env_name, revision[:6])
                self._archive_git(repo_dir, revision, format, tempfd.name, prefix)

            elif repo_type == 'hg':
                # In case of both local:global revision format, use only global
                if ':' in revision:
                    revision = revision.split(':', 1)[1]
                prefix = '%s-%s' % (env_name, revision[:6])
                self._archive_hg(repo_dir, revision, format, tempfd.name, prefix)

            elif repo_type == 'svn':
                assert format == 'zip', 'Only zip format is supported for subversion'

                # Redirect to Trac's internal changeset functionality
                # Example: https://localhost/svnproject/changeset/4/trunk?old_path=%2F&format=zip
                changeset_href = Href('/%s/changeset' % env_name)
                return req.redirect(changeset_href(revision, svn_path, old_path='/', format='zip'))

        # Redirect raises RequestDone: re-raise it
        except RequestDone:
            raise

        except Exception, err:
            self.env.log.exception('Repository dump failed: %s' % err)
            raise TracError('Repository archive failed - please try again later')
开发者ID:juhamust,项目名称:multiproject,代码行数:76,代码来源:archive.py

示例15: process_request

# 需要导入模块: from trac.versioncontrol.api import RepositoryManager [as 别名]
# 或者: from trac.versioncontrol.api.RepositoryManager import get_repository [as 别名]
    def process_request(self, req):
        strategy = req.args.get('strategy')
        term = req.args.get('q')

        if strategy == 'linkresolvers':
            wiki = WikiSystem(self.env)
            completions = []
            for provider in wiki.syntax_providers:
                for name, resolver in provider.get_link_resolvers():
                    if name.startswith(term):
                        completions.append(name)
            self._send_json(req, completions)

        elif strategy == 'ticket':
            with self.env.db_query as db:
                rows = db("""
                    SELECT id, summary
                    FROM ticket
                    WHERE %s %s
                    ORDER BY changetime DESC
                    LIMIT 10
                    """ % (db.cast('id', 'text'), db.prefix_match()),
                    (db.prefix_match_value(term), ))
            completions = [{
                'id': row[0],
                'summary': row[1],
                } for row in rows
                if 'TICKET_VIEW' in req.perm(Resource('ticket', row[0]))]
            self._send_json(req, completions)

        elif strategy == 'wikipage':
            with self.env.db_query as db:
                rows = db("""
                    SELECT name
                    FROM wiki
                    WHERE name %s
                    GROUP BY name
                    ORDER BY name
                    LIMIT 10
                    """ % db.prefix_match(),
                    (db.prefix_match_value(term), ))
            completions = [row[0] for row in rows
                           if 'WIKI_VIEW' in req.perm(Resource('wiki', row[0]))]
            self._send_json(req, completions)

        elif strategy == 'macro':
            resource = Resource()
            context = web_context(req, resource)
            wiki = WikiSystem(self.env)
            macros = []
            for provider in wiki.macro_providers:
                names = list(provider.get_macros() or [])
                for name in names:
                    if name.startswith(term):
                        macros.append((name, provider))
            completions = []
            if len(macros) == 1:
                name, provider = macros[0]
                descr = provider.get_macro_description(name)
                if isinstance(descr, (tuple, list)):
                    descr = dgettext(descr[0], to_unicode(descr[1]))
                descr = format_to_html(self.env, context, descr)
                completions.append({
                    'name': name,
                    'description': descr,
                })
            else:
                for name, provider in macros:
                    descr = provider.get_macro_description(name)
                    if isinstance(descr, (tuple, list)):
                        descr = dgettext(descr[0], to_unicode(descr[1]))
                    descr = format_to_oneliner(self.env, context, descr, shorten=True)
                    completions.append({
                        'name': name,
                        'description': descr,
                    })
            self._send_json(req, completions)

        elif strategy == 'source':
            rm = RepositoryManager(self.env)
            completions = []
            if term.find('/') == -1:
                for reponame, repoinfo in rm.get_all_repositories().iteritems():
                    if 'BROWSER_VIEW' in req.perm(Resource('repository', reponame)):
                        if len(term) == 0 or reponame.lower().startswith(term.lower()):
                            completions.append(reponame+'/')
            else:
                reponame, path = term.split('/', 1)
                repos = rm.get_repository(reponame)
                if repos is not None:
                    if path.find('@') != -1:
                        path, search_rev = path.rsplit('@', 1)
                        node = repos.get_node(path, repos.youngest_rev)
                        if node.can_view(req.perm):
                            for r in node.get_history(10):
                                if str(r[1]).startswith(search_rev):
                                    completions.append('%s/%[email protected]%s' % (reponame, path, r[1]))
                    else:
                        if path.find('/') != -1:
                            dir, filename = path.rsplit('/', 1)
#.........这里部分代码省略.........
开发者ID:kzhamaji,项目名称:WikiAutoCompletePlugin,代码行数:103,代码来源:web_ui.py


注:本文中的trac.versioncontrol.api.RepositoryManager.get_repository方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。