Exemple #1
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
    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):
            persons = [persons]

        for person in persons:
            assert IPerson.providedBy(person), (
                'You can only add() an IPerson: %r' % person)
            # If the person already has a rationale, keep the first one.
            if person in self._personToRationale:
                continue
            self._personToRationale[person] = reason, header
            for receiving_person in get_recipients(person):
                # 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
    def template(self):
        # Check for the magical "index" added by the browser:page template
        # machinery. If it exists this is actually the
        # zope.browserpage.simpleviewclass.simple class that is magically
        # mixed in by the browser:page zcml directive the template defined in
        # the directive should be used.
        if safe_hasattr(self, 'index'):
            return super(HasSpecificationsView, self).template

        # Sprints and Persons don't have a usage enum for blueprints, so we
        # have to fallback to the default.
        if (ISprint.providedBy(self.context)
            or IPerson.providedBy(self.context)):
            return self.default_template

        # ProjectGroups are a special case, as their products may be a
        # combination of usage settings. To deal with this, check all
        # products via the involvment menu.
        if (IProjectGroup.providedBy(self.context)
            or IProjectGroupSeries.providedBy(self.context)):
            involvement = getMultiAdapter(
                (self.context, self.request),
                name='+get-involved')
            if service_uses_launchpad(involvement.blueprints_usage):
                return self.default_template
            else:
                return self.not_launchpad_template

        # Otherwise, determine usage and provide the correct template.
        service_usage = IServiceUsage(self.context)
        if service_uses_launchpad(service_usage.blueprints_usage):
            return self.default_template
        else:
            return self.not_launchpad_template
Exemple #4
0
 def __init__(self, context=None):
     """Pass a Person as context, or anything else for the current user."""
     super(HostedBranchRestrictedOnOwnerVocabulary, self).__init__(context)
     if IPerson.providedBy(self.context):
         self.user = self.context
     else:
         self.user = getUtility(ILaunchBag).user
def get_string_representation(obj):
    """Returns a string representation of an object.

    It can be used as oldvalue and newvalue.

    Returns None if no representation can be made.
    """
    if IPerson.providedBy(obj):
        return obj.name
    if IBug.providedBy(obj):
        return str(obj.id)
    elif ISourcePackageRelease.providedBy(obj):
        return "%s %s" % (obj.sourcepackagename.name, obj.version)
    elif IProductRelease.providedBy(obj):
        return "%s %s" % (obj.product.name, obj.version)
    elif IMilestone.providedBy(obj):
        return obj.name
    elif isinstance(obj, BaseItem):
        return obj.title
    elif isinstance(obj, basestring):
        return obj
    elif isinstance(obj, bool):
        return str(obj)
    else:
        return None
Exemple #6
0
 def create(cls,
            member,
            team,
            reviewer,
            old_status,
            new_status,
            last_change_comment=None):
     if not ITeam.providedBy(team):
         raise TypeError('team must be ITeam: %s' % repr(team))
     if not IPerson.providedBy(reviewer):
         raise TypeError('reviewer must be IPerson: %s' % repr(reviewer))
     if old_status not in TeamMembershipStatus:
         raise TypeError("old_status must be TeamMembershipStatus: %s" %
                         repr(old_status))
     if new_status not in TeamMembershipStatus:
         raise TypeError("new_status must be TeamMembershipStatus: %s" %
                         repr(new_status))
     metadata = {
         'reviewer': reviewer.id,
         'old_status': old_status.name,
         'new_status': new_status.name,
         'last_change_comment': last_change_comment,
     }
     return super(MembershipNotificationJob,
                  cls).create(minor_person=member,
                              major_person=team,
                              metadata=metadata)
    def template(self):
        # Check for the magical "index" added by the browser:page template
        # machinery. If it exists this is actually the
        # zope.browserpage.simpleviewclass.simple class that is magically
        # mixed in by the browser:page zcml directive the template defined in
        # the directive should be used.
        if safe_hasattr(self, 'index'):
            return super(HasSpecificationsView, self).template

        # Sprints and Persons don't have a usage enum for blueprints, so we
        # have to fallback to the default.
        if (ISprint.providedBy(self.context)
                or IPerson.providedBy(self.context)):
            return self.default_template

        # ProjectGroups are a special case, as their products may be a
        # combination of usage settings. To deal with this, check all
        # products via the involvment menu.
        if (IProjectGroup.providedBy(self.context)
                or IProjectGroupSeries.providedBy(self.context)):
            involvement = getMultiAdapter((self.context, self.request),
                                          name='+get-involved')
            if service_uses_launchpad(involvement.blueprints_usage):
                return self.default_template
            else:
                return self.not_launchpad_template

        # Otherwise, determine usage and provide the correct template.
        service_usage = IServiceUsage(self.context)
        if service_uses_launchpad(service_usage.blueprints_usage):
            return self.default_template
        else:
            return self.not_launchpad_template
