~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
# Copyright (C) 2005-2011 Canonical Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

import errno
import os
import re
import stat
import sys
import time
import codecs

from bzrlib.lazy_import import lazy_import
lazy_import(globals(), """
from datetime import datetime
import getpass
import ntpath
import posixpath
# We need to import both shutil and rmtree as we export the later on posix
# and need the former on windows
import shutil
from shutil import rmtree
import socket
import subprocess
# We need to import both tempfile and mkdtemp as we export the later on posix
# and need the former on windows
import tempfile
from tempfile import mkdtemp
import unicodedata

from bzrlib import (
    cache_utf8,
    errors,
    trace,
    win32utils,
    )
""")

from bzrlib.symbol_versioning import (
    deprecated_function,
    deprecated_in,
    )

from hashlib import (
    md5,
    sha1 as sha,
    )


import bzrlib
from bzrlib import symbol_versioning


# Cross platform wall-clock time functionality with decent resolution.
# On Linux ``time.clock`` returns only CPU time. On Windows, ``time.time()``
# only has a resolution of ~15ms. Note that ``time.clock()`` is not
# synchronized with ``time.time()``, this is only meant to be used to find
# delta times by subtracting from another call to this function.
timer_func = time.time
if sys.platform == 'win32':
    timer_func = time.clock

# On win32, O_BINARY is used to indicate the file should
# be opened in binary mode, rather than text mode.
# On other platforms, O_BINARY doesn't exist, because
# they always open in binary mode, so it is okay to
# OR with 0 on those platforms.
# O_NOINHERIT and O_TEXT exists only on win32 too.
O_BINARY = getattr(os, 'O_BINARY', 0)
O_TEXT = getattr(os, 'O_TEXT', 0)
O_NOINHERIT = getattr(os, 'O_NOINHERIT', 0)


def get_unicode_argv():
    try:
        user_encoding = get_user_encoding()
        return [a.decode(user_encoding) for a in sys.argv[1:]]
    except UnicodeDecodeError:
        raise errors.BzrError("Parameter %r encoding is unsupported by %s "
            "application locale." % (a, user_encoding))


def make_readonly(filename):
    """Make a filename read-only."""
    mod = os.lstat(filename).st_mode
    if not stat.S_ISLNK(mod):
        mod = mod & 0777555
        chmod_if_possible(filename, mod)


def make_writable(filename):
    mod = os.lstat(filename).st_mode
    if not stat.S_ISLNK(mod):
        mod = mod | 0200
        chmod_if_possible(filename, mod)


def chmod_if_possible(filename, mode):
    # Set file mode if that can be safely done.
    # Sometimes even on unix the filesystem won't allow it - see
    # https://bugs.launchpad.net/bzr/+bug/606537
    try:
        # It is probably faster to just do the chmod, rather than
        # doing a stat, and then trying to compare
        os.chmod(filename, mode)
    except (IOError, OSError),e:
        # Permission/access denied seems to commonly happen on smbfs; there's
        # probably no point warning about it.
        # <https://bugs.launchpad.net/bzr/+bug/606537>
        if getattr(e, 'errno') in (errno.EPERM, errno.EACCES):
            trace.mutter("ignore error on chmod of %r: %r" % (
                filename, e))
            return
        raise


def minimum_path_selection(paths):
    """Return the smallset subset of paths which are outside paths.

    :param paths: A container (and hence not None) of paths.
    :return: A set of paths sufficient to include everything in paths via
        is_inside, drawn from the paths parameter.
    """
    if len(paths) < 2:
        return set(paths)

    def sort_key(path):
        return path.split('/')
    sorted_paths = sorted(list(paths), key=sort_key)

    search_paths = [sorted_paths[0]]
    for path in sorted_paths[1:]:
        if not is_inside(search_paths[-1], path):
            # This path is unique, add it
            search_paths.append(path)

    return set(search_paths)


_QUOTE_RE = None


def quotefn(f):
    """Return a quoted filename filename

    This previously used backslash quoting, but that works poorly on
    Windows."""
    # TODO: I'm not really sure this is the best format either.x
    global _QUOTE_RE
    if _QUOTE_RE is None:
        _QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/\\_~-])')

    if _QUOTE_RE.search(f):
        return '"' + f + '"'
    else:
        return f


_directory_kind = 'directory'

def get_umask():
    """Return the current umask"""
    # Assume that people aren't messing with the umask while running
    # XXX: This is not thread safe, but there is no way to get the
    #      umask without setting it
    umask = os.umask(0)
    os.umask(umask)
    return umask


_kind_marker_map = {
    "file": "",
    _directory_kind: "/",
    "symlink": "@",
    'tree-reference': '+',
}


def kind_marker(kind):
    try:
        return _kind_marker_map[kind]
    except KeyError:
        # Slightly faster than using .get(, '') when the common case is that
        # kind will be found
        return ''


lexists = getattr(os.path, 'lexists', None)
if lexists is None:
    def lexists(f):
        try:
            stat = getattr(os, 'lstat', os.stat)
            stat(f)
            return True
        except OSError, e:
            if e.errno == errno.ENOENT:
                return False;
            else:
                raise errors.BzrError("lstat/stat of (%r): %r" % (f, e))


def fancy_rename(old, new, rename_func, unlink_func):
    """A fancy rename, when you don't have atomic rename.

    :param old: The old path, to rename from
    :param new: The new path, to rename to
    :param rename_func: The potentially non-atomic rename function
    :param unlink_func: A way to delete the target file if the full rename
        succeeds
    """
    # sftp rename doesn't allow overwriting, so play tricks:
    base = os.path.basename(new)
    dirname = os.path.dirname(new)
    # callers use different encodings for the paths so the following MUST
    # respect that. We rely on python upcasting to unicode if new is unicode
    # and keeping a str if not.
    tmp_name = 'tmp.%s.%.9f.%d.%s' % (base, time.time(),
                                      os.getpid(), rand_chars(10))
    tmp_name = pathjoin(dirname, tmp_name)

    # Rename the file out of the way, but keep track if it didn't exist
    # We don't want to grab just any exception
    # something like EACCES should prevent us from continuing
    # The downside is that the rename_func has to throw an exception
    # with an errno = ENOENT, or NoSuchFile
    file_existed = False
    try:
        rename_func(new, tmp_name)
    except (errors.NoSuchFile,), e:
        pass
    except IOError, e:
        # RBC 20060103 abstraction leakage: the paramiko SFTP clients rename
        # function raises an IOError with errno is None when a rename fails.
        # This then gets caught here.
        if e.errno not in (None, errno.ENOENT, errno.ENOTDIR):
            raise
    except Exception, e:
        if (getattr(e, 'errno', None) is None
            or e.errno not in (errno.ENOENT, errno.ENOTDIR)):
            raise
    else:
        file_existed = True

    failure_exc = None
    success = False
    try:
        try:
            # This may throw an exception, in which case success will
            # not be set.
            rename_func(old, new)
            success = True
        except (IOError, OSError), e:
            # source and target may be aliases of each other (e.g. on a
            # case-insensitive filesystem), so we may have accidentally renamed
            # source by when we tried to rename target
            failure_exc = sys.exc_info()
            if (file_existed and e.errno in (None, errno.ENOENT)
                and old.lower() == new.lower()):
                # source and target are the same file on a case-insensitive
                # filesystem, so we don't generate an exception
                failure_exc = None
    finally:
        if file_existed:
            # If the file used to exist, rename it back into place
            # otherwise just delete it from the tmp location
            if success:
                unlink_func(tmp_name)
            else:
                rename_func(tmp_name, new)
    if failure_exc is not None:
        try:
            raise failure_exc[0], failure_exc[1], failure_exc[2]
        finally:
            del failure_exc


# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
# choke on a Unicode string containing a relative path if
# os.getcwd() returns a non-sys.getdefaultencoding()-encoded
# string.
_fs_enc = sys.getfilesystemencoding() or 'utf-8'
def _posix_abspath(path):
    # jam 20060426 rather than encoding to fsencoding
    # copy posixpath.abspath, but use os.getcwdu instead
    if not posixpath.isabs(path):
        path = posixpath.join(getcwd(), path)
    return _posix_normpath(path)


def _posix_realpath(path):
    return posixpath.realpath(path.encode(_fs_enc)).decode(_fs_enc)


def _posix_normpath(path):
    path = posixpath.normpath(path)
    # Bug 861008: posixpath.normpath() returns a path normalized according to
    # the POSIX standard, which stipulates (for compatibility reasons) that two
    # leading slashes must not be simplified to one, and only if there are 3 or
    # more should they be simplified as one. So we treat the leading 2 slashes
    # as a special case here by simply removing the first slash, as we consider
    # that breaking POSIX compatibility for this obscure feature is acceptable.
    # This is not a paranoid precaution, as we notably get paths like this when
    # the repo is hosted at the root of the filesystem, i.e. in "/".    
    if path.startswith('//'):
        path = path[1:]
    return path


def _win32_fixdrive(path):
    """Force drive letters to be consistent.

    win32 is inconsistent whether it returns lower or upper case
    and even if it was consistent the user might type the other
    so we force it to uppercase
    running python.exe under cmd.exe return capital C:\\
    running win32 python inside a cygwin shell returns lowercase c:\\
    """
    drive, path = ntpath.splitdrive(path)
    return drive.upper() + path


def _win32_abspath(path):
    # Real ntpath.abspath doesn't have a problem with a unicode cwd
    return _win32_fixdrive(ntpath.abspath(unicode(path)).replace('\\', '/'))


