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
77 self.probFilterFlags = [ rpm.RPMPROB_FILTER_OLDPACKAGE,
78 rpm.RPMPROB_FILTER_REPLACEPKG ]
80 self.has_prov_query = True
81 self.install_debuginfo = False
82 # this can't be changed, it is used by zypp
83 self.tmp_file_path = '/var/tmp'
85 def doFileLogSetup(self, uid, logfile):
86 # don't do the file log for the livecd as it can lead to open fds
87 # being left and an inability to clean up after ourself
107 def _cleanupRpmdbLocks(self, installroot):
108 # cleans up temporary files left by bdb so that differing
109 # versions of rpm don't cause problems
111 for f in glob.glob(installroot + "/var/lib/rpm/__db*"):
114 def _cleanupZyppJunk(self, installroot):
116 shutil.rmtree(os.path.join(installroot, '.zypp'))
121 self._cleanupRpmdbLocks(self.instroot)
122 # '/var/tmp' is used by zypp to build cache, so make sure
124 if not os.path.exists(self.tmp_file_path ):
125 os.makedirs(self.tmp_file_path)
127 def whatObsolete(self, pkg):
128 query = zypp.PoolQuery()
129 query.addKind(zypp.ResKind.package)
130 query.addDependency(zypp.SolvAttr.obsoletes, pkg.name(), pkg.edition())
131 query.setMatchExact()
132 for pi in query.queryResults(self.Z.pool()):
136 def _zyppQueryPackage(self, pkg):
137 query = zypp.PoolQuery()
138 query.addKind(zypp.ResKind.package)
139 query.addAttribute(zypp.SolvAttr.name, pkg)
140 query.setMatchExact()
141 for pi in query.queryResults(self.Z.pool()):
145 def _splitPkgString(self, pkg):
146 sp = pkg.rsplit(".", 1)
151 sysarch = zypp.Arch(self.target_arch)
152 if not zypp.Arch(arch).compatible_with (sysarch):
157 def selectPackage(self, pkg):
158 """Select a given package or package pattern, can be specified
159 with name.arch or name* or *name
163 self.__initialize_zypp()
165 def markPoolItem(obs, pi):
167 pi.status().setToBeInstalled (zypp.ResStatus.USER)
169 obs.status().setToBeInstalled (zypp.ResStatus.USER)
172 # compare criterion: arch compatibility first, then repo
173 # priority, and version last
176 if str(a1) != str(a2):
177 if a1.compatible_with(a2):
181 # Priority of a repository is an integer value between 0 (the
182 # highest priority) and 99 (the lowest priority)
183 pr1 = int(p1.repoInfo().priority())
184 pr2 = int(p2.repoInfo().priority())
192 (e1, v1, r1) = map(str, [ed1.epoch(), ed1.version(), ed1.release()])
193 (e2, v2, r2) = map(str, [ed2.epoch(), ed2.version(), ed2.release()])
194 return rpm.labelCompare((e1, v1, r1), (e2, v2, r2))
197 startx = pkg.startswith("*")
198 endx = pkg.endswith("*")
199 ispattern = startx or endx
200 name, arch = self._splitPkgString(pkg)
203 q.addKind(zypp.ResKind.package)
206 if startx and not endx:
207 pattern = '%s$' % (pkg[1:])
208 if endx and not startx:
209 pattern = '^%s' % (pkg[0:-1])
211 pattern = '%s' % (pkg[1:-1])
213 q.addAttribute(zypp.SolvAttr.name, pattern)
217 q.addAttribute(zypp.SolvAttr.name, name)
221 q.addAttribute(zypp.SolvAttr.name, pkg)
224 q.queryResults(self.Z.pool()),
225 cmp=lambda x,y: cmpEVR(zypp.asKindPackage(x), zypp.asKindPackage(y)),
227 item = zypp.asKindPackage(pitem)
228 if item.name() in self.excpkgs.keys() and \
229 self.excpkgs[item.name()] == item.repoInfo().name():
231 if item.name() in self.incpkgs.keys() and \
232 self.incpkgs[item.name()] != item.repoInfo().name():
236 obspkg = self.whatObsolete(item)
238 if arch == str(item.arch()):
239 item.status().setToBeInstalled (zypp.ResStatus.USER)
241 markPoolItem(obspkg, pitem)
245 # Can't match using package name, then search from packge
246 # provides infomation
247 if found == False and not ispattern:
248 q.addAttribute(zypp.SolvAttr.provides, pkg)
249 q.addAttribute(zypp.SolvAttr.name,'')
252 q.queryResults(self.Z.pool()),
253 cmp=lambda x,y: cmpEVR(zypp.asKindPackage(x), zypp.asKindPackage(y)),
255 item = zypp.asKindPackage(pitem)
256 if item.name() in self.excpkgs.keys() and \
257 self.excpkgs[item.name()] == item.repoInfo().name():
259 if item.name() in self.incpkgs.keys() and \
260 self.incpkgs[item.name()] != item.repoInfo().name():
264 obspkg = self.whatObsolete(item)
265 markPoolItem(obspkg, pitem)
271 raise CreatorError("Unable to find package: %s" % (pkg,))
273 def inDeselectPackages(self, pitem):
274 """check if specified pacakges are in the list of inDeselectPackages
276 item = zypp.asKindPackage(pitem)
278 for pkg in self.to_deselect:
279 startx = pkg.startswith("*")
280 endx = pkg.endswith("*")
281 ispattern = startx or endx
282 pkgname, pkgarch = self._splitPkgString(pkg)
285 if name == pkgname and str(item.arch()) == pkgarch:
291 if startx and name.endswith(pkg[1:]):
293 if endx and name.startswith(pkg[:-1]):
298 def deselectPackage(self, pkg):
299 """collect packages should not be installed"""
300 self.to_deselect.append(pkg)
302 def selectGroup(self, grp, include = ksparser.GROUP_DEFAULT):
304 self.__initialize_zypp()
307 q.addKind(zypp.ResKind.pattern)
308 for pitem in q.queryResults(self.Z.pool()):
309 item = zypp.asKindPattern(pitem)
310 summary = "%s" % item.summary()
311 name = "%s" % item.name()
312 if name == grp or summary == grp:
314 pitem.status().setToBeInstalled (zypp.ResStatus.USER)
318 if include == ksparser.GROUP_REQUIRED:
320 lambda p: self.deselectPackage(p),
321 grp.default_packages.keys())
325 raise CreatorError("Unable to find pattern: %s" % (grp,))
327 def addRepository(self, name,
331 proxy_username = None,
332 proxy_password = None,
339 # TODO: Handle cost attribute for repos
341 if not self.repo_manager:
342 self.__initialize_repo_manager()
344 if not proxy and url:
345 proxy = get_proxy_for(url)
347 repo = RepositoryStub()
351 repo.proxy_username = proxy_username
352 repo.proxy_password = proxy_password
353 repo.ssl_verify = ssl_verify
354 repo.nocache = nocache
355 repo.baseurl.append(url)
358 self.incpkgs[pkg] = name
361 self.excpkgs[pkg] = name
364 repo.mirrorlist = mirrorlist
366 # Enable gpg check for verifying corrupt packages
368 if priority is not None:
369 # priority 0 has issue in RepoInfo.setPriority
370 repo.priority = priority + 1
373 repo_info = zypp.RepoInfo()
374 repo_info.setAlias(repo.name)
375 repo_info.setName(repo.name)
376 repo_info.setEnabled(repo.enabled)
377 repo_info.setAutorefresh(repo.autorefresh)
378 repo_info.setKeepPackages(repo.keeppackages)
379 baseurl = zypp.Url(repo.baseurl[0].full)
381 baseurl.setQueryParam("ssl_verify", "no")
383 host = urlparse.urlparse(proxy)[1]
384 # scheme, host, path, parm, query, frag = urlparse.urlparse(proxy)
386 proxyinfo = host.rsplit(":", 1)
390 if len(proxyinfo) > 1:
393 if proxy.startswith("socks") and len(proxy.rsplit(':', 1)) == 2:
394 host = proxy.rsplit(':', 1)[0]
395 port = proxy.rsplit(':', 1)[1]
397 # parse user/pass from proxy host
398 proxyinfo = host.rsplit("@", 1)
399 if len(proxyinfo) == 2:
401 # Known Issue: If password contains ":", which should be
402 # quoted, for example, use '123%3Aabc' instead of 123:abc
403 userpassinfo = proxyinfo[0].rsplit(":", 1)
404 if len(userpassinfo) == 2:
405 proxy_username = userpassinfo[0]
406 proxy_password = userpassinfo[1]
407 elif len(userpassinfo) == 1:
408 proxy_username = userpassinfo[0]
410 baseurl.setQueryParam ("proxy", host)
411 baseurl.setQueryParam ("proxyport", port)
413 baseurl.setQueryParam ("proxyuser", proxy_username)
415 baseurl.setQueryParam ("proxypass", proxy_password)
417 baseurl.setQueryParam ("proxy", "_none_")
419 self.repos.append(repo)
421 repo_info.addBaseUrl(baseurl)
423 if repo.priority is not None:
424 repo_info.setPriority(repo.priority)
426 # this hack is used to change zypp credential file location
427 # the default one is $HOME/.zypp, which cause conflicts when
428 # installing some basic packages, and the location doesn't
429 # have any interface actually, so use a tricky way anyway
431 if 'HOME' in os.environ:
432 homedir = os.environ['HOME']
433 os.environ['HOME'] = '/'
435 os.environ['HOME'] = '/'
437 self.repo_manager.addRepository(repo_info)
439 # save back the $HOME env
441 os.environ['HOME'] = homedir
443 del os.environ['HOME']
445 self.__build_repo_cache(name)
447 except RuntimeError, e:
448 raise CreatorError(str(e))
450 msger.verbose('repo: %s was added' % name)
453 def installHasFile(self, file):
456 def preInstall(self, pkg):
457 self.pre_pkgs.append(pkg)
459 def checkPackage(self, pkg):
460 self.check_pkgs.append(pkg)
462 def runInstall(self, checksize = 0):
463 os.environ["HOME"] = "/"
464 os.environ["LD_PRELOAD"] = ""
465 self.buildTransaction()
467 todo = zypp.GetResolvablesToInsDel(self.Z.pool())
468 installed_pkgs = todo._toInstall
471 for pitem in installed_pkgs:
472 if not zypp.isKindPattern(pitem) and \
473 not self.inDeselectPackages(pitem):
474 item = zypp.asKindPackage(pitem)
477 if item.name() in self.check_pkgs:
478 self.check_pkgs.remove(item.name())
480 if not self.install_debuginfo or str(item.arch()) == "noarch":
483 dipkg = self._zyppQueryPackage("%s-debuginfo" % item.name())
485 ditem = zypp.asKindPackage(dipkg)
488 msger.warning("No debuginfo rpm found for: %s" \
492 raise CreatorError('Packages absent in image: %s' % ','.join(self.check_pkgs))
494 # record all pkg and the content
495 localpkgs = self.localpkgs.keys()
498 if pkg.name() in localpkgs:
499 hdr = rpmmisc.readRpmHeader(self.ts, self.localpkgs[pkg.name()])
500 pkg_long_name = misc.RPM_FMT % {
503 'version': hdr['version'],
504 'release': hdr['release']
506 license = hdr['license']
509 pkg_long_name = misc.RPM_FMT % {
512 'version': pkg.edition().version(),
513 'release': pkg.edition().release()
516 license = pkg.license()
518 if license in self.__pkgs_license.keys():
519 self.__pkgs_license[license].append(pkg_long_name)
521 self.__pkgs_license[license] = [pkg_long_name]
523 total_count = len(dlpkgs)
525 download_total_size = sum(map(lambda x: int(x.downloadSize()), dlpkgs))
526 localpkgs = self.localpkgs.keys()
528 msger.info("Checking packages cached ...")
530 # Check if it is cached locally
531 if po.name() in localpkgs:
534 local = self.getLocalPkgPath(po)
535 name = str(po.repoInfo().name())
537 repo = filter(lambda r: r.name == name, self.repos)[0]
540 nocache = repo.nocache if repo else False
542 if os.path.exists(local):
543 if nocache or self.checkPkg(local) !=0:
546 download_total_size -= int(po.downloadSize())
548 cache_avail_size = misc.get_filesystem_avail(self.cachedir)
549 if cache_avail_size < download_total_size:
550 raise CreatorError("No enough space used for downloading.")
552 # record the total size of installed pkgs
553 install_total_size = sum(map(lambda x: int(x.installSize()), dlpkgs))
554 # check needed size before actually download and install
556 # FIXME: for multiple partitions for loop type, check fails
557 # skip the check temporarily
558 #if checksize and install_total_size > checksize:
559 # raise CreatorError("No enough space used for installing, "
560 # "please resize partition size in ks file")
562 download_count = total_count - cached_count
563 msger.info("Packages: %d Total, %d Cached, %d Missed" \
564 % (total_count, cached_count, download_count))
567 if download_count > 0:
568 msger.info("Downloading packages ...")
569 self.downloadPkgs(dlpkgs, download_count)
571 self.installPkgs(dlpkgs)
573 except (RepoError, RpmError):
576 raise CreatorError("Package installation failed: %s" % (e,))
578 def getVcsInfo(self):
579 if self.__pkgs_vcsinfo:
583 self.__initialize_transaction()
585 mi = self.ts.dbMatch()
587 lname = misc.RPM_FMT % {
590 'version': hdr['version'],
591 'release': hdr['release']
594 self.__pkgs_vcsinfo[lname] = hdr['VCS']
596 # if rpm not support VCS, set to None
597 self.__pkgs_vcsinfo[lname] = None
599 return self.__pkgs_vcsinfo
601 def getAllContent(self):
602 if self.__pkgs_content:
603 return self.__pkgs_content
606 self.__initialize_transaction()
608 mi = self.ts.dbMatch()
610 lname = misc.RPM_FMT % {
613 'version': hdr['version'],
614 'release': hdr['release']
616 self.__pkgs_content[lname] = hdr['FILENAMES']
618 return self.__pkgs_content
620 def getPkgsLicense(self):
621 return self.__pkgs_license
623 def getFilelist(self, pkgname):
628 self.__initialize_transaction()
630 mi = self.ts.dbMatch('name', pkgname)
632 return header['FILENAMES']
634 def __initialize_repo_manager(self):
635 if self.repo_manager:
638 # Clean up repo metadata
639 shutil.rmtree(self.cachedir + "/etc", ignore_errors = True)
640 shutil.rmtree(self.cachedir + "/solv", ignore_errors = True)
641 shutil.rmtree(self.cachedir + "/raw", ignore_errors = True)
643 zypp.KeyRing.setDefaultAccept( zypp.KeyRing.ACCEPT_UNSIGNED_FILE
644 | zypp.KeyRing.ACCEPT_VERIFICATION_FAILED
645 | zypp.KeyRing.ACCEPT_UNKNOWNKEY
646 | zypp.KeyRing.TRUST_KEY_TEMPORARILY
649 self.repo_manager_options = \
650 zypp.RepoManagerOptions(zypp.Pathname(self.instroot))
652 self.repo_manager_options.knownReposPath = \
653 zypp.Pathname(self.cachedir + "/etc/zypp/repos.d")
655 self.repo_manager_options.repoCachePath = \
656 zypp.Pathname(self.cachedir)
658 self.repo_manager_options.repoRawCachePath = \
659 zypp.Pathname(self.cachedir + "/raw")
661 self.repo_manager_options.repoSolvCachePath = \
662 zypp.Pathname(self.cachedir + "/solv")
664 self.repo_manager_options.repoPackagesCachePath = \
665 zypp.Pathname(self.cachedir + "/packages")
667 self.repo_manager = zypp.RepoManager(self.repo_manager_options)
669 def __build_repo_cache(self, name):
670 repo = self.repo_manager.getRepositoryInfo(name)
671 if self.repo_manager.isCached(repo) or not repo.enabled():
674 msger.info('Refreshing repository: %s ...' % name)
675 self.repo_manager.buildCache(repo, zypp.RepoManager.BuildIfNeeded)
677 def __initialize_zypp(self):
681 zconfig = zypp.ZConfig_instance()
683 # Set system architecture
685 zconfig.setSystemArchitecture(zypp.Arch(self.target_arch))
687 msger.info("zypp architecture is <%s>" % zconfig.systemArchitecture())
689 # repoPackagesCachePath is corrected by this
690 self.repo_manager = zypp.RepoManager(self.repo_manager_options)
691 repos = self.repo_manager.knownRepositories()
693 if not repo.enabled():
695 self.repo_manager.loadFromCache(repo)
697 self.Z = zypp.ZYppFactory_instance().getZYpp()
698 self.Z.initializeTarget(zypp.Pathname(self.instroot))
699 self.Z.target().load()
701 def buildTransaction(self):
702 if not self.Z.resolver().resolvePool():
703 probs = self.Z.resolver().problems()
705 for problem in probs:
706 msger.warning("repo problem: %s, %s" \
707 % (problem.description().decode("utf-8"),
708 problem.details().decode("utf-8")))
710 raise RepoError("found %d resolver problem, abort!" \
713 def getLocalPkgPath(self, po):
714 repoinfo = po.repoInfo()
715 cacheroot = repoinfo.packagesPath()
716 location = po.location()
717 rpmpath = str(location.filename())
718 pkgpath = "%s/%s" % (cacheroot, os.path.basename(rpmpath))
721 def installLocal(self, pkg, po=None, updateonly=False):
723 self.__initialize_transaction()
725 solvfile = "%s/.solv" % (self.cachedir)
727 rc, out = runner.runtool([fs_related.find_binary_path("rpms2solv"),
730 f = open(solvfile, "w+")
734 warnmsg = self.repo_manager.loadSolvFile(solvfile,
735 os.path.basename(pkg))
737 msger.warning(warnmsg)
741 msger.warning('Can not get %s solv data.' % pkg)
743 hdr = rpmmisc.readRpmHeader(self.ts, pkg)
744 arch = zypp.Arch(hdr['arch'])
745 sysarch = zypp.Arch(self.target_arch)
747 if arch.compatible_with (sysarch):
748 pkgname = hdr['name']
749 self.localpkgs[pkgname] = pkg
750 self.selectPackage(pkgname)
751 msger.info("Marking %s to be installed" % (pkg))
754 msger.warning("Cannot add package %s to transaction. "
755 "Not a compatible architecture: %s" \
756 % (pkg, hdr['arch']))
758 def downloadPkgs(self, package_objects, count):
759 localpkgs = self.localpkgs.keys()
760 progress_obj = TextProgress(count)
762 for po in package_objects:
763 if po.name() in localpkgs:
766 filename = self.getLocalPkgPath(po)
767 if os.path.exists(filename):
768 if self.checkPkg(filename) == 0:
771 dirn = os.path.dirname(filename)
772 if not os.path.exists(dirn):
775 url = self.get_url(po)
776 proxies = self.get_proxies(po)
779 filename = myurlgrab(url.full, filename, proxies, progress_obj)
784 def preinstallPkgs(self):
786 self.__initialize_transaction()
789 cb = rpmmisc.RPMInstallCallback(self.ts_pre)
790 cb.headmsg = "Preinstall"
791 installlogfile = "%s/__catched_stderr.buf" % (self.instroot)
793 # start to catch stderr output from librpm
794 msger.enable_logstderr(installlogfile)
796 errors = self.ts_pre.run(cb.callback, '')
798 msger.disable_logstderr()
799 self.ts_pre.closeDB()
802 if errors is not None:
804 msger.warning('scriptlet or other non-fatal errors occurred '
805 'during transaction.')
810 raise RepoError('Could not run transaction.')
812 def installPkgs(self, package_objects):
814 self.__initialize_transaction()
817 self._cleanupRpmdbLocks(self.instroot)
818 self._cleanupZyppJunk(self.instroot)
821 for flag in self.probFilterFlags:
823 self.ts.setProbFilter(probfilter)
824 self.ts_pre.setProbFilter(probfilter)
826 localpkgs = self.localpkgs.keys()
828 for po in package_objects:
830 if pkgname in localpkgs:
831 rpmpath = self.localpkgs[pkgname]
833 rpmpath = self.getLocalPkgPath(po)
835 if not os.path.exists(rpmpath):
836 # Maybe it is a local repo
837 rpmuri = self.get_url(po)
838 if rpmuri.startswith("file:/"):
841 if not os.path.exists(rpmpath):
842 raise RpmError("Error: %s doesn't exist" % rpmpath)
844 h = rpmmisc.readRpmHeader(self.ts, rpmpath)
846 if pkgname in self.pre_pkgs:
847 msger.verbose("pre-install package added: %s" % pkgname)
848 self.ts_pre.addInstall(h, rpmpath, 'u')
850 self.ts.addInstall(h, rpmpath, 'u')
852 unresolved_dependencies = self.ts.check()
853 if not unresolved_dependencies:
855 self.preinstallPkgs()
858 cb = rpmmisc.RPMInstallCallback(self.ts)
859 installlogfile = "%s/__catched_stderr.buf" % (self.instroot)
861 # start to catch stderr output from librpm
862 msger.enable_logstderr(installlogfile)
864 errors = self.ts.run(cb.callback, '')
866 msger.disable_logstderr()
870 if errors is not None:
872 msger.warning('scriptlet or other non-fatal errors occurred '
873 'during transaction.')
878 raise RepoError('Could not run transaction.')
881 for pkg, need, needflags, sense, key in unresolved_dependencies:
882 package = '-'.join(pkg)
884 if needflags == rpm.RPMSENSE_LESS:
885 deppkg = ' < '.join(need)
886 elif needflags == rpm.RPMSENSE_EQUAL:
887 deppkg = ' = '.join(need)
888 elif needflags == rpm.RPMSENSE_GREATER:
889 deppkg = ' > '.join(need)
891 deppkg = '-'.join(need)
893 if sense == rpm.RPMDEP_SENSE_REQUIRES:
894 msger.warning("[%s] Requires [%s], which is not provided" \
897 elif sense == rpm.RPMDEP_SENSE_CONFLICTS:
898 msger.warning("[%s] Conflicts with [%s]" % (package, deppkg))
900 raise RepoError("Unresolved dependencies, transaction failed.")
902 def __initialize_transaction(self):
904 self.ts = rpm.TransactionSet(self.instroot)
905 # Set to not verify DSA signatures.
906 self.ts.setVSFlags(rpm._RPMVSF_NOSIGNATURES|rpm._RPMVSF_NODIGESTS)
909 self.ts_pre = rpm.TransactionSet(self.instroot)
910 # Just unpack the files, don't run scripts
911 self.ts_pre.setFlags(rpm.RPMTRANS_FLAG_ALLFILES | rpm.RPMTRANS_FLAG_NOSCRIPTS)
912 # Set to not verify DSA signatures.
913 self.ts_pre.setVSFlags(rpm._RPMVSF_NOSIGNATURES|rpm._RPMVSF_NODIGESTS)
915 def checkPkg(self, pkg):
917 if not os.path.exists(pkg):
919 ret = rpmmisc.checkRpmIntegrity('rpm', pkg)
921 msger.warning("package %s is damaged: %s" \
922 % (os.path.basename(pkg), pkg))
926 def _add_prob_flags(self, *flags):
928 if flag not in self.probFilterFlags:
929 self.probFilterFlags.append(flag)
931 def get_proxies(self, pobj):
937 repoinfo = pobj.repoInfo()
938 reponame = "%s" % repoinfo.name()
939 repos = filter(lambda r: r.name == reponame, self.repos)
940 repourl = str(repoinfo.baseUrls()[0])
943 proxy = repos[0].proxy
945 proxy = get_proxy_for(repourl)
947 proxies = {str(repourl.split(':')[0]): str(proxy)}
951 def get_url(self, pobj):
955 name = str(pobj.repoInfo().name())
957 repo = filter(lambda r: r.name == name, self.repos)[0]
961 location = pobj.location()
962 location = str(location.filename())
963 if location.startswith("./"):
964 location = location[2:]
966 return repo.baseurl[0].join(location)
968 def package_url(self, pkgname):
973 (e1, v1, r1) = map(str, [ed1.epoch(), ed1.version(), ed1.release()])
974 (e2, v2, r2) = map(str, [ed2.epoch(), ed2.version(), ed2.release()])
975 return rpm.labelCompare((e1, v1, r1), (e2, v2, r2))
978 self.__initialize_zypp()
981 q.addKind(zypp.ResKind.package)
983 q.addAttribute(zypp.SolvAttr.name, pkgname)
984 items = sorted(q.queryResults(self.Z.pool()),
985 cmp=lambda x,y: cmpEVR(zypp.asKindPackage(x), zypp.asKindPackage(y)),
989 item = zypp.asKindPackage(items[0])
990 url = self.get_url(item)
991 proxies = self.get_proxies(item)
992 return (url, proxies)