Exemple #8
0
 def __init__(self, context=None):
     """Pass a Person as context, or anything else for the current user."""
     super(HostedBranchRestrictedOnOwnerVocabulary, self).__init__(context)
     if IPerson.providedBy(self.context):
         self.user = self.context
     else:
         self.user = getUtility(ILaunchBag).user
def get_string_representation(obj):
    """Returns a string representation of an object.

    It can be used as oldvalue and newvalue.

    Returns None if no representation can be made.
    """
    if IPerson.providedBy(obj):
        return obj.name
    if IBug.providedBy(obj):
        return str(obj.id)
    elif ISourcePackageRelease.providedBy(obj):
        return "%s %s" % (obj.sourcepackagename.name, obj.version)
    elif IProductRelease.providedBy(obj):
        return "%s %s" % (obj.product.name, obj.version)
    elif IMilestone.providedBy(obj):
        return obj.name
    elif isinstance(obj, BaseItem):
        return obj.title
    elif isinstance(obj, basestring):
        return obj
    elif isinstance(obj, bool):
        return str(obj)
    else:
        return None
Exemple #10
0
 def create(cls, minor_person, major_person, metadata, requester=None):
     """See `IPersonTransferJob`."""
     if not IPerson.providedBy(minor_person):
         raise TypeError("minor_person must be IPerson: %s" %
                         repr(minor_person))
     if not IPerson.providedBy(major_person):
         raise TypeError("major_person must be IPerson: %s" %
                         repr(major_person))
     job = PersonTransferJob(minor_person=minor_person,
                             major_person=major_person,
                             job_type=cls.class_job_type,
                             metadata=metadata,
                             requester=requester)
     derived = cls(job)
     derived.celeryRunOnCommit()
     return derived
 def create(cls, minor_person, major_person, metadata, requester=None):
     """See `IPersonTransferJob`."""
     if not IPerson.providedBy(minor_person):
         raise TypeError("minor_person must be IPerson: %s"
                         % repr(minor_person))
     if not IPerson.providedBy(major_person):
         raise TypeError("major_person must be IPerson: %s"
                         % repr(major_person))
     job = PersonTransferJob(
         minor_person=minor_person,
         major_person=major_person,
         job_type=cls.class_job_type,
         metadata=metadata,
         requester=requester)
     derived = cls(job)
     derived.celeryRunOnCommit()
     return derived
Exemple #12
0
def is_public_person_or_closed_team(person):
    """Return True if person is a Person or not an open or delegated team."""
    from lp.registry.interfaces.person import IPerson
    if not IPerson.providedBy(person):
        return False
    if not person.is_team:
        return person.visibility == PersonVisibility.PUBLIC
    return person.membership_policy in EXCLUSIVE_TEAM_POLICY
Exemple #13
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
 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
def is_public_person_or_closed_team(person):
    """Return True if person is a Person or not an open or delegated team."""
    from lp.registry.interfaces.person import IPerson
    if not IPerson.providedBy(person):
        return False
    if not person.is_team:
        return person.visibility == PersonVisibility.PUBLIC
    return person.membership_policy in EXCLUSIVE_TEAM_POLICY
Exemple #16
0
 def remove(self, persons):
     """See `INotificationRecipientSet`."""
     from zope.security.proxy import removeSecurityProxy
     from lp.registry.model.person import get_recipients
     if IPerson.providedBy(persons):
         persons = [persons]
     for person in persons:
         assert IPerson.providedBy(person), (
             'You can only remove() an IPerson: %r' % person)
         if person in self._personToRationale:
             del self._personToRationale[person]
         for removed_person in get_recipients(person):
             # Bypass zope's security because IEmailAddress.email is
             # not public.
             preferred_email = removeSecurityProxy(
                 removed_person.preferredemail)
             email = str(preferred_email.email)
             self._receiving_people.discard((email, removed_person))
             del self._emailToPerson[email]
 def remove(self, persons):
     """See `INotificationRecipientSet`."""
     from zope.security.proxy import removeSecurityProxy
     from lp.registry.model.person import get_recipients
     if IPerson.providedBy(persons):
         persons = [persons]
     for person in persons:
         assert IPerson.providedBy(person), (
             'You can only remove() an IPerson: %r' % person)
         if person in self._personToRationale:
             del self._personToRationale[person]
         for removed_person in get_recipients(person):
             # Bypass zope's security because IEmailAddress.email is
             # not public.
             preferred_email = removeSecurityProxy(
                 removed_person.preferredemail)
             email = str(preferred_email.email)
             self._receiving_people.discard((email, removed_person))
             del self._emailToPerson[email]
