~bzr-pqm/bzr/bzr.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
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

"""BzrDir logic. The BzrDir is the basic control directory used by bzr.

At format 7 this was split out into Branch, Repository and Checkout control
directories.

Note: This module has a lot of ``open`` functions/methods that return
references to in-memory objects. As a rule, there are no matching ``close``
methods. To free any associated resources, simply stop referencing the
objects returned.
"""

# TODO: Move old formats into a plugin to make this file smaller.

import os
import sys

from bzrlib.lazy_import import lazy_import
lazy_import(globals(), """
from stat import S_ISDIR
import textwrap

import bzrlib
from bzrlib import (
    branch,
    config,
    errors,
    graph,
    lockable_files,
    lockdir,
    osutils,
    remote,
    repository,
    revision as _mod_revision,
    ui,
    urlutils,
    versionedfile,
    win32utils,
    workingtree,
    workingtree_4,
    xml4,
    xml5,
    )
from bzrlib.osutils import (
    sha_string,
    )
from bzrlib.push import (
    PushResult,
    )
from bzrlib.repofmt import pack_repo
from bzrlib.smart.client import _SmartClient
from bzrlib.store.versioned import WeaveStore
from bzrlib.transactions import WriteTransaction
from bzrlib.transport import (
    do_catching_redirections,
    get_transport,
    local,
    remote as remote_transport,
    )
from bzrlib.weave import Weave
""")

from bzrlib.trace import (
    mutter,
    note,
    )

from bzrlib import (
    hooks,
    registry,
    symbol_versioning,
    )


