This file is indexed.

/usr/share/pyshared/smart/control.py is in python-smartpm 1.4-2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
#
# Copyright (c) 2004 Conectiva, Inc.
#
# Written by Gustavo Niemeyer <niemeyer@conectiva.com>
#
# This file is part of Smart Package Manager.
#
# Smart Package Manager 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.
#
# Smart Package Manager 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 Smart Package Manager; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
import cPickle
import sys, os
import copy
import time
import tempfile
import tarfile

from smart.transaction import ChangeSet, ChangeSetSplitter, INSTALL, REMOVE
from smart.util.filetools import compareFiles, setCloseOnExecAll
from smart.util.objdigest import getObjectDigest
from smart.util.pathlocks import PathLocks
from smart.util.strtools import strToBool
from smart.util.metalink import Metalink, Metafile
from smart.searcher import Searcher
from smart.media import MediaSet
from smart.progress import Progress
from smart.fetcher import Fetcher
from smart.report import Report
from smart.channel import *
from smart.cache import *
from smart.const import *
from smart import *


if sys.version_info < (2, 4):
    from sets import Set as set


class Control(object):

    def __init__(self, confpath=None, forcelocks=False):
        self._confpath = None
        self._channels = {} # alias -> Channel()
        self._sysconfchannels = {} # alias -> data dict
        self._dynamicchannels = {} # alias -> Channel()
        self._pathlocks = PathLocks(forcelocks)
        self._cache = Cache()

        self.loadSysConf(confpath)

        self._fetcher = Fetcher()
        self._mediaset = self._fetcher.getMediaSet()
        self._achanset = AvailableChannelSet(self._fetcher)
        self._cachechanged = False

    def getChannels(self):
        return self._channels.values()

    def removeChannel(self, alias):
        channel = self._channels[alias]
        if isinstance(channel, PackageChannel):
            channel.removeLoaders()
        del self._channels[alias]
        if alias in self._sysconfchannels:
            del self._sysconfchannels[alias]
        if alias in self._dynamicchannels:
            del self._dynamicchannels[alias]

    def getFileChannels(self):
        return [x for x in self._channels.values()
                if isinstance(x, FileChannel)]

    def checkPackageFile(self, arg):
        if os.path.exists(arg):
            if filter(None, hooks.call("check-package-file", arg)):
                return True
            if (os.path.isfile(arg) and os.path.getsize(arg) > 0 and
                tarfile.is_tarfile(arg)):
                return True
        return False

    def addFileChannel(self, filename):
        if not self._sysconfchannels:
            # Give a chance for backends to register
            # themselves on FileChannel hooks.
            self.rebuildSysConfChannels()
        found = False
        for channel in hooks.call("create-file-channel", filename):
            if channel:
                if channel.getAlias() in self._channels:
                    raise Error, _("There's another channel with alias '%s'") \
                                 % channel.getAlias()
                self._channels[channel.getAlias()] = channel
                found = True
        if not found and tarfile.is_tarfile(filename):
            tempdir = tempfile.mkdtemp()
            iface.debug("Extracting from %s to %s" % (filename, tempdir))
            tarball = tarfile.open(filename, 'r')
            names = tarball.getnames()
            for name in names:
                tarball.extract(name, path=tempdir)
            tarball.close()
            files = os.listdir(tempdir)
            for file in files:
                path = os.path.join(tempdir, file)
                if os.path.isdir(path) and file == "RPMS":
                    for rpm in os.listdir(path):
                        files.append(os.path.join(path, rpm))
                if os.path.isfile(path) and self.checkPackageFile(path):
                    self.addFileChannel(path)
                    found = True
        if not found:
            raise Error, _("Unable to create channel for file: %s") % filename

    def removeFileChannel(self, filename):
        filename = os.path.abspath(filename)
        for channel in self._channels.values():
            if (isinstance(channel, FileChannel) and
                channel.getFileName() == filename):
                channel.removeLoaders()
                break
        else:
            raise Error, _("Channel not found for '%s'") % filename

    def askForRemovableChannels(self, channels):
        removable = [(str(x), x) for x in channels if x.isRemovable()]
        if not removable:
            return True
        removable.sort()
        removable = [x for name, x in removable]
        self._mediaset.umountAll()
        if not iface.insertRemovableChannels(removable):
            return False
        self._mediaset.mountAll()
        return True

    def getCache(self):
        return self._cache

    def getFetcher(self):
        return self._fetcher

    def getMediaSet(self):
        return self._mediaset

    def restoreMediaState(self):
        self._mediaset.restoreState()

    __stateversion__ = 2

    def loadSysConf(self, confpath=None):
        datadir = sysconf.get("data-dir")
        if confpath:
            confpath = os.path.expanduser(confpath)
            if not os.path.isfile(confpath):
                raise Error, _("Configuration file not found: %s") % confpath
            sysconf.load(confpath)
        else:
            confpath = os.path.join(datadir, CONFFILE)
            if os.path.isfile(confpath):
                sysconf.load(confpath)
        self._confpath = confpath

        if os.path.isdir(datadir):
            writable = os.access(datadir, os.W_OK)
        else:
            try:
                os.makedirs(datadir)
                writable = True
            except OSError:
                raise Error, _("Can't create datadir at %s") % datadir

        if writable and not self._pathlocks.lock(datadir, exclusive=True):
            writable = False

        sysconf.setReadOnly(not writable)

    def saveSysConf(self, confpath=None):
        msys = self._fetcher.getMirrorSystem()
        if msys.getHistoryChanged() and not sysconf.getReadOnly():
            sysconf.set("mirrors-history", msys.getHistory())
        if confpath:
            confpath = os.path.expanduser(confpath)
        else:
            if sysconf.getReadOnly():
                return

            if self._cachechanged:
                cachepath = os.path.join(sysconf.get("data-dir"), "cache")
                if sysconf.get("disk-cache", True):
                    iface.showStatus(_("Saving cache..."))
                    cachefile = open(cachepath+".new", "w")
                    state = (self.__stateversion__,
                             self._cache,
                             self._channels,
                             self._sysconfchannels)
                    cPickle.dump(state, cachefile, 2)
                    cachefile.close()
                    os.rename(cachepath+".new", cachepath)
                    iface.hideStatus()
                elif os.path.isfile(cachepath):
                    os.unlink(cachepath)

            if not sysconf.getModified():
                return

            sysconf.resetModified()
            confpath = self._confpath

        sysconf.save(confpath)

    def reloadMirrors(self):
        mirrors = sysconf.get("mirrors", {})
        for channel in self._channels.values():
            if isinstance(channel, MirrorsChannel):
                cmirrors = channel.getMirrors()
                if cmirrors:
                    for origin in cmirrors:
                        set = dict.fromkeys(cmirrors[origin])
                        set.update(dict.fromkeys(mirrors.get(origin, [])))
                        mirrors[origin] = set.keys()
        msys = self._fetcher.getMirrorSystem()
        msys.setMirrors(mirrors)
        if not msys.getHistory():
            msys.setHistory(sysconf.get("mirrors-history", []))

    def rebuildSysConfChannels(self):

        channels = sysconf.get("channels", ())
    
        forcechannels = sysconf.get("force-channels", "")
        if forcechannels:
            forcechannels = forcechannels.split(",")

        def isEnabled(alias, data):
            if forcechannels:
                return alias in forcechannels
            return not data.get("disabled")

        if channels and not self._channels:
            cachepath = os.path.join(sysconf.get("data-dir"), "cache")
            if os.path.isfile(cachepath) and sysconf.get("disk-cache", True):
                iface.showStatus(_("Loading cache..."))
                cachefile = open(cachepath)
                try:
                    state = cPickle.load(cachefile)
                    if state[0] != self.__stateversion__:
                        raise StateVersionError
                except:
                    if sysconf.get("log-level") == DEBUG:
                        import traceback
                        traceback.print_exc()
                    if os.access(os.path.dirname(cachepath), os.W_OK):
                        os.unlink(cachepath)
                else:
                    (__stateversion__,
                     self._cache,
                     self._channels,
                     self._sysconfchannels) = state
                    for alias in self._channels.keys():
                        if (alias not in channels or
                            not isEnabled(alias, channels[alias])):
                            self.removeChannel(alias)
                cachefile.close()
                iface.hideStatus()

        for alias in channels:
            data = channels[alias]
            if not isEnabled(alias, data):
                continue

            if alias in self._sysconfchannels.keys():
                if self._sysconfchannels[alias] == data:
                    continue
                else:
                    channel = self._channels[alias]
                    if isinstance(channel, PackageChannel):
                        channel.removeLoaders()
                    del self._channels[alias]
                    del self._sysconfchannels[alias]

            channel = createChannel(alias, data)
            self._sysconfchannels[alias] = data
            self._channels[alias] = channel

        for alias in self._sysconfchannels.keys():
            if alias not in channels or channels[alias].get("disabled"):
                self.removeChannel(alias)

    def rebuildDynamicChannels(self):
        for alias in self._dynamicchannels.keys():
            self.removeChannel(alias)
        newchannels = {}
        for channels in hooks.call("rebuild-dynamic-channels"):
            if channels:
                for channel in channels:
                    alias = channel.getAlias()
                    if alias in self._channels:
                        raise Error, _("There's another channel with "
                                       "alias '%s'") % alias
                    newchannels[alias] = channel
        self._channels.update(newchannels)
        self._dynamicchannels.update(newchannels)

    def reloadChannels(self, channels=None, caching=ALWAYS):

        if channels is None:
            manual = False
            self.rebuildSysConfChannels()
            self.rebuildDynamicChannels()
            channels = self._channels.values()
            hooks.call("reload-channels", channels)
        else:
            manual = True

        # Get channels directory and check the necessary locks.
        channelsdir = os.path.join(sysconf.get("data-dir"), "channels/")
        userchannelsdir = os.path.join(sysconf.get("user-data-dir"),
                                       "channels/")
        if not os.path.isdir(channelsdir):
            try:
                os.makedirs(channelsdir)
            except OSError:
                raise Error, _("Unable to create channel directory.")
        if caching is ALWAYS:
            if sysconf.getReadOnly() and os.access(channelsdir, os.W_OK):
                iface.warning(_("The Smart library is already in use by "
                                "another process."))
                iface.warning(_("Configuration is in readonly mode!"))
            if not self._pathlocks.lock(channelsdir):
                raise Error, _("Channel information is locked for writing.")
        elif sysconf.getReadOnly():
            raise Error, _("Can't update channels in readonly mode.")
        elif not self._pathlocks.lock(channelsdir, exclusive=True):
            raise Error, _("Can't update channels with active readers.")
        self._fetcher.setLocalDir(channelsdir, mangle=True)

        # Prepare progress. If we're reading from the cache, we don't want
        # too much information being shown. Otherwise, ask for a full-blown
        # progress for the interface, and build information of currently
        # available packages to compare later.
        if caching is ALWAYS:
            progress = Progress()
        else:
            progress = iface.getProgress(self._fetcher, True)
            oldpkgs = {}
            for pkg in self._cache.getPackages():
                oldpkgs[(pkg.name, pkg.version)] = True
        progress.start()
        steps = 0
        for channel in channels:
            steps += channel.getFetchSteps()
        progress.set(0, steps)

        # Rebuild mirror information.
        self.reloadMirrors()

        self._fetcher.setForceMountedCopy(True)

        self._cache.reset()

        # Do the real work.
        result = True
        for channel in channels:
            digest = channel.getDigest()
            if not manual and channel.hasManualUpdate():
                self._fetcher.setCaching(ALWAYS)
            else:
                self._fetcher.setCaching(caching)
                if channel.getFetchSteps() > 0:
                    progress.setTopic(_("Fetching information for '%s'...") %
                                  (channel.getName() or channel.getAlias()))
                    progress.show()
            self._fetcher.setForceCopy(channel.isRemovable())
            self._fetcher.setLocalPathPrefix(channel.getAlias()+"%%")
            try:
                if not channel.fetch(self._fetcher, progress):
                    iface.debug(_("Failed fetching channel '%s'") % channel)
                    result = False
            except Error, e:
                iface.error(unicode(e))
                iface.debug(_("Failed fetching channel '%s'") % channel)
                result = False
            if (channel.getDigest() != digest and
                isinstance(channel, PackageChannel)):
                channel.addLoaders(self._cache)
                if channel.getAlias() in self._sysconfchannels:
                    self._cachechanged = True
        if result and caching is not ALWAYS:
            sysconf.set("last-update", time.time())
        self._fetcher.setForceMountedCopy(False)
        self._fetcher.setForceCopy(False)
        self._fetcher.setLocalPathPrefix(None)

        # Finish progress.
        progress.setStopped()
        progress.show()
        progress.stop()
 
        # Build cache with the new information.
        self._cache.load()

        # Compare new packages with what we had available, and mark
        # new packages.
        if caching is not ALWAYS:
            pkgconf.clearFlag("new")
            for pkg in self._cache.getPackages():
                if (pkg.name, pkg.version) not in oldpkgs:
                    pkgconf.setFlag("new", pkg.name, "=", pkg.version)

        # Remove unused files from channels directory.
        for dir in (channelsdir, userchannelsdir):
            if os.access(dir, os.W_OK):
                aliases = self._channels.copy()
                aliases.update(dict.fromkeys(sysconf.get("channels", ())))
                for entry in os.listdir(dir):
                    sep = entry.find("%%")
                    if sep == -1 or entry[:sep] not in aliases:
                        os.unlink(os.path.join(dir, entry))

        # Change back to a shared lock.
        self._pathlocks.lock(channelsdir)
        return result

    def markAndSweep(self, changeset=None):
        if changeset==None:
            changeset={}
        # Mark ...
        all = self._cache.getPackages()
        auto = pkgconf.filterByFlag("auto", all)
        marked = {}
        for pkg in all:
            if (pkg.installed and pkg not in auto and
                changeset.get(pkg) != REMOVE):
                marked[pkg] = True
        queue = marked.keys()
        while queue:
            pkg = queue.pop(0)
            for req in pkg.requires:
                for prv in req.providedby:
                    for prvpkg in prv.packages:
                        if (prvpkg.installed and
                            prvpkg not in marked and
                            prvpkg not in changeset):
                            marked[prvpkg] = True
                            queue.append(prvpkg)
        # see what is not marked
        suggestions = ChangeSet(self._cache)
        for pkg in all:
            if pkg.installed and pkg not in marked:
                suggestions[pkg] = REMOVE
        # FIXME: we should probably check here is those suggestions
        #        would break the relations in the cache and bail out
        #        if that happens 

        #if suggestions:
        #    accepted = iface.suggestChanges(suggestions)
        #    if accepted:
        #        changeset.update(accepted)
        return suggestions

    def dumpTransactionURLs(self, trans, output=None):
        changeset = trans.getChangeSet()
        self.dumpURLs([x for x in changeset if changeset[x] is INSTALL])

    def dumpURLs(self, packages, output=None):
        if output is None:
            output = sys.stderr
        urls = []
        for pkg in packages:
            loaders = [x for x in pkg.loaders if not x.getInstalled()]
            if not loaders:
                raise Error, _("Package %s is not available for downloading") \
                             % pkg
            info = loaders[0].getInfo(pkg)
            urls.extend(info.getURLs())
        for url in urls:
            print >>output, url

    def dumpTransactionMetalink(self, trans, output=None):
        changeset = trans.getChangeSet()
        self.dumpMetalink([x for x in changeset if changeset[x] is INSTALL])

    def dumpMetalink(self, packages, output=None):
        if output is None:
            output = sys.stderr
        metalink = Metalink()
        msys = self._fetcher.getMirrorSystem()
        for pkg in packages:
            loaders = [x for x in pkg.loaders if not x.getInstalled()]
            if not loaders:
                raise Error, _("Package %s is not available for downloading") \
                             % pkg
            info = loaders[0].getInfo(pkg)
            if not info.getURLs():
                raise Error, _("Package %s is not available for downloading") \
                             % pkg
            for url in info.getURLs():
                metafile = Metafile(pkg.name, pkg.version, info.getSummary())
                mirror = msys.get(url)
                mirrorurls = []
                mirrorurl = mirror.getNext()
                while mirrorurl:
                    mirrorurls.append(mirrorurl)
                    mirrorurl = mirror.getNext()
                metafile.append(mirrorurls,
                                size=info.getSize(url),
                                md5=info.getMD5(url),
                                sha=info.getSHA(url),
                                sha256=info.getSHA256(url))
                metalink.append(metafile)
        if packages:
            metalink.write(output)

    def dumpTransactionPackages(self, trans, install=False, remove=False,
                                output=None):
        if output is None:
            output = sys.stderr
        ops = set()
        if install:
            ops.add(INSTALL)
        if remove:
            ops.add(REMOVE)
        pkgs = [pkg for (pkg, op) in trans.getChangeSet().items() if op in ops]
        pkgs.sort()
        for pkg in pkgs:
            if sysconf.get("dump-versions", True):
                print >> output, pkg
            else:
                print >> output, pkg.name

    def downloadURLs(self, urllst, what=None, caching=NEVER, targetdir=None):
        fetcher = self._fetcher
        fetcher.reset()
        self.reloadMirrors()
        if targetdir is None:
            localdir = os.path.join(sysconf.get("data-dir"), "tmp/")
            if not os.path.isdir(localdir):
                os.makedirs(localdir)
            fetcher.setLocalDir(localdir, mangle=True)
        else:
            fetcher.setLocalDir(targetdir, mangle=False)
        fetcher.setCaching(caching)
        for url in urllst:
            fetcher.enqueue(url)
        fetcher.run(what=what)
        return fetcher.getSucceededSet(), fetcher.getFailedSet()

    def downloadMetalink(self, metalink, what=None, caching=NEVER, targetdir=None):
        fetcher = self._fetcher
        fetcher.reset()
        self.reloadMirrors()
        if targetdir is None:
            localdir = os.path.join(sysconf.get("data-dir"), "tmp/")
            if not os.path.isdir(localdir):
                os.makedirs(localdir)
            fetcher.setLocalDir(localdir, mangle=True)
        else:
            fetcher.setLocalDir(targetdir, mangle=False)
        fetcher.setCaching(caching)
        for metafile in Metalink.parse(open(metalink)).files():
            urls = metafile.urls()
            info = metafile.info()
            # TODO: use random url
            fetcher.enqueue(urls[0], **info)
        fetcher.run(what=what)
        return fetcher.getSucceededSet(), fetcher.getFailedSet()

    def downloadTransaction(self, trans, caching=OPTIONAL, confirm=True):
        return self.downloadChangeSet(trans.getChangeSet(), caching,
                                      confirm=confirm)

    def downloadChangeSet(self, changeset, caching=OPTIONAL, targetdir=None,
                          confirm=True):
        if confirm and not iface.confirmChangeSet(changeset):
            return False
        return self.downloadPackages([x for x in changeset
                                      if changeset[x] is INSTALL],
                                     caching, targetdir)

    def downloadPackages(self, packages, caching=OPTIONAL, targetdir=None):
        channels = getChannelsWithPackages(packages)
        fetched = 0
        while True:
            if not self.askForRemovableChannels(channels):
                return False
            self._achanset.setChannels(channels)
            fetchpkgs = []
            for channel in channels:
                if self._achanset.isAvailable(channel):
                    fetchpkgs.extend(channels[channel])
            self.fetchPackages(fetchpkgs, caching, targetdir)
            fetched += len(fetchpkgs)
            if fetched == len(packages):
                break
        return True
 
    def packPackages(self, packages, targetdir=None, outputname=None):
        channels = getChannelsWithPackages(packages)
        fetched = 0
        pkgpaths = {}
        while True:
            self._achanset.setChannels(channels)
            fetchpkgs = []
            for channel in channels:
                if self._achanset.isAvailable(channel):
                    fetchpkgs.extend(channels[channel])
            pkgpaths.update(self.fetchPackages(fetchpkgs, OPTIONAL, targetdir))
            fetched += len(fetchpkgs)
            if fetched == len(packages):
                break
        files = []
        for pkg in pkgpaths:
            files.append(pkgpaths[pkg][0])
        self.packFiles(files, targetdir, outputname)

    def packFiles(self, files, targetdir=None, outputname=None):
        prog = iface.getProgress(self, True)
        prog.start()
        prog.setTopic(_("Creating pack..."))
        if outputname:
            filename = outputname
        else:
            filename = "pack.tar"
        if not filename.startswith("/"):
            filename = os.path.join(targetdir, filename)
        tarball = tarfile.open(filename, 'w')
        total = len(files)
        current = 1
        for file in files:
            prog.set(current, total)
            prog.setSubTopic(file, os.path.basename(file))
            prog.setSub(file, 0, 1)
            prog.show()
            tarball.add(file, os.path.basename(file), False)
            prog.setSubDone(file)
            prog.show()
            current += 1
        tarball.close()
        prog.setDone()
        prog.show()
        prog.stop()

    def writeCommitLog(self, changeset):
        """ writes the operations performed in the current changeset
            to a log file specified with via the sysconf"commit-log"
            variable
        """
        logfile = sysconf.get("commit-log",None)
        if logfile == None:
            return
        logdir = os.path.join(sysconf.get("data-dir"), "logs/")
        if not os.path.isdir(logdir):
            os.makedirs(logdir)
        log = open(logdir+logfile,"a")
        for pkg in changeset:
            log.write("%s %s: %s\n" % (time.ctime(), pkg, changeset[pkg]))
        log.write("\n")

    def commitTransaction(self, trans, caching=OPTIONAL, confirm=True):
        return self.commitChangeSet(trans.getChangeSet(), caching, confirm)

    def commitChangeSet(self, changeset, caching=OPTIONAL, confirm=True):
        if confirm and not iface.confirmChangeSet(changeset):
            return False

        if not confirm:
            iface.showChangeSet(changeset)

        if sysconf.get("dry-run"):
            return True

        setCloseOnExecAll()

        pmpkgs = {}
        for pkg in changeset:
            pmclass = pkg.packagemanager
            if pmclass not in pmpkgs:
                pmpkgs[pmclass] = [pkg]
            else:
                pmpkgs[pmclass].append(pkg)

        channels = getChannelsWithPackages([x for x in changeset
                                            if changeset[x] is INSTALL])
        datadir = sysconf.get("data-dir")
        splitter = ChangeSetSplitter(changeset)
        donecs = ChangeSet(self._cache)
        copypkgpaths = {}
        while True:
            if not self.askForRemovableChannels(channels):
                return False
            self._achanset.setChannels(channels)
            splitter.resetLocked()
            splitter.setLockedSet(dict.fromkeys(donecs, True))
            cs = changeset.copy()
            for channel in channels:
                if not self._achanset.isAvailable(channel):
                    for pkg in channels[channel]:
                        if pkg not in donecs and pkg not in copypkgpaths:
                            splitter.exclude(cs, pkg)
            cs = cs.difference(donecs)
            donecs.update(cs)

            if cs:

                pkgpaths = self.fetchPackages([pkg for pkg in cs
                                               if pkg not in copypkgpaths
                                                  and cs[pkg] is INSTALL],
                                              caching)
                for pkg in cs:
                    if pkg in copypkgpaths:
                        pkgpaths[pkg] = copypkgpaths[pkg]
                        del copypkgpaths[pkg]

                hooks.call("pre-commit")
                
                for pmclass in pmpkgs:
                    pmcs = ChangeSet(self._cache)
                    for pkg in pmpkgs[pmclass]:
                        if pkg in cs:
                            pmcs[pkg] = cs[pkg]
                            pmcs.setRequested(pkg, cs.getRequested(pkg))
                    if sysconf.get("commit", True):
                        pmcs.markPackagesAutoInstalled()
                        self.writeCommitLog(pmcs)
                        pmclass().commit(pmcs, pkgpaths)

                hooks.call("post-commit")
                
                if sysconf.get("remove-packages", True):
                    for pkg in pkgpaths:
                        for path in pkgpaths[pkg]:
                            if path.startswith(os.path.join(datadir,
                                                            "packages")):
                                os.unlink(path)

            if donecs == changeset:
                break

            copypkgs = []
            for channel in channels.keys():
                if self._achanset.isAvailable(channel):
                    pkgs = [pkg for pkg in channels[channel] if pkg not in cs]
                    if not pkgs:
                        del channels[channel]
                    elif channel.isRemovable():
                        copypkgs.extend(pkgs)
                        del channels[channel]
                    else:
                        channels[channel] = pkgs
            
            self._fetcher.setForceCopy(True)
            copypkgpaths.update(self.fetchPackages(copypkgs, caching))
            self._fetcher.setForceCopy(False)

        self._mediaset.restoreState()

        return True

    def commitTransactionStepped(self, trans, caching=OPTIONAL, confirm=True):
        return self.commitChangeSetStepped(trans.getChangeSet(),
                                           caching, confirm)

    def commitChangeSetStepped(self, changeset, caching=OPTIONAL,
                               confirm=True):
        if confirm and not iface.confirmChangeSet(changeset):
            return False

        # Order by number of required packages inside the transaction.
        pkglst = []
        for pkg in changeset:
            n = 0
            for req in pkg.requires:
                for prv in req.providedby:
                    for prvpkg in prv.packages:
                        if changeset.get(prvpkg) is INSTALL:
                            n += 1
            pkglst.append((n, pkg))

        pkglst.sort()

        splitter = ChangeSetSplitter(changeset)
        unioncs = ChangeSet(self._cache)
        for n, pkg in pkglst:
            if pkg in unioncs:
                continue
            cs = ChangeSet(self._cache, unioncs)
            splitter.include(unioncs, pkg)
            cs = unioncs.difference(cs)
            self.commitChangeSet(cs, confirm=confirm)

        return True

    def fetchPackages(self, packages, caching=OPTIONAL, targetdir=None):
        fetcher = self._fetcher
        fetcher.reset()
        fetcher.setCaching(caching)
        self.reloadMirrors()
        if targetdir is None:
            localdir = os.path.join(sysconf.get("data-dir"), "packages/")
            if not os.path.isdir(localdir):
                os.makedirs(localdir)
            fetcher.setLocalDir(localdir, mangle=False)
        else:
            fetcher.setLocalDir(targetdir, mangle=False)
        pkgitems = {}
        for pkg in packages:
            for loader in pkg.loaders:
                if loader.getInstalled():
                    continue
                channel = loader.getChannel()
                if self._achanset.isAvailable(channel):
                    break
            else:
                raise Error, _("No channel available for package %s") % pkg
            info = loader.getInfo(pkg)
            urls = info.getURLs()
            pkgitems[pkg] = []
            for url in urls:
                media = self._achanset.getMedia(channel)
                pkgitems[pkg].append(fetcher.enqueue(url, media=media,
                                                     md5=info.getMD5(url),
                                                     sha=info.getSHA(url),
                                                     sha256=info.getSHA256(url),
                                                     size=info.getSize(url),
                                                     validate=info.validate))
        if targetdir:
            fetcher.setForceCopy(True)
        fetcher.run(what=_("packages"))
        fetcher.setForceCopy(False)
        failed = fetcher.getFailedSet()
        if failed:
            raise Error, _("Failed to download packages:\n") + \
                         "\n".join([u"    %s: %s" % (url, failed[url])
                                    for url in failed])
        pkgpaths = {}
        for pkg in packages:
            pkgpaths[pkg] = [item.getTargetPath() for item in pkgitems[pkg]]
        return pkgpaths

    def search(self, s, cutoff=1.00, suggestioncutoff=0.70,
               globcutoff=1.00, globsuggestioncutoff=0.95,
               addprovides=True):
        ratio = 0
        results = []
        suggestions = []

        objects = []

        # If we find packages with exactly the given
        # name or name-version, use them.
        for pkg in self._cache.getPackages(s):
            if pkg.name == s or "%s-%s" % (pkg.name, pkg.version) == s:
                objects.append((1.0, pkg))
         
        if not objects:
            if "*" in s:
                cutoff = globcutoff
                suggestioncutoff = globsuggestioncutoff
            searcher = Searcher()
            searcher.addAuto(s, suggestioncutoff)
            if addprovides:
                searcher.addProvides(s, suggestioncutoff)
            self._cache.search(searcher)
            objects = searcher.getResults()

        if objects:
            bestratio = objects[0][0]
            if bestratio < cutoff:
                suggestions = objects
            else:
                for i in range(len(objects)):
                    ratio, obj = objects[i]
                    if ratio == bestratio:
                        results.append(obj)
                    else:
                        suggestions = objects[i:]
                        break
                if results:
                    ratio = bestratio
        return ratio, results, suggestions