def get_git_namespace(target, owner):
    if IProduct.providedBy(target):
        return getUtility(IGitNamespaceSet).get(owner, project=target)
    elif IDistributionSourcePackage.providedBy(target):
        return getUtility(IGitNamespaceSet).get(
            owner, distribution=target.distribution,
            sourcepackagename=target.sourcepackagename)
    elif target is None or IPerson.providedBy(target):
        return getUtility(IGitNamespaceSet).get(owner)
    else:
        raise AssertionError("No Git namespace defined for %s" % target)
 def getProposalsForContext(context, status=None, visible_by_user=None):
     """See `IBranchMergeProposalGetter`."""
     collection = getUtility(IAllBranches).visibleByUser(visible_by_user)
     if context is None:
         pass
     elif IProduct.providedBy(context):
         collection = collection.inProduct(context)
     elif IPerson.providedBy(context):
         collection = collection.ownedBy(context)
     else:
         raise BadBranchMergeProposalSearchContext(context)
     return collection.getMergeProposals(status)
Exemple #20
0
 def getProposalsForContext(context, status=None, visible_by_user=None):
     """See `IBranchMergeProposalGetter`."""
     collection = getUtility(IAllBranches).visibleByUser(visible_by_user)
     if context is None:
         pass
     elif IProduct.providedBy(context):
         collection = collection.inProduct(context)
     elif IPerson.providedBy(context):
         collection = collection.ownedBy(context)
     else:
         raise BadBranchMergeProposalSearchContext(context)
     return collection.getMergeProposals(status)
 def test_branch_list_recipes_link(self):
     # The link to the source package recipes is always displayed.
     page = self.get_branch_list_page()
     recipes_matcher = soupmatchers.HTMLContains(
         soupmatchers.Tag('Source package recipes link',
                          'a',
                          text='Source package recipes',
                          attrs={'href': self.base_url + '/+recipes'}))
     if IPerson.providedBy(self.default_target):
         self.assertThat(page, recipes_matcher)
     else:
         self.assertThat(page, Not(recipes_matcher))
Exemple #22
0
 def setRenderedValue(self, value):
     """See `IWidget`."""
     self.setUpSubWidgets()
     if value == GitGranteeType.REPOSITORY_OWNER:
         self.default_option = "repository_owner"
         return
     elif value is None or IPerson.providedBy(value):
         self.default_option = "person"
         self.person_widget.setRenderedValue(value)
         return
     else:
         raise AssertionError("Not a valid value: %r" % value)
 def test_branch_list_recipes_link(self):
     # The link to the source package recipes is always displayed.
     page = self.get_branch_list_page()
     recipes_matcher = soupmatchers.HTMLContains(
         soupmatchers.Tag(
             'Source package recipes link', 'a',
             text='Source package recipes',
             attrs={'href': self.base_url + '/+recipes'}))
     if IPerson.providedBy(self.default_target):
         self.assertThat(page, recipes_matcher)
     else:
         self.assertThat(page, Not(recipes_matcher))
 def setRenderedValue(self, value):
     """See IWidget."""
     self.setUpSubWidgets()
     if IBranchTarget.providedBy(value):
         if IProduct.providedBy(value.context):
             self.default_option = 'product'
             self.product_widget.setRenderedValue(value.context)
             return
         elif IPerson.providedBy(value.context):
             self.default_option = 'personal'
             return
     else:
         raise AssertionError('Not a valid value: %r' % value)
 def setRenderedValue(self, value):
     """See IWidget."""
     self.setUpSubWidgets()
     if IBranchTarget.providedBy(value):
         if IProduct.providedBy(value.context):
             self.default_option = 'product'
             self.product_widget.setRenderedValue(value.context)
             return
         elif IPerson.providedBy(value.context):
             self.default_option = 'personal'
             return
     else:
         raise AssertionError('Not a valid value: %r' % value)
 def setRenderedValue(self, value):
     """See `IWidget`."""
     self.setUpSubWidgets()
     if value is None or IPerson.providedBy(value):
         self.default_option = "personal"
         return
     elif IProduct.providedBy(value):
         self.default_option = "project"
         self.project_widget.setRenderedValue(value)
         return
     elif IDistributionSourcePackage.providedBy(value):
         self.default_option = "package"
         self.distribution_widget.setRenderedValue(value.distribution)
         self.package_widget.setRenderedValue(value.sourcepackagename)
     else:
         raise AssertionError("Not a valid value: %r" % value)
