This file is indexed.

/usr/share/pyshared/smart/transaction.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
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
#
# 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
#
from smart.const import INSTALL, REMOVE, UPGRADE, FIX, REINSTALL, KEEP
from smart.cache import PreRequires, Package
from smart import *

class ChangeSet(dict):

    def __init__(self, cache, state=None, requested=None):
        self._cache = cache
        self._requested = {}
        if state:
            self.update(state)
        if requested:
            self._requested.update(requested)

    def clear(self):
        dict.clear(self)
        self._requested.clear()

    def update(self, other):
        dict.update(self, other)
        if type(other) is ChangeSet:
            self._requested.update(other._requested)

    def copy(self):
        return ChangeSet(self._cache, self, self._requested)

    def getCache(self):
        return self._cache

    def getState(self):
        return (self.copy(), self._requested.copy())

    def setState(self, state):
        if state is not self:
            self.clear()
            self.update(state)

    def getPersistentState(self):
        state = {}
        for pkg in self:
            req = pkg in self._requested
            state[(pkg.__class__, pkg.name, pkg.version)] = self[pkg], req
        return state

    def setPersistentState(self, state):
        self.clear()
        for pkg in self._cache.getPackages():
            tup = state.get((pkg.__class__, pkg.name, pkg.version))
            if tup is not None:
                op, req = tup
                self[pkg] = op
                if req:
                    self._requested[pkg] = True

    def markPackagesAutoInstalled(self):
        """ Mark all packages that have been auto-installed permanently
            and reset the flag if the package was removed again. Also
            make sure that the auto-flag is carried to the new pkg on
            upgrades/downgrades.
        """
        # we need to take care of upgrades here, a changeset represents
        # upgrades as a series of REMOVE old-version INSTALL new-version

        upgrade = {}
        # find out about the upgrades/downgrades
        # FIXME: cover the downgrade case too
        for pkg in self:
            if self[pkg] is REMOVE:
                # check if this remove is because the pkg is upgrades
                # and if that is the case, move the "auto" flag to the
                # (upgraded) package and rember that this was a upgraded
                # pkg
                for prv in pkg.provides:
                    for upg in prv.upgradedby:
                        for upgpkg in upg.packages:
                            if self.get(upgpkg) is INSTALL:
                                upgrade[upgpkg] = True
                                if pkgconf.testFlag("auto", pkg):
                                    pkgconf.setFlag("auto",
                                                    upgpkg.name, "=",
                                                    upgpkg.version)
                pkgconf.clearFlag("auto", pkg.name)
        # do the auto-marking on new installs that where not explicitly
        # requested
        for pkg in self:
            if (self[pkg] is INSTALL and
                not pkg in upgrade):
                if not self.getRequested(pkg):
                    pkgconf.setFlag("auto",
                                    pkg.name, "=", pkg.version)
                else:
                    pkgconf.clearFlag("auto",
                                      pkg.name, "=", pkg.version)

    def getRequested(self, pkg):
        return pkg in self._requested

    def setRequested(self, pkg, flag):
        assert pkg in self
        if flag:
            self._requested[pkg] = True
        elif pkg in self._requested:
            del self._requested[pkg]

    def set(self, pkg, op, force=False):
        if self.get(pkg) is op:
            return
        if op is INSTALL:
            if force or not pkg.installed:
                self[pkg] = INSTALL
            else:
                if pkg in self:
                    del self[pkg]
                    if pkg in self._requested:
                        del self._requested[pkg]
        else:
            if force or pkg.installed:
                self[pkg] = REMOVE
            else:
                if pkg in self:
                    del self[pkg]
                    if pkg in self._requested:
                        del self._requested[pkg]

    def installed(self, pkg):
        op = self.get(pkg)
        return op is INSTALL or pkg.installed and not op is REMOVE

    def difference(self, other):
        diff = ChangeSet(self._cache)
        for pkg in self:
            sop = self[pkg]
            if sop is not other.get(pkg):
                diff[pkg] = sop
                if pkg in self._requested:
                    diff._requested[pkg] = True
        return diff

    def intersect(self, other):
        isct = ChangeSet(self._cache)
        for pkg in self:
            sop = self[pkg]
            if sop is other.get(pkg):
                isct[pkg] = sop
                if pkg in self._requested:
                    isct._requested[pkg] = True
        return isct

    def __str__(self):
        l = []
        for pkg in self:
            l.append("%s %s\n" % (self[pkg] is INSTALL and "I" or "R", pkg))
        return "".join(l)

class Policy(object):

    def __init__(self, trans):
        self._trans = trans
        self._locked = {}
        self._sysconflocked = []
        self._priorities = {}

    def runStarting(self):
        self._priorities.clear()
        cache = self._trans.getCache()
        for pkg in pkgconf.filterByFlag("lock", cache.getPackages()):
            if pkg not in self._locked:
                self._sysconflocked.append(pkg)
                self._locked[pkg] = True

    def runFinished(self):
        self._priorities.clear()
        for pkg in self._sysconflocked:
            del self._locked[pkg]
        del self._sysconflocked[:]

    def getLocked(self, pkg):
        return pkg in self._locked

    def setLocked(self, pkg, flag):
        if flag:
            self._locked[pkg] = True
        else:
            if pkg in self._locked:
                del self._locked[pkg]

    def getLockedSet(self):
        return self._locked

    def getWeight(self, changeset):
        return 0

    def getPriority(self, pkg):
        priority = self._priorities.get(pkg)
        if priority is None:
            self._priorities[pkg] = priority = pkg.getPriority()
        return priority

    def getPriorityWeights(self, pkgs):
        set = {}
        lower = None
        for pkg in pkgs:
            priority = self.getPriority(pkg)
            if lower is None or priority < lower:
                lower = priority
            set[pkg] = priority
        for pkg in set:
            set[pkg] = -(set[pkg] - lower)*10
        return set

