Пример #1
0
 def getOrderValuesFor(self, row):
     """Return the values of the order_by expressions for the given row.
     """
     sort_values = []
     if not zope_isinstance(row, tuple):
         row = (row, )
     sort_expressions = self.getOrderBy()
     for expression in sort_expressions:
         expression = plain_expression(expression)
         if not zope_isinstance(expression, PropertyColumn):
             raise StormRangeFactoryError(
                 'StormRangeFactory only supports sorting by '
                 'PropertyColumn, not by %r.' % expression)
         class_instance_found = False
         for row_part in row:
             if zope_isinstance(row_part, expression.cls):
                 sort_values.append(expression.__get__(row_part))
                 class_instance_found = True
                 break
         if not class_instance_found:
             raise StormRangeFactoryError(
                 'Instances of %r are not contained in the result set, '
                 'but are required to retrieve the value of %s.%s.'
                 % (expression.cls, expression.cls.__name__,
                    expression.name))
     return sort_values
Пример #2
0
 def getOrderValuesFor(self, row):
     """Return the values of the order_by expressions for the given row.
     """
     sort_values = []
     if not zope_isinstance(row, tuple):
         row = (row, )
     sort_expressions = self.getOrderBy()
     for expression in sort_expressions:
         expression = plain_expression(expression)
         if not zope_isinstance(expression, PropertyColumn):
             raise StormRangeFactoryError(
                 'StormRangeFactory only supports sorting by '
                 'PropertyColumn, not by %r.' % expression)
         class_instance_found = False
         for row_part in row:
             if zope_isinstance(row_part, expression.cls):
                 sort_values.append(expression.__get__(row_part))
                 class_instance_found = True
                 break
         if not class_instance_found:
             raise StormRangeFactoryError(
                 'Instances of %r are not contained in the result set, '
                 'but are required to retrieve the value of %s.%s.' %
                 (expression.cls, expression.cls.__name__, expression.name))
     return sort_values
Пример #3
0
    def add(self, persons, reason, header):
        """See `INotificationRecipientSet`."""
        from zope.security.proxy import removeSecurityProxy
        from lp.registry.model.person import get_recipients
        if (IPerson.providedBy(persons)
                or zope_isinstance(persons, StubPerson)):
            persons = [persons]

        for person in persons:
            assert (IPerson.providedBy(person)
                    or zope_isinstance(person, StubPerson)), (
                        'You can only add() an IPerson or a StubPerson: %r' %
                        person)
            # If the person already has a rationale, keep the first one.
            if person in self._personToRationale:
                continue
            self._personToRationale[person] = reason, header
            if IPerson.providedBy(person):
                recipients = get_recipients(person)
            else:
                recipients = [person]
            for receiving_person in recipients:
                # Bypass zope's security because IEmailAddress.email is not
                # public.
                preferred_email = removeSecurityProxy(
                    receiving_person).preferredemail
                email = str(preferred_email.email)
                self._receiving_people.add((email, receiving_person))
                old_person = self._emailToPerson.get(email)
                # Only associate this email to the person, if there was
                # no association or if the previous one was to a team and
                # the newer one is to a person.
                if (old_person is None
                        or (old_person.is_team and not person.is_team)):
                    self._emailToPerson[email] = person
Пример #4
0
def summarise_tal_links(links):
    """List the links and their attributes in the dict or list.

    :param links: A dictionary or list of menu links returned by
        `lp.app.browser.tales.MenuAPI`.
    """
    is_dict = zope_isinstance(links, dict)
    if is_dict:
        keys = sorted(links)
    else:
        keys = links
    for key in keys:
        if is_dict:
            link = links[key]
        else:
            link = key
        if ILink.providedBy(link):
            print 'link %s' % link.name
            attributes = ('url', 'enabled', 'menu', 'selected', 'linked')
            for attrname in attributes:
                if not safe_hasattr(link, attrname):
                    continue
                print '    %s:' % attrname, getattr(link, attrname)
        else:
            print 'attribute %s: %s' % (key, link)
Пример #5
0
    def findAndStartJob(cls, vitals, builder, slave):
        """Find a job to run and send it to the buildd slave.

        :return: A Deferred whose value is the `IBuildQueue` instance
            found or None if no job was found.
        """
        logger = cls._getSlaveScannerLogger()
        # XXX This method should be removed in favour of two separately
        # called methods that find and dispatch the job.  It will
        # require a lot of test fixing.
        candidate = builder.acquireBuildCandidate()
        if candidate is None:
            logger.debug("No build candidates available for builder.")
            defer.returnValue(None)

        new_behavior = cls.getBuildBehavior(candidate, builder, slave)
        needed_bfjb = type(removeSecurityProxy(
            IBuildFarmJobBehavior(candidate.specific_job)))
        if not zope_isinstance(new_behavior, needed_bfjb):
            raise AssertionError(
                "Inappropriate IBuildFarmJobBehavior: %r is not a %r" %
                (new_behavior, needed_bfjb))
        yield cls._startBuild(
            candidate, vitals, builder, slave, new_behavior, logger)
        defer.returnValue(candidate)