Exemple #27
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)
Exemple #29
0
    def __init__(self, search_text=None, owner=None, sort=None, product=None,
                 distribution=None, projectgroup=None):
        """Initialize a new FAQ search.

        See `IFAQCollection`.searchFAQs for the basic parameters description.
        Additional parameters:
        :param product: The product in which to search for FAQs.
        :param distribution: The distribution in which to search for FAQs.
        :param projectgroup: The project group in which to search for FAQs.
        """
        if search_text is not None:
            assert isinstance(search_text, basestring), (
                'search_text should be a string, not %s' % type(search_text))
            self.search_text = search_text

        if owner is not None:
            assert IPerson.providedBy(owner), (
                'owner should be an IPerson, not %s' % type(owner))
            self.owner = owner

        if sort is not None:
            assert sort in FAQSort.items, (
                'sort should be an item from FAQSort, not %s' % type(sort))
            self.sort = sort

        if product is not None:
            assert IProduct.providedBy(product), (
                'product should be an IProduct, not %s' % type(product))
            assert distribution is None and projectgroup is None, (
                'can only use one of product, distribution, or projectgroup')
            self.product = product

        if distribution is not None:
            assert IDistribution.providedBy(distribution), (
                'distribution should be an IDistribution, %s' %
                type(distribution))
            assert product is None and projectgroup is None, (
                'can only use one of product, distribution, or projectgroup')
            self.distribution = distribution

        if projectgroup is not None:
            assert IProjectGroup.providedBy(projectgroup), (
                'projectgroup should be an IProjectGroup, not %s' %
                type(projectgroup))
            assert product is None and distribution is None, (
                'can only use one of product, distribution, or projectgroup')
            self.projectgroup = projectgroup
Exemple #30
0
    def __init__(self, search_text=None, owner=None, sort=None, product=None,
                 distribution=None, project=None):
        """Initialize a new FAQ search.

        See `IFAQCollection`.searchFAQs for the basic parameters description.
        Additional parameters:
        :param product: The product in which to search for FAQs.
        :param distribution: The distribution in which to search for FAQs.
        :param project: The project in which to search for FAQs.
        """
        if search_text is not None:
            assert isinstance(search_text, basestring), (
                'search_text should be a string, not %s' % type(search_text))
            self.search_text = search_text

        if owner is not None:
            assert IPerson.providedBy(owner), (
                'owner should be an IPerson, not %s' % type(owner))
            self.owner = owner

        if sort is not None:
            assert sort in FAQSort.items, (
                'sort should be an item from FAQSort, not %s' % type(sort))
            self.sort = sort

        if product is not None:
            assert IProduct.providedBy(product), (
                'product should be an IProduct, not %s' % type(product))
            assert distribution is None and project is None, (
                'can only use one of product, distribution, or project')
            self.product = product

        if distribution is not None:
            assert IDistribution.providedBy(distribution), (
                'distribution should be an IDistribution, %s' %
                type(distribution))
            assert product is None and project is None, (
                'can only use one of product, distribution, or project')
            self.distribution = distribution

        if project is not None:
            assert IProjectGroup.providedBy(project), (
                'project should be an IProjectGroup, not %s' % type(project))
            assert product is None and distribution is None, (
                'can only use one of product, distribution, or project')
            self.project = project
Exemple #31
0
 def _renderSuggestionLabel(self, repository, index):
     """Render a label for the option based on a repository."""
     # To aid usability there needs to be some text connected with the
     # radio buttons that is not a hyperlink in order to select the radio
     # button.  It was decided not to have the entire text as a link, but
     # instead to have a separate link to the repository details.
     text = u'%s (<a href="%s">repository details</a>)'
     # If the repository is the default for the target, say so.
     if not IPerson.providedBy(repository.target):
         repository_set = getUtility(IGitRepositorySet)
         default_target = repository_set.getDefaultRepository(
             repository.target)
         if repository == default_target:
             text += u"&ndash; <em>default repository</em>"
     label = (u'<label for="%s" style="font-weight: normal">' + text +
              u'</label>')
     return structured(label, self._optionId(index),
                       repository.display_name, canonical_url(repository))