def _win98_abspath(path):
    """Return the absolute version of a path.
    Windows 98 safe implementation (python reimplementation
    of Win32 API function GetFullPathNameW)
    """
    # Corner cases:
    #   C:\path     => C:/path
    #   C:/path     => C:/path
    #   \\HOST\path => //HOST/path
    #   //HOST/path => //HOST/path
    #   path        => C:/cwd/path
    #   /path       => C:/path
    path = unicode(path)
    # check for absolute path
    drive = ntpath.splitdrive(path)[0]
    if drive == '' and path[:2] not in('//','\\\\'):
        cwd = os.getcwdu()
        # we cannot simply os.path.join cwd and path
        # because os.path.join('C:','/path') produce '/path'
        # and this is incorrect
        if path[:1] in ('/','\\'):
            cwd = ntpath.splitdrive(cwd)[0]
            path = path[1:]
        path = cwd + '\\' + path
    return _win32_fixdrive(ntpath.normpath(path).replace('\\', '/'))


def _win32_realpath(path):
    # Real ntpath.realpath doesn't have a problem with a unicode cwd
    return _win32_fixdrive(ntpath.realpath(unicode(path)).replace('\\', '/'))


def _win32_pathjoin(*args):
    return ntpath.join(*args).replace('\\', '/')


def _win32_normpath(path):
    return _win32_fixdrive(ntpath.normpath(unicode(path)).replace('\\', '/'))


def _win32_getcwd():
    return _win32_fixdrive(os.getcwdu().replace('\\', '/'))


def _win32_mkdtemp(*args, **kwargs):
    return _win32_fixdrive(tempfile.mkdtemp(*args, **kwargs).replace('\\', '/'))


def _win32_rename(old, new):
    """We expect to be able to atomically replace 'new' with old.

    On win32, if new exists, it must be moved out of the way first,
    and then deleted.
    """
    try:
        fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
    except OSError, e:
        if e.errno in (errno.EPERM, errno.EACCES, errno.EBUSY, errno.EINVAL):
            # If we try to rename a non-existant file onto cwd, we get
            # EPERM or EACCES instead of ENOENT, this will raise ENOENT
            # if the old path doesn't exist, sometimes we get EACCES
            # On Linux, we seem to get EBUSY, on Mac we get EINVAL
            os.lstat(old)
        raise


def _mac_getcwd():
    return unicodedata.normalize('NFC', os.getcwdu())


# Default is to just use the python builtins, but these can be rebound on
# particular platforms.
abspath = _posix_abspath
realpath = _posix_realpath
pathjoin = os.path.join
normpath = _posix_normpath
getcwd = os.getcwdu
rename = os.rename
dirname = os.path.dirname
basename = os.path.basename
split = os.path.split
splitext = os.path.splitext
# These were already lazily imported into local scope
# mkdtemp = tempfile.mkdtemp
# rmtree = shutil.rmtree
lstat = os.lstat
fstat = os.fstat

def wrap_stat(st):
    return st


MIN_ABS_PATHLENGTH = 1


if sys.platform == 'win32':
    if win32utils.winver == 'Windows 98':
        abspath = _win98_abspath
    else:
        abspath = _win32_abspath
    realpath = _win32_realpath
    pathjoin = _win32_pathjoin
    normpath = _win32_normpath
    getcwd = _win32_getcwd
    mkdtemp = _win32_mkdtemp
    rename = _win32_rename
    try:
        from bzrlib import _walkdirs_win32
    except ImportError:
        pass
    else:
        lstat = _walkdirs_win32.lstat
        fstat = _walkdirs_win32.fstat
        wrap_stat = _walkdirs_win32.wrap_stat

    MIN_ABS_PATHLENGTH = 3

    def _win32_delete_readonly(function, path, excinfo):
        """Error handler for shutil.rmtree function [for win32]
        Helps to remove files and dirs marked as read-only.
        """
        exception = excinfo[1]
        if function in (os.remove, os.rmdir) \
            and isinstance(exception, OSError) \
            and exception.errno == errno.EACCES:
            make_writable(path)
            function(path)
        else:
            raise

    def rmtree(path, ignore_errors=False, onerror=_win32_delete_readonly):
        """Replacer for shutil.rmtree: could remove readonly dirs/files"""
        return shutil.rmtree(path, ignore_errors, onerror)

    f = win32utils.get_unicode_argv     # special function or None
    if f is not None:
        get_unicode_argv = f

elif sys.platform == 'darwin':
    getcwd = _mac_getcwd


def get_terminal_encoding(trace=False):
    """Find the best encoding for printing to the screen.

    This attempts to check both sys.stdout and sys.stdin to see
    what encoding they are in, and if that fails it falls back to
    osutils.get_user_encoding().
    The problem is that on Windows, locale.getpreferredencoding()
    is not the same encoding as that used by the console:
    http://mail.python.org/pipermail/python-list/2003-May/162357.html

    On my standard US Windows XP, the preferred encoding is
    cp1252, but the console is cp437

    :param trace: If True trace the selected encoding via mutter().
    """
    from bzrlib.trace import mutter
    output_encoding = getattr(sys.stdout, 'encoding', None)
    if not output_encoding:
        input_encoding = getattr(sys.stdin, 'encoding', None)
        if not input_encoding:
            output_encoding = get_user_encoding()
            if trace:
                mutter('encoding stdout as osutils.get_user_encoding() %r',
                   output_encoding)
        else:
            output_encoding = input_encoding
            if trace:
                mutter('encoding stdout as sys.stdin encoding %r',
                    output_encoding)
    else:
        if trace:
            mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
    if output_encoding == 'cp0':
        # invalid encoding (cp0 means 'no codepage' on Windows)
        output_encoding = get_user_encoding()
        if trace:
            mutter('cp0 is invalid encoding.'
               ' encoding stdout as osutils.get_user_encoding() %r',
               output_encoding)
    # check encoding
    try:
        codecs.lookup(output_encoding)
    except LookupError:
        sys.stderr.write('bzr: warning:'
                         ' unknown terminal encoding %s.\n'
                         '  Using encoding %s instead.\n'
                         % (output_encoding, get_user_encoding())
                        )
        output_encoding = get_user_encoding()

    return output_encoding


def normalizepath(f):
    if getattr(os.path, 'realpath', None) is not None:
        F = realpath
    else:
        F = abspath
    [p,e] = os.path.split(f)
    if e == "" or e == "." or e == "..":
        return F(f)
    else:
        return pathjoin(F(p), e)


def isdir(f):
    """True if f is an accessible directory."""
    try:
        return stat.S_ISDIR(os.lstat(f)[stat.ST_MODE])
    except OSError:
        return False


def isfile(f):
    """True if f is a regular file."""
    try:
        return stat.S_ISREG(os.lstat(f)[stat.ST_MODE])
    except OSError:
        return False

def islink(f):
    """True if f is a symlink."""
    try:
        return stat.S_ISLNK(os.lstat(f)[stat.ST_MODE])
    except OSError:
        return False

def is_inside(dir, fname):
    """True if fname is inside dir.

    The parameters should typically be passed to osutils.normpath first, so
    that . and .. and repeated slashes are eliminated, and the separators
    are canonical for the platform.

    The empty string as a dir name is taken as top-of-tree and matches
    everything.
    """
    # XXX: Most callers of this can actually do something smarter by
    # looking at the inventory
    if dir == fname:
        return True

    if dir == '':
        return True

    if dir[-1] != '/':
        dir += '/'

    return fname.startswith(dir)


def is_inside_any(dir_list, fname):
    """True if fname is inside any of given dirs."""
    for dirname in dir_list:
        if is_inside(dirname, fname):
            return True
    return False


def is_inside_or_parent_of_any(dir_list, fname):
    """True if fname is a child or a parent of any of the given files."""
    for dirname in dir_list:
        if is_inside(dirname, fname) or is_inside(fname, dirname):
            return True
    return False


def pumpfile(from_file, to_file, read_length=-1, buff_size=32768,
             report_activity=None, direction='read'):
    """Copy contents of one file to another.

    The read_length can either be -1 to read to end-of-file (EOF) or
    it can specify the maximum number of bytes to read.

    The buff_size represents the maximum size for each read operation
    performed on from_file.

    :param report_activity: Call this as bytes are read, see
        Transport._report_activity
    :param direction: Will be passed to report_activity

    :return: The number of bytes copied.
    """
    length = 0
    if read_length >= 0:
        # read specified number of bytes

        while read_length > 0:
            num_bytes_to_read = min(read_length, buff_size)

            block = from_file.read(num_bytes_to_read)
            if not block:
                # EOF reached
                break
            if report_activity is not None:
                report_activity(len(block), direction)
            to_file.write(block)

            actual_bytes_read = len(block)
            read_length -= actual_bytes_read
            length += actual_bytes_read
    else:
        # read to EOF
        while True:
            block = from_file.read(buff_size)
            if not block:
                # EOF reached
                break
            if report_activity is not None:
                report_activity(len(block), direction)
            to_file.write(block)
            length += len(block)
    return length


def pump_string_file(bytes, file_handle, segment_size=None):
    """Write bytes to file_handle in many smaller writes.

    :param bytes: The string to write.
    :param file_handle: The file to write to.
    """
    # Write data in chunks rather than all at once, because very large
    # writes fail on some platforms (e.g. Windows with SMB  mounted
    # drives).
    if not segment_size:
        segment_size = 5242880 # 5MB
    segments = range(len(bytes) / segment_size + 1)
    write = file_handle.write
    for segment_index in segments:
        segment = buffer(bytes, segment_index * segment_size, segment_size)
        write(segment)


