aboutsummaryrefslogtreecommitdiff
path: root/paludis/repositories/e/vdb_repository.cc
blob: 08d89250d821964eb2564a86e6438a59f5e805f9 (plain)
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
/* vim: set sw=4 sts=4 et foldmethod=syntax : */

/*
 * Copyright (c) 2006, 2007, 2008, 2009, 2010, 2011 Ciaran McCreesh
 *
 * This file is part of the Paludis package manager. Paludis is free software;
 * you can redistribute it and/or modify it under the terms of the GNU General
 * Public License version 2, as published by the Free Software Foundation.
 *
 * Paludis is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 * Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <paludis/repositories/e/vdb_repository.hh>
#include <paludis/repositories/e/vdb_merger.hh>
#include <paludis/repositories/e/vdb_unmerger.hh>
#include <paludis/repositories/e/vdb_id.hh>
#include <paludis/repositories/e/eapi_phase.hh>
#include <paludis/repositories/e/eapi.hh>
#include <paludis/repositories/e/dep_parser.hh>
#include <paludis/repositories/e/e_repository_params.hh>
#include <paludis/repositories/e/e_repository.hh>
#include <paludis/repositories/e/extra_distribution_data.hh>
#include <paludis/repositories/e/can_skip_phase.hh>

#include <paludis/action.hh>
#include <paludis/util/config_file.hh>
#include <paludis/dep_spec.hh>
#include <paludis/user_dep_spec.hh>
#include <paludis/literal_metadata_key.hh>
#include <paludis/dep_spec_flattener.hh>
#include <paludis/dep_tag.hh>
#include <paludis/distribution.hh>
#include <paludis/environment.hh>
#include <paludis/hook.hh>
#include <paludis/match_package.hh>
#include <paludis/metadata_key.hh>
#include <paludis/package_database.hh>
#include <paludis/package_id.hh>
#include <paludis/repositories/e/ebuild.hh>
#include <paludis/repository_name_cache.hh>
#include <paludis/set_file.hh>
#include <paludis/version_operator.hh>
#include <paludis/version_requirements.hh>
#include <paludis/selection.hh>
#include <paludis/generator.hh>
#include <paludis/filtered_generator.hh>
#include <paludis/filter.hh>
#include <paludis/output_manager.hh>
#include <paludis/partially_made_package_dep_spec.hh>
#include <paludis/dep_spec_annotations.hh>
#include <paludis/unformatted_pretty_printer.hh>

#include <paludis/util/accept_visitor.hh>
#include <paludis/util/fast_unique_copy.hh>
#include <paludis/util/mutex.hh>
#include <paludis/util/is_file_with_extension.hh>
#include <paludis/util/log.hh>
#include <paludis/util/set.hh>
#include <paludis/util/sequence.hh>
#include <paludis/util/map.hh>
#include <paludis/util/stringify.hh>
#include <paludis/util/strip.hh>
#include <paludis/util/system.hh>
#include <paludis/util/tokeniser.hh>
#include <paludis/util/hashes.hh>
#include <paludis/util/make_named_values.hh>
#include <paludis/util/make_null_shared_ptr.hh>
#include <paludis/util/simple_visitor_cast.hh>
#include <paludis/util/wrapped_output_iterator.hh>
#include <paludis/util/safe_ifstream.hh>
#include <paludis/util/safe_ofstream.hh>
#include <paludis/util/timestamp.hh>
#include <paludis/util/destringify.hh>
#include <paludis/util/fs_stat.hh>
#include <paludis/util/fs_iterator.hh>

#include <paludis/util/pimp-impl.hh>
#include <paludis/util/create_iterator-impl.hh>
#include <paludis/util/indirect_iterator-impl.hh>

#include <unordered_map>
#include <functional>
#include <algorithm>
#include <vector>
#include <list>
#include <map>
#include <iostream>
#include <cstring>
#include <cerrno>
#include <ctime>

using namespace paludis;
using namespace paludis::erepository;

typedef std::unordered_map<CategoryNamePart, std::shared_ptr<QualifiedPackageNameSet>, Hash<CategoryNamePart> > CategoryMap;
typedef std::unordered_map<QualifiedPackageName, std::shared_ptr<PackageIDSequence>, Hash<QualifiedPackageName> > IDMap;
typedef std::map<std::pair<QualifiedPackageName, VersionSpec>, std::shared_ptr<std::list<QualifiedPackageName> > > ProvidesMap;

namespace paludis
{
    template <>
    struct Imp<VDBRepository>
    {
        VDBRepositoryParams params;

        const std::shared_ptr<Mutex> big_nasty_mutex;

        mutable CategoryMap categories;
        mutable bool has_category_names;
        mutable IDMap ids;

        mutable std::shared_ptr<RepositoryProvidesInterface::ProvidesSequence> provides;
        mutable std::shared_ptr<ProvidesMap> provides_map;
        mutable bool tried_provides_cache, used_provides_cache;
        std::shared_ptr<RepositoryNameCache> names_cache;

        Imp(const VDBRepository * const, const VDBRepositoryParams &, std::shared_ptr<Mutex> = std::make_shared<Mutex>());
        ~Imp();

        std::shared_ptr<const MetadataValueKey<FSPath> > location_key;
        std::shared_ptr<const MetadataValueKey<FSPath> > root_key;
        std::shared_ptr<const MetadataValueKey<std::string> > format_key;
        std::shared_ptr<const MetadataValueKey<FSPath> > provides_cache_key;
        std::shared_ptr<const MetadataValueKey<FSPath> > names_cache_key;
        std::shared_ptr<const MetadataValueKey<FSPath> > builddir_key;
        std::shared_ptr<const MetadataValueKey<std::string> > eapi_when_unknown_key;
    };

    Imp<VDBRepository>::Imp(const VDBRepository * const r,
            const VDBRepositoryParams & p, std::shared_ptr<Mutex> m) :
        params(p),
        big_nasty_mutex(m),
        has_category_names(false),
        tried_provides_cache(false),
        used_provides_cache(false),
        names_cache(std::make_shared<RepositoryNameCache>(p.names_cache(), r)),
        location_key(std::make_shared<LiteralMetadataValueKey<FSPath> >("location", "location",
                    mkt_significant, params.location())),
        root_key(std::make_shared<LiteralMetadataValueKey<FSPath> >("root", "root",
                    mkt_normal, params.root())),
        format_key(std::make_shared<LiteralMetadataValueKey<std::string> >("format", "format",
                    mkt_significant, "vdb")),
        provides_cache_key(std::make_shared<LiteralMetadataValueKey<FSPath> >("provides_cache", "provides_cache",
                    mkt_normal, params.provides_cache())),
        names_cache_key(std::make_shared<LiteralMetadataValueKey<FSPath> >("names_cache", "names_cache",
                    mkt_normal, params.names_cache())),
        builddir_key(std::make_shared<LiteralMetadataValueKey<FSPath> >("builddir", "builddir",
                    mkt_normal, params.builddir())),
        eapi_when_unknown_key(std::make_shared<LiteralMetadataValueKey<std::string> >(
                    "eapi_when_unknown", "eapi_when_unknown", mkt_normal, params.eapi_when_unknown()))
    {
    }

    Imp<VDBRepository>::~Imp()
    {
    }
}

VDBRepository::VDBRepository(const VDBRepositoryParams & p) :
    EInstalledRepository(
            make_named_values<EInstalledRepositoryParams>(
                n::builddir() = p.builddir(),
                n::environment() = p.environment(),
                n::root() = p.root()
                ),
            p.name(),
            make_named_values<RepositoryCapabilities>(
                n::destination_interface() = this,
                n::environment_variable_interface() = this,
                n::make_virtuals_interface() = static_cast<RepositoryMakeVirtualsInterface *>(0),
                n::manifest_interface() = static_cast<RepositoryManifestInterface *>(0),
                n::provides_interface() = this,
                n::virtuals_interface() = static_cast<RepositoryVirtualsInterface *>(0)
            )),
    _imp(this, p)
{
    _add_metadata_keys();
}

VDBRepository::~VDBRepository()
{
}

void
VDBRepository::_add_metadata_keys() const
{
    clear_metadata_keys();
    add_metadata_key(_imp->location_key);
    add_metadata_key(_imp->root_key);
    add_metadata_key(_imp->format_key);
    add_metadata_key(_imp->provides_cache_key);
    add_metadata_key(_imp->names_cache_key);
    add_metadata_key(_imp->builddir_key);
    add_metadata_key(_imp->eapi_when_unknown_key);
}

bool
VDBRepository::has_category_named(const CategoryNamePart & c) const
{
    Lock l(*_imp->big_nasty_mutex);

    Context context("When checking for category '" + stringify(c) +
            "' in " + stringify(name()) + ":");

    need_category_names();
    return _imp->categories.end() != _imp->categories.find(c);
}

bool
VDBRepository::has_package_named(const QualifiedPackageName & q) const
{
    Lock l(*_imp->big_nasty_mutex);

    Context context("When checking for package '" + stringify(q) +
            "' in " + stringify(name()) + ":");

    need_category_names();

    CategoryMap::iterator cat_iter(_imp->categories.find(q.category()));
    if (_imp->categories.end() == cat_iter)
        return false;

    need_package_ids(q.category());

    return cat_iter->second->end() != cat_iter->second->find(q);
}

const bool
VDBRepository::is_unimportant() const
{
    return false;
}

std::shared_ptr<const CategoryNamePartSet>
VDBRepository::category_names() const
{
    Lock l(*_imp->big_nasty_mutex);

    Context context("When fetching category names in " + stringify(name()) + ":");

    need_category_names();

    std::shared_ptr<CategoryNamePartSet> result(std::make_shared<CategoryNamePartSet>());

    std::transform(_imp->categories.begin(), _imp->categories.end(), result->inserter(),
            std::mem_fn(&std::pair<const CategoryNamePart, std::shared_ptr<QualifiedPackageNameSet> >::first));

    return result;
}

std::shared_ptr<const QualifiedPackageNameSet>
VDBRepository::package_names(const CategoryNamePart & c) const
{
    Lock l(*_imp->big_nasty_mutex);

    Context context("When fetching package names in category '" + stringify(c)
            + "' in " + stringify(name()) + ":");

    std::shared_ptr<QualifiedPackageNameSet> result(std::make_shared<QualifiedPackageNameSet>());

    need_category_names();
    if (! has_category_named(c))
        return std::make_shared<QualifiedPackageNameSet>();

    need_package_ids(c);

    return _imp->categories.find(c)->second;
}

std::shared_ptr<const PackageIDSequence>
VDBRepository::package_ids(const QualifiedPackageName & n) const
{
    Lock l(*_imp->big_nasty_mutex);

    Context context("When fetching versions of '" + stringify(n) + "' in "
            + stringify(name()) + ":");


    need_category_names();
    if (! has_category_named(n.category()))
        return std::make_shared<PackageIDSequence>();

    need_package_ids(n.category());
    if (! has_package_named(n))
        return std::make_shared<PackageIDSequence>();

    return _imp->ids.find(n)->second;
}

std::shared_ptr<Repository>
VDBRepository::repository_factory_create(
        Environment * const env,
        const std::function<std::string (const std::string &)> & f)
{
    Context context("When making VDB repository from repo_file '" + f("repo_file") + "':");

    std::string location(f("location"));
    if (location.empty())
        throw VDBRepositoryConfigurationError("Key 'location' not specified or empty");

    std::string root(f("root"));
    if (root.empty())
        root = "/";

    std::string provides_cache(f("provides_cache"));
    if (provides_cache.empty())
    {
        provides_cache = EExtraDistributionData::get_instance()->data_from_distribution(*DistributionData::get_instance()->distribution_from_string(
                    env->distribution()))->default_provides_cache();
        if (provides_cache.empty())
        {
            Log::get_instance()->message("e.vdb.configuration.no_provides_cache", ll_warning, lc_no_context)
                << "The provides_cache key is not set in '" << f("repo_file")
                << "'. You should read the Paludis documentation and select an appropriate value.";
            provides_cache = "/var/empty";
        }
    }

    std::string names_cache(f("names_cache"));
    if (names_cache.empty())
    {
        names_cache = EExtraDistributionData::get_instance()->data_from_distribution(*DistributionData::get_instance()->distribution_from_string(
                    env->distribution()))->default_names_cache();
        if (names_cache.empty())
        {
            Log::get_instance()->message("e.vdb.configuration.no_names_cache", ll_warning, lc_no_context)
                << "The names_cache key is not set in '" << f("repo_file")
                <<"'. You should read the Paludis documentation and select an appropriate value.";
            names_cache = "/var/empty";
        }
    }

    std::string builddir(f("builddir"));
    if (builddir.empty())
        builddir = EExtraDistributionData::get_instance()->data_from_distribution(*DistributionData::get_instance()->distribution_from_string(
                env->distribution()))->default_buildroot();

    std::string name(f("name"));
    if (name.empty())
        name = "installed";

    std::string eapi_when_unknown(f("eapi_when_unknown"));
    if (eapi_when_unknown.empty())
        eapi_when_unknown = EExtraDistributionData::get_instance()->data_from_distribution(
                *DistributionData::get_instance()->distribution_from_string(
                    env->distribution()))->default_eapi_when_unknown();

    return std::make_shared<VDBRepository>(make_named_values<VDBRepositoryParams>(
                n::builddir() = builddir,
                n::eapi_when_unknown() = eapi_when_unknown,
                n::environment() = env,
                n::location() = location,
                n::name() = RepositoryName(name),
                n::names_cache() = names_cache,
                n::provides_cache() = provides_cache,
                n::root() = root
                ));
}

RepositoryName
VDBRepository::repository_factory_name(
        const Environment * const,
        const std::function<std::string (const std::string &)> & f)
{
    std::string name(f("name"));
    if (name.empty())
        return RepositoryName("installed");
    else
        return RepositoryName(name);
}

std::shared_ptr<const RepositoryNameSet>
VDBRepository::repository_factory_dependencies(
        const Environment * const,
        const std::function<std::string (const std::string &)> &)
{
    return std::make_shared<RepositoryNameSet>();
}

VDBRepositoryConfigurationError::VDBRepositoryConfigurationError(
        const std::string & msg) throw () :
    ConfigurationError("VDB repository configuration error: " + msg)
{
}

VDBRepositoryKeyReadError::VDBRepositoryKeyReadError(
        const std::string & msg) throw () :
    ConfigurationError("VDB repository key read error: " + msg)
{
}

namespace
{
    bool ignore_merged(const std::shared_ptr<const FSPathSet> & s, const FSPath & f)
    {
        return s->end() != s->find(f);
    }
}

void
VDBRepository::perform_uninstall(
        const std::shared_ptr<const ERepositoryID> & id,
        const UninstallAction & a) const
{
    Context context("When uninstalling '" + stringify(*id) + (a.options.is_overwrite() ? "' for an overwrite:" : "':"));

    if (! _imp->params.root().stat().is_directory())
        throw ActionFailedError("Couldn't uninstall '" + stringify(*id) +
                "' because root ('" + stringify(_imp->params.root()) + "') is not a directory");

    if (! id->eapi()->supported())
        throw ActionFailedError("Couldn't uninstall '" + stringify(*id) +
                "' because EAPI is unsupported");

    std::shared_ptr<OutputManager> output_manager(a.options.make_output_manager()(a));

    std::string reinstalling_str(a.options.is_overwrite() ? "-reinstalling-" : "");

    std::shared_ptr<FSPathSequence> eclassdirs(std::make_shared<FSPathSequence>());
    eclassdirs->push_back(FSPath(_imp->params.location() / stringify(id->name().category()) /
                (reinstalling_str + stringify(id->name().package()) + "-" + stringify(id->version()))));

    FSPath pkg_dir(_imp->params.location() / stringify(id->name().category()) / (reinstalling_str +
                stringify(id->name().package()) + "-" + stringify(id->version())));

    std::shared_ptr<FSPath> load_env(std::make_shared<FSPath>(pkg_dir / "environment.bz2"));

    EAPIPhases phases(id->eapi()->supported()->ebuild_phases()->ebuild_uninstall());
    for (EAPIPhases::ConstIterator phase(phases.begin_phases()), phase_end(phases.end_phases()) ;
            phase != phase_end ; ++phase)
    {
        if (can_skip_phase(_imp->params.environment(), id, *phase))
        {
            output_manager->stdout_stream() << "--- No need to do anything for " << phase->equal_option("skipname") << " phase" << std::endl;
            continue;
        }

        if (phase->option("unmerge"))
        {
            /* load CONFIG_PROTECT, CONFIG_PROTECT_MASK from vdb, supplement with env */
            std::string config_protect, config_protect_mask;

            try
            {
                SafeIFStream c(pkg_dir / "CONFIG_PROTECT");
                config_protect = std::string((std::istreambuf_iterator<char>(c)), std::istreambuf_iterator<char>()) +
                    " " + getenv_with_default("CONFIG_PROTECT", "");
            }
            catch (const SafeIFStreamError &)
            {
            }

            try
            {
                SafeIFStream c_m(pkg_dir / "CONFIG_PROTECT_MASK");
                config_protect_mask = std::string((std::istreambuf_iterator<char>(c_m)), std::istreambuf_iterator<char>()) +
                    " " + getenv_with_default("CONFIG_PROTECT_MASK", "");
            }
            catch (const SafeIFStreamError &)
            {
            }

            std::string final_config_protect(config_protect + " " + a.options.config_protect());

            /* unmerge */
            VDBUnmerger unmerger(
                    make_named_values<VDBUnmergerOptions>(
                        n::config_protect() = final_config_protect,
                        n::config_protect_mask() = config_protect_mask,
                        n::environment() = _imp->params.environment(),
                        n::ignore() = a.options.ignore_for_unmerge(),
                        n::output_manager() = output_manager,
                        n::package_id() = id,
                        n::root() = installed_root_key()->value()
                    ));
            unmerger.unmerge();

            VDBPostMergeUnmergeCommand post_unmerge_command(
                    make_named_values<VDBPostMergeUnmergeCommandParams>(
                        n::root() = installed_root_key()->value()
                    ));
            post_unmerge_command();
        }
        else
        {
            FSPath package_builddir(_imp->params.builddir() / (stringify(id->name().category()) + "-" + stringify(id->name().package()) + "-" + stringify(id->version()) + "-uninstall"));
            EbuildCommandParams params(make_named_values<EbuildCommandParams>(
                    n::builddir() = _imp->params.builddir(),
                    n::clearenv() = phase->option("clearenv"),
                    n::commands() = join(phase->begin_commands(), phase->end_commands(), " "),
                    n::distdir() = pkg_dir,
                    n::ebuild_dir() = pkg_dir,
                    n::ebuild_file() = pkg_dir / (stringify(id->name().package()) + "-" + stringify(id->version()) + ".ebuild"),
                    n::eclassdirs() = eclassdirs,
                    n::environment() = _imp->params.environment(),
                    n::exlibsdirs() = std::make_shared<FSPathSequence>(),
                    n::files_dir() = pkg_dir,
                    n::maybe_output_manager() = output_manager,
                    n::package_builddir() = package_builddir,
                    n::package_id() = id,
                    n::portdir() = _imp->params.location(),
                    n::root() = stringify(_imp->params.root()),
                    n::sandbox() = phase->option("sandbox"),
                    n::sydbox() = phase->option("sydbox"),
                    n::userpriv() = phase->option("userpriv")
                    ));

            EbuildUninstallCommandParams uninstall_params(make_named_values<EbuildUninstallCommandParams>(
                        n::load_environment() = load_env.get(),
                        n::loadsaveenv_dir() = package_builddir / "temp",
                        n::replaced_by() = a.options.if_for_install_id(),
                        n::unmerge_only() = false
                    ));

            EbuildUninstallCommand uninstall_cmd_pre(params, uninstall_params);
            uninstall_cmd_pre();
        }
    }

    /* remove vdb entry */
    for (FSIterator d(pkg_dir, { fsio_include_dotfiles, fsio_inode_sort }), d_end ; d != d_end ; ++d)
        d->unlink();
    pkg_dir.rmdir();

    {
        CategoryMap::iterator it(_imp->categories.find(id->name().category()));
        if (_imp->categories.end() != it && it->second)
        {
            IDMap::iterator it2(_imp->ids.find(id->name()));
            if (_imp->ids.end() != it2)
            {
                std::shared_ptr<PackageIDSequence> ids(std::make_shared<PackageIDSequence>());
                std::remove_copy(it2->second->begin(), it2->second->end(), ids->back_inserter(), id);
                it2->second = ids;
            }
        }
    }

    if (! a.options.is_overwrite())
    {
        std::shared_ptr<const PackageIDSequence> ids(package_ids(id->name()));
        bool only(true);
        for (PackageIDSequence::ConstIterator it(ids->begin()),
                 it_end(ids->end()); it_end != it; ++it)
            if (*std::static_pointer_cast<const PackageID>(id) != **it)
            {
                only = false;
                break;
            }
        if (only)
            _imp->names_cache->remove(id->name());
    }

    if (_imp->used_provides_cache || (! _imp->tried_provides_cache && load_provided_using_cache()))
    {
        _imp->provides_map->erase(std::make_pair(id->name(), id->version()));
        write_provides_cache();
        _imp->provides.reset();
    }
}