class PolicyInstall(Policy):
    """Give precedence for keeping functionality in the system."""

    def runStarting(self):
        Policy.runStarting(self)
        self._upgrading = upgrading = {}
        self._upgraded = upgraded = {}
        self._downgraded = downgraded = {}
        for pkg in self._trans.getCache().getPackages():
            # Precompute upgrade relations.
            for upg in pkg.upgrades:
                for prv in upg.providedby:
                    for prvpkg in prv.packages:
                        if prvpkg.installed:
                            if (self.getPriority(pkg) >=
                                self.getPriority(prvpkg)):
                                upgrading[pkg] = True
                                if prvpkg in upgraded:
                                    upgraded[prvpkg].append(pkg)
                                else:
                                    upgraded[prvpkg] = [pkg]
                            else:
                                if prvpkg in downgraded:
                                    downgraded[prvpkg].append(pkg)
                                else:
                                    downgraded[prvpkg] = [pkg]
            # Downgrades are upgrades if they have a higher priority.
            for prv in pkg.provides:
                for upg in prv.upgradedby:
                    for upgpkg in upg.packages:
                        if upgpkg.installed:
                            if (self.getPriority(pkg) >
                                self.getPriority(upgpkg)):
                                upgrading[pkg] = True
                                if upgpkg in upgraded:
                                    upgraded[upgpkg].append(pkg)
                                else:
                                    upgraded[upgpkg] = [pkg]
                            else:
                                if upgpkg in downgraded:
                                    downgraded[upgpkg].append(pkg)
                                else:
                                    downgraded[upgpkg] = [pkg]

    def runFinished(self):
        Policy.runFinished(self)
        del self._upgrading
        del self._upgraded
        del self._downgraded

    def getWeight(self, changeset):
        weight = 0
        upgrading = self._upgrading
        upgraded = self._upgraded
        downgraded = self._downgraded
        for pkg in changeset:
            if changeset[pkg] is REMOVE:
                # Upgrading a package that will be removed
                # is better than upgrading a package that will
                # stay in the system.
                for upgpkg in upgraded.get(pkg, ()):
                    if changeset.get(upgpkg) is INSTALL:
                        weight -= 1
                        break
                else:
                    for dwnpkg in downgraded.get(pkg, ()):
                        if changeset.get(dwnpkg) is INSTALL:
                            weight += 15
                            break
                    else:
                        weight += 20
            else:
                if pkg in upgrading:
                    weight += 2
                else:
                    weight += 3
        return weight

class PolicyRemove(Policy):
    """Give precedence to the choice with less changes."""

    def getWeight(self, changeset):
        weight = 0
        for pkg in changeset:
            if changeset[pkg] is REMOVE:
                weight += 1
            else:
                weight += 5
        return weight

class PolicyUpgrade(Policy):
    """Give precedence to the choice with more upgrades and smaller impact."""

    def runStarting(self):
        Policy.runStarting(self)
        self._upgrading = upgrading = {}
        self._upgraded = upgraded = {}
        self._sortbonus = sortbonus = {}
        self._stablebonus = stablebonus = {}
        queue = self._trans.getQueue()
        for pkg in self._trans.getCache().getPackages():
            # Precompute upgrade relations.
            for upg in pkg.upgrades:
                for prv in upg.providedby:
                    for prvpkg in prv.packages:
                        if (prvpkg.installed and
                            self.getPriority(pkg) >= self.getPriority(prvpkg)):
                            dct = upgrading.get(pkg)
                            if dct:
                                dct[prvpkg] = True
                            else:
                                upgrading[pkg] = {prvpkg: True}
                            lst = upgraded.get(prvpkg)
                            if lst:
                                lst.append(pkg)
                            else:
                                upgraded[prvpkg] = [pkg]
            # Downgrades are upgrades if they have a higher priority.
            for prv in pkg.provides:
                for upg in prv.upgradedby:
                    for upgpkg in upg.packages:
                        if (upgpkg.installed and
                            self.getPriority(pkg) > self.getPriority(upgpkg)):
                            dct = upgrading.get(pkg)
                            if dct:
                                dct[upgpkg] = True
                            else:
                                upgrading[pkg] = {upgpkg: True}
                            lst = upgraded.get(upgpkg)
                            if lst:
                                lst.append(pkg)
                            else:
                                upgraded[upgpkg] = [pkg]

        # If package A-2.0 upgrades package A-1.0, and package A-2.0 is
        # upgraded by A-3.0, give a bonus if A-1.0 is upgraded without
        # installing A-2.0. In practice, this is a little bit more
        # complex since there might be multiple levels of upgrades, and
        # we can't penalize a possible package A2-2.0 which upgrades
        # A-1.0 as well, and is not upgraded by anyone else.
        for bonuspkg in upgraded:
            upgmap = dict.fromkeys(upgraded[bonuspkg])
            sb = {}
            bonusvalue = {}
            bonusdeps = {}
            queue = [[bonuspkg]]
            while queue:
                path = queue.pop(0)
                pathlen = len(path)
                pkg = path[-1]
                for prv in pkg.provides:
                    for upg in prv.upgradedby:
                        for upgpkg in upg.packages:
                            if (not upgpkg.installed and
                                upgpkg in upgmap and upgpkg not in path and
                                self.getPriority(pkg) <=
                                self.getPriority(upgpkg)):
                                if pathlen > 1:
                                    # Paths always increase in size, so we can
                                    # be sure that the value being introduced
                                    # here is >= to the previous one.
                                    bonusvalue[pkg] = -30*(pathlen-1)
                                    deps = bonusdeps.setdefault(pkg, {})
                                    for pathpkg in path[1:]:
                                        deps[pathpkg] = True
                                queue.append(path+[upgpkg])
                for upg in pkg.upgrades:
                    for prv in upg.providedby:
                        for prvpkg in prv.packages:
                            if (not prvpkg.installed and
                                prvpkg in upgmap and prvpkg not in path and
                                self.getPriority(pkg) <
                                self.getPriority(prvpkg)):
                                if pathlen > 1:
                                    bonusvalue[pkg] = -30*(pathlen-1)
                                    deps = bonusdeps.setdefault(pkg, {})
                                    for pathpkg in path[1:-1]:
                                        deps[pathpkg] = True
                                queue.append(path+[prvpkg])
            if bonusvalue:
                lst = [(bonusvalue[pkg], bonusdeps[pkg]) for pkg in bonusvalue]
                lst.sort()
                stablebonus[bonuspkg] = lst

        pkgs = self._trans._queue.keys()
        sortUpgrades(pkgs, self)
        for i, pkg in enumerate(pkgs):
            self._sortbonus[pkg] = -1./(i+100)

    def runFinished(self):
        Policy.runFinished(self)
        del self._upgrading
        del self._upgraded

    def getWeight(self, changeset):
        weight = 0
        upgrading = self._upgrading
        upgraded = self._upgraded
        sortbonus = self._sortbonus
        stablebonus = self._stablebonus

        installedcount = 0
        upgradedmap = {}
        for pkg in changeset:
            if changeset[pkg] is REMOVE:
                # Upgrading a package that will be removed
                # is better than upgrading a package that will
                # stay in the system.
                lst = upgraded.get(pkg, ())
                for lstpkg in lst:
                    if changeset.get(lstpkg) is INSTALL:
                        weight -= 1
                        break
                else:
                    weight += 3
            else:
                installedcount += 1
                upgpkgs = upgrading.get(pkg)
                if upgpkgs:
                    weight += sortbonus.get(pkg, 0)
                    upgradedmap.update(upgpkgs)

        for pkg in upgradedmap:
            sb = stablebonus.get(pkg)
            if sb:
                for bonusvalue, bonusdeps in sb:
                    for deppkg in bonusdeps:
                        if deppkg in changeset:
                            break
                    else:
                        weight += bonusvalue
                        break

        upgradedcount = len(upgradedmap)
        weight += -30*upgradedcount+(installedcount-upgradedcount)
        return weight

