Current File : //usr/bin/repotrack
#!/usr/bin/python -tt
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# (c) 2005 seth vidal skvidal at phy.duke.edu


# helps partially track a repo. Let's you download a package + all of its
# deps from any set of repos.
# use: so you can keep current on any given pkg + its deps from another
#      repo w/o enabling that repo in your yum configuration by default
#      also for making partial mirrors that traverse dependencies.

import os
import sys
import shutil
from optparse import OptionParser
from urlparse import urljoin
import logging


import yum
import yum.Errors
import rpmUtils

from yum.misc import getCacheDir
from yum.constants import *
from yum.packages import parsePackages
from yum.packageSack import ListPackageSack

# for yum 2.4.X compat
def sortPkgObj(pkg1 ,pkg2):
    """sorts a list of yum package objects by name"""
    if pkg1.name > pkg2.name:
        return 1
    elif pkg1.name == pkg2.name:
        return 0
    else:
        return -1
        
class RepoTrack(yum.YumBase):
    def __init__(self, opts):
        yum.YumBase.__init__(self)
        self.logger = logging.getLogger("yum.verbose.repotrack")
        self.opts = opts
           
    def findDeps(self, po):
        """Return the dependencies for a given package, as well
           possible solutions for those dependencies.
           
           Returns the deps as a dict  of:
            dict[reqs] = [list of satisfying pkgs]"""
        
   
        reqs = po.returnPrco('requires')
        reqs.sort()
        pkgresults = {}
        
        for req in reqs:
            (r,f,v) = req
            if r.startswith('rpmlib('):
                continue
            
            pkgresults[req] = list(self.whatProvides(r, f, v))

        return pkgresults
    

def more_to_check(unprocessed_pkgs):
    for pkg in unprocessed_pkgs.keys():
        if unprocessed_pkgs[pkg] is not None:
            return True
    
    return False

def parseArgs():
    usage = """
    Repotrack: keep current on any given pkg and its deps. It will download the package(s) you 
               want to track and all of their dependencies
    
    %s [options] package1 [package2] [package..]    """ % sys.argv[0]
    
    parser = OptionParser(usage=usage)
    parser.add_option("-c", "--config", default='/etc/yum.conf',
        help='config file to use (defaults to /etc/yum.conf)')
    parser.add_option("-a", "--arch", default=None,
        help='check as if running the specified arch (default: current arch)')
    parser.add_option("-r", "--repoid", default=[], action='append',
        help="specify repo ids to query, can be specified multiple times (default is all enabled)")
    parser.add_option("--repofrompath", action="append",
        help="specify repoid & paths of additional repositories - unique repoid "
             "and complete path required, can be specified multiple times. "
             "Example: --repofrompath=myrepo,/path/to/repo")
    parser.add_option("-t", "--tempcache", default=False, action="store_true", 
        help="Use a temp dir for storing/accessing yum-cache")
    parser.add_option("-p", "--download_path", dest='destdir', 
        default=os.getcwd(), help="Path to download packages to")
    parser.add_option("-u", "--urls", default=False, action="store_true", 
        help="Just list urls of what would be downloaded, don't download")
    parser.add_option("-n", "--newest", default=True, action="store_false", 
        help="Toggle downloading only the newest packages(defaults to newest-only)")
    parser.add_option("-q", "--quiet", default=False, action="store_true", 
        help="Output as little as possible")
                          
    (opts, args) = parser.parse_args()
    return (opts, args)