void
VDBRepository::invalidate()
{
    Lock l(*_imp->big_nasty_mutex);
    _imp.reset(new Imp<VDBRepository>(this, _imp->params, _imp->big_nasty_mutex));
    _add_metadata_keys();
}

void
VDBRepository::invalidate_masks()
{
}

std::shared_ptr<const RepositoryProvidesInterface::ProvidesSequence>
VDBRepository::provided_packages() const
{
    Lock l(*_imp->big_nasty_mutex);

    if (_imp->provides)
        return _imp->provides;

    Context context("When finding provided packages for '" + stringify(name()) + "':");

    if (! _imp->provides_map)
    {
        if (! load_provided_using_cache())
            load_provided_the_slow_way();
    }

    _imp->provides = std::make_shared<RepositoryProvidesInterface::ProvidesSequence>();
    for (ProvidesMap::const_iterator it(_imp->provides_map->begin()),
             it_end(_imp->provides_map->end()); it_end != it; ++it)
    {
        std::shared_ptr<const ERepositoryID> id(package_id_if_exists(it->first.first, it->first.second));
        if (! id)
        {
            Log::get_instance()->message("e.vdb.provides.no_package", ll_warning, lc_context) <<
                "No package available for '" << it->first.first <<  " " << it->first.second << "'";
            continue;
        }

        for (std::list<QualifiedPackageName>::const_iterator it2(it->second->begin()),
                 it2_end(it->second->end()); it2_end != it2; ++it2)
            _imp->provides->push_back(make_named_values<RepositoryProvidesEntry>(
                        n::provided_by() = id,
                        n::virtual_name() = *it2
                    ));
    }

    return _imp->provides;
}

