/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

  • Committer: John Arbash Meinel
  • Date: 2006-04-25 18:08:29 UTC
  • mto: This revision was merged to the branch mainline in revision 1752.
  • Revision ID: john@arbash-meinel.com-20060425180829-43a8d6c25d903d17
Minor cleanups

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Bazaar-NG -- distributed version control
 
2
#
 
3
# Copyright (C) 2005 by Canonical Ltd
 
4
#
 
5
# This program is free software; you can redistribute it and/or modify
 
6
# it under the terms of the GNU General Public License as published by
 
7
# the Free Software Foundation; either version 2 of the License, or
 
8
# (at your option) any later version.
 
9
#
 
10
# This program is distributed in the hope that it will be useful,
 
11
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
13
# GNU General Public License for more details.
 
14
#
 
15
# You should have received a copy of the GNU General Public License
 
16
# along with this program; if not, write to the Free Software
 
17
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
18
 
 
19
from shutil import copyfile
 
20
from stat import (S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE,
 
21
                  S_ISCHR, S_ISBLK, S_ISFIFO, S_ISSOCK)
 
22
from cStringIO import StringIO
 
23
import errno
 
24
import os
 
25
import re
 
26
import sha
 
27
import string
 
28
import sys
 
29
import time
 
30
import types
 
31
import tempfile
 
32
import unicodedata
 
33
 
 
34
import bzrlib
 
35
from bzrlib.errors import (BzrError,
 
36
                           BzrBadParameterNotUnicode,
 
37
                           NoSuchFile,
 
38
                           PathNotChild,
 
39
                           IllegalPath,
 
40
                           )
 
41
from bzrlib.trace import mutter
 
42
 
 
43
 
 
44
def make_readonly(filename):
 
45
    """Make a filename read-only."""
 
46
    mod = os.stat(filename).st_mode
 
47
    mod = mod & 0777555
 
48
    os.chmod(filename, mod)
 
49
 
 
50
 
 
51
def make_writable(filename):
 
52
    mod = os.stat(filename).st_mode
 
53
    mod = mod | 0200
 
54
    os.chmod(filename, mod)
 
55
 
 
56
 
 
57
_QUOTE_RE = None
 
58
 
 
59
 
 
60
def quotefn(f):
 
61
    """Return a quoted filename filename
 
62
 
 
63
    This previously used backslash quoting, but that works poorly on
 
64
    Windows."""
 
65
    # TODO: I'm not really sure this is the best format either.x
 
66
    global _QUOTE_RE
 
67
    if _QUOTE_RE == None:
 
68
        _QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/\\_~-])')
 
69
        
 
70
    if _QUOTE_RE.search(f):
 
71
        return '"' + f + '"'
 
72
    else:
 
73
        return f
 
74
 
 
75
 
 
76
def file_kind(f):
 
77
    mode = os.lstat(f)[ST_MODE]
 
78
    if S_ISREG(mode):
 
79
        return 'file'
 
80
    elif S_ISDIR(mode):
 
81
        return 'directory'
 
82
    elif S_ISLNK(mode):
 
83
        return 'symlink'
 
84
    elif S_ISCHR(mode):
 
85
        return 'chardev'
 
86
    elif S_ISBLK(mode):
 
87
        return 'block'
 
88
    elif S_ISFIFO(mode):
 
89
        return 'fifo'
 
90
    elif S_ISSOCK(mode):
 
91
        return 'socket'
 
92
    else:
 
93
        return 'unknown'
 
94
 
 
95
 
 
96
def kind_marker(kind):
 
97
    if kind == 'file':
 
98
        return ''
 
99
    elif kind == 'directory':
 
100
        return '/'
 
101
    elif kind == 'symlink':
 
102
        return '@'
 
103
    else:
 
104
        raise BzrError('invalid file kind %r' % kind)
 
105
 
 
106
def lexists(f):
 
107
    if hasattr(os.path, 'lexists'):
 