def get_person_bugtasks_search_params(user, context, **kwargs):
    """Returns a list of `BugTaskSearchParams` which can be used to
    search for all tasks related to a user given by `context`.

    Which tasks are related to a user?
      * the user has to be either assignee or owner of this task
        OR
      * the user has to be subscriber or commenter to the underlying bug
        OR
      * the user is reporter of the underlying bug, but this condition
        is automatically fulfilled by the first one as each new bug
        always get one task owned by the bug reporter
    """
    from lp.registry.interfaces.person import IPerson
    assert IPerson.providedBy(context), "Context argument needs to be IPerson"
    relevant_fields = ('assignee', 'bug_subscriber', 'owner', 'bug_commenter',
                       'structural_subscriber')
    search_params = []
    for key in relevant_fields:
        # all these parameter default to None
        user_param = kwargs.get(key)
        if user_param is None or user_param == context:
            # we are only creating a `BugTaskSearchParams` object if
            # the field is None or equal to the context
            arguments = kwargs.copy()
            arguments[key] = context
            if key == 'owner':
                # Specify both owner and bug_reporter to try to
                # prevent the same bug (but different tasks)
                # being displayed.
                # see `PersonRelatedBugTaskSearchListingView.searchUnbatched`
                arguments['bug_reporter'] = context
            search_params.append(
                BugTaskSearchParams.fromSearchForm(user, **arguments))
    if len(search_params) == 0:
        # unable to search for related tasks to user_context because user
        # modified the query in an invalid way by overwriting all user
        # related parameters
        raise IllegalRelatedBugTasksParams(
            ('Cannot search for related tasks to \'%s\', at least one '
             'of these parameter has to be empty: %s'
                % (context.name, ", ".join(relevant_fields))))
    return search_params
Exemple #33
0
def get_person_bugtasks_search_params(user, context, **kwargs):
    """Returns a list of `BugTaskSearchParams` which can be used to
    search for all tasks related to a user given by `context`.

    Which tasks are related to a user?
      * the user has to be either assignee or owner of this task
        OR
      * the user has to be subscriber or commenter to the underlying bug
        OR
      * the user is reporter of the underlying bug, but this condition
        is automatically fulfilled by the first one as each new bug
        always get one task owned by the bug reporter
    """
    from lp.registry.interfaces.person import IPerson
    assert IPerson.providedBy(context), "Context argument needs to be IPerson"
    relevant_fields = ('assignee', 'bug_subscriber', 'owner', 'bug_commenter',
                       'structural_subscriber')
    search_params = []
    for key in relevant_fields:
        # all these parameter default to None
        user_param = kwargs.get(key)
        if user_param is None or user_param == context:
            # we are only creating a `BugTaskSearchParams` object if
            # the field is None or equal to the context
            arguments = kwargs.copy()
            arguments[key] = context
            if key == 'owner':
                # Specify both owner and bug_reporter to try to
                # prevent the same bug (but different tasks)
                # being displayed.
                # see `PersonRelatedBugTaskSearchListingView.searchUnbatched`
                arguments['bug_reporter'] = context
            search_params.append(
                BugTaskSearchParams.fromSearchForm(user, **arguments))
    if len(search_params) == 0:
        # unable to search for related tasks to user_context because user
        # modified the query in an invalid way by overwriting all user
        # related parameters
        raise IllegalRelatedBugTasksParams(
            ('Cannot search for related tasks to \'%s\', at least one '
             'of these parameter has to be empty: %s' %
             (context.name, ", ".join(relevant_fields))))
    return search_params
