~abentley/bzrtools/bzrtools.dev

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
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
# arch-tag: david@allouche.net - 2003-11-17 15:23:30 332029000
# Copyright (C) 2003 David Allouche <david@allouche.net>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

"""
Internal module providing top-level arch package names

This module implements the top-level public interface for the
arch_ package. But for convenience reasons the author prefers
to store this code in a file separate from ``__init__.py``.

.. _arch: arch-module.html

This module is strictly internal and should never be used.

:var tla_tells_empty_meta_info: The back-end can to tell empty archive
    meta-info files.

    The behaviour of ``tla`` is controlled by the _presence_ of some
    archive meta-info files, but many releases of tla gave no CLI
    feature to test for existence of meta-info file: the
    ``archive-meta-info`` command only gave the content of the file if
    it was present, and could not differenciate between empty and
    missing files.

    There is no cheap way to autodetect what is the behaviour of the
    currently installed command-line executable, so the behaviour of
    `arch.Archive` objects is configured by this variables.

:type tla_tells_empty_meta_info: bool

:var backend: See `arch.backend`

:var _arch: Internal deprecated interface to the backend
"""

### Package docstring ###

_package_doc = """\
High level bindings for the Arch revision control system

Archive Namespace Class Hierarchy
---------------------------------

:group Namespace Classes: Archive, Category, Branch, Version, Revision

:group Abstract Namespace Classes: NamespaceObject, Setupable, Package,
    CategoryIterable, BranchIterable, VersionIterable, RevisionIterable,
    ArchiveItem, CategoryItem, BranchItem, VersionItem

:group Archive-Related Classes: RevisionFile, NameParser

The archive namespace classes form a complex hierarchy which
cannot be appropriately described in individual classes.

The `Archive`, `Category`, `Branch`, `Version` and `Revision` classes
model the Arch namespace. Namespace objects can be created without the
corresponding archive structure being available.

Since they form a hierarchy of containers with shared methods and
properties in both directions, but do not have any subclass
relationship, they are defined using a collection of mixin classes.

The `RevisionIterable`, `VersionIterable`, `BranchIterable` and
`CategoryIterable` classes define the features which are inherited by
enclosing archive containers. Many methods in that hierarchy are
defined abstract (they raise UnimplementedError). They are always
overriden and are required to prevent legitimate PyChecker warnings.

The `ArchiveItem`, `CategoryItem`, `BranchItem` and `VersionItem`
classes provides features which are inherited by enclosed archive
items. The `NamespaceObject`, `Setupable` and `Package` classes
provide miscellaneous features and define aspects which do not fit
within the rest of the hierarchy.

::

  ,--------------------------------> NamespaceObject
  |                                   / \     / \\
  |                                    |       |
  | CategoryIterable <---- Archive ----'       |
  |         |                              ArchiveItem <-----.
  |         |                                 / \            |
  |        \ /                                 |             |
  | BranchIterable <------ Category -----------+-------> Setupable
  |         |                                  |              / \\
  |         |                                  |               |
  |         |                  ,---------------+---------> Package
  |        \ /                 |               |           / \  |
  | VersionIterable <----- Branch ------> CategoryItem      |   |
  |         |                                 / \           |   |
            |                                  |            |   |
  |         |                  ,---------------+------------'   |
  |        \ /                 |               |                |
  | RevisionIterable <---- Version -----> BranchItem            |
  |     |        / \                          / \               |
  |     |         |                            |                |
  `-----'         |                            |                |
                  |       Revision ----> VersionItem            |
                  |                                             |
                  `---------------------------------------------'


This admittedly complicated hierarchy minimizes code duplication and
provides abstract classes which can be used for testing objects for
features instead of testing for concrete types.


:group Source Tree Classes: SourceTree, ForeignTree, ArchSourceTree,
    LibraryTree, WorkingTree

:group Changeset and Log Classes: Changeset, Patchlog, LogMessage

:group Incremental Ouput: ChangesetCreation, ChangesetApplication,
    Chatter, TreeChange, FileAddition, FileDeletion, FileModification,
    FilePermissionsChange, FileRename, SymlinkModification,
    MergeOutcome, PatchConflict

:group Archive Functions: archives, iter_archives, make_archive,
    register_archive, get, get_patch, make_continuation

:group Source Tree Functions: init_tree, in_source_tree, tree_root

:group User Functions: default_archive, my_id, set_my_id

:group Changeset Generation Functions: changeset, delta, iter_delta

:group Pika Escaping Functions: name_escape, name_unescape

:group Revision Library Functions: register_revision_library,
    unregister_revision_library, iter_revision_libraries, library_archives,
    iter_library_archives

:group Incremental Output Functions: classify_chatter,
    classify_changeset_creation, classify_changeset_application

:group Obsolete Utility Functions: filter_archive_logs, filter_revisions,
    grep_summary, grep_summary_interactive, last_revision, map_name_id,
    revision_which_created, revisions_merging, suspected_move, temphack

:var backend: Backend controller.

    This object is used to configure the backend system: name of the
    executable, process handling strategy and command-line logging.

:type backend: `backends.commandline.CommandLineBackend`
"""

# Configuration option.
# If True, expect archive-meta-info exit(1) for missing meta-info.
# If False, expect it exit(0) and output nothing.
tla_tells_empty_meta_info = True

import os
import shutil
import itertools
import re
from sets import ImmutableSet
import errors
import util
from pathname import PathName, FileName, DirName
from deprecation import deprecated_usage, deprecated_callable
from _escaping import *
from _output import *

__all__ = []

def public(*names):
    __all__.extend(names)


### Backend abstraction and compatibility

class _BackendProxy(object):
    """Internal hack for compatibility with _arch"""
    def __getattribute__(self, name):
        return getattr(backend._module, name)
    def __setattr__(self, name, value):
        setattr(backend._module, name, value)

_arch = _BackendProxy()

from backends import commandline

backend = commandline.default_backend()

public('backend')


### Internal helpers for namespace sanity checks

class _unsafe(tuple):
    """Used internally to disable namespace sanity checks"""


def _archive_param(archive):
    """Internal argument checking utility"""
    if isinstance(archive, Archive):
        return archive.name
    else:
        if not NameParser.is_archive_name(archive):
            raise errors.NamespaceError(archive, 'archive name')
        return archive

def _registered_archive_param(archive):
    """Internal argument checking utility"""
    archive = _archive_param(archive)
    if not _arch.archive_registered(archive):
        raise errors.ArchiveNotRegistered(archive)
    return archive

def _archive_limit_param(archive, item):
    """Internal argument checking utility"""
    if isinstance(item, ArchiveItem):
        if archive != item.archive.name:
            message = "%s is not an item of %s" % (item.fullname, archive)
            raise ValueError(message)
        return item.nonarch
    else:
        p = NameParser(item)
        if not p.has_category():
            raise errors.NamespaceError(item, 'archive limit')
        if not p.has_archive():
            return item
        elif archive != p.get_archive():
            message = "%s is not an item of %s" % (item.fullname, archive)
            raise ValueError(message)
        else:
            return p.get_nonarch()

def _version_param(vsn):
    """Internal argument checking utility"""
    if isinstance(vsn, Version):
        return vsn.fullname
    else:
        p = NameParser(vsn)
        if not p.has_archive() or not p.is_version():
            raise errors.NamespaceError(vsn, 'fully-qualified version')
        return vsn

def _revision_param(rev):
    """Internal argument checking utility."""
    if isinstance(rev, Revision):
        return rev.fullname
    else:
        p = NameParser(rev)
        if not p.has_archive() or not p.has_patchlevel():
            raise errors.NamespaceError(rev, 'fully-qualified revision')
        return rev

def _version_revision_param(vsn_rev):
    """Internal argument checking utility"""
    if isinstance(vsn_rev, BranchItem):
        return vsn_rev.fullname
    else:
        p = NameParser(vsn_rev)
        if not p.has_archive() or not p.has_version():
            raise errors.NamespaceError(vsn_rev,
                                        'fully-qualified version or revision')
        return vsn_rev

def _package_revision_param(pkg_rev):
    """Internal argument checking utility"""
    if isinstance(pkg_rev, CategoryItem):
        return pkg_rev.fullname
    else:
        p = NameParser(pkg_rev)
        if not p.has_archive() or not p.has_package():
            raise errors.NamespaceError(pkg_rev,
                                        'fully-qualified package or revision')
        return pkg_rev

def _check_version_param(param, name):
    """Internal argument checking utility"""
    if not isinstance(param, Version):
        raise TypeError("Parameter \"%r\" must be a Version, but was: %r" \
                        % (name, param))

def _check_revision_param(param, name):
    """Internal argument checking utility"""
    if not isinstance(param, Revision):
        raise TypeError("Parameter \"%s\" must be a Revision"
                        " but was: %r" % (name, param))

def _check_relname_param(param, name):
    """Internal argument checking utility"""
    if not isinstance(param, basestring):
        exc_type = TypeError
    elif os.path.isabs(param):
        exc_type = ValueError
    else:
        return
    raise exc_type("Parameter \"%s\" must be a relative path (string)"
                   " but was: %r" % (name, param))


### Base class for all namespace classes ###

public('NamespaceObject')

class NamespaceObject(object):

    """Base class for all archive objects."""

    def get_fullname(self):
        """Deprecated

        Fully qualified name of this namespace object.

        :rtype: str
        :see: `NamespaceObject.fullname`
        """
        raise NotImplementedError

    fullname = property(get_fullname, doc = """
    Fully qualfied name of this namespace object.

    :type: str
    """)

    def exists(self):
        """Does this namespace exists?

        Within the Arch model, history cannot be changed: created archive
        entries cannot be deleted. However, it is possible to ``unregister`` an
        archive, or to find references to archives whose location is not known.
        Thus, existence cannot always be decided. Testing for the existence of
        a name in a non-registered archive raises
        `errors.ArchiveNotRegistered`.

        :return: whether this namespace object exists.
        :rtype: bool
        :raise errors.ArchiveNotRegistered: the archive name is not registered,
            so existence cannot be decided.
        :raise errors.ExecProblem: there was a problem accessing the archive.
        """
        raise NotImplementedError

    def __repr__(self):
        """Fully-qualified name in angle brackets.

        :rtype: str
        """
        return '<%s>' % self.fullname

    def __str__(self):
        """Fully-qualified name.

        Returns the value of the fullname attribute.

        :rtype: str
        """
        return self.fullname

    def __eq__(self, x):
        """Compare types and fully-qualified names.

        :return: wether objects have the same types and names.
        :rtype: bool
        """
        return type(self) is type(x) \
               and self.__class__ is x.__class__ \
               and self.fullname == x.fullname

    def __ne__(self, x):
        """Compare types and fully-qualified names.

        :return: whether objects have different types or names.
        :rtype: bool
        """
        return type(self) is not type(x) \
               or self.__class__ is not x.__class__ \
               or self.fullname != x.fullname


### Mixins for archive iteration aspect ###

public(
    'RevisionIterable',
    'VersionIterable',
    'BranchIterable',
    'CategoryIterable',
    )

class RevisionIterable(NamespaceObject):

    """Abstract class for namespace classes above Revision.

    RevisionIterable provides features which are common to all objects
    containing revisions.
    """

    def iter_revisions(self, reverse=False):
        """Iterate over archive revisions.

        :param reverse: reverse order, recent revisions first.
        :type reverse: bool
        :return: all existing revisions in this namespace.
        :rtype: iterable of `Revision`

        :precondition: `self.exists()` returns ``True``.
        """
        raise NotImplementedError

    def iter_library_revisions(self, reverse=False):
        """Iterate over library revisions.

        :param reverse: reverse order, recent revisions first.
        :type reverse: bool
        :return: revisions in this namespace which are present in the
            revision library.
        :rtype: iterable of `Revision`
        """
        raise NotImplementedError


class VersionIterable(RevisionIterable):

    """Abstract class for archive classes above Version.

    VersionIterable provides features which are common to all objects
    containing versions.
    """

    def iter_versions(self, reverse=False):
        """Iterate over archive versions.

        :param reverse: reverse order, higher versions first.
        :type reverse: bool
        :return: all existing versions in this namespace.
        :rtype: iterable of `Version`

        :precondition: `self.exists()` returns ``True``.
        """
        raise NotImplementedError

    def iter_library_versions(self, reverse=False):
        """Iterate over library revisions.

        :param reverse: reverse order, higher versions first.
        :type reverse: bool
        :return: versions in this namespace which are present in the
            revision library.
        :rtype: iterable of `Version`
        """
        raise NotImplementedError

    def iter_revisions(self, reverse=False):
        for v in self.iter_versions(reverse):
            for r in v.iter_revisions(reverse): yield r

    def iter_library_revisions(self, reverse=False):
        for v in self.iter_library_versions(reverse):
            for r in v.iter_library_revisions(reverse): yield r