Пример #6
0
    def findAndStartJob(cls, vitals, builder, slave):
        """Find a job to run and send it to the buildd slave.

        :return: A Deferred whose value is the `IBuildQueue` instance
            found or None if no job was found.
        """
        logger = cls._getSlaveScannerLogger()
        # XXX This method should be removed in favour of two separately
        # called methods that find and dispatch the job.  It will
        # require a lot of test fixing.
        candidate = builder.acquireBuildCandidate()
        if candidate is None:
            logger.debug("No build candidates available for builder.")
            defer.returnValue(None)

        new_behavior = cls.getBuildBehavior(candidate, builder, slave)
        needed_bfjb = type(
            removeSecurityProxy(IBuildFarmJobBehavior(candidate.specific_job)))
        if not zope_isinstance(new_behavior, needed_bfjb):
            raise AssertionError(
                "Inappropriate IBuildFarmJobBehavior: %r is not a %r" %
                (new_behavior, needed_bfjb))
        yield cls._startBuild(candidate, vitals, builder, slave, new_behavior,
                              logger)
        defer.returnValue(candidate)
Пример #7
0
 def setRenderedValue(self, value):
     """See `IWidget`."""
     self.setUpSubWidgets()
     if not zope_isinstance(value, dict):
         value = {}
     self.core_widget.setRenderedValue(value.get("core"))
     self.snapcraft_widget.setRenderedValue(value.get("snapcraft"))
Пример #8
0
 def constraint(self, value):
     """See `IField`."""
     if zope_isinstance(value, DBItem) and value.enum == GitGranteeType:
         return value != GitGranteeType.PERSON
     else:
         return value in getVocabularyRegistry().get(
             None, "ValidPersonOrTeam")
Пример #9
0
 def areBranchesMergeable(self, other_target):
     """See `IBranchTarget`."""
     # Branches are mergable into a PackageTarget if the source package
     # name is the same, or the branch is associated with the linked
     # product.
     if zope_isinstance(other_target, ProductBranchTarget):
         return self.product == other_target.context
     elif zope_isinstance(other_target, PackageBranchTarget):
         # If the sourcepackage has a related product, and that product is
         # the same as ours, then the branches are mergeable.
         product_series = other_target.context.productseries
         if product_series is None:
             return False
         else:
             return self.product == product_series.product
     else:
         return False
Пример #10
0
 def _getFromAddress(self, email, recipient):
     """See `BaseMailer`."""
     if (zope_isinstance(recipient, AnnouncementStubPerson)
             and self.announce_from_address is not None):
         return self.announce_from_address
     else:
         return super(PackageUploadMailer,
                      self)._getFromAddress(email, recipient)
Пример #11
0
 def __contains__(self, person_or_email):
     """See `INotificationRecipientSet`."""
     if zope_isinstance(person_or_email, (str, unicode)):
         return person_or_email in self._emailToPerson
     elif IPerson.providedBy(person_or_email):
         return person_or_email in self._personToRationale
     else:
         return False
Пример #12
0
 def makeDecoratedStormResultSet(self):
     bug = self.factory.makeBug()
     with person_logged_in(bug.owner):
         for count in range(5):
             self.factory.makeBugAttachment(bug=bug, owner=bug.owner)
     result = bug.attachments
     self.assertTrue(zope_isinstance(result, DecoratedResultSet))
     return result
Пример #13
0
 def areBranchesMergeable(self, other_target):
     """See `IBranchTarget`."""
     # Branches are mergable into a PackageTarget if the source package
     # name is the same, or the branch is associated with the linked
     # product.
     if zope_isinstance(other_target, ProductBranchTarget):
         return self.product == other_target.context
     elif zope_isinstance(other_target, PackageBranchTarget):
         # If the sourcepackage has a related product, and that product is
         # the same as ours, then the branches are mergeable.
         product_series = other_target.context.productseries
         if product_series is None:
             return False
         else:
             return self.product == product_series.product
     else:
         return False
 def __contains__(self, person_or_email):
     """See `INotificationRecipientSet`."""
     if zope_isinstance(person_or_email, (str, unicode)):
         return person_or_email in self._emailToPerson
     elif IPerson.providedBy(person_or_email):
         return person_or_email in self._personToRationale
     else:
         return False
Пример #15
0
 def _get_shadowed_list(self, result):
     if zope_isinstance(result, DecoratedResultSet):
         items = list(result.copy().config(return_both=True))
         if items:
             shadow_result, real_result = map(list, zip(*items))
         else:
             shadow_result = real_result = []
     else:
         shadow_result = real_result = list(result)
     return ShadowedList(real_result, shadow_result)
Пример #16
0
 def _get_shadowed_list(self, result):
     if zope_isinstance(result, DecoratedResultSet):
         items = list(result.copy().config(return_both=True))
         if items:
             shadow_result, real_result = map(list, zip(*items))
         else:
             shadow_result = real_result = []
     else:
         shadow_result = real_result = list(result)
     return ShadowedList(real_result, shadow_result)
Пример #17
0
 def getComponentOverride(cls, component=None, return_component=False):
     # component can be a Component object or a component name.
     if zope_isinstance(component, Component):
         component = component.name
     override_component_name = cls.DEBIAN_COMPONENT_OVERRIDE_MAP.get(
         component, cls.DEFAULT_OVERRIDE_COMPONENT)
     if return_component:
         return getUtility(IComponentSet)[override_component_name]
     else:
         return override_component_name