Exemple #34
0
    def _generateSuggestionVocab(context, full_vocabulary):
        """Generate the vocabulary for the radio buttons.

        The generated vocabulary contains the default repository for the
        target if there is one, and also any other repositories that the
        user has specified recently as a target for a proposed merge.
        """
        if IGitRef.providedBy(context):
            repository = context.repository
        else:
            repository = context

        if IPerson.providedBy(repository.target):
            # If the source is a personal repository, then the only valid
            # target is that same repository.
            target_repositories = [repository]
        else:
            repository_set = getUtility(IGitRepositorySet)
            default_target = repository_set.getDefaultRepository(
                repository.target)
            logged_in_user = getUtility(ILaunchBag).user
            since = datetime.now(utc) - timedelta(days=90)
            collection = IGitCollection(repository.target).targetedBy(
                logged_in_user, since)
            collection = collection.visibleByUser(logged_in_user)
            # May actually need some eager loading, but the API isn't fine
            # grained yet.
            repositories = collection.getRepositories(eager_load=False).config(
                distinct=True)
            target_repositories = list(repositories.config(limit=5))
            # If there is a default repository, make sure it is always
            # shown, and as the first item.
            if default_target is not None:
                if default_target in target_repositories:
                    target_repositories.remove(default_target)
                target_repositories.insert(0, default_target)

        terms = []
        for repository in target_repositories:
            terms.append(SimpleTerm(repository, repository.unique_name))

        return SimpleVocabulary(terms)
 def create(cls, member, team, reviewer, old_status, new_status,
            last_change_comment=None):
     if not ITeam.providedBy(team):
         raise TypeError('team must be ITeam: %s' % repr(team))
     if not IPerson.providedBy(reviewer):
         raise TypeError('reviewer must be IPerson: %s' % repr(reviewer))
     if old_status not in TeamMembershipStatus:
         raise TypeError("old_status must be TeamMembershipStatus: %s"
                         % repr(old_status))
     if new_status not in TeamMembershipStatus:
         raise TypeError("new_status must be TeamMembershipStatus: %s"
                         % repr(new_status))
     metadata = {
         'reviewer': reviewer.id,
         'old_status': old_status.name,
         'new_status': new_status.name,
         'last_change_comment': last_change_comment,
         }
     return super(MembershipNotificationJob, cls).create(
         minor_person=member, major_person=team, metadata=metadata)
Exemple #36
0
 def getByPath(self, path):
     """See `IGitLookup`."""
     traverser = getUtility(IGitTraverser)
     segments = iter(path.split("/"))
     try:
         owner, target, repository, trailing = traverser.traverse(segments)
     except (InvalidNamespace, InvalidProductName, NameLookupFailed):
         return None, None
     if repository is None:
         if IPerson.providedBy(target):
             return None, None
         repository_set = getUtility(IGitRepositorySet)
         if owner is None:
             repository = repository_set.getDefaultRepository(target)
         else:
             repository = repository_set.getDefaultRepositoryForOwner(
                 owner, target)
     trailing_segments = list(segments)
     if trailing:
         trailing_segments.insert(0, trailing)
     return repository, "/".join(trailing_segments)
Exemple #37
0
    def new(owner, title, content, keywords=keywords, date_created=None,
            product=None, distribution=None):
        """Factory method to create a new FAQ.

        Ensure that only one of product or distribution is given.
        """
        if not IPerson.providedBy(owner):
            raise AssertionError(
                'owner parameter should be an IPerson, not %s' % type(owner))
        if product is not None and distribution is not None:
            raise AssertionError(
                "only one of product or distribution should be provided")
        if product is None and distribution is None:
            raise AssertionError("product or distribution must be provided")
        if date_created is None:
            date_created = DEFAULT
        faq = FAQ(
            owner=owner, title=title, content=content, keywords=keywords,
            date_created=date_created, product=product,
            distribution=distribution)
        notify(ObjectCreatedEvent(faq))
        return faq