def file_iterator(input_file, readsize=32768):
    while True:
        b = input_file.read(readsize)
        if len(b) == 0:
            break
        yield b


def sha_file(f):
    """Calculate the hexdigest of an open file.

    The file cursor should be already at the start.
    """
    s = sha()
    BUFSIZE = 128<<10
    while True:
        b = f.read(BUFSIZE)
        if not b:
            break
        s.update(b)
    return s.hexdigest()


def size_sha_file(f):
    """Calculate the size and hexdigest of an open file.

    The file cursor should be already at the start and
    the caller is responsible for closing the file afterwards.
    """
    size = 0
    s = sha()
    BUFSIZE = 128<<10
    while True:
        b = f.read(BUFSIZE)
        if not b:
            break
        size += len(b)
        s.update(b)
    return size, s.hexdigest()


def sha_file_by_name(fname):
    """Calculate the SHA1 of a file by reading the full text"""
    s = sha()
    f = os.open(fname, os.O_RDONLY | O_BINARY | O_NOINHERIT)
    try:
        while True:
            b = os.read(f, 1<<16)
            if not b:
                return s.hexdigest()
            s.update(b)
    finally:
        os.close(f)


def sha_strings(strings, _factory=sha):
    """Return the sha-1 of concatenation of strings"""
    s = _factory()
    map(s.update, strings)
    return s.hexdigest()


def sha_string(f, _factory=sha):
    return _factory(f).hexdigest()


def fingerprint_file(f):
    b = f.read()
    return {'size': len(b),
            'sha1': sha(b).hexdigest()}


def compare_files(a, b):
    """Returns true if equal in contents"""
    BUFSIZE = 4096
    while True:
        ai = a.read(BUFSIZE)
        bi = b.read(BUFSIZE)
        if ai != bi:
            return False
        if ai == '':
            return True


def local_time_offset(t=None):
    """Return offset of local zone from GMT, either at present or at time t."""
    if t is None:
        t = time.time()
    offset = datetime.fromtimestamp(t) - datetime.utcfromtimestamp(t)
    return offset.days * 86400 + offset.seconds

weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
_default_format_by_weekday_num = [wd + " %Y-%m-%d %H:%M:%S" for wd in weekdays]


def format_date(t, offset=0, timezone='original', date_fmt=None,
                show_offset=True):
    """Return a formatted date string.

    :param t: Seconds since the epoch.
    :param offset: Timezone offset in seconds east of utc.
    :param timezone: How to display the time: 'utc', 'original' for the
         timezone specified by offset, or 'local' for the process's current
         timezone.
    :param date_fmt: strftime format.
    :param show_offset: Whether to append the timezone.
    """
    (date_fmt, tt, offset_str) = \
               _format_date(t, offset, timezone, date_fmt, show_offset)
    date_fmt = date_fmt.replace('%a', weekdays[tt[6]])
    date_str = time.strftime(date_fmt, tt)
    return date_str + offset_str


# Cache of formatted offset strings
_offset_cache = {}


def format_date_with_offset_in_original_timezone(t, offset=0,
    _cache=_offset_cache):
    """Return a formatted date string in the original timezone.

    This routine may be faster then format_date.

    :param t: Seconds since the epoch.
    :param offset: Timezone offset in seconds east of utc.
    """
    if offset is None:
        offset = 0
    tt = time.gmtime(t + offset)
    date_fmt = _default_format_by_weekday_num[tt[6]]
    date_str = time.strftime(date_fmt, tt)
    offset_str = _cache.get(offset, None)
    if offset_str is None:
        offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
        _cache[offset] = offset_str
    return date_str + offset_str


def format_local_date(t, offset=0, timezone='original', date_fmt=None,
                      show_offset=True):
    """Return an unicode date string formatted according to the current locale.

    :param t: Seconds since the epoch.
    :param offset: Timezone offset in seconds east of utc.
    :param timezone: How to display the time: 'utc', 'original' for the
         timezone specified by offset, or 'local' for the process's current
         timezone.
    :param date_fmt: strftime format.
    :param show_offset: Whether to append the timezone.
    """
    (date_fmt, tt, offset_str) = \
               _format_date(t, offset, timezone, date_fmt, show_offset)
    date_str = time.strftime(date_fmt, tt)
    if not isinstance(date_str, unicode):
        date_str = date_str.decode(get_user_encoding(), 'replace')
    return date_str + offset_str


def _format_date(t, offset, timezone, date_fmt, show_offset):
    if timezone == 'utc':
        tt = time.gmtime(t)
        offset = 0
    elif timezone == 'original':
        if offset is None:
            offset = 0
        tt = time.gmtime(t + offset)
    elif timezone == 'local':
        tt = time.localtime(t)
        offset = local_time_offset(t)
    else:
        raise errors.UnsupportedTimezoneFormat(timezone)
    if date_fmt is None:
        date_fmt = "%a %Y-%m-%d %H:%M:%S"
    if show_offset:
        offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
    else:
        offset_str = ''
    return (date_fmt, tt, offset_str)


def compact_date(when):
    return time.strftime('%Y%m%d%H%M%S', time.gmtime(when))


def format_delta(delta):
    """Get a nice looking string for a time delta.

    :param delta: The time difference in seconds, can be positive or negative.
        positive indicates time in the past, negative indicates time in the
        future. (usually time.time() - stored_time)
    :return: String formatted to show approximate resolution
    """
    delta = int(delta)
    if delta >= 0:
        direction = 'ago'
    else:
        direction = 'in the future'
        delta = -delta

    seconds = delta
    if seconds < 90: # print seconds up to 90 seconds
        if seconds == 1:
            return '%d second %s' % (seconds, direction,)
        else:
            return '%d seconds %s' % (seconds, direction)

    minutes = int(seconds / 60)
    seconds -= 60 * minutes
    if seconds == 1:
        plural_seconds = ''
    else:
        plural_seconds = 's'
    if minutes < 90: # print minutes, seconds up to 90 minutes
        if minutes == 1:
            return '%d minute, %d second%s %s' % (
                    minutes, seconds, plural_seconds, direction)
        else:
            return '%d minutes, %d second%s %s' % (
                    minutes, seconds, plural_seconds, direction)

    hours = int(minutes / 60)
    minutes -= 60 * hours
    if minutes == 1:
        plural_minutes = ''
    else:
        plural_minutes = 's'

    if hours == 1:
        return '%d hour, %d minute%s %s' % (hours, minutes,
                                            plural_minutes, direction)
    return '%d hours, %d minute%s %s' % (hours, minutes,
                                         plural_minutes, direction)

def filesize(f):
    """Return size of given open file."""
    return os.fstat(f.fileno())[stat.ST_SIZE]


# Define rand_bytes based on platform.
try:
    # Python 2.4 and later have os.urandom,
    # but it doesn't work on some arches
    os.urandom(1)
    rand_bytes = os.urandom
except (NotImplementedError, AttributeError):
    # If python doesn't have os.urandom, or it doesn't work,
    # then try to first pull random data from /dev/urandom
    try:
        rand_bytes = file('/dev/urandom', 'rb').read
    # Otherwise, use this hack as a last resort
    except (IOError, OSError):
        # not well seeded, but better than nothing
        def rand_bytes(n):
            import random
            s = ''
            while n:
                s += chr(random.randint(0, 255))
                n -= 1
            return s


ALNUM = '0123456789abcdefghijklmnopqrstuvwxyz'
def rand_chars(num):
    """Return a random string of num alphanumeric characters

    The result only contains lowercase chars because it may be used on
    case-insensitive filesystems.
    """
    s = ''
    for raw_byte in rand_bytes(num):
        s += ALNUM[ord(raw_byte) % 36]
    return s


## TODO: We could later have path objects that remember their list
## decomposition (might be too tricksy though.)

def splitpath(p):
    """Turn string into list of parts."""
    # split on either delimiter because people might use either on
    # Windows
    ps = re.split(r'[\\/]', p)

    rps = []
    for f in ps:
        if f == '..':
            raise errors.BzrError("sorry, %r not allowed in path" % f)
        elif (f == '.') or (f == ''):
            pass
        else:
            rps.append(f)
    return rps


def joinpath(p):
    for f in p:
        if (f == '..') or (f is None) or (f == ''):
            raise errors.BzrError("sorry, %r not allowed in path" % f)
    return pathjoin(*p)


def parent_directories(filename):
    """Return the list of parent directories, deepest first.

    For example, parent_directories("a/b/c") -> ["a/b", "a"].
    """
    parents = []
    parts = splitpath(dirname(filename))
    while parts:
        parents.append(joinpath(parts))
        parts.pop()
    return parents


_extension_load_failures = []


def failed_to_load_extension(exception):
    """Handle failing to load a binary extension.

    This should be called from the ImportError block guarding the attempt to
    import the native extension.  If this function returns, the pure-Python
    implementation should be loaded instead::

    >>> try:
    >>>     import bzrlib._fictional_extension_pyx
    >>> except ImportError, e:
    >>>     bzrlib.osutils.failed_to_load_extension(e)
    >>>     import bzrlib._fictional_extension_py
    """
    # NB: This docstring is just an example, not a doctest, because doctest
    # currently can't cope with the use of lazy imports in this namespace --
    # mbp 20090729

    # This currently doesn't report the failure at the time it occurs, because
    # they tend to happen very early in startup when we can't check config
    # files etc, and also we want to report all failures but not spam the user
    # with 10 warnings.
    exception_str = str(exception)
    if exception_str not in _extension_load_failures:
        trace.mutter("failed to load compiled extension: %s" % exception_str)
        _extension_load_failures.append(exception_str)