class BzrDir(object):
    """A .bzr control diretory.

    BzrDir instances let you create or open any of the things that can be
    found within .bzr - checkouts, branches and repositories.

    :ivar transport:
        the transport which this bzr dir is rooted at (i.e. file:///.../.bzr/)
    :ivar root_transport:
        a transport connected to the directory this bzr was opened from
        (i.e. the parent directory holding the .bzr directory).

    Everything in the bzrdir should have the same file permissions.

    :cvar hooks: An instance of BzrDirHooks.
    """

    def break_lock(self):
        """Invoke break_lock on the first object in the bzrdir.

        If there is a tree, the tree is opened and break_lock() called.
        Otherwise, branch is tried, and finally repository.
        """
        # XXX: This seems more like a UI function than something that really
        # belongs in this class.
        try:
            thing_to_unlock = self.open_workingtree()
        except (errors.NotLocalUrl, errors.NoWorkingTree):
            try:
                thing_to_unlock = self.open_branch()
            except errors.NotBranchError:
                try:
                    thing_to_unlock = self.open_repository()
                except errors.NoRepositoryPresent:
                    return
        thing_to_unlock.break_lock()

    def can_convert_format(self):
        """Return true if this bzrdir is one whose format we can convert from."""
        return True

    def check_conversion_target(self, target_format):
        target_repo_format = target_format.repository_format
        source_repo_format = self._format.repository_format
        source_repo_format.check_conversion_target(target_repo_format)

    @staticmethod
    def _check_supported(format, allow_unsupported,
        recommend_upgrade=True,
        basedir=None):
        """Give an error or warning on old formats.

        :param format: may be any kind of format - workingtree, branch,
        or repository.

        :param allow_unsupported: If true, allow opening
        formats that are strongly deprecated, and which may
        have limited functionality.

        :param recommend_upgrade: If true (default), warn
        the user through the ui object that they may wish
        to upgrade the object.
        """
        # TODO: perhaps move this into a base Format class; it's not BzrDir
        # specific. mbp 20070323
        if not allow_unsupported and not format.is_supported():
            # see open_downlevel to open legacy branches.
            raise errors.UnsupportedFormatError(format=format)
        if recommend_upgrade \
            and getattr(format, 'upgrade_recommended', False):
            ui.ui_factory.recommend_upgrade(
                format.get_format_description(),
                basedir)

    def clone(self, url, revision_id=None, force_new_repo=False,
              preserve_stacking=False):
        """Clone this bzrdir and its contents to url verbatim.

        :param url: The url create the clone at.  If url's last component does
            not exist, it will be created.
        :param revision_id: The tip revision-id to use for any branch or
            working tree.  If not None, then the clone operation may tune
            itself to download less data.
        :param force_new_repo: Do not use a shared repository for the target
                               even if one is available.
        :param preserve_stacking: When cloning a stacked branch, stack the
            new branch on top of the other branch's stacked-on branch.
        """
        return self.clone_on_transport(get_transport(url),
                                       revision_id=revision_id,
                                       force_new_repo=force_new_repo,
                                       preserve_stacking=preserve_stacking)

    def clone_on_transport(self, transport, revision_id=None,
        force_new_repo=False, preserve_stacking=False, stacked_on=None,
        create_prefix=False, use_existing_dir=True):
        """Clone this bzrdir and its contents to transport verbatim.

        :param transport: The transport for the location to produce the clone
            at.  If the target directory does not exist, it will be created.
        :param revision_id: The tip revision-id to use for any branch or
            working tree.  If not None, then the clone operation may tune
            itself to download less data.
        :param force_new_repo: Do not use a shared repository for the target,
                               even if one is available.
        :param preserve_stacking: When cloning a stacked branch, stack the
            new branch on top of the other branch's stacked-on branch.
        :param create_prefix: Create any missing directories leading up to
            to_transport.
        :param use_existing_dir: Use an existing directory if one exists.
        """
        # Overview: put together a broad description of what we want to end up
        # with; then make as few api calls as possible to do it.
        
        # We may want to create a repo/branch/tree, if we do so what format
        # would we want for each:
        require_stacking = (stacked_on is not None)
        format = self.cloning_metadir(require_stacking)
        
        # Figure out what objects we want:
        try:
            local_repo = self.find_repository()
        except errors.NoRepositoryPresent:
            local_repo = None
        try:
            local_branch = self.open_branch()
        except errors.NotBranchError:
            local_branch = None
        else:
            # enable fallbacks when branch is not a branch reference
            if local_branch.repository.has_same_location(local_repo):
                local_repo = local_branch.repository
            if preserve_stacking:
                try:
                    stacked_on = local_branch.get_stacked_on_url()
                except (errors.UnstackableBranchFormat,
                        errors.UnstackableRepositoryFormat,
                        errors.NotStacked):
                    pass
        # Bug: We create a metadir without knowing if it can support stacking,
        # we should look up the policy needs first, or just use it as a hint,
        # or something.
        if local_repo:
            make_working_trees = local_repo.make_working_trees()
            want_shared = local_repo.is_shared()
            repo_format_name = format.repository_format.network_name()
        else:
            make_working_trees = False
            want_shared = False
            repo_format_name = None

        result_repo, result, require_stacking, repository_policy = \
            format.initialize_on_transport_ex(transport,
            use_existing_dir=use_existing_dir, create_prefix=create_prefix,
            force_new_repo=force_new_repo, stacked_on=stacked_on,
            stack_on_pwd=self.root_transport.base,
            repo_format_name=repo_format_name,
            make_working_trees=make_working_trees, shared_repo=want_shared)
        if repo_format_name:
            try:
                # If the result repository is in the same place as the
                # resulting bzr dir, it will have no content, further if the
                # result is not stacked then we know all content should be
                # copied, and finally if we are copying up to a specific
                # revision_id then we can use the pending-ancestry-result which
                # does not require traversing all of history to describe it.
                if (result_repo.bzrdir.root_transport.base ==
                    result.root_transport.base and not require_stacking and
                    revision_id is not None):
                    fetch_spec = graph.PendingAncestryResult(
                        [revision_id], local_repo)
                    result_repo.fetch(local_repo, fetch_spec=fetch_spec)
                else:
                    result_repo.fetch(local_repo, revision_id=revision_id)
            finally:
                result_repo.unlock()
        else:
            if result_repo is not None:
                raise AssertionError('result_repo not None(%r)' % result_repo)
        # 1 if there is a branch present
        #   make sure its content is available in the target repository
        #   clone it.
        if local_branch is not None:
            result_branch = local_branch.clone(result, revision_id=revision_id,
                repository_policy=repository_policy)
        try:
            # Cheaper to check if the target is not local, than to try making
            # the tree and fail.
            result.root_transport.local_abspath('.')
            if result_repo is None or result_repo.make_working_trees():
                self.open_workingtree().clone(result)
        except (errors.NoWorkingTree, errors.NotLocalUrl):
            pass
        return result

    # TODO: This should be given a Transport, and should chdir up; otherwise
    # this will open a new connection.
    def _make_tail(self, url):
        t = get_transport(url)
        t.ensure_base()

    @classmethod
    def create(cls, base, format=None, possible_transports=None):
        """Create a new BzrDir at the url 'base'.

        :param format: If supplied, the format of branch to create.  If not
            supplied, the default is used.
        :param possible_transports: If supplied, a list of transports that
            can be reused to share a remote connection.
        """
        if cls is not BzrDir:
            raise AssertionError("BzrDir.create always creates the default"
                " format, not one of %r" % cls)
        t = get_transport(base, possible_transports)
        t.ensure_base()
        if format is None:
            format = BzrDirFormat.get_default_format()
        return format.initialize_on_transport(t)

    @staticmethod
    def find_bzrdirs(transport, evaluate=None, list_current=None):
        """Find bzrdirs recursively from current location.

        This is intended primarily as a building block for more sophisticated
        functionality, like finding trees under a directory, or finding
        branches that use a given repository.
        :param evaluate: An optional callable that yields recurse, value,
            where recurse controls whether this bzrdir is recursed into
            and value is the value to yield.  By default, all bzrdirs
            are recursed into, and the return value is the bzrdir.
        :param list_current: if supplied, use this function to list the current
            directory, instead of Transport.list_dir
        :return: a generator of found bzrdirs, or whatever evaluate returns.
        """
        if list_current is None:
            def list_current(transport):
                return transport.list_dir('')
        if evaluate is None:
            def evaluate(bzrdir):
                return True, bzrdir

        pending = [transport]
        while len(pending) > 0:
            current_transport = pending.pop()
            recurse = True
            try:
                bzrdir = BzrDir.open_from_transport(current_transport)
            except errors.NotBranchError:
                pass
            else:
                recurse, value = evaluate(bzrdir)
                yield value
            try:
                subdirs = list_current(current_transport)
            except errors.NoSuchFile:
                continue
            if recurse:
                for subdir in sorted(subdirs, reverse=True):
                    pending.append(current_transport.clone(subdir))

    @staticmethod
    def find_branches(transport):
        """Find all branches under a transport.

        This will find all branches below the transport, including branches
        inside other branches.  Where possible, it will use
        Repository.find_branches.

        To list all the branches that use a particular Repository, see
        Repository.find_branches
        """
        def evaluate(bzrdir):
            try:
                repository = bzrdir.open_repository()
            except errors.NoRepositoryPresent:
                pass
            else:
                return False, (None, repository)
            try:
                branch = bzrdir.open_branch()
            except errors.NotBranchError:
                return True, (None, None)
            else:
                return True, (branch, None)
        branches = []
        for branch, repo in BzrDir.find_bzrdirs(transport, evaluate=evaluate):
            if repo is not None:
                branches.extend(repo.find_branches())
            if branch is not None:
                branches.append(branch)
        return branches

    def destroy_repository(self):
        """Destroy the repository in this BzrDir"""
        raise NotImplementedError(self.destroy_repository)

    def create_branch(self):
        """Create a branch in this BzrDir.

        The bzrdir's format will control what branch format is created.
        For more control see BranchFormatXX.create(a_bzrdir).
        """
        raise NotImplementedError(self.create_branch)

    def destroy_branch(self):
        """Destroy the branch in this BzrDir"""
        raise NotImplementedError(self.destroy_branch)

    @staticmethod
    def create_branch_and_repo(base, force_new_repo=False, format=None):
        """Create a new BzrDir, Branch and Repository at the url 'base'.

        This will use the current default BzrDirFormat unless one is
        specified, and use whatever
        repository format that that uses via bzrdir.create_branch and
        create_repository. If a shared repository is available that is used
        preferentially.

        The created Branch object is returned.

        :param base: The URL to create the branch at.
        :param force_new_repo: If True a new repository is always created.
        :param format: If supplied, the format of branch to create.  If not
            supplied, the default is used.
        """
        bzrdir = BzrDir.create(base, format)
        bzrdir._find_or_create_repository(force_new_repo)
        return bzrdir.create_branch()

    def determine_repository_policy(self, force_new_repo=False, stack_on=None,
                                    stack_on_pwd=None, require_stacking=False):
        """Return an object representing a policy to use.

        This controls whether a new repository is created, and the format of
        that repository, or some existing shared repository used instead.

        If stack_on is supplied, will not seek a containing shared repo.

        :param force_new_repo: If True, require a new repository to be created.
        :param stack_on: If supplied, the location to stack on.  If not
            supplied, a default_stack_on location may be used.
        :param stack_on_pwd: If stack_on is relative, the location it is
            relative to.
        """
        def repository_policy(found_bzrdir):
            stack_on = None
            stack_on_pwd = None
            config = found_bzrdir.get_config()
            stop = False
            stack_on = config.get_default_stack_on()
            if stack_on is not None:
                stack_on_pwd = found_bzrdir.root_transport.base
                stop = True
            # does it have a repository ?
            try:
                repository = found_bzrdir.open_repository()
            except errors.NoRepositoryPresent:
                repository = None
            else:
                if ((found_bzrdir.root_transport.base !=
                     self.root_transport.base) and not repository.is_shared()):
                    # Don't look higher, can't use a higher shared repo.
                    repository = None
                    stop = True
                else:
                    stop = True
            if not stop:
                return None, False
            if repository:
                return UseExistingRepository(repository, stack_on,
                    stack_on_pwd, require_stacking=require_stacking), True
            else:
                return CreateRepository(self, stack_on, stack_on_pwd,
                    require_stacking=require_stacking), True

        if not force_new_repo:
            if stack_on is None:
                policy = self._find_containing(repository_policy)
                if policy is not None:
                    return policy
            else:
                try:
                    return UseExistingRepository(self.open_repository(),
                        stack_on, stack_on_pwd,
                        require_stacking=require_stacking)
                except errors.NoRepositoryPresent:
                    pass
        return CreateRepository(self, stack_on, stack_on_pwd,
                                require_stacking=require_stacking)

    def _find_or_create_repository(self, force_new_repo):
        """Create a new repository if needed, returning the repository."""
        policy = self.determine_repository_policy(force_new_repo)
        return policy.acquire_repository()[0]

    @staticmethod
    def create_branch_convenience(base, force_new_repo=False,
                                  force_new_tree=None, format=None,
                                  possible_transports=None):
        """Create a new BzrDir, Branch and Repository at the url 'base'.

        This is a convenience function - it will use an existing repository
        if possible, can be told explicitly whether to create a working tree or
        not.

        This will use the current default BzrDirFormat unless one is
        specified, and use whatever
        repository format that that uses via bzrdir.create_branch and
        create_repository. If a shared repository is available that is used
        preferentially. Whatever repository is used, its tree creation policy
        is followed.

        The created Branch object is returned.
        If a working tree cannot be made due to base not being a file:// url,
        no error is raised unless force_new_tree is True, in which case no
        data is created on disk and NotLocalUrl is raised.

        :param base: The URL to create the branch at.
        :param force_new_repo: If True a new repository is always created.
        :param force_new_tree: If True or False force creation of a tree or
                               prevent such creation respectively.
        :param format: Override for the bzrdir format to create.
        :param possible_transports: An optional reusable transports list.
        """
        if force_new_tree:
            # check for non local urls
            t = get_transport(base, possible_transports)
            if not isinstance(t, local.LocalTransport):
                raise errors.NotLocalUrl(base)
        bzrdir = BzrDir.create(base, format, possible_transports)
        repo = bzrdir._find_or_create_repository(force_new_repo)
        result = bzrdir.create_branch()
        if force_new_tree or (repo.make_working_trees() and
                              force_new_tree is None):
            try:
                bzrdir.create_workingtree()
            except errors.NotLocalUrl:
                pass
        return result

    @staticmethod
    def create_standalone_workingtree(base, format=None):
        """Create a new BzrDir, WorkingTree, Branch and Repository at 'base'.

        'base' must be a local path or a file:// url.

        This will use the current default BzrDirFormat unless one is
        specified, and use whatever
        repository format that that uses for bzrdirformat.create_workingtree,
        create_branch and create_repository.

        :param format: Override for the bzrdir format to create.
        :return: The WorkingTree object.
        """
        t = get_transport(base)
        if not isinstance(t, local.LocalTransport):
            raise errors.NotLocalUrl(base)
        bzrdir = BzrDir.create_branch_and_repo(base,
                                               force_new_repo=True,
                                               format=format).bzrdir
        return bzrdir.create_workingtree()

    def create_workingtree(self, revision_id=None, from_branch=None,
        accelerator_tree=None, hardlink=False):
        """Create a working tree at this BzrDir.

        :param revision_id: create it as of this revision id.
        :param from_branch: override bzrdir branch (for lightweight checkouts)
        :param accelerator_tree: A tree which can be used for retrieving file
            contents more quickly than the revision tree, i.e. a workingtree.
            The revision tree will be used for cases where accelerator_tree's
            content is different.
        """
        raise NotImplementedError(self.create_workingtree)

    def backup_bzrdir(self):
        """Backup this bzr control directory.

        :return: Tuple with old path name and new path name
        """
        pb = ui.ui_factory.nested_progress_bar()
        try:
            # FIXME: bug 300001 -- the backup fails if the backup directory
            # already exists, but it should instead either remove it or make
            # a new backup directory.
            #
            # FIXME: bug 262450 -- the backup directory should have the same
            # permissions as the .bzr directory (probably a bug in copy_tree)
            old_path = self.root_transport.abspath('.bzr')
            new_path = self.root_transport.abspath('backup.bzr')
            pb.note('making backup of %s' % (old_path,))
            pb.note('  to %s' % (new_path,))
            self.root_transport.copy_tree('.bzr', 'backup.bzr')
            return (old_path, new_path)
        finally:
            pb.finished()

    def retire_bzrdir(self, limit=10000):
        """Permanently disable the bzrdir.

        This is done by renaming it to give the user some ability to recover
        if there was a problem.

        This will have horrible consequences if anyone has anything locked or
        in use.
        :param limit: number of times to retry
        """
        i  = 0
        while True:
            try:
                to_path = '.bzr.retired.%d' % i
                self.root_transport.rename('.bzr', to_path)
                note("renamed %s to %s"
                    % (self.root_transport.abspath('.bzr'), to_path))
                return
            except (errors.TransportError, IOError, errors.PathError):
                i += 1
                if i > limit:
                    raise
                else:
                    pass

    def destroy_workingtree(self):
        """Destroy the working tree at this BzrDir.

        Formats that do not support this may raise UnsupportedOperation.
        """
        raise NotImplementedError(self.destroy_workingtree)

    def destroy_workingtree_metadata(self):
        """Destroy the control files for the working tree at this BzrDir.

        The contents of working tree files are not affected.
        Formats that do not support this may raise UnsupportedOperation.
        """
        raise NotImplementedError(self.destroy_workingtree_metadata)

    def _find_containing(self, evaluate):
        """Find something in a containing control directory.

        This method will scan containing control dirs, until it finds what
        it is looking for, decides that it will never find it, or runs out
        of containing control directories to check.

        It is used to implement find_repository and
        determine_repository_policy.

        :param evaluate: A function returning (value, stop).  If stop is True,
            the value will be returned.
        """
        found_bzrdir = self
        while True:
            result, stop = evaluate(found_bzrdir)
            if stop:
                return result
            next_transport = found_bzrdir.root_transport.clone('..')
            if (found_bzrdir.root_transport.base == next_transport.base):
                # top of the file system
                return None
            # find the next containing bzrdir
            try:
                found_bzrdir = BzrDir.open_containing_from_transport(
                    next_transport)[0]
            except errors.NotBranchError:
                return None

    def find_repository(self):
        """Find the repository that should be used.

        This does not require a branch as we use it to find the repo for
        new branches as well as to hook existing branches up to their
        repository.
        """
        def usable_repository(found_bzrdir):
            # does it have a repository ?
            try:
                repository = found_bzrdir.open_repository()
            except errors.NoRepositoryPresent:
                return None, False
            if found_bzrdir.root_transport.base == self.root_transport.base:
                return repository, True
            elif repository.is_shared():
                return repository, True
            else:
                return None, True

        found_repo = self._find_containing(usable_repository)
        if found_repo is None:
            raise errors.NoRepositoryPresent(self)
        return found_repo

    def get_branch_reference(self):
        """Return the referenced URL for the branch in this bzrdir.

        :raises NotBranchError: If there is no Branch.
        :return: The URL the branch in this bzrdir references if it is a
            reference branch, or None for regular branches.
        """
        return None

    def get_branch_transport(self, branch_format):
        """Get the transport for use by branch format in this BzrDir.

        Note that bzr dirs that do not support format strings will raise
        IncompatibleFormat if the branch format they are given has
        a format string, and vice versa.

        If branch_format is None, the transport is returned with no
        checking. If it is not None, then the returned transport is
        guaranteed to point to an existing directory ready for use.
        """
        raise NotImplementedError(self.get_branch_transport)

    def _find_creation_modes(self):
        """Determine the appropriate modes for files and directories.

        They're always set to be consistent with the base directory,
        assuming that this transport allows setting modes.
        """
        # TODO: Do we need or want an option (maybe a config setting) to turn
        # this off or override it for particular locations? -- mbp 20080512
        if self._mode_check_done:
            return
        self._mode_check_done = True
        try:
            st = self.transport.stat('.')
        except errors.TransportNotPossible:
            self._dir_mode = None
            self._file_mode = None
        else:
            # Check the directory mode, but also make sure the created
            # directories and files are read-write for this user. This is
            # mostly a workaround for filesystems which lie about being able to
            # write to a directory (cygwin & win32)
            if (st.st_mode & 07777 == 00000):
                # FTP allows stat but does not return dir/file modes
                self._dir_mode = None
                self._file_mode = None
            else:
                self._dir_mode = (st.st_mode & 07777) | 00700
                # Remove the sticky and execute bits for files
                self._file_mode = self._dir_mode & ~07111

    def _get_file_mode(self):
        """Return Unix mode for newly created files, or None.
        """
        if not self._mode_check_done:
            self._find_creation_modes()
        return self._file_mode

    def _get_dir_mode(self):
        """Return Unix mode for newly created directories, or None.
        """
        if not self._mode_check_done:
            self._find_creation_modes()
        return self._dir_mode

    def get_repository_transport(self, repository_format):
        """Get the transport for use by repository format in this BzrDir.

        Note that bzr dirs that do not support format strings will raise
        IncompatibleFormat if the repository format they are given has
        a format string, and vice versa.

        If repository_format is None, the transport is returned with no
        checking. If it is not None, then the returned transport is
        guaranteed to point to an existing directory ready for use.
        """
        raise NotImplementedError(self.get_repository_transport)

    def get_workingtree_transport(self, tree_format):
        """Get the transport for use by workingtree format in this BzrDir.

        Note that bzr dirs that do not support format strings will raise
        IncompatibleFormat if the workingtree format they are given has a
        format string, and vice versa.

        If workingtree_format is None, the transport is returned with no
        checking. If it is not None, then the returned transport is
        guaranteed to point to an existing directory ready for use.
        """
        raise NotImplementedError(self.get_workingtree_transport)

    def get_config(self):
        """Get configuration for this BzrDir."""
        return config.BzrDirConfig(self)

    def _get_config(self):
        """By default, no configuration is available."""
        return None

    def __init__(self, _transport, _format):
        """Initialize a Bzr control dir object.

        Only really common logic should reside here, concrete classes should be
        made with varying behaviours.

        :param _format: the format that is creating this BzrDir instance.
        :param _transport: the transport this dir is based at.
        """
        self._format = _format
        self.transport = _transport.clone('.bzr')
        self.root_transport = _transport
        self._mode_check_done = False

    def is_control_filename(self, filename):
        """True if filename is the name of a path which is reserved for bzrdir's.

        :param filename: A filename within the root transport of this bzrdir.

        This is true IF and ONLY IF the filename is part of the namespace reserved
        for bzr control dirs. Currently this is the '.bzr' directory in the root
        of the root_transport. it is expected that plugins will need to extend
        this in the future - for instance to make bzr talk with svn working
        trees.
        """
        # this might be better on the BzrDirFormat class because it refers to
        # all the possible bzrdir disk formats.
        # This method is tested via the workingtree is_control_filename tests-
        # it was extracted from WorkingTree.is_control_filename. If the method's
        # contract is extended beyond the current trivial implementation, please
        # add new tests for it to the appropriate place.
        return filename == '.bzr' or filename.startswith('.bzr/')

    def needs_format_conversion(self, format=None):
        """Return true if this bzrdir needs convert_format run on it.

        For instance, if the repository format is out of date but the
        branch and working tree are not, this should return True.

        :param format: Optional parameter indicating a specific desired
                       format we plan to arrive at.
        """
        raise NotImplementedError(self.needs_format_conversion)

    @staticmethod
    def open_unsupported(base):
        """Open a branch which is not supported."""
        return BzrDir.open(base, _unsupported=True)

    @staticmethod
    def open(base, _unsupported=False, possible_transports=None):
        """Open an existing bzrdir, rooted at 'base' (url).

        :param _unsupported: a private parameter to the BzrDir class.
        """
        t = get_transport(base, possible_transports=possible_transports)
        return BzrDir.open_from_transport(t, _unsupported=_unsupported)

    @staticmethod
    def open_from_transport(transport, _unsupported=False,
                            _server_formats=True):
        """Open a bzrdir within a particular directory.

        :param transport: Transport containing the bzrdir.
        :param _unsupported: private.
        """
        for hook in BzrDir.hooks['pre_open']:
            hook(transport)
        # Keep initial base since 'transport' may be modified while following
        # the redirections.
        base = transport.base
        def find_format(transport):
            return transport, BzrDirFormat.find_format(
                transport, _server_formats=_server_formats)

        def redirected(transport, e, redirection_notice):
            redirected_transport = transport._redirected_to(e.source, e.target)
            if redirected_transport is None:
                raise errors.NotBranchError(base)
            note('%s is%s redirected to %s',
                 transport.base, e.permanently, redirected_transport.base)
            return redirected_transport

        try:
            transport, format = do_catching_redirections(find_format,
                                                         transport,
                                                         redirected)
        except errors.TooManyRedirections:
            raise errors.NotBranchError(base)

        BzrDir._check_supported(format, _unsupported)
        return format.open(transport, _found=True)

    def open_branch(self, unsupported=False, ignore_fallbacks=False):
        """Open the branch object at this BzrDir if one is present.

        If unsupported is True, then no longer supported branch formats can
        still be opened.

        TODO: static convenience version of this?
        """
        raise NotImplementedError(self.open_branch)

    @staticmethod
    def open_containing(url, possible_transports=None):
        """Open an existing branch which contains url.

        :param url: url to search from.
        See open_containing_from_transport for more detail.
        """
        transport = get_transport(url, possible_transports)
        return BzrDir.open_containing_from_transport(transport)

    @staticmethod
    def open_containing_from_transport(a_transport):
        """Open an existing branch which contains a_transport.base.

        This probes for a branch at a_transport, and searches upwards from there.

        Basically we keep looking up until we find the control directory or
        run into the root.  If there isn't one, raises NotBranchError.
        If there is one and it is either an unrecognised format or an unsupported
        format, UnknownFormatError or UnsupportedFormatError are raised.
        If there is one, it is returned, along with the unused portion of url.

        :return: The BzrDir that contains the path, and a Unicode path
                for the rest of the URL.
        """
        # this gets the normalised url back. I.e. '.' -> the full path.
        url = a_transport.base
        while True:
            try:
                result = BzrDir.open_from_transport(a_transport)
                return result, urlutils.unescape(a_transport.relpath(url))
            except errors.NotBranchError, e:
                pass
            try:
                new_t = a_transport.clone('..')
            except errors.InvalidURLJoin:
                # reached the root, whatever that may be
                raise errors.NotBranchError(path=url)
            if new_t.base == a_transport.base:
                # reached the root, whatever that may be
                raise errors.NotBranchError(path=url)
            a_transport = new_t

    def _get_tree_branch(self):
        """Return the branch and tree, if any, for this bzrdir.

        Return None for tree if not present or inaccessible.
        Raise NotBranchError if no branch is present.
        :return: (tree, branch)
        """
        try:
            tree = self.open_workingtree()
        except (errors.NoWorkingTree, errors.NotLocalUrl):
            tree = None
            branch = self.open_branch()
        else:
            branch = tree.branch
        return tree, branch

    @classmethod
    def open_tree_or_branch(klass, location):
        """Return the branch and working tree at a location.

        If there is no tree at the location, tree will be None.
        If there is no branch at the location, an exception will be
        raised
        :return: (tree, branch)
        """
        bzrdir = klass.open(location)
        return bzrdir._get_tree_branch()

    @classmethod
    def open_containing_tree_or_branch(klass, location):
        """Return the branch and working tree contained by a location.

        Returns (tree, branch, relpath).
        If there is no tree at containing the location, tree will be None.
        If there is no branch containing the location, an exception will be
        raised
        relpath is the portion of the path that is contained by the branch.
        """
        bzrdir, relpath = klass.open_containing(location)
        tree, branch = bzrdir._get_tree_branch()
        return tree, branch, relpath

    @classmethod
    def open_containing_tree_branch_or_repository(klass, location):
        """Return the working tree, branch and repo contained by a location.

        Returns (tree, branch, repository, relpath).
        If there is no tree containing the location, tree will be None.
        If there is no branch containing the location, branch will be None.
        If there is no repository containing the location, repository will be
        None.
        relpath is the portion of the path that is contained by the innermost
        BzrDir.

        If no tree, branch or repository is found, a NotBranchError is raised.
        """
        bzrdir, relpath = klass.open_containing(location)
        try:
            tree, branch = bzrdir._get_tree_branch()
        except errors.NotBranchError:
            try:
                repo = bzrdir.find_repository()
                return None, None, repo, relpath
            except (errors.NoRepositoryPresent):
                raise errors.NotBranchError(location)
        return tree, branch, branch.repository, relpath

    def open_repository(self, _unsupported=False):
        """Open the repository object at this BzrDir if one is present.

        This will not follow the Branch object pointer - it's strictly a direct
        open facility. Most client code should use open_branch().repository to
        get at a repository.

        :param _unsupported: a private parameter, not part of the api.
        TODO: static convenience version of this?
        """
        raise NotImplementedError(self.open_repository)

    def open_workingtree(self, _unsupported=False,
                         recommend_upgrade=True, from_branch=None):
        """Open the workingtree object at this BzrDir if one is present.

        :param recommend_upgrade: Optional keyword parameter, when True (the
            default), emit through the ui module a recommendation that the user
            upgrade the working tree when the workingtree being opened is old
            (but still fully supported).
        :param from_branch: override bzrdir branch (for lightweight checkouts)
        """
        raise NotImplementedError(self.open_workingtree)

    def has_branch(self):
        """Tell if this bzrdir contains a branch.

        Note: if you're going to open the branch, you should just go ahead
        and try, and not ask permission first.  (This method just opens the
        branch and discards it, and that's somewhat expensive.)
        """
        try:
            self.open_branch()
            return True
        except errors.NotBranchError:
            return False

    def has_workingtree(self):
        """Tell if this bzrdir contains a working tree.

        This will still raise an exception if the bzrdir has a workingtree that
        is remote & inaccessible.

        Note: if you're going to open the working tree, you should just go ahead
        and try, and not ask permission first.  (This method just opens the
        workingtree and discards it, and that's somewhat expensive.)
        """
        try:
            self.open_workingtree(recommend_upgrade=False)
            return True
        except errors.NoWorkingTree:
            return False

    def _cloning_metadir(self):
        """Produce a metadir suitable for cloning with.

        :returns: (destination_bzrdir_format, source_repository)
        """
        result_format = self._format.__class__()
        try:
            try:
                branch = self.open_branch(ignore_fallbacks=True)
                source_repository = branch.repository
                result_format._branch_format = branch._format
            except errors.NotBranchError:
                source_branch = None
                source_repository = self.open_repository()
        except errors.NoRepositoryPresent:
            source_repository = None
        else:
            # XXX TODO: This isinstance is here because we have not implemented
            # the fix recommended in bug # 103195 - to delegate this choice the
            # repository itself.
            repo_format = source_repository._format
            if isinstance(repo_format, remote.RemoteRepositoryFormat):
                source_repository._ensure_real()
                repo_format = source_repository._real_repository._format
            result_format.repository_format = repo_format
        try:
            # TODO: Couldn't we just probe for the format in these cases,
            # rather than opening the whole tree?  It would be a little
            # faster. mbp 20070401
            tree = self.open_workingtree(recommend_upgrade=False)
        except (errors.NoWorkingTree, errors.NotLocalUrl):
            result_format.workingtree_format = None
        else:
            result_format.workingtree_format = tree._format.__class__()
        return result_format, source_repository

    def cloning_metadir(self, require_stacking=False):
        """Produce a metadir suitable for cloning or sprouting with.

        These operations may produce workingtrees (yes, even though they're
        "cloning" something that doesn't have a tree), so a viable workingtree
        format must be selected.

        :require_stacking: If True, non-stackable formats will be upgraded
            to similar stackable formats.
        :returns: a BzrDirFormat with all component formats either set
            appropriately or set to None if that component should not be
            created.
        """
        format, repository = self._cloning_metadir()
        if format._workingtree_format is None:
            # No tree in self.
            if repository is None:
                # No repository either
                return format
            # We have a repository, so set a working tree? (Why? This seems to
            # contradict the stated return value in the docstring).
            tree_format = repository._format._matchingbzrdir.workingtree_format
            format.workingtree_format = tree_format.__class__()
        if require_stacking:
            format.require_stacking()
        return format

    def checkout_metadir(self):
        return self.cloning_metadir()

    def sprout(self, url, revision_id=None, force_new_repo=False,
               recurse='down', possible_transports=None,
               accelerator_tree=None, hardlink=False, stacked=False,
               source_branch=None, create_tree_if_local=True):
        """Create a copy of this bzrdir prepared for use as a new line of
        development.

        If url's last component does not exist, it will be created.

        Attributes related to the identity of the source branch like
        branch nickname will be cleaned, a working tree is created
        whether one existed before or not; and a local branch is always
        created.

        if revision_id is not None, then the clone operation may tune
            itself to download less data.
        :param accelerator_tree: A tree which can be used for retrieving file
            contents more quickly than the revision tree, i.e. a workingtree.
            The revision tree will be used for cases where accelerator_tree's
            content is different.
        :param hardlink: If true, hard-link files from accelerator_tree,
            where possible.
        :param stacked: If true, create a stacked branch referring to the
            location of this control directory.
        :param create_tree_if_local: If true, a working-tree will be created
            when working locally.
        """
        target_transport = get_transport(url, possible_transports)
        target_transport.ensure_base()
        cloning_format = self.cloning_metadir(stacked)
        # Create/update the result branch
        result = cloning_format.initialize_on_transport(target_transport)
        # if a stacked branch wasn't requested, we don't create one
        # even if the origin was stacked
        stacked_branch_url = None
        if source_branch is not None:
            if stacked:
                stacked_branch_url = self.root_transport.base
            source_repository = source_branch.repository
        else:
            try:
                source_branch = self.open_branch()
                source_repository = source_branch.repository
                if stacked:
                    stacked_branch_url = self.root_transport.base
            except errors.NotBranchError:
                source_branch = None
                try:
                    source_repository = self.open_repository()
                except errors.NoRepositoryPresent:
                    source_repository = None
        repository_policy = result.determine_repository_policy(
            force_new_repo, stacked_branch_url, require_stacking=stacked)
        result_repo, is_new_repo = repository_policy.acquire_repository()
        if is_new_repo and revision_id is not None and not stacked:
            fetch_spec = graph.PendingAncestryResult(
                [revision_id], source_repository)
        else:
            fetch_spec = None
        if source_repository is not None:
            # Fetch while stacked to prevent unstacked fetch from
            # Branch.sprout.
            if fetch_spec is None:
                result_repo.fetch(source_repository, revision_id=revision_id)
            else:
                result_repo.fetch(source_repository, fetch_spec=fetch_spec)

        if source_branch is None:
            # this is for sprouting a bzrdir without a branch; is that
            # actually useful?
            # Not especially, but it's part of the contract.
            result_branch = result.create_branch()
        else:
            result_branch = source_branch.sprout(result,
                revision_id=revision_id, repository_policy=repository_policy)
        mutter("created new branch %r" % (result_branch,))

        # Create/update the result working tree
        if (create_tree_if_local and
            isinstance(target_transport, local.LocalTransport) and
            (result_repo is None or result_repo.make_working_trees())):
            wt = result.create_workingtree(accelerator_tree=accelerator_tree,
                hardlink=hardlink)
            wt.lock_write()
            try:
                if wt.path2id('') is None:
                    try:
                        wt.set_root_id(self.open_workingtree.get_root_id())
                    except errors.NoWorkingTree:
                        pass
            finally:
                wt.unlock()
        else:
            wt = None
        if recurse == 'down':
            if wt is not None:
                basis = wt.basis_tree()
                basis.lock_read()
                subtrees = basis.iter_references()
            elif result_branch is not None:
                basis = result_branch.basis_tree()
                basis.lock_read()
                subtrees = basis.iter_references()
            elif source_branch is not None:
                basis = source_branch.basis_tree()
                basis.lock_read()
                subtrees = basis.iter_references()
            else:
                subtrees = []
                basis = None
            try:
                for path, file_id in subtrees:
                    target = urlutils.join(url, urlutils.escape(path))
                    sublocation = source_branch.reference_parent(file_id, path)
                    sublocation.bzrdir.sprout(target,
                        basis.get_reference_revision(file_id, path),
                        force_new_repo=force_new_repo, recurse=recurse,
                        stacked=stacked)
            finally:
                if basis is not None:
                    basis.unlock()
        return result

    def push_branch(self, source, revision_id=None, overwrite=False, 
        remember=False):
        """Push the source branch into this BzrDir."""
        br_to = None
        # If we can open a branch, use its direct repository, otherwise see
        # if there is a repository without a branch.
        try:
            br_to = self.open_branch()
        except errors.NotBranchError:
            # Didn't find a branch, can we find a repository?
            repository_to = self.find_repository()
        else:
            # Found a branch, so we must have found a repository
            repository_to = br_to.repository

        push_result = PushResult()
        push_result.source_branch = source
        if br_to is None:
            # We have a repository but no branch, copy the revisions, and then
            # create a branch.
            repository_to.fetch(source.repository, revision_id=revision_id)
            br_to = source.clone(self, revision_id=revision_id)
            if source.get_push_location() is None or remember:
                source.set_push_location(br_to.base)
            push_result.stacked_on = None
            push_result.branch_push_result = None
            push_result.old_revno = None
            push_result.old_revid = _mod_revision.NULL_REVISION
            push_result.target_branch = br_to
            push_result.master_branch = None
            push_result.workingtree_updated = False
        else:
            # We have successfully opened the branch, remember if necessary:
            if source.get_push_location() is None or remember:
                source.set_push_location(br_to.base)
            try:
                tree_to = self.open_workingtree()
            except errors.NotLocalUrl:
                push_result.branch_push_result = source.push(br_to, 
                    overwrite, stop_revision=revision_id)
                push_result.workingtree_updated = False
            except errors.NoWorkingTree:
                push_result.branch_push_result = source.push(br_to,
                    overwrite, stop_revision=revision_id)
                push_result.workingtree_updated = None # Not applicable
            else:
                tree_to.lock_write()
                try:
                    push_result.branch_push_result = source.push(
                        tree_to.branch, overwrite, stop_revision=revision_id)
                    tree_to.update()
                finally:
                    tree_to.unlock()
                push_result.workingtree_updated = True
            push_result.old_revno = push_result.branch_push_result.old_revno
            push_result.old_revid = push_result.branch_push_result.old_revid
            push_result.target_branch = \
                push_result.branch_push_result.target_branch
        return push_result