bool
VDBRepository::load_provided_using_cache() const
{
    Lock l(*_imp->big_nasty_mutex);
    _imp->tried_provides_cache = true;

    if (_imp->params.provides_cache() == FSPath("/var/empty"))
        return false;

    Context context("When loading VDB PROVIDEs map using '" + stringify(_imp->params.provides_cache()) + "':");

    if (! _imp->params.provides_cache().stat().is_regular_file())
    {
        Log::get_instance()->message("e.vdb.provides_cache.not_regular_file", ll_warning, lc_no_context)
            << "Provides cache at '" << _imp->params.provides_cache() << "' is not a regular file. Perhaps you need to regenerate "
            "the cache using 'cave fix-cache'?";
        return false;
    }

    SafeIFStream provides_cache(_imp->params.provides_cache());

    std::string version;
    std::getline(provides_cache, version);

    if (version != "paludis-3")
    {
        Log::get_instance()->message("e.vdb.provides_cache.unsupported", ll_warning, lc_no_context) << "Can't use provides cache at '"
            << _imp->params.provides_cache() << "' because format '" << version << "' is not 'paludis-3'. Perhaps you need to regenerate "
            "the cache using 'cave fix-cache'?";
        return false;
    }

    std::string for_name;
    std::getline(provides_cache, for_name);
    if (for_name != stringify(name()))
    {
        Log::get_instance()->message("e.vdb.provides_cache.unusable", ll_warning, lc_no_context)
            << "Can't use provides cache at '" << _imp->params.provides_cache() << "' because it was generated for repository '"
            << for_name << "'. You must not have multiple provides caches at the same location.";
        return false;
    }

    _imp->provides_map = std::make_shared<ProvidesMap>();

    std::string line;
    while (std::getline(provides_cache, line))
    {
        try
        {
            std::vector<std::string> tokens;
            tokenise_whitespace(line, std::back_inserter(tokens));
            if (tokens.size() < 3)
            {
                Log::get_instance()->message("e.vdb.provides_cache.malformed", ll_warning, lc_context)
                    << "Not using PROVIDES cache line '" << line << "' as it contains fewer than three tokens";
                continue;
            }

            QualifiedPackageName q(tokens.at(0));
            VersionSpec v(tokens.at(1), EAPIData::get_instance()->eapi_from_string(
                        _imp->params.eapi_when_unknown())->supported()->version_spec_options());

            std::shared_ptr<std::list<QualifiedPackageName> > qpns(std::make_shared<std::list<QualifiedPackageName>>());
            std::copy(tokens.begin() + 2, tokens.end(), create_inserter<QualifiedPackageName>(
                        std::back_inserter(*qpns)));

            if (_imp->provides_map->end() != _imp->provides_map->find(std::make_pair(q, v)))
                Log::get_instance()->message("e.vdb.provides_cache.duplicate", ll_warning, lc_context)
                    << "Not using PROVIDES cache line '" << line << "' as it names a package that has already been specified";
            else
                _imp->provides_map->insert(std::make_pair(std::make_pair(q, v), qpns));
        }
        catch (const InternalError &)
        {
            throw;
        }
        catch (const Exception & e)
        {
            Log::get_instance()->message("e.vdb.provides_cache.unusable", ll_warning, lc_context)
                << "Not using PROVIDES cache line '" << line << "' due to exception '" << e.message() << "' (" << e.what() << ")";
        }
    }

    _imp->used_provides_cache = true;
    return true;
}