def report_extension_load_failures():
    if not _extension_load_failures:
        return
    from bzrlib.config import GlobalConfig
    if GlobalConfig().get_user_option_as_bool('ignore_missing_extensions'):
        return
    # the warnings framework should by default show this only once
    from bzrlib.trace import warning
    warning(
        "bzr: warning: some compiled extensions could not be loaded; "
        "see <https://answers.launchpad.net/bzr/+faq/703>")
    # we no longer show the specific missing extensions here, because it makes
    # the message too long and scary - see
    # https://bugs.launchpad.net/bzr/+bug/430529


try:
    from bzrlib._chunks_to_lines_pyx import chunks_to_lines
except ImportError, e:
    failed_to_load_extension(e)
    from bzrlib._chunks_to_lines_py import chunks_to_lines


def split_lines(s):
    """Split s into lines, but without removing the newline characters."""
    # Trivially convert a fulltext into a 'chunked' representation, and let
    # chunks_to_lines do the heavy lifting.
    if isinstance(s, str):
        # chunks_to_lines only supports 8-bit strings
        return chunks_to_lines([s])
    else:
        return _split_lines(s)


def _split_lines(s):
    """Split s into lines, but without removing the newline characters.

    This supports Unicode or plain string objects.
    """
    lines = s.split('\n')
    result = [line + '\n' for line in lines[:-1]]
    if lines[-1]:
        result.append(lines[-1])
    return result


def hardlinks_good():
    return sys.platform not in ('win32', 'cygwin', 'darwin')


def link_or_copy(src, dest):
    """Hardlink a file, or copy it if it can't be hardlinked."""
    if not hardlinks_good():
        shutil.copyfile(src, dest)
        return
    try:
        os.link(src, dest)
    except (OSError, IOError), e:
        if e.errno != errno.EXDEV:
            raise
        shutil.copyfile(src, dest)


def delete_any(path):
    """Delete a file, symlink or directory.

    Will delete even if readonly.
    """
    try:
       _delete_file_or_dir(path)
    except (OSError, IOError), e:
        if e.errno in (errno.EPERM, errno.EACCES):
            # make writable and try again
            try:
                make_writable(path)
            except (OSError, IOError):
                pass
            _delete_file_or_dir(path)
        else:
            raise


def _delete_file_or_dir(path):
    # Look Before You Leap (LBYL) is appropriate here instead of Easier to Ask for
    # Forgiveness than Permission (EAFP) because:
    # - root can damage a solaris file system by using unlink,
    # - unlink raises different exceptions on different OSes (linux: EISDIR, win32:
    #   EACCES, OSX: EPERM) when invoked on a directory.
    if isdir(path): # Takes care of symlinks
        os.rmdir(path)
    else:
        os.unlink(path)


def has_symlinks():
    if getattr(os, 'symlink', None) is not None:
        return True
    else:
        return False


def has_hardlinks():
    if getattr(os, 'link', None) is not None:
        return True
    else:
        return False


def host_os_dereferences_symlinks():
    return (has_symlinks()
            and sys.platform not in ('cygwin', 'win32'))


def readlink(abspath):
    """Return a string representing the path to which the symbolic link points.

    :param abspath: The link absolute unicode path.

    This his guaranteed to return the symbolic link in unicode in all python
    versions.
    """
    link = abspath.encode(_fs_enc)
    target = os.readlink(link)
    target = target.decode(_fs_enc)
    return target


def contains_whitespace(s):
    """True if there are any whitespace characters in s."""
    # string.whitespace can include '\xa0' in certain locales, because it is
    # considered "non-breaking-space" as part of ISO-8859-1. But it
    # 1) Isn't a breaking whitespace
    # 2) Isn't one of ' \t\r\n' which are characters we sometimes use as
    #    separators
    # 3) '\xa0' isn't unicode safe since it is >128.

    # This should *not* be a unicode set of characters in case the source
    # string is not a Unicode string. We can auto-up-cast the characters since
    # they are ascii, but we don't want to auto-up-cast the string in case it
    # is utf-8
    for ch in ' \t\n\r\v\f':
        if ch in s:
            return True
    else:
        return False


def contains_linebreaks(s):
    """True if there is any vertical whitespace in s."""
    for ch in '\f\n\r':
        if ch in s:
            return True
    else:
        return False


def relpath(base, path):
    """Return path relative to base, or raise PathNotChild exception.

    The path may be either an absolute path or a path relative to the
    current working directory.

    os.path.commonprefix (python2.4) has a bad bug that it works just
    on string prefixes, assuming that '/u' is a prefix of '/u2'.  This
    avoids that problem.

    NOTE: `base` should not have a trailing slash otherwise you'll get
    PathNotChild exceptions regardless of `path`.
    """

    if len(base) < MIN_ABS_PATHLENGTH:
        # must have space for e.g. a drive letter
        raise ValueError('%r is too short to calculate a relative path'
            % (base,))

    rp = abspath(path)

    s = []
    head = rp
    while True:
        if len(head) <= len(base) and head != base:
            raise errors.PathNotChild(rp, base)
        if head == base:
            break
        head, tail = split(head)
        if tail:
            s.append(tail)

    if s:
        return pathjoin(*reversed(s))
    else:
        return ''


def _cicp_canonical_relpath(base, path):
    """Return the canonical path relative to base.

    Like relpath, but on case-insensitive-case-preserving file-systems, this
    will return the relpath as stored on the file-system rather than in the
    case specified in the input string, for all existing portions of the path.

    This will cause O(N) behaviour if called for every path in a tree; if you
    have a number of paths to convert, you should use canonical_relpaths().
    """
    # TODO: it should be possible to optimize this for Windows by using the
    # win32 API FindFiles function to look for the specified name - but using
    # os.listdir() still gives us the correct, platform agnostic semantics in
    # the short term.

    rel = relpath(base, path)
    # '.' will have been turned into ''
    if not rel:
        return rel

    abs_base = abspath(base)
    current = abs_base
    _listdir = os.listdir

    # use an explicit iterator so we can easily consume the rest on early exit.
    bit_iter = iter(rel.split('/'))
    for bit in bit_iter:
        lbit = bit.lower()
        try:
            next_entries = _listdir(current)
        except OSError: # enoent, eperm, etc
            # We can't find this in the filesystem, so just append the
            # remaining bits.
            current = pathjoin(current, bit, *list(bit_iter))
            break
        for look in next_entries:
            if lbit == look.lower():
                current = pathjoin(current, look)
                break
        else:
            # got to the end, nothing matched, so we just return the
            # non-existing bits as they were specified (the filename may be
            # the target of a move, for example).
            current = pathjoin(current, bit, *list(bit_iter))
            break
    return current[len(abs_base):].lstrip('/')

# XXX - TODO - we need better detection/integration of case-insensitive
# file-systems; Linux often sees FAT32 devices (or NFS-mounted OSX
# filesystems), for example, so could probably benefit from the same basic
# support there.  For now though, only Windows and OSX get that support, and
# they get it for *all* file-systems!
if sys.platform in ('win32', 'darwin'):
    canonical_relpath = _cicp_canonical_relpath
else:
    canonical_relpath = relpath

def canonical_relpaths(base, paths):
    """Create an iterable to canonicalize a sequence of relative paths.

    The intent is for this implementation to use a cache, vastly speeding
    up multiple transformations in the same directory.
    """
    # but for now, we haven't optimized...
    return [canonical_relpath(base, p) for p in paths]


def decode_filename(filename):
    """Decode the filename using the filesystem encoding

    If it is unicode, it is returned.
    Otherwise it is decoded from the the filesystem's encoding. If decoding
    fails, a errors.BadFilenameEncoding exception is raised.
    """
    if type(filename) is unicode:
        return filename
    try:
        return filename.decode(_fs_enc)
    except UnicodeDecodeError:
        raise errors.BadFilenameEncoding(filename, _fs_enc)


def safe_unicode(unicode_or_utf8_string):
    """Coerce unicode_or_utf8_string into unicode.

    If it is unicode, it is returned.
    Otherwise it is decoded from utf-8. If decoding fails, the exception is
    wrapped in a BzrBadParameterNotUnicode exception.
    """
    if isinstance(unicode_or_utf8_string, unicode):
        return unicode_or_utf8_string
    try:
        return unicode_or_utf8_string.decode('utf8')
    except UnicodeDecodeError:
        raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)


def safe_utf8(unicode_or_utf8_string):
    """Coerce unicode_or_utf8_string to a utf8 string.

    If it is a str, it is returned.
    If it is Unicode, it is encoded into a utf-8 string.
    """
    if isinstance(unicode_or_utf8_string, str):
        # TODO: jam 20070209 This is overkill, and probably has an impact on
        #       performance if we are dealing with lots of apis that want a
        #       utf-8 revision id
        try:
            # Make sure it is a valid utf-8 string
            unicode_or_utf8_string.decode('utf-8')
        except UnicodeDecodeError:
            raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
        return unicode_or_utf8_string
    return unicode_or_utf8_string.encode('utf-8')


_revision_id_warning = ('Unicode revision ids were deprecated in bzr 0.15.'
                        ' Revision id generators should be creating utf8'
                        ' revision ids.')


def safe_revision_id(unicode_or_utf8_string, warn=True):
    """Revision ids should now be utf8, but at one point they were unicode.

    :param unicode_or_utf8_string: A possibly Unicode revision_id. (can also be
        utf8 or None).
    :param warn: Functions that are sanitizing user data can set warn=False
    :return: None or a utf8 revision id.
    """
    if (unicode_or_utf8_string is None
        or unicode_or_utf8_string.__class__ == str):
        return unicode_or_utf8_string
    if warn:
        symbol_versioning.warn(_revision_id_warning, DeprecationWarning,
                               stacklevel=2)
    return cache_utf8.encode(unicode_or_utf8_string)