Пример #18
0
 def _getFooter(self, email, recipient, params):
     """See `BaseMailer`."""
     if zope_isinstance(recipient, AnnouncementStubPerson):
         return None
     else:
         footer_lines = []
         if self.archive.is_ppa:
             footer_lines.append("%(ARCHIVE_URL)s\n")
         footer_lines.append("%(reason)s\n")
         return "".join(footer_lines) % params
Пример #19
0
def value_string(item):
    """Return a unicode string representing value.

    This text is special cased for enumerated types.
    """
    if item is None:
        return '(not set)'
    elif zope_isinstance(item, BaseItem):
        return item.title
    else:
        return unicode(item)
Пример #20
0
def value_string(item):
    """Return a unicode string representing value.

    This text is special cased for enumerated types.
    """
    if item is None:
        return '(not set)'
    elif zope_isinstance(item, BaseItem):
        return item.title
    else:
        return unicode(item)
 def _recipe_names(self):
     """A generator of recipe names."""
     # +junk-daily doesn't make a very good recipe name, so use the
     # branch name in that case.
     if zope_isinstance(self.context.target, PersonBranchTarget):
         branch_target_name = self.context.name
     else:
         branch_target_name = self.context.target.name.split('/')[-1]
     yield "%s-daily" % branch_target_name
     counter = itertools.count(1)
     while True:
         yield "%s-daily-%s" % (branch_target_name, counter.next())
Пример #22
0
 def _recipe_names(self):
     """A generator of recipe names."""
     # +junk-daily doesn't make a very good recipe name, so use the
     # branch name in that case.
     if zope_isinstance(self.context.target, PersonBranchTarget):
         branch_target_name = self.context.name
     else:
         branch_target_name = self.context.target.name.split('/')[-1]
     yield "%s-daily" % branch_target_name
     counter = itertools.count(1)
     while True:
         yield "%s-daily-%s" % (branch_target_name, counter.next())
    def config(self, *args, **kwargs):
        """See `IResultSet`.

        :return: The decorated result set.after updating the config.
        """
        return_both = kwargs.pop('return_both', None)
        if return_both is not None:
            self.return_both = return_both
            if zope_isinstance(self.result_set, DecoratedResultSet):
                self.result_set.config(return_both=return_both)

        self.result_set.config(*args, **kwargs)
        return self
    def config(self, *args, **kwargs):
        """See `IResultSet`.

        :return: The decorated result set.after updating the config.
        """
        return_both = kwargs.pop('return_both', None)
        if return_both is not None:
            self.return_both = return_both
            if zope_isinstance(self.result_set, DecoratedResultSet):
                self.result_set.config(return_both=return_both)

        self.result_set.config(*args, **kwargs)
        return self
Пример #25
0
def getSpecificJobs(jobs):
    """Return the specific build jobs associated with each of the jobs
        in the provided job list.

    If the job is already a specific job, it will be returned unchanged.
    """
    builds = []
    key = attrgetter('job_type.name')
    nonspecific_jobs = sorted(
        (job for job in jobs if zope_isinstance(job, BuildFarmJob)), key=key)
    job_builds = {}
    for job_type_name, grouped_jobs in groupby(nonspecific_jobs, key=key):
        # Fetch the jobs in batches grouped by their job type.
        source = getUtility(ISpecificBuildFarmJobSource, job_type_name)
        builds = [
            build for build in source.getByBuildFarmJobs(list(grouped_jobs))
            if build is not None
        ]
        for build in builds:
            try:
                job_builds[build.build_farm_job.id] = build
            except Unauthorized:
                # If the build farm job is private, we will get an
                # Unauthorized exception; we only use
                # removeSecurityProxy to get the id of build_farm_job
                # but the corresponding build returned in the list
                # will be 'None'.
                naked_build = removeSecurityProxy(build)
                job_builds[naked_build.build_farm_job.id] = None
    # Return the corresponding builds.
    try:
        return [
            job_builds[job.id] if zope_isinstance(job, BuildFarmJob) else job
            for job in jobs
        ]
    except KeyError:
        raise InconsistentBuildFarmJobError(
            "Could not find all the related specific jobs.")
Пример #26
0
    def _anyfy(cls, value):
        """If value is a sequence, wrap its items with the `any` combinator.

        Otherwise, return value as is, or None if it's a zero-length sequence.
        """
        if zope_isinstance(value, (list, tuple)):
            if len(value) > 1:
                return any(*value)
            elif len(value) == 1:
                return value[0]
            else:
                return None
        else:
            return value
Пример #27
0
 def areRepositoriesMergeable(self, this, other):
     """See `IGitNamespacePolicy`."""
     # Repositories are mergeable into a package repository if the
     # package is the same.
     # XXX cjwatson 2015-04-18: Allow merging from a project repository
     # if any (active?) series links this package to that project.
     if this.namespace != self:
         raise AssertionError(
             "Namespace of %s is not %s." % (this.unique_name, self.name))
     other_namespace = other.namespace
     if zope_isinstance(other_namespace, PackageGitNamespace):
         return self.target == other_namespace.target
     else:
         return False
Пример #28
0
    def _anyfy(cls, value):
        """If value is a sequence, wrap its items with the `any` combinator.

        Otherwise, return value as is, or None if it's a zero-length sequence.
        """
        if zope_isinstance(value, (list, tuple)):
            if len(value) > 1:
                return any(*value)
            elif len(value) == 1:
                return value[0]
            else:
                return None
        else:
            return value