void
VDBRepository::provides_from_package_id(const std::shared_ptr<const PackageID> & id) const
{
    Context context("When loading VDB PROVIDEs entry for '" + stringify(*id) + "':");

    try
    {
        if (! id->provide_key())
            return;

        std::shared_ptr<const ProvideSpecTree> provide(id->provide_key()->value());
        DepSpecFlattener<ProvideSpecTree, PackageDepSpec> f(_imp->params.environment(), id);
        provide->top()->accept(f);

        std::shared_ptr<std::list<QualifiedPackageName> > qpns(std::make_shared<std::list<QualifiedPackageName>>());

        for (DepSpecFlattener<ProvideSpecTree, PackageDepSpec>::ConstIterator
                 p(f.begin()), p_end(f.end()) ; p != p_end ; ++p)
        {
            QualifiedPackageName pp((*p)->text());

            if (pp.category() != CategoryNamePart("virtual"))
                Log::get_instance()->message("e.vdb.provide.non_virtual", ll_warning, lc_no_context)
                    << "PROVIDE of non-virtual '" << pp << "' from '" << *id << "' will not work as expected";

            qpns->push_back(pp);
        }

        ProvidesMap::iterator it(_imp->provides_map->find(std::make_pair(id->name(), id->version())));
        if (qpns->empty())
        {
            if (_imp->provides_map->end() != it)
                _imp->provides_map->erase(it);
        }
        else
        {
            if (_imp->provides_map->end() == it)
                _imp->provides_map->insert(std::make_pair(std::make_pair(id->name(), id->version()), qpns));
            else
                it->second = qpns;
        }
    }
    catch (const InternalError &)
    {
        throw;
    }
    catch (const Exception & ee)
    {
        Log::get_instance()->message("e.vdb.provides.failure", ll_warning, lc_no_context) << "Skipping VDB PROVIDE entry for '"
            << *id << "' due to exception '" << ee.message() << "' (" << ee.what() << ")";
    }
}

void
VDBRepository::load_provided_the_slow_way() const
{
    Lock l(*_imp->big_nasty_mutex);

    using namespace std::placeholders;

    Context context("When loading VDB PROVIDEs map the slow way:");

    Log::get_instance()->message("e.vdb.provides.starting", ll_debug, lc_no_context) << "Starting VDB PROVIDEs map creation";
    _imp->provides_map = std::make_shared<ProvidesMap>();

    need_category_names();
    std::for_each(_imp->categories.begin(), _imp->categories.end(),
            std::bind(std::mem_fn(&VDBRepository::need_package_ids), this,
                std::bind<CategoryNamePart>(std::mem_fn(
                        &std::pair<const CategoryNamePart, std::shared_ptr<QualifiedPackageNameSet> >::first), _1)));


    for (IDMap::const_iterator i(_imp->ids.begin()), i_end(_imp->ids.end()) ;
            i != i_end ; ++i)
        for (PackageIDSequence::ConstIterator e(i->second->begin()), e_end(i->second->end()) ;
                e != e_end ; ++e)
            provides_from_package_id(*e);

    Log::get_instance()->message("e.vdb.provides.done", ll_debug, lc_no_context) << "Done VDB PROVIDEs map creation";
}

void
VDBRepository::write_provides_cache() const
{
    Context context("When saving provides cache to '" + stringify(_imp->params.provides_cache()) + "':");

    if (! _imp->params.provides_cache().dirname().stat().exists())
    {
        Log::get_instance()->message("e.vdb.provides.no_dir", ll_warning, lc_no_context) << "Directory '"
            << _imp->params.provides_cache().dirname() << "' does not exist, so cannot save cache file '"
            << _imp->params.provides_cache() << "' "
            << "(see the faq for why this directory will not be created automatically)";
        return;
    }

    try
    {
        SafeOFStream f(_imp->params.provides_cache(), -1, true);

        f << "paludis-3" << std::endl;
        f << name() << std::endl;

        for (ProvidesMap::const_iterator it(_imp->provides_map->begin()),
                 it_end(_imp->provides_map->end()); it_end != it; ++it)
        {
            f << it->first.first << " " << it->first.second;
            for (std::list<QualifiedPackageName>::const_iterator it2(it->second->begin()),
                     it2_end(it->second->end()); it2_end != it2; ++it2)
                f << " " << *it2;
            f << std::endl;
        }
    }
    catch (const SafeOFStreamError & e)
    {
        Log::get_instance()->message("e.vdb.provides.write_failed", ll_warning, lc_context) << "Cannot write to '" <<
                _imp->params.provides_cache() << "': '" << e.message() << "' (" << e.what() << ")";
        return;
    }
}