class Failed(Error): pass

PENDING_REMOVE   = 1
PENDING_INSTALL  = 2
PENDING_UPDOWN   = 3

class Transaction(object):
    def __init__(self, cache, policy=None, changeset=None, queue=None):
        self._cache = cache
        self._policy = policy and policy(self) or Policy(self)
        self._changeset = changeset or ChangeSet(cache)
        self._queue = queue or {}

    def clear(self):
        self._changeset.clear()
        self._queue.clear()

    def getCache(self):
        return self._cache

    def getQueue(self):
        return self._queue

    def getPolicy(self):
        return self._policy

    def setPolicy(self, policy):
        self._policy = policy(self)

    def getWeight(self):
        return self._policy.getWeight(self._changeset)

    def getChangeSet(self):
        return self._changeset

    def setChangeSet(self, changeset):
        self._changeset = changeset

    def getState(self):
        return self._changeset.getState()

    def setState(self, state):
        self._changeset.setState(state)

    def __nonzero__(self):
        return bool(self._changeset)

    def __str__(self):
        return str(self._changeset)

    def _install(self, pkg, changeset, locked, pending, depth=0):
        #print "[%03d] _install(%s)" % (depth, pkg)
        #depth += 1

        ownpending = pending is None
        if ownpending:
            pending = []

        locked[pkg] = True
        changeset.set(pkg, INSTALL)
        isinst = changeset.installed

        # Remove packages conflicted by this one.
        for cnf in pkg.conflicts:
            for prv in cnf.providedby:
                for prvpkg in prv.packages:
                    if prvpkg is pkg:
                        continue
                    if not isinst(prvpkg):
                        locked[prvpkg] = True
                        continue
                    if prvpkg in locked:
                        raise Failed, _("Can't install %s: conflicted package "
                                        "%s is locked") % (pkg, prvpkg)
                    self._remove(prvpkg, changeset, locked, pending, depth)
                    pending.append((PENDING_UPDOWN, prvpkg))

        # Remove packages conflicting with this one.
        for prv in pkg.provides:
            for cnf in prv.conflictedby:
                for cnfpkg in cnf.packages:
                    if cnfpkg is pkg:
                        continue
                    if not isinst(cnfpkg):
                        locked[cnfpkg] = True
                        continue
                    if cnfpkg in locked:
                        raise Failed, _("Can't install %s: it's conflicted by "
                                        "the locked package %s") \
                                      % (pkg, cnfpkg)
                    self._remove(cnfpkg, changeset, locked, pending, depth)
                    pending.append((PENDING_UPDOWN, cnfpkg))

        # Remove packages with the same name that can't
        # coexist with this one.
        namepkgs = self._cache.getPackages(pkg.name)
        for namepkg in namepkgs:
            if namepkg is not pkg and not pkg.coexists(namepkg):
                if not isinst(namepkg):
                    locked[namepkg] = True
                    continue
                if namepkg in locked:
                    raise Failed, _("Can't install %s: it can't coexist "
                                    "with %s") % (pkg, namepkg)
                self._remove(namepkg, changeset, locked, pending, depth)

        # Install packages required by this one.
        for req in pkg.requires:

            # Check if someone is already providing it.
            prvpkgs = {}
            found = False
            for prv in req.providedby:
                for prvpkg in prv.packages:
                    if isinst(prvpkg):
                        found = True
                        break
                    if prvpkg not in locked:
                        prvpkgs[prvpkg] = True
                else:
                    continue
                break
            if found:
                # Someone is already providing it. Good.
                continue

            # No one is currently providing it. Do something.

            if not prvpkgs:
                # No packages provide it at all. Give up.
                raise Failed, _("Can't install %s: no package provides %s") % \
                              (pkg, req)

            if len(prvpkgs) == 1:
                # Don't check locked here. prvpkgs was
                # already filtered above.
                self._install(prvpkgs.popitem()[0], changeset, locked,
                              pending, depth)
            else:
                # More than one package provide it. This package
                # must be post-processed.
                pending.append((PENDING_INSTALL, pkg, req, prvpkgs.keys()))

        if ownpending:
            self._pending(changeset, locked, pending, depth)

    def _remove(self, pkg, changeset, locked, pending, depth=0):
        #print "[%03d] _remove(%s)" % (depth, pkg)
        #depth += 1

        if pkg.essential:
            raise Failed, _("Can't remove %s: it's an essential package")

        ownpending = pending is None
        if ownpending:
            pending = []

        locked[pkg] = True
        changeset.set(pkg, REMOVE)
        isinst = changeset.installed

        # Check packages requiring this one.
        for prv in pkg.provides:
            for req in prv.requiredby:
                # Check if someone installed is requiring it.
                for reqpkg in req.packages:
                    if isinst(reqpkg):
                        break
                else:
                    # No one requires it, so it doesn't matter.
                    continue

                # Check if someone installed is still providing it.
                prvpkgs = {}
                found = False
                for prv in req.providedby:
                    for prvpkg in prv.packages:
                        if prvpkg is pkg:
                            continue
                        if isinst(prvpkg):
                            found = True
                            break
                        if prvpkg not in locked:
                            prvpkgs[prvpkg] = True
                    else:
                        continue
                    break
                if found:
                    # Someone is still providing it. Good.
                    continue

                # No one is providing it anymore. We'll have to do
                # something about it.

                if prvpkgs:
                    # There are other options, besides removing.
                    pending.append((PENDING_REMOVE, pkg, prv, req.packages,
                                    prvpkgs.keys()))
                else:
                    # Remove every requiring package, or
                    # upgrade/downgrade them to something which
                    # does not require this dependency.
                    for reqpkg in req.packages:
                        if not isinst(reqpkg):
                            continue
                        if reqpkg in locked:
                            raise Failed, _("Can't remove %s: %s is locked") \
                                          % (pkg, reqpkg)
                        self._remove(reqpkg, changeset, locked, pending, depth)
                        pending.append((PENDING_UPDOWN, reqpkg))

        if ownpending:
            self._pending(changeset, locked, pending, depth)

    def _updown(self, pkg, changeset, locked, depth=0):
        #print "[%03d] _updown(%s)" % (depth, pkg)
        #depth += 1

        isinst = changeset.installed
        getpriority = self._policy.getPriority

        pkgpriority = getpriority(pkg)

        # Check if any upgrading version of this package is installed.
        # If so, we won't try to install any other version.
        upgpkgs = {}
        for prv in pkg.provides:
            for upg in prv.upgradedby:
                for upgpkg in upg.packages:
                    if isinst(upgpkg):
                        return
                    if getpriority(upgpkg) < pkgpriority:
                        continue
                    if upgpkg not in locked and upgpkg not in upgpkgs:
                        upgpkgs[upgpkg] = True
        # Also check if any downgrading version with a higher
        # priority is installed.
        for upg in pkg.upgrades:
            for prv in upg.providedby:
                for prvpkg in prv.packages:
                    if getpriority(prvpkg) <= pkgpriority:
                        continue
                    if isinst(prvpkg):
                        return
                    if prvpkg not in locked and prvpkg not in upgpkgs:
                        upgpkgs[prvpkg] = True

        # No, let's try to upgrade it.
        getweight = self._policy.getWeight
        alternatives = [(getweight(changeset), changeset)]

        # Check if upgrading is possible.
        for upgpkg in upgpkgs:
            try:
                cs = changeset.copy()
                lk = locked.copy()
                self._install(upgpkg, cs, lk, None, depth)
            except Failed:
                pass
            else:
                alternatives.append((getweight(cs), cs))

        # Is any downgrading version of this package installed?
        try:
            dwnpkgs = {}
            for upg in pkg.upgrades:
                for prv in upg.providedby:
                    for prvpkg in prv.packages:
                        if getpriority(prvpkg) > pkgpriority:
                            continue
                        if isinst(prvpkg):
                            raise StopIteration
                        if prvpkg not in locked:
                            dwnpkgs[prvpkg] = True
            # Also check if any upgrading version with a lower
            # priority is installed.
            for prv in pkg.provides:
                for upg in prv.upgradedby:
                    for upgpkg in upg.packages:
                        if getpriority(upgpkg) >= pkgpriority:
                            continue
                        if isinst(upgpkg):
                            raise StopIteration
                        if upgpkg not in locked:
                            dwnpkgs[upgpkg] = True
        except StopIteration:
            pass
        else:
            # Check if downgrading is possible.
            for dwnpkg in dwnpkgs:
                try:
                    cs = changeset.copy()
                    lk = locked.copy()
                    self._install(dwnpkg, cs, lk, None, depth)
                except Failed:
                    pass
                else:
                    alternatives.append((getweight(cs), cs))

        # If there's only one alternative, it's the one currenlty in use.
        if len(alternatives) > 1:
            alternatives.sort()
            changeset.setState(alternatives[0][1])

    def _pending(self, changeset, locked, pending, depth=0):
        #print "[%03d] _pending()" % depth
        #depth += 1

        isinst = changeset.installed
        getweight = self._policy.getWeight

        updown = []
        while pending:
            item = pending.pop(0)
            kind = item[0]
            if kind == PENDING_UPDOWN:
                updown.append(item[1])
            elif kind == PENDING_INSTALL:
                kind, pkg, req, prvpkgs = item

                # Check if any prvpkg was already selected for installation
                # due to some other change.
                found = False
                for i in range(len(prvpkgs)-1,-1,-1):
                    prvpkg = prvpkgs[i]
                    if isinst(prvpkg):
                        found = True
                        break
                    if prvpkg in locked:
                        del prvpkgs[i]
                if found:
                    continue

                if not prvpkgs:
                    # No packages provide it at all. Give up.
                    raise Failed, _("Can't install %s: no package "
                                    "provides %s") % (pkg, req)

                if len(prvpkgs) > 1:
                    # More than one package provide it. We use _pending here,
                    # since any option must consider the whole change for
                    # weighting.
                    alternatives = []
                    failures = []
                    sortUpgrades(prvpkgs)
                    keeporder = 0.000001
                    pw = self._policy.getPriorityWeights(prvpkgs)
                    for prvpkg in prvpkgs:
                        try:
                            cs = changeset.copy()
                            lk = locked.copy()
                            self._install(prvpkg, cs, lk, None, depth)
                        except Failed, e:
                            failures.append(unicode(e))
                        else:
                            alternatives.append((getweight(cs)+pw[prvpkg]+
                                                 keeporder, cs, lk))
                            keeporder += 0.000001
                    if not alternatives:
                        raise Failed, _("Can't install %s: all packages "
                                        "providing %s failed to install:\n%s")\
                                      % (pkg, req,  "\n".join(failures))
                    alternatives.sort()
                    changeset.setState(alternatives[0][1])
                    if len(alternatives) == 1:
                        locked.update(alternatives[0][2])
                else:
                    # This turned out to be the only way.
                    self._install(prvpkgs[0], changeset, locked,
                                  pending, depth)

            elif kind == PENDING_REMOVE:
                kind, pkg, prv, reqpkgs, prvpkgs = item

                # Check if someone installed is still requiring it.
                reqpkgs = [x for x in reqpkgs if isinst(x)]
                if not reqpkgs:
                    continue

                # Check if someone installed is providing it.
                found = False
                for prvpkg in prvpkgs:
                    if isinst(prvpkg):
                        found = True
                        break
                if found:
                    # Someone is still providing it. Good.
                    continue

                prvpkgs = [x for x in prvpkgs if x not in locked]

                # No one is providing it anymore. We'll have to do
                # something about it.

                # Try to install other providing packages.
                if prvpkgs:

                    alternatives = []
                    failures = []

                    pw = self._policy.getPriorityWeights(prvpkgs)
                    for prvpkg in prvpkgs:
                        try:
                            cs = changeset.copy()
                            lk = locked.copy()
                            self._install(prvpkg, cs, lk, None, depth)
                        except Failed, e:
                            failures.append(unicode(e))
                        else:
                            alternatives.append((getweight(cs)+pw[prvpkg],
                                                cs, lk))

                if not prvpkgs or not alternatives:

                    # There's no alternatives. We must remove
                    # every requiring package.

                    for reqpkg in reqpkgs:
                        if reqpkg in locked and isinst(reqpkg):
                            raise Failed, _("Can't remove %s: requiring "
                                            "package %s is locked") % \
                                          (pkg, reqpkg)
                    for reqpkg in reqpkgs:
                        # We check again, since other actions may have
                        # changed their state.
                        if not isinst(reqpkg):
                            continue
                        if reqpkg in locked:
                            raise Failed, _("Can't remove %s: requiring "
                                            "package %s is locked") % \
                                          (pkg, reqpkg)
                        self._remove(reqpkg, changeset, locked,
                                     pending, depth)
                    continue

                # Then, remove every requiring package, or
                # upgrade/downgrade them to something which
                # does not require this dependency.
                cs = changeset.copy()
                lk = locked.copy()
                try:
                    for reqpkg in reqpkgs:
                        if reqpkg in locked and isinst(reqpkg):
                            raise Failed, _("%s is locked") % reqpkg
                    for reqpkg in reqpkgs:
                        if not cs.installed(reqpkg):
                            continue
                        if reqpkg in lk:
                            raise Failed, _("%s is locked") % reqpkg
                        self._remove(reqpkg, cs, lk, None, depth)
                except Failed, e:
                    failures.append(unicode(e))
                else:
                    alternatives.append((getweight(cs), cs, lk))

                if not alternatives:
                    raise Failed, _("Can't install %s: all packages providing "
                                    "%s failed to install:\n%s") \
                                  % (pkg, prv,  "\n".join(failures))

                alternatives.sort()
                changeset.setState(alternatives[0][1])
                if len(alternatives) == 1:
                    locked.update(alternatives[0][2])

        for pkg in updown:
            self._updown(pkg, changeset, locked, depth)

        del pending[:]

    def _upgrade(self, pkgs, changeset, locked, pending, depth=0):
        #print "[%03d] _upgrade()" % depth
        #depth += 1

        isinst = changeset.installed
        getweight = self._policy.getWeight

        sortUpgrades(pkgs, self._policy)

        lockedstate = {}

        origchangeset = changeset.copy()

        weight = getweight(changeset)
        for pkg in pkgs:
            if pkg in locked and not isinst(pkg):
                continue

            try:
                cs = changeset.copy()
                lk = locked.copy()
                self._install(pkg, cs, lk, None, depth)
            except Failed, e:
                pass
            else:
                lockedstate[pkg] = lk
                csweight = getweight(cs)
                if csweight < weight:
                    weight = csweight
                    changeset.setState(cs)

        lockedstates = {}
        for pkg in pkgs:
            if changeset.get(pkg) is INSTALL:
                state = lockedstate.get(pkg)
                if state:
                    lockedstates.update(state)

        for pkg in changeset.keys():

            op = changeset.get(pkg)
            if (op and op != origchangeset.get(pkg) and
                pkg not in locked and pkg not in lockedstates):

                try:
                    cs = changeset.copy()
                    lk = locked.copy()
                    if op is REMOVE:
                        self._install(pkg, cs, lk, None, depth)
                    elif op is INSTALL:
                        self._remove(pkg, cs, lk, None, depth)
                except Failed, e:
                    pass
                else:
                    csweight = getweight(cs)
                    if csweight < weight:
                        weight = csweight
                        changeset.setState(cs)
                
    def _fix(self, pkgs, changeset, locked, pending, depth=0):
        #print "[%03d] _fix()" % depth
        #depth += 1

        getweight = self._policy.getWeight
        isinst = changeset.installed

        sortUpgrades(pkgs)

        for pkg in pkgs:

            if not isinst(pkg):
                continue

            # Is it broken at all?
            try:
                for req in pkg.requires:
                    for prv in req.providedby:
                        for prvpkg in prv.packages:
                            if isinst(prvpkg):
                                break
                        else:
                            continue
                        break
                    else:
                        iface.debug(_("Unsatisfied dependency: "
                                      "%s requires %s") % (pkg, req))
                        raise StopIteration
                for cnf in pkg.conflicts:
                    for prv in cnf.providedby:
                        for prvpkg in prv.packages:
                            if prvpkg is pkg:
                                continue
                            if isinst(prvpkg):
                                iface.debug(_("Unsatisfied dependency: "
                                              "%s conflicts with %s")
                                            % (pkg, prvpkg))
                                raise StopIteration
                for prv in pkg.provides:
                    for cnf in prv.conflictedby:
                        for cnfpkg in cnf.packages:
                            if cnfpkg is pkg:
                                continue
                            if isinst(cnfpkg):
                                iface.debug(_("Unsatisfied dependency: "
                                              "%s conflicts with %s")
                                            % (cnfpkg, pkg))
                                raise StopIteration
                # Check packages with the same name that can't
                # coexist with this one.
                namepkgs = self._cache.getPackages(pkg.name)
                for namepkg in namepkgs:
                    if (isinst(namepkg) and namepkg is not pkg
                        and not pkg.coexists(namepkg)):
                        iface.debug(_("Package %s can't coexist with %s") %
                                    (namepkg, pkg))
                        raise StopIteration
            except StopIteration:
                pass
            else:
                continue

            # We have a broken package. Fix it.

            alternatives = []
            failures = []

            # Try to fix by installing it.
            try:
                cs = changeset.copy()
                lk = locked.copy()
                self._install(pkg, cs, lk, None, depth)
            except Failed, e:
                failures.append(unicode(e))
            else:
                # If they weight the same, it's better to keep the package.
                alternatives.append((getweight(cs)-0.000001, cs))

            # Try to fix by removing it.
            try:
                cs = changeset.copy()
                lk = locked.copy()
                self._remove(pkg, cs, lk, None, depth)
                self._updown(pkg, cs, lk, depth)
            except Failed, e:
                failures.append(unicode(e))
            else:
                alternatives.append((getweight(cs), cs))

            if not alternatives:
                raise Failed, _("Can't fix %s:\n%s") % \
                              (pkg, "\n".join(failures))

            alternatives.sort()
            changeset.setState(alternatives[0][1])

    def enqueue(self, pkg, op):
        if op is UPGRADE:
            isinst = self._changeset.installed
            _upgpkgs = {}
            try:
                pkgpriority = pkg.getPriority()
                for prv in pkg.provides:
                    for upg in prv.upgradedby:
                        for upgpkg in upg.packages:
                            if upgpkg.getPriority() < pkgpriority:
                                continue
                            if isinst(upgpkg):
                                raise StopIteration
                            _upgpkgs[upgpkg] = True
                for upg in pkg.upgrades:
                    for prv in upg.providedby:
                        for prvpkg in prv.packages:
                            if prvpkg.getPriority() <= pkgpriority:
                                continue
                            if isinst(prvpkg):
                                raise StopIteration
                            _upgpkgs[prvpkg] = True
            except StopIteration:
                pass
            else:
                for upgpkg in _upgpkgs:
                    self._queue[upgpkg] = op
        else:
            self._queue[pkg] = op

    def run(self):

        self._policy.runStarting()

        try:
            changeset = self._changeset.copy()
            isinst = changeset.installed
            locked = self._policy.getLockedSet().copy()
            pending = []

            for pkg in self._queue:
                op = self._queue[pkg]
                if op is KEEP:
                    if pkg in changeset:
                        del changeset[pkg]
                    locked[pkg] = True
                elif op is INSTALL:
                    if not isinst(pkg) and pkg in locked:
                        raise Failed, _("Can't install %s: it's locked") % pkg
                    changeset.set(pkg, INSTALL)
                    locked[pkg] = True
                elif op is REMOVE:
                    if isinst(pkg) and pkg in locked:
                        raise Failed, _("Can't remove %s: it's locked") % pkg
                    changeset.set(pkg, REMOVE)
                    locked[pkg] = True
                elif op is REINSTALL:
                    if pkg in locked:
                        raise Failed, _("Can't reinstall %s: it's locked")%pkg
                    changeset.set(pkg, INSTALL, force=True)
                    locked[pkg] = True
                elif op is UPGRADE:
                    pass

            upgpkgs = []
            fixpkgs = []
            for pkg in self._queue:
                op = self._queue[pkg]
                if op is KEEP:
                    if pkg.installed:
                        op = INSTALL
                    else:
                        op = REMOVE
                if op is INSTALL or op is REINSTALL:
                    self._install(pkg, changeset, locked, pending)
                    if pkg in changeset:
                        changeset.setRequested(pkg, True)
                elif op is REMOVE:
                    self._remove(pkg, changeset, locked, pending)
                elif op is UPGRADE:
                    upgpkgs.append(pkg)
                elif op is FIX:
                    fixpkgs.append(pkg)

            if pending:
                self._pending(changeset, locked, pending)

            if upgpkgs:
                self._upgrade(upgpkgs, changeset, locked, pending)

            if fixpkgs:
                self._fix(fixpkgs, changeset, locked, pending)

            self._changeset.setState(changeset)

        finally:
            self._queue.clear()
            self._policy.runFinished()


