~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
# Copyright (C) 2006, 2007, 2008 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

"""DirState objects record the state of a directory and its bzr metadata.

Pseudo EBNF grammar for the state file. Fields are separated by NULLs, and
lines by NL. The field delimiters are ommitted in the grammar, line delimiters
are not - this is done for clarity of reading. All string data is in utf8.

MINIKIND = "f" | "d" | "l" | "a" | "r" | "t";
NL = "\n";
NULL = "\0";
WHOLE_NUMBER = {digit}, digit;
BOOLEAN = "y" | "n";
REVISION_ID = a non-empty utf8 string;

dirstate format = header line, full checksum, row count, parent details,
 ghost_details, entries;
header line = "#bazaar dirstate flat format 3", NL;
full checksum = "crc32: ", ["-"], WHOLE_NUMBER, NL;
row count = "num_entries: ", WHOLE_NUMBER, NL;
parent_details = WHOLE NUMBER, {REVISION_ID}* NL;
ghost_details = WHOLE NUMBER, {REVISION_ID}*, NL;
entries = {entry};
entry = entry_key, current_entry_details, {parent_entry_details};
entry_key = dirname,  basename, fileid;
current_entry_details = common_entry_details, working_entry_details;
parent_entry_details = common_entry_details, history_entry_details;
common_entry_details = MINIKIND, fingerprint, size, executable
working_entry_details = packed_stat
history_entry_details = REVISION_ID;
executable = BOOLEAN;
size = WHOLE_NUMBER;
fingerprint = a nonempty utf8 sequence with meaning defined by minikind.

Given this definition, the following is useful to know:
entry (aka row) - all the data for a given key.
entry[0]: The key (dirname, basename, fileid)
entry[0][0]: dirname
entry[0][1]: basename
entry[0][2]: fileid
entry[1]: The tree(s) data for this path and id combination.
entry[1][0]: The current tree
entry[1][1]: The second tree

For an entry for a tree, we have (using tree 0 - current tree) to demonstrate:
entry[1][0][0]: minikind
entry[1][0][1]: fingerprint
entry[1][0][2]: size
entry[1][0][3]: executable
entry[1][0][4]: packed_stat
OR (for non tree-0)
entry[1][1][4]: revision_id

There may be multiple rows at the root, one per id present in the root, so the
in memory root row is now:
self._dirblocks[0] -> ('', [entry ...]),
and the entries in there are
entries[0][0]: ''
entries[0][1]: ''
entries[0][2]: file_id
entries[1][0]: The tree data for the current tree for this fileid at /
etc.

Kinds:
'r' is a relocated entry: This path is not present in this tree with this id,
    but the id can be found at another location. The fingerprint is used to
    point to the target location.
'a' is an absent entry: In that tree the id is not present at this path.
'd' is a directory entry: This path in this tree is a directory with the
    current file id. There is no fingerprint for directories.
'f' is a file entry: As for directory, but its a file. The fingerprint is a
    sha1 value.
'l' is a symlink entry: As for directory, but a symlink. The fingerprint is the
    link target.
't' is a reference to a nested subtree; the fingerprint is the referenced
    revision.

Ordering:

The entries on disk and in memory are ordered according to the following keys:

    directory, as a list of components
    filename
    file-id

--- Format 1 had the following different definition: ---
rows = dirname, NULL, basename, NULL, MINIKIND, NULL, fileid_utf8, NULL,
    WHOLE NUMBER (* size *), NULL, packed stat, NULL, sha1|symlink target, 
    {PARENT ROW}
PARENT ROW = NULL, revision_utf8, NULL, MINIKIND, NULL, dirname, NULL,
    basename, NULL, WHOLE NUMBER (* size *), NULL, "y" | "n", NULL,
    SHA1

PARENT ROW's are emitted for every parent that is not in the ghosts details
line. That is, if the parents are foo, bar, baz, and the ghosts are bar, then
each row will have a PARENT ROW for foo and baz, but not for bar.


In any tree, a kind of 'moved' indicates that the fingerprint field
(which we treat as opaque data specific to the 'kind' anyway) has the
details for the id of this row in that tree.

I'm strongly tempted to add a id->path index as well, but I think that
where we need id->path mapping; we also usually read the whole file, so
I'm going to skip that for the moment, as we have the ability to locate
via bisect any path in any tree, and if we lookup things by path, we can
accumulate an id->path mapping as we go, which will tend to match what we
looked for.

I plan to implement this asap, so please speak up now to alter/tweak the
design - and once we stabilise on this, I'll update the wiki page for
it.

The rationale for all this is that we want fast operations for the
common case (diff/status/commit/merge on all files) and extremely fast
operations for the less common but still occurs a lot status/diff/commit
on specific files). Operations on specific files involve a scan for all
the children of a path, *in every involved tree*, which the current
format did not accommodate. 
----

Design priorities:
 1) Fast end to end use for bzr's top 5 uses cases. (commmit/diff/status/merge/???)
 2) fall back current object model as needed.
 3) scale usably to the largest trees known today - say 50K entries. (mozilla
    is an example of this)


Locking:
 Eventually reuse dirstate objects across locks IFF the dirstate file has not
 been modified, but will require that we flush/ignore cached stat-hit data
 because we won't want to restat all files on disk just because a lock was
 acquired, yet we cannot trust the data after the previous lock was released.

Memory representation:
 vector of all directories, and vector of the childen ?
   i.e. 
     root_entrie = (direntry for root, [parent_direntries_for_root]), 
     dirblocks = [
     ('', ['data for achild', 'data for bchild', 'data for cchild'])
     ('dir', ['achild', 'cchild', 'echild'])
     ]
    - single bisect to find N subtrees from a path spec
    - in-order for serialisation - this is 'dirblock' grouping.
    - insertion of a file '/a' affects only the '/' child-vector, that is, to
      insert 10K elements from scratch does not generates O(N^2) memoves of a
      single vector, rather each individual, which tends to be limited to a 
      manageable number. Will scale badly on trees with 10K entries in a 
      single directory. compare with Inventory.InventoryDirectory which has
      a dictionary for the children. No bisect capability, can only probe for
      exact matches, or grab all elements and sort.
    - What's the risk of error here? Once we have the base format being processed
      we should have a net win regardless of optimality. So we are going to 
      go with what seems reasonable.
open questions:

Maybe we should do a test profile of the core structure - 10K simulated
searches/lookups/etc?

Objects for each row?
The lifetime of Dirstate objects is current per lock, but see above for
possible extensions. The lifetime of a row from a dirstate is expected to be
very short in the optimistic case: which we are optimising for. For instance,
subtree status will determine from analysis of the disk data what rows need to
be examined at all, and will be able to determine from a single row whether
that file has altered or not, so we are aiming to process tens of thousands of
entries each second within the dirstate context, before exposing anything to
the larger codebase. This suggests we want the time for a single file
comparison to be < 0.1 milliseconds. That would give us 10000 paths per second
processed, and to scale to 100 thousand we'll another order of magnitude to do
that. Now, as the lifetime for all unchanged entries is the time to parse, stat
the file on disk, and then immediately discard, the overhead of object creation
becomes a significant cost.

Figures: Creating a tuple from from 3 elements was profiled at 0.0625
microseconds, whereas creating a object which is subclassed from tuple was
0.500 microseconds, and creating an object with 3 elements and slots was 3
microseconds long. 0.1 milliseconds is 100 microseconds, and ideally we'll get
down to 10 microseconds for the total processing - having 33% of that be object
creation is a huge overhead. There is a potential cost in using tuples within
each row which is that the conditional code to do comparisons may be slower
than method invocation, but method invocation is known to be slow due to stack
frame creation, so avoiding methods in these tight inner loops in unfortunately
desirable. We can consider a pyrex version of this with objects in future if
desired.

"""

import bisect
import binascii
import errno
import os
from stat import S_IEXEC
import stat
import struct
import sys
import time
import zlib

from bzrlib import (
    cache_utf8,
    debug,
    errors,
    inventory,
    lock,
    osutils,
    trace,
    )


def pack_stat(st, _encode=binascii.b2a_base64, _pack=struct.pack):
    """Convert stat values into a packed representation."""
    # jam 20060614 it isn't really worth removing more entries if we
    # are going to leave it in packed form.
    # With only st_mtime and st_mode filesize is 5.5M and read time is 275ms
    # With all entries, filesize is 5.9M and read time is maybe 280ms
    # well within the noise margin

    # base64 encoding always adds a final newline, so strip it off
    # The current version
    return _encode(_pack('>LLLLLL'
        , st.st_size, int(st.st_mtime), int(st.st_ctime)
        , st.st_dev, st.st_ino & 0xFFFFFFFF, st.st_mode))[:-1]
    # This is 0.060s / 1.520s faster by not encoding as much information
    # return _encode(_pack('>LL', int(st.st_mtime), st.st_mode))[:-1]
    # This is not strictly faster than _encode(_pack())[:-1]
    # return '%X.%X.%X.%X.%X.%X' % (
    #      st.st_size, int(st.st_mtime), int(st.st_ctime),
    #      st.st_dev, st.st_ino, st.st_mode)
    # Similar to the _encode(_pack('>LL'))
    # return '%X.%X' % (int(st.st_mtime), st.st_mode)