void
VDBRepository::regenerate_cache() const
{
    Lock l(*_imp->big_nasty_mutex);

    regenerate_provides_cache();
    _imp->names_cache->regenerate_cache();
}

void
VDBRepository::regenerate_provides_cache() const
{
    Lock l(*_imp->big_nasty_mutex);

    using namespace std::placeholders;

    if (_imp->params.provides_cache() == FSPath("/var/empty"))
        return;

    Context context("When generating VDB repository provides cache at '"
            + stringify(_imp->params.provides_cache()) + "':");

    FSPath(_imp->params.provides_cache()).unlink();

    load_provided_the_slow_way();
    write_provides_cache();
}

std::shared_ptr<const CategoryNamePartSet>
VDBRepository::category_names_containing_package(const PackageNamePart & p) const
{
    Lock l(*_imp->big_nasty_mutex);

    if (! _imp->names_cache->usable())
        return Repository::category_names_containing_package(p);

    std::shared_ptr<const CategoryNamePartSet> result(
            _imp->names_cache->category_names_containing_package(p));

    return result ? result : Repository::category_names_containing_package(p);
}

namespace
{
    bool slot_is_same(const std::shared_ptr<const PackageID> & a,
            const std::shared_ptr<const PackageID> & b)
    {
        if (a->slot_key())
            return b->slot_key() && a->slot_key()->value() == b->slot_key()->value();
        else
            return ! b->slot_key();
    }

    std::shared_ptr<OutputManager> this_output_manager(const std::shared_ptr<OutputManager> & o, const Action &)
    {
        return o;
    }
}

void
VDBRepository::merge(const MergeParams & m)
{
    Context context("When merging '" + stringify(*m.package_id()) + "' at '" + stringify(m.image_dir())
            + "' to VDB repository '" + stringify(name()) + "':");

    if (! is_suitable_destination_for(m.package_id()))
        throw ActionFailedError("Not a suitable destination for '" + stringify(*m.package_id()) + "'");

    std::shared_ptr<const ERepositoryID> is_replace(package_id_if_exists(m.package_id()->name(), m.package_id()->version()));

    FSPath tmp_vdb_dir(_imp->params.location());
    if (! tmp_vdb_dir.stat().exists())
        tmp_vdb_dir.mkdir(0755, { });
    tmp_vdb_dir /= stringify(m.package_id()->name().category());
    if (! tmp_vdb_dir.stat().exists())
        tmp_vdb_dir.mkdir(0755, { });
    tmp_vdb_dir /= ("-checking-" + stringify(m.package_id()->name().package()) + "-" + stringify(m.package_id()->version()));
    tmp_vdb_dir.mkdir(0755, { });

    WriteVDBEntryCommand write_vdb_entry_command(
            make_named_values<WriteVDBEntryParams>(
                n::environment() = _imp->params.environment(),
                n::environment_file() = m.environment_file(),
                n::maybe_output_manager() = m.output_manager(),
                n::output_directory() = tmp_vdb_dir,
                n::package_id() = std::static_pointer_cast<const ERepositoryID>(m.package_id())
            ));

    write_vdb_entry_command();

    /* load CONFIG_PROTECT, CONFIG_PROTECT_MASK from vdb */
    std::string config_protect, config_protect_mask;
    try
    {
        SafeIFStream c(tmp_vdb_dir / "CONFIG_PROTECT");
        config_protect = std::string((std::istreambuf_iterator<char>(c)), std::istreambuf_iterator<char>());
    }
    catch (const SafeIFStreamError &)
    {
    }

    try
    {
        SafeIFStream c_m(tmp_vdb_dir / "CONFIG_PROTECT_MASK");
        config_protect_mask = std::string((std::istreambuf_iterator<char>(c_m)), std::istreambuf_iterator<char>());
    }
    catch (const SafeIFStreamError &)
    {
    }

    FSPath vdb_dir(_imp->params.location());
    vdb_dir /= stringify(m.package_id()->name().category());
    vdb_dir /= (stringify(m.package_id()->name().package()) + "-" + stringify(m.package_id()->version()));

    bool fix_mtimes(std::static_pointer_cast<const ERepositoryID>(
                m.package_id())->eapi()->supported()->ebuild_options()->fix_mtimes());

    VDBMerger merger(
            make_named_values<VDBMergerParams>(
                n::config_protect() = config_protect,
                n::config_protect_mask() = config_protect_mask,
                n::contents_file() = vdb_dir / "CONTENTS",
                n::environment() = _imp->params.environment(),
                n::fix_mtimes_before() = fix_mtimes ?  m.build_start_time() : Timestamp(0, 0),
                n::image() = m.image_dir(),
                n::merged_entries() = m.merged_entries(),
                n::options() = m.options(),
                n::output_manager() = m.output_manager(),
                n::package_id() = m.package_id(),
                n::root() = installed_root_key()->value()
            ));

    (m.used_this_for_config_protect())(config_protect);

    if (! merger.check())
    {
        for (FSIterator d(tmp_vdb_dir, { fsio_include_dotfiles, fsio_inode_sort }), d_end ; d != d_end ; ++d)
            d->unlink();
        tmp_vdb_dir.rmdir();
        throw ActionFailedError("Not proceeding with install due to merge sanity check failing");
    }

    if (is_replace)
    {
        /* hack: before we nuke its vdb dir, preload CONTENTS */
        if (! is_replace->contents_key())
            throw InternalError(PALUDIS_HERE, "No contents key in " + stringify(*is_replace) + ". How did that happen?");
        is_replace->contents_key()->value();

        FSPath old_vdb_dir(_imp->params.location());
        old_vdb_dir /= stringify(is_replace->name().category());
        old_vdb_dir /= (stringify(is_replace->name().package()) + "-" + stringify(is_replace->version()));

        if ((old_vdb_dir.dirname() / ("-reinstalling-" + old_vdb_dir.basename())).stat().exists())
            throw ActionFailedError("Directory '" + stringify(old_vdb_dir.dirname() /
                        ("-reinstalling-" + old_vdb_dir.basename())) + "' already exists, probably due to "
                    "a previous failed upgrade. If it is safe to do so, remove this directory and try "
                    "again.");
        old_vdb_dir.rename(old_vdb_dir.dirname() / ("-reinstalling-" + old_vdb_dir.basename()));
    }

    tmp_vdb_dir.rename(vdb_dir);

    std::shared_ptr<const PackageID> new_id;
    {
        CategoryMap::iterator it(_imp->categories.find(m.package_id()->name().category()));
        if (_imp->categories.end() != it && it->second)
        {
            it->second->insert(m.package_id()->name());
            IDMap::iterator it2(_imp->ids.find(m.package_id()->name()));
            if (_imp->ids.end() == it2)
            {
                std::shared_ptr<PackageIDSequence> ids(std::make_shared<PackageIDSequence>());
                it2 = _imp->ids.insert(std::make_pair(m.package_id()->name(), ids)).first;
            }
            it2->second->push_back(new_id = make_id(m.package_id()->name(), m.package_id()->version(), vdb_dir));
        }
    }

    merger.merge();

    if (is_replace)
    {
        UninstallActionOptions uo(make_named_values<UninstallActionOptions>(
                    n::config_protect() = config_protect,
                    n::if_for_install_id() = m.package_id(),
                    n::ignore_for_unmerge() = std::bind(&ignore_merged, m.merged_entries(),
                            std::placeholders::_1),
                    n::is_overwrite() = true,
                    n::make_output_manager() = std::bind(&this_output_manager, m.output_manager(), std::placeholders::_1)
                    ));
        m.perform_uninstall()(is_replace, uo);
    }

    if (std::static_pointer_cast<const ERepositoryID>(m.package_id())
            ->eapi()->supported()->ebuild_phases()->ebuild_new_upgrade_phase_order())
    {
        const std::shared_ptr<const PackageIDSequence> & replace_candidates(package_ids(m.package_id()->name()));
        for (PackageIDSequence::ConstIterator it(replace_candidates->begin()),
                 it_end(replace_candidates->end()); it_end != it; ++it)
        {
            std::shared_ptr<const ERepositoryID> candidate(std::static_pointer_cast<const ERepositoryID>(*it));
            if (candidate != is_replace && candidate != new_id && slot_is_same(candidate, m.package_id()))
            {
                UninstallActionOptions uo(make_named_values<UninstallActionOptions>(
                            n::config_protect() = config_protect,
                            n::if_for_install_id() = m.package_id(),
                            n::ignore_for_unmerge() = std::bind(&ignore_merged, m.merged_entries(),
                                    std::placeholders::_1),
                            n::is_overwrite() = false,
                            n::make_output_manager() = std::bind(&this_output_manager, m.output_manager(), std::placeholders::_1)
                            ));
                m.perform_uninstall()(candidate, uo);
            }
        }
    }

    VDBPostMergeUnmergeCommand post_merge_command(
            make_named_values<VDBPostMergeUnmergeCommandParams>(
                n::root() = installed_root_key()->value()
            ));
    post_merge_command();

    _imp->names_cache->add(m.package_id()->name());

    if (_imp->used_provides_cache || (! _imp->tried_provides_cache && load_provided_using_cache()))
    {
        provides_from_package_id(m.package_id());
        write_provides_cache();
        _imp->provides.reset();
    }
}