Пример #29
0
def getSpecificJobs(jobs):
    """Return the specific build jobs associated with each of the jobs
        in the provided job list.

    If the job is already a specific job, it will be returned unchanged.
    """
    builds = []
    key = attrgetter('job_type.name')
    nonspecific_jobs = sorted(
        (job for job in jobs if zope_isinstance(job, BuildFarmJob)), key=key)
    job_builds = {}
    for job_type_name, grouped_jobs in groupby(nonspecific_jobs, key=key):
        # Fetch the jobs in batches grouped by their job type.
        source = getUtility(
            ISpecificBuildFarmJobSource, job_type_name)
        builds = [build for build
            in source.getByBuildFarmJobs(list(grouped_jobs))
            if build is not None]
        for build in builds:
            try:
                job_builds[build.build_farm_job.id] = build
            except Unauthorized:
                # If the build farm job is private, we will get an
                # Unauthorized exception; we only use
                # removeSecurityProxy to get the id of build_farm_job
                # but the corresponding build returned in the list
                # will be 'None'.
                naked_build = removeSecurityProxy(build)
                job_builds[naked_build.build_farm_job.id] = None
    # Return the corresponding builds.
    try:
        return [
            job_builds[job.id]
            if zope_isinstance(job, BuildFarmJob) else job for job in jobs]
    except KeyError:
        raise InconsistentBuildFarmJobError(
            "Could not find all the related specific jobs.")
Пример #30
0
    def checkAuthenticated(self,
                           person,
                           archive,
                           permission,
                           item,
                           distroseries=None):
        """See `IArchivePermissionSet`."""
        clauses = [
            """
            ArchivePermission.archive = %s AND
            ArchivePermission.permission = %s AND
            ArchivePermission.person = TeamParticipation.team AND
            TeamParticipation.person = %s
            """ % sqlvalues(archive, permission, person)
        ]

        prejoins = []

        if IComponent.providedBy(item):
            clauses.append("ArchivePermission.component = %s" %
                           sqlvalues(item))
            prejoins.append("component")
        elif ISourcePackageName.providedBy(item):
            clauses.append("ArchivePermission.sourcepackagename = %s" %
                           sqlvalues(item))
            prejoins.append("sourcepackagename")
        elif IPackageset.providedBy(item):
            clauses.append("ArchivePermission.packageset = %s" %
                           sqlvalues(item.id))
            prejoins.append("packageset")
        elif (zope_isinstance(item, DBItem)
              and item.enum.name == "PackagePublishingPocket"):
            clauses.append("ArchivePermission.pocket = %s" % sqlvalues(item))
            if distroseries is not None:
                clauses.append("(ArchivePermission.distroseries IS NULL OR "
                               "ArchivePermission.distroseries = %s)" %
                               sqlvalues(distroseries))
                prejoins.append("distroseries")
        else:
            raise AssertionError(
                "'item' %r is not an IComponent, IPackageset, "
                "ISourcePackageName or PackagePublishingPocket" % item)

        query = " AND ".join(clauses)
        auth = ArchivePermission.select(query,
                                        clauseTables=["TeamParticipation"],
                                        prejoins=prejoins)

        return auth
    def _extract_plain_and_result(self, results):
        """Extract the plain and normal results from a sub-result.

        This gets slightly complicated when there are nested
        DecoratedResultSets, as we have to propogate the plain result
        all the way up.
        """
        if not results:
            return [], []
        elif (zope_isinstance(self.result_set, DecoratedResultSet)
              and self.return_both):
            assert (removeSecurityProxy(
                self.result_set).return_both == self.return_both)
            return zip(*results)
        else:
            return results, results
Пример #32
0
 def parse_set(self, value, from_db):
     if from_db:
         for enum in self._enum:
             try:
                 return enum.items[value]
             except KeyError:
                 pass
         raise KeyError('%r not in present in any of %r' % (
             value, self._enum))
     else:
         if not zope_isinstance(value, DBItem):
             raise TypeError("Not a DBItem: %r" % (value,))
         if value.enum not in self._enum:
             raise TypeError("DBItem from unknown enum, %r not in %r" % (
                     value.enum.name, self._enum))
         return value
Пример #33
0
 def getReason(self, person_or_email):
     """See `INotificationRecipientSet`."""
     if zope_isinstance(person_or_email, basestring):
         try:
             person = self._emailToPerson[person_or_email]
         except KeyError:
             raise UnknownRecipientError(person_or_email)
     elif IPerson.providedBy(person_or_email):
         person = person_or_email
     else:
         raise AssertionError('Not an IPerson or email address: %r' %
                              person_or_email)
     try:
         return self._personToRationale[person]
     except KeyError:
         raise UnknownRecipientError(person)
 def getReason(self, person_or_email):
     """See `INotificationRecipientSet`."""
     if zope_isinstance(person_or_email, basestring):
         try:
             person = self._emailToPerson[person_or_email]
         except KeyError:
             raise UnknownRecipientError(person_or_email)
     elif IPerson.providedBy(person_or_email):
         person = person_or_email
     else:
         raise AssertionError(
             'Not an IPerson or email address: %r' % person_or_email)
     try:
         return self._personToRationale[person]
     except KeyError:
         raise UnknownRecipientError(person)