def main():
# TODO/FIXME
# gpg/sha checksum them

    (opts, user_pkg_list) = parseArgs()
    
    if len(user_pkg_list) == 0:
        print >> sys.stderr, "Error: no packages specified to parse"
        sys.exit(1)
        
    if not os.path.exists(opts.destdir) and not opts.urls:
        try:
            os.makedirs(opts.destdir)
        except OSError, e:
            print >> sys.stderr, "Error: Cannot create destination dir %s" % opts.destdir
            sys.exit(1)
    
    if not os.access(opts.destdir, os.W_OK) and not opts.urls:
        print >> sys.stderr, "Error: Cannot write to  destination dir %s" % opts.destdir
        sys.exit(1)
        
    my = RepoTrack(opts=opts)
    my.doConfigSetup(fn=opts.config,init_plugins=False) # init yum, without plugins
    
    if opts.arch:
        archlist = []
        archlist.extend(rpmUtils.arch.getArchList(opts.arch))
    else:
        archlist = rpmUtils.arch.getArchList()

    if opts.repofrompath:
        for repo in opts.repofrompath:
            tmp = tuple(repo.split(','))
            if len(tmp) != 2:
                my.logger.error("Error: Bad repofrompath argument: %s" %repo)
                continue
            repoid, repopath = tmp
            if repopath and repopath[0] == '/':
                baseurl = 'file://' + repopath
            else:
                baseurl = repopath
            try:
                my.add_enable_repo(repoid, baseurls=[baseurl],
                                   basecachedir=my.conf.cachedir,
                                   timestamp_check=False)
            except yum.Errors.DuplicateRepoError, e:
                my.logger.error(e)
                sys.exit(1)
            if not opts.quiet:
                my.logger.info("Added %s repo from %s" % (repoid, repopath))
        
    # do the happy tmpdir thing if we're not root
    if os.geteuid() != 0 or opts.tempcache:
        cachedir = getCacheDir()
        if cachedir is None:
            print >> sys.stderr, "Error: Could not make cachedir, exiting"
            sys.exit(50)
            
        my.repos.setCacheDir(cachedir)

    if len(opts.repoid) > 0:
        myrepos = []
        
        # find the ones we want
        for glob in opts.repoid:
            myrepos.extend(my.repos.findRepos(glob))
        
        # disable them all
        for repo in my.repos.repos.values():
            repo.disable()
        
        # enable the ones we like
        for repo in myrepos:
            repo.enable()
            try:
                my._getSacks(archlist=archlist, thisrepo=repo.id)
            except yum.Errors.RepoError, e:
                my.logger.error(e)
                sys.exit(1)

    try:
        my.doRepoSetup()
        my._getSacks(archlist=archlist)
    except yum.Errors.RepoError, e:
        my.logger.error(e)
        sys.exit(1)
    
    unprocessed_pkgs = {}
    final_pkgs = {}
    pkg_list = []
    
    avail = my.pkgSack.returnPackages()
    for item in user_pkg_list:
        exactmatch, matched, unmatched = parsePackages(avail, [item])
        pkg_list.extend(exactmatch)
        pkg_list.extend(matched)
        if opts.newest:
            this_sack = ListPackageSack()
            this_sack.addList(pkg_list)
            pkg_list = this_sack.returnNewestByNameArch()
            del this_sack
    
    if len(pkg_list) == 0:
        print >> sys.stderr, "Nothing found to download matching packages specified"
        sys.exit(1)
        
    for po in pkg_list:
        unprocessed_pkgs[po.pkgtup] = po
    

    while more_to_check(unprocessed_pkgs):
    
        for pkgtup in unprocessed_pkgs.keys():
            if unprocessed_pkgs[pkgtup] is None:
                continue

            po = unprocessed_pkgs[pkgtup]
            final_pkgs[po.pkgtup] = po
            
            deps_dict = my.findDeps(po)
            unprocessed_pkgs[po.pkgtup] = None
            for req in deps_dict.keys():
                pkg_list = deps_dict[req]
                if opts.newest:
                    this_sack = ListPackageSack()
                    this_sack.addList(pkg_list)
                    pkg_list = this_sack.returnNewestByNameArch()
                    del this_sack

                for res in pkg_list:
                    if res is not None and res.pkgtup not in unprocessed_pkgs:
                        unprocessed_pkgs[res.pkgtup] = res
    
    
    
    download_list = final_pkgs.values()
    if opts.newest:
        this_sack = ListPackageSack()
        this_sack.addList(download_list)
        download_list = this_sack.returnNewestByNameArch()
        
    download_list.sort(sortPkgObj)
    for pkg in download_list:
        repo = my.repos.getRepo(pkg.repoid)
        remote = pkg.returnSimple('relativepath')
        local = os.path.basename(remote)
        local = os.path.join(opts.destdir, local)
        if (os.path.exists(local) and 
            os.path.getsize(local) == int(pkg.returnSimple('packagesize'))):
            
            if not opts.quiet:
                my.logger.info("%s already exists and appears to be complete" % local)
            continue

        if opts.urls:
            url = urljoin(repo.urls[0],remote)
            print '%s' % url
            continue

        # Disable cache otherwise things won't download
        repo.cache = 0
        if not opts.quiet:        
            my.logger.info('Downloading %s' % os.path.basename(remote))
        pkg.localpath = local # Hack: to set the localpath to what we want.
        path = repo.getPackage(pkg, copy_local=1)

        if not os.path.exists(local) or not os.path.samefile(path, local):
            shutil.copy2(path, local)

if __name__ == "__main__":
    main()
    
blog

blog

Mostbet apk.527

Mostbet apk ▶️ PLAY Содержимое Mostbet Apk: A Comprehensive Guide What is Mostbet Apk? Features of Mostbet Apk Mostbet is a popular online betting and gaming platform that has been gaining traction globally. With its user-friendly interface and wide range of games and betting options, it’s no wonder why many …

Read More »

Krikya Online Casino in Bangladesh Customer Support.632

Krikya Online Casino in Bangladesh – Customer Support ▶️ PLAY Содержимое Responsive and Timely Support Multi-Channel Support Options Knowledge Base and FAQs General Information Games and Services Secure and Confidential Support In the rapidly growing online gaming industry, Krikya Online Casino has established itself as a prominent player in Bangladesh. …

