def traverse(self, name): """Return the IPOFile associated with the given name.""" assert self.request.method in [ 'GET', 'HEAD', 'POST' ], ('We only know about GET, HEAD, and POST') user = getUtility(ILaunchBag).user # We do not want users to see the 'en' potemplate because # we store the messages we want to translate as English. if name == 'en': raise NotFoundError(name) pofile = self.context.getPOFileByLang(name) if pofile is not None: # Already have a valid POFile entry, just return it. return pofile elif self.request.method in ['GET', 'HEAD']: # It's just a query, get a fake one so we don't create new # POFiles just because someone is browsing the web. language = getUtility(ILanguageSet).getLanguageByCode(name) if language is None: raise NotFoundError(name) return self.context.getDummyPOFile(language, requester=user, check_for_existing=False) else: # It's a POST. # XXX CarlosPerelloMarin 2006-04-20 bug=40275: We should # check the kind of POST we got. A logout will also be a # POST and we should not create a POFile in that case. return self.context.newPOFile(name, owner=user)
def __init__(self, repository, path): self.repository = repository self.path = path self.message = ( "The repository at %s does not contain a reference named '%s'." % (repository.display_name, path)) NotFoundError.__init__(self, self.message)
def traverse(self, name): """Return the IPOTemplate associated with the given name.""" assert self.request.method in [ 'GET', 'HEAD', 'PATCH', 'POST' ], ('We only know about GET, HEAD, PATCH and POST') # Get the requested potemplate. potemplate = self.context.getPOTemplateByName(name) if potemplate is None: # The template doesn't exist. raise NotFoundError(name) # Get whether the target for the requested template is officially # using Launchpad Translations. if potemplate.distribution is None: product_or_distro = potemplate.productseries.product else: product_or_distro = potemplate.distroseries.distribution translations_usage = product_or_distro.translations_usage if (service_uses_launchpad(translations_usage) and potemplate.iscurrent): # This template is available for translation. return potemplate elif check_permission('launchpad.TranslationsAdmin', potemplate): # User has Edit privileges for this template and can access it. return potemplate else: raise NotFoundError(name)
def __getitem__(self, attach_id): """See IBugAttachmentSet.""" try: attach_id = int(attach_id) except ValueError: raise NotFoundError(attach_id) try: item = BugAttachment.get(attach_id) except SQLObjectNotFound: raise NotFoundError(attach_id) return item
def _self_in_database(self): """See `GitRefDatabaseBackedMixin`.""" path = self.repository.default_branch if path is None: raise NotFoundError( "Repository '%s' has no default branch" % self.repository) ref = IStore(GitRef).get(GitRef, (self.repository_id, path)) if ref is None: raise NotFoundError( "Repository '%s' has default branch '%s', but there is no " "such reference" % (self.repository, path)) return ref
def run_with_login(login_id, function, *args, **kwargs): """Run 'function' logged in with 'login_id'. The first argument passed to 'function' will be the Launchpad `Person` object corresponding to 'login_id'. The exception is when the requesting login ID is `LAUNCHPAD_SERVICES`. In that case, we'll pass through the `LAUNCHPAD_SERVICES` variable and the method will do whatever security proxy hackery is required to provide read privileges to the Launchpad services. """ if login_id == LAUNCHPAD_SERVICES or login_id == LAUNCHPAD_ANONYMOUS: # Don't pass in an actual user. Instead pass in LAUNCHPAD_SERVICES # and expect `function` to use `removeSecurityProxy` or similar. return function(login_id, *args, **kwargs) if isinstance(login_id, basestring): requester = getUtility(IPersonSet).getByName(login_id) else: requester = getUtility(IPersonSet).get(login_id) if requester is None: raise NotFoundError("No person with id %s." % login_id) setupInteractionForPerson(requester) try: return function(requester, *args, **kwargs) finally: endInteraction()
def traverse_faq(self, name): """Return the FAQ by ID.""" try: id_ = int(name) except ValueError: raise NotFoundError(name) return self.context.getFAQ(id_)
def get(self, milestoneid): """See lp.registry.interfaces.milestone.IMilestoneSet.""" result = list(self.getByIds([milestoneid])) if not result: raise NotFoundError("Milestone with ID %d does not exist" % milestoneid) return result[0]
def __getitem__(self, tokentext): """See ILoginTokenSet.""" token = IStore(LoginToken).find( LoginToken, _token=hashlib.sha256(tokentext).hexdigest()).one() if token is None: raise NotFoundError(tokentext) token._plaintext_token = tokentext return token
def traverse_question(self, name): """Return the question.""" # questions should be ints try: question_id = int(name) except ValueError: raise NotFoundError(name) question = self.context.getQuestion(question_id) if question is not None: return question # Try to find the question in another context, since it may have # been retargeted. question = getUtility(IQuestionSet).get(question_id) if question is None: raise NotFoundError(name) return self.redirectSubTree(canonical_url(question))
def getFileByName(self, filename): """See `ISourcePackageRecipeBuild`.""" files = dict((lfa.filename, lfa) for lfa in [self.log, self.upload_log] if lfa is not None) try: return files[filename] except KeyError: raise NotFoundError(filename)
def _self_in_database(self): """See `GitRefDatabaseBackedMixin`.""" ref = IStore(GitRef).get(GitRef, (self.repository_id, self.path)) if ref is None: raise NotFoundError( "Repository '%s' does not currently contain a reference named " "'%s'" % (self.repository, self.path)) return ref
def __getitem__(self, code): """See `ILanguageSet`.""" language = self.getLanguageByCode(code) if language is None: raise NotFoundError(code) return language
def getPackage(self, distroseries): """See IProductSeries.""" for pkg in self.sourcepackages: if pkg.distroseries == distroseries: return pkg # XXX sabdfl 2005-06-23: This needs to search through the ancestry of # the distroseries to try to find a relevant packaging record raise NotFoundError(distroseries)
def getFileAliasByName(self, name): """See `IProductRelease`.""" for file_ in self.files: if file_.libraryfile.filename == name: return file_.libraryfile elif file_.signature and file_.signature.filename == name: return file_.signature raise NotFoundError(name)
def getBySnapAndID(cls, snap, job_id): """See `ISnapRequestBuildsJobSource`.""" snap_job = IStore(SnapJob).find( SnapJob, SnapJob.job_id == job_id, SnapJob.snap == snap, SnapJob.job_type == cls.class_job_type).one() if snap_job is None: raise NotFoundError( "No REQUEST_BUILDS job with ID %d found for %r" % (job_id, snap)) return cls(snap_job)
def getFileByName(self, filename): """See `ISourcePackageRelease`.""" sprf = Store.of(self).find( SourcePackageReleaseFile, SourcePackageReleaseFile.sourcepackagerelease == self.id, LibraryFileAlias.id == SourcePackageReleaseFile.libraryfileID, LibraryFileAlias.filename == filename).one() if sprf: return sprf.libraryfile else: raise NotFoundError(filename)
def _getFileByName(self, filename): """Return the corresponding file reference in the policy context. If the filename ends in '.orig.tar.gz', then we look for it in the distribution primary archive as well, with the PPA file taking precedence in case it's found in both archives. This is needed so that PPA uploaders don't have to waste bandwidth uploading huge upstream tarballs that are already published in the target distribution. When the file reference is found, its corresponding LibraryFileAlias and Archive are returned. :param filename: string containing the exact name of the wanted file. :return: a tuple containing a `ILibraryFileAlias` corresponding to the matching file and an `Archive` where it was published. :raise: `NotFoundError` when the wanted file could not be found. """ # We cannot check the archive purpose for partner archives here, # because the archive override rules have not been applied yet. # Uploads destined for the Ubuntu main archive and the 'partner' # component will eventually end up in the partner archive though. if (self.policy.archive.purpose == ArchivePurpose.PRIMARY and self.component_name == 'partner'): archives = [ getUtility(IArchiveSet).getByDistroPurpose( distribution=self.policy.distro, purpose=ArchivePurpose.PARTNER) ] elif (self.policy.archive.purpose == ArchivePurpose.PPA and determine_source_file_type(filename) in (SourcePackageFileType.ORIG_TARBALL, SourcePackageFileType.COMPONENT_ORIG_TARBALL)): archives = [self.policy.archive, self.policy.distro.main_archive] else: archives = [self.policy.archive] archives = [archive for archive in archives if archive is not None] library_file = None for archive in archives: try: library_file = archive.getFileByName(filename) self.logger.debug("%s found in %s" % (filename, archive.displayname)) return library_file, archive except NotFoundError: pass raise NotFoundError(filename)
def get(cls, job_id): """Get a job by id. :return: The `SnapBuildJob` with the specified id, as the current `SnapBuildJobDerived` subclass. :raises: `NotFoundError` if there is no job with the specified id, or its `job_type` does not match the desired subclass. """ snap_build_job = IStore(SnapBuildJob).get(SnapBuildJob, job_id) if snap_build_job.job_type != cls.class_job_type: raise NotFoundError("No object found with id %d and type %s" % (job_id, cls.class_job_type.title)) return cls(snap_build_job)
def __getitem__(self, language_code): """See `ITranslationGroup`.""" query = Store.of(self).find( Translator, Translator.translationgroup == self, Translator.languageID == Language.id, Language.code == language_code) translator = query.one() if translator is None: raise NotFoundError(language_code) return translator
def get(cls, job_id): """Get a job by id. :return: the PackageCopyJob with the specified id, as the current PackageCopyJobDerived subclass. :raises: NotFoundError if there is no job with the specified id, or its job_type does not match the desired subclass. """ job = IStore(PackageCopyJob).get(PackageCopyJob, job_id) if job.job_type != cls.class_job_type: raise NotFoundError('No object found with id %d and type %s' % (job_id, cls.class_job_type.title)) return cls(job)
def updateKarmaValue(self, value, person_id, category_id, product_id=None, distribution_id=None, sourcepackagename_id=None, projectgroup_id=None): """See IKarmaCacheManager.""" entry = self._getEntry( person_id=person_id, category_id=category_id, product_id=product_id, distribution_id=distribution_id, projectgroup_id=projectgroup_id, sourcepackagename_id=sourcepackagename_id) if entry is None: raise NotFoundError("KarmaCache not found: %s" % vars()) else: entry.karmavalue = value entry.syncUpdate()
def get(self, projectgroupid): """See `lp.registry.interfaces.projectgroup.IProjectGroupSet`. >>> getUtility(IProjectGroupSet).get(1).name u'apache' >>> getUtility(IProjectGroupSet).get(-1) Traceback (most recent call last): ... NotFoundError: -1 """ try: projectgroup = ProjectGroup.get(projectgroupid) except SQLObjectNotFound: raise NotFoundError(projectgroupid) return projectgroup
def traverse(self, name): """Return the IPOMsgSet associated with the given name.""" assert self.request.method in ['GET', 'HEAD', 'POST'], ( 'We only know about GET, HEAD, and POST') try: sequence = int(name) except ValueError: # The URL does not have a number to do the traversal. raise NotFoundError( "%r is not a valid sequence number." % name) if sequence < 1: # We got an invalid sequence number. raise NotFoundError( "%r is not a valid sequence number." % name) potmsgset = self.context.potemplate.getPOTMsgSetBySequence(sequence) if potmsgset is None: raise NotFoundError( "%r is not a valid sequence number." % name) return potmsgset.getCurrentTranslationMessageOrDummy(self.context)
def getFileByName(self, filename): """See `ILiveFSBuild`.""" if filename.endswith(".txt.gz"): file_object = self.log elif filename.endswith("_log.txt"): file_object = self.upload_log else: file_object = Store.of(self).find( LibraryFileAlias, LiveFSFile.livefsbuild == self.id, LibraryFileAlias.id == LiveFSFile.libraryfile_id, LibraryFileAlias.filename == filename).one() if file_object is not None and file_object.filename == filename: return file_object raise NotFoundError(filename)
def current_published(self): """See IDistroArchSeriesBinaryPackage.""" current = IStore(BinaryPackagePublishingHistory).find( BinaryPackagePublishingHistory, BinaryPackagePublishingHistory.status == PackagePublishingStatus.PUBLISHED, *self._getPublicationJoins()).order_by( Desc(BinaryPackagePublishingHistory.datecreated)).first() if current is None: raise NotFoundError("Binary package %s not published in %s/%s" % (self.binarypackagename.name, self.distroarchseries.distroseries.name, self.distroarchseries.architecturetag)) return current
def traverse_lang(self, langcode): """Retrieve the ProductSeriesLanguage or a dummy if it is None.""" # We do not want users to see the 'en' pofile because # we store the messages we want to translate as English. if langcode == 'en': raise NotFoundError(langcode) langset = getUtility(ILanguageSet) try: lang = langset[langcode] except IndexError: # Unknown language code. raise NotFoundError psl_set = getUtility(IProductSeriesLanguageSet) psl = psl_set.getProductSeriesLanguage(self.context, lang) return psl
def _getFileByName(self, filename): """Return the corresponding file reference in the policy context. If the filename ends in '.orig.tar.gz', then we look for it in the distribution primary archive as well, with the PPA file taking precedence in case it's found in both archives. This is needed so that PPA uploaders don't have to waste bandwidth uploading huge upstream tarballs that are already published in the target distribution. When the file reference is found, its corresponding LibraryFileAlias and Archive are returned. :param filename: string containing the exact name of the wanted file. :return: a tuple containing a `ILibraryFileAlias` corresponding to the matching file and an `Archive` where it was published. :raise: `NotFoundError` when the wanted file could not be found. """ if (self.policy.archive.purpose == ArchivePurpose.PPA and determine_source_file_type(filename) in ( SourcePackageFileType.ORIG_TARBALL, SourcePackageFileType.COMPONENT_ORIG_TARBALL, SourcePackageFileType.ORIG_TARBALL_SIGNATURE, SourcePackageFileType.COMPONENT_ORIG_TARBALL_SIGNATURE, )): archives = [self.policy.archive, self.policy.distro.main_archive] else: archives = [self.policy.archive] archives = [archive for archive in archives if archive is not None] library_file = None for archive in archives: try: library_file = archive.getFileByName(filename) self.logger.debug("%s found in %s" % (filename, archive.displayname)) return library_file, archive except NotFoundError: pass raise NotFoundError(filename)
def _nameToPackageset(self, packageset): """Helper to convert a possible string name to IPackageset.""" if isinstance(packageset, basestring): # A package set name was passed, assume the current distro series. ubuntu = getUtility(IDistributionSet).getByName('ubuntu') name = packageset store = IStore(Packageset) packageset = store.find(Packageset, name=name, distroseries=ubuntu.currentseries).one() if packageset is not None: return packageset else: raise NotFoundError("No such package set '%s'" % name) elif IPackageset.providedBy(packageset): return packageset else: raise ValueError('Not a package set: %s' % _extract_type_name(packageset))
def traverse_lang(self, langcode): """Retrieve the DistroSeriesLanguage or a dummy if one it is None.""" # We do not want users to see the 'en' pofile because # we store the messages we want to translate as English. if langcode == 'en': raise NotFoundError(langcode) langset = getUtility(ILanguageSet) try: lang = langset[langcode] except IndexError: # Unknown language code. raise NotFoundError distroserieslang = self.context.getDistroSeriesLanguageOrDummy(lang) # Check if user is able to view the translations for # this distribution series language. # If not, raise TranslationUnavailable. check_distroseries_translations_viewable(self.context) return distroserieslang