Пример #35
0
def get_bug_changes(bug_delta):
    """Generate `IBugChange` objects describing an `IBugDelta`."""
    # The order of the field names in this list is important; this is
    # the order in which changes will appear both in the bug activity
    # log and in notification emails.
    bug_change_field_names = [
        'duplicateof', 'title', 'description', 'information_type', 'tags',
        'attachment'
    ]
    for field_name in bug_change_field_names:
        field_delta = getattr(bug_delta, field_name)
        if field_delta is not None:
            bug_change_class = get_bug_change_class(bug_delta.bug, field_name)
            yield bug_change_class(when=None,
                                   person=bug_delta.user,
                                   what_changed=field_name,
                                   old_value=field_delta['old'],
                                   new_value=field_delta['new'])

    if bug_delta.bugtask_deltas is not None:
        bugtask_deltas = bug_delta.bugtask_deltas
        # Use zope_isinstance, to ensure that this Just Works with
        # security-proxied objects.
        if not zope_isinstance(bugtask_deltas, (list, tuple)):
            bugtask_deltas = [bugtask_deltas]

        # The order here is important; see bug_change_field_names.
        bugtask_change_field_names = [
            'target',
            'importance',
            'status',
            'milestone',
            'bugwatch',
            'assignee',
        ]
        for bugtask_delta in bugtask_deltas:
            for field_name in bugtask_change_field_names:
                field_delta = getattr(bugtask_delta, field_name)
                if field_delta is not None:
                    bug_change_class = get_bug_change_class(
                        bugtask_delta.bugtask, field_name)
                    yield bug_change_class(bug_task=bugtask_delta.bugtask,
                                           when=None,
                                           person=bug_delta.user,
                                           what_changed=field_name,
                                           old_value=field_delta['old'],
                                           new_value=field_delta['new'])
    def _extract_plain_and_result(self, results):
        """Extract the plain and normal results from a sub-result.

        This gets slightly complicated when there are nested
        DecoratedResultSets, as we have to propogate the plain result
        all the way up.
        """
        if not results:
            return [], []
        elif (zope_isinstance(self.result_set, DecoratedResultSet)
              and self.return_both):
            assert (
                removeSecurityProxy(self.result_set).return_both
                    == self.return_both)
            return zip(*results)
        else:
            return results, results
Пример #37
0
def get_current_view(request=None):
    """Return the current view or None.

    :param request: A `IHTTPApplicationRequest`. If request is None, the
        current browser request is used.
    :return: The view from requests that provide IHTTPApplicationRequest.
    """
    request = request or get_current_browser_request()
    if request is None:
        return
    # The view is not in the list of traversed_objects, though it is listed
    # among the traversed_names. We need to get it from a private attribute.
    view = request._last_obj_traversed
    # Note: The last traversed object may be a view's instance method.
    bare = removeSecurityProxy(view)
    if zope_isinstance(view, types.MethodType):
        return bare.im_self
    return bare
Пример #38
0
def get_current_view(request=None):
    """Return the current view or None.

    :param request: A `IHTTPApplicationRequest`. If request is None, the
        current browser request is used.
    :return: The view from requests that provide IHTTPApplicationRequest.
    """
    request = request or get_current_browser_request()
    if request is None:
        return
    # The view is not in the list of traversed_objects, though it is listed
    # among the traversed_names. We need to get it from a private attribute.
    view = request._last_obj_traversed
    # Note: The last traversed object may be a view's instance method.
    bare = removeSecurityProxy(view)
    if zope_isinstance(view, types.MethodType):
        return bare.im_self
    return bare
Пример #39
0
    def checkAuthenticated(self, person, archive, permission, item,
                           distroseries=None):
        """See `IArchivePermissionSet`."""
        clauses = ["""
            ArchivePermission.archive = %s AND
            ArchivePermission.permission = %s AND
            ArchivePermission.person = TeamParticipation.team AND
            TeamParticipation.person = %s
            """ % sqlvalues(archive, permission, person)]

        prejoins = []

        if IComponent.providedBy(item):
            clauses.append(
                "ArchivePermission.component = %s" % sqlvalues(item))
            prejoins.append("component")
        elif ISourcePackageName.providedBy(item):
            clauses.append(
                "ArchivePermission.sourcepackagename = %s" % sqlvalues(item))
            prejoins.append("sourcepackagename")
        elif IPackageset.providedBy(item):
            clauses.append(
                "ArchivePermission.packageset = %s" % sqlvalues(item.id))
            prejoins.append("packageset")
        elif (zope_isinstance(item, DBItem) and
              item.enum.name == "PackagePublishingPocket"):
            clauses.append("ArchivePermission.pocket = %s" % sqlvalues(item))
            if distroseries is not None:
                clauses.append(
                    "(ArchivePermission.distroseries IS NULL OR "
                     "ArchivePermission.distroseries = %s)" %
                    sqlvalues(distroseries))
                prejoins.append("distroseries")
        else:
            raise AssertionError(
                "'item' %r is not an IComponent, IPackageset, "
                "ISourcePackageName or PackagePublishingPocket" % item)

        query = " AND ".join(clauses)
        auth = ArchivePermission.select(
            query, clauseTables=["TeamParticipation"],
            prejoins=prejoins)

        return auth