108
        return os.path.lexists(f)
 
109
    try:
 
110
        if hasattr(os, 'lstat'):
 
111
            os.lstat(f)
 
112
        else:
 
113
            os.stat(f)
 
114
        return True
 
115
    except OSError,e:
 
116
        if e.errno == errno.ENOENT:
 
117
            return False;
 
118
        else:
 
119
            raise BzrError("lstat/stat of (%r): %r" % (f, e))
 
120
 
 
121
def fancy_rename(old, new, rename_func, unlink_func):
 
122
    """A fancy rename, when you don't have atomic rename.
 
123
    
 
124
    :param old: The old path, to rename from
 
125
    :param new: The new path, to rename to
 
126
    :param rename_func: The potentially non-atomic rename function
 
127
    :param unlink_func: A way to delete the target file if the full rename succeeds
 
128
    """
 
129
 
 
130
    # sftp rename doesn't allow overwriting, so play tricks:
 
131
    import random
 
132
    base = os.path.basename(new)
 
133
    dirname = os.path.dirname(new)
 
134
    tmp_name = u'tmp.%s.%.9f.%d.%s' % (base, time.time(), os.getpid(), rand_chars(10))
 
135
    tmp_name = pathjoin(dirname, tmp_name)
 
136
 
 
137
    # Rename the file out of the way, but keep track if it didn't exist
 
138
    # We don't want to grab just any exception
 
139
    # something like EACCES should prevent us from continuing
 
140
    # The downside is that the rename_func has to throw an exception
 
141
    # with an errno = ENOENT, or NoSuchFile
 
142
    file_existed = False
 
143
    try:
 
144
        rename_func(new, tmp_name)
 
145
    except (NoSuchFile,), e:
 
146
        pass
 
147
    except IOError, e:
 
148
        # RBC 20060103 abstraction leakage: the paramiko SFTP clients rename
 
149
        # function raises an IOError with errno == None when a rename fails.
 
150
        # This then gets caught here.
 
151
        if e.errno not in (None, errno.ENOENT, errno.ENOTDIR):
 
152
            raise
 
153
    except Exception, e:
 
154
        if (not hasattr(e, 'errno') 
 
155
            or e.errno not in (errno.ENOENT, errno.ENOTDIR)):
 
156
            raise
 
157
    else:
 
158
        file_existed = True
 
159
 
 
160
    success = False
 
161
    try:
 
162
        # This may throw an exception, in which case success will
 
163
        # not be set.
 
164
        rename_func(old, new)
 
165
        success = True
 
166
    finally:
 
167
        if file_existed:
 
168
            # If the file used to exist, rename it back into place
 
169
            # otherwise just delete it from the tmp location
 
170
            if success:
 
171
                unlink_func(tmp_name)
 
172
            else:
 
173
                rename_func(tmp_name, new)
 
174
 
 
175
# Default is to just use the python builtins
 
176
abspath = os.path.abspath
 
177
realpath = os.path.realpath
 
178
pathjoin = os.path.join
 
179
normpath = os.path.normpath
 
180
getcwd = os.getcwdu
 
181
mkdtemp = tempfile.mkdtemp
 
182
rename = os.rename
 
183
dirname = os.path.dirname
 
184
basename = os.path.basename
 
185
 
 
186
MIN_ABS_PATHLENGTH = 1
 
187
 
 
188
if os.name == "posix":
 
189
    # In Python 2.4.2 and older, os.path.abspath and os.path.realpath
 
190
    # choke on a Unicode string containing a relative path if
 
191
    # os.getcwd() returns a non-sys.getdefaultencoding()-encoded
 
192
    # string.
 
193
    _fs_enc = sys.getfilesystemencoding()
 
194
    def abspath(path):
 
195
        return os.path.abspath(path.encode(_fs_enc)).decode(_fs_enc)
 
196
 
 
197
    def realpath(path):
 