void
VDBRepository::need_category_names() const
{
    Lock l(*_imp->big_nasty_mutex);

    if (_imp->has_category_names)
        return;

    Context context("When loading category names from '" + stringify(_imp->params.location()) + "':");

    for (FSIterator d(_imp->params.location(), { fsio_inode_sort, fsio_want_directories, fsio_deref_symlinks_for_wants }), d_end ; d != d_end ; ++d)
        try
        {
            _imp->categories.insert(std::make_pair(CategoryNamePart(d->basename()),
                        std::shared_ptr<QualifiedPackageNameSet>()));
        }
        catch (const InternalError &)
        {
            throw;
        }
        catch (const Exception & e)
        {
            Log::get_instance()->message("e.vdb.categories.failure", ll_warning, lc_context) << "Skipping VDB category dir '"
                << *d << "' due to exception '" << e.message() << "' (" << e.what() << ")";
        }

    _imp->has_category_names = true;
}

void
VDBRepository::need_package_ids(const CategoryNamePart & c) const
{
    Lock l(*_imp->big_nasty_mutex);

    if (_imp->categories[c])
        return;

    Context context("When loading package names from '" + stringify(_imp->params.location()) +
            "' in category '" + stringify(c) + "':");

    std::shared_ptr<QualifiedPackageNameSet> q(std::make_shared<QualifiedPackageNameSet>());

    for (FSIterator d(_imp->params.location() / stringify(c), { fsio_inode_sort, fsio_want_directories, fsio_deref_symlinks_for_wants }), d_end ;
            d != d_end ; ++d)
        try
        {
            std::string s(d->basename());
            if (std::string::npos == s.rfind('-'))
                continue;

            PackageDepSpec p(parse_user_package_dep_spec("=" + stringify(c) + "/" + s,
                        _imp->params.environment(), { }));
            q->insert(*p.package_ptr());
            IDMap::iterator i(_imp->ids.find(*p.package_ptr()));
            if (_imp->ids.end() == i)
                i = _imp->ids.insert(std::make_pair(*p.package_ptr(), std::make_shared<PackageIDSequence>())).first;
            i->second->push_back(make_id(*p.package_ptr(), p.version_requirements_ptr()->begin()->version_spec(), *d));
        }
        catch (const InternalError &)
        {
            throw;
        }
        catch (const Exception & e)
        {
            Log::get_instance()->message("e.vdb.packages.failure", ll_warning, lc_context) << "Skipping VDB package dir '"
                << *d << "' due to exception '" << e.message() << "' (" << e.what() << ")";
        }

    _imp->categories[c] = q;
}

const std::shared_ptr<const ERepositoryID>
VDBRepository::make_id(const QualifiedPackageName & q, const VersionSpec & v, const FSPath & f) const
{
    Lock l(*_imp->big_nasty_mutex);

    Context context("When creating ID for '" + stringify(q) + "-" + stringify(v) + "' from '" + stringify(f) + "':");

    std::shared_ptr<VDBID> result(std::make_shared<VDBID>(q, v, _imp->params.environment(), name(), f));
    return result;
}

const std::shared_ptr<const ERepositoryID>
VDBRepository::package_id_if_exists(const QualifiedPackageName & q, const VersionSpec & v) const
{
    Lock l(*_imp->big_nasty_mutex);

    if (! has_package_named(q))
        return std::shared_ptr<const ERepositoryID>();

    need_package_ids(q.category());

    using namespace std::placeholders;

    PackageIDSequence::ConstIterator i(_imp->ids[q]->begin()), i_end(_imp->ids[q]->end());
    for ( ; i != i_end ; ++i)
        if (v == (*i)->version())
            return std::static_pointer_cast<const ERepositoryID>(*i);
    return std::shared_ptr<const ERepositoryID>();
}

void
VDBRepository::need_keys_added() const
{
}

const std::shared_ptr<const MetadataValueKey<std::string> >
VDBRepository::format_key() const
{
    return _imp->format_key;
}

const std::shared_ptr<const MetadataValueKey<FSPath> >
VDBRepository::location_key() const
{
    return _imp->location_key;
}

const std::shared_ptr<const MetadataValueKey<FSPath> >
VDBRepository::installed_root_key() const
{
    return _imp->root_key;
}

const std::shared_ptr<const MetadataCollectionKey<Map<std::string, std::string> > >
VDBRepository::sync_host_key() const
{
    return make_null_shared_ptr();
}

namespace
{
    typedef std::map<QualifiedPackageName, QualifiedPackageName> DepRewrites;

    struct DepRewriter
    {
        const DepRewrites & rewrites;
        bool changed;

        std::stringstream str;
        UnformattedPrettyPrinter f;

        DepRewriter(const DepRewrites & w) :
            rewrites(w),
            changed(false)
        {
        }

        void do_annotations(const DepSpec & p)
        {
            if (p.maybe_annotations() && (p.maybe_annotations()->begin() != p.maybe_annotations()->end()))
            {
                str << " [[ ";
                for (auto m(p.maybe_annotations()->begin()), m_end(p.maybe_annotations()->end()) ;
                        m != m_end ; ++m)
                    str << m->key() << " = [" << (m->value().empty() ? " " : " " + m->value() + " ") << "] ";
                str << "]] ";
            }
        }

        void visit(const DependencySpecTree::NodeType<AnyDepSpec>::Type & node)
        {
            str << "|| ( ";
            std::for_each(indirect_iterator(node.begin()), indirect_iterator(node.end()), accept_visitor(*this));
            str << " ) ";
            do_annotations(*node.spec());
        }

        void visit(const DependencySpecTree::NodeType<AllDepSpec>::Type & node)
        {
            str << "( ";
            std::for_each(indirect_iterator(node.begin()), indirect_iterator(node.end()), accept_visitor(*this));
            str << " ) ";
            do_annotations(*node.spec());
        }