class ChangeSetSplitter(object):
    # This class operates on *sane* changesets.

    DEBUG = 0

    def __init__(self, changeset, forcerequires=True):
        self._changeset = changeset
        self._forcerequires = forcerequires
        self._locked = {}

    def getForceRequires(self):
        return self._userequires

    def setForceRequires(self, flag):
        self._forcerequires = flag

    def getLocked(self, pkg):
        return pkg in self._locked

    def setLocked(self, pkg, flag):
        if flag:
            self._locked[pkg] = True
        else:
            if pkg in self._locked:
                del self._locked[pkg]

    def setLockedSet(self, set):
        self._locked.clear()
        self._locked.update(set)

    def resetLocked(self):
        self._locked.clear()

    def _remove(self, subset, pkg, locked):
        set = self._changeset

        # Include requiring packages being removed, or exclude
        # requiring packages being installed.
        for prv in pkg.provides:
            for req in prv.requiredby:

                reqpkgs = [reqpkg for reqpkg in req.packages if
                           subset.get(reqpkg) is INSTALL or
                           subset.get(reqpkg) is not REMOVE and
                           reqpkg.installed]

                if not reqpkgs:
                    continue

                # Check if some package that will stay
                # in the system or some package already
                # selected for installation provide the
                # needed dependency.
                found = False
                for prv in req.providedby:
                    for prvpkg in prv.packages:
                        if (subset.get(prvpkg) is INSTALL or
                            (prvpkg.installed and not
                             subset.get(prvpkg) is REMOVE)):
                            found = True
                            break
                    else:
                        continue
                    break
                if found:
                    continue

                # Try to include some providing package
                # that is selected for installation.
                found = False
                for prv in req.providedby:
                    for prvpkg in prv.packages:
                        if (set.get(prvpkg) is INSTALL and
                            prvpkg not in locked):
                            try:
                                self.include(subset, prvpkg, locked)
                            except Error:
                                pass
                            else:
                                found = True
                                break
                    else:
                        continue
                    break
                if found:
                    continue

                # Now, try to keep in the system some
                # providing package which is already installed.
                found = False
                wasbroken = True
                for prv in req.providedby:
                    for prvpkg in prv.packages:
                        if set.get(prvpkg) is not REMOVE:
                            continue
                        wasbroken = False
                        # Package is necessarily in subset
                        # otherwise we wouldn't get here.
                        if prvpkg not in locked:
                            try:
                                self.exclude(subset, prvpkg, locked)
                            except Error:
                                pass
                            else:
                                found = True
                                break
                    else:
                        continue
                    break
                if found:
                    continue

                needed = (not wasbroken and 
                          (self._forcerequires or
                           isinstance(req, PreRequires)))

                for reqpkg in reqpkgs:

                    # Finally, try to exclude the requiring
                    # package if it is being installed, or
                    # include it if it's being removed.
                    reqpkgop = set.get(reqpkg)
                    if reqpkgop and reqpkg not in locked:
                        try:
                            if reqpkgop is INSTALL:
                                self.exclude(subset, reqpkg, locked)
                            else:
                                self.include(subset, reqpkg, locked)
                        except Error:
                            if needed: raise
                        else:
                            continue

                    # Should we care about this?
                    if needed:
                        raise Error, _("No providers for '%s', "
                                       "required by '%s'") % (req, reqpkg)

        # Check upgrading/downgrading packages.
        relpkgs = [upgpkg for prv in pkg.provides
                          for upg in prv.upgradedby
                          for upgpkg in upg.packages]
        relpkgs.extend([prvpkg for upg in pkg.upgrades
                               for prv in upg.providedby
                               for prvpkg in prv.packages])
        if set[pkg] is INSTALL:
            # Package is being installed, but excluded from the
            # subset. Exclude every related package which is
            # being removed.
            for relpkg in relpkgs:
                if subset.get(relpkg) is REMOVE:
                    if relpkg in locked:
                        raise Error, _("Package '%s' is locked") % relpkg
                    self.exclude(subset, relpkg, locked)
        else:
            # Package is being removed, and included in the
            # subset. Include every related package which is
            # being installed.
            for relpkg in relpkgs:
                if set.get(relpkg) is INSTALL and relpkg not in subset:
                    if relpkg in locked:
                        raise Error, _("Package '%s' is locked") % relpkg
                    self.include(subset, relpkg, locked)

    def _install(self, subset, pkg, locked):
        set = self._changeset

        # Check all dependencies needed by this package.
        for req in pkg.requires:

            # Check if any already installed or to be installed
            # package will solve the problem.
            found = False
            for prv in req.providedby:
                for prvpkg in prv.packages:
                    if (subset.get(prvpkg) is INSTALL or
                        (prvpkg.installed and
                         subset.get(prvpkg) is not REMOVE)):
                        found = True
                        break
                else:
                    continue
                break
            if found:
                continue

            # Check if any package that could be installed
            # may solve the problem.
            found = False
            for prv in req.providedby:
                for prvpkg in prv.packages:
                    if (set.get(prvpkg) is INSTALL
                        and prvpkg not in locked):
                        try:
                            self.include(subset, prvpkg, locked)
                        except Error:
                            pass
                        else:
                            found = True
                            break
                else:
                    continue
                break
            if found:
                continue

            # Nope. Let's try to keep in the system some
            # package providing the dependency.
            found = False
            wasbroken = True
            for prv in req.providedby:
                for prvpkg in prv.packages:
                    if set.get(prvpkg) is not REMOVE:
                        continue
                    wasbroken = False
                    # Package is necessarily in subset
                    # otherwise we wouldn't get here.
                    if prvpkg not in locked:
                        try:
                            self.exclude(subset, prvpkg, locked)
                        except Error:
                            pass
                        else:
                            found = True
                            break
                else:
                    continue
                break
            if found or wasbroken:
                continue

            # There are no solutions for the problem.
            # Should we really care about it?
            if (self._forcerequires or
                isinstance(req, PreRequires)):
                raise Error, _("No providers for '%s', "
                               "required by '%s'") % (req, pkg)

        cnfpkgs = [prvpkg for cnf in pkg.conflicts
                          for prv in cnf.providedby
                          for prvpkg in prv.packages
                           if prvpkg is not pkg]
        cnfpkgs.extend([cnfpkg for prv in pkg.provides
                               for cnf in prv.conflictedby
                               for cnfpkg in cnf.packages
                                if cnfpkg is not pkg])

        for cnfpkg in cnfpkgs:
            if (subset.get(cnfpkg) is INSTALL or
                cnfpkg.installed and subset.get(cnfpkg) is not REMOVE):
                if cnfpkg not in set:
                    raise Error, _("Can't remove %s, which conflicts with %s")\
                                 % (cnfpkg, pkg)
                if set[cnfpkg] is INSTALL:
                    self.exclude(subset, cnfpkg, locked)
                else:
                    self.include(subset, cnfpkg, locked)

        # Check upgrading/downgrading packages.
        relpkgs = [upgpkg for prv in pkg.provides
                          for upg in prv.upgradedby
                          for upgpkg in upg.packages]
        relpkgs.extend([prvpkg for upg in pkg.upgrades
                               for prv in upg.providedby
                               for prvpkg in prv.packages])
        if set[pkg] is INSTALL:
            # Package is being installed, and included in the
            # subset. Include every related package which is
            # being removed.
            for relpkg in relpkgs:
                if set.get(relpkg) is REMOVE and relpkg not in subset:
                    if relpkg in locked:
                        raise Error, _("Package '%s' is locked") % relpkg
                    self.include(subset, relpkg, locked)
        else:
            # Package is being removed, but excluded from the
            # subset. Exclude every related package which is
            # being installed.
            for relpkg in relpkgs:
                if subset.get(relpkg) is INSTALL:
                    if relpkg in locked:
                        raise Error, _("Package '%s' is locked") % relpkg
                    self.exclude(subset, relpkg, locked)

    def include(self, subset, pkg, locked=None):
        set = self._changeset

        if locked is None:
            locked = self._locked
            if self.DEBUG: print "-"*79
        else:
            locked = locked.copy()
        if self.DEBUG:
            strop = set.get(pkg) is INSTALL and "INSTALL" or "REMOVE"
            print "Including %s of %s" % (strop, pkg)

        if pkg not in set:
            raise Error, _("Package '%s' is not in changeset") % pkg
        if pkg in locked:
            raise Error, _("Package '%s' is locked") % pkg

        locked[pkg] = True

        op = subset[pkg] = set[pkg]
        try:
            if op is INSTALL:
                self._install(subset, pkg, locked)
            else:
                self._remove(subset, pkg, locked)
        except Error, e:
            if self.DEBUG:
                print "FAILED: Including %s of %s: %s" % (strop, pkg, e)
            del subset[pkg]
            raise

    def exclude(self, subset, pkg, locked=None):
        set = self._changeset

        if locked is None:
            locked = self._locked
            if self.DEBUG: print "-"*79
        else:
            locked = locked.copy()
        if self.DEBUG:
            strop = set.get(pkg) is INSTALL and "INSTALL" or "REMOVE"
            print "Excluding %s of %s" % (strop, pkg)

        if pkg not in set:
            raise Error, _("Package '%s' is not in changeset") % pkg
        if pkg in locked:
            raise Error, _("Package '%s' is locked") % pkg

        locked[pkg] = True

        if pkg in subset:
            del subset[pkg]

        op = set[pkg]
        try:
            if op is INSTALL:
                self._remove(subset, pkg, locked)
            elif op is REMOVE:
                self._install(subset, pkg, locked)
        except Error, e:
            if self.DEBUG:
                print "FAILED: Excluding %s of %s: %s" % (strop, pkg, e)
            subset[pkg] = op
            raise

    def includeAll(self, subset):
        # Include everything that doesn't change locked packages
        set = self._changeset.get()
        for pkg in set.keys():
            try:
                self.include(subset, pkg)
            except Error:
                pass

    def excludeAll(self, subset):
        # Exclude everything that doesn't change locked packages
        set = self._changeset.get()
        for pkg in set.keys():
            try:
                self.exclude(subset, pkg)
            except Error:
                pass