198
        return os.path.realpath(path.encode(_fs_enc)).decode(_fs_enc)
 
199
 
 
200
if sys.platform == 'win32':
 
201
    # We need to use the Unicode-aware os.path.abspath and
 
202
    # os.path.realpath on Windows systems.
 
203
    def abspath(path):
 
204
        return os.path.abspath(path).replace('\\', '/')
 
205
 
 
206
    def realpath(path):
 
207
        return os.path.realpath(path).replace('\\', '/')
 
208
 
 
209
    def pathjoin(*args):
 
210
        return os.path.join(*args).replace('\\', '/')
 
211
 
 
212
    def normpath(path):
 
213
        return os.path.normpath(path).replace('\\', '/')
 
214
 
 
215
    def getcwd():
 
216
        return os.getcwdu().replace('\\', '/')
 
217
 
 
218
    def mkdtemp(*args, **kwargs):
 
219
        return tempfile.mkdtemp(*args, **kwargs).replace('\\', '/')
 
220
 
 
221
    def rename(old, new):
 
222
        fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
 
223
 
 
224
    MIN_ABS_PATHLENGTH = 3
 
225
 
 
226
def normalizepath(f):
 
227
    if hasattr(os.path, 'realpath'):
 
228
        F = realpath
 
229
    else:
 
230
        F = abspath
 
231
    [p,e] = os.path.split(f)
 
232
    if e == "" or e == "." or e == "..":
 
233
        return F(f)
 
234
    else:
 
235
        return pathjoin(F(p), e)
 
236
 
 
237
 
 
238
def backup_file(fn):
 
239
    """Copy a file to a backup.
 
240
 
 
241
    Backups are named in GNU-style, with a ~ suffix.
 
242
 
 
243
    If the file is already a backup, it's not copied.
 
244
    """
 
245
    if fn[-1] == '~':
 
246
        return
 
247
    bfn = fn + '~'
 
248
 
 
249
    if has_symlinks() and os.path.islink(fn):
 
250
        target = os.readlink(fn)
 
251
        os.symlink(target, bfn)
 
252
        return
 
253
    inf = file(fn, 'rb')
 
254
    try:
 
255
        content = inf.read()
 
256
    finally:
 
257
        inf.close()
 
258
    
 
259
    outf = file(bfn, 'wb')
 
260
    try:
 
261
        outf.write(content)
 
262
    finally:
 
263
        outf.close()
 
264
 
 
265
 
 
266
def isdir(f):
 
267
    """True if f is an accessible directory."""
 
268
    try:
 
269
        return S_ISDIR(os.lstat(f)[ST_MODE])
 
270
    except OSError:
 
271
        return False
 
272
 
 
273
 
 
274
def isfile(f):
 
275
    """True if f is a regular file."""
 
276
    try:
 
277
        return S_ISREG(os.lstat(f)[ST_MODE])
 
278
    except OSError:
 
279
        return False
 
280
 
 
281
def islink(f):
 
282
    """True if f is a symlink."""
 
283
    try:
 
284
        return S_ISLNK(os.lstat(f)[ST_MODE])
 
285
    except OSError:
 
286
        return False
 
287
 
 
288
def is_inside(dir, fname):
 
289
    """True if fname is inside dir.
 
290
    
 
291
    The parameters should typically be passed to osutils.normpath first, so
 
292
    that . and .. and repeated slashes are eliminated, and the separators
 
293
    are canonical for the platform.
 
294
    
 
295
    The empty string as a dir name is taken as top-of-tree and matches 
 
296
    everything.
 
297
    
 
298
    >>> is_inside('src', pathjoin('src', 'foo.c'))
 
299
    True
 
300
    >>> is_inside('src', 'srccontrol')
 
301
    False
 
302
    >>> is_inside('src', pathjoin('src', 'a', 'a', 'a', 'foo.c'))
 
303
    True
 
304
    >>> is_inside('foo.c', 'foo.c')
 
305
    True
 
306
    >>> is_inside('foo.c', '')
 
307
    False
 
308
    >>> is_inside('', 'foo.c')
 
309
    True
 
310
    """
 