Read More »

Mostbet AZ – bukmeker ve kazino Mostbet Giri rsmi sayt.5879

Mostbet AZ – bukmeker ve kazino Mostbet – Giriş rəsmi sayt ▶️ OYNA Содержимое Mostbet AZ rəsmi saytı haqqında məlumatlar Mostbet AZ-da qazanmaq üçün nəzərə alınmalıdır maliyyə planları Mostbet AZ-da maliyyə planı təyin etmək üçün nə qədər məbləği təyin etməliyim? mostbet AZ – bukmeker və kazino şirkətinin Azerbaycan üçün hazırladığı …

Read More »

Mostbet AZ – bukmeker ve kazino Mostbet Giri rsmi sayt.4013

Mostbet AZ – bukmeker ve kazino Mostbet – Giriş rəsmi sayt ▶️ OYNA Содержимое Mostbet AZ rəsmi saytı haqqında məlumatlar Mostbet AZ-da qeydiyyatdan keçmək Mostbet AZ-da qazanmaq üçün nəzərə alınmalıdır maliyyə tədbirləri Mostbet AZ-da oyun oynayın və kazanın Mostbet AZ – bukmeker və kazino şirkətinin Azerbaycan riyazi qazanlar üçün rəsmi …

Read More »

Casibom – casibom casino resmi gncel giri.902

Casibom – casibom casino resmi güncel giriş ▶️ OYNAMAK Содержимое Casibom Kasino Hakkında Temel Bilgiler Casibom Kasino Oyunları ve Bonus Programı Casibom Giriş ve Kayıt Casibom, en popüler ve güvenilir kasıtlı oyun sitelerinden biridir. Casibom 158 giriş sayesinde kullanıcılar, güvenli ve profesyonel bir ortamda çeşitli oyunları deneyebilirler. Cadibom adı ile …

Read More »

PariMatch (ПаріМатч) ставки на спорт та онлайн казино.3457

PariMatch (ПаріМатч) ставки на спорт та онлайн казино ▶️ ГРАТИ Содержимое ПариMatch – лідер українського ринку онлайн-ставок Преимущества Париматча Що таке PariMatch? Що може зробити PariMatch? Як зареєструватися на PariMatch Шаг 2: Введіть дані для реєстрації Оставки на спорт та онлайн-казино на PariMatch Що таке PariMatch? Переваги PariMatch Допомога та …

Read More »

Pinco Online Kazino (Пинко) 2025 Qaydalar və Şərtlər üzrə Bələdçi.153

Pinco Online Kazino (РџРёРЅРєРѕ) 2025 – Qaydalar vЙ™ ЕћЙ™rtlЙ™r ГјzrЙ™ BЙ™lЙ™dГ§i ▶️ OYNA Содержимое Pinco Online Kazino (РџРёРЅРєРѕ) 2025 – Qaydalar vЙ™ ЕћЙ™rtlЙ™r ГњzrЙ™ BЙ™lЙ™dГ§i Qeydiyyat vЙ™ Promokodlar TЙ™hlГјkЙ™sizlik vЙ™ Qaydalar Qeydiyyat vЙ™ Daxil Olma QaydalarД± Г–dЙ™niЕџ vЙ™ Г‡Д±xarД±Еџ QaydalarД± TЙ™hlГјkЙ™sizlik vЙ™ MЙ™xfilik QaydalarД± Bonus vЙ™ Kampaniya QaydalarД± Pinco online …

Read More »

Vavada Зеркало Вход на официальный сайт.1552

Вавада казино | Vavada Зеркало Вход на официальный сайт ▶️ ИГРАТЬ Содержимое Vavada Casino – Mirror – Entrance to the official website Преимущества использования Vavada зеркала Официальный сайт Vavada Миррор Vavada – безопасный доступ Преимущества игры в Vavada Большой выбор игр Безопасность и конфиденциальность Как начать играть в Vavada Выбор …

Read More »

Kasyno internetowe – jak sprawdzić licencję operatora.534

Kasyno internetowe – jak sprawdzić licencję operatora? ▶️ GRAĆ Содержимое Sposoby sprawdzania licencji Znaczenie licencji dla gracza Wady nieposiadania licencji Ważne informacje o kasynach online W dzisiejszym świecie, gdzie internet jest nieodłącznym elementem naszego życia, kasyna online stały się coraz bardziej popularne. W Polsce, gdzie hazard jest regulowany, wiele osób …

Read More »

– Официальный сайт Pinco Casino.2384 (2)

Пинко Казино – Официальный сайт Pinco Casino ▶️ ИГРАТЬ Содержимое Преимущества игроков в Pinco Casino Возможности для игроков Большой выбор игр Ограничения и условия В современном мире азартных игр, где каждый день появляются новые онлайн-казино, сложно найти надежный и проверенный игроком ресурс. Однако, pinco Casino – это исключение из правил. …

Read More »