        void visit(const DependencySpecTree::NodeType<BlockDepSpec>::Type & node)
        {
            /* don't rewrite blocks. some people block the old package after
             * doing a move. */
            str << f.prettify(*node.spec()) << " ";
            do_annotations(*node.spec());
        }

        void visit(const DependencySpecTree::NodeType<DependenciesLabelsDepSpec>::Type & node)
        {
            str << f.prettify(*node.spec()) << " ";
            do_annotations(*node.spec());
        }

        void visit(const DependencySpecTree::NodeType<PackageDepSpec>::Type & node)
        {
            if (node.spec()->package_ptr() && rewrites.end() != rewrites.find(*node.spec()->package_ptr()))
            {
                changed = true;
                str << f.prettify(PartiallyMadePackageDepSpec(*node.spec())
                        .package(rewrites.find(*node.spec()->package_ptr())->second)) << " ";
            }
            else
                str << f.prettify(*node.spec()) << " ";

            do_annotations(*node.spec());
        }

        void visit(const DependencySpecTree::NodeType<ConditionalDepSpec>::Type & node)
        {
            str << f.prettify(*node.spec()) << " ( ";
            std::for_each(indirect_iterator(node.begin()), indirect_iterator(node.end()), accept_visitor(*this));
            str << " ) ";
            do_annotations(*node.spec());
        }

        void visit(const DependencySpecTree::NodeType<NamedSetDepSpec>::Type & node)
        {
            str << f.prettify(*node.spec()) << " ";
            do_annotations(*node.spec());
        }
    };

    bool rewrite_dependencies(
            const FSPath & f,
            const std::shared_ptr<const MetadataSpecTreeKey<DependencySpecTree> > & key,
            const DepRewrites & rewrites)
    {
        DepRewriter v(rewrites);
        key->value()->top()->accept(v);
        if (v.changed)
        {
            std::cout << "    Rewriting " << f << std::endl;
            SafeOFStream ff(f, -1, true);
            ff << v.str.str() << std::endl;
        }

        return v.changed;
    }
}