Пример #40
0
def get_linked_to_branch(provided):
    """Get the `ICanHasLinkedBranch` for 'provided', whatever that is.

    :raise CannotHaveLinkedBranch: If 'provided' can never have a linked
        branch.
    :raise NoLinkedBranch: If 'provided' could have a linked branch, but
        doesn't.
    :return: The `ICanHasLinkedBranch` object.
    """
    has_linked_branch = ICanHasLinkedBranch(provided, None)
    if has_linked_branch is None:
        if zope_isinstance(provided, tuple):
            # Distroseries are returned as tuples containing distroseries and
            # pocket.
            provided = provided[0]
        raise CannotHaveLinkedBranch(provided)
    if has_linked_branch.branch is None:
        raise NoLinkedBranch(provided)
    return has_linked_branch
Пример #41
0
def get_linked_to_branch(provided):
    """Get the `ICanHasLinkedBranch` for 'provided', whatever that is.

    :raise CannotHaveLinkedBranch: If 'provided' can never have a linked
        branch.
    :raise NoLinkedBranch: If 'provided' could have a linked branch, but
        doesn't.
    :return: The `ICanHasLinkedBranch` object.
    """
    has_linked_branch = ICanHasLinkedBranch(provided, None)
    if has_linked_branch is None:
        if zope_isinstance(provided, tuple):
            # Distroseries are returned as tuples containing distroseries and
            # pocket.
            provided = provided[0]
        raise CannotHaveLinkedBranch(provided)
    if has_linked_branch.branch is None:
        raise NoLinkedBranch(provided)
    return has_linked_branch
Пример #42
0
    def __init__(self, resultset, error_cb=None):
        """Create a new StormRangeFactory instance.

        :param resultset: A Storm ResultSet instance or a DecoratedResultSet
            instance.
        :param error_cb: A function which takes one string as a parameter.
            It is called when the parameter endpoint_memo of getSlice()
            does not match the order settings of a resultset.
        """
        self.resultset = resultset
        if zope_isinstance(resultset, DecoratedResultSet):
            self.plain_resultset = resultset.get_plain_result_set()
        else:
            self.plain_resultset = resultset
        self.error_cb = error_cb
        if not self.empty_resultset:
            self.forward_sort_order = self.getOrderBy()
            if self.forward_sort_order is Undef:
                raise StormRangeFactoryError(
                    'StormRangeFactory requires a sorted result set.')
            self.backward_sort_order = self.reverseSortOrder()
Пример #43
0
    def __init__(self, resultset, error_cb=None):
        """Create a new StormRangeFactory instance.

        :param resultset: A Storm ResultSet instance or a DecoratedResultSet
            instance.
        :param error_cb: A function which takes one string as a parameter.
            It is called when the parameter endpoint_memo of getSlice()
            does not match the order settings of a resultset.
        """
        self.resultset = resultset
        if zope_isinstance(resultset, DecoratedResultSet):
            self.plain_resultset = resultset.get_plain_result_set()
        else:
            self.plain_resultset = resultset
        self.error_cb = error_cb
        if not self.empty_resultset:
            self.forward_sort_order = self.getOrderBy()
            if self.forward_sort_order is Undef:
                raise StormRangeFactoryError(
                    'StormRangeFactory requires a sorted result set.')
            self.backward_sort_order = self.reverseSortOrder()
Пример #44
0
def get_bug_changes(bug_delta):
    """Generate `IBugChange` objects describing an `IBugDelta`."""
    # The order of the field names in this list is important; this is
    # the order in which changes will appear both in the bug activity
    # log and in notification emails.
    bug_change_field_names = ['duplicateof', 'title', 'description',
        'information_type', 'tags', 'attachment']
    for field_name in bug_change_field_names:
        field_delta = getattr(bug_delta, field_name)
        if field_delta is not None:
            bug_change_class = get_bug_change_class(bug_delta.bug, field_name)
            yield bug_change_class(
                when=None, person=bug_delta.user, what_changed=field_name,
                old_value=field_delta['old'], new_value=field_delta['new'])

    if bug_delta.bugtask_deltas is not None:
        bugtask_deltas = bug_delta.bugtask_deltas
        # Use zope_isinstance, to ensure that this Just Works with
        # security-proxied objects.
        if not zope_isinstance(bugtask_deltas, (list, tuple)):
            bugtask_deltas = [bugtask_deltas]

        # The order here is important; see bug_change_field_names.
        bugtask_change_field_names = [
            'target', 'importance', 'status', 'milestone', 'bugwatch',
            'assignee',
            ]
        for bugtask_delta in bugtask_deltas:
            for field_name in bugtask_change_field_names:
                field_delta = getattr(bugtask_delta, field_name)
                if field_delta is not None:
                    bug_change_class = get_bug_change_class(
                        bugtask_delta.bugtask, field_name)
                    yield bug_change_class(
                        bug_task=bugtask_delta.bugtask,
                        when=None, person=bug_delta.user,
                        what_changed=field_name,
                        old_value=field_delta['old'],
                        new_value=field_delta['new'])