class BranchIterable(VersionIterable):

    """Base class for archive classes above Branch.

    BranchIterable provides features which are common to all objects
    containing branches.
    """

    def iter_branches(self):
        """Iterate over archive branches.

        :return: all existing branches in this namespace.
        :rtype: iterable of `Branch`
        :precondition: `self.exists()` returns ``True``.
        """
        raise NotImplementedError

    def iter_library_branches(self):
        """Iterate over library branches.

        :return: branches in this namespace which are present in the
            revision library.
        :rtype: iterable of `Branch`
        """
        raise NotImplementedError

    def iter_versions(self, reverse=False):
        for b in self.iter_branches():
            for v in b.iter_versions(reverse): yield v

    def iter_library_versions(self, reverse=False):
        for b in self.iter_library_branches():
            for v in b.iter_library_versions(reverse): yield v


class CategoryIterable(BranchIterable):

    """Base class for Archive.

    CategoryIterable provides features for the aspect of Archive wich
    relates to its containing other archive objects.
    """

    def iter_categories(self):
        """Iterate over archive categories.

        :return: all existing categories in this namespace.
        :rtype: iterable of `Category`
        :precondition: `self.exists()` returns ``True``.
        """
        raise NotImplementedError

    def iter_library_categories(self):
        """Iterate over library categories.

        :return: categories in this namespace which are present in the
            revision library.
        :rtype: iterable of `Category`
        """
        raise NotImplementedError

    def iter_branches(self):
        for c in self.iter_categories():
            for b in c.iter_branches(): yield b

    def iter_library_branches(self):
        for c in self.iter_library_categories():
            for b in c.iter_library_branches(): yield b


### Base classes for archive containment aspect ###

public(
    'ArchiveItem',
    'CategoryItem',
    'BranchItem',
    'VersionItem',
    )

class ArchiveItem(NamespaceObject):

    """Base class for all archive components classes.

    ArchiveItem provides features common to all objects which are
    structural components of Archive.
    """

    def __init__(self, archive, nonarch):
        self._archive = archive
        self._nonarch = nonarch

    def get_archive(self):
        """Deprecated.

        Archive which contains this namespace object.

        :rtype: `Archive`
        :see: `ArchiveItem.archive`
        """
        deprecated_callable(self.get_archive, (type(self), 'archive'))
        return self.archive

    def _get_archive(self):
        return Archive(_unsafe((self._archive,)))

    archive = property(_get_archive, doc="""
    Archive which contains this namespace object.

    :type: `Archive`
    """)

    def get_nonarch(self):
        """Deprecated.

        Non-arch part of this namespace name.

        :rtype: str
        :see: `ArchiveItem.nonarch`
        """
        deprecated_callable(self.get_nonarch, (type(self), 'nonarch'))
        return self.nonarch

    def _get_nonarch(self):
        return self._nonarch

    nonarch = property(_get_nonarch, doc="""
    Non-arch part of this namespace name.

    :type: str
    """)

    def get_fullname(self):
        deprecated_callable(self.get_fullname, (type(self), 'fullname'))
        return self.fullname

    def _get_fullname(self):
        return '%s/%s' % (self._archive, self._nonarch)

    fullname = property(_get_fullname, doc=NamespaceObject.fullname.__doc__)


class CategoryItem(ArchiveItem):

    """Base class for archive classes below Category.

    CategoryItem provides features common to all objects which are
    structural components of Category.
    """

    def get_category(self):
        """Deprecated.

        Category which contains this namespace object.

        :rtype: `Category`
        :see: `CategoryItem.category`
        """
        deprecated_callable(self.get_category, (type(self), 'category'))
        return self.category

    def _get_category(self):
        return Category(_unsafe((self._archive, self._nonarch.split('--')[0])))

    category = property(_get_category, doc="""
    Category which contains this object.

    :type: `Category`
    """)


class BranchItem(CategoryItem):

    """Base class for archive classes Version and Revision.

    BranchItem provides features common to all objects which are
    structural components of Branch.
    """

    def get_branch(self):
        """Deprecated.

        Branch which contains this object.

        :rtype: `Branch`
        :see: `BranchItem.branch`
        """
        deprecated_callable(self.get_branch, (type(self), 'branch'))
        return self.branch

    def _get_branch(self):
        assert isinstance(self, Version)
        package = '--'.join(self._nonarch.split('--')[0:-1])
        return Branch(_unsafe((self._archive, package)))

    branch = property(_get_branch, doc="""
    Branch which contains this namespace object.

    :type: `Branch`
    """)


class VersionItem(BranchItem):

    """Base class for Revision.

    VersionItem provides features for the aspect of Revision which
    relate to its containment within other archive objects.
    """

    def __init__(self, archive, version, patchlevel):
        BranchItem.__init__(self, archive, "%s--%s" % (version, patchlevel))
        self._version, self._patchlevel = version, patchlevel

    def get_branch(self):
        deprecated_callable(self.get_branch, (type(self), 'branch'))
        return self.branch

    def _get_branch(self):
        assert isinstance(self, Revision)
        package = '--'.join(self._version.split('--')[0:-1])
        return Branch(_unsafe((self._archive, package)))

    branch = property(_get_branch, doc=BranchItem.branch.__doc__)

    def get_version(self):
        """Deprecated.

        Version which contains this revision.

        :rtype: `Version`
        :see: `VersionItem.version`
        """
        deprecated_callable(self.get_version, (type(self), 'version'))
        return self.version

    def _get_version(self):
        return Version(_unsafe((self._archive, self._version)))

    version = property(_get_version, doc="""
    Version which contains this revision.

    :type: `Version`
    """)

    def get_patchlevel(self):
        """Deprecated.

        Patch-level part of this object's name.

        :rtype: str
        :see: `VersionItem.patchlevel`
        """
        deprecated_callable(self.get_patchlevel, (type(self), 'patchlevel'))
        return self.patchlevel

    def _get_patchlevel(self):
        return self._patchlevel

    patchlevel = property(_get_patchlevel, doc="""
    Patch-level part of this object's name.

    :type: str
    """)


### Mixins for misc. features of archive objects ###

public('Setupable', 'Package')

class Setupable(ArchiveItem):

    """Base class for container archive objects."""

    def setup(self):
        """Create this namespace in the archive.

        :precondition: self.archive.exists()
        :postcondition: `self.exists()`
        :raise errors.ExecProblem: the archive is not registered or
            there was a problem accessing the archive
        """
        # FIXME: do not do the right thing for anonymous branches
        _arch.archive_setup(self.fullname)


class Package(Setupable, RevisionIterable):

    """Base class for ordered container archive objects."""

    def as_revision(self):
        """Deprecated.

        Latest revision in this package.

        :rtype: `Revision`
        :precondition: `self.exists()` returns ``True``
        :precondition: `self.iter_revisions()` yields at least one object.
        :raises StopIteration: this package contains no revision
        :see: `Package.latest_revision`
        """
        deprecated_callable(self.as_revision, self.latest_revision)
        return self.iter_revisions(reverse=True).next()

    def latest_revision(self):
        """Latest revision in this package.

        :rtype: `Revision`
        :precondition: `self.exists()` returns ``True``
        :precondition: `self.iter_revisions()` yields at least one object.
        :raises ValueError: the archive is not registered, or this
            package does not exist, or it contains no revision.
        """
        try:
            return self.iter_revisions(reverse=True).next()
        except errors.ExecProblem:
            try:
                self_exists = self.exists()
            except errors.ArchiveNotRegistered:
                raise ValueError('Archive is not registered: %s'
                                 % self.archive)
            if not self_exists:
                raise ValueError('Package does not exist: %s' % self)
            raise
        except StopIteration:
            raise ValueError('Package contains no revision: %s' % self)


### Archive classes ###

public('Archive', 'Category', 'Branch', 'Version', 'Revision')

class Archive(CategoryIterable):

    """Arch archive namespace object.

    In the Arch revision control system, archives are the units of
    storage. They store revisions organized in categories, branches
    and versions, and are associated to a `name` and a `location`.

    :see: `Category`, `Branch`, `Version`, `Revision`
    """

    def __init__(self, name):
        """Create an archive object from its registered name.

        :param name: archive name, like "jdoe@example.com--2003"
        :type name: str
        :raise errors.NamespaceError: invalid archive name.
        """
        if isinstance(name, Archive):
            name = name.__name
        if isinstance(name, _unsafe):
            assert len(name) == 1
            name = name[0]
        elif not NameParser.is_archive_name(name):
            raise errors.NamespaceError(name, 'archive name')
        self.__name = name

    def get_name(self):
        """Deprecated.

        Logical name of the archive.

        :rtype: str
        :see: `Archive.name`
        """
        deprecated_callable(Archive.get_name, (Archive, 'name'))
        return self.name

    def _get_name(self):
        return self.__name

    name = property(_get_name, doc="""
    Logical name of the archive.

    :type: str
    """)

    def get_fullname(self):
        deprecated_callable(Archive.get_fullname, (Archive, 'fullname'))
        return self.name

    fullname = property(_get_name, doc=NamespaceObject.fullname.__doc__)

    def get_location(self):
        """Deprecated.

        URI of the archive, specifies location and access method.

        :rtype: str
        :see: `Archive.location`
        """
        deprecated_callable(Archive.get_location, (Archive, 'location'))
        return self.location

    def _get_location(self):
        return _arch.whereis_archive(self.name)

    location = property(_get_location, doc="""
    URI of the archive, specifies location and access method.

    For example 'http://ddaa.net/arch/2004', or
    'sftp://user@sourcecontrol.net/public_html/2004'.

    :type: str
    """)

    def _meta_info(self, key):
        return _arch.archive_meta_info(self.name, key)

    def _has_meta_info(self, key):
        if tla_tells_empty_meta_info:
            try:
                _arch.archive_meta_info(self.name, key)
                return True
            except KeyError:
                return False
        else:
            return _arch.archive_meta_info(self.name, key) is not None

    def get_is_mirror(self):
        """Deprecated.

        Is this archive registration a mirror?

        :rtype: bool
        :see: Archive.is_mirror
        """
        deprecated_callable(Archive.get_is_mirror, (Archive, 'is_mirror'))
        return self.is_mirror

    def _get_is_mirror(self):
        return self._has_meta_info('mirror')

    is_mirror = property(_get_is_mirror, doc="""
    Is this archive registration a mirror?

    :type: bool
    """)

    def get_official_name(self):
        """Deprecated.

        Official archive name of this archive registration.

        :rtype: str
        :see: `Archive.official_name`
        """
        deprecated_callable(Archive.get_official_name,
                            (Archive, 'official_name'))
        return self.official_name

    def _get_official_name(self):
        return _arch.archive_meta_info(self.name, 'name')

    official_name = property(_get_official_name, doc="""
    Official archive name of this archive registration.

    :type: str
    """)

    def get_is_signed(self):
        """Deprecated.

        Is the archive GPG-signed?

        :rtype: bool
        :see: `Archive.is_signed`
        """
        deprecated_callable(Archive.get_is_signed, (Archive, 'is_signed'))
        return self.is_signed

    def _get_is_signed(self):
        return self._has_meta_info('signed-archive')

    is_signed = property(_get_is_signed, doc="""
    Is the archive GPG-signed?

    :type: bool
    """)

    def get_has_listings(self):
        """Deprecated.

        Does the archive provide .listing file for http access?

        :rtype: bool
        :see: `Archive.has_listings`
        """
        deprecated_callable(Archive.get_has_listings,
                            (Archive, 'has_listings'))
        return self.has_listings

    def _get_has_listings(self):
        return self._has_meta_info('http-blows')

    has_listings = property(_get_has_listings, doc="""
    Does the archive provide .listing file for http access?

    :type: bool
    """)

    def _get_version_string(self):
        location = '/'.join((self.location, '.archive-version'))
        import urllib
        version_file = urllib.urlopen(location)
        try:
            ret = version_file.read()
        finally:
            version_file.close()
        return ret.rstrip()

    version_string = property(_get_version_string, doc="""
    Version string of the archive.

    Contents of the ``.archive-version`` file at the root of the archive.

    :type: str
    """)

    def __getitem__(self, category):
        """Instanciate a Category belonging to this archive.

        :param category: unqualified category name
        :type category: str
        :rtype: `Category`
        """
        if not NameParser.is_category_name(category):
            raise errors.NamespaceError(category, 'unqualified category name')
        return Category(_unsafe((self.name, category)))

    def exists(self):
        if _arch.archive_registered(self.name):
            return True
        else:
            raise errors.ArchiveNotRegistered(self.name)

    def is_registered(self):
        """Is this archive registered?

        :return: Whether the location associated to this registration name is
            known.
        :rtype: bool
        :see: `register_archive`, `Archive.unregister`
        """
        return _arch.archive_registered(self.name)

    def iter_categories(self):
        for c in _arch.categories(self.name):
            yield Category(_unsafe((self.name, c)))

    def iter_library_categories(self):
        for c in _arch.library_categories(self.name):
            yield Category(_unsafe((self.name, c)))

    def get_categories(self):
        """Deprecated.

        Categories in this archive.

        :rtype: tuple of `Category`
        :see: `iter_categories`
        """
        deprecated_callable(Archive.get_categories, Archive.iter_categories)
        return tuple(self.iter_categories())

    def _get_categories(self):
        deprecated_callable((Archive, 'categories'), Archive.iter_categories)
        return tuple(self.iter_categories())

    categories = property(_get_categories, doc="""
        Deprecated.

        Categories in this archive.

        :type: tuple of `Category`
        :see: `iter_categories`
        """)

    def get_library_categories(self):
        """Deprecated.

        Categories in this archive  present in the library.

        :rtype: tuple of `Category`
        :see: `iter_library_categories`
        """
        deprecated_callable(Archive.get_library_categories,
                            Archive.iter_library_categories)
        return tuple(self.iter_library_categories())

    def _get_library_categories(self):
        deprecated_callable((Archive, 'library_categories'),
                            Archive.iter_library_categories)
        return tuple(self.iter_library_categories())

    library_categories = property(_get_library_categories, doc="""
    Deprecated.

    Categories in this archive  present in the library.

    :type; tuple of `Category`
    :see: `iter_library_categories`
    """)

    def unregister(self):
        """Unregister this archive.

        :precondition: `self.is_registered()`
        :postcondition: not `self.is_registered()`
        :see: `register_archive`
        """
        return _arch.unregister_archive(self.name)

    def make_mirror(self, name, location, signed=False, listing=False):
        """Create and register a new mirror of this archive.

        :param name: name of the new mirror (for example
            'david@allouche.net--2003b-MIRROR').
        :type name: str
        :param location: writeable URI were to create the archive mirror.
        :type location: str
        :param signed: create GPG signatures for the mirror contents
        :type signed: bool
        :param listing: maintains ''.listing'' files to enable HTTP access.
        :type listing: bool

        :return: object for the newly created archive mirror.
        :rtype: `Archive`

        :precondition: `self.is_registered()`
        :precondition: ``name`` is not a registered archive name
        :precondition: ``location`` does not exist and can be created
        :postcondition: Archive(name).is_registered()

        :raise errors.NamespaceError: ``name`` is not a valid archive name.
        """
        a = Archive(name) # check archive name validity first
        _arch.make_archive_mirror(self.official_name, name, location,
                                  signed, listing)
        return a

    def mirror(self, limit=None, fromto=None,
               no_cached=False, cached_tags=False):
        """Update an archive mirror.

        :param limit: restrict mirrorring to those archive items. All items
            must belong to this archive.
        :type limit: iterable of at least one ArchiveItem or str

        :param fromto: update the mirror specified by the second item with the
            contents of the archive specified by the first item.
        :type fromto: sequence of exactly two Archive or str.

        :precondition: If ``fromto`` is provided, both items must be registered
            archives names whose official name is this archive.

        :param no_cached: do not copy cached revisions.
        :type no_cached: bool

        :param cached_tags: copy only cachedrevs for tags to other archives.
        :type cached_tags: bool
        """
        if limit:
            limit = map(lambda x: _archive_limit_param(self.name, x), limit)
        if fromto is None:
            _arch.archive_mirror(self.name, None, limit=limit,
                                 no_cached=no_cached, cached_tags=cached_tags)
        if fromto is not None:
            from_, to = map(_registered_archive_param, fromto)
            _arch.archive_mirror(from_, to, limit=limit,
                                 no_cached=no_cached, cached_tags=cached_tags)