311
    # XXX: Most callers of this can actually do something smarter by 
 
312
    # looking at the inventory
 
313
    if dir == fname:
 
314
        return True
 
315
    
 
316
    if dir == '':
 
317
        return True
 
318
 
 
319
    if dir[-1] != '/':
 
320
        dir += '/'
 
321
 
 
322
    return fname.startswith(dir)
 
323
 
 
324
 
 
325
def is_inside_any(dir_list, fname):
 
326
    """True if fname is inside any of given dirs."""
 
327
    for dirname in dir_list:
 
328
        if is_inside(dirname, fname):
 
329
            return True
 
330
    else:
 
331
        return False
 
332
 
 
333
 
 
334
def pumpfile(fromfile, tofile):
 
335
    """Copy contents of one file to another."""
 
336
    BUFSIZE = 32768
 
337
    while True:
 
338
        b = fromfile.read(BUFSIZE)
 
339
        if not b:
 
340
            break
 
341
        tofile.write(b)
 
342
 
 
343
 
 
344
def file_iterator(input_file, readsize=32768):
 
345
    while True:
 
346
        b = input_file.read(readsize)
 
347
        if len(b) == 0:
 
348
            break
 
349
        yield b
 
350
 
 
351
 
 
352
def sha_file(f):
 
353
    if hasattr(f, 'tell'):
 
354
        assert f.tell() == 0
 
355
    s = sha.new()
 
356
    BUFSIZE = 128<<10
 
357
    while True:
 
358
        b = f.read(BUFSIZE)
 
359
        if not b:
 
360
            break
 
361
        s.update(b)
 
362
    return s.hexdigest()
 
363
 
 
364
 
 
365
 
 
366
def sha_strings(strings):
 
367
    """Return the sha-1 of concatenation of strings"""
 
368
    s = sha.new()
 
369
    map(s.update, strings)
 
370
    return s.hexdigest()
 
371
 
 
372
 
 
373
def sha_string(f):
 
374
    s = sha.new()
 
375
    s.update(f)
 
376
    return s.hexdigest()
 
377
 
 
378
 
 
379
def fingerprint_file(f):
 
380
    s = sha.new()
 
381
    b = f.read()
 
382
    s.update(b)
 
383
    size = len(b)
 
384
    return {'size': size,
 
385
            'sha1': s.hexdigest()}
 
386
 
 
387
 
 
388
def compare_files(a, b):
 
389
    """Returns true if equal in contents"""
 
390
    BUFSIZE = 4096
 
391
    while True:
 
392
        ai = a.read(BUFSIZE)
 
393
        bi = b.read(BUFSIZE)
 
394
        if ai != bi:
 
395
            return False
 
396
        if ai == '':
 
397
            return True
 
398
 
 
399
 
 
400
def local_time_offset(t=None):
 
401
    """Return offset of local zone from GMT, either at present or at time t."""
 
402
    # python2.3 localtime() can't take None
 
403
    if t == None:
 
404
        t = time.time()
 
405
        
 
406
    if time.localtime(t).tm_isdst and time.daylight:
 
407
        return -time.altzone
 
408
    else:
 
409
        return -time.timezone
 
410
 
 
411
    
 
412
def format_date(t, offset=0, timezone='original', date_fmt=None, 
 
413
                show_offset=True):
 
414
    ## TODO: Perhaps a global option to use either universal or local time?
 
415
    ## Or perhaps just let people set $TZ?
 
416
    assert isinstance(t, float)
 
417
    
 
418
    if timezone == 'utc':
 
419
        tt = time.gmtime(t)
 
420
        offset = 0
 
421
    elif timezone == 'original':
 
422
        if offset == None:
 
423
            offset = 0
 