def sortUpgrades(pkgs, policy=None):
    upgpkgs = {}
    for pkg in pkgs:
        dct = {}
        rupg = recursiveUpgrades(pkg, dct)
        del dct[pkg]
        upgpkgs[pkg] = dct
    pkgs.sort()
    pkgs.reverse()
    newpkgs = []
    priority = {}
    if policy:
        for pkg in pkgs:
            priority[pkg] = policy.getPriority(pkg)
    else:
        for pkg in pkgs:
            priority[pkg] = pkg.getPriority()
    for pkg in pkgs:
        pkgupgs = upgpkgs[pkg]
        for i in range(len(newpkgs)):
            newpkg = newpkgs[i]
            if newpkg in pkgupgs or priority[pkg] > priority[newpkg]:
                newpkgs.insert(i, pkg)
                break
        else:
            newpkgs.append(pkg)
    pkgs[:] = newpkgs

def recursiveUpgrades(pkg, set):
    set[pkg] = True
    for upg in pkg.upgrades:
        for prv in upg.providedby:
            for prvpkg in prv.packages:
                if prvpkg not in set:
                    recursiveUpgrades(prvpkg, set)

def sortInternalRequires(pkgs):
    rellst = []
    numrel = {}
    pkgmap = dict.fromkeys(pkgs, True)
    for pkg in pkgs:
        rellst.append((recursiveInternalRequires(pkgmap, pkg, numrel), pkg))
    rellst.sort()
    rellst.reverse()
    pkgs[:] = [x[1] for x in rellst]