class BzrDirHooks(hooks.Hooks):
    """Hooks for BzrDir operations."""

    def __init__(self):
        """Create the default hooks."""
        hooks.Hooks.__init__(self)
        self.create_hook(hooks.HookPoint('pre_open',
            "Invoked before attempting to open a BzrDir with the transport "
            "that the open will use.", (1, 14), None))

# install the default hooks
BzrDir.hooks = BzrDirHooks()


class BzrDirPreSplitOut(BzrDir):
    """A common class for the all-in-one formats."""

    def __init__(self, _transport, _format):
        """See BzrDir.__init__."""
        super(BzrDirPreSplitOut, self).__init__(_transport, _format)
        self._control_files = lockable_files.LockableFiles(
                                            self.get_branch_transport(None),
                                            self._format._lock_file_name,
                                            self._format._lock_class)

    def break_lock(self):
        """Pre-splitout bzrdirs do not suffer from stale locks."""
        raise NotImplementedError(self.break_lock)

    def cloning_metadir(self, require_stacking=False):
        """Produce a metadir suitable for cloning with."""
        if require_stacking:
            return format_registry.make_bzrdir('1.6')
        return self._format.__class__()

    def clone(self, url, revision_id=None, force_new_repo=False,
              preserve_stacking=False):
        """See BzrDir.clone().

        force_new_repo has no effect, since this family of formats always
        require a new repository.
        preserve_stacking has no effect, since no source branch using this
        family of formats can be stacked, so there is no stacking to preserve.
        """
        self._make_tail(url)
        result = self._format._initialize_for_clone(url)
        self.open_repository().clone(result, revision_id=revision_id)
        from_branch = self.open_branch()
        from_branch.clone(result, revision_id=revision_id)
        try:
            tree = self.open_workingtree()
        except errors.NotLocalUrl:
            # make a new one, this format always has to have one.
            result._init_workingtree()
        else:
            tree.clone(result)
        return result

    def create_branch(self):
        """See BzrDir.create_branch."""
        return self._format.get_branch_format().initialize(self)

    def destroy_branch(self):
        """See BzrDir.destroy_branch."""
        raise errors.UnsupportedOperation(self.destroy_branch, self)

    def create_repository(self, shared=False):
        """See BzrDir.create_repository."""
        if shared:
            raise errors.IncompatibleFormat('shared repository', self._format)
        return self.open_repository()

    def destroy_repository(self):
        """See BzrDir.destroy_repository."""
        raise errors.UnsupportedOperation(self.destroy_repository, self)

    def create_workingtree(self, revision_id=None, from_branch=None,
                           accelerator_tree=None, hardlink=False):
        """See BzrDir.create_workingtree."""
        # The workingtree is sometimes created when the bzrdir is created,
        # but not when cloning.

        # this looks buggy but is not -really-
        # because this format creates the workingtree when the bzrdir is
        # created
        # clone and sprout will have set the revision_id
        # and that will have set it for us, its only
        # specific uses of create_workingtree in isolation
        # that can do wonky stuff here, and that only
        # happens for creating checkouts, which cannot be
        # done on this format anyway. So - acceptable wart.
        try:
            result = self.open_workingtree(recommend_upgrade=False)
        except errors.NoSuchFile:
            result = self._init_workingtree()
        if revision_id is not None:
            if revision_id == _mod_revision.NULL_REVISION:
                result.set_parent_ids([])
            else:
                result.set_parent_ids([revision_id])
        return result

    def _init_workingtree(self):
        from bzrlib.workingtree import WorkingTreeFormat2
        try:
            return WorkingTreeFormat2().initialize(self)
        except errors.NotLocalUrl:
            # Even though we can't access the working tree, we need to
            # create its control files.
            return WorkingTreeFormat2()._stub_initialize_on_transport(
                self.transport, self._control_files._file_mode)

    def destroy_workingtree(self):
        """See BzrDir.destroy_workingtree."""
        raise errors.UnsupportedOperation(self.destroy_workingtree, self)

    def destroy_workingtree_metadata(self):
        """See BzrDir.destroy_workingtree_metadata."""
        raise errors.UnsupportedOperation(self.destroy_workingtree_metadata,
                                          self)

    def get_branch_transport(self, branch_format):
        """See BzrDir.get_branch_transport()."""
        if branch_format is None:
            return self.transport
        try:
            branch_format.get_format_string()
        except NotImplementedError:
            return self.transport
        raise errors.IncompatibleFormat(branch_format, self._format)

    def get_repository_transport(self, repository_format):
        """See BzrDir.get_repository_transport()."""
        if repository_format is None:
            return self.transport
        try:
            repository_format.get_format_string()
        except NotImplementedError:
            return self.transport
        raise errors.IncompatibleFormat(repository_format, self._format)

    def get_workingtree_transport(self, workingtree_format):
        """See BzrDir.get_workingtree_transport()."""
        if workingtree_format is None:
            return self.transport
        try:
            workingtree_format.get_format_string()
        except NotImplementedError:
            return self.transport
        raise errors.IncompatibleFormat(workingtree_format, self._format)

    def needs_format_conversion(self, format=None):
        """See BzrDir.needs_format_conversion()."""
        # if the format is not the same as the system default,
        # an upgrade is needed.
        if format is None:
            symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
                % 'needs_format_conversion(format=None)')
            format = BzrDirFormat.get_default_format()
        return not isinstance(self._format, format.__class__)

    def open_branch(self, unsupported=False, ignore_fallbacks=False):
        """See BzrDir.open_branch."""
        from bzrlib.branch import BzrBranchFormat4
        format = BzrBranchFormat4()
        self._check_supported(format, unsupported)
        return format.open(self, _found=True)

    def sprout(self, url, revision_id=None, force_new_repo=False,
               possible_transports=None, accelerator_tree=None,
               hardlink=False, stacked=False, create_tree_if_local=True,
               source_branch=None):
        """See BzrDir.sprout()."""
        if source_branch is not None:
            my_branch = self.open_branch()
            if source_branch.base != my_branch.base:
                raise AssertionError(
                    "source branch %r is not within %r with branch %r" %
                    (source_branch, self, my_branch))
        if stacked:
            raise errors.UnstackableBranchFormat(
                self._format, self.root_transport.base)
        if not create_tree_if_local:
            raise errors.MustHaveWorkingTree(
                self._format, self.root_transport.base)
        from bzrlib.workingtree import WorkingTreeFormat2
        self._make_tail(url)
        result = self._format._initialize_for_clone(url)
        try:
            self.open_repository().clone(result, revision_id=revision_id)
        except errors.NoRepositoryPresent:
            pass
        try:
            self.open_branch().sprout(result, revision_id=revision_id)
        except errors.NotBranchError:
            pass

        # we always want a working tree
        WorkingTreeFormat2().initialize(result,
                                        accelerator_tree=accelerator_tree,
                                        hardlink=hardlink)
        return result