424
        tt = time.gmtime(t + offset)
 
425
    elif timezone == 'local':
 
426
        tt = time.localtime(t)
 
427
        offset = local_time_offset(t)
 
428
    else:
 
429
        raise BzrError("unsupported timezone format %r" % timezone,
 
430
                       ['options are "utc", "original", "local"'])
 
431
    if date_fmt is None:
 
432
        date_fmt = "%a %Y-%m-%d %H:%M:%S"
 
433
    if show_offset:
 
434
        offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
 
435
    else:
 
436
        offset_str = ''
 
437
    return (time.strftime(date_fmt, tt) +  offset_str)
 
438
 
 
439
 
 
440
def compact_date(when):
 
441
    return time.strftime('%Y%m%d%H%M%S', time.gmtime(when))
 
442
    
 
443
 
 
444
 
 
445
def filesize(f):
 
446
    """Return size of given open file."""
 
447
    return os.fstat(f.fileno())[ST_SIZE]
 
448
 
 
449
 
 
450
# Define rand_bytes based on platform.
 
451
try:
 
452
    # Python 2.4 and later have os.urandom,
 
453
    # but it doesn't work on some arches
 
454
    os.urandom(1)
 
455
    rand_bytes = os.urandom
 
456
except (NotImplementedError, AttributeError):
 
457
    # If python doesn't have os.urandom, or it doesn't work,
 
458
    # then try to first pull random data from /dev/urandom
 
459
    if os.path.exists("/dev/urandom"):
 
460
        rand_bytes = file('/dev/urandom', 'rb').read
 
461
    # Otherwise, use this hack as a last resort
 
462
    else:
 
463
        # not well seeded, but better than nothing
 
464
        def rand_bytes(n):
 
465
            import random
 
466
            s = ''
 
467
            while n:
 
468
                s += chr(random.randint(0, 255))
 
469
                n -= 1
 
470
            return s
 
471
 
 
472
 
 
473
ALNUM = '0123456789abcdefghijklmnopqrstuvwxyz'
 
474
def rand_chars(num):
 
475
    """Return a random string of num alphanumeric characters
 
476
    
 
477
    The result only contains lowercase chars because it may be used on 
 
478
    case-insensitive filesystems.
 
479
    """
 
480
    s = ''
 
481
    for raw_byte in rand_bytes(num):
 
482
        s += ALNUM[ord(raw_byte) % 36]
 
483
    return s
 
484
 
 
485
 
 
486
## TODO: We could later have path objects that remember their list
 
487
## decomposition (might be too tricksy though.)
 
488
 
 
489
def splitpath(p):
 
490
    """Turn string into list of parts.
 
491
 
 
492
    >>> splitpath('a')
 
493
    ['a']
 
494
    >>> splitpath('a/b')
 
495
    ['a', 'b']
 
496
    >>> splitpath('a/./b')
 
497
    ['a', 'b']
 
498
    >>> splitpath('a/.b')
 
499
    ['a', '.b']
 
500
    >>> splitpath('a/../b')
 
501
    Traceback (most recent call last):
 
502
    ...
 
503
    BzrError: sorry, '..' not allowed in path
 
504
    """
 
505
    assert isinstance(p, types.StringTypes)
 
506
 
 
507
    # split on either delimiter because people might use either on
 
508
    # Windows
 
509
    ps = re.split(r'[\\/]', p)
 
510
 
 
511
    rps = []
 
512
    for f in ps:
 
513
        if f == '..':
 
514
            raise BzrError("sorry, %r not allowed in path" % f)
 
515
        elif (f == '.') or (f == ''):
 
516
            pass
 
517
        else:
 
518
            rps.append(f)
 
519
    return rps
 
520
 
 
521
def joinpath(p):
 
522
    assert isinstance(p, list)
 
523
    for f in p:
 
524
        if (f == '..') or (f == None) or (f == ''):
 
525
            raise BzrError("sorry, %r not allowed in path" % f)
 