def recursiveInternalRequires(pkgmap, pkg, numrel, done=None):
    if done is None:
        done = {}
    done[pkg] = True
    if pkg in numrel:
        return numrel[pkg]
    n = 0
    for prv in pkg.provides:
        for req in prv.requiredby:
            for relpkg in req.packages:
                if relpkg in pkgmap and relpkg not in done:
                    n += 1
                    if relpkg in numrel:
                        n += numrel[relpkg]
                    else:
                        n += recursiveInternalRequires(pkgmap, relpkg,
                                                       numrel, done)
    numrel[pkg] = n
    return n

def forwardRequires(pkg, map):
    for req in pkg.requires:
        if req not in map:
            map[req] = True
            for prv in req.providedby:
                if prv not in map:
                    map[prv] = True
                    for prvpkg in prv.packages:
                        if prvpkg not in map:
                            map[prvpkg] = True
                            forwardRequires(prvpkg, map)

def backwardRequires(pkg, map):
    for prv in pkg.provides:
        if prv not in map:
            map[prv] = True
            for req in prv.requiredby:
                if req not in map:
                    map[req] = True
                    for reqpkg in req.packages:
                        if reqpkg not in map:
                            map[reqpkg] = True
                            backwardRequires(reqpkg, map)

def forwardPkgRequires(pkg, map=None):
    if map is None:
        map = {}
    forwardRequires(pkg, map)
    for item in map.keys():
        if not isinstance(item, Package):
            del map[item]
    return map