class BzrDir4(BzrDirPreSplitOut):
    """A .bzr version 4 control object.

    This is a deprecated format and may be removed after sept 2006.
    """

    def create_repository(self, shared=False):
        """See BzrDir.create_repository."""
        return self._format.repository_format.initialize(self, shared)

    def needs_format_conversion(self, format=None):
        """Format 4 dirs are always in need of conversion."""
        if format is None:
            symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
                % 'needs_format_conversion(format=None)')
        return True

    def open_repository(self):
        """See BzrDir.open_repository."""
        from bzrlib.repofmt.weaverepo import RepositoryFormat4
        return RepositoryFormat4().open(self, _found=True)


class BzrDir5(BzrDirPreSplitOut):
    """A .bzr version 5 control object.

    This is a deprecated format and may be removed after sept 2006.
    """

    def open_repository(self):
        """See BzrDir.open_repository."""
        from bzrlib.repofmt.weaverepo import RepositoryFormat5
        return RepositoryFormat5().open(self, _found=True)

    def open_workingtree(self, _unsupported=False,
            recommend_upgrade=True):
        """See BzrDir.create_workingtree."""
        from bzrlib.workingtree import WorkingTreeFormat2
        wt_format = WorkingTreeFormat2()
        # we don't warn here about upgrades; that ought to be handled for the
        # bzrdir as a whole
        return wt_format.open(self, _found=True)


class BzrDir6(BzrDirPreSplitOut):
    """A .bzr version 6 control object.

    This is a deprecated format and may be removed after sept 2006.
    """

    def open_repository(self):
        """See BzrDir.open_repository."""
        from bzrlib.repofmt.weaverepo import RepositoryFormat6
        return RepositoryFormat6().open(self, _found=True)

    def open_workingtree(self, _unsupported=False,
        recommend_upgrade=True):
        """See BzrDir.create_workingtree."""
        # we don't warn here about upgrades; that ought to be handled for the
        # bzrdir as a whole
        from bzrlib.workingtree import WorkingTreeFormat2
        return WorkingTreeFormat2().open(self, _found=True)


class BzrDirMeta1(BzrDir):
    """A .bzr meta version 1 control object.

    This is the first control object where the
    individual aspects are really split out: there are separate repository,
    workingtree and branch subdirectories and any subset of the three can be
    present within a BzrDir.
    """

    def can_convert_format(self):
        """See BzrDir.can_convert_format()."""
        return True

    def create_branch(self):
        """See BzrDir.create_branch."""
        return self._format.get_branch_format().initialize(self)

    def destroy_branch(self):
        """See BzrDir.create_branch."""
        self.transport.delete_tree('branch')

    def create_repository(self, shared=False):
        """See BzrDir.create_repository."""
        return self._format.repository_format.initialize(self, shared)

    def destroy_repository(self):
        """See BzrDir.destroy_repository."""
        self.transport.delete_tree('repository')

    def create_workingtree(self, revision_id=None, from_branch=None,
                           accelerator_tree=None, hardlink=False):
        """See BzrDir.create_workingtree."""
        return self._format.workingtree_format.initialize(
            self, revision_id, from_branch=from_branch,
            accelerator_tree=accelerator_tree, hardlink=hardlink)

    def destroy_workingtree(self):
        """See BzrDir.destroy_workingtree."""
        wt = self.open_workingtree(recommend_upgrade=False)
        repository = wt.branch.repository
        empty = repository.revision_tree(_mod_revision.NULL_REVISION)
        wt.revert(old_tree=empty)
        self.destroy_workingtree_metadata()

    def destroy_workingtree_metadata(self):
        self.transport.delete_tree('checkout')

    def find_branch_format(self):
        """Find the branch 'format' for this bzrdir.

        This might be a synthetic object for e.g. RemoteBranch and SVN.
        """
        from bzrlib.branch import BranchFormat
        return BranchFormat.find_format(self)

    def _get_mkdir_mode(self):
        """Figure out the mode to use when creating a bzrdir subdir."""
        temp_control = lockable_files.LockableFiles(self.transport, '',
                                     lockable_files.TransportLock)
        return temp_control._dir_mode

    def get_branch_reference(self):
        """See BzrDir.get_branch_reference()."""
        from bzrlib.branch import BranchFormat
        format = BranchFormat.find_format(self)
        return format.get_reference(self)

    def get_branch_transport(self, branch_format):
        """See BzrDir.get_branch_transport()."""
        if branch_format is None:
            return self.transport.clone('branch')
        try:
            branch_format.get_format_string()
        except NotImplementedError:
            raise errors.IncompatibleFormat(branch_format, self._format)
        try:
            self.transport.mkdir('branch', mode=self._get_mkdir_mode())
        except errors.FileExists:
            pass
        return self.transport.clone('branch')

    def get_repository_transport(self, repository_format):
        """See BzrDir.get_repository_transport()."""
        if repository_format is None:
            return self.transport.clone('repository')
        try:
            repository_format.get_format_string()
        except NotImplementedError:
            raise errors.IncompatibleFormat(repository_format, self._format)
        try:
            self.transport.mkdir('repository', mode=self._get_mkdir_mode())
        except errors.FileExists:
            pass
        return self.transport.clone('repository')

    def get_workingtree_transport(self, workingtree_format):
        """See BzrDir.get_workingtree_transport()."""
        if workingtree_format is None:
            return self.transport.clone('checkout')
        try:
            workingtree_format.get_format_string()
        except NotImplementedError:
            raise errors.IncompatibleFormat(workingtree_format, self._format)
        try:
            self.transport.mkdir('checkout', mode=self._get_mkdir_mode())
        except errors.FileExists:
            pass
        return self.transport.clone('checkout')

    def needs_format_conversion(self, format=None):
        """See BzrDir.needs_format_conversion()."""
        if format is None:
            symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
                % 'needs_format_conversion(format=None)')
        if format is None:
            format = BzrDirFormat.get_default_format()
        if not isinstance(self._format, format.__class__):
            # it is not a meta dir format, conversion is needed.
            return True
        # we might want to push this down to the repository?
        try:
            if not isinstance(self.open_repository()._format,
                              format.repository_format.__class__):
                # the repository needs an upgrade.
                return True
        except errors.NoRepositoryPresent:
            pass
        try:
            if not isinstance(self.open_branch()._format,
                              format.get_branch_format().__class__):
                # the branch needs an upgrade.
                return True
        except errors.NotBranchError:
            pass
        try:
            my_wt = self.open_workingtree(recommend_upgrade=False)
            if not isinstance(my_wt._format,
                              format.workingtree_format.__class__):
                # the workingtree needs an upgrade.
                return True
        except (errors.NoWorkingTree, errors.NotLocalUrl):
            pass
        return False

    def open_branch(self, unsupported=False, ignore_fallbacks=False):
        """See BzrDir.open_branch."""
        format = self.find_branch_format()
        self._check_supported(format, unsupported)
        return format.open(self, _found=True, ignore_fallbacks=ignore_fallbacks)

    def open_repository(self, unsupported=False):
        """See BzrDir.open_repository."""
        from bzrlib.repository import RepositoryFormat
        format = RepositoryFormat.find_format(self)
        self._check_supported(format, unsupported)
        return format.open(self, _found=True)

    def open_workingtree(self, unsupported=False,
            recommend_upgrade=True):
        """See BzrDir.open_workingtree."""
        from bzrlib.workingtree import WorkingTreeFormat
        format = WorkingTreeFormat.find_format(self)
        self._check_supported(format, unsupported,
            recommend_upgrade,
            basedir=self.root_transport.base)
        return format.open(self, _found=True)

    def _get_config(self):
        return config.TransportConfig(self.transport, 'control.conf')


class BzrDirFormat(object):
    """An encapsulation of the initialization and open routines for a format.

    Formats provide three things:
     * An initialization routine,
     * a format string,
     * an open routine.

    Formats are placed in a dict by their format string for reference
    during bzrdir opening. These should be subclasses of BzrDirFormat
    for consistency.

    Once a format is deprecated, just deprecate the initialize and open
    methods on the format class. Do not deprecate the object, as the
    object will be created every system load.
    """

    _default_format = None
    """The default format used for new .bzr dirs."""

    _formats = {}
    """The known formats."""

    _control_formats = []
    """The registered control formats - .bzr, ....

    This is a list of BzrDirFormat objects.
    """

    _control_server_formats = []
    """The registered control server formats, e.g. RemoteBzrDirs.

    This is a list of BzrDirFormat objects.
    """

    _lock_file_name = 'branch-lock'

    # _lock_class must be set in subclasses to the lock type, typ.
    # TransportLock or LockDir

    @classmethod
    def find_format(klass, transport, _server_formats=True):
        """Return the format present at transport."""
        if _server_formats:
            formats = klass._control_server_formats + klass._control_formats
        else:
            formats = klass._control_formats
        for format in formats:
            try:
                return format.probe_transport(transport)
            except errors.NotBranchError:
                # this format does not find a control dir here.
                pass
        raise errors.NotBranchError(path=transport.base)

    @classmethod
    def probe_transport(klass, transport):
        """Return the .bzrdir style format present in a directory."""
        try:
            format_string = transport.get(".bzr/branch-format").read()
        except errors.NoSuchFile:
            raise errors.NotBranchError(path=transport.base)

        try:
            return klass._formats[format_string]
        except KeyError:
            raise errors.UnknownFormatError(format=format_string, kind='bzrdir')

    @classmethod
    def get_default_format(klass):
        """Return the current default format."""
        return klass._default_format

    def get_format_string(self):
        """Return the ASCII format string that identifies this format."""
        raise NotImplementedError(self.get_format_string)

    def get_format_description(self):
        """Return the short description for this format."""
        raise NotImplementedError(self.get_format_description)

    def get_converter(self, format=None):
        """Return the converter to use to convert bzrdirs needing converts.

        This returns a bzrlib.bzrdir.Converter object.

        This should return the best upgrader to step this format towards the
        current default format. In the case of plugins we can/should provide
        some means for them to extend the range of returnable converters.

        :param format: Optional format to override the default format of the
                       library.
        """
        raise NotImplementedError(self.get_converter)

    def initialize(self, url, possible_transports=None):
        """Create a bzr control dir at this url and return an opened copy.

        While not deprecated, this method is very specific and its use will
        lead to many round trips to setup a working environment. See
        initialize_on_transport_ex for a [nearly] all-in-one method.

        Subclasses should typically override initialize_on_transport
        instead of this method.
        """
        return self.initialize_on_transport(get_transport(url,
                                                          possible_transports))

    def initialize_on_transport(self, transport):
        """Initialize a new bzrdir in the base directory of a Transport."""
        try:
            # can we hand off the request to the smart server rather than using
            # vfs calls?
            client_medium = transport.get_smart_medium()
        except errors.NoSmartMedium:
            return self._initialize_on_transport_vfs(transport)
        else:
            # Current RPC's only know how to create bzr metadir1 instances, so
            # we still delegate to vfs methods if the requested format is not a
            # metadir1
            if type(self) != BzrDirMetaFormat1:
                return self._initialize_on_transport_vfs(transport)
            remote_format = RemoteBzrDirFormat()
            self._supply_sub_formats_to(remote_format)
            return remote_format.initialize_on_transport(transport)

    def initialize_on_transport_ex(self, transport, use_existing_dir=False,
        create_prefix=False, force_new_repo=False, stacked_on=None,
        stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
        shared_repo=False, vfs_only=False):
        """Create this format on transport.

        The directory to initialize will be created.

        :param force_new_repo: Do not use a shared repository for the target,
                               even if one is available.
        :param create_prefix: Create any missing directories leading up to
            to_transport.
        :param use_existing_dir: Use an existing directory if one exists.
        :param stacked_on: A url to stack any created branch on, None to follow
            any target stacking policy.
        :param stack_on_pwd: If stack_on is relative, the location it is
            relative to.
        :param repo_format_name: If non-None, a repository will be
            made-or-found. Should none be found, or if force_new_repo is True
            the repo_format_name is used to select the format of repository to
            create.
        :param make_working_trees: Control the setting of make_working_trees
            for a new shared repository when one is made. None to use whatever
            default the format has.
        :param shared_repo: Control whether made repositories are shared or
            not.
        :param vfs_only: If True do not attempt to use a smart server
        :return: repo, bzrdir, require_stacking, repository_policy. repo is
            None if none was created or found, bzrdir is always valid.
            require_stacking is the result of examining the stacked_on
            parameter and any stacking policy found for the target.
        """
        if not vfs_only:
            # Try to hand off to a smart server 
            try:
                client_medium = transport.get_smart_medium()
            except errors.NoSmartMedium:
                pass
            else:
                # TODO: lookup the local format from a server hint.
                remote_dir_format = RemoteBzrDirFormat()
                remote_dir_format._network_name = self.network_name()
                self._supply_sub_formats_to(remote_dir_format)
                return remote_dir_format.initialize_on_transport_ex(transport,
                    use_existing_dir=use_existing_dir, create_prefix=create_prefix,
                    force_new_repo=force_new_repo, stacked_on=stacked_on,
                    stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
                    make_working_trees=make_working_trees, shared_repo=shared_repo)
        # XXX: Refactor the create_prefix/no_create_prefix code into a
        #      common helper function
        # The destination may not exist - if so make it according to policy.
        def make_directory(transport):
            transport.mkdir('.')
            return transport
        def redirected(transport, e, redirection_notice):
            note(redirection_notice)
            return transport._redirected_to(e.source, e.target)
        try:
            transport = do_catching_redirections(make_directory, transport,
                redirected)
        except errors.FileExists:
            if not use_existing_dir:
                raise
        except errors.NoSuchFile:
            if not create_prefix:
                raise
            transport.create_prefix()

        require_stacking = (stacked_on is not None)
        # Now the target directory exists, but doesn't have a .bzr
        # directory. So we need to create it, along with any work to create
        # all of the dependent branches, etc.

        result = self.initialize_on_transport(transport)
        if repo_format_name:
            try:
                # use a custom format
                result._format.repository_format = \
                    repository.network_format_registry.get(repo_format_name)
            except AttributeError:
                # The format didn't permit it to be set.
                pass
            # A repository is desired, either in-place or shared.
            repository_policy = result.determine_repository_policy(
                force_new_repo, stacked_on, stack_on_pwd,
                require_stacking=require_stacking)
            result_repo, is_new_repo = repository_policy.acquire_repository(
                make_working_trees, shared_repo)
            if not require_stacking and repository_policy._require_stacking:
                require_stacking = True
                result._format.require_stacking()
            result_repo.lock_write()
        else:
            result_repo = None
            repository_policy = None
        return result_repo, result, require_stacking, repository_policy

    def _initialize_on_transport_vfs(self, transport):
        """Initialize a new bzrdir using VFS calls.

        :param transport: The transport to create the .bzr directory in.
        :return: A
        """
        # Since we are creating a .bzr directory, inherit the
        # mode from the root directory
        temp_control = lockable_files.LockableFiles(transport,
                            '', lockable_files.TransportLock)
        temp_control._transport.mkdir('.bzr',
                                      # FIXME: RBC 20060121 don't peek under
                                      # the covers
                                      mode=temp_control._dir_mode)
        if sys.platform == 'win32' and isinstance(transport, local.LocalTransport):
            win32utils.set_file_attr_hidden(transport._abspath('.bzr'))
        file_mode = temp_control._file_mode
        del temp_control
        bzrdir_transport = transport.clone('.bzr')
        utf8_files = [('README',
                       "This is a Bazaar control directory.\n"
                       "Do not change any files in this directory.\n"
                       "See http://bazaar-vcs.org/ for more information about Bazaar.\n"),
                      ('branch-format', self.get_format_string()),
                      ]
        # NB: no need to escape relative paths that are url safe.
        control_files = lockable_files.LockableFiles(bzrdir_transport,
            self._lock_file_name, self._lock_class)
        control_files.create_lock()
        control_files.lock_write()
        try:
            for (filename, content) in utf8_files:
                bzrdir_transport.put_bytes(filename, content,
                    mode=file_mode)
        finally:
            control_files.unlock()
        return self.open(transport, _found=True)

    def is_supported(self):
        """Is this format supported?

        Supported formats must be initializable and openable.
        Unsupported formats may not support initialization or committing or
        some other features depending on the reason for not being supported.
        """
        return True

    def network_name(self):
        """A simple byte string uniquely identifying this format for RPC calls.

        Bzr control formats use thir disk format string to identify the format
        over the wire. Its possible that other control formats have more
        complex detection requirements, so we permit them to use any unique and
        immutable string they desire.
        """
        raise NotImplementedError(self.network_name)

    def same_model(self, target_format):
        return (self.repository_format.rich_root_data ==
            target_format.rich_root_data)

    @classmethod
    def known_formats(klass):
        """Return all the known formats.

        Concrete formats should override _known_formats.
        """
        # There is double indirection here to make sure that control
        # formats used by more than one dir format will only be probed
        # once. This can otherwise be quite expensive for remote connections.
        result = set()
        for format in klass._control_formats:
            result.update(format._known_formats())
        return result

    @classmethod
    def _known_formats(klass):
        """Return the known format instances for this control format."""
        return set(klass._formats.values())

    def open(self, transport, _found=False):
        """Return an instance of this format for the dir transport points at.

        _found is a private parameter, do not use it.
        """
        if not _found:
            found_format = BzrDirFormat.find_format(transport)
            if not isinstance(found_format, self.__class__):
                raise AssertionError("%s was asked to open %s, but it seems to need "
                        "format %s"
                        % (self, transport, found_format))
            # Allow subclasses - use the found format.
            self._supply_sub_formats_to(found_format)
            return found_format._open(transport)
        return self._open(transport)

    def _open(self, transport):
        """Template method helper for opening BzrDirectories.

        This performs the actual open and any additional logic or parameter
        passing.
        """
        raise NotImplementedError(self._open)

    @classmethod
    def register_format(klass, format):
        klass._formats[format.get_format_string()] = format
        # bzr native formats have a network name of their format string.
        network_format_registry.register(format.get_format_string(), format.__class__)

    @classmethod
    def register_control_format(klass, format):
        """Register a format that does not use '.bzr' for its control dir.

        TODO: This should be pulled up into a 'ControlDirFormat' base class
        which BzrDirFormat can inherit from, and renamed to register_format
        there. It has been done without that for now for simplicity of
        implementation.
        """
        klass._control_formats.append(format)

    @classmethod
    def register_control_server_format(klass, format):
        """Register a control format for client-server environments.

        These formats will be tried before ones registered with
        register_control_format.  This gives implementations that decide to the
        chance to grab it before anything looks at the contents of the format
        file.
        """
        klass._control_server_formats.append(format)

    @classmethod
    def _set_default_format(klass, format):
        """Set default format (for testing behavior of defaults only)"""
        klass._default_format = format

    def __str__(self):
        # Trim the newline
        return self.get_format_description().rstrip()

    def _supply_sub_formats_to(self, other_format):
        """Give other_format the same values for sub formats as this has.

        This method is expected to be used when parameterising a
        RemoteBzrDirFormat instance with the parameters from a
        BzrDirMetaFormat1 instance.

        :param other_format: other_format is a format which should be
            compatible with whatever sub formats are supported by self.
        :return: None.
        """

    @classmethod
    def unregister_format(klass, format):
        del klass._formats[format.get_format_string()]

    @classmethod
    def unregister_control_format(klass, format):
        klass._control_formats.remove(format)