class Category(Setupable, BranchIterable):

    """Arch category namespace object.

    :see: `Archive`, `Branch`, `Version`, `Revision`
    """

    def __init__(self, name):
        """Create a category object from its name.

        :param name: fully-qualified category name, like
          "jdoe@example.com/frob"
        :type name: str
        :raise errors.NamespaceError: ``name`` is not a valid category name.
        """
        if isinstance(name, Category):
            name = (name._archive, name._nonarch)
        elif not isinstance(name, _unsafe):
            p = NameParser(name)
            if not p.has_archive() or not p.is_category():
                raise errors.NamespaceError(name, 'fully-qualified category')
            name = (p.get_archive(), p.get_nonarch())
        ArchiveItem.__init__(self, *name)

    def __getitem__(self, b):
        """Instanciate a branch belonging to this category.

        For example ``Category('jdoe@example.com/frob')['devel']`` is
        equivalent to ``Branch('jdoe@example.com/frob--devel')``.

        :param b: branch id.
        :type b: str
        :rtype: `Category`

        :raise NamespaceError: argument is not a valid branch id.
        """
        if b is not None and not NameParser.is_branch_name(b):
            raise errors.NamespaceError(b, 'unqualified branch name')
        if b is None:                   # nameless branch
            return Branch(_unsafe((self._archive, self._nonarch)))
        else:                           # named branch
            return Branch(_unsafe((self._archive,
                                   "%s--%s" % (self._nonarch, b))))

    def exists(self):
        return _arch.category_exists(self._archive, self._nonarch)

    def iter_branches(self):
        for b in _arch.branches(self.fullname):
            yield Branch(_unsafe((self._archive, b)))

    def iter_library_branches(self):
        for b in _arch.library_branches(self.fullname):
            yield Branch(_unsafe((self._archive, b)))

    def get_branches(self):
        """Deprecated.

        Branches in this category.

        :rtype: tuple of `Branch`
        :see: `iter_branches`
        """
        deprecated_callable(self.get_branches, self.iter_branches)
        return tuple(self.iter_branches())

    def _get_branches(self):
        deprecated_callable((type(self), 'branches'), self.iter_branches)
        return tuple(self.iter_branches())

    branches = property(_get_branches, doc="""
    Deprecated.

    Branches in this category.

    :type: tuple of `Branch`
    :see: `Category.iter_branches`
    """)

    def get_library_branches(self):
        """Deprecated.

        Branches in this category present in the library.

        :rtype: tuple of `Branch`
        :see: `iter_library_branches`
        """
        deprecated_callable(self.get_library_branches,
                            self.iter_library_branches)
        return tuple(self.iter_library_branches())

    def _get_library_branches(self):
        deprecated_callable((Category, 'library_branches'),
                            self.iter_library_branches)
        return tuple(self.iter_library_branches())

    library_branches = property(_get_library_branches, doc="""
    Deprecated.

    Branches in this category present in the library.

    :type: tuple of `Branch`
    :see: `Category.iter_branches`
    """)


class Branch(CategoryItem, Package, VersionIterable):

    """Arch branch namespace object.

    :see: `Archive`, `Category`, `Version`, `Revision`
    """

    def __init__(self, name):
        """Create a Branch object from its name.

        :param name: fully-qualified branch name, like
            "jdoe@example.com--2004/frob--devo" or
            "jdoe@example.com--2004/frob".
        :type name: str
        :raise errors.NamespaceError: ``name`` is not a valid branch name.
        """
        if isinstance(name, Branch):
            name = (name._archive, name._nonarch)
        elif not isinstance(name, _unsafe):
            p = NameParser(name)
            if not p.has_archive() or not p.is_package():
                raise errors.NamespaceError(name, 'fully-qualified branch')
            assert p.is_package()
            name = (p.get_archive(), p.get_nonarch())
        CategoryItem.__init__(self, *name)

    def __getitem__(self, v):
        """Instanciate a version belonging to this branch.

        For example ``Branch('jdoe@example.com/frob--devel')['0']`` is
        equivalent to ``Branch('jdoe@example.com/frob--devel--0')``.

        :param v: branch id.
        :type v: str
        :rtype: `Version`

        :raise NamespaceError: argument is not a valid version id.
        """
        if not NameParser.is_version_id(v):
            raise errors.NamespaceError(v, 'version id')
        return Version(_unsafe((self._archive, "%s--%s" % (self._nonarch, v))))

    def exists(self):
        return _arch.branch_exists(self._archive, self._nonarch)

    def iter_versions(self, reverse=False):
        for v in _arch.versions(self.fullname, reverse):
            yield Version(_unsafe((self._archive, v)))

    def iter_library_versions(self, reverse=False):
        for v in _arch.library_versions(self.fullname, reverse):
            yield Version(_unsafe((self._archive, v)))

    def get_versions(self, reverse=False):
        """Deprecated.

        Versions in this branch.

        :rtype: tuple of `Version`
        :see: `iter_versions`
        """
        deprecated_callable(self.get_versions, self.iter_versions)
        return tuple(self.iter_versions(reverse))

    def _get_versions(self):
        deprecated_callable((Branch, 'versions'), self.iter_versions)
        return tuple(self.iter_versions(reverse=False))

    versions = property(_get_versions, doc="""
    Deprecated.

    Versions in this branch.

    :type: tuple of `Version`
    :see: `iter_versions`
    """)

    def get_library_versions(self, reverse=False):
        """Deprecated.

        Versions in this branch present in the library.

        :rtype: tuple of `Version`
        :see: `iter_library_versions`
        """
        deprecated_callable(self.get_library_versions,
                            self.iter_library_versions)
        return tuple(self.iter_library_versions(reverse))

    def _get_library_versions(self):
        deprecated_callable((Branch, 'library_versions'),
                            self.iter_library_versions)
        return tuple(self.iter_library_versions(reverse=False))

    library_versions = property(_get_library_versions, doc="""
    Deprecated.

    Versions in this branch present in the library.

    :type: tuple of `Version`
    :see: `iter_library_versions`
    """)

    def as_version(self):
        """Deprecated.

        Latest version in this branch.

        :rtype: `Version`
        :precondition: `self.exists()` returns ``True``
        :precondition: `self.iter_versions` yields at least one object.
        :raise IndexError: this branch is empty.
        :see: `latest_version`
        """
        deprecated_callable(self.as_version, self.latest_version)
        return list(self.iter_versions(reverse=True))[0]

    def latest_version(self):
        """Latest version in this branch.

        :rtype: `Version`
        :precondition: `self.exists()` returns ``True``
        :precondition: `self.iter_versions` yields at least one object.
        :raise ValueError: the archive is not registered, or this branch does
            not exist, or it contains no version.
        """
        try:
            return self.iter_versions(reverse=True).next()
        except errors.ExecProblem:
            try:
                self_exists = self.exists()
            except errors.ArchiveNotRegistered:
                raise ValueError('Archive is not registered: %s'
                                 % self.archive)
            if not self_exists:
                raise ValueError('Branch does not exist: %s' % self)
            raise
        except StopIteration:
            raise ValueError('Branch contains no version: %s' % self)