void
VDBRepository::perform_updates()
{
    Context context("When performing updates:");

    DepRewrites dep_rewrites;

    typedef std::list<std::pair<std::shared_ptr<const PackageID>, QualifiedPackageName> > Moves;
    Moves moves;

    typedef std::list<std::pair<std::shared_ptr<const PackageID>, SlotName> > SlotMoves;
    SlotMoves slot_moves;

    std::map<FSPath, std::time_t, FSPathComparator> cache_contents;
    FSPath cache_dir(_imp->params.location() / ".cache");
    FSPath cache_file(cache_dir / "updates_time_cache");
    if (cache_file.stat().is_regular_file_or_symlink_to_regular_file())
    {
        Context ctx2("When reading update file timestamps from '" + stringify(cache_file) + "':");
        LineConfigFile f(cache_file, { lcfo_preserve_whitespace });

        for (LineConfigFile::ConstIterator line(f.begin()), line_end(f.end()) ;
                line != line_end ; ++line)
        {
            std::string::size_type tab(line->find('\t'));
            if (std::string::npos == tab)
            {
                Log::get_instance()->message("e.vdb.updates.bad_timestamp_line", ll_warning, lc_context)
                    << "Line '" << *line << "' does not contain a tab character";
                continue;
            }
            try
            {
                cache_contents.insert(std::make_pair(FSPath(line->substr(tab + 1)), destringify<std::time_t>(line->substr(0, tab))));
            }
            catch (const DestringifyError &)
            {
                Log::get_instance()->message("e.vdb.updates.bad_timestamp_line", ll_warning, lc_context)
                    << "Line '" << *line << "' contains an invalid timestamp";
            }
        }
    }

    std::cout << std::endl << "Checking for updates (package moves etc):" << std::endl;

    std::map<FSPath, std::time_t, FSPathComparator> update_timestamps;
    for (PackageDatabase::RepositoryConstIterator r(_imp->params.environment()->package_database()->begin_repositories()),
            r_end(_imp->params.environment()->package_database()->end_repositories()) ;
            r != r_end ; ++r)
    {
        Context context_2("When performing updates from '" + stringify((*r)->name()) + "':");

        try
        {
            if (0 == stringify((*r)->name()).compare(0, 2, "x-"))
            {
                /* ticket:897. not really the best solution, but it'll do for now. */
                continue;
            }

            Repository::MetadataConstIterator k_iter((*r)->find_metadata("e_updates_location"));
            if (k_iter == (*r)->end_metadata())
            {
                Log::get_instance()->message("e.vdb.updates.no_key", ll_debug, lc_context) <<
                    "Repository " << (*r)->name() << " defines no e_updates_location key";
                continue;
            }

            const MetadataValueKey<FSPath> * k(simple_visitor_cast<const MetadataValueKey<FSPath> >(**k_iter));
            if (! k)
            {
                Log::get_instance()->message("e.vdb.udpates.bad_key", ll_warning, lc_context) <<
                    "Repository " << (*r)->name() << " defines an e_updates_location key, but it is not an FSPath key";
                continue;
            }

            FSPath dir(k->value());
            if (! dir.stat().is_directory_or_symlink_to_directory())
            {
                Log::get_instance()->message("e.vdb.updates.bad_key", ll_warning, lc_context) <<
                    "Repository " << (*r)->name() << " has e_updates_location " << dir << ", but this is not a directory";
                continue;
            }

            for (FSIterator d(k->value(), { fsio_want_regular_files, fsio_deref_symlinks_for_wants }), d_end ; d != d_end ; ++d)
            {
                Context context_3("When performing updates from '" + stringify(*d) + "':");

                FSStat d_stat(*d);
                update_timestamps.insert(std::make_pair(*d, d_stat.mtim().seconds()));
                std::map<FSPath, std::time_t, FSPathComparator>::const_iterator last_checked(cache_contents.find(*d));
                if (cache_contents.end() != last_checked && d_stat.mtim().seconds() <= last_checked->second)
                {
                    Log::get_instance()->message("e.vdb.updates.ignoring", ll_debug, lc_context) <<
                        "Ignoring " << *d << " because it hasn't changed";
                    continue;
                }

                std::cout << "    Considering " << *d << std::endl;

                LineConfigFile f(*d, { });

                for (LineConfigFile::ConstIterator line(f.begin()), line_end(f.end()) ;
                        line != line_end ; ++line)
                {
                    std::vector<std::string> tokens;
                    tokenise_whitespace(*line, std::back_inserter(tokens));

                    if (tokens.empty())
                        continue;

                    if ("move" == tokens.at(0))
                    {
                        if (3 == tokens.size())
                        {
                            QualifiedPackageName old_q(tokens.at(1)), new_q(tokens.at(2));

                            /* we want to rewrite deps to avoid a mess. we do
                             * this even if we don't have an installed thing
                             * matching the dep, since a package might dep upon
                             * || ( a b ) where a is installed and b is being
                             * moved. */
                            dep_rewrites.insert(std::make_pair(old_q, new_q)).first->second = new_q;

                            const std::shared_ptr<const PackageIDSequence> ids((*_imp->params.environment())[selection::AllVersionsSorted(
                                        generator::Package(old_q) & generator::InRepository(name())
                                        )]);
                            if (! ids->empty())
                            {
                                for (PackageIDSequence::ConstIterator i(ids->begin()), i_end(ids->end()) ;
                                        i != i_end ; ++i)
                                    moves.push_back(std::make_pair(*i, new_q));
                            }
                        }
                        else
                            Log::get_instance()->message("e.vdb.updates.bad_line", ll_warning, lc_context) <<
                                "Don't know how to handle '" << *line << "' in " << *d << ": expected 3 tokens for a move";
                    }
                    else if ("slotmove" == tokens.at(0))
                    {
                        if (4 == tokens.size())
                        {
                            PackageDepSpec old_spec(parse_user_package_dep_spec(tokens.at(1), _imp->params.environment(),
                                        { }));
                            SlotName old_slot(tokens.at(2)), new_slot(tokens.at(3));

                            const std::shared_ptr<const PackageIDSequence> ids((*_imp->params.environment())[selection::AllVersionsSorted(
                                        (generator::Matches(old_spec, make_null_shared_ptr(), { }) & generator::InRepository(name())) |
                                        filter::Slot(old_slot)
                                        )]);
                            if (! ids->empty())
                            {
                                for (PackageIDSequence::ConstIterator i(ids->begin()), i_end(ids->end()) ;
                                        i != i_end ; ++i)
                                    slot_moves.push_back(std::make_pair(*i, new_slot));
                            }
                        }
                        else
                            Log::get_instance()->message("e.vdb.updates.bad_line", ll_warning, lc_context) <<
                                "Don't know how to handle '" << *line << "' in " << *d << ": expected 4 tokens for a slotmove";
                    }
                    else
                        Log::get_instance()->message("e.vdb.updates.bad_line", ll_warning, lc_context) <<
                            "Don't know how to handle '" << *line << "' in " << *d << ": unknown operation";
                }
            }
        }
        catch (const Exception & e)
        {
            Log::get_instance()->message("e.vdb.updates.exception", ll_warning, lc_context) <<
                "Caught exception '" << e.message() << "' (" << e.what() << ") when looking for updates. This is "
                "probably bad.";
        }
    }

    bool failed(false);
    try
    {
        std::cout << std::endl;

        if (! moves.empty())
        {
            std::cout << std::endl << "Performing moves:" << std::endl;
            for (Moves::const_iterator m(moves.begin()), m_end(moves.end()) ;
                    m != m_end ; ++m)
            {
                std::cout << "    " << *m->first << " to " << m->second << std::endl;

                FSPath target_cat_dir(_imp->params.location() / stringify(m->second.category()));
                target_cat_dir.mkdir(0755, { fspmkdo_ok_if_exists });

                FSPath from_dir(m->first->fs_location_key()->value());
                FSPath to_dir(target_cat_dir / ((stringify(m->second.package()) + "-" + stringify(m->first->version()))));

                if (to_dir.stat().exists())
                {
                    /* Uh oh. It's possible to install both a package and its renamed version. */
                    Log::get_instance()->message("e.vdb.updates.collision", ll_warning, lc_context) <<
                        "I wanted to rename '" << from_dir << "' to '" << to_dir << "' for a package move, but the "
                        "latter already exists. Consult the Paludis FAQ for how to proceed.";
                    failed = true;
                }
                else
                {
                    std::string oldpf(stringify(m->first->name().package()) + "-" + stringify(m->first->version()));
                    std::string newpf(stringify(m->second.package()) + "-" + stringify(m->first->version()));

                    from_dir.rename(to_dir);

                    std::shared_ptr<const EAPI> eapi(std::static_pointer_cast<const VDBID>(m->first)->eapi());
                    if (eapi->supported())
                    {
                        SafeOFStream pf(to_dir / eapi->supported()->ebuild_environment_variables()->env_pf(), -1, true);
                        pf << newpf << std::endl;
                    }
                    else
                    {
                        Log::get_instance()->message("e.vdb.updates.eapi", ll_warning, lc_context)
                            << "Unsupported EAPI '" << eapi->name() << "' for '" << *m->first
                            << "', cannot update PF-equivalent VDB key for move";
                    }

                    SafeOFStream category(to_dir / "CATEGORY", -1, true);
                    category << m->second.category() << std::endl;

                    if (newpf != oldpf)
                    {
                        for (FSIterator it(to_dir, { fsio_inode_sort }), it_end; it_end != it; ++it)
                        {
                            std::string::size_type lastdot(it->basename().rfind('.'));
                            if (std::string::npos != lastdot && 0 == it->basename().compare(0, lastdot, oldpf, 0, oldpf.length()))
                                it->rename(to_dir / (newpf + it->basename().substr(lastdot)));
                        }
                    }
                }
            }
        }

        if (! slot_moves.empty())
        {
            std::cout << std::endl << "Performing slot moves:" << std::endl;
            for (SlotMoves::const_iterator m(slot_moves.begin()), m_end(slot_moves.end()) ;
                    m != m_end ; ++m)
            {
                std::cout << "    " << *m->first << " to " << m->second << std::endl;

                SafeOFStream f(m->first->fs_location_key()->value() / "SLOT", -1, true);
                f << m->second << std::endl;
            }
        }

        if ((! moves.empty()) || (! slot_moves.empty()))
        {
            invalidate();

            if (_imp->params.provides_cache() != FSPath("/var/empty"))
                if (_imp->params.provides_cache().stat().is_regular_file_or_symlink_to_regular_file())
                {
                    std::cout << std::endl << "Invalidating provides cache following updates" << std::endl;
                    _imp->params.provides_cache().unlink();
                    regenerate_provides_cache();
                }

            std::cout << std::endl << "Invalidating names cache following updates" << std::endl;
            _imp->names_cache->regenerate_cache();
        }

        if (! dep_rewrites.empty())
        {
            std::cout << std::endl << "Updating installed package dependencies" << std::endl;

            bool rewrite_done(false);
            const std::shared_ptr<const PackageIDSequence> ids((*_imp->params.environment())[selection::AllVersionsSorted(
                        generator::InRepository(name()))]);
            for (PackageIDSequence::ConstIterator i(ids->begin()), i_end(ids->end()) ;
                    i != i_end ; ++i)
            {
                if ((*i)->build_dependencies_key())
                    rewrite_done |= rewrite_dependencies((*i)->fs_location_key()->value() / (*i)->build_dependencies_key()->raw_name(),
                            (*i)->build_dependencies_key(), dep_rewrites);
                if ((*i)->run_dependencies_key())
                    rewrite_done |= rewrite_dependencies((*i)->fs_location_key()->value() / (*i)->run_dependencies_key()->raw_name(),
                            (*i)->run_dependencies_key(), dep_rewrites);
                if ((*i)->post_dependencies_key())
                    rewrite_done |= rewrite_dependencies((*i)->fs_location_key()->value() / (*i)->post_dependencies_key()->raw_name(),
                            (*i)->post_dependencies_key(), dep_rewrites);
                if ((*i)->suggested_dependencies_key())
                    rewrite_done |= rewrite_dependencies((*i)->fs_location_key()->value() / (*i)->suggested_dependencies_key()->raw_name(),
                            (*i)->suggested_dependencies_key(), dep_rewrites);
            }

            std::cout << std::endl << "Updating configuration files" << std::endl;

            for (DepRewrites::const_iterator i(dep_rewrites.begin()), i_end(dep_rewrites.end()) ;
                    i != i_end ; ++i)
                _imp->params.environment()->update_config_files_for_package_move(
                        make_package_dep_spec({ }).package(i->first),
                        i->second
                        );
        }

        if (! failed)
        {
            cache_dir.mkdir(0755, { fspmkdo_ok_if_exists });
            SafeOFStream cache_file_f(cache_file, -1, true);
            for (std::map<FSPath, std::time_t, FSPathComparator>::const_iterator it(update_timestamps.begin()),
                     it_end(update_timestamps.end()); it_end != it; ++it)
                cache_file_f << it->second << '\t' << it->first << std::endl;
        }
    }
    catch (const Exception & e)
    {
        Log::get_instance()->message("e.vdb.updates.exception", ll_warning, lc_context) <<
            "Caught exception '" << e.message() << "' (" << e.what() << ") when performing updates. This is "
            "probably bad.";
    }
}

const std::shared_ptr<const MetadataValueKey<std::string> >
VDBRepository::accept_keywords_key() const
{
    return make_null_shared_ptr();
}