Exemple #38
0
    def new(owner, title, content, keywords=keywords, date_created=None,
            product=None, distribution=None):
        """Factory method to create a new FAQ.

        Ensure that only one of product or distribution is given.
        """
        if not IPerson.providedBy(owner):
            raise AssertionError(
                'owner parameter should be an IPerson, not %s' % type(owner))
        if product is not None and distribution is not None:
            raise AssertionError(
                "only one of product or distribution should be provided")
        if product is None and distribution is None:
            raise AssertionError("product or distribution must be provided")
        if date_created is None:
            date_created = DEFAULT
        faq = FAQ(
            owner=owner, title=title, content=content, keywords=keywords,
            date_created=date_created, product=product,
            distribution=distribution)
        notify(ObjectCreatedEvent(faq))
        return faq
    def initialize(self):
        if IPerson.providedBy(self.context):
            self.is_person = True
        elif IDistribution.providedBy(self.context):
            self.is_target = True
            self.is_pillar = True
            self.show_series = True
        elif IProduct.providedBy(self.context):
            self.is_target = True
            self.is_pillar = True
            self.has_wiki = True
            self.show_series = True
        elif IProjectGroup.providedBy(self.context):
            self.is_project = True
            self.is_pillar = True
            self.has_wiki = True
            self.show_target = True
            self.show_series = True
        elif IProjectGroupSeries.providedBy(self.context):
            self.show_milestone = True
            self.show_target = True
            self.show_series = True
        elif (IProductSeries.providedBy(self.context) or
              IDistroSeries.providedBy(self.context)):
            self.is_series = True
            self.show_milestone = True
        elif ISprint.providedBy(self.context):
            self.is_sprint = True
            self.show_target = True
        else:
            raise AssertionError('Unknown blueprint listing site.')

        if IHasDrivers.providedBy(self.context):
            self.has_drivers = True

        self.batchnav = BatchNavigator(
            self.specs, self.request,
            size=config.launchpad.default_batch_size)
    def initialize(self):
        if IPerson.providedBy(self.context):
            self.is_person = True
        elif IDistribution.providedBy(self.context):
            self.is_target = True
            self.is_pillar = True
            self.show_series = True
        elif IProduct.providedBy(self.context):
            self.is_target = True
            self.is_pillar = True
            self.has_wiki = True
            self.show_series = True
        elif IProjectGroup.providedBy(self.context):
            self.is_project = True
            self.is_pillar = True
            self.has_wiki = True
            self.show_target = True
            self.show_series = True
        elif IProjectGroupSeries.providedBy(self.context):
            self.show_milestone = True
            self.show_target = True
            self.show_series = True
        elif (IProductSeries.providedBy(self.context)
              or IDistroSeries.providedBy(self.context)):
            self.is_series = True
            self.show_milestone = True
        elif ISprint.providedBy(self.context):
            self.is_sprint = True
            self.show_target = True
        else:
            raise AssertionError('Unknown blueprint listing site.')

        if IHasDrivers.providedBy(self.context):
            self.has_drivers = True

        self.batchnav = BatchNavigator(
            self.specs, self.request, size=config.launchpad.default_batch_size)
    def getForDistroSeries(distro_series,
                           difference_type=None,
                           name_filter=None,
                           status=None,
                           child_version_higher=False,
                           parent_series=None,
                           packagesets=None,
                           changed_by=None):
        """See `IDistroSeriesDifferenceSource`."""
        if isinstance(status, DBItem):
            status = (status, )
        if IPerson.providedBy(changed_by):
            changed_by = (changed_by, )

        # Aliases, to improve readability.
        DSD = DistroSeriesDifference
        PSS = PackagesetSources
        SPN = SourcePackageName
        SPPH = SourcePackagePublishingHistory
        SPR = SourcePackageRelease
        TP = TeamParticipation

        conditions = [
            DSD.derived_series == distro_series,
            DSD.source_package_name == SPN.id,  # For ordering.
        ]
        if difference_type is not None:
            conditions.append(DSD.difference_type == difference_type)
        if status is not None:
            conditions.append(DSD.status.is_in(tuple(status)))

        if child_version_higher:
            conditions.append(DSD.source_version > DSD.parent_source_version)

        if parent_series:
            conditions.append(DSD.parent_series == parent_series.id)

        # Take a copy of the conditions specified thus far.
        basic_conditions = list(conditions)

        if name_filter:
            name_matches = [SPN.name == name_filter]
            try:
                packageset = getUtility(IPackagesetSet).getByName(
                    name_filter, distroseries=distro_series)
            except NoSuchPackageSet:
                packageset = None
            if packageset is not None:
                name_matches.append(
                    DSD.source_package_name_id.is_in(
                        Select(PSS.sourcepackagename_id,
                               PSS.packageset == packageset)))
            conditions.append(Or(*name_matches))

        if packagesets is not None:
            set_ids = [packageset.id for packageset in packagesets]
            conditions.append(
                DSD.source_package_name_id.is_in(
                    Select(PSS.sourcepackagename_id,
                           PSS.packageset_id.is_in(set_ids))))

        store = IStore(DSD)
        columns = (DSD, SPN.name)
        differences = store.find(columns, And(*conditions))

        if changed_by is not None:
            # Identify all DSDs referring to SPRs created by changed_by for
            # this distroseries. The set of DSDs for the given distroseries
            # can then be discovered as the intersection between this set and
            # the already established differences.
            differences_changed_by_conditions = And(
                basic_conditions,
                SPPH.archiveID == distro_series.main_archive.id,
                SPPH.distroseriesID == distro_series.id,
                SPPH.sourcepackagereleaseID == SPR.id,
                SPPH.status.is_in(active_publishing_status),
                SPR.creatorID == TP.personID,
                SPR.sourcepackagenameID == DSD.source_package_name_id,
                TP.teamID.is_in(person.id for person in changed_by))
            differences_changed_by = store.find(
                columns, differences_changed_by_conditions)
            differences = differences.intersection(differences_changed_by)

        differences = differences.order_by(SPN.name)

        def pre_iter_hook(rows):
            # Each row is (dsd, spn.name). Modify the results in place.
            rows[:] = (dsd for (dsd, spn_name) in rows)
            # Eager load everything to do with DSDs.
            return eager_load_dsds(rows)

        return DecoratedResultSet(differences, pre_iter_hook=pre_iter_hook)
 def _get_person_celebrities(self, is_team):
     for name in ILaunchpadCelebrities.names():
         attr = getattr(self.celebs, name)
         if IPerson.providedBy(attr) and attr.is_team == is_team:
             yield (name, attr)