_file_id_warning = ('Unicode file ids were deprecated in bzr 0.15. File id'
                    ' generators should be creating utf8 file ids.')


def safe_file_id(unicode_or_utf8_string, warn=True):
    """File ids should now be utf8, but at one point they were unicode.

    This is the same as safe_utf8, except it uses the cached encode functions
    to save a little bit of performance.

    :param unicode_or_utf8_string: A possibly Unicode file_id. (can also be
        utf8 or None).
    :param warn: Functions that are sanitizing user data can set warn=False
    :return: None or a utf8 file id.
    """
    if (unicode_or_utf8_string is None
        or unicode_or_utf8_string.__class__ == str):
        return unicode_or_utf8_string
    if warn:
        symbol_versioning.warn(_file_id_warning, DeprecationWarning,
                               stacklevel=2)
    return cache_utf8.encode(unicode_or_utf8_string)


_platform_normalizes_filenames = False
if sys.platform == 'darwin':
    _platform_normalizes_filenames = True


def normalizes_filenames():
    """Return True if this platform normalizes unicode filenames.

    Only Mac OSX.
    """
    return _platform_normalizes_filenames


def _accessible_normalized_filename(path):
    """Get the unicode normalized path, and if you can access the file.

    On platforms where the system normalizes filenames (Mac OSX),
    you can access a file by any path which will normalize correctly.
    On platforms where the system does not normalize filenames
    (everything else), you have to access a file by its exact path.

    Internally, bzr only supports NFC normalization, since that is
    the standard for XML documents.

    So return the normalized path, and a flag indicating if the file
    can be accessed by that path.
    """

    return unicodedata.normalize('NFC', unicode(path)), True


def _inaccessible_normalized_filename(path):
    __doc__ = _accessible_normalized_filename.__doc__

    normalized = unicodedata.normalize('NFC', unicode(path))
    return normalized, normalized == path


if _platform_normalizes_filenames:
    normalized_filename = _accessible_normalized_filename
else:
    normalized_filename = _inaccessible_normalized_filename


def set_signal_handler(signum, handler, restart_syscall=True):
    """A wrapper for signal.signal that also calls siginterrupt(signum, False)
    on platforms that support that.

    :param restart_syscall: if set, allow syscalls interrupted by a signal to
        automatically restart (by calling `signal.siginterrupt(signum,
        False)`).  May be ignored if the feature is not available on this
        platform or Python version.
    """
    try:
        import signal
        siginterrupt = signal.siginterrupt
    except ImportError:
        # This python implementation doesn't provide signal support, hence no
        # handler exists
        return None
    except AttributeError:
        # siginterrupt doesn't exist on this platform, or for this version
        # of Python.
        siginterrupt = lambda signum, flag: None
    if restart_syscall:
        def sig_handler(*args):
            # Python resets the siginterrupt flag when a signal is
            # received.  <http://bugs.python.org/issue8354>
            # As a workaround for some cases, set it back the way we want it.
            siginterrupt(signum, False)
            # Now run the handler function passed to set_signal_handler.
            handler(*args)
    else:
        sig_handler = handler
    old_handler = signal.signal(signum, sig_handler)
    if restart_syscall:
        siginterrupt(signum, False)
    return old_handler


default_terminal_width = 80
"""The default terminal width for ttys.

This is defined so that higher levels can share a common fallback value when
terminal_width() returns None.
"""

# Keep some state so that terminal_width can detect if _terminal_size has
# returned a different size since the process started.  See docstring and
# comments of terminal_width for details.
# _terminal_size_state has 3 possible values: no_data, unchanged, and changed.
_terminal_size_state = 'no_data'
_first_terminal_size = None

def terminal_width():
    """Return terminal width.

    None is returned if the width can't established precisely.

    The rules are:
    - if BZR_COLUMNS is set, returns its value
    - if there is no controlling terminal, returns None
    - query the OS, if the queried size has changed since the last query,
      return its value,
    - if COLUMNS is set, returns its value,
    - if the OS has a value (even though it's never changed), return its value.

    From there, we need to query the OS to get the size of the controlling
    terminal.

    On Unices we query the OS by:
    - get termios.TIOCGWINSZ
    - if an error occurs or a negative value is obtained, returns None

    On Windows we query the OS by:
    - win32utils.get_console_size() decides,
    - returns None on error (provided default value)
    """
    # Note to implementors: if changing the rules for determining the width,
    # make sure you've considered the behaviour in these cases:
    #  - M-x shell in emacs, where $COLUMNS is set and TIOCGWINSZ returns 0,0.
    #  - bzr log | less, in bash, where $COLUMNS not set and TIOCGWINSZ returns
    #    0,0.
    #  - (add more interesting cases here, if you find any)
    # Some programs implement "Use $COLUMNS (if set) until SIGWINCH occurs",
    # but we don't want to register a signal handler because it is impossible
    # to do so without risking EINTR errors in Python <= 2.6.5 (see
    # <http://bugs.python.org/issue8354>).  Instead we check TIOCGWINSZ every
    # time so we can notice if the reported size has changed, which should have
    # a similar effect.

    # If BZR_COLUMNS is set, take it, user is always right
    # Except if they specified 0 in which case, impose no limit here
    try:
        width = int(os.environ['BZR_COLUMNS'])
    except (KeyError, ValueError):
        width = None
    if width is not None:
        if width > 0:
            return width
        else:
            return None

    isatty = getattr(sys.stdout, 'isatty', None)
    if isatty is None or not isatty():
        # Don't guess, setting BZR_COLUMNS is the recommended way to override.
        return None

    # Query the OS
    width, height = os_size = _terminal_size(None, None)
    global _first_terminal_size, _terminal_size_state
    if _terminal_size_state == 'no_data':
        _first_terminal_size = os_size
        _terminal_size_state = 'unchanged'
    elif (_terminal_size_state == 'unchanged' and
          _first_terminal_size != os_size):
        _terminal_size_state = 'changed'

    # If the OS claims to know how wide the terminal is, and this value has
    # ever changed, use that.
    if _terminal_size_state == 'changed':
        if width is not None and width > 0:
            return width

    # If COLUMNS is set, use it.
    try:
        return int(os.environ['COLUMNS'])
    except (KeyError, ValueError):
        pass

    # Finally, use an unchanged size from the OS, if we have one.
    if _terminal_size_state == 'unchanged':
        if width is not None and width > 0:
            return width

    # The width could not be determined.
    return None


def _win32_terminal_size(width, height):
    width, height = win32utils.get_console_size(defaultx=width, defaulty=height)
    return width, height


def _ioctl_terminal_size(width, height):
    try:
        import struct, fcntl, termios
        s = struct.pack('HHHH', 0, 0, 0, 0)
        x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
        height, width = struct.unpack('HHHH', x)[0:2]
    except (IOError, AttributeError):
        pass
    return width, height

_terminal_size = None
"""Returns the terminal size as (width, height).

:param width: Default value for width.
:param height: Default value for height.

This is defined specifically for each OS and query the size of the controlling
terminal. If any error occurs, the provided default values should be returned.
"""
if sys.platform == 'win32':
    _terminal_size = _win32_terminal_size
else:
    _terminal_size = _ioctl_terminal_size


def supports_executable():
    return sys.platform != "win32"


def supports_posix_readonly():
    """Return True if 'readonly' has POSIX semantics, False otherwise.

    Notably, a win32 readonly file cannot be deleted, unlike POSIX where the
    directory controls creation/deletion, etc.

    And under win32, readonly means that the directory itself cannot be
    deleted.  The contents of a readonly directory can be changed, unlike POSIX
    where files in readonly directories cannot be added, deleted or renamed.
    """
    return sys.platform != "win32"


def set_or_unset_env(env_variable, value):
    """Modify the environment, setting or removing the env_variable.

    :param env_variable: The environment variable in question
    :param value: The value to set the environment to. If None, then
        the variable will be removed.
    :return: The original value of the environment variable.
    """
    orig_val = os.environ.get(env_variable)
    if value is None:
        if orig_val is not None:
            del os.environ[env_variable]
    else:
        if isinstance(value, unicode):
            value = value.encode(get_user_encoding())
        os.environ[env_variable] = value
    return orig_val


_validWin32PathRE = re.compile(r'^([A-Za-z]:[/\\])?[^:<>*"?\|]*$')


def check_legal_path(path):
    """Check whether the supplied path is legal.
    This is only required on Windows, so we don't test on other platforms
    right now.
    """
    if sys.platform != "win32":
        return
    if _validWin32PathRE.match(path) is None:
        raise errors.IllegalPath(path)


_WIN32_ERROR_DIRECTORY = 267 # Similar to errno.ENOTDIR

def _is_error_enotdir(e):
    """Check if this exception represents ENOTDIR.

    Unfortunately, python is very inconsistent about the exception
    here. The cases are:
      1) Linux, Mac OSX all versions seem to set errno == ENOTDIR
      2) Windows, Python2.4, uses errno == ERROR_DIRECTORY (267)
         which is the windows error code.
      3) Windows, Python2.5 uses errno == EINVAL and
         winerror == ERROR_DIRECTORY

    :param e: An Exception object (expected to be OSError with an errno
        attribute, but we should be able to cope with anything)
    :return: True if this represents an ENOTDIR error. False otherwise.
    """
    en = getattr(e, 'errno', None)
    if (en == errno.ENOTDIR
        or (sys.platform == 'win32'
            and (en == _WIN32_ERROR_DIRECTORY
                 or (en == errno.EINVAL
                     and getattr(e, 'winerror', None) == _WIN32_ERROR_DIRECTORY)
        ))):
        return True
    return False