def backwardPkgRequires(pkg, map=None):
    if map is None:
        map = {}
    backwardRequires(pkg, map)
    for item in map.keys():
        if not isinstance(item, Package):
            del map[item]
    return map

def getAlternates(pkg, cache):
    """
    For a given package, return every package that *might* get
    removed if the given package was installed. The alternate
    packages are every package that conflicts with any of the
    required packages, or require any package conflicting with
    any of the required packages.
    """
    conflicts = {}

    # Direct conflicts.
    for namepkg in cache.getPackages(pkg.name):
        if namepkg is not pkg and not pkg.coexists(namepkg):
            conflicts[(pkg, namepkg)] = True
    for cnf in pkg.conflicts:
        for prv in cnf.providedby:
            for prvpkg in prv.packages:
                if prvpkg is not pkg:
                    conflicts[(pkg, prvpkg)] = True
    for prv in pkg.provides:
        for cnf in prv.conflictedby:
            for cnfpkg in cnf.packages:
                if cnfpkg is not pkg:
                    conflicts[(pkg, cnfpkg)] = True

    # Conflicts of requires.
    queue = [pkg]
    done = {}
    while queue:
        qpkg = queue.pop()
        done[qpkg] = True
        for req in qpkg.requires:
            prvpkgs = {}
            for prv in req.providedby:
                for prvpkg in prv.packages:
                    if prvpkg is qpkg or prvpkg is pkg:
                        break
                    prvpkgs[prvpkg] = True
                else:
                    continue
                break
            else:
                for prvpkg in prvpkgs:
                    if prvpkg in done:
                        continue
                    done[prvpkg] = True
                    queue.append(prvpkg)
                    for namepkg in cache.getPackages(prvpkg.name):
                        if (namepkg not in prvpkgs and
                            namepkg is not pkg and
                            not prvpkg.coexists(namepkg)):
                            conflicts[(prvpkg, namepkg)] = True
                    for cnf in prvpkg.conflicts:
                        for prv in cnf.providedby:
                            for _prvpkg in prv.packages:
                                if (_prvpkg is not pkg and
                                    _prvpkg not in prvpkgs):
                                    conflicts[(prvpkg, _prvpkg)] = True
                    for prv in prvpkg.provides:
                        for cnf in prv.conflictedby:
                            for cnfpkg in cnf.packages:
                                if (cnfpkg is not pkg and
                                    cnfpkg not in prvpkgs):
                                    conflicts[(prvpkg, cnfpkg)] = True

    alternates = {}
    for reqpkg, cnfpkg in conflicts:
        print reqpkg, cnfpkg
        alternates[cnfpkg] = True
        for prv in cnfpkg.provides:
            for req in prv.requiredby:
                # Do not ascend if reqpkg also provides
                # what cnfpkg is offering.
                for _prv in req.providedby:
                    if reqpkg in _prv.packages:
                        break
                else:
                    for _reqpkg in req.packages:
                        alternates[_reqpkg] = True
                        alternates.update(backwardPkgRequires(_reqpkg))

    return alternates