Пример #45
0
    def _getHeaders(self, email, recipient):
        """See `BaseMailer`."""
        headers = super(PackageUploadMailer,
                        self)._getHeaders(email, recipient)
        headers['X-Katie'] = 'Launchpad actually'
        headers['X-Launchpad-Archive'] = self.archive.reference

        # The deprecated PPA reference header is included for Ubuntu PPAs to
        # avoid breaking existing consumers.
        if self.archive.is_ppa and self.archive.distribution.name == u'ubuntu':
            headers['X-Launchpad-PPA'] = get_ppa_reference(self.archive)

        # Include a 'X-Launchpad-Component' header with the component and
        # the section of the source package uploaded in order to facilitate
        # filtering on the part of the email recipients.
        if self.spr:
            headers['X-Launchpad-Component'] = 'component=%s, section=%s' % (
                self.spr.component.name, self.spr.section.name)

        # All emails from here have a Bcc to the default recipient.
        bcc_text = format_address(config.uploader.default_recipient_name,
                                  config.uploader.default_recipient_address)
        if zope_isinstance(recipient, AnnouncementStubPerson):
            name = None
            if self.spr:
                name = self.spr.name
            elif self.bprs:
                name = self.bprs[0].build.source_package_release.name
            if name:
                distribution = self.distroseries.distribution
                email_base = distribution.package_derivatives_email
                if email_base:
                    bcc_text += ", " + email_base.format(package_name=name)
        headers['Bcc'] = bcc_text

        return headers
Пример #46
0
 def empty_resultset(self):
     return zope_isinstance(self.plain_resultset, EmptyResultSet)
 def get_plain_result_set(self):
     """Return the plain Storm result set."""
     if zope_isinstance(self.result_set, DecoratedResultSet):
         return self.result_set.get_plain_result_set()
     else:
         return self.result_set
Пример #48
0
    def fromSearchForm(cls, user,
                       order_by=('-importance', ), search_text=None,
                       status=list(UNRESOLVED_BUGTASK_STATUSES),
                       importance=None,
                       assignee=None, bug_reporter=None, bug_supervisor=None,
                       bug_commenter=None, bug_subscriber=None, owner=None,
                       affected_user=None, affects_me=False,
                       has_patch=None, has_cve=None,
                       distribution=None, tags=None,
                       tags_combinator=BugTagsSearchCombinator.ALL,
                       omit_duplicates=True, omit_targeted=None,
                       status_upstream=None, milestone=None, component=None,
                       nominated_for=None, sourcepackagename=None,
                       has_no_package=None, hardware_bus=None,
                       hardware_vendor_id=None, hardware_product_id=None,
                       hardware_driver_name=None,
                       hardware_driver_package_name=None,
                       hardware_owner_is_bug_reporter=None,
                       hardware_owner_is_affected_by_bug=False,
                       hardware_owner_is_subscribed_to_bug=False,
                       hardware_is_linked_to_bug=False, linked_branches=None,
                       linked_blueprints=None, structural_subscriber=None,
                       modified_since=None, created_since=None,
                       created_before=None, information_type=None):
        """Create and return a new instance using the parameter list."""
        search_params = cls(user=user, orderby=order_by)

        search_params.searchtext = search_text
        search_params.status = cls._anyfy(status)
        search_params.importance = cls._anyfy(importance)
        search_params.assignee = assignee
        search_params.bug_reporter = bug_reporter
        search_params.bug_supervisor = bug_supervisor
        search_params.bug_commenter = bug_commenter
        search_params.subscriber = bug_subscriber
        search_params.owner = owner
        search_params.affected_user = affected_user
        search_params.distribution = distribution
        if has_patch:
            # Import this here to avoid circular imports
            from lp.bugs.interfaces.bugattachment import (
                BugAttachmentType)
            search_params.attachmenttype = BugAttachmentType.PATCH
        search_params.has_cve = has_cve
        if zope_isinstance(tags, (list, tuple)):
            if len(tags) > 0:
                if tags_combinator == BugTagsSearchCombinator.ALL:
                    search_params.tag = all(*tags)
                else:
                    search_params.tag = any(*tags)
        elif zope_isinstance(tags, str):
            search_params.tag = tags
        elif tags is None:
            pass  # tags not supplied
        else:
            raise AssertionError(
                'Tags can only be supplied as a list or a string.')
        search_params.omit_dupes = omit_duplicates
        search_params.omit_targeted = omit_targeted
        if status_upstream is not None:
            if 'pending_bugwatch' in status_upstream:
                search_params.pending_bugwatch_elsewhere = True
            if 'resolved_upstream' in status_upstream:
                search_params.resolved_upstream = True
            if 'open_upstream' in status_upstream:
                search_params.open_upstream = True
            if 'hide_upstream' in status_upstream:
                search_params.has_no_upstream_bugtask = True
        search_params.milestone = cls._anyfy(milestone)
        search_params.component = cls._anyfy(component)
        search_params.sourcepackagename = sourcepackagename
        if has_no_package:
            search_params.sourcepackagename = NULL
        search_params.nominated_for = nominated_for

        search_params.hardware_bus = hardware_bus
        search_params.hardware_vendor_id = hardware_vendor_id
        search_params.hardware_product_id = hardware_product_id
        search_params.hardware_driver_name = hardware_driver_name
        search_params.hardware_driver_package_name = (
            hardware_driver_package_name)
        search_params.hardware_owner_is_bug_reporter = (
            hardware_owner_is_bug_reporter)
        search_params.hardware_owner_is_affected_by_bug = (
            hardware_owner_is_affected_by_bug)
        search_params.hardware_owner_is_subscribed_to_bug = (
            hardware_owner_is_subscribed_to_bug)
        search_params.hardware_is_linked_to_bug = (
            hardware_is_linked_to_bug)
        search_params.linked_branches = linked_branches
        search_params.linked_blueprints = linked_blueprints
        search_params.structural_subscriber = structural_subscriber
        search_params.modified_since = modified_since
        search_params.created_since = created_since
        search_params.created_before = created_before
        search_params.information_type = information_type

        return search_params