class BzrDirFormat4(BzrDirFormat):
    """Bzr dir format 4.

    This format is a combined format for working tree, branch and repository.
    It has:
     - Format 1 working trees [always]
     - Format 4 branches [always]
     - Format 4 repositories [always]

    This format is deprecated: it indexes texts using a text it which is
    removed in format 5; write support for this format has been removed.
    """

    _lock_class = lockable_files.TransportLock

    def get_format_string(self):
        """See BzrDirFormat.get_format_string()."""
        return "Bazaar-NG branch, format 0.0.4\n"

    def get_format_description(self):
        """See BzrDirFormat.get_format_description()."""
        return "All-in-one format 4"

    def get_converter(self, format=None):
        """See BzrDirFormat.get_converter()."""
        # there is one and only one upgrade path here.
        return ConvertBzrDir4To5()

    def initialize_on_transport(self, transport):
        """Format 4 branches cannot be created."""
        raise errors.UninitializableFormat(self)

    def is_supported(self):
        """Format 4 is not supported.

        It is not supported because the model changed from 4 to 5 and the
        conversion logic is expensive - so doing it on the fly was not
        feasible.
        """
        return False

    def network_name(self):
        return self.get_format_string()

    def _open(self, transport):
        """See BzrDirFormat._open."""
        return BzrDir4(transport, self)

    def __return_repository_format(self):
        """Circular import protection."""
        from bzrlib.repofmt.weaverepo import RepositoryFormat4
        return RepositoryFormat4()
    repository_format = property(__return_repository_format)


class BzrDirFormatAllInOne(BzrDirFormat):
    """Common class for formats before meta-dirs."""

    def initialize_on_transport_ex(self, transport, use_existing_dir=False,
        create_prefix=False, force_new_repo=False, stacked_on=None,
        stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
        shared_repo=False):
        """See BzrDirFormat.initialize_on_transport_ex."""
        require_stacking = (stacked_on is not None)
        # Format 5 cannot stack, but we've been asked to - actually init
        # a Meta1Dir
        if require_stacking:
            format = BzrDirMetaFormat1()
            return format.initialize_on_transport_ex(transport,
                use_existing_dir=use_existing_dir, create_prefix=create_prefix,
                force_new_repo=force_new_repo, stacked_on=stacked_on,
                stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
                make_working_trees=make_working_trees, shared_repo=shared_repo)
        return BzrDirFormat.initialize_on_transport_ex(self, transport,
            use_existing_dir=use_existing_dir, create_prefix=create_prefix,
            force_new_repo=force_new_repo, stacked_on=stacked_on,
            stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
            make_working_trees=make_working_trees, shared_repo=shared_repo)


class BzrDirFormat5(BzrDirFormatAllInOne):
    """Bzr control format 5.

    This format is a combined format for working tree, branch and repository.
    It has:
     - Format 2 working trees [always]
     - Format 4 branches [always]
     - Format 5 repositories [always]
       Unhashed stores in the repository.
    """

    _lock_class = lockable_files.TransportLock

    def get_format_string(self):
        """See BzrDirFormat.get_format_string()."""
        return "Bazaar-NG branch, format 5\n"

    def get_branch_format(self):
        from bzrlib import branch
        return branch.BzrBranchFormat4()

    def get_format_description(self):
        """See BzrDirFormat.get_format_description()."""
        return "All-in-one format 5"

    def get_converter(self, format=None):
        """See BzrDirFormat.get_converter()."""
        # there is one and only one upgrade path here.
        return ConvertBzrDir5To6()

    def _initialize_for_clone(self, url):
        return self.initialize_on_transport(get_transport(url), _cloning=True)

    def initialize_on_transport(self, transport, _cloning=False):
        """Format 5 dirs always have working tree, branch and repository.

        Except when they are being cloned.
        """
        from bzrlib.branch import BzrBranchFormat4
        from bzrlib.repofmt.weaverepo import RepositoryFormat5
        result = (super(BzrDirFormat5, self).initialize_on_transport(transport))
        RepositoryFormat5().initialize(result, _internal=True)
        if not _cloning:
            branch = BzrBranchFormat4().initialize(result)
            result._init_workingtree()
        return result

    def network_name(self):
        return self.get_format_string()

    def _open(self, transport):
        """See BzrDirFormat._open."""
        return BzrDir5(transport, self)

    def __return_repository_format(self):
        """Circular import protection."""
        from bzrlib.repofmt.weaverepo import RepositoryFormat5
        return RepositoryFormat5()
    repository_format = property(__return_repository_format)


class BzrDirFormat6(BzrDirFormatAllInOne):
    """Bzr control format 6.

    This format is a combined format for working tree, branch and repository.
    It has:
     - Format 2 working trees [always]
     - Format 4 branches [always]
     - Format 6 repositories [always]
    """

    _lock_class = lockable_files.TransportLock

    def get_format_string(self):
        """See BzrDirFormat.get_format_string()."""
        return "Bazaar-NG branch, format 6\n"

    def get_format_description(self):
        """See BzrDirFormat.get_format_description()."""
        return "All-in-one format 6"

    def get_branch_format(self):
        from bzrlib import branch
        return branch.BzrBranchFormat4()

    def get_converter(self, format=None):
        """See BzrDirFormat.get_converter()."""
        # there is one and only one upgrade path here.
        return ConvertBzrDir6ToMeta()

    def _initialize_for_clone(self, url):
        return self.initialize_on_transport(get_transport(url), _cloning=True)

    def initialize_on_transport(self, transport, _cloning=False):
        """Format 6 dirs always have working tree, branch and repository.

        Except when they are being cloned.
        """
        from bzrlib.branch import BzrBranchFormat4
        from bzrlib.repofmt.weaverepo import RepositoryFormat6
        result = super(BzrDirFormat6, self).initialize_on_transport(transport)
        RepositoryFormat6().initialize(result, _internal=True)
        if not _cloning:
            branch = BzrBranchFormat4().initialize(result)
            result._init_workingtree()
        return result

    def network_name(self):
        return self.get_format_string()

    def _open(self, transport):
        """See BzrDirFormat._open."""
        return BzrDir6(transport, self)

    def __return_repository_format(self):
        """Circular import protection."""
        from bzrlib.repofmt.weaverepo import RepositoryFormat6
        return RepositoryFormat6()
    repository_format = property(__return_repository_format)


class BzrDirMetaFormat1(BzrDirFormat):
    """Bzr meta control format 1

    This is the first format with split out working tree, branch and repository
    disk storage.
    It has:
     - Format 3 working trees [optional]
     - Format 5 branches [optional]
     - Format 7 repositories [optional]
    """

    _lock_class = lockdir.LockDir

    def __init__(self):
        self._workingtree_format = None
        self._branch_format = None
        self._repository_format = None

    def __eq__(self, other):
        if other.__class__ is not self.__class__:
            return False
        if other.repository_format != self.repository_format:
            return False
        if other.workingtree_format != self.workingtree_format:
            return False
        return True

    def __ne__(self, other):
        return not self == other

    def get_branch_format(self):
        if self._branch_format is None:
            from bzrlib.branch import BranchFormat
            self._branch_format = BranchFormat.get_default_format()
        return self._branch_format

    def set_branch_format(self, format):
        self._branch_format = format

    def require_stacking(self, stack_on=None, possible_transports=None):
        """We have a request to stack, try to ensure the formats support it.

        :param stack_on: If supplied, it is the URL to a branch that we want to
            stack on. Check to see if that format supports stacking before
            forcing an upgrade.
        """
        # Stacking is desired. requested by the target, but does the place it
        # points at support stacking? If it doesn't then we should
        # not implicitly upgrade. We check this here.
        new_repo_format = None
        new_branch_format = None

        # a bit of state for get_target_branch so that we don't try to open it
        # 2 times, for both repo *and* branch
        target = [None, False, None] # target_branch, checked, upgrade anyway
        def get_target_branch():
            if target[1]:
                # We've checked, don't check again
                return target
            if stack_on is None:
                # No target format, that means we want to force upgrading
                target[:] = [None, True, True]
                return target
            try:
                target_dir = BzrDir.open(stack_on,
                    possible_transports=possible_transports)
            except errors.NotBranchError:
                # Nothing there, don't change formats
                target[:] = [None, True, False]
                return target
            except errors.JailBreak:
                # JailBreak, JFDI and upgrade anyway
                target[:] = [None, True, True]
                return target
            try:
                target_branch = target_dir.open_branch()
            except errors.NotBranchError:
                # No branch, don't upgrade formats
                target[:] = [None, True, False]
                return target
            target[:] = [target_branch, True, False]
            return target

        if not (self.repository_format.supports_external_lookups):
            # We need to upgrade the Repository.
            target_branch, _, do_upgrade = get_target_branch()
            if target_branch is None:
                # We don't have a target branch, should we upgrade anyway?
                if do_upgrade:
                    # stack_on is inaccessible, JFDI.
                    # TODO: bad monkey, hard-coded formats...
                    if self.repository_format.rich_root_data:
                        new_repo_format = pack_repo.RepositoryFormatKnitPack5RichRoot()
                    else:
                        new_repo_format = pack_repo.RepositoryFormatKnitPack5()
            else:
                # If the target already supports stacking, then we know the
                # project is already able to use stacking, so auto-upgrade
                # for them
                new_repo_format = target_branch.repository._format
                if not new_repo_format.supports_external_lookups:
                    # target doesn't, source doesn't, so don't auto upgrade
                    # repo
                    new_repo_format = None
            if new_repo_format is not None:
                self.repository_format = new_repo_format
                note('Source repository format does not support stacking,'
                     ' using format:\n  %s',
                     new_repo_format.get_format_description())

        if not self.get_branch_format().supports_stacking():
            # We just checked the repo, now lets check if we need to
            # upgrade the branch format
            target_branch, _, do_upgrade = get_target_branch()
            if target_branch is None:
                if do_upgrade:
                    # TODO: bad monkey, hard-coded formats...
                    new_branch_format = branch.BzrBranchFormat7()
            else:
                new_branch_format = target_branch._format
                if not new_branch_format.supports_stacking():
                    new_branch_format = None
            if new_branch_format is not None:
                # Does support stacking, use its format.
                self.set_branch_format(new_branch_format)
                note('Source branch format does not support stacking,'
                     ' using format:\n  %s',
                     new_branch_format.get_format_description())

    def get_converter(self, format=None):
        """See BzrDirFormat.get_converter()."""
        if format is None:
            format = BzrDirFormat.get_default_format()
        if not isinstance(self, format.__class__):
            # converting away from metadir is not implemented
            raise NotImplementedError(self.get_converter)
        return ConvertMetaToMeta(format)

    def get_format_string(self):
        """See BzrDirFormat.get_format_string()."""
        return "Bazaar-NG meta directory, format 1\n"

    def get_format_description(self):
        """See BzrDirFormat.get_format_description()."""
        return "Meta directory format 1"

    def network_name(self):
        return self.get_format_string()

    def _open(self, transport):
        """See BzrDirFormat._open."""
        # Create a new format instance because otherwise initialisation of new
        # metadirs share the global default format object leading to alias
        # problems.
        format = BzrDirMetaFormat1()
        self._supply_sub_formats_to(format)
        return BzrDirMeta1(transport, format)

    def __return_repository_format(self):
        """Circular import protection."""
        if self._repository_format:
            return self._repository_format
        from bzrlib.repository import RepositoryFormat
        return RepositoryFormat.get_default_format()

    def _set_repository_format(self, value):
        """Allow changing the repository format for metadir formats."""
        self._repository_format = value

    repository_format = property(__return_repository_format,
        _set_repository_format)

    def _supply_sub_formats_to(self, other_format):
        """Give other_format the same values for sub formats as this has.

        This method is expected to be used when parameterising a
        RemoteBzrDirFormat instance with the parameters from a
        BzrDirMetaFormat1 instance.

        :param other_format: other_format is a format which should be
            compatible with whatever sub formats are supported by self.
        :return: None.
        """
        if getattr(self, '_repository_format', None) is not None:
            other_format.repository_format = self.repository_format
        if self._branch_format is not None:
            other_format._branch_format = self._branch_format
        if self._workingtree_format is not None:
            other_format.workingtree_format = self.workingtree_format

    def __get_workingtree_format(self):
        if self._workingtree_format is None:
            from bzrlib.workingtree import WorkingTreeFormat
            self._workingtree_format = WorkingTreeFormat.get_default_format()
        return self._workingtree_format

    def __set_workingtree_format(self, wt_format):
        self._workingtree_format = wt_format

    workingtree_format = property(__get_workingtree_format,
                                  __set_workingtree_format)