def checkPackagesSimple(cache, checkset=None, report=False,
                        installed=False, available=False):
    if installed and available:
        relateset = cache.getPackages()
    elif installed:
        relateset = [pkg for pkg in cache.getPackages() if pkg.installed]
    elif available:
        relateset = []
        for pkg in cache.getPackages():
            if not pkg.installed:
                relateset.append(pkg)
            else:
                for loader in pkg.loaders:
                    if not loader.getInstalled():
                        relateset.append(pkg)
                        break
    else:
        raise Error, "checkPackagesSimple() called with invalid parameters"
    if checkset is None:
        checkset = relateset
    return checkPackages(cache, checkset, relateset, report)

def checkPackages(cache, checkset, relateset, report=False):
    checkset = list(checkset)
    checkset.sort()
    relateset = dict.fromkeys(relateset, True)

    problems = False
    coexistchecked = {}
    for pkg in checkset:
        for req in pkg.requires:
            for prv in req.providedby:
                for prvpkg in prv.packages:
                    if prvpkg in relateset:
                        break
                else:
                    continue
                break
            else:
                if not report:
                    return False
                problems = True
                iface.info(_("Unsatisfied dependency: %s requires %s") %
                           (pkg, req))

        if not pkg.installed:
            continue

        for cnf in pkg.conflicts:
            for prv in cnf.providedby:
                for prvpkg in prv.packages:
                    if (prvpkg is not pkg and
                        prvpkg.installed and
                        prvpkg in relateset):
                        if not report:
                            return False
                        problems = True
                        iface.info(_("Unsatisfied dependency: "
                                     "%s conflicts with %s") % (pkg, prvpkg))

        namepkgs = cache.getPackages(pkg.name)
        for namepkg in namepkgs:
            if (namepkg is not pkg and
                namepkg.installed and
                namepkg in relateset and
                (namepkg, pkg) not in coexistchecked):
                coexistchecked[(pkg, namepkg)] = True
                if not pkg.coexists(namepkg):
                    if not report:
                        return False
                    problems = True
                    iface.info(_("Package %s can't coexist with %s") %
                               (namepkg, pkg))

    return not problems

def enablePsyco(psyco):
    psyco.bind(PolicyInstall.getWeight)
    psyco.bind(PolicyRemove.getWeight)
    psyco.bind(PolicyUpgrade.getWeight)
    psyco.bind(Transaction._install)
    psyco.bind(Transaction._remove)
    psyco.bind(Transaction._updown)
    psyco.bind(Transaction._pending)
    psyco.bind(Transaction._upgrade)
    psyco.bind(Transaction.enqueue)
    psyco.bind(sortUpgrades)
    psyco.bind(recursiveUpgrades)
    psyco.bind(checkPackages)

hooks.register("enable-psyco", enablePsyco)

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