class Version(BranchItem, Package, RevisionIterable):

    """Arch version namespace object.

    :see: `Archive`, `Category`, `Branch`, `Revision`
    """

    def __init__(self, name):
        """Create a Version object from its name.

        :param name: fully-qualified version name, like
           "jdoe@example.com--2004/frob--devo--1.2".
        :type name: str

        :note: Nameless branches have no "branch" part in their name.
        """
        if isinstance(name, Version):
            name = (name._archive, name._nonarch)
        elif not isinstance(name, _unsafe):
            p = NameParser(name)
            if not p.has_archive() or not p.is_version():
                raise errors.NamespaceError(name, 'fully-qualified version')
            name = (p.get_archive(), p.get_nonarch())
        BranchItem.__init__(self, *name)

    def __getitem__(self, lvl):
        """Instanciate a revision belonging to this version.

        For example ``Version('jdoe@example.com/frob--devel--0')['patch-1']``
        is equivalent to
        ``Revision('jdoe@example.com/frob--devel--0--patch1')``.

        :param lvl: patch level.
        :type lvl: str
        :rtype: `Revision`

        :raise NamespaceError: argument is not a valid version patchlevel.
        """
        if not NameParser.is_patchlevel(lvl):
            raise errors.NamespaceError(lvl, 'unqualified patchlevel')
        return Revision(_unsafe((self._archive, self._nonarch, lvl)))

    def as_version(self):
        """Deprecated.

        This version.

        :rtype: `Version`
        """
        deprecated_callable(self.as_version, because='Foolish consistency.')
        return self

    def exists(self):
        return _arch.version_exists(self._archive, self._nonarch)

    def iter_revisions(self, reverse=False):
        for lvl in _arch.revisions(self.fullname, reverse):
            yield Revision(_unsafe((self._archive, self._nonarch, lvl)))

    def iter_library_revisions(self, reverse=False):
        for lvl in _arch.library_revisions(self.fullname, reverse):
            yield Revision(_unsafe((self._archive, self._nonarch, lvl)))

    def get_revisions(self, reverse=False):
        """Deprecated.

        Revisions in this version.

        :rtype: tuple of `Revision`
        :see: `iter_revisions`
        """
        deprecated_callable(self.get_revisions, self.iter_revisions)
        return tuple(self.iter_revisions(reverse))

    def _get_revisions(self):
        deprecated_callable((Version, 'revisions'), self.iter_revisions)
        return tuple(self.iter_revisions(reverse=False))

    revisions = property(_get_revisions, doc="""
    Deprecated.

    Revisions in this version.

    :type: tuple of `Revision`
    :see: `iter_revisions`
    """)

    def get_library_revisions(self, reverse=False):
        """Deprecated.

        Revisions in this version present in the library.

        :rtype: tuple of `Revision`
        :see: `iter_library_revisions`
        """
        deprecated_callable(self.get_library_revisions,
                            self.iter_library_revisions)
        return tuple(self.iter_library_revisions(reverse))

    def _get_library_revisions(self):
        deprecated_callable((Version, 'library_revisions'),
                            self.iter_library_revisions)
        return tuple(self.iter_library_revisions(reverse=False))

    library_revisions = property(_get_library_revisions, doc="""
    Deprecated.

    Revisions in this version present in the library.

    :type: tuple of `Revision`
    :see: `iter_library_revisions`
    """)

    def iter_merges(self, other=None, reverse=False, metoo=True):
        """Iterate over merge points in this version.

        This method is mostly useful to save multiple invocations of
        the command-line tool and multiple connection to a remote
        archives when building an ancestry graph. Ideally, it would
        not be present and the desired merge graph traversal would be
        done using the new_patches and merges properties of Patchlog
        objects.

        :param other: list merges with that version.
        :type other: `Version`
        :param reverse: reverse order, recent revisions first.
        :type reverse: bool
        :param metoo: do not report the presence of a patch within itself
        :type metoo: bool

        :return: Iterator of tuples (R, T) where R are revisions in this
            version and T are iterable of revisions in the ``other`` version.
        :rtype: iterable of `Revision`
        """
        if other is None: othername = None
        else: othername = other.fullname
        flow = _arch.iter_merges(self.fullname, othername, reverse, metoo)
        last_target = None
        sources = []
        for target, source in flow:
            if last_target is None:
                last_target = target
            if target == last_target:
                sources.append(source)
            else:
                yield self[last_target], itertools.imap(Revision, sources)
                last_target = target
                sources = [source]
        yield self[last_target], itertools.imap(Revision, sources)

    def iter_cachedrevs(self):
        """Iterate over the cached revisions in this version.

        :rtype: iterator of `Revision`
        """
        for rev in _arch.cachedrevs(self.fullname):
            lvl = rev.split('--')[-1]
            yield self[lvl]


class Revision(VersionItem):

    """Arch revision namespace object.

    :see: `Archive`, `Category`, `Branch`, `Version`
    :group Libray Methods: library_add, library_remove, library_find
    :group History Methods: get_ancestor, get_previous, iter_ancestors
    """

    def __init__(self, name):
        """Create a Revision object from its name.

        :param name: fully-qualified revision, like
            "jdoe@example.com--2004/frob--devo--1.2--patch-2".
        :type name: str

        :note: Nameless branches have no "branch" part in their name.
        """
        if isinstance(name, Revision):
            name = (name._archive, name._version, name._patchlevel)
        elif not isinstance(name, _unsafe):
            p = NameParser(name)
            if not p.has_archive() or not p.has_patchlevel():
                raise errors.NamespaceError(name, 'fully-qualified revision')
            name = (p.get_archive(), p.get_package_version(),
                    p.get_patchlevel())
        VersionItem.__init__(self, *name)
        self.__patchlog = Patchlog(self)

    def as_revision(self):
        """Deprecated

        Returns this revision. For consistency with `Package.as_revision()`.

        :rtype: `Revision`
        """
        deprecated_callable(self.as_revision, because='Foolish consistency.')
        return self

    def exists(self):
        return _arch.revision_exists \
               (self._archive, self._version, self._patchlevel)

    def get(self, dir, link=False):
        """Construct a project tree for this revision.

        Extract this revision from the archive.

        :param dir: path of the project tree to create. Must not
            already exist.
        :type dir: str
        :param link: hardlink files to revision library instead of copying
        :type link: bool
        :return: newly created project tree.
        :rtype: `WorkingTree`
        """
        _arch.get(self.fullname, dir, link)
        return WorkingTree(dir)

    def get_patch(self, dir):
        """Fetch the changeset associated to this revision.

        :param dir: name of the changeset directory to create. Must
            not already exist.
        :type dir: str
        :return: changeset associated to this revision.
        :rtype: `Changeset`
        """
        _arch.get_patch(self.fullname, dir)
        return Changeset(dir)

    def get_patchlog(self):
        """Deprecated.

        Patchlog associated to this revision.

        :rtype: `Patchlog`
        :see: `Revision.patchlog`
        """
        deprecated_callable(self.get_patchlog, (Revision, 'patchlog'))
        return self.patchlog

    def _get_patchlog(self):
        return self.__patchlog

    patchlog = property(_get_patchlog, doc="""
    Patchlog associated to this revision.

    The `Patchlog` object is created in `__init__`, since log parsing is
    deferred that has little overhead and avoid parsing the log for a given
    revision several times. The patchlog data is read from the archive.

    :type: `Patchlog`
    :see: `ArchSourceTree.iter_logs`
    """)

    def make_continuation(self, target):
        """Create a continuation of this revision in the target version.

        :param target: version to create a continuation into. If it does not
            exist yet, it is created.
        :type target: Version
        """
        _check_version_param(target, 'target')
        target_name = target.fullname
        _arch.archive_setup(target_name)
        _arch.tag(self.fullname, target_name)

    def library_add(self, library=None):
        """Add this revision to the library.

        :postcondition: self in self.version.iter_library_revisions()
        """
        _arch.library_add(self.fullname, library)

    def library_remove(self):
        """Remove this revision from the library.

        :precondition: self in self.version.iter_library_revisions()
        :postcondition: self not in self.version.iter_library_revisions()
        """
        _arch.library_remove(self.fullname)

    def library_find(self):
        """The copy of this revision in the library.

        :rtype: `LibraryTree`
        :precondition: self in self.version.iter_library_revisions()
        """
        return LibraryTree(_arch.library_find(self.fullname))

    #def library_file(self, file):
    #    raise NotImplementedError, "library_file is not yet implemented"

    def get_ancestor(self):
        """Deprecated.

        Parent revision.

        :return:
            - The previous namespace revision, if this revision is regular
              commit.
            - The tag origin, if this revision is a continuation
            - ``None`` if this revision is an import.

        :rtype: `Revision` or None
        :see: `Revision.ancestor`
        """
        deprecated_callable(self.get_ancestor, (Revision, 'ancestor'))
        return self.ancestor

    def _get_ancestor(self):
        rvsn = _arch.ancestor(self.fullname)
        if rvsn is None:
            return None
        else:
            return Revision(rvsn)

    ancestor = property(_get_ancestor, doc="""
    Parent revision.

    - The previous namespace revision, if this revision is regular commit.
    - The tag origin, if this revision is a continuation
    - ``None`` if this revision is an import.

    :type: `Revision` or None
    """)

    def get_previous(self):
        """Deprecated.

        Previous namespace revision.

        :return: the previous revision in the same version, or None if this
            revision is a ``base-0``.
        :rtype: `Revision` or None
        :see: `Revision.previous`
        """
        deprecated_callable(self.get_previous, (Revision, 'previous'))
        return self.previous

    def _get_previous(self):
        rvsn = _arch.previous(self.fullname)
        if rvsn is None: return None
        else: return Revision(rvsn)

    previous = property(_get_previous, doc="""
    Previous namespace revision.

    The previous revision in the same version, or None if this revision is a
    ``base-0``.

    :type: `Revision` or None
    """)

    def iter_ancestors(self, metoo=False):
        """Ancestor revisions.

        :param metoo: yield ``self`` as the first revision.
        :type metoo: bool
        :return: all the revisions in that line of development.
        :rtype: iterator of `Revision`
        """
        i = _arch.iter_ancestry_graph(self.fullname)
        if not metoo: i.next() # the first revision is self
        for ancest, merge in i:
            yield Revision(ancest)

    def cache(self, cache=None):
        """Cache a full source tree for this revision in its archive.

        :param cache: cache root for trees with pristines.
        :type cache: bool
        """
        _arch.cacherev(self.fullname, cache)

    def uncache(self):
        """Remove the cached tree of this revision from its archive."""
        _arch.uncacherev(self.fullname)

    def _file_url(self, name):
        return '/'.join([self.archive.location, self.category.nonarch,
                         self.branch.nonarch, self.version.nonarch,
                         self.patchlevel, name])

    _checksum_regex = re.compile(
        "^Signature-for: (.*)/(.*)\n"
        "([a-zA-Z0-9]+ [^/\\s]+ [a-fA-F0-9]+\n)*",
        re.MULTILINE)

    def _parse_checksum(self, text):
        match = self._checksum_regex.search(text)
        checksum_body = match.group()
        checksum_lines = checksum_body.strip().split('\n')
        checksum_words = map(lambda x: x.split(), checksum_lines)
        assert checksum_words[0] == ['Signature-for:', self.fullname]
        del checksum_words[0]
        checksums = {}
        for algo, name, value in checksum_words:
            name_sums = checksums.setdefault(name, dict())
            name_sums[algo] = value
        return checksums

    def iter_files(self):
        """Files stored in the archive for that revision.

        :rtype: iterable of `RevisionFile`
        """
        import urllib
        for checksum_name, can_fail in \
                (('checksum', False), ('checksum.cacherev', True)):
            try:
                checksum_file = urllib.urlopen(self._file_url(checksum_name))
            except IOError:
                if can_fail: continue
                else: raise
            try:
                checksum_data = checksum_file.read()
            finally:
                checksum_file.close()
            yield RevisionFile(self, checksum_name, {})
            checksums = self._parse_checksum(checksum_data)
            for name, name_sums in checksums.items():
                yield RevisionFile(self, name, name_sums)


public('RevisionFile')

class RevisionFile(object):

    """File component of an archived revision.

    :ivar revision: revision this file belongs to.
    :type revision: `Revision`
    :ivar name: name of that file.
    :type name: str
    :ivar checksums: dictionnary whose keys are checksum algorithms
        (e.g. ``"md5"``, ``"sha1"``) and whose values are checksum
        values (strings of hexadecimal digits).
    :type checksums: dict of str to str
    """

    def __init__(self, revision, name, checksums):
        self.revision = revision
        self.name = name
        self.checksums = checksums

    def _get_data(self):
        import urllib
        my_file = urllib.urlopen(self.revision._file_url(self.name))
        try:
            ret = my_file.read()
        finally:
            my_file.close()
        return ret

    data = property(_get_data,
                    """Content of of that file.

                    :type: str
                    """)


### Patch logs ###

import email
import email.Parser
import email.Generator

public('Patchlog')