Пример #49
0
 def empty_resultset(self):
     return zope_isinstance(self.plain_resultset, EmptyResultSet)
Пример #50
0
    def fromSearchForm(cls,
                       user,
                       order_by=('-importance', ),
                       search_text=None,
                       status=list(UNRESOLVED_BUGTASK_STATUSES),
                       importance=None,
                       assignee=None,
                       bug_reporter=None,
                       bug_supervisor=None,
                       bug_commenter=None,
                       bug_subscriber=None,
                       owner=None,
                       affected_user=None,
                       affects_me=False,
                       has_patch=None,
                       has_cve=None,
                       distribution=None,
                       tags=None,
                       tags_combinator=BugTagsSearchCombinator.ALL,
                       omit_duplicates=True,
                       omit_targeted=None,
                       status_upstream=None,
                       milestone=None,
                       component=None,
                       nominated_for=None,
                       sourcepackagename=None,
                       has_no_package=None,
                       hardware_bus=None,
                       hardware_vendor_id=None,
                       hardware_product_id=None,
                       hardware_driver_name=None,
                       hardware_driver_package_name=None,
                       hardware_owner_is_bug_reporter=None,
                       hardware_owner_is_affected_by_bug=False,
                       hardware_owner_is_subscribed_to_bug=False,
                       hardware_is_linked_to_bug=False,
                       linked_branches=None,
                       linked_merge_proposals=None,
                       linked_blueprints=None,
                       structural_subscriber=None,
                       modified_since=None,
                       created_since=None,
                       created_before=None,
                       information_type=None):
        """Create and return a new instance using the parameter list."""
        search_params = cls(user=user, orderby=order_by)

        search_params.searchtext = search_text
        search_params.status = cls._anyfy(status)
        search_params.importance = cls._anyfy(importance)
        search_params.assignee = assignee
        search_params.bug_reporter = bug_reporter
        search_params.bug_supervisor = bug_supervisor
        search_params.bug_commenter = bug_commenter
        search_params.subscriber = bug_subscriber
        search_params.owner = owner
        search_params.affected_user = affected_user
        search_params.distribution = distribution
        if has_patch:
            # Import this here to avoid circular imports
            from lp.bugs.interfaces.bugattachment import (BugAttachmentType)
            search_params.attachmenttype = BugAttachmentType.PATCH
        search_params.has_cve = has_cve
        if zope_isinstance(tags, (list, tuple)):
            if len(tags) > 0:
                if tags_combinator == BugTagsSearchCombinator.ALL:
                    search_params.tag = all(*tags)
                else:
                    search_params.tag = any(*tags)
        elif zope_isinstance(tags, str):
            search_params.tag = tags
        elif tags is None:
            pass  # tags not supplied
        else:
            raise AssertionError(
                'Tags can only be supplied as a list or a string.')
        search_params.omit_dupes = omit_duplicates
        search_params.omit_targeted = omit_targeted
        if status_upstream is not None:
            if 'pending_bugwatch' in status_upstream:
                search_params.pending_bugwatch_elsewhere = True
            if 'resolved_upstream' in status_upstream:
                search_params.resolved_upstream = True
            if 'open_upstream' in status_upstream:
                search_params.open_upstream = True
            if 'hide_upstream' in status_upstream:
                search_params.has_no_upstream_bugtask = True
        search_params.milestone = cls._anyfy(milestone)
        search_params.component = cls._anyfy(component)
        search_params.sourcepackagename = sourcepackagename
        if has_no_package:
            search_params.sourcepackagename = NULL
        search_params.nominated_for = nominated_for

        search_params.hardware_bus = hardware_bus
        search_params.hardware_vendor_id = hardware_vendor_id
        search_params.hardware_product_id = hardware_product_id
        search_params.hardware_driver_name = hardware_driver_name
        search_params.hardware_driver_package_name = (
            hardware_driver_package_name)
        search_params.hardware_owner_is_bug_reporter = (
            hardware_owner_is_bug_reporter)
        search_params.hardware_owner_is_affected_by_bug = (
            hardware_owner_is_affected_by_bug)
        search_params.hardware_owner_is_subscribed_to_bug = (
            hardware_owner_is_subscribed_to_bug)
        search_params.hardware_is_linked_to_bug = (hardware_is_linked_to_bug)
        search_params.linked_branches = linked_branches
        search_params.linked_merge_proposals = linked_merge_proposals
        search_params.linked_blueprints = linked_blueprints
        search_params.structural_subscriber = structural_subscriber
        search_params.modified_since = modified_since
        search_params.created_since = created_since
        search_params.created_before = created_before
        search_params.information_type = information_type

        return search_params