526
    return pathjoin(*p)
 
527
 
 
528
 
 
529
def appendpath(p1, p2):
 
530
    if p1 == '':
 
531
        return p2
 
532
    else:
 
533
        return pathjoin(p1, p2)
 
534
    
 
535
 
 
536
def split_lines(s):
 
537
    """Split s into lines, but without removing the newline characters."""
 
538
    lines = s.split('\n')
 
539
    result = [line + '\n' for line in lines[:-1]]
 
540
    if lines[-1]:
 
541
        result.append(lines[-1])
 
542
    return result
 
543
 
 
544
 
 
545
def hardlinks_good():
 
546
    return sys.platform not in ('win32', 'cygwin', 'darwin')
 
547
 
 
548
 
 
549
def link_or_copy(src, dest):
 
550
    """Hardlink a file, or copy it if it can't be hardlinked."""
 
551
    if not hardlinks_good():
 
552
        copyfile(src, dest)
 
553
        return
 
554
    try:
 
555
        os.link(src, dest)
 
556
    except (OSError, IOError), e:
 
557
        if e.errno != errno.EXDEV:
 
558
            raise
 
559
        copyfile(src, dest)
 
560
 
 
561
def delete_any(full_path):
 
562
    """Delete a file or directory."""
 
563
    try:
 
564
        os.unlink(full_path)
 
565
    except OSError, e:
 
566
    # We may be renaming a dangling inventory id
 
567
        if e.errno not in (errno.EISDIR, errno.EACCES, errno.EPERM):
 
568
            raise
 
569
        os.rmdir(full_path)
 
570
 
 
571
 
 
572
def has_symlinks():
 
573
    if hasattr(os, 'symlink'):
 
574
        return True
 
575
    else:
 
576
        return False
 
577
        
 
578
 
 
579
def contains_whitespace(s):
 
580
    """True if there are any whitespace characters in s."""
 
581
    for ch in string.whitespace:
 
582
        if ch in s:
 
583
            return True
 
584
    else:
 
585
        return False
 
586
 
 
587
 
 
588
def contains_linebreaks(s):
 
589
    """True if there is any vertical whitespace in s."""
 
590
    for ch in '\f\n\r':
 
591
        if ch in s:
 
592
            return True
 
593
    else:
 
594
        return False
 
595
 
 
596
 
 
597
def relpath(base, path):
 
598
    """Return path relative to base, or raise exception.
 
599
 
 
600
    The path may be either an absolute path or a path relative to the
 
601
    current working directory.
 
602
 
 
603
    os.path.commonprefix (python2.4) has a bad bug that it works just
 
604
    on string prefixes, assuming that '/u' is a prefix of '/u2'.  This
 
605
    avoids that problem.
 
606
    """
 
607
 
 
608
    assert len(base) >= MIN_ABS_PATHLENGTH, ('Length of base must be equal or'
 
609
        ' exceed the platform minimum length (which is %d)' % 
 
610
        MIN_ABS_PATHLENGTH)
 
611
    rp = abspath(path)
 
612
 
 
613
    s = []
 
614
    head = rp
 
615
    while len(head) >= len(base):
 
616
        if head == base:
 
617
            break
 
618
        head, tail = os.path.split(head)
 
619
        if tail:
 
620
            s.insert(0, tail)
 
621
    else:
 
622
        # XXX This should raise a NotChildPath exception, as its not tied
 
623
        # to branch anymore.
 
624
        raise PathNotChild(rp, base)
 
625
 
 
626
    if s:
 
627
        return pathjoin(*s)
 
628
    else:
 
629
        return ''
 
630
 
 
631
 
 
632
def safe_unicode(unicode_or_utf8_string):
 
633
    """Coerce unicode_or_utf8_string into unicode.
 
634
 
 
635
    If it is unicode, it is returned.
 
636
    Otherwise it is decoded from utf-8. If a decoding error
 
637
    occurs, it is wrapped as a If the decoding fails, the exception is wrapped 
 
638
    as a BzrBadParameter exception.
 
639
    """
 