class Patchlog(object):

    """Log entry associated to a revision.

    May be produced by `Revision.patchlog` or `ArchSourceTree.iter_logs()`. It
    provides an extensive summary of the associated changeset, a natural
    language description of the changes, and any number of user-defined
    extension headers.

    Patchlogs are formatted according to RFC-822, and are parsed using the
    standard email-handling facilities.

    Note that the patchlog text is not actually parsed before it is needed.
    That deferred evaluation feature is implemented in the `_parse` method.

    The fundamental accessors are `__getitem__`, which give the text of a named
    patchlog header, and the `description` property which gives the text of the
    patchlog body, that is anything after the headers.

    Additional properties provide appropriate standard conversion of the
    standard headers.
    """

    def __init__(self, revision, tree=None, fromlib=False):
        """Patchlog associated to the given revision.

        The patchlog may be retrieved from the provided ``tree``, from the
        revision library if ``fromlib`` is set, or from the archive.

        :param tree: source tree to retrieve the patchlog from.
        :type tree: `ArchSourceTree`, None
        :param fromlib: retrieve the patchlog from the revision library.
        :type fromblib: bool
        """
        if isinstance(revision, Revision):
            self.__revision = revision.fullname
        elif isinstance(revision, _unsafe):
            self.__revision, = revision
        else:
            p = NameParser(revision)
            if not p.has_archive() or not p.has_patchlevel:
                raise errors.NamespaceError(revision,
                                            'fully-qualified revision')
            self.__revision = revision
        self.tree = None
        if tree is not None: self.tree = str(tree)
        self.fromlib = bool(fromlib)
        self.__email = None

    def __repr__(self):
        if self.tree is not None:
            return 'Patchlog(%s)' % repr(self.__revision)
        else:
            return 'Patchlog(%s, tree=%s)' % (repr(self.__revision),
                                              repr(self.tree))

    def _parse(self):
        """Deferred parsing of the log text."""
        if self.__email is not None:
            return self.__email
        if self.tree is not None:
            s = _arch.cat_log(self.tree, self.__revision)
        elif self.fromlib:
            s = _arch.library_log(self.__revision)
        else:
            s = _arch.cat_archive_log(self.__revision)
        self.__email = email.Parser.Parser().parsestr(s)
        return self.__email

    def __getitem__(self, header):
        """Text of a patchlog header by name.

        :param header: name of a patchlog header.
        :type header: str
        :return: text of the header, or None if the header is not present.
        :rtype: str, None
        """
        return self._parse()[header]

    def items(self):
        """List of 2-tuples containing all headers and values.

        :rtype: list of 2-tuple of str
        """
        return self._parse().items()

    def get_revision(self):
        """Deprecated.

        Revision associated to this patchlog.

        :rtype: `Revision`
        :see: `Patchlog.revision`
        """
        deprecated_callable(self.get_revision, (Patchlog, 'revision'))
        return self.revision

    def _get_revision(self):
        assert self.__revision == self['Archive']+'/'+self['Revision']
        return Revision(self.__revision)

    revision = property(_get_revision, doc="""
    Revision associated to this patchlog.

    :type: `Revision`
    """)

    def get_summary(self):
        """Deprecated.

        Patchlog summary, a one-line natural language description.

        :rtype: str
        :see: `Patchlog.summary`
        """
        deprecated_callable(self.get_summary, (Patchlog, 'summary'))
        return self.summary

    def _get_summary(self):
        return self['Summary']

    summary = property(_get_summary, doc="""
    Patchlog summary, a one-line natural language description.

    :type: str
    """)

    def get_description(self):
        """Deprecated.

        Patchlog body, a long natural language description.

        :rtype: str
        :see: `Patchlog.description`
        """
        deprecated_callable(self.get_description, (Patchlog, 'description'))
        return self.description

    def _get_description(self):
        m = self._parse()
        assert not m.is_multipart()
        return m.get_payload()

    description = property(_get_description, doc="""
    Patchlog body, a long natural language description.

    :type: str
    """)

    def get_date(self):
        """Deprecated.

        For the description of the local time tuple, see the
        documentation of the `time` module.

        :rtype: local time tuple
        :see: `Patchlog.date`
        """
        deprecated_callable(self.get_date, (Patchlog, 'date'))
        return self.date

    def _get_date(self):
        d = self['Standard-date']
        from time import strptime
        return strptime(d, '%Y-%m-%d %H:%M:%S %Z')

    date = property(_get_date, doc="""
    Time of the associated revision.

    For the description of the local time tuple, see the documentation
    of the `time` module.

    :type: local time tuple
    """)

    def get_creator(self):
        """Deprecated.

        User id of the the creator of the associated revision.

        :rtype: str
        :see: `Patchlog.creator`
        """
        deprecated_callable(self.get_creator, (Patchlog, 'creator'))
        return self.creator

    def _get_creator(self):
        return self['Creator']

    creator = property(_get_creator, doc="""
    User id of the the creator of the associated revision.

    :type: str
    """)

    def get_continuation(self):
        """Deprecated.

        Ancestor of tag revisions.
        None for commit and import revisions.

        :rtype: `Revision`, None.
        :see: `Patchlog.continuation_of`
        """
        deprecated_callable(
            self.get_continuation, (Patchlog, 'continuation_of'))
        return self.continuation_of

    def _get_continuation(self):
        deprecated_callable(
            (Patchlog, 'continuation'), (Patchlog, 'continuation_of'))
        return self.continuation_of

    continuation = property(_get_continuation, doc="""
    Deprecated.

    Ancestor of tag revisions.
    None for commit and import revisions.

    :type: `Revision`, None.
    :see: `Patchlog.continuation_of`
    """)

    def _get_continuation_of(self):
        c = self['Continuation-of']
        if c is None:
            return None
        return Revision(c)

    continuation_of = property(_get_continuation_of, doc="""
    Ancestor of tag revisions.
    None for commit and import revisions.

    :type: `Revision`, None.
    """)

    def new_merge_revision(self, revision_name):
        """Helper to produce a correct output even on broken baz logs

        :param revision_name: The name of a revision to produce
        :type revision_name: str
        """
        if revision_name == "!!!!!nothing-should-depend-on-this":
            return self.revision
        else:
            return Revision(revision_name)

    def get_new_patches(self):
        """Deprecated.

        New-patches header as an iterable of Revision.

        :rtype: iterable of `Revision`
        :see: `Patchlog.new_patches`
        """
        deprecated_callable(
            Patchlog.get_new_patches, (Patchlog, 'new_patches'))
        return self.new_patches

    def _get_new_patches(self):
        return map(self.new_merge_revision, self['New-patches'].split())

    new_patches = property(_get_new_patches, doc="""
    New-patches header as an iterable of Revision.

    Patchlogs added in this revision.

    :type: iterable of `Revision`
    """)

    def get_merged_patches(self):
        """Deprecated.

        Revisions merged in this revision. That is the revisions
        listed in the New-patches header except the revision of the
        patchlog.

        :rtype: iterable of `Revision`
        :see: `Patchlog.merged_patches`
        """
        deprecated_callable(
            Patchlog.get_merged_patches, (Patchlog, 'merged_patches'))
        return self.merged_patches

    def _get_merged_patches(self):
        rvsn = self.revision.fullname
        return filter(lambda(r): r.fullname != rvsn, self.new_patches)

    merged_patches = property(_get_merged_patches, doc="""
    Revisions merged in this revision.

    That is the revisions listed in the New-patches header except the
    revision of the patchlog.

    :type: iterable of `Revision`
    """)

    def get_new_files(self):
        """Deprecated.

        Source files added in the associated revision.

        :rtype: iterable of `FileName`
        :see: `Patchlog.new_files`
        """
        deprecated_callable(self.get_new_files, (Patchlog, 'new_files'))
        return self.new_files

    def _get_new_files(self):
        s = self['New-files']
        if s is None: return []
        return [ FileName(name_unescape(f)) for f in s.split() ]

    new_files = property(_get_new_files, doc="""
    Source files added in the associated revision.

    :type: iterable of `FileName`
    """)

    def get_modified_files(self):
        """Deprecated.

        Names of source files modified in the associated revision.

        :rtype: iterable of `FileName`
        """
        deprecated_callable(
            self.get_modified_files, (Patchlog, 'modified_files'))
        return self.modified_files

    def _get_modified_files(self):
        s = self['Modified-files']
        if s is None: return []
        return [ FileName(name_unescape(f)) for f in s.split() ]

    modified_files = property(_get_modified_files, doc="""
    Names of source files modified in the associated revision.

    :type: iterable of `FileName`
    """)

    def get_renamed_files(self):
        """Deprecated.

        Source files renames in the associated revision.

        Dictionnary whose keys are old names and whose values are the
        corresponding new names. Explicit file ids are listed in
        addition to their associated source file.

        :rtype: dict
        """
        deprecated_callable(
            self.get_renamed_files, (Patchlog, 'renamed_files'))
        return self.renamed_files

    def _get_renamed_files(self):
        s = self['Renamed-files']
        renames = {}
        if s is None:
            return renames
        s = s.split()
        for i in range(len(s)/2):
            renames[s[i*2]] = s[i*2+1]
        return renames

    renamed_files = property(_get_renamed_files, doc="""
    Source files renames in the associated revision.

    Dictionnary whose keys are old names and whose values are the
    corresponding new names. Explicit file ids are listed in
    addition to their associated source file.

    :type: dict
    """)

    def get_removed_files(self):
        """Deprecated.

        Names of source files removed in the associated revision.

        :rtype: iterable of `FileName`
        """
        deprecated_callable(
            self.get_removed_files, (Patchlog, 'removed_files'))
        return self.removed_files

    def _get_removed_files(self):
        s = self['Removed-files']
        if s is None: return []
        return [ FileName(name_unescape(f)) for f in s.split() ]

    removed_files = property(_get_removed_files, doc="""
    Names of source files removed in the associated revision.

    :type: iterable of `FileName`
    """)


public('LogMessage')

class LogMessage(object):

    """Log message for use with commit, import or tag operations.

    This is the write-enabled counterpart of Patchlog. When creating a new
    revision with import, commit or tag, a log message file can be used to
    specify a long description and custom headers.

    Commit and import can use the default log file of the source tree, with a
    special name. You can create the LogMessage object associated to the
    default log file with the WorkingTree.log_message method.

    For integration with external tools, it is useful to be able to parse an
    existing log file and write the parsed object back idempotently. We are
    lucky since this idempotence is provided by the standard email.Parser and
    email.Generator.
    """

    def __init__(self, name):
        self.__name = name
        self.__email = None
        self.__dirty = False

    def get_name(self): return self.__name
    name = property(get_name)

    def load(self):
        """Read the log message from disk."""
        self.__email = email.Parser.Parser().parse(file(self.__name))
        self.__dirty = False

    def save(self):
        """Write the log message to disk."""
        if self.__dirty:
            f = file(self.__name, 'w')
            email.Generator.Generator(f).flatten(self.__email)
            self.__dirty = False

    def clear(self):
        """Clear the in-memory log message.

        When creating a new log message file, this method must be used
        first before setting the message parts. That should help early
        detection of erroneous log file names.
        """
        self.__email = email.Message.Message()
        self.__dirty = True

    def __getitem__(self, header):
        """Text of a patchlog header by name."""
        if self.__email is None: self.load()
        return self.__email[header]

    def __setitem__(self, header, text):
        """Set a patchlog header."""
        if self.__email is None: self.load()
        try:
            self.__email.replace_header(header, text)
        except KeyError:
            self.__email.add_header(header, text)
        self.__dirty = True

    def get_description(self):
        """Body of the log message."""
        if self.__email is None: self.load()
        assert not self.__email.is_multipart()
        return self.__email.get_payload()

    def set_description(self, s):
        """Set the body of the log message."""
        if self.__email is None: self.load()
        self.__email.set_payload(s)
        self.__dirty = True

    description = property(get_description, set_description)


### Source trees ###

public(
    'init_tree',
    'in_source_tree',
    'tree_root',
    )

def init_tree(directory, version=None, nested=False):
    """Initialize a new project tree.

    :param directory: directory to initialize as a source tree.
    :type directory: str
    :param version: if given, set the the ``tree-version`` and create an empty
       log version.
    :type version: `Version`
    :param nested: if true, the command will succeed even if 'directory'
        is already within a source tree.
    :type nested: bool
    :return: source tree object for the given directory.
    :rtype: `WorkingTree`
    """
    if version is not None:
        version = _version_param(version)
    _arch.init_tree(directory, version, nested)
    return WorkingTree(directory)


def in_source_tree(directory=None):
    """Is directory inside a Arch source tree?

    :param directory: test if that directory is in an Arch source tree.
    :type directory: str
    :return: whether this directory is inside an Arch source tree.
    :rtype: bool

    :warning: omitting the ``directory`` argument is deprecated.
    """
    if directory is None:
        deprecated_usage(
            in_source_tree, "Argument defaults to current direcotry.")
        directory = '.'
    return _arch.in_tree(directory)


def tree_root(directory=None):
    """SourceTree containing the given directory.

    :param directory: give the ``tree-root`` of this directory. Specify "." to
        get the ``tree-root`` of the current directory.
    :type directory: str
    :return: source tree containing ``directory``.
    :rtype: `ArchSourceTree`

    :warning: omitting the ``directory`` argument is deprecated.
    """
    if directory is None:
        deprecated_usage(tree_root, "Argument defaults to current directory.")
        directory = '.'
    root = _arch.tree_root(directory)
    # XXX use SourceTree to instanciate either WorkingTree or LibraryTree
    return SourceTree(root)


public('SourceTree',
       'ForeignTree',
       'ArchSourceTree',
       'LibraryTree',
       'WorkingTree')

class SourceTree(DirName):

    """Abstract base class for `ForeignTree` and `ArchSourceTree`."""

    def __new__(cls, root=None):
        """Create a source tree object for the given root path.

        `ForeignTree` if root does not point to a Arch source tree.
        `LibraryTree` if root is a tree in the revision library. `WorkingTree`
        if root is a Arch source tree outside of the revision library.

        If root is omitted, use the tree-root of the current working directory.
        """
        __pychecker__ = 'no-returnvalues'
        # checking root actually is a root done by LibraryTree and WorkingTree
        if cls is not SourceTree:
            assert root is not None
            return DirName.__new__(cls, root)
        else:
            if not root:
                root = _arch.tree_root(os.getcwd())
            root = DirName(root).realpath()
            if _arch.is_tree_root(root):
                for revlib in _arch.iter_revision_libraries():
                    if root.startswith(revlib):
                      return LibraryTree(root)
                return WorkingTree(root)
            else:
                assert not _arch.in_tree(root)
                return ForeignTree(root)