class AvailableChannelSet(object):

    def __init__(self, fetcher, channels=None, progress=None):
        self._channels = channels or []
        self._fetcher = fetcher
        self._progress = progress or Progress()
        self._available = {}
        self._media = {}
        if self._channels:
            self.compute()

    def setChannels(self, channels):
        self._channels = channels
        self.compute()

    def isAvailable(self, channel):
        return channel in self._available

    def getMedia(self, channel):
        return self._media.get(channel)

    def compute(self):

        self._available.clear()
        self._media.clear()

        fetcher = self._fetcher
        progress = self._progress
        mediaset = fetcher.getMediaSet()

        steps = 0
        for channel in self._channels:
            steps += len(channel.getCacheCompareURLs())

        progress.start()
        progress.set(0, steps*2)

        for channel in self._channels:

            if not channel.isRemovable():
                self._available[channel] = True
                progress.add(2)
                continue

            urls = channel.getCacheCompareURLs()
            if not urls:
                self._available[channel] = False
                progress.add(2)
                continue

            datadir = sysconf.get("data-dir")
            tmpdir = os.path.join(datadir, "tmp/")
            if not os.path.isdir(tmpdir):
                os.makedirs(tmpdir)
            channelsdir = os.path.join(datadir, "channels/")
            if not os.path.isdir(channelsdir):
                self._available[channel] = False
                progress.add(2)
                continue

            media = None
            available = False
            for url in urls:

                # Fetch cached item.
                fetcher.reset()
                fetcher.setLocalDir(channelsdir, mangle=True)
                fetcher.setCaching(ALWAYS)
                fetcher.setForceCopy(True)
                fetcher.setLocalPathPrefix(channel.getAlias()+"%%")
                channelsitem = fetcher.enqueue(url)
                fetcher.run("channels", progress=progress)
                fetcher.setForceCopy(False)
                fetcher.setLocalPathPrefix(None)
                if channelsitem.getStatus() is FAILED:
                    progress.add(1)
                    break

                if url.startswith("localmedia:/"):
                    progress.add(1)
                    channelspath = channelsitem.getTargetPath()
                    media = mediaset.findFile(url, comparepath=channelspath)
                    if not media:
                        break
                else:
                    # Fetch temporary item.
                    fetcher.reset()
                    fetcher.setLocalDir(tmpdir, mangle=True)
                    fetcher.setCaching(NEVER)
                    tmpitem = fetcher.enqueue(url)
                    fetcher.run("tmp", progress=progress)
                    if tmpitem.getStatus() is FAILED:
                        break

                    # Compare items.
                    channelspath = channelsitem.getTargetPath()
                    tmppath = tmpitem.getTargetPath()

                    if not compareFiles(channelspath, tmppath):
                        if tmppath.startswith(datadir):
                            os.unlink(tmppath)
                        break
            else:
                self._available[channel] = True
                if media:
                    self._media[channel] = media

        progress.stop()

class ChannelSorter(object):
    def __init__(self, channel):
        self.channel = channel
    def __cmp__(self, other):
        rc = -cmp(isinstance(self.channel, FileChannel),
                  isinstance(other.channel, FileChannel))
        if rc == 0:
            rc = cmp(self.channel.isRemovable(), other.channel.isRemovable())
            if rc and sysconf.get("prefer-removable"):
                rc *= -1
        return rc

def getChannelsWithPackages(packages):
    channels = {}
    for pkg in packages:
        sorters = [ChannelSorter(x.getChannel()) for x in pkg.loaders
                   if not x.getInstalled()]
        if not sorters:
            raise Error, _("%s is not available for downloading") % pkg
        sorters.sort()
        channel = sorters[0].channel
        try:
            channels[channel].append(pkg)
        except KeyError:
            channels[channel] = [pkg]
    return channels

# vim:ts=4:sw=4:et