class DirState(object):
    """Record directory and metadata state for fast access.

    A dirstate is a specialised data structure for managing local working
    tree state information. Its not yet well defined whether it is platform
    specific, and if it is how we detect/parameterize that.

    Dirstates use the usual lock_write, lock_read and unlock mechanisms.
    Unlike most bzr disk formats, DirStates must be locked for reading, using
    lock_read.  (This is an os file lock internally.)  This is necessary
    because the file can be rewritten in place.

    DirStates must be explicitly written with save() to commit changes; just
    unlocking them does not write the changes to disk.
    """

    _kind_to_minikind = {
            'absent': 'a',
            'file': 'f',
            'directory': 'd',
            'relocated': 'r',
            'symlink': 'l',
            'tree-reference': 't',
        }
    _minikind_to_kind = {
            'a': 'absent',
            'f': 'file',
            'd': 'directory',
            'l':'symlink',
            'r': 'relocated',
            't': 'tree-reference',
        }
    _stat_to_minikind = {
        stat.S_IFDIR:'d',
        stat.S_IFREG:'f',
        stat.S_IFLNK:'l',
    }
    _to_yesno = {True:'y', False: 'n'} # TODO profile the performance gain
     # of using int conversion rather than a dict here. AND BLAME ANDREW IF
     # it is faster.

    # TODO: jam 20070221 Figure out what to do if we have a record that exceeds
    #       the BISECT_PAGE_SIZE. For now, we just have to make it large enough
    #       that we are sure a single record will always fit.
    BISECT_PAGE_SIZE = 4096

    NOT_IN_MEMORY = 0
    IN_MEMORY_UNMODIFIED = 1
    IN_MEMORY_MODIFIED = 2

    # A pack_stat (the x's) that is just noise and will never match the output
    # of base64 encode.
    NULLSTAT = 'x' * 32
    NULL_PARENT_DETAILS = ('a', '', 0, False, '')

    HEADER_FORMAT_2 = '#bazaar dirstate flat format 2\n'
    HEADER_FORMAT_3 = '#bazaar dirstate flat format 3\n'

    def __init__(self, path):
        """Create a  DirState object.

        :param path: The path at which the dirstate file on disk should live.
        """
        # _header_state and _dirblock_state represent the current state
        # of the dirstate metadata and the per-row data respectiely.
        # NOT_IN_MEMORY indicates that no data is in memory
        # IN_MEMORY_UNMODIFIED indicates that what we have in memory
        #   is the same as is on disk
        # IN_MEMORY_MODIFIED indicates that we have a modified version
        #   of what is on disk. 
        # In future we will add more granularity, for instance _dirblock_state
        # will probably support partially-in-memory as a separate variable,
        # allowing for partially-in-memory unmodified and partially-in-memory
        # modified states.
        self._header_state = DirState.NOT_IN_MEMORY
        self._dirblock_state = DirState.NOT_IN_MEMORY
        # If true, an error has been detected while updating the dirstate, and 
        # for safety we're not going to commit to disk.
        self._changes_aborted = False
        self._dirblocks = []
        self._ghosts = []
        self._parents = []
        self._state_file = None
        self._filename = path
        self._lock_token = None
        self._lock_state = None
        self._id_index = None
        # a map from packed_stat to sha's.
        self._packed_stat_index = None
        self._end_of_header = None
        self._cutoff_time = None
        self._split_path_cache = {}
        self._bisect_page_size = DirState.BISECT_PAGE_SIZE
        if 'hashcache' in debug.debug_flags:
            self._sha1_file = self._sha1_file_and_mutter
        else:
            self._sha1_file = osutils.sha_file_by_name
        # These two attributes provide a simple cache for lookups into the
        # dirstate in-memory vectors. By probing respectively for the last
        # block, and for the next entry, we save nearly 2 bisections per path
        # during commit.
        self._last_block_index = None
        self._last_entry_index = None

    def __repr__(self):
        return "%s(%r)" % \
            (self.__class__.__name__, self._filename)

    def add(self, path, file_id, kind, stat, fingerprint):
        """Add a path to be tracked.

        :param path: The path within the dirstate - '' is the root, 'foo' is the
            path foo within the root, 'foo/bar' is the path bar within foo 
            within the root.
        :param file_id: The file id of the path being added.
        :param kind: The kind of the path, as a string like 'file', 
            'directory', etc.
        :param stat: The output of os.lstat for the path.
        :param fingerprint: The sha value of the file,
            or the target of a symlink,
            or the referenced revision id for tree-references,
            or '' for directories.
        """
        # adding a file:
        # find the block its in. 
        # find the location in the block.
        # check its not there
        # add it.
        #------- copied from inventory.ensure_normalized_name - keep synced.
        # --- normalized_filename wants a unicode basename only, so get one.
        dirname, basename = osutils.split(path)
        # we dont import normalized_filename directly because we want to be
        # able to change the implementation at runtime for tests.
        norm_name, can_access = osutils.normalized_filename(basename)
        if norm_name != basename:
            if can_access:
                basename = norm_name
            else:
                raise errors.InvalidNormalization(path)
        # you should never have files called . or ..; just add the directory
        # in the parent, or according to the special treatment for the root
        if basename == '.' or basename == '..':
            raise errors.InvalidEntryName(path)
        # now that we've normalised, we need the correct utf8 path and 
        # dirname and basename elements. This single encode and split should be
        # faster than three separate encodes.
        utf8path = (dirname + '/' + basename).strip('/').encode('utf8')
        dirname, basename = osutils.split(utf8path)
        # uses __class__ for speed; the check is needed for safety
        if file_id.__class__ is not str:
            raise AssertionError(
                "must be a utf8 file_id not %s" % (type(file_id), ))
        # Make sure the file_id does not exist in this tree
        file_id_entry = self._get_entry(0, fileid_utf8=file_id)
        if file_id_entry != (None, None):
            path = osutils.pathjoin(file_id_entry[0][0], file_id_entry[0][1])
            kind = DirState._minikind_to_kind[file_id_entry[1][0][0]]
            info = '%s:%s' % (kind, path)
            raise errors.DuplicateFileId(file_id, info)
        first_key = (dirname, basename, '')
        block_index, present = self._find_block_index_from_key(first_key)
        if present:
            # check the path is not in the tree
            block = self._dirblocks[block_index][1]
            entry_index, _ = self._find_entry_index(first_key, block)
            while (entry_index < len(block) and 
                block[entry_index][0][0:2] == first_key[0:2]):
                if block[entry_index][1][0][0] not in 'ar':
                    # this path is in the dirstate in the current tree.
                    raise Exception, "adding already added path!"
                entry_index += 1
        else:
            # The block where we want to put the file is not present. But it
            # might be because the directory was empty, or not loaded yet. Look
            # for a parent entry, if not found, raise NotVersionedError
            parent_dir, parent_base = osutils.split(dirname)
            parent_block_idx, parent_entry_idx, _, parent_present = \
                self._get_block_entry_index(parent_dir, parent_base, 0)
            if not parent_present:
                raise errors.NotVersionedError(path, str(self))
            self._ensure_block(parent_block_idx, parent_entry_idx, dirname)
        block = self._dirblocks[block_index][1]
        entry_key = (dirname, basename, file_id)
        if stat is None:
            size = 0
            packed_stat = DirState.NULLSTAT
        else:
            size = stat.st_size
            packed_stat = pack_stat(stat)
        parent_info = self._empty_parent_info()
        minikind = DirState._kind_to_minikind[kind]
        if kind == 'file':
            entry_data = entry_key, [
                (minikind, fingerprint, size, False, packed_stat),
                ] + parent_info
        elif kind == 'directory':
            entry_data = entry_key, [
                (minikind, '', 0, False, packed_stat),
                ] + parent_info
        elif kind == 'symlink':
            entry_data = entry_key, [
                (minikind, fingerprint, size, False, packed_stat),
                ] + parent_info
        elif kind == 'tree-reference':
            entry_data = entry_key, [
                (minikind, fingerprint, 0, False, packed_stat),
                ] + parent_info
        else:
            raise errors.BzrError('unknown kind %r' % kind)
        entry_index, present = self._find_entry_index(entry_key, block)
        if not present:
            block.insert(entry_index, entry_data)
        else:
            if block[entry_index][1][0][0] != 'a':
                raise AssertionError(" %r(%r) already added" % (basename, file_id))
            block[entry_index][1][0] = entry_data[1][0]

        if kind == 'directory':
           # insert a new dirblock
           self._ensure_block(block_index, entry_index, utf8path)
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
        if self._id_index:
            self._id_index.setdefault(entry_key[2], set()).add(entry_key)

    def _bisect(self, paths):
        """Bisect through the disk structure for specific rows.

        :param paths: A list of paths to find
        :return: A dict mapping path => entries for found entries. Missing
                 entries will not be in the map.
                 The list is not sorted, and entries will be populated
                 based on when they were read.
        """
        self._requires_lock()
        # We need the file pointer to be right after the initial header block
        self._read_header_if_needed()
        # If _dirblock_state was in memory, we should just return info from
        # there, this function is only meant to handle when we want to read
        # part of the disk.
        if self._dirblock_state != DirState.NOT_IN_MEMORY:
            raise AssertionError("bad dirblock state %r" % self._dirblock_state)

        # The disk representation is generally info + '\0\n\0' at the end. But
        # for bisecting, it is easier to treat this as '\0' + info + '\0\n'
        # Because it means we can sync on the '\n'
        state_file = self._state_file
        file_size = os.fstat(state_file.fileno()).st_size
        # We end up with 2 extra fields, we should have a trailing '\n' to
        # ensure that we read the whole record, and we should have a precursur
        # '' which ensures that we start after the previous '\n'
        entry_field_count = self._fields_per_entry() + 1

        low = self._end_of_header
        high = file_size - 1 # Ignore the final '\0'
        # Map from (dir, name) => entry
        found = {}

        # Avoid infinite seeking
        max_count = 30*len(paths)
        count = 0
        # pending is a list of places to look.
        # each entry is a tuple of low, high, dir_names
        #   low -> the first byte offset to read (inclusive)
        #   high -> the last byte offset (inclusive)
        #   dir_names -> The list of (dir, name) pairs that should be found in
        #                the [low, high] range
        pending = [(low, high, paths)]

        page_size = self._bisect_page_size

        fields_to_entry = self._get_fields_to_entry()

        while pending:
            low, high, cur_files = pending.pop()

            if not cur_files or low >= high:
                # Nothing to find
                continue

            count += 1
            if count > max_count:
                raise errors.BzrError('Too many seeks, most likely a bug.')

            mid = max(low, (low+high-page_size)/2)

            state_file.seek(mid)
            # limit the read size, so we don't end up reading data that we have
            # already read.
            read_size = min(page_size, (high-mid)+1)
            block = state_file.read(read_size)

            start = mid
            entries = block.split('\n')

            if len(entries) < 2:
                # We didn't find a '\n', so we cannot have found any records.
                # So put this range back and try again. But we know we have to
                # increase the page size, because a single read did not contain
                # a record break (so records must be larger than page_size)
                page_size *= 2
                pending.append((low, high, cur_files))
                continue

            # Check the first and last entries, in case they are partial, or if
            # we don't care about the rest of this page
            first_entry_num = 0
            first_fields = entries[0].split('\0')
            if len(first_fields) < entry_field_count:
                # We didn't get the complete first entry
                # so move start, and grab the next, which
                # should be a full entry
                start += len(entries[0])+1
                first_fields = entries[1].split('\0')
                first_entry_num = 1

            if len(first_fields) <= 2:
                # We didn't even get a filename here... what do we do?
                # Try a large page size and repeat this query
                page_size *= 2
                pending.append((low, high, cur_files))
                continue
            else:
                # Find what entries we are looking for, which occur before and
                # after this first record.
                after = start
                if first_fields[1]:
                    first_path = first_fields[1] + '/' + first_fields[2]
                else:
                    first_path = first_fields[2]
                first_loc = _bisect_path_left(cur_files, first_path)

                # These exist before the current location
                pre = cur_files[:first_loc]
                # These occur after the current location, which may be in the
                # data we read, or might be after the last entry
                post = cur_files[first_loc:]

            if post and len(first_fields) >= entry_field_count:
                # We have files after the first entry

                # Parse the last entry
                last_entry_num = len(entries)-1
                last_fields = entries[last_entry_num].split('\0')
                if len(last_fields) < entry_field_count:
                    # The very last hunk was not complete,
                    # read the previous hunk
                    after = mid + len(block) - len(entries[-1])
                    last_entry_num -= 1
                    last_fields = entries[last_entry_num].split('\0')
                else:
                    after = mid + len(block)

                if last_fields[1]:
                    last_path = last_fields[1] + '/' + last_fields[2]
                else:
                    last_path = last_fields[2]
                last_loc = _bisect_path_right(post, last_path)

                middle_files = post[:last_loc]
                post = post[last_loc:]

                if middle_files:
                    # We have files that should occur in this block
                    # (>= first, <= last)
                    # Either we will find them here, or we can mark them as
                    # missing.

                    if middle_files[0] == first_path:
                        # We might need to go before this location
                        pre.append(first_path)
                    if middle_files[-1] == last_path:
                        post.insert(0, last_path)

                    # Find out what paths we have
                    paths = {first_path:[first_fields]}
                    # last_path might == first_path so we need to be
                    # careful if we should append rather than overwrite
                    if last_entry_num != first_entry_num:
                        paths.setdefault(last_path, []).append(last_fields)
                    for num in xrange(first_entry_num+1, last_entry_num):
                        # TODO: jam 20070223 We are already splitting here, so
                        #       shouldn't we just split the whole thing rather
                        #       than doing the split again in add_one_record?
                        fields = entries[num].split('\0')
                        if fields[1]:
                            path = fields[1] + '/' + fields[2]
                        else:
                            path = fields[2]
                        paths.setdefault(path, []).append(fields)

                    for path in middle_files:
                        for fields in paths.get(path, []):
                            # offset by 1 because of the opening '\0'
                            # consider changing fields_to_entry to avoid the
                            # extra list slice
                            entry = fields_to_entry(fields[1:])
                            found.setdefault(path, []).append(entry)

            # Now we have split up everything into pre, middle, and post, and
            # we have handled everything that fell in 'middle'.
            # We add 'post' first, so that we prefer to seek towards the
            # beginning, so that we will tend to go as early as we need, and
            # then only seek forward after that.
            if post:
                pending.append((after, high, post))
            if pre:
                pending.append((low, start-1, pre))

        # Consider that we may want to return the directory entries in sorted
        # order. For now, we just return them in whatever order we found them,
        # and leave it up to the caller if they care if it is ordered or not.
        return found

    def _bisect_dirblocks(self, dir_list):
        """Bisect through the disk structure to find entries in given dirs.

        _bisect_dirblocks is meant to find the contents of directories, which
        differs from _bisect, which only finds individual entries.

        :param dir_list: A sorted list of directory names ['', 'dir', 'foo'].
        :return: A map from dir => entries_for_dir
        """
        # TODO: jam 20070223 A lot of the bisecting logic could be shared
        #       between this and _bisect. It would require parameterizing the
        #       inner loop with a function, though. We should evaluate the
        #       performance difference.
        self._requires_lock()
        # We need the file pointer to be right after the initial header block
        self._read_header_if_needed()
        # If _dirblock_state was in memory, we should just return info from
        # there, this function is only meant to handle when we want to read
        # part of the disk.
        if self._dirblock_state != DirState.NOT_IN_MEMORY:
            raise AssertionError("bad dirblock state %r" % self._dirblock_state)
        # The disk representation is generally info + '\0\n\0' at the end. But
        # for bisecting, it is easier to treat this as '\0' + info + '\0\n'
        # Because it means we can sync on the '\n'
        state_file = self._state_file
        file_size = os.fstat(state_file.fileno()).st_size
        # We end up with 2 extra fields, we should have a trailing '\n' to
        # ensure that we read the whole record, and we should have a precursur
        # '' which ensures that we start after the previous '\n'
        entry_field_count = self._fields_per_entry() + 1

        low = self._end_of_header
        high = file_size - 1 # Ignore the final '\0'
        # Map from dir => entry
        found = {}

        # Avoid infinite seeking
        max_count = 30*len(dir_list)
        count = 0
        # pending is a list of places to look.
        # each entry is a tuple of low, high, dir_names
        #   low -> the first byte offset to read (inclusive)
        #   high -> the last byte offset (inclusive)
        #   dirs -> The list of directories that should be found in
        #                the [low, high] range
        pending = [(low, high, dir_list)]

        page_size = self._bisect_page_size

        fields_to_entry = self._get_fields_to_entry()

        while pending:
            low, high, cur_dirs = pending.pop()

            if not cur_dirs or low >= high:
                # Nothing to find
                continue

            count += 1
            if count > max_count:
                raise errors.BzrError('Too many seeks, most likely a bug.')

            mid = max(low, (low+high-page_size)/2)

            state_file.seek(mid)
            # limit the read size, so we don't end up reading data that we have
            # already read.
            read_size = min(page_size, (high-mid)+1)
            block = state_file.read(read_size)

            start = mid
            entries = block.split('\n')

            if len(entries) < 2:
                # We didn't find a '\n', so we cannot have found any records.
                # So put this range back and try again. But we know we have to
                # increase the page size, because a single read did not contain
                # a record break (so records must be larger than page_size)
                page_size *= 2
                pending.append((low, high, cur_dirs))
                continue

            # Check the first and last entries, in case they are partial, or if
            # we don't care about the rest of this page
            first_entry_num = 0
            first_fields = entries[0].split('\0')
            if len(first_fields) < entry_field_count:
                # We didn't get the complete first entry
                # so move start, and grab the next, which
                # should be a full entry
                start += len(entries[0])+1
                first_fields = entries[1].split('\0')
                first_entry_num = 1

            if len(first_fields) <= 1:
                # We didn't even get a dirname here... what do we do?
                # Try a large page size and repeat this query
                page_size *= 2
                pending.append((low, high, cur_dirs))
                continue
            else:
                # Find what entries we are looking for, which occur before and
                # after this first record.
                after = start
                first_dir = first_fields[1]
                first_loc = bisect.bisect_left(cur_dirs, first_dir)

                # These exist before the current location
                pre = cur_dirs[:first_loc]
                # These occur after the current location, which may be in the
                # data we read, or might be after the last entry
                post = cur_dirs[first_loc:]

            if post and len(first_fields) >= entry_field_count:
                # We have records to look at after the first entry

                # Parse the last entry
                last_entry_num = len(entries)-1
                last_fields = entries[last_entry_num].split('\0')
                if len(last_fields) < entry_field_count:
                    # The very last hunk was not complete,
                    # read the previous hunk
                    after = mid + len(block) - len(entries[-1])
                    last_entry_num -= 1
                    last_fields = entries[last_entry_num].split('\0')
                else:
                    after = mid + len(block)

                last_dir = last_fields[1]
                last_loc = bisect.bisect_right(post, last_dir)

                middle_files = post[:last_loc]
                post = post[last_loc:]

                if middle_files:
                    # We have files that should occur in this block
                    # (>= first, <= last)
                    # Either we will find them here, or we can mark them as
                    # missing.

                    if middle_files[0] == first_dir:
                        # We might need to go before this location
                        pre.append(first_dir)
                    if middle_files[-1] == last_dir:
                        post.insert(0, last_dir)

                    # Find out what paths we have
                    paths = {first_dir:[first_fields]}
                    # last_dir might == first_dir so we need to be
                    # careful if we should append rather than overwrite
                    if last_entry_num != first_entry_num:
                        paths.setdefault(last_dir, []).append(last_fields)
                    for num in xrange(first_entry_num+1, last_entry_num):
                        # TODO: jam 20070223 We are already splitting here, so
                        #       shouldn't we just split the whole thing rather
                        #       than doing the split again in add_one_record?
                        fields = entries[num].split('\0')
                        paths.setdefault(fields[1], []).append(fields)

                    for cur_dir in middle_files:
                        for fields in paths.get(cur_dir, []):
                            # offset by 1 because of the opening '\0'
                            # consider changing fields_to_entry to avoid the
                            # extra list slice
                            entry = fields_to_entry(fields[1:])
                            found.setdefault(cur_dir, []).append(entry)

            # Now we have split up everything into pre, middle, and post, and
            # we have handled everything that fell in 'middle'.
            # We add 'post' first, so that we prefer to seek towards the
            # beginning, so that we will tend to go as early as we need, and
            # then only seek forward after that.
            if post:
                pending.append((after, high, post))
            if pre:
                pending.append((low, start-1, pre))

        return found

    def _bisect_recursive(self, paths):
        """Bisect for entries for all paths and their children.

        This will use bisect to find all records for the supplied paths. It
        will then continue to bisect for any records which are marked as
        directories. (and renames?)

        :param paths: A sorted list of (dir, name) pairs
             eg: [('', 'a'), ('', 'f'), ('a/b', 'c')]
        :return: A dictionary mapping (dir, name, file_id) => [tree_info]
        """
        # Map from (dir, name, file_id) => [tree_info]
        found = {}

        found_dir_names = set()

        # Directories that have been read
        processed_dirs = set()
        # Get the ball rolling with the first bisect for all entries.
        newly_found = self._bisect(paths)

        while newly_found:
            # Directories that need to be read
            pending_dirs = set()
            paths_to_search = set()
            for entry_list in newly_found.itervalues():
                for dir_name_id, trees_info in entry_list:
                    found[dir_name_id] = trees_info
                    found_dir_names.add(dir_name_id[:2])
                    is_dir = False
                    for tree_info in trees_info:
                        minikind = tree_info[0]
                        if minikind == 'd':
                            if is_dir:
                                # We already processed this one as a directory,
                                # we don't need to do the extra work again.
                                continue
                            subdir, name, file_id = dir_name_id
                            path = osutils.pathjoin(subdir, name)
                            is_dir = True
                            if path not in processed_dirs:
                                pending_dirs.add(path)
                        elif minikind == 'r':
                            # Rename, we need to directly search the target
                            # which is contained in the fingerprint column
                            dir_name = osutils.split(tree_info[1])
                            if dir_name[0] in pending_dirs:
                                # This entry will be found in the dir search
                                continue
                            if dir_name not in found_dir_names:
                                paths_to_search.add(tree_info[1])
            # Now we have a list of paths to look for directly, and
            # directory blocks that need to be read.
            # newly_found is mixing the keys between (dir, name) and path
            # entries, but that is okay, because we only really care about the
            # targets.
            newly_found = self._bisect(sorted(paths_to_search))
            newly_found.update(self._bisect_dirblocks(sorted(pending_dirs)))
            processed_dirs.update(pending_dirs)
        return found

    def _discard_merge_parents(self):
        """Discard any parents trees beyond the first.
        
        Note that if this fails the dirstate is corrupted.

        After this function returns the dirstate contains 2 trees, neither of
        which are ghosted.
        """
        self._read_header_if_needed()
        parents = self.get_parent_ids()
        if len(parents) < 1:
            return
        # only require all dirblocks if we are doing a full-pass removal.
        self._read_dirblocks_if_needed()
        dead_patterns = set([('a', 'r'), ('a', 'a'), ('r', 'r'), ('r', 'a')])
        def iter_entries_removable():
            for block in self._dirblocks:
                deleted_positions = []
                for pos, entry in enumerate(block[1]):
                    yield entry
                    if (entry[1][0][0], entry[1][1][0]) in dead_patterns:
                        deleted_positions.append(pos)
                if deleted_positions:
                    if len(deleted_positions) == len(block[1]):
                        del block[1][:]
                    else:
                        for pos in reversed(deleted_positions):
                            del block[1][pos]
        # if the first parent is a ghost:
        if parents[0] in self.get_ghosts():
            empty_parent = [DirState.NULL_PARENT_DETAILS]
            for entry in iter_entries_removable():
                entry[1][1:] = empty_parent
        else:
            for entry in iter_entries_removable():
                del entry[1][2:]

        self._ghosts = []
        self._parents = [parents[0]]
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
        self._header_state = DirState.IN_MEMORY_MODIFIED

    def _empty_parent_info(self):
        return [DirState.NULL_PARENT_DETAILS] * (len(self._parents) -
                                                    len(self._ghosts))

    def _ensure_block(self, parent_block_index, parent_row_index, dirname):
        """Ensure a block for dirname exists.

        This function exists to let callers which know that there is a
        directory dirname ensure that the block for it exists. This block can
        fail to exist because of demand loading, or because a directory had no
        children. In either case it is not an error. It is however an error to
        call this if there is no parent entry for the directory, and thus the
        function requires the coordinates of such an entry to be provided.

        The root row is special cased and can be indicated with a parent block
        and row index of -1

        :param parent_block_index: The index of the block in which dirname's row
            exists.
        :param parent_row_index: The index in the parent block where the row
            exists.
        :param dirname: The utf8 dirname to ensure there is a block for.
        :return: The index for the block.
        """
        if dirname == '' and parent_row_index == 0 and parent_block_index == 0:
            # This is the signature of the root row, and the
            # contents-of-root row is always index 1
            return 1
        # the basename of the directory must be the end of its full name.
        if not (parent_block_index == -1 and
            parent_block_index == -1 and dirname == ''):
            if not dirname.endswith(
                    self._dirblocks[parent_block_index][1][parent_row_index][0][1]):
                raise AssertionError("bad dirname %r" % dirname)
        block_index, present = self._find_block_index_from_key((dirname, '', ''))
        if not present:
            ## In future, when doing partial parsing, this should load and 
            # populate the entire block.
            self._dirblocks.insert(block_index, (dirname, []))
        return block_index

    def _entries_to_current_state(self, new_entries):
        """Load new_entries into self.dirblocks.

        Process new_entries into the current state object, making them the active
        state.  The entries are grouped together by directory to form dirblocks.

        :param new_entries: A sorted list of entries. This function does not sort
            to prevent unneeded overhead when callers have a sorted list already.
        :return: Nothing.
        """
        if new_entries[0][0][0:2] != ('', ''):
            raise AssertionError(
                "Missing root row %r" % (new_entries[0][0],))
        # The two blocks here are deliberate: the root block and the 
        # contents-of-root block.
        self._dirblocks = [('', []), ('', [])]
        current_block = self._dirblocks[0][1]
        current_dirname = ''
        root_key = ('', '')
        append_entry = current_block.append
        for entry in new_entries:
            if entry[0][0] != current_dirname:
                # new block - different dirname
                current_block = []
                current_dirname = entry[0][0]
                self._dirblocks.append((current_dirname, current_block))
                append_entry = current_block.append
            # append the entry to the current block
            append_entry(entry)
        self._split_root_dirblock_into_contents()

    def _split_root_dirblock_into_contents(self):
        """Split the root dirblocks into root and contents-of-root.

        After parsing by path, we end up with root entries and contents-of-root
        entries in the same block. This loop splits them out again.
        """
        # The above loop leaves the "root block" entries mixed with the
        # "contents-of-root block". But we don't want an if check on
        # all entries, so instead we just fix it up here.
        if self._dirblocks[1] != ('', []):
            raise ValueError("bad dirblock start %r" % (self._dirblocks[1],))
        root_block = []
        contents_of_root_block = []
        for entry in self._dirblocks[0][1]:
            if not entry[0][1]: # This is a root entry
                root_block.append(entry)
            else:
                contents_of_root_block.append(entry)
        self._dirblocks[0] = ('', root_block)
        self._dirblocks[1] = ('', contents_of_root_block)

    def _entry_to_line(self, entry):
        """Serialize entry to a NULL delimited line ready for _get_output_lines.

        :param entry: An entry_tuple as defined in the module docstring.
        """
        entire_entry = list(entry[0])
        for tree_number, tree_data in enumerate(entry[1]):
            # (minikind, fingerprint, size, executable, tree_specific_string)
            entire_entry.extend(tree_data)
            # 3 for the key, 5 for the fields per tree.
            tree_offset = 3 + tree_number * 5
            # minikind
            entire_entry[tree_offset + 0] = tree_data[0]
            # size
            entire_entry[tree_offset + 2] = str(tree_data[2])
            # executable
            entire_entry[tree_offset + 3] = DirState._to_yesno[tree_data[3]]
        return '\0'.join(entire_entry)

    def _fields_per_entry(self):
        """How many null separated fields should be in each entry row.

        Each line now has an extra '\n' field which is not used
        so we just skip over it
        entry size:
            3 fields for the key
            + number of fields per tree_data (5) * tree count
            + newline
         """
        tree_count = 1 + self._num_present_parents()
        return 3 + 5 * tree_count + 1

    def _find_block(self, key, add_if_missing=False):
        """Return the block that key should be present in.

        :param key: A dirstate entry key.
        :return: The block tuple.
        """
        block_index, present = self._find_block_index_from_key(key)
        if not present:
            if not add_if_missing:
                # check to see if key is versioned itself - we might want to
                # add it anyway, because dirs with no entries dont get a
                # dirblock at parse time.
                # This is an uncommon branch to take: most dirs have children,
                # and most code works with versioned paths.
                parent_base, parent_name = osutils.split(key[0])
                if not self._get_block_entry_index(parent_base, parent_name, 0)[3]:
                    # some parent path has not been added - its an error to add
                    # this child
                    raise errors.NotVersionedError(key[0:2], str(self))
            self._dirblocks.insert(block_index, (key[0], []))
        return self._dirblocks[block_index]

    def _find_block_index_from_key(self, key):
        """Find the dirblock index for a key.

        :return: The block index, True if the block for the key is present.
        """
        if key[0:2] == ('', ''):
            return 0, True
        try:
            if (self._last_block_index is not None and
                self._dirblocks[self._last_block_index][0] == key[0]):
                return self._last_block_index, True
        except IndexError:
            pass
        block_index = bisect_dirblock(self._dirblocks, key[0], 1,
                                      cache=self._split_path_cache)
        # _right returns one-past-where-key is so we have to subtract
        # one to use it. we use _right here because there are two
        # '' blocks - the root, and the contents of root
        # we always have a minimum of 2 in self._dirblocks: root and
        # root-contents, and for '', we get 2 back, so this is 
        # simple and correct:
        present = (block_index < len(self._dirblocks) and
            self._dirblocks[block_index][0] == key[0])
        self._last_block_index = block_index
        # Reset the entry index cache to the beginning of the block.
        self._last_entry_index = -1
        return block_index, present

    def _find_entry_index(self, key, block):
        """Find the entry index for a key in a block.

        :return: The entry index, True if the entry for the key is present.
        """
        len_block = len(block)
        try:
            if self._last_entry_index is not None:
                # mini-bisect here.
                entry_index = self._last_entry_index + 1
                # A hit is when the key is after the last slot, and before or
                # equal to the next slot.
                if ((entry_index > 0 and block[entry_index - 1][0] < key) and
                    key <= block[entry_index][0]):
                    self._last_entry_index = entry_index
                    present = (block[entry_index][0] == key)
                    return entry_index, present
        except IndexError:
            pass
        entry_index = bisect.bisect_left(block, (key, []))
        present = (entry_index < len_block and
            block[entry_index][0] == key)
        self._last_entry_index = entry_index
        return entry_index, present

    @staticmethod
    def from_tree(tree, dir_state_filename):
        """Create a dirstate from a bzr Tree.

        :param tree: The tree which should provide parent information and
            inventory ids.
        :return: a DirState object which is currently locked for writing.
            (it was locked by DirState.initialize)
        """
        result = DirState.initialize(dir_state_filename)
        try:
            tree.lock_read()
            try:
                parent_ids = tree.get_parent_ids()
                num_parents = len(parent_ids)
                parent_trees = []
                for parent_id in parent_ids:
                    parent_tree = tree.branch.repository.revision_tree(parent_id)
                    parent_trees.append((parent_id, parent_tree))
                    parent_tree.lock_read()
                result.set_parent_trees(parent_trees, [])
                result.set_state_from_inventory(tree.inventory)
            finally:
                for revid, parent_tree in parent_trees:
                    parent_tree.unlock()
                tree.unlock()
        except:
            # The caller won't have a chance to unlock this, so make sure we
            # cleanup ourselves
            result.unlock()
            raise
        return result

    def update_by_delta(self, delta):
        """Apply an inventory delta to the dirstate for tree 0

        :param delta: An inventory delta.  See Inventory.apply_delta for
            details.
        """
        self._read_dirblocks_if_needed()
        insertions = {}
        removals = {}
        for old_path, new_path, file_id, inv_entry in sorted(delta, reverse=True):
            if (file_id in insertions) or (file_id in removals):
                raise AssertionError("repeated file id in delta %r" % (file_id,))
            if old_path is not None:
                old_path = old_path.encode('utf-8')
                removals[file_id] = old_path
            if new_path is not None:
                new_path = new_path.encode('utf-8')
                dirname, basename = osutils.split(new_path)
                key = (dirname, basename, file_id)
                minikind = DirState._kind_to_minikind[inv_entry.kind]
                if minikind == 't':
                    fingerprint = inv_entry.reference_revision
                else:
                    fingerprint = ''
                insertions[file_id] = (key, minikind, inv_entry.executable,
                                       fingerprint, new_path)
            if None not in (old_path, new_path):
                for child in self._iter_child_entries(0, old_path):
                    if child[0][2] in insertions or child[0][2] in removals:
                        continue
                    child_dirname = child[0][0]
                    child_basename = child[0][1]
                    minikind = child[1][0][0]
                    fingerprint = child[1][0][4]
                    executable = child[1][0][3]
                    old_child_path = osutils.pathjoin(child[0][0],
                                                      child[0][1])
                    removals[child[0][2]] = old_child_path
                    child_suffix = child_dirname[len(old_path):]
                    new_child_dirname = (new_path + child_suffix)
                    key = (new_child_dirname, child_basename, child[0][2])
                    new_child_path = os.path.join(new_child_dirname,
                                                  child_basename)
                    insertions[child[0][2]] = (key, minikind, executable,
                                               fingerprint, new_child_path)
        self._apply_removals(removals.values())
        self._apply_insertions(insertions.values())

    def _apply_removals(self, removals):
        for path in sorted(removals, reverse=True):
            dirname, basename = osutils.split(path)
            block_i, entry_i, d_present, f_present = \
                self._get_block_entry_index(dirname, basename, 0)
            entry = self._dirblocks[block_i][1][entry_i]
            self._make_absent(entry)

    def _apply_insertions(self, adds):
        for key, minikind, executable, fingerprint, path_utf8 in sorted(adds):
            self.update_minimal(key, minikind, executable, fingerprint,
                                path_utf8=path_utf8)

    def update_basis_by_delta(self, delta, new_revid):
        """Update the parents of this tree after a commit.

        This gives the tree one parent, with revision id new_revid. The
        inventory delta is applied to the current basis tree to generate the
        inventory for the parent new_revid, and all other parent trees are
        discarded.

        Note that an exception during the operation of this method will leave
        the dirstate in a corrupt state where it should not be saved.

        Finally, we expect all changes to be synchronising the basis tree with
        the working tree.

        :param new_revid: The new revision id for the trees parent.
        :param delta: An inventory delta (see apply_inventory_delta) describing
            the changes from the current left most parent revision to new_revid.
        """
        self._read_dirblocks_if_needed()
        self._discard_merge_parents()
        if self._ghosts != []:
            raise NotImplementedError(self.update_basis_by_delta)
        if len(self._parents) == 0:
            # setup a blank tree, the most simple way.
            empty_parent = DirState.NULL_PARENT_DETAILS
            for entry in self._iter_entries():
                entry[1].append(empty_parent)
            self._parents.append(new_revid)

        self._parents[0] = new_revid

        delta = sorted(delta, reverse=True)
        adds = []
        changes = []
        deletes = []
        # The paths this function accepts are unicode and must be encoded as we
        # go.
        encode = cache_utf8.encode
        inv_to_entry = self._inv_entry_to_details
        # delta is now (deletes, changes), (adds) in reverse lexographical
        # order.
        # deletes in reverse lexographic order are safe to process in situ.
        # renames are not, as a rename from any path could go to a path
        # lexographically lower, so we transform renames into delete, add pairs,
        # expanding them recursively as needed.
        # At the same time, to reduce interface friction we convert the input
        # inventory entries to dirstate.
        root_only = ('', '')
        for old_path, new_path, file_id, inv_entry in delta:
            if old_path is None:
                adds.append((None, encode(new_path), file_id,
                    inv_to_entry(inv_entry), True))
            elif new_path is None:
                deletes.append((encode(old_path), None, file_id, None, True))
            elif (old_path, new_path) != root_only:
                # Renames:
                # Because renames must preserve their children we must have
                # processed all relocations and removes before hand. The sort
                # order ensures we've examined the child paths, but we also
                # have to execute the removals, or the split to an add/delete
                # pair will result in the deleted item being reinserted, or
                # renamed items being reinserted twice - and possibly at the
                # wrong place. Splitting into a delete/add pair also simplifies
                # the handling of entries with ('f', ...), ('r' ...) because
                # the target of the 'r' is old_path here, and we add that to
                # deletes, meaning that the add handler does not need to check
                # for 'r' items on every pass.
                self._update_basis_apply_deletes(deletes)
                deletes = []
                new_path_utf8 = encode(new_path)
                # Split into an add/delete pair recursively.
                adds.append((None, new_path_utf8, file_id,
                    inv_to_entry(inv_entry), False))
                # Expunge deletes that we've seen so that deleted/renamed
                # children of a rename directory are handled correctly.
                new_deletes = reversed(list(self._iter_child_entries(1,
                    encode(old_path))))
                # Remove the current contents of the tree at orig_path, and
                # reinsert at the correct new path.
                for entry in new_deletes:
                    if entry[0][0]:
                        source_path = entry[0][0] + '/' + entry[0][1]
                    else:
                        source_path = entry[0][1]
                    if new_path_utf8:
                        target_path = new_path_utf8 + source_path[len(old_path):]
                    else:
                        if old_path == '':
                            raise AssertionError("cannot rename directory to"
                                " itself")
                        target_path = source_path[len(old_path) + 1:]
                    adds.append((None, target_path, entry[0][2], entry[1][1], False))
                    deletes.append(
                        (source_path, target_path, entry[0][2], None, False))
                deletes.append(
                    (encode(old_path), new_path, file_id, None, False))
            else:
                # changes to just the root should not require remove/insertion
                # of everything.
                changes.append((encode(old_path), encode(new_path), file_id,
                    inv_to_entry(inv_entry)))

        # Finish expunging deletes/first half of renames.
        self._update_basis_apply_deletes(deletes)
        # Reinstate second half of renames and new paths.
        self._update_basis_apply_adds(adds)
        # Apply in-situ changes.
        self._update_basis_apply_changes(changes)

        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
        self._header_state = DirState.IN_MEMORY_MODIFIED
        self._id_index = None
        return

    def _update_basis_apply_adds(self, adds):
        """Apply a sequence of adds to tree 1 during update_basis_by_delta.

        They may be adds, or renames that have been split into add/delete
        pairs.

        :param adds: A sequence of adds. Each add is a tuple:
            (None, new_path_utf8, file_id, (entry_details), real_add). real_add
            is False when the add is the second half of a remove-and-reinsert
            pair created to handle renames and deletes.
        """
        # Adds are accumulated partly from renames, so can be in any input
        # order - sort it.
        adds.sort()
        # adds is now in lexographic order, which places all parents before
        # their children, so we can process it linearly.
        absent = 'ar'
        for old_path, new_path, file_id, new_details, real_add in adds:
            # the entry for this file_id must be in tree 0.
            entry = self._get_entry(0, file_id, new_path)
            if entry[0] is None or entry[0][2] != file_id:
                self._changes_aborted = True
                raise errors.InconsistentDelta(new_path, file_id,
                    'working tree does not contain new entry')
            if real_add and entry[1][1][0] not in absent:
                self._changes_aborted = True
                raise errors.InconsistentDelta(new_path, file_id,
                    'The entry was considered to be a genuinely new record,'
                    ' but there was already an old record for it.')
            # We don't need to update the target of an 'r' because the handling
            # of renames turns all 'r' situations into a delete at the original
            # location.
            entry[1][1] = new_details

    def _update_basis_apply_changes(self, changes):
        """Apply a sequence of changes to tree 1 during update_basis_by_delta.

        :param adds: A sequence of changes. Each change is a tuple:
            (path_utf8, path_utf8, file_id, (entry_details))
        """
        absent = 'ar'
        for old_path, new_path, file_id, new_details in changes:
            # the entry for this file_id must be in tree 0.
            entry = self._get_entry(0, file_id, new_path)
            if entry[0] is None or entry[0][2] != file_id:
                self._changes_aborted = True
                raise errors.InconsistentDelta(new_path, file_id,
                    'working tree does not contain new entry')
            if (entry[1][0][0] in absent or
                entry[1][1][0] in absent):
                self._changes_aborted = True
                raise errors.InconsistentDelta(new_path, file_id,
                    'changed considered absent')
            entry[1][1] = new_details

    def _update_basis_apply_deletes(self, deletes):
        """Apply a sequence of deletes to tree 1 during update_basis_by_delta.

        They may be deletes, or renames that have been split into add/delete
        pairs.

        :param deletes: A sequence of deletes. Each delete is a tuple:
            (old_path_utf8, new_path_utf8, file_id, None, real_delete).
            real_delete is True when the desired outcome is an actual deletion
            rather than the rename handling logic temporarily deleting a path
            during the replacement of a parent.
        """
        null = DirState.NULL_PARENT_DETAILS
        for old_path, new_path, file_id, _, real_delete in deletes:
            if real_delete != (new_path is None):
                raise AssertionError("bad delete delta")
            # the entry for this file_id must be in tree 1.
            dirname, basename = osutils.split(old_path)
            block_index, entry_index, dir_present, file_present = \
                self._get_block_entry_index(dirname, basename, 1)
            if not file_present:
                self._changes_aborted = True
                raise errors.InconsistentDelta(old_path, file_id,
                    'basis tree does not contain removed entry')
            entry = self._dirblocks[block_index][1][entry_index]
            if entry[0][2] != file_id:
                self._changes_aborted = True
                raise errors.InconsistentDelta(old_path, file_id,
                    'mismatched file_id in tree 1')
            if real_delete:
                if entry[1][0][0] != 'a':
                    self._changes_aborted = True
                    raise errors.InconsistentDelta(old_path, file_id,
                            'This was marked as a real delete, but the WT state'
                            ' claims that it still exists and is versioned.')
                del self._dirblocks[block_index][1][entry_index]
            else:
                if entry[1][0][0] == 'a':
                    self._changes_aborted = True
                    raise errors.InconsistentDelta(old_path, file_id,
                        'The entry was considered a rename, but the source path'
                        ' is marked as absent.')
                    # For whatever reason, we were asked to rename an entry
                    # that was originally marked as deleted. This could be
                    # because we are renaming the parent directory, and the WT
                    # current state has the file marked as deleted.
                elif entry[1][0][0] == 'r':
                    # implement the rename
                    del self._dirblocks[block_index][1][entry_index]
                else:
                    # it is being resurrected here, so blank it out temporarily.
                    self._dirblocks[block_index][1][entry_index][1][1] = null

    def update_entry(self, entry, abspath, stat_value,
                     _stat_to_minikind=_stat_to_minikind,
                     _pack_stat=pack_stat):
        """Update the entry based on what is actually on disk.

        :param entry: This is the dirblock entry for the file in question.
        :param abspath: The path on disk for this file.
        :param stat_value: (optional) if we already have done a stat on the
            file, re-use it.
        :return: The sha1 hexdigest of the file (40 bytes) or link target of a
                symlink.
        """
        try:
            minikind = _stat_to_minikind[stat_value.st_mode & 0170000]
        except KeyError:
            # Unhandled kind
            return None
        packed_stat = _pack_stat(stat_value)
        (saved_minikind, saved_link_or_sha1, saved_file_size,
         saved_executable, saved_packed_stat) = entry[1][0]

        if (minikind == saved_minikind
            and packed_stat == saved_packed_stat):
            # The stat hasn't changed since we saved, so we can re-use the
            # saved sha hash.
            if minikind == 'd':
                return None

            # size should also be in packed_stat
            if saved_file_size == stat_value.st_size:
                return saved_link_or_sha1

        # If we have gotten this far, that means that we need to actually
        # process this entry.
        link_or_sha1 = None
        if minikind == 'f':
            link_or_sha1 = self._sha1_file(abspath)
            executable = self._is_executable(stat_value.st_mode,
                                             saved_executable)
            if self._cutoff_time is None:
                self._sha_cutoff_time()
            if (stat_value.st_mtime < self._cutoff_time
                and stat_value.st_ctime < self._cutoff_time):
                entry[1][0] = ('f', link_or_sha1, stat_value.st_size,
                               executable, packed_stat)
            else:
                entry[1][0] = ('f', '', stat_value.st_size,
                               executable, DirState.NULLSTAT)
        elif minikind == 'd':
            link_or_sha1 = None
            entry[1][0] = ('d', '', 0, False, packed_stat)
            if saved_minikind != 'd':
                # This changed from something into a directory. Make sure we
                # have a directory block for it. This doesn't happen very
                # often, so this doesn't have to be super fast.
                block_index, entry_index, dir_present, file_present = \
                    self._get_block_entry_index(entry[0][0], entry[0][1], 0)
                self._ensure_block(block_index, entry_index,
                                   osutils.pathjoin(entry[0][0], entry[0][1]))
        elif minikind == 'l':
            link_or_sha1 = self._read_link(abspath, saved_link_or_sha1)
            if self._cutoff_time is None:
                self._sha_cutoff_time()
            if (stat_value.st_mtime < self._cutoff_time
                and stat_value.st_ctime < self._cutoff_time):
                entry[1][0] = ('l', link_or_sha1, stat_value.st_size,
                               False, packed_stat)
            else:
                entry[1][0] = ('l', '', stat_value.st_size,
                               False, DirState.NULLSTAT)
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
        return link_or_sha1

    def _sha_cutoff_time(self):
        """Return cutoff time.

        Files modified more recently than this time are at risk of being
        undetectably modified and so can't be cached.
        """
        # Cache the cutoff time as long as we hold a lock.
        # time.time() isn't super expensive (approx 3.38us), but
        # when you call it 50,000 times it adds up.
        # For comparison, os.lstat() costs 7.2us if it is hot.
        self._cutoff_time = int(time.time()) - 3
        return self._cutoff_time

    def _lstat(self, abspath, entry):
        """Return the os.lstat value for this path."""
        return os.lstat(abspath)

    def _sha1_file_and_mutter(self, abspath):
        # when -Dhashcache is turned on, this is monkey-patched in to log
        # file reads
        trace.mutter("dirstate sha1 " + abspath)
        return osutils.sha_file_by_name(abspath)

    def _is_executable(self, mode, old_executable):
        """Is this file executable?"""
        return bool(S_IEXEC & mode)

    def _is_executable_win32(self, mode, old_executable):
        """On win32 the executable bit is stored in the dirstate."""
        return old_executable

    if sys.platform == 'win32':
        _is_executable = _is_executable_win32

    def _read_link(self, abspath, old_link):
        """Read the target of a symlink"""
        # TODO: jam 200700301 On Win32, this could just return the value
        #       already in memory. However, this really needs to be done at a
        #       higher level, because there either won't be anything on disk,
        #       or the thing on disk will be a file.
        return os.readlink(abspath)

    def get_ghosts(self):
        """Return a list of the parent tree revision ids that are ghosts."""
        self._read_header_if_needed()
        return self._ghosts

    def get_lines(self):
        """Serialise the entire dirstate to a sequence of lines."""
        if (self._header_state == DirState.IN_MEMORY_UNMODIFIED and
            self._dirblock_state == DirState.IN_MEMORY_UNMODIFIED):
            # read whats on disk.
            self._state_file.seek(0)
            return self._state_file.readlines()
        lines = []
        lines.append(self._get_parents_line(self.get_parent_ids()))
        lines.append(self._get_ghosts_line(self._ghosts))
        # append the root line which is special cased
        lines.extend(map(self._entry_to_line, self._iter_entries()))
        return self._get_output_lines(lines)

    def _get_ghosts_line(self, ghost_ids):
        """Create a line for the state file for ghost information."""
        return '\0'.join([str(len(ghost_ids))] + ghost_ids)

    def _get_parents_line(self, parent_ids):
        """Create a line for the state file for parents information."""
        return '\0'.join([str(len(parent_ids))] + parent_ids)

    def _get_fields_to_entry(self):
        """Get a function which converts entry fields into a entry record.

        This handles size and executable, as well as parent records.

        :return: A function which takes a list of fields, and returns an
            appropriate record for storing in memory.
        """
        # This is intentionally unrolled for performance
        num_present_parents = self._num_present_parents()
        if num_present_parents == 0:
            def fields_to_entry_0_parents(fields, _int=int):
                path_name_file_id_key = (fields[0], fields[1], fields[2])
                return (path_name_file_id_key, [
                    ( # Current tree
                        fields[3],                # minikind
                        fields[4],                # fingerprint
                        _int(fields[5]),          # size
                        fields[6] == 'y',         # executable
                        fields[7],                # packed_stat or revision_id
                    )])
            return fields_to_entry_0_parents
        elif num_present_parents == 1:
            def fields_to_entry_1_parent(fields, _int=int):
                path_name_file_id_key = (fields[0], fields[1], fields[2])
                return (path_name_file_id_key, [
                    ( # Current tree
                        fields[3],                # minikind
                        fields[4],                # fingerprint
                        _int(fields[5]),          # size
                        fields[6] == 'y',         # executable
                        fields[7],                # packed_stat or revision_id
                    ),
                    ( # Parent 1
                        fields[8],                # minikind
                        fields[9],                # fingerprint
                        _int(fields[10]),         # size
                        fields[11] == 'y',        # executable
                        fields[12],               # packed_stat or revision_id
                    ),
                    ])
            return fields_to_entry_1_parent
        elif num_present_parents == 2:
            def fields_to_entry_2_parents(fields, _int=int):
                path_name_file_id_key = (fields[0], fields[1], fields[2])
                return (path_name_file_id_key, [
                    ( # Current tree
                        fields[3],                # minikind
                        fields[4],                # fingerprint
                        _int(fields[5]),          # size
                        fields[6] == 'y',         # executable
                        fields[7],                # packed_stat or revision_id
                    ),
                    ( # Parent 1
                        fields[8],                # minikind
                        fields[9],                # fingerprint
                        _int(fields[10]),         # size
                        fields[11] == 'y',        # executable
                        fields[12],               # packed_stat or revision_id
                    ),
                    ( # Parent 2
                        fields[13],               # minikind
                        fields[14],               # fingerprint
                        _int(fields[15]),         # size
                        fields[16] == 'y',        # executable
                        fields[17],               # packed_stat or revision_id
                    ),
                    ])
            return fields_to_entry_2_parents
        else:
            def fields_to_entry_n_parents(fields, _int=int):
                path_name_file_id_key = (fields[0], fields[1], fields[2])
                trees = [(fields[cur],                # minikind
                          fields[cur+1],              # fingerprint
                          _int(fields[cur+2]),        # size
                          fields[cur+3] == 'y',       # executable
                          fields[cur+4],              # stat or revision_id
                         ) for cur in xrange(3, len(fields)-1, 5)]
                return path_name_file_id_key, trees
            return fields_to_entry_n_parents

    def get_parent_ids(self):
        """Return a list of the parent tree ids for the directory state."""
        self._read_header_if_needed()
        return list(self._parents)

    def _get_block_entry_index(self, dirname, basename, tree_index):
        """Get the coordinates for a path in the state structure.

        :param dirname: The utf8 dirname to lookup.
        :param basename: The utf8 basename to lookup.
        :param tree_index: The index of the tree for which this lookup should
            be attempted.
        :return: A tuple describing where the path is located, or should be
            inserted. The tuple contains four fields: the block index, the row
            index, the directory is present (boolean), the entire path is
            present (boolean).  There is no guarantee that either
            coordinate is currently reachable unless the found field for it is
            True. For instance, a directory not present in the searched tree
            may be returned with a value one greater than the current highest
            block offset. The directory present field will always be True when
            the path present field is True. The directory present field does
            NOT indicate that the directory is present in the searched tree,
            rather it indicates that there are at least some files in some
            tree present there.
        """
        self._read_dirblocks_if_needed()
        key = dirname, basename, ''
        block_index, present = self._find_block_index_from_key(key)
        if not present:
            # no such directory - return the dir index and 0 for the row.
            return block_index, 0, False, False
        block = self._dirblocks[block_index][1] # access the entries only
        entry_index, present = self._find_entry_index(key, block)
        # linear search through entries at this path to find the one
        # requested.
        while entry_index < len(block) and block[entry_index][0][1] == basename:
            if block[entry_index][1][tree_index][0] not in 'ar':
                # neither absent or relocated
                return block_index, entry_index, True, True
            entry_index += 1
        return block_index, entry_index, True, False

    def _get_entry(self, tree_index, fileid_utf8=None, path_utf8=None):
        """Get the dirstate entry for path in tree tree_index.

        If either file_id or path is supplied, it is used as the key to lookup.
        If both are supplied, the fastest lookup is used, and an error is
        raised if they do not both point at the same row.

        :param tree_index: The index of the tree we wish to locate this path
            in. If the path is present in that tree, the entry containing its
            details is returned, otherwise (None, None) is returned
            0 is the working tree, higher indexes are successive parent
            trees.
        :param fileid_utf8: A utf8 file_id to look up.
        :param path_utf8: An utf8 path to be looked up.
        :return: The dirstate entry tuple for path, or (None, None)
        """
        self._read_dirblocks_if_needed()
        if path_utf8 is not None:
            if type(path_utf8) is not str:
                raise AssertionError('path_utf8 is not a str: %s %s'
                    % (type(path_utf8), path_utf8))
            # path lookups are faster
            dirname, basename = osutils.split(path_utf8)
            block_index, entry_index, dir_present, file_present = \
                self._get_block_entry_index(dirname, basename, tree_index)
            if not file_present:
                return None, None
            entry = self._dirblocks[block_index][1][entry_index]
            if not (entry[0][2] and entry[1][tree_index][0] not in ('a', 'r')):
                raise AssertionError('unversioned entry?')
            if fileid_utf8:
                if entry[0][2] != fileid_utf8:
                    self._changes_aborted = True
                    raise errors.BzrError('integrity error ? : mismatching'
                                          ' tree_index, file_id and path')
            return entry
        else:
            possible_keys = self._get_id_index().get(fileid_utf8, None)
            if not possible_keys:
                return None, None
            for key in possible_keys:
                block_index, present = \
                    self._find_block_index_from_key(key)
                # strange, probably indicates an out of date
                # id index - for now, allow this.
                if not present:
                    continue
                # WARNING: DO not change this code to use _get_block_entry_index
                # as that function is not suitable: it does not use the key
                # to lookup, and thus the wrong coordinates are returned.
                block = self._dirblocks[block_index][1]
                entry_index, present = self._find_entry_index(key, block)
                if present:
                    entry = self._dirblocks[block_index][1][entry_index]
                    if entry[1][tree_index][0] in 'fdlt':
                        # this is the result we are looking for: the  
                        # real home of this file_id in this tree.
                        return entry
                    if entry[1][tree_index][0] == 'a':
                        # there is no home for this entry in this tree
                        return None, None
                    if entry[1][tree_index][0] != 'r':
                        raise AssertionError(
                            "entry %r has invalid minikind %r for tree %r" \
                            % (entry,
                               entry[1][tree_index][0],
                               tree_index))
                    real_path = entry[1][tree_index][1]
                    return self._get_entry(tree_index, fileid_utf8=fileid_utf8,
                        path_utf8=real_path)
            return None, None

    @classmethod
    def initialize(cls, path):
        """Create a new dirstate on path.

        The new dirstate will be an empty tree - that is it has no parents,
        and only a root node - which has id ROOT_ID.

        :param path: The name of the file for the dirstate.
        :return: A write-locked DirState object.
        """
        # This constructs a new DirState object on a path, sets the _state_file
        # to a new empty file for that path. It then calls _set_data() with our
        # stock empty dirstate information - a root with ROOT_ID, no children,
        # and no parents. Finally it calls save() to ensure that this data will
        # persist.
        result = cls(path)
        # root dir and root dir contents with no children.
        empty_tree_dirblocks = [('', []), ('', [])]
        # a new root directory, with a NULLSTAT.
        empty_tree_dirblocks[0][1].append(
            (('', '', inventory.ROOT_ID), [
                ('d', '', 0, False, DirState.NULLSTAT),
            ]))
        result.lock_write()
        try:
            result._set_data([], empty_tree_dirblocks)
            result.save()
        except:
            result.unlock()
            raise
        return result

    def _inv_entry_to_details(self, inv_entry):
        """Convert an inventory entry (from a revision tree) to state details.

        :param inv_entry: An inventory entry whose sha1 and link targets can be
            relied upon, and which has a revision set.
        :return: A details tuple - the details for a single tree at a path +
            id.
        """
        kind = inv_entry.kind
        minikind = DirState._kind_to_minikind[kind]
        tree_data = inv_entry.revision
        if kind == 'directory':
            fingerprint = ''
            size = 0
            executable = False
        elif kind == 'symlink':
            fingerprint = inv_entry.symlink_target or ''
            size = 0
            executable = False
        elif kind == 'file':
            fingerprint = inv_entry.text_sha1 or ''
            size = inv_entry.text_size or 0
            executable = inv_entry.executable
        elif kind == 'tree-reference':
            fingerprint = inv_entry.reference_revision or ''
            size = 0
            executable = False
        else:
            raise Exception("can't pack %s" % inv_entry)
        return (minikind, fingerprint, size, executable, tree_data)

    def _iter_child_entries(self, tree_index, path_utf8):
        """Iterate over all the entries that are children of path_utf.

        This only returns entries that are present (not in 'a', 'r') in 
        tree_index. tree_index data is not refreshed, so if tree 0 is used,
        results may differ from that obtained if paths were statted to
        determine what ones were directories.

        Asking for the children of a non-directory will return an empty
        iterator.
        """
        pending_dirs = []
        next_pending_dirs = [path_utf8]
        absent = 'ar'
        while next_pending_dirs:
            pending_dirs = next_pending_dirs
            next_pending_dirs = []
            for path in pending_dirs:
                block_index, present = self._find_block_index_from_key(
                    (path, '', ''))
                if block_index == 0:
                    block_index = 1
                    if len(self._dirblocks) == 1:
                        # asked for the children of the root with no other
                        # contents.
                        return
                if not present:
                    # children of a non-directory asked for.
                    continue
                block = self._dirblocks[block_index]
                for entry in block[1]:
                    kind = entry[1][tree_index][0]
                    if kind not in absent:
                        yield entry
                    if kind == 'd':
                        if entry[0][0]:
                            path = entry[0][0] + '/' + entry[0][1]
                        else:
                            path = entry[0][1]
                        next_pending_dirs.append(path)
    
    def _iter_entries(self):
        """Iterate over all the entries in the dirstate.

        Each yelt item is an entry in the standard format described in the
        docstring of bzrlib.dirstate.
        """
        self._read_dirblocks_if_needed()
        for directory in self._dirblocks:
            for entry in directory[1]:
                yield entry

    def _get_id_index(self):
        """Get an id index of self._dirblocks."""
        if self._id_index is None:
            id_index = {}
            for key, tree_details in self._iter_entries():
                id_index.setdefault(key[2], set()).add(key)
            self._id_index = id_index
        return self._id_index

    def _get_output_lines(self, lines):
        """Format lines for final output.

        :param lines: A sequence of lines containing the parents list and the
            path lines.
        """
        output_lines = [DirState.HEADER_FORMAT_3]
        lines.append('') # a final newline
        inventory_text = '\0\n\0'.join(lines)
        output_lines.append('crc32: %s\n' % (zlib.crc32(inventory_text),))
        # -3, 1 for num parents, 1 for ghosts, 1 for final newline
        num_entries = len(lines)-3
        output_lines.append('num_entries: %s\n' % (num_entries,))
        output_lines.append(inventory_text)
        return output_lines

    def _make_deleted_row(self, fileid_utf8, parents):
        """Return a deleted row for fileid_utf8."""
        return ('/', 'RECYCLED.BIN', 'file', fileid_utf8, 0, DirState.NULLSTAT,
            ''), parents

    def _num_present_parents(self):
        """The number of parent entries in each record row."""
        return len(self._parents) - len(self._ghosts)

    @staticmethod
    def on_file(path):
        """Construct a DirState on the file at path path.

        :return: An unlocked DirState object, associated with the given path.
        """
        result = DirState(path)
        return result

    def _read_dirblocks_if_needed(self):
        """Read in all the dirblocks from the file if they are not in memory.
        
        This populates self._dirblocks, and sets self._dirblock_state to
        IN_MEMORY_UNMODIFIED. It is not currently ready for incremental block
        loading.
        """
        self._read_header_if_needed()
        if self._dirblock_state == DirState.NOT_IN_MEMORY:
            _read_dirblocks(self)

    def _read_header(self):
        """This reads in the metadata header, and the parent ids.

        After reading in, the file should be positioned at the null
        just before the start of the first record in the file.

        :return: (expected crc checksum, number of entries, parent list)
        """
        self._read_prelude()
        parent_line = self._state_file.readline()
        info = parent_line.split('\0')
        num_parents = int(info[0])
        self._parents = info[1:-1]
        ghost_line = self._state_file.readline()
        info = ghost_line.split('\0')
        num_ghosts = int(info[1])
        self._ghosts = info[2:-1]
        self._header_state = DirState.IN_MEMORY_UNMODIFIED
        self._end_of_header = self._state_file.tell()

    def _read_header_if_needed(self):
        """Read the header of the dirstate file if needed."""
        # inline this as it will be called a lot
        if not self._lock_token:
            raise errors.ObjectNotLocked(self)
        if self._header_state == DirState.NOT_IN_MEMORY:
            self._read_header()

    def _read_prelude(self):
        """Read in the prelude header of the dirstate file.

        This only reads in the stuff that is not connected to the crc
        checksum. The position will be correct to read in the rest of
        the file and check the checksum after this point.
        The next entry in the file should be the number of parents,
        and their ids. Followed by a newline.
        """
        header = self._state_file.readline()
        if header != DirState.HEADER_FORMAT_3:
            raise errors.BzrError(
                'invalid header line: %r' % (header,))
        crc_line = self._state_file.readline()
        if not crc_line.startswith('crc32: '):
            raise errors.BzrError('missing crc32 checksum: %r' % crc_line)
        self.crc_expected = int(crc_line[len('crc32: '):-1])
        num_entries_line = self._state_file.readline()
        if not num_entries_line.startswith('num_entries: '):
            raise errors.BzrError('missing num_entries line')
        self._num_entries = int(num_entries_line[len('num_entries: '):-1])

    def sha1_from_stat(self, path, stat_result, _pack_stat=pack_stat):
        """Find a sha1 given a stat lookup."""
        return self._get_packed_stat_index().get(_pack_stat(stat_result), None)

    def _get_packed_stat_index(self):
        """Get a packed_stat index of self._dirblocks."""
        if self._packed_stat_index is None:
            index = {}
            for key, tree_details in self._iter_entries():
                if tree_details[0][0] == 'f':
                    index[tree_details[0][4]] = tree_details[0][1]
            self._packed_stat_index = index
        return self._packed_stat_index

    def save(self):
        """Save any pending changes created during this session.

        We reuse the existing file, because that prevents race conditions with
        file creation, and use oslocks on it to prevent concurrent modification
        and reads - because dirstate's incremental data aggregation is not
        compatible with reading a modified file, and replacing a file in use by
        another process is impossible on Windows.

        A dirstate in read only mode should be smart enough though to validate
        that the file has not changed, and otherwise discard its cache and
        start over, to allow for fine grained read lock duration, so 'status'
        wont block 'commit' - for example.
        """
        if self._changes_aborted:
            # Should this be a warning? For now, I'm expecting that places that
            # mark it inconsistent will warn, making a warning here redundant.
            trace.mutter('Not saving DirState because '
                    '_changes_aborted is set.')
            return
        if (self._header_state == DirState.IN_MEMORY_MODIFIED or
            self._dirblock_state == DirState.IN_MEMORY_MODIFIED):

            grabbed_write_lock = False
            if self._lock_state != 'w':
                grabbed_write_lock, new_lock = self._lock_token.temporary_write_lock()
                # Switch over to the new lock, as the old one may be closed.
                # TODO: jam 20070315 We should validate the disk file has
                #       not changed contents. Since temporary_write_lock may
                #       not be an atomic operation.
                self._lock_token = new_lock
                self._state_file = new_lock.f
                if not grabbed_write_lock:
                    # We couldn't grab a write lock, so we switch back to a read one
                    return
            try:
                self._state_file.seek(0)
                self._state_file.writelines(self.get_lines())
                self._state_file.truncate()
                self._state_file.flush()
                self._header_state = DirState.IN_MEMORY_UNMODIFIED
                self._dirblock_state = DirState.IN_MEMORY_UNMODIFIED
            finally:
                if grabbed_write_lock:
                    self._lock_token = self._lock_token.restore_read_lock()
                    self._state_file = self._lock_token.f
                    # TODO: jam 20070315 We should validate the disk file has
                    #       not changed contents. Since restore_read_lock may
                    #       not be an atomic operation.

    def _set_data(self, parent_ids, dirblocks):
        """Set the full dirstate data in memory.

        This is an internal function used to completely replace the objects
        in memory state. It puts the dirstate into state 'full-dirty'.

        :param parent_ids: A list of parent tree revision ids.
        :param dirblocks: A list containing one tuple for each directory in the
            tree. Each tuple contains the directory path and a list of entries 
            found in that directory.
        """
        # our memory copy is now authoritative.
        self._dirblocks = dirblocks
        self._header_state = DirState.IN_MEMORY_MODIFIED
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
        self._parents = list(parent_ids)
        self._id_index = None
        self._packed_stat_index = None

    def set_path_id(self, path, new_id):
        """Change the id of path to new_id in the current working tree.

        :param path: The path inside the tree to set - '' is the root, 'foo'
            is the path foo in the root.
        :param new_id: The new id to assign to the path. This must be a utf8
            file id (not unicode, and not None).
        """
        self._read_dirblocks_if_needed()
        if len(path):
            # TODO: logic not written
            raise NotImplementedError(self.set_path_id)
        # TODO: check new id is unique
        entry = self._get_entry(0, path_utf8=path)
        if entry[0][2] == new_id:
            # Nothing to change.
            return
        # mark the old path absent, and insert a new root path
        self._make_absent(entry)
        self.update_minimal(('', '', new_id), 'd',
            path_utf8='', packed_stat=entry[1][0][4])
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
        if self._id_index is not None:
            self._id_index.setdefault(new_id, set()).add(entry[0])

    def set_parent_trees(self, trees, ghosts):
        """Set the parent trees for the dirstate.

        :param trees: A list of revision_id, tree tuples. tree must be provided
            even if the revision_id refers to a ghost: supply an empty tree in 
            this case.
        :param ghosts: A list of the revision_ids that are ghosts at the time
            of setting.
        """ 
        # TODO: generate a list of parent indexes to preserve to save 
        # processing specific parent trees. In the common case one tree will
        # be preserved - the left most parent.
        # TODO: if the parent tree is a dirstate, we might want to walk them
        # all by path in parallel for 'optimal' common-case performance.
        # generate new root row.
        self._read_dirblocks_if_needed()
        # TODO future sketch: Examine the existing parents to generate a change
        # map and then walk the new parent trees only, mapping them into the
        # dirstate. Walk the dirstate at the same time to remove unreferenced
        # entries.
        # for now: 
        # sketch: loop over all entries in the dirstate, cherry picking 
        # entries from the parent trees, if they are not ghost trees.
        # after we finish walking the dirstate, all entries not in the dirstate
        # are deletes, so we want to append them to the end as per the design
        # discussions. So do a set difference on ids with the parents to
        # get deletes, and add them to the end.
        # During the update process we need to answer the following questions:
        # - find other keys containing a fileid in order to create cross-path
        #   links. We dont't trivially use the inventory from other trees
        #   because this leads to either double touching, or to accessing
        #   missing keys,
        # - find other keys containing a path 
        # We accumulate each entry via this dictionary, including the root 
        by_path = {}
        id_index = {}
        # we could do parallel iterators, but because file id data may be
        # scattered throughout, we dont save on index overhead: we have to look
        # at everything anyway. We can probably save cycles by reusing parent
        # data and doing an incremental update when adding an additional
        # parent, but for now the common cases are adding a new parent (merge),
        # and replacing completely (commit), and commit is more common: so
        # optimise merge later.
        
        # ---- start generation of full tree mapping data
        # what trees should we use?
        parent_trees = [tree for rev_id, tree in trees if rev_id not in ghosts]
        # how many trees do we end up with 
        parent_count = len(parent_trees)

        # one: the current tree
        for entry in self._iter_entries():
            # skip entries not in the current tree
            if entry[1][0][0] in 'ar': # absent, relocated
                continue
            by_path[entry[0]] = [entry[1][0]] + \
                [DirState.NULL_PARENT_DETAILS] * parent_count
            id_index[entry[0][2]] = set([entry[0]])
        
        # now the parent trees:
        for tree_index, tree in enumerate(parent_trees):
            # the index is off by one, adjust it.
            tree_index = tree_index + 1
            # when we add new locations for a fileid we need these ranges for
            # any fileid in this tree as we set the by_path[id] to:
            # already_processed_tree_details + new_details + new_location_suffix
            # the suffix is from tree_index+1:parent_count+1.
            new_location_suffix = [DirState.NULL_PARENT_DETAILS] * (parent_count - tree_index)
            # now stitch in all the entries from this tree
            for path, entry in tree.inventory.iter_entries_by_dir():
                # here we process each trees details for each item in the tree.
                # we first update any existing entries for the id at other paths,
                # then we either create or update the entry for the id at the
                # right path, and finally we add (if needed) a mapping from
                # file_id to this path. We do it in this order to allow us to
                # avoid checking all known paths for the id when generating a
                # new entry at this path: by adding the id->path mapping last,
                # all the mappings are valid and have correct relocation
                # records where needed. 
                file_id = entry.file_id
                path_utf8 = path.encode('utf8')
                dirname, basename = osutils.split(path_utf8)
                new_entry_key = (dirname, basename, file_id)
                # tree index consistency: All other paths for this id in this tree
                # index must point to the correct path.
                for entry_key in id_index.setdefault(file_id, set()):
                    # TODO:PROFILING: It might be faster to just update
                    # rather than checking if we need to, and then overwrite
                    # the one we are located at.
                    if entry_key != new_entry_key:
                        # this file id is at a different path in one of the
                        # other trees, so put absent pointers there
                        # This is the vertical axis in the matrix, all pointing
                        # to the real path.
                        by_path[entry_key][tree_index] = ('r', path_utf8, 0, False, '')
                # by path consistency: Insert into an existing path record (trivial), or 
                # add a new one with relocation pointers for the other tree indexes.
                if new_entry_key in id_index[file_id]:
                    # there is already an entry where this data belongs, just insert it.
                    by_path[new_entry_key][tree_index] = \
                        self._inv_entry_to_details(entry)
                else:
                    # add relocated entries to the horizontal axis - this row
                    # mapping from path,id. We need to look up the correct path
                    # for the indexes from 0 to tree_index -1
                    new_details = []
                    for lookup_index in xrange(tree_index):
                        # boundary case: this is the first occurence of file_id
                        # so there are no id_indexs, possibly take this out of
                        # the loop?
                        if not len(id_index[file_id]):
                            new_details.append(DirState.NULL_PARENT_DETAILS)
                        else:
                            # grab any one entry, use it to find the right path.
                            # TODO: optimise this to reduce memory use in highly 
                            # fragmented situations by reusing the relocation
                            # records.
                            a_key = iter(id_index[file_id]).next()
                            if by_path[a_key][lookup_index][0] in ('r', 'a'):
                                # its a pointer or missing statement, use it as is.
                                new_details.append(by_path[a_key][lookup_index])
                            else:
                                # we have the right key, make a pointer to it.
                                real_path = ('/'.join(a_key[0:2])).strip('/')
                                new_details.append(('r', real_path, 0, False, ''))
                    new_details.append(self._inv_entry_to_details(entry))
                    new_details.extend(new_location_suffix)
                    by_path[new_entry_key] = new_details
                    id_index[file_id].add(new_entry_key)
        # --- end generation of full tree mappings

        # sort and output all the entries
        new_entries = self._sort_entries(by_path.items())
        self._entries_to_current_state(new_entries)
        self._parents = [rev_id for rev_id, tree in trees]
        self._ghosts = list(ghosts)
        self._header_state = DirState.IN_MEMORY_MODIFIED
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
        self._id_index = id_index

    def _sort_entries(self, entry_list):
        """Given a list of entries, sort them into the right order.

        This is done when constructing a new dirstate from trees - normally we
        try to keep everything in sorted blocks all the time, but sometimes
        it's easier to sort after the fact.
        """
        def _key(entry):
            # sort by: directory parts, file name, file id
            return entry[0][0].split('/'), entry[0][1], entry[0][2]
        return sorted(entry_list, key=_key)

    def set_state_from_inventory(self, new_inv):
        """Set new_inv as the current state. 

        This API is called by tree transform, and will usually occur with
        existing parent trees.

        :param new_inv: The inventory object to set current state from.
        """
        if 'evil' in debug.debug_flags:
            trace.mutter_callsite(1,
                "set_state_from_inventory called; please mutate the tree instead")
        self._read_dirblocks_if_needed()
        # sketch:
        # Two iterators: current data and new data, both in dirblock order. 
        # We zip them together, which tells about entries that are new in the
        # inventory, or removed in the inventory, or present in both and
        # possibly changed.  
        #
        # You might think we could just synthesize a new dirstate directly
        # since we're processing it in the right order.  However, we need to
        # also consider there may be any number of parent trees and relocation
        # pointers, and we don't want to duplicate that here.
        new_iterator = new_inv.iter_entries_by_dir()
        # we will be modifying the dirstate, so we need a stable iterator. In
        # future we might write one, for now we just clone the state into a
        # list - which is a shallow copy.
        old_iterator = iter(list(self._iter_entries()))
        # both must have roots so this is safe:
        current_new = new_iterator.next()
        current_old = old_iterator.next()
        def advance(iterator):
            try:
                return iterator.next()
            except StopIteration:
                return None
        while current_new or current_old:
            # skip entries in old that are not really there
            if current_old and current_old[1][0][0] in 'ar':
                # relocated or absent
                current_old = advance(old_iterator)
                continue
            if current_new:
                # convert new into dirblock style
                new_path_utf8 = current_new[0].encode('utf8')
                new_dirname, new_basename = osutils.split(new_path_utf8)
                new_id = current_new[1].file_id
                new_entry_key = (new_dirname, new_basename, new_id)
                current_new_minikind = \
                    DirState._kind_to_minikind[current_new[1].kind]
                if current_new_minikind == 't':
                    fingerprint = current_new[1].reference_revision or ''
                else:
                    # We normally only insert or remove records, or update
                    # them when it has significantly changed.  Then we want to
                    # erase its fingerprint.  Unaffected records should
                    # normally not be updated at all.
                    fingerprint = ''
            else:
                # for safety disable variables
                new_path_utf8 = new_dirname = new_basename = new_id = \
                    new_entry_key = None
            # 5 cases, we dont have a value that is strictly greater than everything, so
            # we make both end conditions explicit
            if not current_old:
                # old is finished: insert current_new into the state.
                self.update_minimal(new_entry_key, current_new_minikind,
                    executable=current_new[1].executable,
                    path_utf8=new_path_utf8, fingerprint=fingerprint)
                current_new = advance(new_iterator)
            elif not current_new:
                # new is finished
                self._make_absent(current_old)
                current_old = advance(old_iterator)
            elif new_entry_key == current_old[0]:
                # same -  common case
                # We're looking at the same path and id in both the dirstate
                # and inventory, so just need to update the fields in the
                # dirstate from the one in the inventory.
                # TODO: update the record if anything significant has changed.
                # the minimal required trigger is if the execute bit or cached
                # kind has changed.
                if (current_old[1][0][3] != current_new[1].executable or
                    current_old[1][0][0] != current_new_minikind):
                    self.update_minimal(current_old[0], current_new_minikind,
                        executable=current_new[1].executable,
                        path_utf8=new_path_utf8, fingerprint=fingerprint)
                # both sides are dealt with, move on
                current_old = advance(old_iterator)
                current_new = advance(new_iterator)
            elif (cmp_by_dirs(new_dirname, current_old[0][0]) < 0
                  or (new_dirname == current_old[0][0]
                      and new_entry_key[1:] < current_old[0][1:])):
                # new comes before:
                # add a entry for this and advance new
                self.update_minimal(new_entry_key, current_new_minikind,
                    executable=current_new[1].executable,
                    path_utf8=new_path_utf8, fingerprint=fingerprint)
                current_new = advance(new_iterator)
            else:
                # we've advanced past the place where the old key would be,
                # without seeing it in the new list.  so it must be gone.
                self._make_absent(current_old)
                current_old = advance(old_iterator)
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
        self._id_index = None
        self._packed_stat_index = None

    def _make_absent(self, current_old):
        """Mark current_old - an entry - as absent for tree 0.

        :return: True if this was the last details entry for the entry key:
            that is, if the underlying block has had the entry removed, thus
            shrinking in length.
        """
        # build up paths that this id will be left at after the change is made,
        # so we can update their cross references in tree 0
        all_remaining_keys = set()
        # Dont check the working tree, because it's going.
        for details in current_old[1][1:]:
            if details[0] not in 'ar': # absent, relocated
                all_remaining_keys.add(current_old[0])
            elif details[0] == 'r': # relocated
                # record the key for the real path.
                all_remaining_keys.add(tuple(osutils.split(details[1])) + (current_old[0][2],))
            # absent rows are not present at any path.
        last_reference = current_old[0] not in all_remaining_keys
        if last_reference:
            # the current row consists entire of the current item (being marked
            # absent), and relocated or absent entries for the other trees:
            # Remove it, its meaningless.
            block = self._find_block(current_old[0])
            entry_index, present = self._find_entry_index(current_old[0], block[1])
            if not present:
                raise AssertionError('could not find entry for %s' % (current_old,))
            block[1].pop(entry_index)
            # if we have an id_index in use, remove this key from it for this id.
            if self._id_index is not None:
                self._id_index[current_old[0][2]].remove(current_old[0])
        # update all remaining keys for this id to record it as absent. The
        # existing details may either be the record we are marking as deleted
        # (if there were other trees with the id present at this path), or may
        # be relocations.
        for update_key in all_remaining_keys:
            update_block_index, present = \
                self._find_block_index_from_key(update_key)
            if not present:
                raise AssertionError('could not find block for %s' % (update_key,))
            update_entry_index, present = \
                self._find_entry_index(update_key, self._dirblocks[update_block_index][1])
            if not present:
                raise AssertionError('could not find entry for %s' % (update_key,))
            update_tree_details = self._dirblocks[update_block_index][1][update_entry_index][1]
            # it must not be absent at the moment
            if update_tree_details[0][0] == 'a': # absent
                raise AssertionError('bad row %r' % (update_tree_details,))
            update_tree_details[0] = DirState.NULL_PARENT_DETAILS
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
        return last_reference

    def update_minimal(self, key, minikind, executable=False, fingerprint='',
                       packed_stat=None, size=0, path_utf8=None):
        """Update an entry to the state in tree 0.

        This will either create a new entry at 'key' or update an existing one.
        It also makes sure that any other records which might mention this are
        updated as well.

        :param key: (dir, name, file_id) for the new entry
        :param minikind: The type for the entry ('f' == 'file', 'd' ==
                'directory'), etc.
        :param executable: Should the executable bit be set?
        :param fingerprint: Simple fingerprint for new entry: sha1 for files, 
            referenced revision id for subtrees, etc.
        :param packed_stat: Packed stat value for new entry.
        :param size: Size information for new entry
        :param path_utf8: key[0] + '/' + key[1], just passed in to avoid doing
                extra computation.

        If packed_stat and fingerprint are not given, they're invalidated in
        the entry.
        """
        block = self._find_block(key)[1]
        if packed_stat is None:
            packed_stat = DirState.NULLSTAT
        # XXX: Some callers pass '' as the packed_stat, and it seems to be
        # sometimes present in the dirstate - this seems oddly inconsistent.
        # mbp 20071008
        entry_index, present = self._find_entry_index(key, block)
        new_details = (minikind, fingerprint, size, executable, packed_stat)
        id_index = self._get_id_index()
        if not present:
            # new entry, synthesis cross reference here,
            existing_keys = id_index.setdefault(key[2], set())
            if not existing_keys:
                # not currently in the state, simplest case
                new_entry = key, [new_details] + self._empty_parent_info()
            else:
                # present at one or more existing other paths.
                # grab one of them and use it to generate parent
                # relocation/absent entries.
                new_entry = key, [new_details]
                for other_key in existing_keys:
                    # change the record at other to be a pointer to this new
                    # record. The loop looks similar to the change to
                    # relocations when updating an existing record but its not:
                    # the test for existing kinds is different: this can be
                    # factored out to a helper though.
                    other_block_index, present = self._find_block_index_from_key(other_key)
                    if not present:
                        raise AssertionError('could not find block for %s' % (other_key,))
                    other_entry_index, present = self._find_entry_index(other_key,
                                            self._dirblocks[other_block_index][1])
                    if not present:
                        raise AssertionError('could not find entry for %s' % (other_key,))
                    if path_utf8 is None:
                        raise AssertionError('no path')
                    self._dirblocks[other_block_index][1][other_entry_index][1][0] = \
                        ('r', path_utf8, 0, False, '')

                num_present_parents = self._num_present_parents()
                for lookup_index in xrange(1, num_present_parents + 1):
                    # grab any one entry, use it to find the right path.
                    # TODO: optimise this to reduce memory use in highly 
                    # fragmented situations by reusing the relocation
                    # records.
                    update_block_index, present = \
                        self._find_block_index_from_key(other_key)
                    if not present:
                        raise AssertionError('could not find block for %s' % (other_key,))
                    update_entry_index, present = \
                        self._find_entry_index(other_key, self._dirblocks[update_block_index][1])
                    if not present:
                        raise AssertionError('could not find entry for %s' % (other_key,))
                    update_details = self._dirblocks[update_block_index][1][update_entry_index][1][lookup_index]
                    if update_details[0] in 'ar': # relocated, absent
                        # its a pointer or absent in lookup_index's tree, use
                        # it as is.
                        new_entry[1].append(update_details)
                    else:
                        # we have the right key, make a pointer to it.
                        pointer_path = osutils.pathjoin(*other_key[0:2])
                        new_entry[1].append(('r', pointer_path, 0, False, ''))
            block.insert(entry_index, new_entry)
            existing_keys.add(key)
        else:
            # Does the new state matter? 
            block[entry_index][1][0] = new_details
            # parents cannot be affected by what we do.
            # other occurences of this id can be found 
            # from the id index.
            # ---
            # tree index consistency: All other paths for this id in this tree
            # index must point to the correct path. We have to loop here because
            # we may have passed entries in the state with this file id already
            # that were absent - where parent entries are - and they need to be
            # converted to relocated.
            if path_utf8 is None:
                raise AssertionError('no path')
            for entry_key in id_index.setdefault(key[2], set()):
                # TODO:PROFILING: It might be faster to just update
                # rather than checking if we need to, and then overwrite
                # the one we are located at.
                if entry_key != key:
                    # this file id is at a different path in one of the
                    # other trees, so put absent pointers there
                    # This is the vertical axis in the matrix, all pointing
                    # to the real path.
                    block_index, present = self._find_block_index_from_key(entry_key)
                    if not present:
                        raise AssertionError('not present: %r', entry_key)
                    entry_index, present = self._find_entry_index(entry_key, self._dirblocks[block_index][1])
                    if not present:
                        raise AssertionError('not present: %r', entry_key)
                    self._dirblocks[block_index][1][entry_index][1][0] = \
                        ('r', path_utf8, 0, False, '')
        # add a containing dirblock if needed.
        if new_details[0] == 'd':
            subdir_key = (osutils.pathjoin(*key[0:2]), '', '')
            block_index, present = self._find_block_index_from_key(subdir_key)
            if not present:
                self._dirblocks.insert(block_index, (subdir_key[0], []))

        self._dirblock_state = DirState.IN_MEMORY_MODIFIED

    def _validate(self):
        """Check that invariants on the dirblock are correct.

        This can be useful in debugging; it shouldn't be necessary in 
        normal code.

        This must be called with a lock held.
        """
        # NOTE: This must always raise AssertionError not just assert,
        # otherwise it may not behave properly under python -O
        #
        # TODO: All entries must have some content that's not 'a' or 'r',
        # otherwise it could just be removed.
        #
        # TODO: All relocations must point directly to a real entry.
        #
        # TODO: No repeated keys.
        #
        # -- mbp 20070325
        from pprint import pformat
        self._read_dirblocks_if_needed()
        if len(self._dirblocks) > 0:
            if not self._dirblocks[0][0] == '':
                raise AssertionError(
                    "dirblocks don't start with root block:\n" + \
                    pformat(self._dirblocks))
        if len(self._dirblocks) > 1:
            if not self._dirblocks[1][0] == '':
                raise AssertionError(
                    "dirblocks missing root directory:\n" + \
                    pformat(self._dirblocks))
        # the dirblocks are sorted by their path components, name, and dir id
        dir_names = [d[0].split('/')
                for d in self._dirblocks[1:]]
        if dir_names != sorted(dir_names):
            raise AssertionError(
                "dir names are not in sorted order:\n" + \
                pformat(self._dirblocks) + \
                "\nkeys:\n" +
                pformat(dir_names))
        for dirblock in self._dirblocks:
            # within each dirblock, the entries are sorted by filename and
            # then by id.
            for entry in dirblock[1]:
                if dirblock[0] != entry[0][0]:
                    raise AssertionError(
                        "entry key for %r"
                        "doesn't match directory name in\n%r" %
                        (entry, pformat(dirblock)))
            if dirblock[1] != sorted(dirblock[1]):
                raise AssertionError(
                    "dirblock for %r is not sorted:\n%s" % \
                    (dirblock[0], pformat(dirblock)))

        def check_valid_parent():
            """Check that the current entry has a valid parent.

            This makes sure that the parent has a record,
            and that the parent isn't marked as "absent" in the
            current tree. (It is invalid to have a non-absent file in an absent
            directory.)
            """
            if entry[0][0:2] == ('', ''):
                # There should be no parent for the root row
                return
            parent_entry = self._get_entry(tree_index, path_utf8=entry[0][0])
            if parent_entry == (None, None):
                raise AssertionError(
                    "no parent entry for: %s in tree %s"
                    % (this_path, tree_index))
            if parent_entry[1][tree_index][0] != 'd':
                raise AssertionError(
                    "Parent entry for %s is not marked as a valid"
                    " directory. %s" % (this_path, parent_entry,))

        # For each file id, for each tree: either
        # the file id is not present at all; all rows with that id in the
        # key have it marked as 'absent'
        # OR the file id is present under exactly one name; any other entries 
        # that mention that id point to the correct name.
        #
        # We check this with a dict per tree pointing either to the present
        # name, or None if absent.
        tree_count = self._num_present_parents() + 1
        id_path_maps = [dict() for i in range(tree_count)]
        # Make sure that all renamed entries point to the correct location.
        for entry in self._iter_entries():
            file_id = entry[0][2]
            this_path = osutils.pathjoin(entry[0][0], entry[0][1])
            if len(entry[1]) != tree_count:
                raise AssertionError(
                "wrong number of entry details for row\n%s" \
                ",\nexpected %d" % \
                (pformat(entry), tree_count))
            absent_positions = 0
            for tree_index, tree_state in enumerate(entry[1]):
                this_tree_map = id_path_maps[tree_index]
                minikind = tree_state[0]
                if minikind in 'ar':
                    absent_positions += 1
                # have we seen this id before in this column?
                if file_id in this_tree_map:
                    previous_path, previous_loc = this_tree_map[file_id]
                    # any later mention of this file must be consistent with
                    # what was said before
                    if minikind == 'a':
                        if previous_path is not None:
                            raise AssertionError(
                            "file %s is absent in row %r but also present " \
                            "at %r"% \
                            (file_id, entry, previous_path))
                    elif minikind == 'r':
                        target_location = tree_state[1]
                        if previous_path != target_location:
                            raise AssertionError(
                            "file %s relocation in row %r but also at %r" \
                            % (file_id, entry, previous_path))
                    else:
                        # a file, directory, etc - may have been previously
                        # pointed to by a relocation, which must point here
                        if previous_path != this_path:
                            raise AssertionError(
                                "entry %r inconsistent with previous path %r "
                                "seen at %r" %
                                (entry, previous_path, previous_loc))
                        check_valid_parent()
                else:
                    if minikind == 'a':
                        # absent; should not occur anywhere else
                        this_tree_map[file_id] = None, this_path
                    elif minikind == 'r':
                        # relocation, must occur at expected location 
                        this_tree_map[file_id] = tree_state[1], this_path
                    else:
                        this_tree_map[file_id] = this_path, this_path
                        check_valid_parent()
            if absent_positions == tree_count:
                raise AssertionError(
                    "entry %r has no data for any tree." % (entry,))

    def _wipe_state(self):
        """Forget all state information about the dirstate."""
        self._header_state = DirState.NOT_IN_MEMORY
        self._dirblock_state = DirState.NOT_IN_MEMORY
        self._changes_aborted = False
        self._parents = []
        self._ghosts = []
        self._dirblocks = []
        self._id_index = None
        self._packed_stat_index = None
        self._end_of_header = None
        self._cutoff_time = None
        self._split_path_cache = {}

    def lock_read(self):
        """Acquire a read lock on the dirstate."""
        if self._lock_token is not None:
            raise errors.LockContention(self._lock_token)
        # TODO: jam 20070301 Rather than wiping completely, if the blocks are
        #       already in memory, we could read just the header and check for
        #       any modification. If not modified, we can just leave things
        #       alone
        self._lock_token = lock.ReadLock(self._filename)
        self._lock_state = 'r'
        self._state_file = self._lock_token.f
        self._wipe_state()

    def lock_write(self):
        """Acquire a write lock on the dirstate."""
        if self._lock_token is not None:
            raise errors.LockContention(self._lock_token)
        # TODO: jam 20070301 Rather than wiping completely, if the blocks are
        #       already in memory, we could read just the header and check for
        #       any modification. If not modified, we can just leave things
        #       alone
        self._lock_token = lock.WriteLock(self._filename)
        self._lock_state = 'w'
        self._state_file = self._lock_token.f
        self._wipe_state()

    def unlock(self):
        """Drop any locks held on the dirstate."""
        if self._lock_token is None:
            raise errors.LockNotHeld(self)
        # TODO: jam 20070301 Rather than wiping completely, if the blocks are
        #       already in memory, we could read just the header and check for
        #       any modification. If not modified, we can just leave things
        #       alone
        self._state_file = None
        self._lock_state = None
        self._lock_token.unlock()
        self._lock_token = None
        self._split_path_cache = {}

    def _requires_lock(self):
        """Check that a lock is currently held by someone on the dirstate."""
        if not self._lock_token:
            raise errors.ObjectNotLocked(self)


# Try to load the compiled form if possible
try:
    from bzrlib._dirstate_helpers_c import (
        _read_dirblocks_c as _read_dirblocks,
        bisect_dirblock_c as bisect_dirblock,
        _bisect_path_left_c as _bisect_path_left,
        _bisect_path_right_c as _bisect_path_right,
        cmp_by_dirs_c as cmp_by_dirs,
        )
except ImportError:
    from bzrlib._dirstate_helpers_py import (
        _read_dirblocks_py as _read_dirblocks,
        bisect_dirblock_py as bisect_dirblock,
        _bisect_path_left_py as _bisect_path_left,
        _bisect_path_right_py as _bisect_path_right,
        cmp_by_dirs_py as cmp_by_dirs,
        )