class ForeignTree(SourceTree):
    """Generic source tree without Arch support.

    Unlike Arch source trees, the root may not even exist.
    """
    def __init__(self, root): pass


class ArchSourceTree(SourceTree):

    """Abstract base class for Arch source trees."""

    def get_tree_version(self):
        """Default version of the tree, also called tree-version.

        :raise errors.TreeVersionError: no valid default version set.
        :raise IOError: unable to read the ++default-version file.
        """
        data = _arch.tree_version(self)
        if data is None:
            raise errors.TreeVersionError(self)
        try:
            return Version(data)
        except errors.NamespaceError:
            raise errors.TreeVersionError(self, data)
    tree_version = property(get_tree_version)

    def _get_tree_revision(self):
        """Revision of the last patchlog for the tree-version.

        :raise errors.TreeVersionError: no valid default version set.
        :raise IOError: unable to read the ++default-version file.
        """
        reverse_logs = self.iter_logs(reverse=True)
        try: last_log = reverse_logs.next()
        except StopIteration:
            raise RuntimeError('no logs for the tree-version')
        return last_log.revision
    tree_revision = property(_get_tree_revision)

    def check_is_tree_root(self):
        assert os.path.isdir(self)
        if not _arch.is_tree_root(self):
            raise Exception, "%s is not a tla project tree" % self

    def get_tagging_method(self):
        return _arch.tagging_method(self)
    tagging_method = property(get_tagging_method)

    def __inventory_filter(self, trees, directories, files, both):
        assert sum(map(bool, (trees, directories, files, both))) == 1
        if trees: return lambda(t): SourceTree(self/name_unescape(t))
        elif directories: return lambda(d): DirName(name_unescape(d))
        elif files: return lambda(f): FileName(name_unescape(f))
        elif both:
            def ctor(f):
                if os.path.isdir(self/f): return DirName(name_unescape(f))
                else: return FileName(name_unescape(f))
            return ctor
        else:
            raise AssertionError, 'not reached'

    def iter_inventory(self, source=False, precious=False, backups=False,
                       junk=False, unrecognized=False, trees=False,
                       directories=False, files=False, both=False,
                       names=False, limit=None):
        """Tree inventory.

        The kind of files looked for is specified by setting to
        ``True`` exactly one of the following keyword arguments:

            ``source``, ``precious``, ``backups``, ``junk``,
            ``unrecognized``, ``trees``.

        If the ``trees`` argument is not set, whether files, directory
        or both should be listed is specified by setting to ``True``
        exactly one of the following keyword arguments:

            ``directories``, ``files``, ``both``.

        :keyword source: list source files only.
        :keyword precious: list precious files only.
        :keyword backups: list backup files only.
        :keyword junk: list junk files only.
        :keyword unrecognized: list unrecognized files only.
        :keyword trees: list nested trees only. If this is true, the
            iterator wil only yield `ArchSourceTree` objects.

        :keyword directories: list directories only,
            yield only `FileName` objects.
        :keyword files: list files only, yield only `DirName` objects.
        :keyword both: list both files and directories,
            yield both FileName and `DirName` objects.

        :keyword name: do inventory as if the id-tagging-method was
            set to ``names``. That is useful to ignore
            ``untagged-source`` classification.

        :keyword limit: restrict the inventory to this directory. Must
            be the name of a directory relative to the tree root.

        :rtype: iterator of `FileName`, `DirName`, `ArchSourceTree`
            according to the arguments.
        """
        __pychecker__ = 'maxargs=12'
        if limit is not None: _check_relname_param(limit, 'limit')
        return itertools.imap\
               (self.__inventory_filter(trees, directories, files, both),
                _arch.iter_inventory(self, source, precious, backups,
                                     junk, unrecognized, trees,
                                     directories, files, both, names, limit))

    def iter_inventory_ids(self,source=False, precious=False, backups=False,
                           junk=False, unrecognized=False, trees=False,
                           directories=False, files=False, both=False,
                           limit=None):
        """Tree inventory with file ids.

        :see: `ArchSourceTree.iter_inventory`

        :rtype: iterator of tuples ``(id, item)``, where ``item`` is
            `FileName`, `DirName`, `ArchSourceTree` according to the
            arguments and ``id`` is the associated inventory id.
        """
        if limit is not None: _check_relname_param(limit, 'limit')
        f = self.__inventory_filter(trees, directories, files, both)
        def ff(t): name, id_ = t; return id_, f(name)
        return itertools.imap\
               (ff, _arch.iter_inventory_ids(self, source, precious, backups,
                                             junk, unrecognized, trees,
                                             directories, files, both, limit))

    def inventory(self, *args, **kw):
        """Inventory of the source tree as a list. See iter_inventory.

        DEPRECATED
        """
        return list (self.iter_inventory(*args, **kw))

    def get_tree(self):
        return util.sorttree(self.inventory(source=True, both=True))

    def iter_log_versions(self, limit=None, reverse=False):
        """Iterate over versions this tree has a log-version for.

        :param limit: only iterate log-versions in this namespace.
        :type limit: `Archive`, `Category`, `Branch`, `Version`
        :param reverse: yield log-versions in reverse order.
        :type reverse: bool
        """
        kwargs = {}
        if isinstance(limit, Archive):
            kwargs['archive'] = limit.name
        elif isinstance(limit, (Category, Branch, Version)):
            kwargs['archive'] = limit.archive.name
        if isinstance(limit, Category): kwargs['category'] = limit.nonarch
        elif isinstance(limit, Branch): kwargs['branch'] = limit.nonarch
        elif isinstance(limit, Version): kwargs['version'] = limit.nonarch
        elif limit is not None and not isinstance(limit, Archive):
            raise TypeError("Expected Archive, Category, Branch or Version"
                            " but got: %r" % limit)
        for vsn in _arch.iter_log_versions(self, reverse=reverse, **kwargs):
            yield Version(vsn)

    def iter_logs(self, version=None, reverse=False):
        """Iterate over patchlogs present in this tree.

        :param version: list patchlogs from this version. Defaults to
            the tree-version.
        :type version: `Version`
        :param reverse: iterate more recent logs first.
        :type reverse: bool
        :return: patchlogs from ``version``.
        :rtype: iterator of `Patchlog`.
        :raise errors.TreeVersionError: no valid default version set.
        :raise IOError: unable to read the ++default-version file.
        """
        if version is None: version = self.tree_version.fullname
        else: version = _version_param(version)
        for rvsn in _arch.iter_log_ls(self, version, reverse=reverse):
            yield Patchlog(_unsafe((rvsn,)), tree=self)

    def get_tag(self, file):
        """File id set by an explicit id tag or tagline.

        :param file: name of a source file relative to the tree-root.
        :type file: str
        :return: file id if the file has an explicit id or a tagline.
        :rtype: str
        """
        if not os.path.exists(self/file) and not os.path.islink(self/file):
            raise IOError(2, 'No such file or directory', file)
        return _arch.get_tag(self/file)

    def file_find(self, name, revision):
         """Find a pristine copy of a file for a given revision.

         Will create the requested revision in the library or in the
         current tree pristines if needed.

         :param name: name of the file.
         :type name: str
         :param revision: revision to look for the file into.
         :type revision: `Revision`
         :return: absolute path name of a pristine copy of the file.
         :rtype: `pathname.PathName`
         :raise errors.MissingFileError: file is not source or is not
             present in the specified revision.
         """
         revision = _revision_param(revision)
         result = _arch.file_find(self, name, revision)
         if result is None:
             raise errors.MissingFileError(self, name, revision)
         # XXX Work around relative path when using pristines
         result = os.path.join(self, result)
         return PathName(result)


class LibraryTree(ArchSourceTree):

    """Read-only Arch source tree."""

    def __init__(self, root):
        """Create a LibraryTree object with the given root path.

        Root must be a directory containing a Arch source tree in the
        revision library.
        """
        ArchSourceTree.__init__(self, root)
        self.check_is_tree_root()


