3 # Copyright (c) 2010, 2011 Intel, Inc.
5 # This program is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by the Free
7 # Software Foundation; version 2 of the License
9 # This program is distributed in the hope that it will be useful, but
10 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
11 # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 # You should have received a copy of the GNU General Public License along
15 # with this program; if not, write to the Free Software Foundation, Inc., 59
16 # Temple Place - Suite 330, Boston, MA 02111-1307, USA.
24 if not hasattr(zypp, 'PoolQuery') or \
25 not hasattr(zypp.RepoManager, 'loadSolvFile'):
26 raise ImportError("python-zypp in host system cannot support PoolQuery or "
27 "loadSolvFile interface, please update it to enhanced "
28 "version which can be found in download.tizen.org/tools")
31 from mic.kickstart import ksparser
32 from mic.utils import misc, rpmmisc, runner, fs_related
33 from mic.utils.grabber import myurlgrab, TextProgress
34 from mic.utils.proxy import get_proxy_for
35 from mic.utils.errors import CreatorError, RepoError, RpmError
36 from mic.imager.baseimager import BaseImageCreator
42 self.mirrorlist = None
44 self.proxy_username = None
45 self.proxy_password = None
49 self.autorefresh = True
50 self.keeppackages = True
53 from mic.pluginbase import BackendPlugin
54 class Zypp(BackendPlugin):
57 def __init__(self, target_arch, instroot, cachedir):
58 self.cachedir = cachedir
59 self.instroot = instroot
60 self.target_arch = target_arch
62 self.__pkgs_license = {}
63 self.__pkgs_content = {}
64 self.__pkgs_vcsinfo = {}
68 self.repo_manager = None
69 self.repo_manager_options = None
76 self.probFilterFlags = [ rpm.RPMPROB_FILTER_OLDPACKAGE,
77 rpm.RPMPROB_FILTER_REPLACEPKG ]
79 self.has_prov_query = True
80 self.install_debuginfo = False
82 def doFileLogSetup(self, uid, logfile):
83 # don't do the file log for the livecd as it can lead to open fds
84 # being left and an inability to clean up after ourself
101 if not os.path.exists("/etc/fedora-release") and \
102 not os.path.exists("/etc/meego-release"):
103 for i in range(3, os.sysconf("SC_OPEN_MAX")):
112 def _cleanupRpmdbLocks(self, installroot):
113 # cleans up temporary files left by bdb so that differing
114 # versions of rpm don't cause problems
116 for f in glob.glob(installroot + "/var/lib/rpm/__db*"):
119 def _cleanupZyppJunk(self, installroot):
121 shutil.rmtree(os.path.join(installroot, '.zypp'))
126 self._cleanupRpmdbLocks(self.instroot)
128 def whatObsolete(self, pkg):
129 query = zypp.PoolQuery()
130 query.addKind(zypp.ResKind.package)
131 query.addAttribute(zypp.SolvAttr.obsoletes, pkg)
132 query.setMatchExact()
133 for pi in query.queryResults(self.Z.pool()):
137 def _zyppQueryPackage(self, pkg):
138 query = zypp.PoolQuery()
139 query.addKind(zypp.ResKind.package)
140 query.addAttribute(zypp.SolvAttr.name,pkg)
141 query.setMatchExact()
142 for pi in query.queryResults(self.Z.pool()):
146 def _splitPkgString(self, pkg):
147 sp = pkg.rsplit(".",1)
152 sysarch = zypp.Arch(self.target_arch)
153 if not zypp.Arch(arch).compatible_with (sysarch):
158 def selectPackage(self, pkg):
159 """Select a given package or package pattern, can be specified
160 with name.arch or name* or *name
164 self.__initialize_zypp()
166 def markPoolItem(obs, pi):
168 pi.status().setToBeInstalled (zypp.ResStatus.USER)
170 obs.status().setToBeInstalled (zypp.ResStatus.USER)
173 # compare criterion: arch compatibility first, then repo
174 # priority, and version last
177 if str(a1) != str(a2):
178 if a1.compatible_with(a2):
182 # Priority of a repository is an integer value between 0 (the
183 # highest priority) and 99 (the lowest priority)
184 pr1 = int(p1.repoInfo().priority())
185 pr2 = int(p2.repoInfo().priority())
193 (e1, v1, r1) = map(str, [ed1.epoch(), ed1.version(), ed1.release()])
194 (e2, v2, r2) = map(str, [ed2.epoch(), ed2.version(), ed2.release()])
195 return rpm.labelCompare((e1, v1, r1), (e2, v2, r2))
198 startx = pkg.startswith("*")
199 endx = pkg.endswith("*")
200 ispattern = startx or endx
201 name, arch = self._splitPkgString(pkg)
204 q.addKind(zypp.ResKind.package)
207 if startx and not endx:
208 pattern = '%s$' % (pkg[1:])
209 if endx and not startx:
210 pattern = '^%s' % (pkg[0:-1])
212 pattern = '%s' % (pkg[1:-1])
214 q.addAttribute(zypp.SolvAttr.name,pattern)
218 q.addAttribute(zypp.SolvAttr.name,name)
222 q.addAttribute(zypp.SolvAttr.name,pkg)
225 q.queryResults(self.Z.pool()),
226 cmp=lambda x,y: cmpEVR(zypp.asKindPackage(x), zypp.asKindPackage(y)),
228 item = zypp.asKindPackage(pitem)
229 if item.name() in self.excpkgs.keys() and \
230 self.excpkgs[item.name()] == item.repoInfo().name():
232 if item.name() in self.incpkgs.keys() and \
233 self.incpkgs[item.name()] != item.repoInfo().name():
237 obspkg = self.whatObsolete(item.name())
239 if arch == str(item.arch()):
240 item.status().setToBeInstalled (zypp.ResStatus.USER)
242 markPoolItem(obspkg, pitem)
246 # Can't match using package name, then search from packge
247 # provides infomation
248 if found == False and not ispattern:
249 q.addAttribute(zypp.SolvAttr.provides, pkg)
250 q.addAttribute(zypp.SolvAttr.name,'')
253 q.queryResults(self.Z.pool()),
254 cmp=lambda x,y: cmpEVR(zypp.asKindPackage(x), zypp.asKindPackage(y)),
256 item = zypp.asKindPackage(pitem)
257 if item.name() in self.excpkgs.keys() and \
258 self.excpkgs[item.name()] == item.repoInfo().name():
260 if item.name() in self.incpkgs.keys() and \
261 self.incpkgs[item.name()] != item.repoInfo().name():
265 obspkg = self.whatObsolete(item.name())
266 markPoolItem(obspkg, pitem)
272 raise CreatorError("Unable to find package: %s" % (pkg,))
274 def inDeselectPackages(self, pitem):
275 """check if specified pacakges are in the list of inDeselectPackages
277 item = zypp.asKindPackage(pitem)
279 for pkg in self.to_deselect:
280 startx = pkg.startswith("*")
281 endx = pkg.endswith("*")
282 ispattern = startx or endx
283 pkgname, pkgarch = self._splitPkgString(pkg)
286 if name == pkgname and str(item.arch()) == pkgarch:
292 if startx and name.endswith(pkg[1:]):
294 if endx and name.startswith(pkg[:-1]):
299 def deselectPackage(self, pkg):
300 """collect packages should not be installed"""
301 self.to_deselect.append(pkg)
303 def selectGroup(self, grp, include = ksparser.GROUP_DEFAULT):
305 self.__initialize_zypp()
308 q.addKind(zypp.ResKind.pattern)
309 for pitem in q.queryResults(self.Z.pool()):
310 item = zypp.asKindPattern(pitem)
311 summary = "%s" % item.summary()
312 name = "%s" % item.name()
313 if name == grp or summary == grp:
315 pitem.status().setToBeInstalled (zypp.ResStatus.USER)
319 if include == ksparser.GROUP_REQUIRED:
321 lambda p: self.deselectPackage(p),
322 grp.default_packages.keys())
326 raise CreatorError("Unable to find pattern: %s" % (grp,))
328 def addRepository(self, name,
332 proxy_username = None,
333 proxy_password = None,
340 # TODO: Handle cost attribute for repos
342 if not self.repo_manager:
343 self.__initialize_repo_manager()
345 if not proxy and url:
346 proxy = get_proxy_for(url)
348 repo = RepositoryStub()
352 repo.proxy_username = proxy_username
353 repo.proxy_password = proxy_password
354 repo.ssl_verify = ssl_verify
355 repo.nocache = nocache
356 repo.baseurl.append(url)
359 self.incpkgs[pkg] = name
362 self.excpkgs[pkg] = name
364 # check LICENSE files
365 if not rpmmisc.checkRepositoryEULA(name, repo):
366 msger.warning('skip repo:%s for failed EULA confirmation' % name)
370 repo.mirrorlist = mirrorlist
372 # Enable gpg check for verifying corrupt packages
374 if priority is not None:
375 # priority 0 has issue in RepoInfo.setPriority
376 repo.priority = priority + 1
379 repo_info = zypp.RepoInfo()
380 repo_info.setAlias(repo.name)
381 repo_info.setName(repo.name)
382 repo_info.setEnabled(repo.enabled)
383 repo_info.setAutorefresh(repo.autorefresh)
384 repo_info.setKeepPackages(repo.keeppackages)
385 baseurl = zypp.Url(repo.baseurl[0])
387 baseurl.setQueryParam("ssl_verify", "no")
389 scheme, host, path, parm, query, frag = urlparse.urlparse(proxy)
391 proxyinfo = host.split(":")
395 if len(proxyinfo) > 1:
398 if proxy.startswith("socks") and len(proxy.rsplit(':', 1)) == 2:
399 host = proxy.rsplit(':', 1)[0]
400 port = proxy.rsplit(':', 1)[1]
402 baseurl.setQueryParam ("proxy", host)
403 baseurl.setQueryParam ("proxyport", port)
405 repo.baseurl[0] = baseurl.asCompleteString()
406 self.repos.append(repo)
408 repo_info.addBaseUrl(baseurl)
410 if repo.priority is not None:
411 repo_info.setPriority(repo.priority)
413 # this hack is used to change zypp credential file location
414 # the default one is $HOME/.zypp, which cause conflicts when
415 # installing some basic packages, and the location doesn't
416 # have any interface actually, so use a tricky way anyway
418 if 'HOME' in os.environ:
419 homedir = os.environ['HOME']
420 os.environ['HOME'] = '/'
422 os.environ['HOME'] = '/'
424 self.repo_manager.addRepository(repo_info)
426 # save back the $HOME env
428 os.environ['HOME'] = homedir
430 del os.environ['HOME']
432 self.__build_repo_cache(name)
434 except RuntimeError, e:
435 raise CreatorError(str(e))
437 msger.verbose('repo: %s was added' % name)
440 def installHasFile(self, file):
443 def preInstall(self, pkg):
444 self.pre_pkgs.append(pkg)
446 def runInstall(self, checksize = 0):
447 os.environ["HOME"] = "/"
448 os.environ["LD_PRELOAD"] = ""
449 self.buildTransaction()
451 todo = zypp.GetResolvablesToInsDel(self.Z.pool())
452 installed_pkgs = todo._toInstall
454 for pitem in installed_pkgs:
455 if not zypp.isKindPattern(pitem) and \
456 not self.inDeselectPackages(pitem):
457 item = zypp.asKindPackage(pitem)
460 if not self.install_debuginfo or str(item.arch()) == "noarch":
463 dipkg = self._zyppQueryPackage("%s-debuginfo" % item.name())
465 ditem = zypp.asKindPackage(dipkg)
468 msger.warning("No debuginfo rpm found for: %s" \
471 # record all pkg and the content
472 localpkgs = self.localpkgs.keys()
475 if pkg.name() in localpkgs:
476 hdr = rpmmisc.readRpmHeader(self.ts, self.localpkgs[pkg.name()])
477 pkg_long_name = misc.RPM_FMT % {
480 'version': hdr['version'],
481 'release': hdr['release']
483 license = hdr['license']
486 pkg_long_name = misc.RPM_FMT % {
489 'version': pkg.edition().version(),
490 'release': pkg.edition().release()
493 license = pkg.license()
495 if license in self.__pkgs_license.keys():
496 self.__pkgs_license[license].append(pkg_long_name)
498 self.__pkgs_license[license] = [pkg_long_name]
500 total_count = len(dlpkgs)
502 download_total_size = sum(map(lambda x: int(x.downloadSize()), dlpkgs))
503 localpkgs = self.localpkgs.keys()
505 msger.info("Checking packages cached ...")
507 # Check if it is cached locally
508 if po.name() in localpkgs:
511 local = self.getLocalPkgPath(po)
512 name = str(po.repoInfo().name())
514 repo = filter(lambda r: r.name == name, self.repos)[0]
517 nocache = repo.nocache if repo else False
519 if os.path.exists(local):
520 if nocache or self.checkPkg(local) !=0:
523 download_total_size -= int(po.downloadSize())
525 cache_avail_size = misc.get_filesystem_avail(self.cachedir)
526 if cache_avail_size < download_total_size:
527 raise CreatorError("No enough space used for downloading.")
529 # record the total size of installed pkgs
530 install_total_size = sum(map(lambda x: int(x.installSize()), dlpkgs))
531 # check needed size before actually download and install
533 # FIXME: for multiple partitions for loop type, check fails
534 # skip the check temporarily
535 #if checksize and install_total_size > checksize:
536 # raise CreatorError("No enough space used for installing, "
537 # "please resize partition size in ks file")
539 download_count = total_count - cached_count
540 msger.info("Packages: %d Total, %d Cached, %d Missed" \
541 % (total_count, cached_count, download_count))
544 if download_count > 0:
545 msger.info("Downloading packages ...")
546 self.downloadPkgs(dlpkgs, download_count)
548 self.installPkgs(dlpkgs)
550 except (RepoError, RpmError):
553 raise CreatorError("Package installation failed: %s" % (e,))
555 def getVcsInfo(self):
556 if self.__pkgs_vcsinfo:
560 self.__initialize_transaction()
562 mi = self.ts.dbMatch()
564 lname = misc.RPM_FMT % {
567 'version': hdr['version'],
568 'release': hdr['release']
571 self.__pkgs_vcsinfo[lname] = hdr['VCS']
573 # if rpm not support VCS, set to None
574 self.__pkgs_vcsinfo[lname] = None
576 return self.__pkgs_vcsinfo
578 def getAllContent(self):
579 if self.__pkgs_content:
580 return self.__pkgs_content
583 self.__initialize_transaction()
585 mi = self.ts.dbMatch()
587 lname = misc.RPM_FMT % {
590 'version': hdr['version'],
591 'release': hdr['release']
593 self.__pkgs_content[lname] = hdr['FILENAMES']
595 return self.__pkgs_content
597 def getPkgsLicense(self):
598 return self.__pkgs_license
600 def getFilelist(self, pkgname):
605 self.__initialize_transaction()
607 mi = self.ts.dbMatch('name', pkgname)
609 return header['FILENAMES']
611 def __initialize_repo_manager(self):
612 if self.repo_manager:
615 # Clean up repo metadata
616 shutil.rmtree(self.cachedir + "/etc", ignore_errors = True)
617 shutil.rmtree(self.cachedir + "/solv", ignore_errors = True)
618 shutil.rmtree(self.cachedir + "/raw", ignore_errors = True)
620 zypp.KeyRing.setDefaultAccept( zypp.KeyRing.ACCEPT_UNSIGNED_FILE
621 | zypp.KeyRing.ACCEPT_VERIFICATION_FAILED
622 | zypp.KeyRing.ACCEPT_UNKNOWNKEY
623 | zypp.KeyRing.TRUST_KEY_TEMPORARILY
626 self.repo_manager_options = \
627 zypp.RepoManagerOptions(zypp.Pathname(self.instroot))
629 self.repo_manager_options.knownReposPath = \
630 zypp.Pathname(self.cachedir + "/etc/zypp/repos.d")
632 self.repo_manager_options.repoCachePath = \
633 zypp.Pathname(self.cachedir)
635 self.repo_manager_options.repoRawCachePath = \
636 zypp.Pathname(self.cachedir + "/raw")
638 self.repo_manager_options.repoSolvCachePath = \
639 zypp.Pathname(self.cachedir + "/solv")
641 self.repo_manager_options.repoPackagesCachePath = \
642 zypp.Pathname(self.cachedir + "/packages")
644 self.repo_manager = zypp.RepoManager(self.repo_manager_options)
646 def __build_repo_cache(self, name):
647 repo = self.repo_manager.getRepositoryInfo(name)
648 if self.repo_manager.isCached(repo) or not repo.enabled():
651 msger.info('Refreshing repository: %s ...' % name)
652 self.repo_manager.buildCache(repo, zypp.RepoManager.BuildIfNeeded)
654 def __initialize_zypp(self):
658 zconfig = zypp.ZConfig_instance()
660 # Set system architecture
662 zconfig.setSystemArchitecture(zypp.Arch(self.target_arch))
664 msger.info("zypp architecture is <%s>" % zconfig.systemArchitecture())
666 # repoPackagesCachePath is corrected by this
667 self.repo_manager = zypp.RepoManager(self.repo_manager_options)
668 repos = self.repo_manager.knownRepositories()
670 if not repo.enabled():
672 self.repo_manager.loadFromCache(repo)
674 self.Z = zypp.ZYppFactory_instance().getZYpp()
675 self.Z.initializeTarget(zypp.Pathname(self.instroot))
676 self.Z.target().load()
678 def buildTransaction(self):
679 if not self.Z.resolver().resolvePool():
680 probs = self.Z.resolver().problems()
682 for problem in probs:
683 msger.warning("repo problem: %s, %s" \
684 % (problem.description().decode("utf-8"),
685 problem.details().decode("utf-8")))
687 raise RepoError("found %d resolver problem, abort!" \
690 def getLocalPkgPath(self, po):
691 repoinfo = po.repoInfo()
692 cacheroot = repoinfo.packagesPath()
693 location= po.location()
694 rpmpath = str(location.filename())
695 pkgpath = "%s/%s" % (cacheroot, os.path.basename(rpmpath))
698 def installLocal(self, pkg, po=None, updateonly=False):
700 self.__initialize_transaction()
702 solvfile = "%s/.solv" % (self.cachedir)
704 rc, out = runner.runtool([fs_related.find_binary_path("rpms2solv"),
707 f = open(solvfile, "w+")
711 warnmsg = self.repo_manager.loadSolvFile(solvfile,
712 os.path.basename(pkg))
714 msger.warning(warnmsg)
718 msger.warning('Can not get %s solv data.' % pkg)
720 hdr = rpmmisc.readRpmHeader(self.ts, pkg)
721 arch = zypp.Arch(hdr['arch'])
722 sysarch = zypp.Arch(self.target_arch)
724 if arch.compatible_with (sysarch):
725 pkgname = hdr['name']
726 self.localpkgs[pkgname] = pkg
727 self.selectPackage(pkgname)
728 msger.info("Marking %s to be installed" % (pkg))
731 msger.warning("Cannot add package %s to transaction. "
732 "Not a compatible architecture: %s" \
733 % (pkg, hdr['arch']))
735 def downloadPkgs(self, package_objects, count):
736 localpkgs = self.localpkgs.keys()
737 progress_obj = TextProgress(count)
739 for po in package_objects:
740 if po.name() in localpkgs:
743 filename = self.getLocalPkgPath(po)
744 if os.path.exists(filename):
745 if self.checkPkg(filename) == 0:
748 dirn = os.path.dirname(filename)
749 if not os.path.exists(dirn):
752 url = self.get_url(po)
753 proxies = self.get_proxies(po)
756 filename = myurlgrab(url, filename, proxies, progress_obj)
761 def preinstallPkgs(self):
763 self.__initialize_transaction()
766 cb = rpmmisc.RPMInstallCallback(self.ts_pre)
767 cb.headmsg = "Preinstall"
768 installlogfile = "%s/__catched_stderr.buf" % (self.instroot)
770 # start to catch stderr output from librpm
771 msger.enable_logstderr(installlogfile)
773 errors = self.ts_pre.run(cb.callback, '')
775 msger.disable_logstderr()
776 self.ts_pre.closeDB()
779 if errors is not None:
781 msger.warning('scriptlet or other non-fatal errors occurred '
782 'during transaction.')
787 raise RepoError('Could not run transaction.')
789 def installPkgs(self, package_objects):
791 self.__initialize_transaction()
794 self._cleanupRpmdbLocks(self.instroot)
795 self._cleanupZyppJunk(self.instroot)
798 for flag in self.probFilterFlags:
800 self.ts.setProbFilter(probfilter)
801 self.ts_pre.setProbFilter(probfilter)
803 localpkgs = self.localpkgs.keys()
805 for po in package_objects:
807 if pkgname in localpkgs:
808 rpmpath = self.localpkgs[pkgname]
810 rpmpath = self.getLocalPkgPath(po)
812 if not os.path.exists(rpmpath):
813 # Maybe it is a local repo
814 rpmuri = self.get_url(po)
815 if rpmuri.startswith("file:/"):
818 if not os.path.exists(rpmpath):
819 raise RpmError("Error: %s doesn't exist" % rpmpath)
821 h = rpmmisc.readRpmHeader(self.ts, rpmpath)
823 if pkgname in self.pre_pkgs:
824 msger.verbose("pre-install package added: %s" % pkgname)
825 self.ts_pre.addInstall(h, rpmpath, 'u')
827 self.ts.addInstall(h, rpmpath, 'u')
829 unresolved_dependencies = self.ts.check()
830 if not unresolved_dependencies:
832 self.preinstallPkgs()
835 cb = rpmmisc.RPMInstallCallback(self.ts)
836 installlogfile = "%s/__catched_stderr.buf" % (self.instroot)
838 # start to catch stderr output from librpm
839 msger.enable_logstderr(installlogfile)
841 errors = self.ts.run(cb.callback, '')
843 msger.disable_logstderr()
847 if errors is not None:
849 msger.warning('scriptlet or other non-fatal errors occurred '
850 'during transaction.')
855 raise RepoError('Could not run transaction.')
858 for pkg, need, needflags, sense, key in unresolved_dependencies:
859 package = '-'.join(pkg)
861 if needflags == rpm.RPMSENSE_LESS:
862 deppkg = ' < '.join(need)
863 elif needflags == rpm.RPMSENSE_EQUAL:
864 deppkg = ' = '.join(need)
865 elif needflags == rpm.RPMSENSE_GREATER:
866 deppkg = ' > '.join(need)
868 deppkg = '-'.join(need)
870 if sense == rpm.RPMDEP_SENSE_REQUIRES:
871 msger.warning("[%s] Requires [%s], which is not provided" \
874 elif sense == rpm.RPMDEP_SENSE_CONFLICTS:
875 msger.warning("[%s] Conflicts with [%s]" %(package,deppkg))
877 raise RepoError("Unresolved dependencies, transaction failed.")
879 def __initialize_transaction(self):
881 self.ts = rpm.TransactionSet(self.instroot)
882 # Set to not verify DSA signatures.
883 self.ts.setVSFlags(rpm._RPMVSF_NOSIGNATURES|rpm._RPMVSF_NODIGESTS)
886 self.ts_pre = rpm.TransactionSet(self.instroot)
887 # Just unpack the files, don't run scripts
888 self.ts_pre.setFlags(rpm.RPMTRANS_FLAG_ALLFILES | rpm.RPMTRANS_FLAG_NOSCRIPTS)
889 # Set to not verify DSA signatures.
890 self.ts_pre.setVSFlags(rpm._RPMVSF_NOSIGNATURES|rpm._RPMVSF_NODIGESTS)
892 def checkPkg(self, pkg):
894 if not os.path.exists(pkg):
896 ret = rpmmisc.checkRpmIntegrity('rpm', pkg)
898 msger.warning("package %s is damaged: %s" \
899 % (os.path.basename(pkg), pkg))
903 def _add_prob_flags(self, *flags):
905 if flag not in self.probFilterFlags:
906 self.probFilterFlags.append(flag)
908 def get_proxies(self, pobj):
914 repoinfo = pobj.repoInfo()
915 reponame = "%s" % repoinfo.name()
916 repos = filter(lambda r: r.name == reponame, self.repos)
917 repourl = str(repoinfo.baseUrls()[0])
920 proxy = repos[0].proxy
922 proxy = get_proxy_for(repourl)
924 proxies = {str(repourl.split(':')[0]): str(proxy)}
928 def get_url(self, pobj):
932 name = str(pobj.repoInfo().name())
934 repo = filter(lambda r: r.name == name, self.repos)[0]
938 baseurl = repo.baseurl[0]
940 index = baseurl.find("?")
942 baseurl = baseurl[:index]
944 location = pobj.location()
945 location = str(location.filename())
946 if location.startswith("./"):
947 location = location[2:]
949 return os.path.join(baseurl, location)
951 def package_url(self, pkgname):
956 (e1, v1, r1) = map(str, [ed1.epoch(), ed1.version(), ed1.release()])
957 (e2, v2, r2) = map(str, [ed2.epoch(), ed2.version(), ed2.release()])
958 return rpm.labelCompare((e1, v1, r1), (e2, v2, r2))
961 self.__initialize_zypp()
964 q.addKind(zypp.ResKind.package)
966 q.addAttribute(zypp.SolvAttr.name, pkgname)
967 items = sorted(q.queryResults(self.Z.pool()),
968 cmp=lambda x,y: cmpEVR(zypp.asKindPackage(x), zypp.asKindPackage(y)),
972 item = zypp.asKindPackage(items[0])
973 url = self.get_url(item)
974 proxies = self.get_proxies(item)
975 return (url, proxies)