network_format_registry = registry.FormatRegistry()
"""Registry of formats indexed by their network name.

The network name for a BzrDirFormat is an identifier that can be used when
referring to formats with smart server operations. See
BzrDirFormat.network_name() for more detail.
"""


# Register bzr control format
BzrDirFormat.register_control_format(BzrDirFormat)

# Register bzr formats
BzrDirFormat.register_format(BzrDirFormat4())
BzrDirFormat.register_format(BzrDirFormat5())
BzrDirFormat.register_format(BzrDirFormat6())
__default_format = BzrDirMetaFormat1()
BzrDirFormat.register_format(__default_format)
BzrDirFormat._default_format = __default_format


class Converter(object):
    """Converts a disk format object from one format to another."""

    def convert(self, to_convert, pb):
        """Perform the conversion of to_convert, giving feedback via pb.

        :param to_convert: The disk object to convert.
        :param pb: a progress bar to use for progress information.
        """

    def step(self, message):
        """Update the pb by a step."""
        self.count +=1
        self.pb.update(message, self.count, self.total)


class ConvertBzrDir4To5(Converter):
    """Converts format 4 bzr dirs to format 5."""

    def __init__(self):
        super(ConvertBzrDir4To5, self).__init__()
        self.converted_revs = set()
        self.absent_revisions = set()
        self.text_count = 0
        self.revisions = {}

    def convert(self, to_convert, pb):
        """See Converter.convert()."""
        self.bzrdir = to_convert
        self.pb = pb
        self.pb.note('starting upgrade from format 4 to 5')
        if isinstance(self.bzrdir.transport, local.LocalTransport):
            self.bzrdir.get_workingtree_transport(None).delete('stat-cache')
        self._convert_to_weaves()
        return BzrDir.open(self.bzrdir.root_transport.base)

    def _convert_to_weaves(self):
        self.pb.note('note: upgrade may be faster if all store files are ungzipped first')
        try:
            # TODO permissions
            stat = self.bzrdir.transport.stat('weaves')
            if not S_ISDIR(stat.st_mode):
                self.bzrdir.transport.delete('weaves')
                self.bzrdir.transport.mkdir('weaves')
        except errors.NoSuchFile:
            self.bzrdir.transport.mkdir('weaves')
        # deliberately not a WeaveFile as we want to build it up slowly.
        self.inv_weave = Weave('inventory')
        # holds in-memory weaves for all files
        self.text_weaves = {}
        self.bzrdir.transport.delete('branch-format')
        self.branch = self.bzrdir.open_branch()
        self._convert_working_inv()
        rev_history = self.branch.revision_history()
        # to_read is a stack holding the revisions we still need to process;
        # appending to it adds new highest-priority revisions
        self.known_revisions = set(rev_history)
        self.to_read = rev_history[-1:]
        while self.to_read:
            rev_id = self.to_read.pop()
            if (rev_id not in self.revisions
                and rev_id not in self.absent_revisions):
                self._load_one_rev(rev_id)
        self.pb.clear()
        to_import = self._make_order()
        for i, rev_id in enumerate(to_import):
            self.pb.update('converting revision', i, len(to_import))
            self._convert_one_rev(rev_id)
        self.pb.clear()
        self._write_all_weaves()
        self._write_all_revs()
        self.pb.note('upgraded to weaves:')
        self.pb.note('  %6d revisions and inventories', len(self.revisions))
        self.pb.note('  %6d revisions not present', len(self.absent_revisions))
        self.pb.note('  %6d texts', self.text_count)
        self._cleanup_spare_files_after_format4()
        self.branch._transport.put_bytes(
            'branch-format',
            BzrDirFormat5().get_format_string(),
            mode=self.bzrdir._get_file_mode())

    def _cleanup_spare_files_after_format4(self):
        # FIXME working tree upgrade foo.
        for n in 'merged-patches', 'pending-merged-patches':
            try:
                ## assert os.path.getsize(p) == 0
                self.bzrdir.transport.delete(n)
            except errors.NoSuchFile:
                pass
        self.bzrdir.transport.delete_tree('inventory-store')
        self.bzrdir.transport.delete_tree('text-store')

    def _convert_working_inv(self):
        inv = xml4.serializer_v4.read_inventory(
                self.branch._transport.get('inventory'))
        new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv, working=True)
        self.branch._transport.put_bytes('inventory', new_inv_xml,
            mode=self.bzrdir._get_file_mode())

    def _write_all_weaves(self):
        controlweaves = WeaveStore(self.bzrdir.transport, prefixed=False)
        weave_transport = self.bzrdir.transport.clone('weaves')
        weaves = WeaveStore(weave_transport, prefixed=False)
        transaction = WriteTransaction()

        try:
            i = 0
            for file_id, file_weave in self.text_weaves.items():
                self.pb.update('writing weave', i, len(self.text_weaves))
                weaves._put_weave(file_id, file_weave, transaction)
                i += 1
            self.pb.update('inventory', 0, 1)
            controlweaves._put_weave('inventory', self.inv_weave, transaction)
            self.pb.update('inventory', 1, 1)
        finally:
            self.pb.clear()

    def _write_all_revs(self):
        """Write all revisions out in new form."""
        self.bzrdir.transport.delete_tree('revision-store')
        self.bzrdir.transport.mkdir('revision-store')
        revision_transport = self.bzrdir.transport.clone('revision-store')
        # TODO permissions
        from bzrlib.xml5 import serializer_v5
        from bzrlib.repofmt.weaverepo import RevisionTextStore
        revision_store = RevisionTextStore(revision_transport,
            serializer_v5, False, versionedfile.PrefixMapper(),
            lambda:True, lambda:True)
        try:
            for i, rev_id in enumerate(self.converted_revs):
                self.pb.update('write revision', i, len(self.converted_revs))
                text = serializer_v5.write_revision_to_string(
                    self.revisions[rev_id])
                key = (rev_id,)
                revision_store.add_lines(key, None, osutils.split_lines(text))
        finally:
            self.pb.clear()

    def _load_one_rev(self, rev_id):
        """Load a revision object into memory.

        Any parents not either loaded or abandoned get queued to be
        loaded."""
        self.pb.update('loading revision',
                       len(self.revisions),
                       len(self.known_revisions))
        if not self.branch.repository.has_revision(rev_id):
            self.pb.clear()
            self.pb.note('revision {%s} not present in branch; '
                         'will be converted as a ghost',
                         rev_id)
            self.absent_revisions.add(rev_id)
        else:
            rev = self.branch.repository.get_revision(rev_id)
            for parent_id in rev.parent_ids:
                self.known_revisions.add(parent_id)
                self.to_read.append(parent_id)
            self.revisions[rev_id] = rev

    def _load_old_inventory(self, rev_id):
        old_inv_xml = self.branch.repository.inventory_store.get(rev_id).read()
        inv = xml4.serializer_v4.read_inventory_from_string(old_inv_xml)
        inv.revision_id = rev_id
        rev = self.revisions[rev_id]
        return inv

    def _load_updated_inventory(self, rev_id):
        inv_xml = self.inv_weave.get_text(rev_id)
        inv = xml5.serializer_v5.read_inventory_from_string(inv_xml, rev_id)
        return inv

    def _convert_one_rev(self, rev_id):
        """Convert revision and all referenced objects to new format."""
        rev = self.revisions[rev_id]
        inv = self._load_old_inventory(rev_id)
        present_parents = [p for p in rev.parent_ids
                           if p not in self.absent_revisions]
        self._convert_revision_contents(rev, inv, present_parents)
        self._store_new_inv(rev, inv, present_parents)
        self.converted_revs.add(rev_id)

    def _store_new_inv(self, rev, inv, present_parents):
        new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv)
        new_inv_sha1 = sha_string(new_inv_xml)
        self.inv_weave.add_lines(rev.revision_id,
                                 present_parents,
                                 new_inv_xml.splitlines(True))
        rev.inventory_sha1 = new_inv_sha1

    def _convert_revision_contents(self, rev, inv, present_parents):
        """Convert all the files within a revision.

        Also upgrade the inventory to refer to the text revision ids."""
        rev_id = rev.revision_id
        mutter('converting texts of revision {%s}',
               rev_id)
        parent_invs = map(self._load_updated_inventory, present_parents)
        entries = inv.iter_entries()
        entries.next()
        for path, ie in entries:
            self._convert_file_version(rev, ie, parent_invs)

    def _convert_file_version(self, rev, ie, parent_invs):
        """Convert one version of one file.

        The file needs to be added into the weave if it is a merge
        of >=2 parents or if it's changed from its parent.
        """
        file_id = ie.file_id
        rev_id = rev.revision_id
        w = self.text_weaves.get(file_id)
        if w is None:
            w = Weave(file_id)
            self.text_weaves[file_id] = w
        text_changed = False
        parent_candiate_entries = ie.parent_candidates(parent_invs)
        heads = graph.Graph(self).heads(parent_candiate_entries.keys())
        # XXX: Note that this is unordered - and this is tolerable because
        # the previous code was also unordered.
        previous_entries = dict((head, parent_candiate_entries[head]) for head
            in heads)
        self.snapshot_ie(previous_entries, ie, w, rev_id)
        del ie.text_id

    def get_parent_map(self, revision_ids):
        """See graph.StackedParentsProvider.get_parent_map"""
        return dict((revision_id, self.revisions[revision_id])
                    for revision_id in revision_ids
                     if revision_id in self.revisions)

    def snapshot_ie(self, previous_revisions, ie, w, rev_id):
        # TODO: convert this logic, which is ~= snapshot to
        # a call to:. This needs the path figured out. rather than a work_tree
        # a v4 revision_tree can be given, or something that looks enough like
        # one to give the file content to the entry if it needs it.
        # and we need something that looks like a weave store for snapshot to
        # save against.
        #ie.snapshot(rev, PATH, previous_revisions, REVISION_TREE, InMemoryWeaveStore(self.text_weaves))
        if len(previous_revisions) == 1:
            previous_ie = previous_revisions.values()[0]
            if ie._unchanged(previous_ie):
                ie.revision = previous_ie.revision
                return
        if ie.has_text():
            text = self.branch.repository._text_store.get(ie.text_id)
            file_lines = text.readlines()
            w.add_lines(rev_id, previous_revisions, file_lines)
            self.text_count += 1
        else:
            w.add_lines(rev_id, previous_revisions, [])
        ie.revision = rev_id

    def _make_order(self):
        """Return a suitable order for importing revisions.

        The order must be such that an revision is imported after all
        its (present) parents.
        """
        todo = set(self.revisions.keys())
        done = self.absent_revisions.copy()
        order = []
        while todo:
            # scan through looking for a revision whose parents
            # are all done
            for rev_id in sorted(list(todo)):
                rev = self.revisions[rev_id]
                parent_ids = set(rev.parent_ids)
                if parent_ids.issubset(done):
                    # can take this one now
                    order.append(rev_id)
                    todo.remove(rev_id)
                    done.add(rev_id)
        return order


class ConvertBzrDir5To6(Converter):
    """Converts format 5 bzr dirs to format 6."""

    def convert(self, to_convert, pb):
        """See Converter.convert()."""
        self.bzrdir = to_convert
        self.pb = pb
        self.pb.note('starting upgrade from format 5 to 6')
        self._convert_to_prefixed()
        return BzrDir.open(self.bzrdir.root_transport.base)

    def _convert_to_prefixed(self):
        from bzrlib.store import TransportStore
        self.bzrdir.transport.delete('branch-format')
        for store_name in ["weaves", "revision-store"]:
            self.pb.note("adding prefixes to %s" % store_name)
            store_transport = self.bzrdir.transport.clone(store_name)
            store = TransportStore(store_transport, prefixed=True)
            for urlfilename in store_transport.list_dir('.'):
                filename = urlutils.unescape(urlfilename)
                if (filename.endswith(".weave") or
                    filename.endswith(".gz") or
                    filename.endswith(".sig")):
                    file_id, suffix = os.path.splitext(filename)
                else:
                    file_id = filename
                    suffix = ''
                new_name = store._mapper.map((file_id,)) + suffix
                # FIXME keep track of the dirs made RBC 20060121
                try:
                    store_transport.move(filename, new_name)
                except errors.NoSuchFile: # catches missing dirs strangely enough
                    store_transport.mkdir(osutils.dirname(new_name))
                    store_transport.move(filename, new_name)
        self.bzrdir.transport.put_bytes(
            'branch-format',
            BzrDirFormat6().get_format_string(),
            mode=self.bzrdir._get_file_mode())


class ConvertBzrDir6ToMeta(Converter):
    """Converts format 6 bzr dirs to metadirs."""

    def convert(self, to_convert, pb):
        """See Converter.convert()."""
        from bzrlib.repofmt.weaverepo import RepositoryFormat7
        from bzrlib.branch import BzrBranchFormat5
        self.bzrdir = to_convert
        self.pb = pb
        self.count = 0
        self.total = 20 # the steps we know about
        self.garbage_inventories = []
        self.dir_mode = self.bzrdir._get_dir_mode()
        self.file_mode = self.bzrdir._get_file_mode()

        self.pb.note('starting upgrade from format 6 to metadir')
        self.bzrdir.transport.put_bytes(
                'branch-format',
                "Converting to format 6",
                mode=self.file_mode)
        # its faster to move specific files around than to open and use the apis...
        # first off, nuke ancestry.weave, it was never used.
        try:
            self.step('Removing ancestry.weave')
            self.bzrdir.transport.delete('ancestry.weave')
        except errors.NoSuchFile:
            pass
        # find out whats there
        self.step('Finding branch files')
        last_revision = self.bzrdir.open_branch().last_revision()
        bzrcontents = self.bzrdir.transport.list_dir('.')
        for name in bzrcontents:
            if name.startswith('basis-inventory.'):
                self.garbage_inventories.append(name)
        # create new directories for repository, working tree and branch
        repository_names = [('inventory.weave', True),
                            ('revision-store', True),
                            ('weaves', True)]
        self.step('Upgrading repository  ')
        self.bzrdir.transport.mkdir('repository', mode=self.dir_mode)
        self.make_lock('repository')
        # we hard code the formats here because we are converting into
        # the meta format. The meta format upgrader can take this to a
        # future format within each component.
        self.put_format('repository', RepositoryFormat7())
        for entry in repository_names:
            self.move_entry('repository', entry)

        self.step('Upgrading branch      ')
        self.bzrdir.transport.mkdir('branch', mode=self.dir_mode)
        self.make_lock('branch')
        self.put_format('branch', BzrBranchFormat5())
        branch_files = [('revision-history', True),
                        ('branch-name', True),
                        ('parent', False)]
        for entry in branch_files:
            self.move_entry('branch', entry)

        checkout_files = [('pending-merges', True),
                          ('inventory', True),
                          ('stat-cache', False)]
        # If a mandatory checkout file is not present, the branch does not have
        # a functional checkout. Do not create a checkout in the converted
        # branch.
        for name, mandatory in checkout_files:
            if mandatory and name not in bzrcontents:
                has_checkout = False
                break
        else:
            has_checkout = True
        if not has_checkout:
            self.pb.note('No working tree.')
            # If some checkout files are there, we may as well get rid of them.
            for name, mandatory in checkout_files:
                if name in bzrcontents:
                    self.bzrdir.transport.delete(name)
        else:
            from bzrlib.workingtree import WorkingTreeFormat3
            self.step('Upgrading working tree')
            self.bzrdir.transport.mkdir('checkout', mode=self.dir_mode)
            self.make_lock('checkout')
            self.put_format(
                'checkout', WorkingTreeFormat3())
            self.bzrdir.transport.delete_multi(
                self.garbage_inventories, self.pb)
            for entry in checkout_files:
                self.move_entry('checkout', entry)
            if last_revision is not None:
                self.bzrdir.transport.put_bytes(
                    'checkout/last-revision', last_revision)
        self.bzrdir.transport.put_bytes(
            'branch-format',
            BzrDirMetaFormat1().get_format_string(),
            mode=self.file_mode)
        return BzrDir.open(self.bzrdir.root_transport.base)

    def make_lock(self, name):
        """Make a lock for the new control dir name."""
        self.step('Make %s lock' % name)
        ld = lockdir.LockDir(self.bzrdir.transport,
                             '%s/lock' % name,
                             file_modebits=self.file_mode,
                             dir_modebits=self.dir_mode)
        ld.create()

    def move_entry(self, new_dir, entry):
        """Move then entry name into new_dir."""
        name = entry[0]
        mandatory = entry[1]
        self.step('Moving %s' % name)
        try:
            self.bzrdir.transport.move(name, '%s/%s' % (new_dir, name))
        except errors.NoSuchFile:
            if mandatory:
                raise

    def put_format(self, dirname, format):
        self.bzrdir.transport.put_bytes('%s/format' % dirname,
            format.get_format_string(),
            self.file_mode)