Exemple #43
0
def get_person_picker_entry_metadata(picker_entry):
    """Return the picker entry meta for a given result value."""
    if picker_entry is not None and IPerson.providedBy(picker_entry):
        return "team" if picker_entry.is_team else "person"
    return None
Exemple #44
0
def is_public_person(person):
    """Return True if the person is public."""
    from lp.registry.interfaces.person import IPerson
    if not IPerson.providedBy(person):
        return False
    return person.visibility == PersonVisibility.PUBLIC
    def getForDistroSeries(distro_series, difference_type=None,
                           name_filter=None, status=None,
                           child_version_higher=False, parent_series=None,
                           packagesets=None, changed_by=None):
        """See `IDistroSeriesDifferenceSource`."""
        if isinstance(status, DBItem):
            status = (status,)
        if IPerson.providedBy(changed_by):
            changed_by = (changed_by,)

        # Aliases, to improve readability.
        DSD = DistroSeriesDifference
        PSS = PackagesetSources
        SPN = SourcePackageName
        SPPH = SourcePackagePublishingHistory
        SPR = SourcePackageRelease
        TP = TeamParticipation

        conditions = [
            DSD.derived_series == distro_series,
            DSD.source_package_name == SPN.id,  # For ordering.
            ]
        if difference_type is not None:
            conditions.append(DSD.difference_type == difference_type)
        if status is not None:
            conditions.append(DSD.status.is_in(tuple(status)))

        if child_version_higher:
            conditions.append(DSD.source_version > DSD.parent_source_version)

        if parent_series:
            conditions.append(DSD.parent_series == parent_series.id)

        # Take a copy of the conditions specified thus far.
        basic_conditions = list(conditions)

        if name_filter:
            name_matches = [SPN.name == name_filter]
            try:
                packageset = getUtility(IPackagesetSet).getByName(
                    name_filter, distroseries=distro_series)
            except NoSuchPackageSet:
                packageset = None
            if packageset is not None:
                name_matches.append(
                    DSD.source_package_name_id.is_in(
                        Select(PSS.sourcepackagename_id,
                               PSS.packageset == packageset)))
            conditions.append(Or(*name_matches))

        if packagesets is not None:
            set_ids = [packageset.id for packageset in packagesets]
            conditions.append(
                DSD.source_package_name_id.is_in(
                    Select(PSS.sourcepackagename_id,
                           PSS.packageset_id.is_in(set_ids))))

        store = IStore(DSD)
        columns = (DSD, SPN.name)
        differences = store.find(columns, And(*conditions))

        if changed_by is not None:
            # Identify all DSDs referring to SPRs created by changed_by for
            # this distroseries. The set of DSDs for the given distroseries
            # can then be discovered as the intersection between this set and
            # the already established differences.
            differences_changed_by_conditions = And(
                basic_conditions,
                SPPH.archiveID == distro_series.main_archive.id,
                SPPH.distroseriesID == distro_series.id,
                SPPH.sourcepackagereleaseID == SPR.id,
                SPPH.status.is_in(active_publishing_status),
                SPR.creatorID == TP.personID,
                SPR.sourcepackagenameID == DSD.source_package_name_id,
                TP.teamID.is_in(person.id for person in changed_by))
            differences_changed_by = store.find(
                columns, differences_changed_by_conditions)
            differences = differences.intersection(differences_changed_by)

        differences = differences.order_by(SPN.name)

        def pre_iter_hook(rows):
            # Each row is (dsd, spn.name). Modify the results in place.
            rows[:] = (dsd for (dsd, spn_name) in rows)
            # Eager load everything to do with DSDs.
            return eager_load_dsds(rows)

        return DecoratedResultSet(differences, pre_iter_hook=pre_iter_hook)
def is_public_person(person):
    """Return True if the person is public."""
    from lp.registry.interfaces.person import IPerson
    if not IPerson.providedBy(person):
        return False
    return person.visibility == PersonVisibility.PUBLIC