class WorkingTree(ArchSourceTree):

    """Working source tree, Arch source tree which can be modified."""

    def __init__(self, root):
        """Create WorkingTree object with the given root path.

        Root must be a directory containing a valid Arch source tree
        outside of the revision library.
        """
        ArchSourceTree.__init__(self, root)
        self.check_is_tree_root()

    def sync_tree(self, revision):
        """Adds the patchlogs in the given revision to the current tree.

        Create a temporary source tree for ``revision``, then add all the
        patchlogs present in that tree to the current tree. No content
        is touched besides the patchlogs.

        :param revision: revision to synchronize with.
        :type revision: `Version`, `Revision` or str
        :raise errors.NamespaceError: ``revision`` is not a valid
            version or revision name.
        """
        revision = _version_revision_param(revision)
        _arch.sync_tree(self, revision)

    def set_tree_version(self, version):
        version = _version_param(version)
        _arch.set_tree_version(self, version)
    tree_version = property(ArchSourceTree.get_tree_version, set_tree_version)

    def has_changes(self):
        """Are there uncommited changes is this source tree?

        :rtype: bool
        """
        return _arch.has_changes(self)

    def changes(self, revision=None, output=None):
        """Uncommited changes in this tree.

        :param revision: produce the changeset between this revision
            and the tree. If ``revision`` is ``None``, use the
            tree-revision.
        :type revision: `Revision`, None
        :param output: absolute path of the changeset to produce.
        :type output: string
        :return: changeset between ``revision`` and the tree.
        :rtype: Changeset
        :raise errors.TreeVersionError: no valid default version set.
        :raise IOError: unable to read the ++default-version file.
        """
        if revision is None: revision = self.tree_revision
        _check_str_param(output, 'output')
        _check_revision_param(revision, 'revision')
        return delta(revision, self, output)


    def star_merge(self, from_=None, reference=None, forward=False,
                   diff3=False):
        """Merge mutually merged branches.

        :param from_: branch to merge changes from, ``None`` means the
            ``tree-version``.
        :type from_: None, `Version`, `Revision`, or str
        :param reference: reference version for the merge, ``None``
            means the ``tree-version``.
        :type reference: None, `Version` or str
        :param forward: ignore already applied patch hunks.
        :type forward: bool
        :param diff3: produce inline conflict markers instead of
            ``.rej`` files.
        :type diff3: bool
        :raise errors.NamespaceError: ``from_`` or ``reference`` is
            not a valid version or revision name.
        """
        list(self.iter_star_merge(from_, reference, forward, diff3))

    def iter_star_merge(self, from_=None, reference=None,
                   forward=False, diff3=False):
        """Merge mutually merged branches.

        :bug: if the merge causes a conflict, a RuntimeError is
            raised. You should not rely on this behaviour as it is
            likely to change in the future. If you want to support
            conflicting merges, use `iter_star_merge` instead.

        :param `from_`: branch to merge changes from, ``None`` means the
            ``tree-version``.
        :type `from_`: None, `Version`, `Revision`, or str
        :param reference: reference version for the merge, ``None``
            means the ``tree-version``.
        :type reference: None, `Version` or str
        :param forward: ignore already applied patch hunks.
        :type forward: bool
        :param diff3: produce inline conflict markers instead of
            ``.rej`` files.
        :type diff3: bool
        :raise errors.NamespaceError: ``from_`` or ``reference`` is
            not a valid version or revision name.
        :return: `MergeOutcome` iterator
        :rtype: `iter_changes`
        """
        if from_ is not None:
            from_ = _version_revision_param(from_)
        if reference is not None:
            reference = _version_revision_param(reference)
        _arch.star_merge(self, from_, reference, forward, diff3)

    def iter_star_merge(self, from_=None, reference=None,
                        forward=False, diff3=False):
        """Merge mutually merged branches.

        :param `from_`: branch to merge changes from, ``None`` means the
            ``tree-version``.
        :type `from_`: None, `Version`, `Revision`, or str
        :param reference: reference version for the merge, ``None``
            means the ``tree-version``.
        :type reference: None, `Version` or str
        :param forward: ignore already applied patch hunks.
        :type forward: bool
        :param diff3: produce inline conflict markers instead of
            ``.rej`` files.
        :type diff3: bool
        :raise errors.NamespaceError: ``from_`` or ``reference`` is
            not a valid version or revision name.
        :rtype: `ChangesetApplication`
        """
        # the --changes option must be supported by another method
        # which returns a Changeset.
        if from_ is not None:
            from_ = _version_revision_param(from_)
        if reference is not None:
            reference = _version_revision_param(reference)
        return ChangesetApplication(
            _arch.iter_star_merge(self, from_, reference, forward, diff3))

    def undo(self, revision=None, output=None, quiet=False, throw_away=False):
        """Undo and save changes in a project tree.

        Remove local changes since revision and optionally save them
        as a changeset.

        :keyword revision: revision to revert to. Default to the last
            revision of the tree-version for which a patchlog is present.
        :type revision: `Revision`, str
        :keyword output: name of the output changeset directory. Must
            not already exist. Default to an automatic ,,undo-N name
            in the working tree.
        :type output: str
        :keyword quiet: OBSOLETE. Incremental output is always discarded.
        :type quiet: bool
        :keyword throw_away: discard the output changeset and return
            ``None``. Must not be used at the same time as ``output``.
        :type throw_away: bool
        :return: changeset restoring the undone changes,
            or None if ``throw_away``.
        :rtype: `Changeset`, None
        """
        assert sum(map(bool, (output, throw_away))) < 2
        if output is None:
            output = util.new_numbered_name(self, ',,undo-')
        if revision is not None:
            revision = _revision_param(revision)
        _arch.undo(self, revision, output, quiet, throw_away)
        if throw_away: return None
        return Changeset(output)

    def redo(self, patch=None, keep=False, quiet=False):
        """Redo changes in a project tree.

        Apply patch to the project tree and delete patch.

        If patch is provided, it must be a Changeset object. Else, the highest
        numbered ,,undo-N directory in the project tree root is used.

        If keep is true, the patch directory is not deleted.
        """
        _arch.redo(self, patch, keep, quiet)

    def set_tagging_method(self, method):
        _arch.set_tagging_method(self, method)
    tagging_method = property(ArchSourceTree.get_tagging_method,
                              set_tagging_method)

    def add_tag(self, file):
        _arch.add(self/file)

    def move_tag(self, src, dest):
        _arch.move(self/src, self/dest)

    def move_file(self, src, dest):
        # FIXME: move explicit tag if present
        dest = PathName(dest)
        assert os.path.exists((self/dest).dirname())
        os.rename(self/src, self/dest)

    def delete(self, file):
        fullfile = self/file
        if os.path.isfile(fullfile):
            if _arch.has_explicit_id(fullfile):
                _arch.delete(fullfile)
            os.unlink(fullfile)
        elif os.path.isdir(fullfile):
            shutil.rmtree(fullfile)

    def del_file(self, file):
        fullfile = self/file
        if os.path.isfile(fullfile):
            os.unlink(fullfile)
        else:
            shutil.rmtree(fullfile)

    def del_tag(self, file):
        if not os.path.islink(self/file):
            assert os.path.exists(self/file)
        _arch.delete(self/file)

    def import_(self, log=None):
        """Archive a full-source base-0 revision.

        If log is specified, it must be a LogMessage object or a file
        name as a string. If omitted, the default log message file of
        the tree is used.

        The --summary, --log-message and --setup options to tla are
        mere CLI convenience features and are not directly supported.
        """
        if isinstance(log, LogMessage):
            log.save()
            log = log.name
        assert log is None or isinstance(log, str)
        _arch.import_(self, log)

    def commit(self, log=None, strict=False, seal=False, fix=False,
               out_of_date_ok=False, file_list=None, version=None):
        """Archive a changeset-based revision.

        :keyword version: version in which to commit the revision.
            Defaults to the `tree_version`.
        :type version: `Version`, str
        :keyword log: Log message for this revision. Defaults to the log
            message file of the tree-version (the file created by
            ``tla make-log``.
        :type log: `LogMessage`
        :keyword strict: perform a strict tree-lint before commiting.
        :type strict: bool
        :keyword seal: create a ``version-0`` revision.
        :type seal: bool
        :keyword fix: create a ``versionfix`` revision.
        :type fix: bool
        :keyword out_of_date_ok: commit even if the tree is out of
            date.
        :type out_of_date_ok: bool
        :keyword file_list: Only commit changes to those files,
            specified relative to the tree-root.
        :type file_list: iterable of str, with at least one item.

        The --summary and --log-message options to tla are mere CLI
        convenience features and are not directly supported.

        :see: `WorkingTree.iter_commit`
        """
        for unused in self.iter_commit(
            log, strict, seal, fix, out_of_date_ok, file_list, version):
            pass

    def log_for_merge(self):
        """Standard arch log of newly merged patches.

        :rtype: str
        """
        return _arch.log_for_merge(self)


    def iter_commit(self, log=None, strict=False, seal=False, fix=False,
                    out_of_date_ok=False, file_list=None, version=None,
                    base=None):
        """Archive a changeset-based revision, returning an iterator.


        :keyword version: version in which to commit the revision.
            Defaults to the `tree_version`.
        :type version: `Version`, str
        :keyword log: Log message for this revision. Defaults to the log
            message file of the tree-version (the file created by
            ``tla make-log``.
        :type log: `LogMessage`
        :keyword strict: perform a strict tree-lint before commiting.
        :type strict: bool
        :keyword seal: create a ``version-0`` revision.
        :type seal: bool
        :keyword fix: create a ``versionfix`` revision.
        :type fix: bool
        :keyword out_of_date_ok: commit even if the tree is out of
            date.
        :type out_of_date_ok: bool
        :keyword file_list: Only commit changes to those files,
            specified relative to the tree-root.
        :type file_list: iterable of str, with at least one item.
        :rtype: iterator of `TreeChange`, `Chatter` or str

        The --summary and --log-message options to tla are mere CLI
        convenience features and are not directly supported.

        :see: `WorkingTree.commit`
        """
        if version is None:
            version = self.tree_version.fullname
        else:
            version = _version_param(version)
        if isinstance(log, LogMessage):
            log.save()
            log = log.name
        assert log is None or isinstance(log, str)
        if log is not None:
            log = os.path.abspath(log)
        iterator = _arch.iter_commit(
            self, version, log, strict, seal, fix, out_of_date_ok, file_list,
            base)
        return classify_changeset_creation(iterator)

    def log_message(self, create=True, version=None):
        """Default log-message object used by import and commit.

        If `create` is False, and the standard log file does not already
        exists, return None. If `create` is True, use ``tla make-log`` if
        needed.
        """
        if version is not None:
            version = str(version)
        name = _arch.log_name(self, version)
        if not os.path.exists(name):
            if not create: return None
            _arch.make_log(self, version)
        return LogMessage(name)

    def add_log_version(self, version):
        """Add a patch log version to the project tree."""
        version = _version_param(version)
        _arch.add_log_version(self, version)

    def remove_log_version(self, version):
        """Remove a patch log version from the project tree."""
        version = _version_param(version)
        _arch.remove_log_version(self, version)

    def replay(self):
        """Replay changesets into this working tree."""
        _arch.replay(self)

    def update(self):
        """Apply delta of new revisions in the archive.

        Apply delta(A,B) on this working tree, where A and B are both
        revisions of the tree version, A is the latest whose patchlog
        is present in the tree and B is the latest present in the
        archive.
        """
        _arch.update(self)

    def iter_pristines(self):
        """Pristines present in that source tree.

        :return: Revisions which have pristine trees in that source tree.
        :rtype: iterable of `Revision`
        """
        for rvsn in _arch.iter_pristines(self):
            yield Revision(rvsn)

    def add_pristine(self, revision):
        """Ensure that the project tree has a particular pristine revision.

        :param revision: revision to add a pristine for.
        :type revision: `Revision`
        """
        revision = _revision_param(revision)
        _arch.add_pristine(self, revision)

    def find_pristine(self, revision):
        """Path to a pristine tree for the given revision.

        :param revision: find a pristine for that revision.
        :type revision: `Revision`
        :rtype: `ArchSourceTree`
        :raise errors.NoPristineFoundError: no pristine tree was found
            for the given revision.
        """
        if revision not in self.iter_pristines():
            raise errors.NoPristineFoundError(self, revision)
        revision = _revision_param(revision)
        return ArchSourceTree(_arch.find_pristine(self, revision))


### Changesets ###

public('Changeset')

class Changeset(DirName):

    """Arch whole-tree changeset."""

    def __init__(self, name):
        DirName.__init__(self, name)
        self.__index = {}
        self.__index_excl = {}
        self.__metadata = {}
        self.exclude_re = re.compile('^[AE]_')

    def get_index(self, name, all=False):
        """Load and parse an index file from the changeset.

        Expectable indexes are:
        mod-dirs mod-files orig-dirs orig-files (more?)
        """
        key = (name, all)
        if name in self.__index: return self.__index[key]
        if all:
            not_exclude = lambda(id_): True
        else:
            not_exclude = lambda(id_): not self.exclude_re.match(id_)
        retval = {}
        fullname = self/(name + '-index')
        if os.path.exists(fullname):
            index_file = open(fullname)
            try:
                for line in index_file:
                    n, id_ = map(lambda(s): s.strip(), line.split())
                    if not_exclude(id_):
                        retval[id_] = os.path.normpath(name_unescape(n))
            finally:
                index_file.close()
        self.__index[key] = retval
        return retval

    def _get_does_nothing(self):
        """Is the changeset a no-op?"""
        # TODO: checking that all indices are empty can yield false negatives
        # rather we should check for the effective absence of changes.
        for index_name in ('mod-files', 'orig-files', 'mod-dirs', 'orig-dirs'):
            index = self.get_index(index_name, True)
            if index: return False
        return True
    does_nothing = property(_get_does_nothing)

#     def get_metadata(self, name):
#         """Load and parse a metadata file from the changeset.
#
#         Expectable metadata tables are:
#         modified-only-dir original-only-dir (more?)
#         """
#         raise NotImplementedError, "not yet implemented"
#         if name in self.__metadata: return self.__metadata[name]
#         retval = []
#         fullname = self/(name + '-metadata')
#         if os.path.exists(fullname):
#             for line in open(fullname):
#                 pass # Not implemented
#         self.__metadata[name] = retval
#         return retval

    def __iter_mod_helper(self, what, all):
        __pychecker__ = 'no-abstract' # for ImmutableSet
        orig_index = self.get_index('orig-' + what, all)
        mod_index = self.get_index('mod-' + what, all)
        orig_ids = ImmutableSet(orig_index.iterkeys())
        mod_ids = ImmutableSet(mod_index.iterkeys())
        for id_ in orig_ids & mod_ids:
            yield (id_, orig_index[id_], mod_index[id_])

    def iter_mod_files(self, all=False):
        """Iterator over (id, orig, mod) tuples for files which are are
        patched, renamed, or have their permissions changed."""
        return self.__iter_mod_helper('files', all)

    def iter_patched_files(self, all=False):
        """Iterate over (id, orig, mod) of patched files."""
        patchdir = self/'patches'
        for f in self.iter_mod_files(all):
            if os.path.isfile(patchdir/f[1]+'.patch'):
                yield f
            else:
                print "file does not exists: %s" % str(patchdir/f[1]+'.patch')
        #return itertools.ifilter(lambda(f): os.path.isfile(patchdir/f[2]),
        #                         self.iter_mod_files())

    def patch_file(self, modname):
        return self/'patches'/modname+'.patch'

    def __iter_renames_helper(self, what):
        for id_, orig, mod in self.__iter_mod_helper(what, all=False):
            if orig != mod:
                yield (id_, orig, mod)

    def iter_renames(self):
        """Iterate over (id, orig, dest) triples representing renames.

        id is the persistant file tag, and the key of the dictionnary.
        orig is the name in the original tree.
        dest is the name in the modified tree.
        """
        from itertools import chain
        return chain(*map(self.__iter_renames_helper, ('files', 'dirs')))

    def __iter_created_helper(self, what, removed=False, all=False):
        __pychecker__ = 'no-abstract' # for ImmutableSet
        orig_index = self.get_index('orig-' + what, all)
        mod_index = self.get_index('mod-' + what, all)
        if removed: orig_index, mod_index = mod_index, orig_index
        orig_ids = ImmutableSet(orig_index.iterkeys())
        mod_ids = ImmutableSet(mod_index.iterkeys())
        for id_ in mod_ids - orig_ids:
            yield (id_, mod_index[id_])

    def iter_created_files(self, all=False):
        """Iterator over tuples (id, dest) for created files.

        :param all: include Arch control files.
        :type all: bool
        """
        return self.__iter_created_helper('files', all=all)

    def created_file(self, name):
        return self/'new-files-archive'/name

    def iter_removed_files(self, all=False):
        """Iterator over tuples (id, orig) for removed files.

        :param all: include Arch control files.
        :type all: bool
        """
        return self.__iter_created_helper('files', removed=True, all=all)

    def removed_file(self, name):
        return self/'removed-files-archive'/name

    def iter_created_dirs(self, all=False):
        """Iterator over tuples (id, dest) for created directories.

        :param all: include Arch control files.
        :type all: bool
        """
        return self.__iter_created_helper('dirs', all=all)

    def iter_removed_dirs(self, all=False):
        """Iterator over tuples (id, orig) for removed directories.

        :param all: include Arch control files.
        :type all: bool
        """
        return self.__iter_created_helper('dirs', removed=True, all=all)

    def iter_apply(self, tree, reverse=False):
        """Apply this changeset to a tree, with incremental output.

        :param tree: the tree to apply changes to.
        :type tree: `WorkingTree`
        :param reverse: invert the meaning of the changeset; adds
            become deletes, etc.
        :type reverse: bool
        :rtype: `ChangesetApplication`
        """
        _check_working_tree_param(tree, 'tree')
        return ChangesetApplication(
            _arch.iter_apply_changeset(self, tree, reverse))