class ConvertMetaToMeta(Converter):
    """Converts the components of metadirs."""

    def __init__(self, target_format):
        """Create a metadir to metadir converter.

        :param target_format: The final metadir format that is desired.
        """
        self.target_format = target_format

    def convert(self, to_convert, pb):
        """See Converter.convert()."""
        self.bzrdir = to_convert
        self.pb = pb
        self.count = 0
        self.total = 1
        self.step('checking repository format')
        try:
            repo = self.bzrdir.open_repository()
        except errors.NoRepositoryPresent:
            pass
        else:
            if not isinstance(repo._format, self.target_format.repository_format.__class__):
                from bzrlib.repository import CopyConverter
                self.pb.note('starting repository conversion')
                converter = CopyConverter(self.target_format.repository_format)
                converter.convert(repo, pb)
        try:
            branch = self.bzrdir.open_branch()
        except errors.NotBranchError:
            pass
        else:
            # TODO: conversions of Branch and Tree should be done by
            # InterXFormat lookups/some sort of registry.
            # Avoid circular imports
            from bzrlib import branch as _mod_branch
            old = branch._format.__class__
            new = self.target_format.get_branch_format().__class__
            while old != new:
                if (old == _mod_branch.BzrBranchFormat5 and
                    new in (_mod_branch.BzrBranchFormat6,
                        _mod_branch.BzrBranchFormat7,
                        _mod_branch.BzrBranchFormat8)):
                    branch_converter = _mod_branch.Converter5to6()
                elif (old == _mod_branch.BzrBranchFormat6 and
                    new in (_mod_branch.BzrBranchFormat7,
                            _mod_branch.BzrBranchFormat8)):
                    branch_converter = _mod_branch.Converter6to7()
                elif (old == _mod_branch.BzrBranchFormat7 and
                      new is _mod_branch.BzrBranchFormat8):
                    branch_converter = _mod_branch.Converter7to8()
                else:
                    raise errors.BadConversionTarget("No converter", new)
                branch_converter.convert(branch)
                branch = self.bzrdir.open_branch()
                old = branch._format.__class__
        try:
            tree = self.bzrdir.open_workingtree(recommend_upgrade=False)
        except (errors.NoWorkingTree, errors.NotLocalUrl):
            pass
        else:
            # TODO: conversions of Branch and Tree should be done by
            # InterXFormat lookups
            if (isinstance(tree, workingtree.WorkingTree3) and
                not isinstance(tree, workingtree_4.DirStateWorkingTree) and
                isinstance(self.target_format.workingtree_format,
                    workingtree_4.DirStateWorkingTreeFormat)):
                workingtree_4.Converter3to4().convert(tree)
            if (isinstance(tree, workingtree_4.DirStateWorkingTree) and
                not isinstance(tree, workingtree_4.WorkingTree5) and
                isinstance(self.target_format.workingtree_format,
                    workingtree_4.WorkingTreeFormat5)):
                workingtree_4.Converter4to5().convert(tree)
            if (isinstance(tree, workingtree_4.DirStateWorkingTree) and
                not isinstance(tree, workingtree_4.WorkingTree6) and
                isinstance(self.target_format.workingtree_format,
                    workingtree_4.WorkingTreeFormat6)):
                workingtree_4.Converter4or5to6().convert(tree)
        return to_convert


# This is not in remote.py because it's relatively small, and needs to be
# registered. Putting it in remote.py creates a circular import problem.
# we can make it a lazy object if the control formats is turned into something
# like a registry.
class RemoteBzrDirFormat(BzrDirMetaFormat1):
    """Format representing bzrdirs accessed via a smart server"""

    def __init__(self):
        BzrDirMetaFormat1.__init__(self)
        self._network_name = None

    def get_format_description(self):
        return 'bzr remote bzrdir'

    def get_format_string(self):
        raise NotImplementedError(self.get_format_string)

    def network_name(self):
        if self._network_name:
            return self._network_name
        else:
            raise AssertionError("No network name set.")

    @classmethod
    def probe_transport(klass, transport):
        """Return a RemoteBzrDirFormat object if it looks possible."""
        try:
            medium = transport.get_smart_medium()
        except (NotImplementedError, AttributeError,
                errors.TransportNotPossible, errors.NoSmartMedium,
                errors.SmartProtocolError):
            # no smart server, so not a branch for this format type.
            raise errors.NotBranchError(path=transport.base)
        else:
            # Decline to open it if the server doesn't support our required
            # version (3) so that the VFS-based transport will do it.
            if medium.should_probe():
                try:
                    server_version = medium.protocol_version()
                except errors.SmartProtocolError:
                    # Apparently there's no usable smart server there, even though
                    # the medium supports the smart protocol.
                    raise errors.NotBranchError(path=transport.base)
                if server_version != '2':
                    raise errors.NotBranchError(path=transport.base)
            return klass()

    def initialize_on_transport(self, transport):
        try:
            # hand off the request to the smart server
            client_medium = transport.get_smart_medium()
        except errors.NoSmartMedium:
            # TODO: lookup the local format from a server hint.
            local_dir_format = BzrDirMetaFormat1()
            return local_dir_format.initialize_on_transport(transport)
        client = _SmartClient(client_medium)
        path = client.remote_path_from_transport(transport)
        try:
            response = client.call('BzrDirFormat.initialize', path)
        except errors.ErrorFromSmartServer, err:
            remote._translate_error(err, path=path)
        if response[0] != 'ok':
            raise errors.SmartProtocolError('unexpected response code %s' % (response,))
        format = RemoteBzrDirFormat()
        self._supply_sub_formats_to(format)
        return remote.RemoteBzrDir(transport, format)

    def parse_NoneTrueFalse(self, arg):
        if not arg:
            return None
        if arg == 'False':
            return False
        if arg == 'True':
            return True
        raise AssertionError("invalid arg %r" % arg)

    def _serialize_NoneTrueFalse(self, arg):
        if arg is False:
            return 'False'
        if arg:
            return 'True'
        return ''

    def _serialize_NoneString(self, arg):
        return arg or ''

    def initialize_on_transport_ex(self, transport, use_existing_dir=False,
        create_prefix=False, force_new_repo=False, stacked_on=None,
        stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
        shared_repo=False):
        try:
            # hand off the request to the smart server
            client_medium = transport.get_smart_medium()
        except errors.NoSmartMedium:
            do_vfs = True
        else:
            # Decline to open it if the server doesn't support our required
            # version (3) so that the VFS-based transport will do it.
            if client_medium.should_probe():
                try:
                    server_version = client_medium.protocol_version()
                    if server_version != '2':
                        do_vfs = True
                    else:
                        do_vfs = False
                except errors.SmartProtocolError:
                    # Apparently there's no usable smart server there, even though
                    # the medium supports the smart protocol.
                    do_vfs = True
            else:
                do_vfs = False
        if not do_vfs:
            client = _SmartClient(client_medium)
            path = client.remote_path_from_transport(transport)
            if client_medium._is_remote_before((1, 15)):
                do_vfs = True
        if do_vfs:
            # TODO: lookup the local format from a server hint.
            local_dir_format = BzrDirMetaFormat1()
            self._supply_sub_formats_to(local_dir_format)
            return local_dir_format.initialize_on_transport_ex(transport,
                use_existing_dir=use_existing_dir, create_prefix=create_prefix,
                force_new_repo=force_new_repo, stacked_on=stacked_on,
                stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
                make_working_trees=make_working_trees, shared_repo=shared_repo,
                vfs_only=True)
        return self._initialize_on_transport_ex_rpc(client, path, transport,
            use_existing_dir, create_prefix, force_new_repo, stacked_on,
            stack_on_pwd, repo_format_name, make_working_trees, shared_repo)

    def _initialize_on_transport_ex_rpc(self, client, path, transport,
        use_existing_dir, create_prefix, force_new_repo, stacked_on,
        stack_on_pwd, repo_format_name, make_working_trees, shared_repo):
        args = []
        args.append(self._serialize_NoneTrueFalse(use_existing_dir))
        args.append(self._serialize_NoneTrueFalse(create_prefix))
        args.append(self._serialize_NoneTrueFalse(force_new_repo))
        args.append(self._serialize_NoneString(stacked_on))
        # stack_on_pwd is often/usually our transport
        if stack_on_pwd:
            try:
                stack_on_pwd = transport.relpath(stack_on_pwd)
                if not stack_on_pwd:
                    stack_on_pwd = '.'
            except errors.PathNotChild:
                pass
        args.append(self._serialize_NoneString(stack_on_pwd))
        args.append(self._serialize_NoneString(repo_format_name))
        args.append(self._serialize_NoneTrueFalse(make_working_trees))
        args.append(self._serialize_NoneTrueFalse(shared_repo))
        if self._network_name is None:
            self._network_name = \
            BzrDirFormat.get_default_format().network_name()
        try:
            response = client.call('BzrDirFormat.initialize_ex',
                self.network_name(), path, *args)
        except errors.UnknownSmartMethod:
            local_dir_format = BzrDirMetaFormat1()
            self._supply_sub_formats_to(local_dir_format)
            return local_dir_format.initialize_on_transport_ex(transport,
                use_existing_dir=use_existing_dir, create_prefix=create_prefix,
                force_new_repo=force_new_repo, stacked_on=stacked_on,
                stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
                make_working_trees=make_working_trees, shared_repo=shared_repo,
                vfs_only=True)
        except errors.ErrorFromSmartServer, err:
            remote._translate_error(err, path=path)
        repo_path = response[0]
        bzrdir_name = response[6]
        require_stacking = response[7]
        require_stacking = self.parse_NoneTrueFalse(require_stacking)
        format = RemoteBzrDirFormat()
        format._network_name = bzrdir_name
        self._supply_sub_formats_to(format)
        bzrdir = remote.RemoteBzrDir(transport, format, _client=client)
        if repo_path:
            repo_format = remote.response_tuple_to_repo_format(response[1:])
            if repo_path == '.':
                repo_path = ''
            if repo_path:
                repo_bzrdir_format = RemoteBzrDirFormat()
                repo_bzrdir_format._network_name = response[5]
                repo_bzr = remote.RemoteBzrDir(transport.clone(repo_path),
                    repo_bzrdir_format)
            else:
                repo_bzr = bzrdir
            final_stack = response[8] or None
            final_stack_pwd = response[9] or None
            remote_repo = remote.RemoteRepository(repo_bzr, repo_format)
            if len(response) > 10:
                # Updated server verb that locks remotely.
                repo_lock_token = response[10] or None
                remote_repo.lock_write(repo_lock_token, _skip_rpc=True)
                if repo_lock_token:
                    remote_repo.dont_leave_lock_in_place()
            else:
                remote_repo.lock_write()
            policy = UseExistingRepository(remote_repo, final_stack,
                final_stack_pwd, require_stacking)
            policy.acquire_repository()
        else:
            remote_repo = None
            policy = None
        return remote_repo, bzrdir, require_stacking, policy

    def _open(self, transport):
        return remote.RemoteBzrDir(transport, self)

    def __eq__(self, other):
        if not isinstance(other, RemoteBzrDirFormat):
            return False
        return self.get_format_description() == other.get_format_description()

    def __return_repository_format(self):
        # Always return a RemoteRepositoryFormat object, but if a specific bzr
        # repository format has been asked for, tell the RemoteRepositoryFormat
        # that it should use that for init() etc.
        result = remote.RemoteRepositoryFormat()
        custom_format = getattr(self, '_repository_format', None)
        if custom_format:
            if isinstance(custom_format, remote.RemoteRepositoryFormat):
                return custom_format
            else:
                # We will use the custom format to create repositories over the
                # wire; expose its details like rich_root_data for code to
                # query
                result._custom_format = custom_format
        return result

    def get_branch_format(self):
        result = BzrDirMetaFormat1.get_branch_format(self)
        if not isinstance(result, remote.RemoteBranchFormat):
            new_result = remote.RemoteBranchFormat()
            new_result._custom_format = result
            # cache the result
            self.set_branch_format(new_result)
            result = new_result
        return result

    repository_format = property(__return_repository_format,
        BzrDirMetaFormat1._set_repository_format) #.im_func)


BzrDirFormat.register_control_server_format(RemoteBzrDirFormat)


class BzrDirFormatInfo(object):

    def __init__(self, native, deprecated, hidden, experimental):
        self.deprecated = deprecated
        self.native = native
        self.hidden = hidden
        self.experimental = experimental