def walkdirs(top, prefix=""):
    """Yield data about all the directories in a tree.

    This yields all the data about the contents of a directory at a time.
    After each directory has been yielded, if the caller has mutated the list
    to exclude some directories, they are then not descended into.

    The data yielded is of the form:
    ((directory-relpath, directory-path-from-top),
    [(relpath, basename, kind, lstat, path-from-top), ...]),
     - directory-relpath is the relative path of the directory being returned
       with respect to top. prefix is prepended to this.
     - directory-path-from-root is the path including top for this directory.
       It is suitable for use with os functions.
     - relpath is the relative path within the subtree being walked.
     - basename is the basename of the path
     - kind is the kind of the file now. If unknown then the file is not
       present within the tree - but it may be recorded as versioned. See
       versioned_kind.
     - lstat is the stat data *if* the file was statted.
     - planned, not implemented:
       path_from_tree_root is the path from the root of the tree.

    :param prefix: Prefix the relpaths that are yielded with 'prefix'. This
        allows one to walk a subtree but get paths that are relative to a tree
        rooted higher up.
    :return: an iterator over the dirs.
    """
    #TODO there is a bit of a smell where the results of the directory-
    # summary in this, and the path from the root, may not agree
    # depending on top and prefix - i.e. ./foo and foo as a pair leads to
    # potentially confusing output. We should make this more robust - but
    # not at a speed cost. RBC 20060731
    _lstat = os.lstat
    _directory = _directory_kind
    _listdir = os.listdir
    _kind_from_mode = file_kind_from_stat_mode
    pending = [(safe_unicode(prefix), "", _directory, None, safe_unicode(top))]
    while pending:
        # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
        relroot, _, _, _, top = pending.pop()
        if relroot:
            relprefix = relroot + u'/'
        else:
            relprefix = ''
        top_slash = top + u'/'

        dirblock = []
        append = dirblock.append
        try:
            names = sorted(map(decode_filename, _listdir(top)))
        except OSError, e:
            if not _is_error_enotdir(e):
                raise
        else:
            for name in names:
                abspath = top_slash + name
                statvalue = _lstat(abspath)
                kind = _kind_from_mode(statvalue.st_mode)
                append((relprefix + name, name, kind, statvalue, abspath))
        yield (relroot, top), dirblock

        # push the user specified dirs from dirblock
        pending.extend(d for d in reversed(dirblock) if d[2] == _directory)


class DirReader(object):
    """An interface for reading directories."""

    def top_prefix_to_starting_dir(self, top, prefix=""):
        """Converts top and prefix to a starting dir entry

        :param top: A utf8 path
        :param prefix: An optional utf8 path to prefix output relative paths
            with.
        :return: A tuple starting with prefix, and ending with the native
            encoding of top.
        """
        raise NotImplementedError(self.top_prefix_to_starting_dir)

    def read_dir(self, prefix, top):
        """Read a specific dir.

        :param prefix: A utf8 prefix to be preprended to the path basenames.
        :param top: A natively encoded path to read.
        :return: A list of the directories contents. Each item contains:
            (utf8_relpath, utf8_name, kind, lstatvalue, native_abspath)
        """
        raise NotImplementedError(self.read_dir)


_selected_dir_reader = None


def _walkdirs_utf8(top, prefix=""):
    """Yield data about all the directories in a tree.

    This yields the same information as walkdirs() only each entry is yielded
    in utf-8. On platforms which have a filesystem encoding of utf8 the paths
    are returned as exact byte-strings.

    :return: yields a tuple of (dir_info, [file_info])
        dir_info is (utf8_relpath, path-from-top)
        file_info is (utf8_relpath, utf8_name, kind, lstat, path-from-top)
        if top is an absolute path, path-from-top is also an absolute path.
        path-from-top might be unicode or utf8, but it is the correct path to
        pass to os functions to affect the file in question. (such as os.lstat)
    """
    global _selected_dir_reader
    if _selected_dir_reader is None:
        fs_encoding = _fs_enc.upper()
        if sys.platform == "win32" and win32utils.winver == 'Windows NT':
            # Win98 doesn't have unicode apis like FindFirstFileW
            # TODO: We possibly could support Win98 by falling back to the
            #       original FindFirstFile, and using TCHAR instead of WCHAR,
            #       but that gets a bit tricky, and requires custom compiling
            #       for win98 anyway.
            try:
                from bzrlib._walkdirs_win32 import Win32ReadDir
                _selected_dir_reader = Win32ReadDir()
            except ImportError:
                pass
        elif fs_encoding in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
            # ANSI_X3.4-1968 is a form of ASCII
            try:
                from bzrlib._readdir_pyx import UTF8DirReader
                _selected_dir_reader = UTF8DirReader()
            except ImportError, e:
                failed_to_load_extension(e)
                pass

    if _selected_dir_reader is None:
        # Fallback to the python version
        _selected_dir_reader = UnicodeDirReader()

    # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
    # But we don't actually uses 1-3 in pending, so set them to None
    pending = [[_selected_dir_reader.top_prefix_to_starting_dir(top, prefix)]]
    read_dir = _selected_dir_reader.read_dir
    _directory = _directory_kind
    while pending:
        relroot, _, _, _, top = pending[-1].pop()
        if not pending[-1]:
            pending.pop()
        dirblock = sorted(read_dir(relroot, top))
        yield (relroot, top), dirblock
        # push the user specified dirs from dirblock
        next = [d for d in reversed(dirblock) if d[2] == _directory]
        if next:
            pending.append(next)


class UnicodeDirReader(DirReader):
    """A dir reader for non-utf8 file systems, which transcodes."""

    __slots__ = ['_utf8_encode']

    def __init__(self):
        self._utf8_encode = codecs.getencoder('utf8')

    def top_prefix_to_starting_dir(self, top, prefix=""):
        """See DirReader.top_prefix_to_starting_dir."""
        return (safe_utf8(prefix), None, None, None, safe_unicode(top))

    def read_dir(self, prefix, top):
        """Read a single directory from a non-utf8 file system.

        top, and the abspath element in the output are unicode, all other paths
        are utf8. Local disk IO is done via unicode calls to listdir etc.

        This is currently the fallback code path when the filesystem encoding is
        not UTF-8. It may be better to implement an alternative so that we can
        safely handle paths that are not properly decodable in the current
        encoding.

        See DirReader.read_dir for details.
        """
        _utf8_encode = self._utf8_encode
        _lstat = os.lstat
        _listdir = os.listdir
        _kind_from_mode = file_kind_from_stat_mode

        if prefix:
            relprefix = prefix + '/'
        else:
            relprefix = ''
        top_slash = top + u'/'

        dirblock = []
        append = dirblock.append
        for name in sorted(_listdir(top)):
            try:
                name_utf8 = _utf8_encode(name)[0]
            except UnicodeDecodeError:
                raise errors.BadFilenameEncoding(
                    _utf8_encode(relprefix)[0] + name, _fs_enc)
            abspath = top_slash + name
            statvalue = _lstat(abspath)
            kind = _kind_from_mode(statvalue.st_mode)
            append((relprefix + name_utf8, name_utf8, kind, statvalue, abspath))
        return dirblock


def copy_tree(from_path, to_path, handlers={}):
    """Copy all of the entries in from_path into to_path.

    :param from_path: The base directory to copy.
    :param to_path: The target directory. If it does not exist, it will
        be created.
    :param handlers: A dictionary of functions, which takes a source and
        destinations for files, directories, etc.
        It is keyed on the file kind, such as 'directory', 'symlink', or 'file'
        'file', 'directory', and 'symlink' should always exist.
        If they are missing, they will be replaced with 'os.mkdir()',
        'os.readlink() + os.symlink()', and 'shutil.copy2()', respectively.
    """
    # Now, just copy the existing cached tree to the new location
    # We use a cheap trick here.
    # Absolute paths are prefixed with the first parameter
    # relative paths are prefixed with the second.
    # So we can get both the source and target returned
    # without any extra work.

    def copy_dir(source, dest):
        os.mkdir(dest)

    def copy_link(source, dest):
        """Copy the contents of a symlink"""
        link_to = os.readlink(source)
        os.symlink(link_to, dest)

    real_handlers = {'file':shutil.copy2,
                     'symlink':copy_link,
                     'directory':copy_dir,
                    }
    real_handlers.update(handlers)

    if not os.path.exists(to_path):
        real_handlers['directory'](from_path, to_path)

    for dir_info, entries in walkdirs(from_path, prefix=to_path):
        for relpath, name, kind, st, abspath in entries:
            real_handlers[kind](abspath, relpath)


def copy_ownership_from_path(dst, src=None):
    """Copy usr/grp ownership from src file/dir to dst file/dir.

    If src is None, the containing directory is used as source. If chown
    fails, the error is ignored and a warning is printed.
    """
    chown = getattr(os, 'chown', None)
    if chown is None:
        return

    if src == None:
        src = os.path.dirname(dst)
        if src == '':
            src = '.'

    try:
        s = os.stat(src)
        chown(dst, s.st_uid, s.st_gid)
    except OSError, e:
        trace.warning(
            'Unable to copy ownership from "%s" to "%s". '
            'You may want to set it manually.', src, dst)
        trace.log_exception_quietly()