public('changeset')

def changeset(orig, mod, dest):
    """Deprecated.

    :see: `delta`
    :rtype: `Changeset`
    """
    deprecated_callable(changeset, delta)
    return delta(ArchSourceTree(orig), ArchSourceTree(mod), dest)


def _tree_or_existing_revision_param(param, name):
    if isinstance(param, Revision):
        # should check for actual existence, but that is expensive
        if not param.archive.is_registered():
            raise errors.ArchiveNotRegistered(param.archive)
        return param.fullname
    elif isinstance(param, ArchSourceTree):
        return param
    else:
        raise TypeError("Parameter \"%s\" must be ArchSourceTree or Revision"
                        " but was: %r" % (name, param))

def _check_str_param(param, name):
    """Internal argument checking utility"""
    if not isinstance(param, basestring):
        raise TypeError("Parameter \"%s\" must be a string"
                        " but was: %r" % (name, param))

def _check_working_tree_param(param, name):
    """Internal argument checking utility"""
    if not isinstance(param, WorkingTree):
        raise TypeError("Parameter \"%s\" must be a WorkingTree"
                        " but was: %r" % (name, param))


public('ChangesetApplication', 'ChangesetCreation', 'delta', 'iter_delta')

class ChangesetApplication(object):
    """Incremental changeset application process."""

    def __init__(self, proc):
        """For internal use only."""
        self._iter_process = proc

    def __iter__(self):
        """Return an iterator of `MergeOutcome`"""
        return classify_changeset_application(self._iter_process)

    def _get_conflicting(self):
        "Did conflicts occur during changeset application?"
        if not self.finished:
            raise AttributeError("Changeset application is not complete.")
        return self._iter_process.status == 1
    conflicting = property(_get_conflicting)

    def _get_finished(self):
        "Is the changeset application complete?"
        return self._iter_process.finished
    finished = property(_get_finished)

class ChangesetCreation(object):
    """Incremental changeset generation process."""

    def __init__(self, proc, dest):
        """For internal use only."""
        self._iter_process = proc
        self._dest = dest
        self._changeset = None

    def __iter__(self):
        """Return an iterator of `TreeChange`"""
        return classify_changeset_creation(self._iter_process)

    def _get_changeset(self):
        """Generated changeset."""
        if self._changeset is None:
            if not self.finished:
                raise AttributeError("Changeset generation is not complete.")
            self._changeset = Changeset(self._dest)
        return self._changeset
    changeset = property(_get_changeset)

    def _get_finished(self):
        "Is the changeset creation complete?"
        return self._iter_process.finished
    finished = property(_get_finished)


def iter_delta(orig, mod, dest):
    """Compute a whole-tree changeset with incremental output.

    :param orig: old revision or directory.
    :type orig: `Revision`, `ArchSourceTree`
    :param mod: new revision or directory,
    :type mod: `Revision`, `ArchSourceTree`
    :param dest: path of the changeset to create.
    :type dest: str
    :rtype: `ChangesetCreation`
    """
    orig = _tree_or_existing_revision_param(orig, 'orig')
    mod = _tree_or_existing_revision_param(mod, 'mod')
    _check_str_param(dest, 'dest')
    proc = _arch.iter_delta(orig, mod, dest)
    return ChangesetCreation(proc, dest)


def delta(orig, mod, dest):
    """Compute a whole-tree changeset.

    Create the output directory ``dest`` (it must not already exist).

    Compare the source trees ``orig`` and ``mod`` (which may be source
    arch source tree or revisions). Create a changeset in ``dest``.

    :param orig: the old revision or directory.
    :type orig: `Revision`, `ArchSourceTree`
    :param mod: the new revision or directory.
    :type mod: `Revision`, `ArchSourceTree`
    :param dest: path of the changeset to create.
    :type dest: str
    :return: changeset from ``orig`` to ``mod``.
    :rtype: `Changeset`
    """
    __pychecker__ = 'unusednames=line'
    iter_ = iter_delta(orig, mod, dest)
    for line in iter_: pass
    return iter_.changeset


### Top level archive functions ###

public('my_id', 'set_my_id', 'make_archive', 'register_archive')

def my_id():
    """The current registered user id

    :return: the user id, for example 'John Doe <jdoe@example.org>'.
    :rtype: str
    """
    return _arch.my_id()


def set_my_id(new_id):
    """Set the current registered user id

    :param new_id: new value of the user id.
    :type new_id: str
    """
    return _arch.set_my_id(new_id)


def make_archive(name, location, signed=False, listing=False):
    """Create and register new commitable archive.

    :param name: archive name (e.g. "david@allouche.net--2003b").
    :type name: `Archive` or str
    :param location: URL of the archive
    :type location: str
    :param signed: create GPG signatures for the archive contents.
    :type signed: bool
    :param listing: maintains ''.listing'' files to enable HTTP access.
    :type listing: bool

    :return: an `Archive` instance for the given name.
    :rtype: `Archive`

    :raise errors.NamespaceError: ``name`` is not a valid archive name.
    """
    name = _archive_param(name)
    _arch.make_archive(name, location, signed, listing)
    return Archive(_unsafe((name,)))

def register_archive(name, location):
    """Record the location of an archive.

    :param name: archive name, or None to use the official name stored in the
        archive.
    :type name: str, None
    :param location: URL of the archive.
    :type location: str
    :return: newly registered archive.
    :rtype: `Archive`.
    """
    if name is not None:
        name = _archive_param(name)
    _arch.register_archive(name, location)
    if name is not None:
        return Archive(_unsafe((name,)))
    else:
        for n in _arch.archives():
            a = Archive(_unsafe((n,)))
            if a.location == location:
                return a
        raise AssertionError, 'not reached'


public('iter_archives', 'archives')

def iter_archives():
    """Iterate over registered archives.

    :return: all registered archives.
    :rtype: iterable of `Archive`
    """
    for n in _arch.archives():
        yield Archive(n)


def archives():
    """Deprecated.

    List of registered archives.

    :rtype: sequence of `Archive`
    :see: `iter_archives`
    """
    deprecated_callable(archives, iter_archives)
    return list(iter_archives())


public('iter_library_archives', 'library_archives')

def iter_library_archives():
    """Iterate over archives present in the revision library.

    :returns: all archives which are present in the revision library.
    :rtype: iterable of `Archive`
    """
    for n in _arch.library_archives():
        yield Archive(n)


def library_archives():
    """Deprecated.

    List of archives present in the revision library.

    :rtype: sequence of `Archive`
    :see: `iter_library_archives`
    """
    deprecated_callable(library_archives, iter_library_archives)
    return list(iter_library_archives())


public('default_archive')

def default_archive():
    """Default Archive object or None.

    :return: the default archive, or None.
    :rtype: `Archive`, None
    """
    name = _arch.default_archive()
    if name is None:
        return None
    else:
        return Archive(name)


public('make_continuation')

def make_continuation(source_revision, tag_version):
    """Deprecated.

    :see: `Revision.make_continuation`
    """
    deprecated_callable(make_continuation, Revision.make_continuation)
    source_revision = _version_revision_param(source_revision)
    tag_version = _version_param(tag_version)
    _arch.archive_setup(tag_version)
    _arch.tag(source_revision, tag_version)

public('get', 'get_patch')

def get(revision, dir, link=False):
    """Deprecated.

    Construct a project tree for a revision.

    :rtype: `WorkingTree`
    :see: `Revision.get`
    """
    deprecated_callable(get, Revision.get)
    revision = _package_revision_param(revision)
    _arch.get(revision, dir, link)
    return WorkingTree(dir)


def get_patch(revision, dir):
    """Deprecated.

    :rtype: `Changeset`
    :see: `Revision.get_patch`
    """
    deprecated_callable(get_patch, Revision.get_patch)
    revision = _revision_param(revision)
    _arch.get_patch(revision, dir)
    return Changeset(dir)


public(
    'iter_revision_libraries',
    'register_revision_library',
    'unregister_revision_library',
    )

def iter_revision_libraries():
    """Iterate over registered revision library directories.

    :return: directory names of all registered revision libraries.
    :rtype: iterable of str
    """
    return _arch.iter_revision_libraries()

def register_revision_library(dirname):
    """Register an existing revision library directory.

    :param dirname: absolute path name of existing user-writable directory.
    :type dirname: str
    :todo: create_revision_library which abstracts out revlib construction.
    :postcondition: ``dirname`` is present in `iter_revision_libraries` output.
    """
    if not os.path.isabs(dirname):
        raise ValueError, "not an absolute path: %r" % dirname
    if not os.path.isdir(dirname):
        raise ValueError, "directory does not exist: %r" % dirname
    _arch.register_revision_library(dirname)

def unregister_revision_library(dirname):
    """Unregister a revision library directory.

    :param dirname: registered revision library directory.
    :type dirname: str
    :todo: delete_revision_library which abstracts out revlib destruction.
    :precondition: ``dirname`` is present in `iter_revision_libraries` output.
    :postcondition: ``dirname`` is not listed by `iter_revision_libraries`.
    """
    if not os.path.isabs(dirname):
        raise ValueError, "not an absolute path: %r" % dirname
    _arch.unregister_revision_library(dirname)


### Parsing Arch names ###

public('NameParser')

class NameParser(_arch.NameParser):

    """Parser for names in Arch archive namespace.

    :see: `backends.tla.NameParser`
    """

    def object(self):
        """Create the Category, Branch, Version or Revision object

        Create the namespace object corresponding to the name. This
        requires some guessing so, for example, nameless branches will
        not be recognized.

        :warning: DEPRECATED: unsafe and not really useful.
        """
        a = self.get_archive()
        if not a: return None
        a = Archive(a)
        c = self.get_category()
        if not c: return a
        c = a[c]
        b = self.get_branch()
        if not b: return c
        b = c[b]
        v = self.get_version()
        if not v: return b
        v = b[v]
        r = self.get_patchlevel()
        if not r: return v
        return v[r]


### Searching in Archives ###

public(
    'filter_archive_logs',
    'filter_revisions',
    'grep_summary',
    'grep_summary_interactive',
    'suspected_move',
    'revisions_merging',
    'temphack',
    'revision_which_created',
    'last_revision',
    'map_name_id',
    )

def filter_archive_logs(limit, pred):
    deprecated_callable(filter_archive_logs,
                        because='It does not belong here.')
    for r in limit.iter_revisions():
        if pred(r.patchlog): yield r


def filter_revisions(limit, pred):
    deprecated_callable(filter_archive_logs,
                        because='It does not belong here.')
    for r in limit.iter_revisions():
        if pred(r): yield r

def grep_summary(limit, rx):
    deprecated_callable(grep_summary,
                        because='It does not belong here.')
    crx = re.compile(rx)
    def pred(p): return crx.search(p['Summary'])
    return filter_archive_logs(limit, pred)


def grep_summary_interactive(limit):
    deprecated_callable(grep_summary_interactive,
                        because='It does not belong here.')
    while True:
        try:
            rx = raw_input('search> ')
        except KeyboardInterrupt:
            break
        if not rx: break
        for r in grep_summary(limit, rx):
            p = r.patchlog
            print 'Revision:', p['Revision']
            print 'Summary: ', p['Summary']


def suspected_move(limit):
    deprecated_callable(suspected_move,
                        because='It does not belong here.')
    def pred(p): return bool(p['New-files'] and p['Removed-files'])
    return filter_archive_logs(limit, pred)


def revisions_merging(limit, rev):
    deprecated_callable(revisions_merging,
                        because='It does not belong here.')
    def pred(p): return rev in p.merged_patches
    return filter_archive_logs(limit, pred)


def temphack(revision):
    deprecated_callable(temphack,
                        because='It does not belong here.')
    import sets
    retval = sets.Set()
    for ancstr in revision.iter_ancestors(metoo=True):
        for k in ancstr.patchlog.keys():
            retval.add(k)
    return retval


def revision_which_created(file, revision):
    deprecated_callable(revision_which_created,
                        because='It does not belong here.')
    for ancstr in revision.iter_ancestors(metoo=True):
        if file in ancstr.patchlog.new_files:
            return ancstr
    return None

def last_revision(tree):
    deprecated_callable(last_revision, (ArchSourceTree, 'tree_revision'))
    tree = SourceTree(tree)
    return tree.iter_logs(reverse=True).next().revision


def map_name_id(tree):
    deprecated_callable(map_name_id,
                        because='It does not belong here.')
    if not isinstance(tree, SourceTree):
        tree = SourceTree(tree)
    retval = {}
    for id_, name in tree.iter_inventory_ids(source=True, files=True):
        retval[name] = id_
    return retval