640
    if isinstance(unicode_or_utf8_string, unicode):
 
641
        return unicode_or_utf8_string
 
642
    try:
 
643
        return unicode_or_utf8_string.decode('utf8')
 
644
    except UnicodeDecodeError:
 
645
        raise BzrBadParameterNotUnicode(unicode_or_utf8_string)
 
646
 
 
647
 
 
648
_platform_normalizes_filenames = False
 
649
if sys.platform == 'darwin':
 
650
    _platform_normalizes_filenames = True
 
651
 
 
652
 
 
653
def normalizes_filenames():
 
654
    """Return True if this platform normalizes unicode filenames.
 
655
 
 
656
    Mac OSX does, Windows/Linux do not.
 
657
    """
 
658
    return _platform_normalizes_filenames
 
659
 
 
660
 
 
661
if _platform_normalizes_filenames:
 
662
    def unicode_filename(path):
 
663
        """Make sure 'path' is a properly normalized filename.
 
664
 
 
665
        On platforms where the system normalizes filenames (Mac OSX),
 
666
        you can access a file by any path which will normalize
 
667
        correctly.
 
668
        Internally, bzr only supports NFC/NFKC normalization, since
 
669
        that is the standard for XML documents.
 
670
        So we return an normalized path, and indicate this has been
 
671
        properly normalized.
 
672
 
 
673
        :return: (path, is_normalized) Return a path which can
 
674
                access the file, and whether or not this path is
 
675
                normalized.
 
676
        """
 
677
        return unicodedata.normalize('NFKC', path), True
 
678
else:
 
679
    def unicode_filename(path):
 
680
        """Make sure 'path' is a properly normalized filename.
 
681
 
 
682
        On platforms where the system does not normalize filenames 
 
683
        (Windows, Linux), you have to access a file by its exact path.
 
684
        Internally, bzr only supports NFC/NFKC normalization, since
 
685
        that is the standard for XML documents.
 
686
        So we return the original path, and indicate if this is
 
687
        properly normalized.
 
688
 
 
689
        :return: (path, is_normalized) Return a path which can
 
690
                access the file, and whether or not this path is
 
691
                normalized.
 
692
        """
 
693
        return path, unicodedata.normalize('NFKC', path) == path
 
694
 
 
695
 
 
696
def terminal_width():
 
697
    """Return estimated terminal width."""
 
698
 
 
699
    # TODO: Do something smart on Windows?
 
700
 
 
701
    # TODO: Is there anything that gets a better update when the window
 
702
    # is resized while the program is running? We could use the Python termcap
 
703
    # library.
 
704
    try:
 
705
        return int(os.environ['COLUMNS'])
 
706
    except (IndexError, KeyError, ValueError):
 
707
        return 80
 
708
 
 
709
def supports_executable():
 
710
    return sys.platform != "win32"
 
711
 
 
712
 
 
713
def strip_trailing_slash(path):
 
714
    """Strip trailing slash, except for root paths.
 
715
    The definition of 'root path' is platform-dependent.
 
716
    """
 
717
    if len(path) != MIN_ABS_PATHLENGTH and path[-1] == '/':
 
718
        return path[:-1]
 
719
    else:
 
720
        return path
 
721
 
 
722
 
 
723
_validWin32PathRE = re.compile(r'^([A-Za-z]:[/\\])?[^:<>*"?\|]*$')
 
724
 
 
725
 
 
726
def check_legal_path(path):
 
727
    """Check whether the supplied path is legal.  
 
728
    This is only required on Windows, so we don't test on other platforms
 
729
    right now.
 
730
    """
 
731
    if sys.platform != "win32":
 
732
        return
 
733
    if _validWin32PathRE.match(path) is None:
 
734
        raise IllegalPath(path)