def path_prefix_key(path):
    """Generate a prefix-order path key for path.

    This can be used to sort paths in the same way that walkdirs does.
    """
    return (dirname(path) , path)


def compare_paths_prefix_order(path_a, path_b):
    """Compare path_a and path_b to generate the same order walkdirs uses."""
    key_a = path_prefix_key(path_a)
    key_b = path_prefix_key(path_b)
    return cmp(key_a, key_b)


_cached_user_encoding = None


def get_user_encoding(use_cache=True):
    """Find out what the preferred user encoding is.

    This is generally the encoding that is used for command line parameters
    and file contents. This may be different from the terminal encoding
    or the filesystem encoding.

    :param  use_cache:  Enable cache for detected encoding.
                        (This parameter is turned on by default,
                        and required only for selftesting)

    :return: A string defining the preferred user encoding
    """
    global _cached_user_encoding
    if _cached_user_encoding is not None and use_cache:
        return _cached_user_encoding

    if sys.platform == 'darwin':
        # python locale.getpreferredencoding() always return
        # 'mac-roman' on darwin. That's a lie.
        sys.platform = 'posix'
        try:
            if os.environ.get('LANG', None) is None:
                # If LANG is not set, we end up with 'ascii', which is bad
                # ('mac-roman' is more than ascii), so we set a default which
                # will give us UTF-8 (which appears to work in all cases on
                # OSX). Users are still free to override LANG of course, as
                # long as it give us something meaningful. This work-around
                # *may* not be needed with python 3k and/or OSX 10.5, but will
                # work with them too -- vila 20080908
                os.environ['LANG'] = 'en_US.UTF-8'
            import locale
        finally:
            sys.platform = 'darwin'
    else:
        import locale

    try:
        user_encoding = locale.getpreferredencoding()
    except locale.Error, e:
        sys.stderr.write('bzr: warning: %s\n'
                         '  Could not determine what text encoding to use.\n'
                         '  This error usually means your Python interpreter\n'
                         '  doesn\'t support the locale set by $LANG (%s)\n'
                         "  Continuing with ascii encoding.\n"
                         % (e, os.environ.get('LANG')))
        user_encoding = 'ascii'

    # Windows returns 'cp0' to indicate there is no code page. So we'll just
    # treat that as ASCII, and not support printing unicode characters to the
    # console.
    #
    # For python scripts run under vim, we get '', so also treat that as ASCII
    if user_encoding in (None, 'cp0', ''):
        user_encoding = 'ascii'
    else:
        # check encoding
        try:
            codecs.lookup(user_encoding)
        except LookupError:
            sys.stderr.write('bzr: warning:'
                             ' unknown encoding %s.'
                             ' Continuing with ascii encoding.\n'
                             % user_encoding
                            )
            user_encoding = 'ascii'

    if use_cache:
        _cached_user_encoding = user_encoding

    return user_encoding


def get_diff_header_encoding():
    return get_terminal_encoding()


def get_host_name():
    """Return the current unicode host name.

    This is meant to be used in place of socket.gethostname() because that
    behaves inconsistently on different platforms.
    """
    if sys.platform == "win32":
        import win32utils
        return win32utils.get_host_name()
    else:
        import socket
        return socket.gethostname().decode(get_user_encoding())


# We must not read/write any more than 64k at a time from/to a socket so we
# don't risk "no buffer space available" errors on some platforms.  Windows in
# particular is likely to throw WSAECONNABORTED or WSAENOBUFS if given too much
# data at once.
MAX_SOCKET_CHUNK = 64 * 1024

_end_of_stream_errors = [errno.ECONNRESET]
for _eno in ['WSAECONNRESET', 'WSAECONNABORTED']:
    _eno = getattr(errno, _eno, None)
    if _eno is not None:
        _end_of_stream_errors.append(_eno)
del _eno


def read_bytes_from_socket(sock, report_activity=None,
        max_read_size=MAX_SOCKET_CHUNK):
    """Read up to max_read_size of bytes from sock and notify of progress.

    Translates "Connection reset by peer" into file-like EOF (return an
    empty string rather than raise an error), and repeats the recv if
    interrupted by a signal.
    """
    while 1:
        try:
            bytes = sock.recv(max_read_size)
        except socket.error, e:
            eno = e.args[0]
            if eno in _end_of_stream_errors:
                # The connection was closed by the other side.  Callers expect
                # an empty string to signal end-of-stream.
                return ""
            elif eno == errno.EINTR:
                # Retry the interrupted recv.
                continue
            raise
        else:
            if report_activity is not None:
                report_activity(len(bytes), 'read')
            return bytes


def recv_all(socket, count):
    """Receive an exact number of bytes.

    Regular Socket.recv() may return less than the requested number of bytes,
    depending on what's in the OS buffer.  MSG_WAITALL is not available
    on all platforms, but this should work everywhere.  This will return
    less than the requested amount if the remote end closes.

    This isn't optimized and is intended mostly for use in testing.
    """
    b = ''
    while len(b) < count:
        new = read_bytes_from_socket(socket, None, count - len(b))
        if new == '':
            break # eof
        b += new
    return b


def send_all(sock, bytes, report_activity=None):
    """Send all bytes on a socket.

    Breaks large blocks in smaller chunks to avoid buffering limitations on
    some platforms, and catches EINTR which may be thrown if the send is
    interrupted by a signal.

    This is preferred to socket.sendall(), because it avoids portability bugs
    and provides activity reporting.

    :param report_activity: Call this as bytes are read, see
        Transport._report_activity
    """
    sent_total = 0
    byte_count = len(bytes)
    while sent_total < byte_count:
        try:
            sent = sock.send(buffer(bytes, sent_total, MAX_SOCKET_CHUNK))
        except socket.error, e:
            if e.args[0] != errno.EINTR:
                raise
        else:
            sent_total += sent
            report_activity(sent, 'write')


def connect_socket(address):
    # Slight variation of the socket.create_connection() function (provided by
    # python-2.6) that can fail if getaddrinfo returns an empty list. We also
    # provide it for previous python versions. Also, we don't use the timeout
    # parameter (provided by the python implementation) so we don't implement
    # it either).
    err = socket.error('getaddrinfo returns an empty list')
    host, port = address
    for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
        af, socktype, proto, canonname, sa = res
        sock = None
        try:
            sock = socket.socket(af, socktype, proto)
            sock.connect(sa)
            return sock

        except socket.error, err:
            # 'err' is now the most recent error
            if sock is not None:
                sock.close()
    raise err


def dereference_path(path):
    """Determine the real path to a file.

    All parent elements are dereferenced.  But the file itself is not
    dereferenced.
    :param path: The original path.  May be absolute or relative.
    :return: the real path *to* the file
    """
    parent, base = os.path.split(path)
    # The pathjoin for '.' is a workaround for Python bug #1213894.
    # (initial path components aren't dereferenced)
    return pathjoin(realpath(pathjoin('.', parent)), base)


def supports_mapi():
    """Return True if we can use MAPI to launch a mail client."""
    return sys.platform == "win32"


def resource_string(package, resource_name):
    """Load a resource from a package and return it as a string.

    Note: Only packages that start with bzrlib are currently supported.

    This is designed to be a lightweight implementation of resource
    loading in a way which is API compatible with the same API from
    pkg_resources. See
    http://peak.telecommunity.com/DevCenter/PkgResources#basic-resource-access.
    If and when pkg_resources becomes a standard library, this routine
    can delegate to it.
    """
    # Check package name is within bzrlib
    if package == "bzrlib":
        resource_relpath = resource_name
    elif package.startswith("bzrlib."):
        package = package[len("bzrlib."):].replace('.', os.sep)
        resource_relpath = pathjoin(package, resource_name)
    else:
        raise errors.BzrError('resource package %s not in bzrlib' % package)

    # Map the resource to a file and read its contents
    base = dirname(bzrlib.__file__)
    if getattr(sys, 'frozen', None):    # bzr.exe
        base = abspath(pathjoin(base, '..', '..'))
    f = file(pathjoin(base, resource_relpath), "rU")
    try:
        return f.read()
    finally:
        f.close()

def file_kind_from_stat_mode_thunk(mode):
    global file_kind_from_stat_mode
    if file_kind_from_stat_mode is file_kind_from_stat_mode_thunk:
        try:
            from bzrlib._readdir_pyx import UTF8DirReader
            file_kind_from_stat_mode = UTF8DirReader().kind_from_mode
        except ImportError, e:
            # This is one time where we won't warn that an extension failed to
            # load. The extension is never available on Windows anyway.
            from bzrlib._readdir_py import (
                _kind_from_mode as file_kind_from_stat_mode
                )
    return file_kind_from_stat_mode(mode)
file_kind_from_stat_mode = file_kind_from_stat_mode_thunk


def file_kind(f, _lstat=os.lstat):
    try:
        return file_kind_from_stat_mode(_lstat(f).st_mode)
    except OSError, e:
        if getattr(e, 'errno', None) in (errno.ENOENT, errno.ENOTDIR):
            raise errors.NoSuchFile(f)
        raise


def until_no_eintr(f, *a, **kw):
    """Run f(*a, **kw), retrying if an EINTR error occurs.

    WARNING: you must be certain that it is safe to retry the call repeatedly
    if EINTR does occur.  This is typically only true for low-level operations
    like os.read.  If in any doubt, don't use this.

    Keep in mind that this is not a complete solution to EINTR.  There is
    probably code in the Python standard library and other dependencies that
    may encounter EINTR if a signal arrives (and there is signal handler for
    that signal).  So this function can reduce the impact for IO that bzrlib
    directly controls, but it is not a complete solution.
    """
    # Borrowed from Twisted's twisted.python.util.untilConcludes function.
    while True:
        try:
            return f(*a, **kw)
        except (IOError, OSError), e:
            if e.errno == errno.EINTR:
                continue
            raise