class BzrDirFormatRegistry(registry.Registry):
    """Registry of user-selectable BzrDir subformats.

    Differs from BzrDirFormat._control_formats in that it provides sub-formats,
    e.g. BzrDirMeta1 with weave repository.  Also, it's more user-oriented.
    """

    def __init__(self):
        """Create a BzrDirFormatRegistry."""
        self._aliases = set()
        self._registration_order = list()
        super(BzrDirFormatRegistry, self).__init__()

    def aliases(self):
        """Return a set of the format names which are aliases."""
        return frozenset(self._aliases)

    def register_metadir(self, key,
             repository_format, help, native=True, deprecated=False,
             branch_format=None,
             tree_format=None,
             hidden=False,
             experimental=False,
             alias=False):
        """Register a metadir subformat.

        These all use a BzrDirMetaFormat1 bzrdir, but can be parameterized
        by the Repository/Branch/WorkingTreeformats.

        :param repository_format: The fully-qualified repository format class
            name as a string.
        :param branch_format: Fully-qualified branch format class name as
            a string.
        :param tree_format: Fully-qualified tree format class name as
            a string.
        """
        # This should be expanded to support setting WorkingTree and Branch
        # formats, once BzrDirMetaFormat1 supports that.
        def _load(full_name):
            mod_name, factory_name = full_name.rsplit('.', 1)
            try:
                mod = __import__(mod_name, globals(), locals(),
                        [factory_name])
            except ImportError, e:
                raise ImportError('failed to load %s: %s' % (full_name, e))
            try:
                factory = getattr(mod, factory_name)
            except AttributeError:
                raise AttributeError('no factory %s in module %r'
                    % (full_name, mod))
            return factory()

        def helper():
            bd = BzrDirMetaFormat1()
            if branch_format is not None:
                bd.set_branch_format(_load(branch_format))
            if tree_format is not None:
                bd.workingtree_format = _load(tree_format)
            if repository_format is not None:
                bd.repository_format = _load(repository_format)
            return bd
        self.register(key, helper, help, native, deprecated, hidden,
            experimental, alias)

    def register(self, key, factory, help, native=True, deprecated=False,
                 hidden=False, experimental=False, alias=False):
        """Register a BzrDirFormat factory.

        The factory must be a callable that takes one parameter: the key.
        It must produce an instance of the BzrDirFormat when called.

        This function mainly exists to prevent the info object from being
        supplied directly.
        """
        registry.Registry.register(self, key, factory, help,
            BzrDirFormatInfo(native, deprecated, hidden, experimental))
        if alias:
            self._aliases.add(key)
        self._registration_order.append(key)

    def register_lazy(self, key, module_name, member_name, help, native=True,
        deprecated=False, hidden=False, experimental=False, alias=False):
        registry.Registry.register_lazy(self, key, module_name, member_name,
            help, BzrDirFormatInfo(native, deprecated, hidden, experimental))
        if alias:
            self._aliases.add(key)
        self._registration_order.append(key)

    def set_default(self, key):
        """Set the 'default' key to be a clone of the supplied key.

        This method must be called once and only once.
        """
        registry.Registry.register(self, 'default', self.get(key),
            self.get_help(key), info=self.get_info(key))
        self._aliases.add('default')

    def set_default_repository(self, key):
        """Set the FormatRegistry default and Repository default.

        This is a transitional method while Repository.set_default_format
        is deprecated.
        """
        if 'default' in self:
            self.remove('default')
        self.set_default(key)
        format = self.get('default')()

    def make_bzrdir(self, key):
        return self.get(key)()

    def help_topic(self, topic):
        output = ""
        default_realkey = None
        default_help = self.get_help('default')
        help_pairs = []
        for key in self._registration_order:
            if key == 'default':
                continue
            help = self.get_help(key)
            if help == default_help:
                default_realkey = key
            else:
                help_pairs.append((key, help))

        def wrapped(key, help, info):
            if info.native:
                help = '(native) ' + help
            return ':%s:\n%s\n\n' % (key,
                textwrap.fill(help, initial_indent='    ',
                    subsequent_indent='    ',
                    break_long_words=False))
        if default_realkey is not None:
            output += wrapped(default_realkey, '(default) %s' % default_help,
                              self.get_info('default'))
        deprecated_pairs = []
        experimental_pairs = []
        for key, help in help_pairs:
            info = self.get_info(key)
            if info.hidden:
                continue
            elif info.deprecated:
                deprecated_pairs.append((key, help))
            elif info.experimental:
                experimental_pairs.append((key, help))
            else:
                output += wrapped(key, help, info)
        output += "\nSee ``bzr help formats`` for more about storage formats."
        other_output = ""
        if len(experimental_pairs) > 0:
            other_output += "Experimental formats are shown below.\n\n"
            for key, help in experimental_pairs:
                info = self.get_info(key)
                other_output += wrapped(key, help, info)
        else:
            other_output += \
                "No experimental formats are available.\n\n"
        if len(deprecated_pairs) > 0:
            other_output += "\nDeprecated formats are shown below.\n\n"
            for key, help in deprecated_pairs:
                info = self.get_info(key)
                other_output += wrapped(key, help, info)
        else:
            other_output += \
                "\nNo deprecated formats are available.\n\n"
        other_output += \
            "\nSee ``bzr help formats`` for more about storage formats."

        if topic == 'other-formats':
            return other_output
        else:
            return output


class RepositoryAcquisitionPolicy(object):
    """Abstract base class for repository acquisition policies.

    A repository acquisition policy decides how a BzrDir acquires a repository
    for a branch that is being created.  The most basic policy decision is
    whether to create a new repository or use an existing one.
    """
    def __init__(self, stack_on, stack_on_pwd, require_stacking):
        """Constructor.

        :param stack_on: A location to stack on
        :param stack_on_pwd: If stack_on is relative, the location it is
            relative to.
        :param require_stacking: If True, it is a failure to not stack.
        """
        self._stack_on = stack_on
        self._stack_on_pwd = stack_on_pwd
        self._require_stacking = require_stacking

    def configure_branch(self, branch):
        """Apply any configuration data from this policy to the branch.

        Default implementation sets repository stacking.
        """
        if self._stack_on is None:
            return
        if self._stack_on_pwd is None:
            stack_on = self._stack_on
        else:
            try:
                stack_on = urlutils.rebase_url(self._stack_on,
                    self._stack_on_pwd,
                    branch.bzrdir.root_transport.base)
            except errors.InvalidRebaseURLs:
                stack_on = self._get_full_stack_on()
        try:
            branch.set_stacked_on_url(stack_on)
        except (errors.UnstackableBranchFormat,
                errors.UnstackableRepositoryFormat):
            if self._require_stacking:
                raise

    def _get_full_stack_on(self):
        """Get a fully-qualified URL for the stack_on location."""
        if self._stack_on is None:
            return None
        if self._stack_on_pwd is None:
            return self._stack_on
        else:
            return urlutils.join(self._stack_on_pwd, self._stack_on)

    def _add_fallback(self, repository, possible_transports=None):
        """Add a fallback to the supplied repository, if stacking is set."""
        stack_on = self._get_full_stack_on()
        if stack_on is None:
            return
        try:
            stacked_dir = BzrDir.open(stack_on,
                                      possible_transports=possible_transports)
        except errors.JailBreak:
            # We keep the stacking details, but we are in the server code so
            # actually stacking is not needed.
            return
        try:
            stacked_repo = stacked_dir.open_branch().repository
        except errors.NotBranchError:
            stacked_repo = stacked_dir.open_repository()
        try:
            repository.add_fallback_repository(stacked_repo)
        except errors.UnstackableRepositoryFormat:
            if self._require_stacking:
                raise
        else:
            self._require_stacking = True

    def acquire_repository(self, make_working_trees=None, shared=False):
        """Acquire a repository for this bzrdir.

        Implementations may create a new repository or use a pre-exising
        repository.
        :param make_working_trees: If creating a repository, set
            make_working_trees to this value (if non-None)
        :param shared: If creating a repository, make it shared if True
        :return: A repository, is_new_flag (True if the repository was
            created).
        """
        raise NotImplemented(RepositoryAcquisitionPolicy.acquire_repository)


class CreateRepository(RepositoryAcquisitionPolicy):
    """A policy of creating a new repository"""

    def __init__(self, bzrdir, stack_on=None, stack_on_pwd=None,
                 require_stacking=False):
        """
        Constructor.
        :param bzrdir: The bzrdir to create the repository on.
        :param stack_on: A location to stack on
        :param stack_on_pwd: If stack_on is relative, the location it is
            relative to.
        """
        RepositoryAcquisitionPolicy.__init__(self, stack_on, stack_on_pwd,
                                             require_stacking)
        self._bzrdir = bzrdir

    def acquire_repository(self, make_working_trees=None, shared=False):
        """Implementation of RepositoryAcquisitionPolicy.acquire_repository

        Creates the desired repository in the bzrdir we already have.
        """
        stack_on = self._get_full_stack_on()
        if stack_on:
            format = self._bzrdir._format
            format.require_stacking(stack_on=stack_on,
                                    possible_transports=[self._bzrdir.root_transport])
            if not self._require_stacking:
                # We have picked up automatic stacking somewhere.
                note('Using default stacking branch %s at %s', self._stack_on,
                    self._stack_on_pwd)
        repository = self._bzrdir.create_repository(shared=shared)
        self._add_fallback(repository,
                           possible_transports=[self._bzrdir.transport])
        if make_working_trees is not None:
            repository.set_make_working_trees(make_working_trees)
        return repository, True


class UseExistingRepository(RepositoryAcquisitionPolicy):
    """A policy of reusing an existing repository"""

    def __init__(self, repository, stack_on=None, stack_on_pwd=None,
                 require_stacking=False):
        """Constructor.

        :param repository: The repository to use.
        :param stack_on: A location to stack on
        :param stack_on_pwd: If stack_on is relative, the location it is
            relative to.
        """
        RepositoryAcquisitionPolicy.__init__(self, stack_on, stack_on_pwd,
                                             require_stacking)
        self._repository = repository

    def acquire_repository(self, make_working_trees=None, shared=False):
        """Implementation of RepositoryAcquisitionPolicy.acquire_repository

        Returns an existing repository to use.
        """
        self._add_fallback(self._repository,
                       possible_transports=[self._repository.bzrdir.transport])
        return self._repository, False


# Please register new formats after old formats so that formats
# appear in chronological order and format descriptions can build
# on previous ones.
format_registry = BzrDirFormatRegistry()
# The pre-0.8 formats have their repository format network name registered in
# repository.py. MetaDir formats have their repository format network name
# inferred from their disk format string.
format_registry.register('weave', BzrDirFormat6,
    'Pre-0.8 format.  Slower than knit and does not'
    ' support checkouts or shared repositories.',
    deprecated=True)
format_registry.register_metadir('metaweave',
    'bzrlib.repofmt.weaverepo.RepositoryFormat7',
    'Transitional format in 0.8.  Slower than knit.',
    branch_format='bzrlib.branch.BzrBranchFormat5',
    tree_format='bzrlib.workingtree.WorkingTreeFormat3',
    deprecated=True)
format_registry.register_metadir('knit',
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
    'Format using knits.  Recommended for interoperation with bzr <= 0.14.',
    branch_format='bzrlib.branch.BzrBranchFormat5',
    tree_format='bzrlib.workingtree.WorkingTreeFormat3',
    deprecated=True)
format_registry.register_metadir('dirstate',
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
    help='New in 0.15: Fast local operations. Compatible with bzr 0.8 and '
        'above when accessed over the network.',
    branch_format='bzrlib.branch.BzrBranchFormat5',
    # this uses bzrlib.workingtree.WorkingTreeFormat4 because importing
    # directly from workingtree_4 triggers a circular import.
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
    deprecated=True)
format_registry.register_metadir('dirstate-tags',
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
    help='New in 0.15: Fast local operations and improved scaling for '
        'network operations. Additionally adds support for tags.'
        ' Incompatible with bzr < 0.15.',
    branch_format='bzrlib.branch.BzrBranchFormat6',
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
    deprecated=True)
format_registry.register_metadir('rich-root',
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit4',
    help='New in 1.0.  Better handling of tree roots.  Incompatible with'
        ' bzr < 1.0.',
    branch_format='bzrlib.branch.BzrBranchFormat6',
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
    deprecated=True)
format_registry.register_metadir('dirstate-with-subtree',
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit3',
    help='New in 0.15: Fast local operations and improved scaling for '
        'network operations. Additionally adds support for versioning nested '
        'bzr branches. Incompatible with bzr < 0.15.',
    branch_format='bzrlib.branch.BzrBranchFormat6',
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
    experimental=True,
    hidden=True,
    )
format_registry.register_metadir('pack-0.92',
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack1',
    help='New in 0.92: Pack-based format with data compatible with '
        'dirstate-tags format repositories. Interoperates with '
        'bzr repositories before 0.92 but cannot be read by bzr < 0.92. '
        'Previously called knitpack-experimental.  '
        'For more information, see '
        'http://doc.bazaar-vcs.org/latest/developers/packrepo.html.',
    branch_format='bzrlib.branch.BzrBranchFormat6',
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
    )
format_registry.register_metadir('pack-0.92-subtree',
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack3',
    help='New in 0.92: Pack-based format with data compatible with '
        'dirstate-with-subtree format repositories. Interoperates with '
        'bzr repositories before 0.92 but cannot be read by bzr < 0.92. '
        'Previously called knitpack-experimental.  '
        'For more information, see '
        'http://doc.bazaar-vcs.org/latest/developers/packrepo.html.',
    branch_format='bzrlib.branch.BzrBranchFormat6',
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
    hidden=True,
    experimental=True,
    )
format_registry.register_metadir('rich-root-pack',
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack4',
    help='New in 1.0: A variant of pack-0.92 that supports rich-root data '
         '(needed for bzr-svn and bzr-git).',
    branch_format='bzrlib.branch.BzrBranchFormat6',
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
    )
format_registry.register_metadir('1.6',
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack5',
    help='A format that allows a branch to indicate that there is another '
         '(stacked) repository that should be used to access data that is '
         'not present locally.',
    branch_format='bzrlib.branch.BzrBranchFormat7',
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
    )
format_registry.register_metadir('1.6.1-rich-root',
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack5RichRoot',
    help='A variant of 1.6 that supports rich-root data '
         '(needed for bzr-svn and bzr-git).',
    branch_format='bzrlib.branch.BzrBranchFormat7',
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
    )
format_registry.register_metadir('1.9',
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6',
    help='A repository format using B+tree indexes. These indexes '
         'are smaller in size, have smarter caching and provide faster '
         'performance for most operations.',
    branch_format='bzrlib.branch.BzrBranchFormat7',
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
    )
format_registry.register_metadir('1.9-rich-root',
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6RichRoot',
    help='A variant of 1.9 that supports rich-root data '
         '(needed for bzr-svn and bzr-git).',
    branch_format='bzrlib.branch.BzrBranchFormat7',
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
    )
format_registry.register_metadir('1.14',
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6',
    help='A working-tree format that supports content filtering.',
    branch_format='bzrlib.branch.BzrBranchFormat7',
    tree_format='bzrlib.workingtree.WorkingTreeFormat5',
    )
format_registry.register_metadir('1.14-rich-root',
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6RichRoot',
    help='A variant of 1.14 that supports rich-root data '
         '(needed for bzr-svn and bzr-git).',
    branch_format='bzrlib.branch.BzrBranchFormat7',
    tree_format='bzrlib.workingtree.WorkingTreeFormat5',
    )
# The following un-numbered 'development' formats should always just be aliases.
format_registry.register_metadir('development-rich-root',
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormatCHK1',
    help='Current development format. Supports rich roots. Can convert data '
        'to and from rich-root-pack (and anything compatible with '
        'rich-root-pack) format repositories. Repositories and branches in '
        'this format can only be read by bzr.dev. Please read '
        'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
        'before use.',
    branch_format='bzrlib.branch.BzrBranchFormat7',
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
    experimental=True,
    alias=True,
    )
format_registry.register_metadir('development-subtree',
    'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment2Subtree',
    help='Current development format, subtree variant. Can convert data to and '
        'from pack-0.92-subtree (and anything compatible with '
        'pack-0.92-subtree) format repositories. Repositories and branches in '
        'this format can only be read by bzr.dev. Please read '
        'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
        'before use.',
    branch_format='bzrlib.branch.BzrBranchFormat7',
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
    experimental=True,
    alias=False, # Restore to being an alias when an actual development subtree format is added
                 # This current non-alias status is simply because we did not introduce a
                 # chk based subtree format.
    )

# And the development formats above will have aliased one of the following:
format_registry.register_metadir('development6-rich-root',
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormatCHK1',
    help='pack-1.9 with 255-way hashed CHK inv, group compress, rich roots '
        'Please read '
        'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
        'before use.',
    branch_format='bzrlib.branch.BzrBranchFormat7',
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
    hidden=True,
    experimental=True,
    )

format_registry.register_metadir('development7-rich-root',
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormatCHK2',
    help='pack-1.9 with 255-way hashed CHK inv, bencode revision, group compress, '
        'rich roots. Please read '
        'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
        'before use.',
    branch_format='bzrlib.branch.BzrBranchFormat7',
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
    hidden=True,
    experimental=True,
    )

# The following format should be an alias for the rich root equivalent 
# of the default format
format_registry.register_metadir('default-rich-root',
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack4',
    help='Default format, rich root variant. (needed for bzr-svn and bzr-git).',
    branch_format='bzrlib.branch.BzrBranchFormat6',
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
    alias=True,
    )
# The current format that is made on 'bzr init'.
format_registry.set_default('pack-0.92')