@deprecated_function(deprecated_in((2, 2, 0)))
def re_compile_checked(re_string, flags=0, where=""):
    """Return a compiled re, or raise a sensible error.

    This should only be used when compiling user-supplied REs.

    :param re_string: Text form of regular expression.
    :param flags: eg re.IGNORECASE
    :param where: Message explaining to the user the context where
        it occurred, eg 'log search filter'.
    """
    # from https://bugs.launchpad.net/bzr/+bug/251352
    try:
        re_obj = re.compile(re_string, flags)
        re_obj.search("")
        return re_obj
    except errors.InvalidPattern, e:
        if where:
            where = ' in ' + where
        # despite the name 'error' is a type
        raise errors.BzrCommandError('Invalid regular expression%s: %s'
            % (where, e.msg))


if sys.platform == "win32":
    import msvcrt
    def getchar():
        return msvcrt.getch()
else:
    import tty
    import termios
    def getchar():
        fd = sys.stdin.fileno()
        settings = termios.tcgetattr(fd)
        try:
            tty.setraw(fd)
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, settings)
        return ch

if sys.platform == 'linux2':
    def _local_concurrency():
        try:
            return os.sysconf('SC_NPROCESSORS_ONLN')
        except (ValueError, OSError, AttributeError):
            return None
elif sys.platform == 'darwin':
    def _local_concurrency():
        return subprocess.Popen(['sysctl', '-n', 'hw.availcpu'],
                                stdout=subprocess.PIPE).communicate()[0]
elif "bsd" in sys.platform:
    def _local_concurrency():
        return subprocess.Popen(['sysctl', '-n', 'hw.ncpu'],
                                stdout=subprocess.PIPE).communicate()[0]
elif sys.platform == 'sunos5':
    def _local_concurrency():
        return subprocess.Popen(['psrinfo', '-p',],
                                stdout=subprocess.PIPE).communicate()[0]
elif sys.platform == "win32":
    def _local_concurrency():
        # This appears to return the number of cores.
        return os.environ.get('NUMBER_OF_PROCESSORS')
else:
    def _local_concurrency():
        # Who knows ?
        return None


_cached_local_concurrency = None

def local_concurrency(use_cache=True):
    """Return how many processes can be run concurrently.

    Rely on platform specific implementations and default to 1 (one) if
    anything goes wrong.
    """
    global _cached_local_concurrency

    if _cached_local_concurrency is not None and use_cache:
        return _cached_local_concurrency

    concurrency = os.environ.get('BZR_CONCURRENCY', None)
    if concurrency is None:
        try:
            import multiprocessing
        except ImportError:
            # multiprocessing is only available on Python >= 2.6
            try:
                concurrency = _local_concurrency()
            except (OSError, IOError):
                pass
        else:
            concurrency = multiprocessing.cpu_count()
    try:
        concurrency = int(concurrency)
    except (TypeError, ValueError):
        concurrency = 1
    if use_cache:
        _cached_concurrency = concurrency
    return concurrency


class UnicodeOrBytesToBytesWriter(codecs.StreamWriter):
    """A stream writer that doesn't decode str arguments."""

    def __init__(self, encode, stream, errors='strict'):
        codecs.StreamWriter.__init__(self, stream, errors)
        self.encode = encode

    def write(self, object):
        if type(object) is str:
            self.stream.write(object)
        else:
            data, _ = self.encode(object, self.errors)
            self.stream.write(data)

if sys.platform == 'win32':
    def open_file(filename, mode='r', bufsize=-1):
        """This function is used to override the ``open`` builtin.

        But it uses O_NOINHERIT flag so the file handle is not inherited by
        child processes.  Deleting or renaming a closed file opened with this
        function is not blocking child processes.
        """
        writing = 'w' in mode
        appending = 'a' in mode
        updating = '+' in mode
        binary = 'b' in mode

        flags = O_NOINHERIT
        # see http://msdn.microsoft.com/en-us/library/yeby3zcb%28VS.71%29.aspx
        # for flags for each modes.
        if binary:
            flags |= O_BINARY
        else:
            flags |= O_TEXT

        if writing:
            if updating:
                flags |= os.O_RDWR
            else:
                flags |= os.O_WRONLY
            flags |= os.O_CREAT | os.O_TRUNC
        elif appending:
            if updating:
                flags |= os.O_RDWR
            else:
                flags |= os.O_WRONLY
            flags |= os.O_CREAT | os.O_APPEND
        else: #reading
            if updating:
                flags |= os.O_RDWR
            else:
                flags |= os.O_RDONLY

        return os.fdopen(os.open(filename, flags), mode, bufsize)
else:
    open_file = open


def getuser_unicode():
    """Return the username as unicode.
    """
    try:
        user_encoding = get_user_encoding()
        username = getpass.getuser().decode(user_encoding)
    except UnicodeDecodeError:
        raise errors.BzrError("Can't decode username as %s." % \
                user_encoding)
    except ImportError, e:
        if sys.platform != 'win32':
            raise
        if str(e) != 'No module named pwd':
            raise
        # https://bugs.launchpad.net/bzr/+bug/660174
        # getpass.getuser() is unable to return username on Windows
        # if there is no USERNAME environment variable set.
        # That could be true if bzr is running as a service,
        # e.g. running `bzr serve` as a service on Windows.
        # We should not fail with traceback in this case.
        username = u'UNKNOWN'
    return username


def available_backup_name(base, exists):
    """Find a non-existing backup file name.

    This will *not* create anything, this only return a 'free' entry.  This
    should be used for checking names in a directory below a locked
    tree/branch/repo to avoid race conditions. This is LBYL (Look Before You
    Leap) and generally discouraged.

    :param base: The base name.

    :param exists: A callable returning True if the path parameter exists.
    """
    counter = 1
    name = "%s.~%d~" % (base, counter)
    while exists(name):
        counter += 1
        name = "%s.~%d~" % (base, counter)
    return name


def set_fd_cloexec(fd):
    """Set a Unix file descriptor's FD_CLOEXEC flag.  Do nothing if platform
    support for this is not available.
    """
    try:
        import fcntl
        old = fcntl.fcntl(fd, fcntl.F_GETFD)
        fcntl.fcntl(fd, fcntl.F_SETFD, old | fcntl.FD_CLOEXEC)
    except (ImportError, AttributeError):
        # Either the fcntl module or specific constants are not present
        pass


def find_executable_on_path(name):
    """Finds an executable on the PATH.
    
    On Windows, this will try to append each extension in the PATHEXT
    environment variable to the name, if it cannot be found with the name
    as given.
    
    :param name: The base name of the executable.
    :return: The path to the executable found or None.
    """
    path = os.environ.get('PATH')
    if path is None:
        return None
    path = path.split(os.pathsep)
    if sys.platform == 'win32':
        exts = os.environ.get('PATHEXT', '').split(os.pathsep)
        exts = [ext.lower() for ext in exts]
        base, ext = os.path.splitext(name)
        if ext != '':
            if ext.lower() not in exts:
                return None
            name = base
            exts = [ext]
    else:
        exts = ['']
    for ext in exts:
        for d in path:
            f = os.path.join(d, name) + ext
            if os.access(f, os.X_OK):
                return f
    return None


def _posix_is_local_pid_dead(pid):
    """True if pid doesn't correspond to live process on this machine"""
    try:
        # Special meaning of unix kill: just check if it's there.
        os.kill(pid, 0)
    except OSError, e:
        if e.errno == errno.ESRCH:
            # On this machine, and really not found: as sure as we can be
            # that it's dead.
            return True
        elif e.errno == errno.EPERM:
            # exists, though not ours
            return False
        else:
            mutter("os.kill(%d, 0) failed: %s" % (pid, e))
            # Don't really know.
            return False
    else:
        # Exists and our process: not dead.
        return False

if sys.platform == "win32":
    is_local_pid_dead = win32utils.is_local_pid_dead
else:
    is_local_pid_dead = _posix_is_local_pid_dead

_maybe_ignored = ['EAGAIN', 'EINTR', 'ENOTSUP', 'EOPNOTSUPP', 'EACCES']
_fdatasync_ignored = [getattr(errno, name) for name in _maybe_ignored
                      if getattr(errno, name, None) is not None]


def fdatasync(fileno):
    """Flush file contents to disk if possible.
    
    :param fileno: Integer OS file handle.
    :raises TransportNotPossible: If flushing to disk is not possible.
    """
    fn = getattr(os, 'fdatasync', getattr(os, 'fsync', None))
    if fn is not None:
        try:
            fn(fileno)
        except IOError, e:
            # See bug #1075108, on some platforms fdatasync exists, but can
            # raise ENOTSUP. However, we are calling fdatasync to be helpful
            # and reduce the chance of corruption-on-powerloss situations. It
            # is not a mandatory call, so it is ok to suppress failures.
            trace.mutter("ignoring error calling fdatasync: %s" % (e,))
            if getattr(e, 'errno', None) not in _fdatasync_ignored:
                raise


def ensure_empty_directory_exists(path, exception_class):
    """Make sure a local directory exists and is empty.
    
    If it does not exist, it is created.  If it exists and is not empty, an
    instance of exception_class is raised.
    """
    try:
        os.mkdir(path)
    except OSError, e:
        if e.errno != errno.EEXIST:
            raise
        if os.listdir(path) != []:
            raise exception_class(path)