~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

  • Committer: Aaron Bentley
  • Date: 2008-10-16 21:27:10 UTC
  • mfrom: (0.15.26 unshelve)
  • mto: (0.16.74 shelf-ui)
  • mto: This revision was merged to the branch mainline in revision 3820.
  • Revision ID: aaron@aaronbentley.com-20081016212710-h9av3nhk76dvmsv5
Merge with unshelve

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
import os
 
18
import re
 
19
import stat
 
20
from stat import (S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE,
 
21
                  S_ISCHR, S_ISBLK, S_ISFIFO, S_ISSOCK)
 
22
import sys
 
23
import time
 
24
 
 
25
from bzrlib.lazy_import import lazy_import
 
26
lazy_import(globals(), """
 
27
import codecs
 
28
from datetime import datetime
 
29
import errno
 
30
from ntpath import (abspath as _nt_abspath,
 
31
                    join as _nt_join,
 
32
                    normpath as _nt_normpath,
 
33
                    realpath as _nt_realpath,
 
34
                    splitdrive as _nt_splitdrive,
 
35
                    )
 
36
import posixpath
 
37
import shutil
 
38
from shutil import (
 
39
    rmtree,
 
40
    )
 
41
import tempfile
 
42
from tempfile import (
 
43
    mkdtemp,
 
44
    )
 
45
import unicodedata
 
46
 
 
47
from bzrlib import (
 
48
    cache_utf8,
 
49
    errors,
 
50
    win32utils,
 
51
    )
 
52
""")
 
53
 
 
54
# sha and md5 modules are deprecated in python2.6 but hashlib is available as
 
55
# of 2.5
 
56
if sys.version_info < (2, 5):
 
57
    import md5 as _mod_md5
 
58
    md5 = _mod_md5.new
 
59
    import sha as _mod_sha
 
60
    sha = _mod_sha.new
 
61
else:
 
62
    from hashlib import (
 
63
        md5,
 
64
        sha1 as sha,
 
65
        )
 
66
 
 
67
 
 
68
import bzrlib
 
69
from bzrlib import symbol_versioning
 
70
 
 
71
 
 
72
# On win32, O_BINARY is used to indicate the file should
 
73
# be opened in binary mode, rather than text mode.
 
74
# On other platforms, O_BINARY doesn't exist, because
 
75
# they always open in binary mode, so it is okay to
 
76
# OR with 0 on those platforms
 
77
O_BINARY = getattr(os, 'O_BINARY', 0)
 
78
 
 
79
 
 
80
def make_readonly(filename):
 
81
    """Make a filename read-only."""
 
82
    mod = os.lstat(filename).st_mode
 
83
    if not stat.S_ISLNK(mod):
 
84
        mod = mod & 0777555
 
85
        os.chmod(filename, mod)
 
86
 
 
87
 
 
88
def make_writable(filename):
 
89
    mod = os.lstat(filename).st_mode
 
90
    if not stat.S_ISLNK(mod):
 
91
        mod = mod | 0200
 
92
        os.chmod(filename, mod)
 
93
 
 
94
 
 
95
def minimum_path_selection(paths):
 
96
    """Return the smallset subset of paths which are outside paths.
 
97
 
 
98
    :param paths: A container (and hence not None) of paths.
 
99
    :return: A set of paths sufficient to include everything in paths via
 
100
        is_inside_any, drawn from the paths parameter.
 
101
    """
 
102
    search_paths = set()
 
103
    paths = set(paths)
 
104
    for path in paths:
 
105
        other_paths = paths.difference([path])
 
106
        if not is_inside_any(other_paths, path):
 
107
            # this is a top level path, we must check it.
 
108
            search_paths.add(path)
 
109
    return search_paths
 
110
 
 
111
 
 
112
_QUOTE_RE = None
 
113
 
 
114
 
 
115
def quotefn(f):
 
116
    """Return a quoted filename filename
 
117
 
 
118
    This previously used backslash quoting, but that works poorly on
 
119
    Windows."""
 
120
    # TODO: I'm not really sure this is the best format either.x
 
121
    global _QUOTE_RE
 
122
    if _QUOTE_RE is None:
 
123
        _QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/\\_~-])')
 
124
        
 
125
    if _QUOTE_RE.search(f):
 
126
        return '"' + f + '"'
 
127
    else:
 
128
        return f
 
129
 
 
130
 
 
131
_directory_kind = 'directory'
 
132
 
 
133
def get_umask():
 
134
    """Return the current umask"""
 
135
    # Assume that people aren't messing with the umask while running
 
136
    # XXX: This is not thread safe, but there is no way to get the
 
137
    #      umask without setting it
 
138
    umask = os.umask(0)
 
139
    os.umask(umask)
 
140
    return umask
 
141
 
 
142
 
 
143
_kind_marker_map = {
 
144
    "file": "",
 
145
    _directory_kind: "/",
 
146
    "symlink": "@",
 
147
    'tree-reference': '+',
 
148
}
 
149
 
 
150
 
 
151
def kind_marker(kind):
 
152
    try:
 
153
        return _kind_marker_map[kind]
 
154
    except KeyError:
 
155
        raise errors.BzrError('invalid file kind %r' % kind)
 
156
 
 
157
 
 
158
lexists = getattr(os.path, 'lexists', None)
 
159
if lexists is None:
 
160
    def lexists(f):
 
161
        try:
 
162
            stat = getattr(os, 'lstat', os.stat)
 
163
            stat(f)
 
164
            return True
 
165
        except OSError, e:
 
166
            if e.errno == errno.ENOENT:
 
167
                return False;
 
168
            else:
 
169
                raise errors.BzrError("lstat/stat of (%r): %r" % (f, e))
 
170
 
 
171
 
 
172
def fancy_rename(old, new, rename_func, unlink_func):
 
173
    """A fancy rename, when you don't have atomic rename.
 
174
    
 
175
    :param old: The old path, to rename from
 
176
    :param new: The new path, to rename to
 
177
    :param rename_func: The potentially non-atomic rename function
 
178
    :param unlink_func: A way to delete the target file if the full rename succeeds
 
179
    """
 
180
 
 
181
    # sftp rename doesn't allow overwriting, so play tricks:
 
182
    base = os.path.basename(new)
 
183
    dirname = os.path.dirname(new)
 
184
    tmp_name = u'tmp.%s.%.9f.%d.%s' % (base, time.time(), os.getpid(), rand_chars(10))
 
185
    tmp_name = pathjoin(dirname, tmp_name)
 
186
 
 
187
    # Rename the file out of the way, but keep track if it didn't exist
 
188
    # We don't want to grab just any exception
 
189
    # something like EACCES should prevent us from continuing
 
190
    # The downside is that the rename_func has to throw an exception
 
191
    # with an errno = ENOENT, or NoSuchFile
 
192
    file_existed = False
 
193
    try:
 
194
        rename_func(new, tmp_name)
 
195
    except (errors.NoSuchFile,), e:
 
196
        pass
 
197
    except IOError, e:
 
198
        # RBC 20060103 abstraction leakage: the paramiko SFTP clients rename
 
199
        # function raises an IOError with errno is None when a rename fails.
 
200
        # This then gets caught here.
 
201
        if e.errno not in (None, errno.ENOENT, errno.ENOTDIR):
 
202
            raise
 
203
    except Exception, e:
 
204
        if (getattr(e, 'errno', None) is None
 
205
            or e.errno not in (errno.ENOENT, errno.ENOTDIR)):
 
206
            raise
 
207
    else:
 
208
        file_existed = True
 
209
 
 
210
    success = False
 
211
    try:
 
212
        try:
 
213
            # This may throw an exception, in which case success will
 
214
            # not be set.
 
215
            rename_func(old, new)
 
216
            success = True
 
217
        except (IOError, OSError), e:
 
218
            # source and target may be aliases of each other (e.g. on a
 
219
            # case-insensitive filesystem), so we may have accidentally renamed
 
220
            # source by when we tried to rename target
 
221
            if not (file_existed and e.errno in (None, errno.ENOENT)):
 
222
                raise
 
223
    finally:
 
224
        if file_existed:
 
225
            # If the file used to exist, rename it back into place
 
226
            # otherwise just delete it from the tmp location
 
227
            if success:
 
228
                unlink_func(tmp_name)
 
229
            else:
 
230
                rename_func(tmp_name, new)
 
231
 
 
232
 
 
233
# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
 
234
# choke on a Unicode string containing a relative path if
 
235
# os.getcwd() returns a non-sys.getdefaultencoding()-encoded
 
236
# string.
 
237
_fs_enc = sys.getfilesystemencoding() or 'utf-8'
 
238
def _posix_abspath(path):
 
239
    # jam 20060426 rather than encoding to fsencoding
 
240
    # copy posixpath.abspath, but use os.getcwdu instead
 
241
    if not posixpath.isabs(path):
 
242
        path = posixpath.join(getcwd(), path)
 
243
    return posixpath.normpath(path)
 
244
 
 
245
 
 
246
def _posix_realpath(path):
 
247
    return posixpath.realpath(path.encode(_fs_enc)).decode(_fs_enc)
 
248
 
 
249
 
 
250
def _win32_fixdrive(path):
 
251
    """Force drive letters to be consistent.
 
252
 
 
253
    win32 is inconsistent whether it returns lower or upper case
 
254
    and even if it was consistent the user might type the other
 
255
    so we force it to uppercase
 
256
    running python.exe under cmd.exe return capital C:\\
 
257
    running win32 python inside a cygwin shell returns lowercase c:\\
 
258
    """
 
259
    drive, path = _nt_splitdrive(path)
 
260
    return drive.upper() + path
 
261
 
 
262
 
 
263
def _win32_abspath(path):
 
264
    # Real _nt_abspath doesn't have a problem with a unicode cwd
 
265
    return _win32_fixdrive(_nt_abspath(unicode(path)).replace('\\', '/'))
 
266
 
 
267
 
 
268
def _win98_abspath(path):
 
269
    """Return the absolute version of a path.
 
270
    Windows 98 safe implementation (python reimplementation
 
271
    of Win32 API function GetFullPathNameW)
 
272
    """
 
273
    # Corner cases:
 
274
    #   C:\path     => C:/path
 
275
    #   C:/path     => C:/path
 
276
    #   \\HOST\path => //HOST/path
 
277
    #   //HOST/path => //HOST/path
 
278
    #   path        => C:/cwd/path
 
279
    #   /path       => C:/path
 
280
    path = unicode(path)
 
281
    # check for absolute path
 
282
    drive = _nt_splitdrive(path)[0]
 
283
    if drive == '' and path[:2] not in('//','\\\\'):
 
284
        cwd = os.getcwdu()
 
285
        # we cannot simply os.path.join cwd and path
 
286
        # because os.path.join('C:','/path') produce '/path'
 
287
        # and this is incorrect
 
288
        if path[:1] in ('/','\\'):
 
289
            cwd = _nt_splitdrive(cwd)[0]
 
290
            path = path[1:]
 
291
        path = cwd + '\\' + path
 
292
    return _win32_fixdrive(_nt_normpath(path).replace('\\', '/'))
 
293
 
 
294
 
 
295
def _win32_realpath(path):
 
296
    # Real _nt_realpath doesn't have a problem with a unicode cwd
 
297
    return _win32_fixdrive(_nt_realpath(unicode(path)).replace('\\', '/'))
 
298
 
 
299
 
 
300
def _win32_pathjoin(*args):
 
301
    return _nt_join(*args).replace('\\', '/')
 
302
 
 
303
 
 
304
def _win32_normpath(path):
 
305
    return _win32_fixdrive(_nt_normpath(unicode(path)).replace('\\', '/'))
 
306
 
 
307
 
 
308
def _win32_getcwd():
 
309
    return _win32_fixdrive(os.getcwdu().replace('\\', '/'))
 
310
 
 
311
 
 
312
def _win32_mkdtemp(*args, **kwargs):
 
313
    return _win32_fixdrive(tempfile.mkdtemp(*args, **kwargs).replace('\\', '/'))
 
314
 
 
315
 
 
316
def _win32_rename(old, new):
 
317
    """We expect to be able to atomically replace 'new' with old.
 
318
 
 
319
    On win32, if new exists, it must be moved out of the way first,
 
320
    and then deleted. 
 
321
    """
 
322
    try:
 
323
        fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
 
324
    except OSError, e:
 
325
        if e.errno in (errno.EPERM, errno.EACCES, errno.EBUSY, errno.EINVAL):
 
326
            # If we try to rename a non-existant file onto cwd, we get 
 
327
            # EPERM or EACCES instead of ENOENT, this will raise ENOENT 
 
328
            # if the old path doesn't exist, sometimes we get EACCES
 
329
            # On Linux, we seem to get EBUSY, on Mac we get EINVAL
 
330
            os.lstat(old)
 
331
        raise
 
332
 
 
333
 
 
334
def _mac_getcwd():
 
335
    return unicodedata.normalize('NFC', os.getcwdu())
 
336
 
 
337
 
 
338
# Default is to just use the python builtins, but these can be rebound on
 
339
# particular platforms.
 
340
abspath = _posix_abspath
 
341
realpath = _posix_realpath
 
342
pathjoin = os.path.join
 
343
normpath = os.path.normpath
 
344
getcwd = os.getcwdu
 
345
rename = os.rename
 
346
dirname = os.path.dirname
 
347
basename = os.path.basename
 
348
split = os.path.split
 
349
splitext = os.path.splitext
 
350
# These were already imported into local scope
 
351
# mkdtemp = tempfile.mkdtemp
 
352
# rmtree = shutil.rmtree
 
353
 
 
354
MIN_ABS_PATHLENGTH = 1
 
355
 
 
356
 
 
357
if sys.platform == 'win32':
 
358
    if win32utils.winver == 'Windows 98':
 
359
        abspath = _win98_abspath
 
360
    else:
 
361
        abspath = _win32_abspath
 
362
    realpath = _win32_realpath
 
363
    pathjoin = _win32_pathjoin
 
364
    normpath = _win32_normpath
 
365
    getcwd = _win32_getcwd
 
366
    mkdtemp = _win32_mkdtemp
 
367
    rename = _win32_rename
 
368
 
 
369
    MIN_ABS_PATHLENGTH = 3
 
370
 
 
371
    def _win32_delete_readonly(function, path, excinfo):
 
372
        """Error handler for shutil.rmtree function [for win32]
 
373
        Helps to remove files and dirs marked as read-only.
 
374
        """
 
375
        exception = excinfo[1]
 
376
        if function in (os.remove, os.rmdir) \
 
377
            and isinstance(exception, OSError) \
 
378
            and exception.errno == errno.EACCES:
 
379
            make_writable(path)
 
380
            function(path)
 
381
        else:
 
382
            raise
 
383
 
 
384
    def rmtree(path, ignore_errors=False, onerror=_win32_delete_readonly):
 
385
        """Replacer for shutil.rmtree: could remove readonly dirs/files"""
 
386
        return shutil.rmtree(path, ignore_errors, onerror)
 
387
elif sys.platform == 'darwin':
 
388
    getcwd = _mac_getcwd
 
389
 
 
390
 
 
391
def get_terminal_encoding():
 
392
    """Find the best encoding for printing to the screen.
 
393
 
 
394
    This attempts to check both sys.stdout and sys.stdin to see
 
395
    what encoding they are in, and if that fails it falls back to
 
396
    osutils.get_user_encoding().
 
397
    The problem is that on Windows, locale.getpreferredencoding()
 
398
    is not the same encoding as that used by the console:
 
399
    http://mail.python.org/pipermail/python-list/2003-May/162357.html
 
400
 
 
401
    On my standard US Windows XP, the preferred encoding is
 
402
    cp1252, but the console is cp437
 
403
    """
 
404
    from bzrlib.trace import mutter
 
405
    output_encoding = getattr(sys.stdout, 'encoding', None)
 
406
    if not output_encoding:
 
407
        input_encoding = getattr(sys.stdin, 'encoding', None)
 
408
        if not input_encoding:
 
409
            output_encoding = get_user_encoding()
 
410
            mutter('encoding stdout as osutils.get_user_encoding() %r',
 
411
                   output_encoding)
 
412
        else:
 
413
            output_encoding = input_encoding
 
414
            mutter('encoding stdout as sys.stdin encoding %r', output_encoding)
 
415
    else:
 
416
        mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
 
417
    if output_encoding == 'cp0':
 
418
        # invalid encoding (cp0 means 'no codepage' on Windows)
 
419
        output_encoding = get_user_encoding()
 
420
        mutter('cp0 is invalid encoding.'
 
421
               ' encoding stdout as osutils.get_user_encoding() %r',
 
422
               output_encoding)
 
423
    # check encoding
 
424
    try:
 
425
        codecs.lookup(output_encoding)
 
426
    except LookupError:
 
427
        sys.stderr.write('bzr: warning:'
 
428
                         ' unknown terminal encoding %s.\n'
 
429
                         '  Using encoding %s instead.\n'
 
430
                         % (output_encoding, get_user_encoding())
 
431
                        )
 
432
        output_encoding = get_user_encoding()
 
433
 
 
434
    return output_encoding
 
435
 
 
436
 
 
437
def normalizepath(f):
 
438
    if getattr(os.path, 'realpath', None) is not None:
 
439
        F = realpath
 
440
    else:
 
441
        F = abspath
 
442
    [p,e] = os.path.split(f)
 
443
    if e == "" or e == "." or e == "..":
 
444
        return F(f)
 
445
    else:
 
446
        return pathjoin(F(p), e)
 
447
 
 
448
 
 
449
def isdir(f):
 
450
    """True if f is an accessible directory."""
 
451
    try:
 
452
        return S_ISDIR(os.lstat(f)[ST_MODE])
 
453
    except OSError:
 
454
        return False
 
455
 
 
456
 
 
457
def isfile(f):
 
458
    """True if f is a regular file."""
 
459
    try:
 
460
        return S_ISREG(os.lstat(f)[ST_MODE])
 
461
    except OSError:
 
462
        return False
 
463
 
 
464
def islink(f):
 
465
    """True if f is a symlink."""
 
466
    try:
 
467
        return S_ISLNK(os.lstat(f)[ST_MODE])
 
468
    except OSError:
 
469
        return False
 
470
 
 
471
def is_inside(dir, fname):
 
472
    """True if fname is inside dir.
 
473
    
 
474
    The parameters should typically be passed to osutils.normpath first, so
 
475
    that . and .. and repeated slashes are eliminated, and the separators
 
476
    are canonical for the platform.
 
477
    
 
478
    The empty string as a dir name is taken as top-of-tree and matches 
 
479
    everything.
 
480
    """
 
481
    # XXX: Most callers of this can actually do something smarter by 
 
482
    # looking at the inventory
 
483
    if dir == fname:
 
484
        return True
 
485
    
 
486
    if dir == '':
 
487
        return True
 
488
 
 
489
    if dir[-1] != '/':
 
490
        dir += '/'
 
491
 
 
492
    return fname.startswith(dir)
 
493
 
 
494
 
 
495
def is_inside_any(dir_list, fname):
 
496
    """True if fname is inside any of given dirs."""
 
497
    for dirname in dir_list:
 
498
        if is_inside(dirname, fname):
 
499
            return True
 
500
    return False
 
501
 
 
502
 
 
503
def is_inside_or_parent_of_any(dir_list, fname):
 
504
    """True if fname is a child or a parent of any of the given files."""
 
505
    for dirname in dir_list:
 
506
        if is_inside(dirname, fname) or is_inside(fname, dirname):
 
507
            return True
 
508
    return False
 
509
 
 
510
 
 
511
def pumpfile(from_file, to_file, read_length=-1, buff_size=32768):
 
512
    """Copy contents of one file to another.
 
513
 
 
514
    The read_length can either be -1 to read to end-of-file (EOF) or
 
515
    it can specify the maximum number of bytes to read.
 
516
 
 
517
    The buff_size represents the maximum size for each read operation
 
518
    performed on from_file.
 
519
 
 
520
    :return: The number of bytes copied.
 
521
    """
 
522
    length = 0
 
523
    if read_length >= 0:
 
524
        # read specified number of bytes
 
525
 
 
526
        while read_length > 0:
 
527
            num_bytes_to_read = min(read_length, buff_size)
 
528
 
 
529
            block = from_file.read(num_bytes_to_read)
 
530
            if not block:
 
531
                # EOF reached
 
532
                break
 
533
            to_file.write(block)
 
534
 
 
535
            actual_bytes_read = len(block)
 
536
            read_length -= actual_bytes_read
 
537
            length += actual_bytes_read
 
538
    else:
 
539
        # read to EOF
 
540
        while True:
 
541
            block = from_file.read(buff_size)
 
542
            if not block:
 
543
                # EOF reached
 
544
                break
 
545
            to_file.write(block)
 
546
            length += len(block)
 
547
    return length
 
548
 
 
549
 
 
550
def pump_string_file(bytes, file_handle, segment_size=None):
 
551
    """Write bytes to file_handle in many smaller writes.
 
552
 
 
553
    :param bytes: The string to write.
 
554
    :param file_handle: The file to write to.
 
555
    """
 
556
    # Write data in chunks rather than all at once, because very large
 
557
    # writes fail on some platforms (e.g. Windows with SMB  mounted
 
558
    # drives).
 
559
    if not segment_size:
 
560
        segment_size = 5242880 # 5MB
 
561
    segments = range(len(bytes) / segment_size + 1)
 
562
    write = file_handle.write
 
563
    for segment_index in segments:
 
564
        segment = buffer(bytes, segment_index * segment_size, segment_size)
 
565
        write(segment)
 
566
 
 
567
 
 
568
def file_iterator(input_file, readsize=32768):
 
569
    while True:
 
570
        b = input_file.read(readsize)
 
571
        if len(b) == 0:
 
572
            break
 
573
        yield b
 
574
 
 
575
 
 
576
def sha_file(f):
 
577
    """Calculate the hexdigest of an open file.
 
578
 
 
579
    The file cursor should be already at the start.
 
580
    """
 
581
    s = sha()
 
582
    BUFSIZE = 128<<10
 
583
    while True:
 
584
        b = f.read(BUFSIZE)
 
585
        if not b:
 
586
            break
 
587
        s.update(b)
 
588
    return s.hexdigest()
 
589
 
 
590
 
 
591
def sha_file_by_name(fname):
 
592
    """Calculate the SHA1 of a file by reading the full text"""
 
593
    s = sha()
 
594
    f = os.open(fname, os.O_RDONLY | O_BINARY)
 
595
    try:
 
596
        while True:
 
597
            b = os.read(f, 1<<16)
 
598
            if not b:
 
599
                return s.hexdigest()
 
600
            s.update(b)
 
601
    finally:
 
602
        os.close(f)
 
603
 
 
604
 
 
605
def sha_strings(strings, _factory=sha):
 
606
    """Return the sha-1 of concatenation of strings"""
 
607
    s = _factory()
 
608
    map(s.update, strings)
 
609
    return s.hexdigest()
 
610
 
 
611
 
 
612
def sha_string(f, _factory=sha):
 
613
    return _factory(f).hexdigest()
 
614
 
 
615
 
 
616
def fingerprint_file(f):
 
617
    b = f.read()
 
618
    return {'size': len(b),
 
619
            'sha1': sha(b).hexdigest()}
 
620
 
 
621
 
 
622
def compare_files(a, b):
 
623
    """Returns true if equal in contents"""
 
624
    BUFSIZE = 4096
 
625
    while True:
 
626
        ai = a.read(BUFSIZE)
 
627
        bi = b.read(BUFSIZE)
 
628
        if ai != bi:
 
629
            return False
 
630
        if ai == '':
 
631
            return True
 
632
 
 
633
 
 
634
def local_time_offset(t=None):
 
635
    """Return offset of local zone from GMT, either at present or at time t."""
 
636
    if t is None:
 
637
        t = time.time()
 
638
    offset = datetime.fromtimestamp(t) - datetime.utcfromtimestamp(t)
 
639
    return offset.days * 86400 + offset.seconds
 
640
 
 
641
weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
 
642
    
 
643
def format_date(t, offset=0, timezone='original', date_fmt=None,
 
644
                show_offset=True):
 
645
    """Return a formatted date string.
 
646
 
 
647
    :param t: Seconds since the epoch.
 
648
    :param offset: Timezone offset in seconds east of utc.
 
649
    :param timezone: How to display the time: 'utc', 'original' for the
 
650
         timezone specified by offset, or 'local' for the process's current
 
651
         timezone.
 
652
    :param date_fmt: strftime format.
 
653
    :param show_offset: Whether to append the timezone.
 
654
    """
 
655
    (date_fmt, tt, offset_str) = \
 
656
               _format_date(t, offset, timezone, date_fmt, show_offset)
 
657
    date_fmt = date_fmt.replace('%a', weekdays[tt[6]])
 
658
    date_str = time.strftime(date_fmt, tt)
 
659
    return date_str + offset_str
 
660
 
 
661
def format_local_date(t, offset=0, timezone='original', date_fmt=None,
 
662
                      show_offset=True):
 
663
    """Return an unicode date string formatted according to the current locale.
 
664
 
 
665
    :param t: Seconds since the epoch.
 
666
    :param offset: Timezone offset in seconds east of utc.
 
667
    :param timezone: How to display the time: 'utc', 'original' for the
 
668
         timezone specified by offset, or 'local' for the process's current
 
669
         timezone.
 
670
    :param date_fmt: strftime format.
 
671
    :param show_offset: Whether to append the timezone.
 
672
    """
 
673
    (date_fmt, tt, offset_str) = \
 
674
               _format_date(t, offset, timezone, date_fmt, show_offset)
 
675
    date_str = time.strftime(date_fmt, tt)
 
676
    if not isinstance(date_str, unicode):
 
677
        date_str = date_str.decode(bzrlib.user_encoding, 'replace')
 
678
    return date_str + offset_str
 
679
 
 
680
def _format_date(t, offset, timezone, date_fmt, show_offset):
 
681
    if timezone == 'utc':
 
682
        tt = time.gmtime(t)
 
683
        offset = 0
 
684
    elif timezone == 'original':
 
685
        if offset is None:
 
686
            offset = 0
 
687
        tt = time.gmtime(t + offset)
 
688
    elif timezone == 'local':
 
689
        tt = time.localtime(t)
 
690
        offset = local_time_offset(t)
 
691
    else:
 
692
        raise errors.UnsupportedTimezoneFormat(timezone)
 
693
    if date_fmt is None:
 
694
        date_fmt = "%a %Y-%m-%d %H:%M:%S"
 
695
    if show_offset:
 
696
        offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
 
697
    else:
 
698
        offset_str = ''
 
699
    return (date_fmt, tt, offset_str)
 
700
 
 
701
 
 
702
def compact_date(when):
 
703
    return time.strftime('%Y%m%d%H%M%S', time.gmtime(when))
 
704
    
 
705
 
 
706
def format_delta(delta):
 
707
    """Get a nice looking string for a time delta.
 
708
 
 
709
    :param delta: The time difference in seconds, can be positive or negative.
 
710
        positive indicates time in the past, negative indicates time in the
 
711
        future. (usually time.time() - stored_time)
 
712
    :return: String formatted to show approximate resolution
 
713
    """
 
714
    delta = int(delta)
 
715
    if delta >= 0:
 
716
        direction = 'ago'
 
717
    else:
 
718
        direction = 'in the future'
 
719
        delta = -delta
 
720
 
 
721
    seconds = delta
 
722
    if seconds < 90: # print seconds up to 90 seconds
 
723
        if seconds == 1:
 
724
            return '%d second %s' % (seconds, direction,)
 
725
        else:
 
726
            return '%d seconds %s' % (seconds, direction)
 
727
 
 
728
    minutes = int(seconds / 60)
 
729
    seconds -= 60 * minutes
 
730
    if seconds == 1:
 
731
        plural_seconds = ''
 
732
    else:
 
733
        plural_seconds = 's'
 
734
    if minutes < 90: # print minutes, seconds up to 90 minutes
 
735
        if minutes == 1:
 
736
            return '%d minute, %d second%s %s' % (
 
737
                    minutes, seconds, plural_seconds, direction)
 
738
        else:
 
739
            return '%d minutes, %d second%s %s' % (
 
740
                    minutes, seconds, plural_seconds, direction)
 
741
 
 
742
    hours = int(minutes / 60)
 
743
    minutes -= 60 * hours
 
744
    if minutes == 1:
 
745
        plural_minutes = ''
 
746
    else:
 
747
        plural_minutes = 's'
 
748
 
 
749
    if hours == 1:
 
750
        return '%d hour, %d minute%s %s' % (hours, minutes,
 
751
                                            plural_minutes, direction)
 
752
    return '%d hours, %d minute%s %s' % (hours, minutes,
 
753
                                         plural_minutes, direction)
 
754
 
 
755
def filesize(f):
 
756
    """Return size of given open file."""
 
757
    return os.fstat(f.fileno())[ST_SIZE]
 
758
 
 
759
 
 
760
# Define rand_bytes based on platform.
 
761
try:
 
762
    # Python 2.4 and later have os.urandom,
 
763
    # but it doesn't work on some arches
 
764
    os.urandom(1)
 
765
    rand_bytes = os.urandom
 
766
except (NotImplementedError, AttributeError):
 
767
    # If python doesn't have os.urandom, or it doesn't work,
 
768
    # then try to first pull random data from /dev/urandom
 
769
    try:
 
770
        rand_bytes = file('/dev/urandom', 'rb').read
 
771
    # Otherwise, use this hack as a last resort
 
772
    except (IOError, OSError):
 
773
        # not well seeded, but better than nothing
 
774
        def rand_bytes(n):
 
775
            import random
 
776
            s = ''
 
777
            while n:
 
778
                s += chr(random.randint(0, 255))
 
779
                n -= 1
 
780
            return s
 
781
 
 
782
 
 
783
ALNUM = '0123456789abcdefghijklmnopqrstuvwxyz'
 
784
def rand_chars(num):
 
785
    """Return a random string of num alphanumeric characters
 
786
    
 
787
    The result only contains lowercase chars because it may be used on 
 
788
    case-insensitive filesystems.
 
789
    """
 
790
    s = ''
 
791
    for raw_byte in rand_bytes(num):
 
792
        s += ALNUM[ord(raw_byte) % 36]
 
793
    return s
 
794
 
 
795
 
 
796
## TODO: We could later have path objects that remember their list
 
797
## decomposition (might be too tricksy though.)
 
798
 
 
799
def splitpath(p):
 
800
    """Turn string into list of parts."""
 
801
    # split on either delimiter because people might use either on
 
802
    # Windows
 
803
    ps = re.split(r'[\\/]', p)
 
804
 
 
805
    rps = []
 
806
    for f in ps:
 
807
        if f == '..':
 
808
            raise errors.BzrError("sorry, %r not allowed in path" % f)
 
809
        elif (f == '.') or (f == ''):
 
810
            pass
 
811
        else:
 
812
            rps.append(f)
 
813
    return rps
 
814
 
 
815
def joinpath(p):
 
816
    for f in p:
 
817
        if (f == '..') or (f is None) or (f == ''):
 
818
            raise errors.BzrError("sorry, %r not allowed in path" % f)
 
819
    return pathjoin(*p)
 
820
 
 
821
 
 
822
def split_lines(s):
 
823
    """Split s into lines, but without removing the newline characters."""
 
824
    lines = s.split('\n')
 
825
    result = [line + '\n' for line in lines[:-1]]
 
826
    if lines[-1]:
 
827
        result.append(lines[-1])
 
828
    return result
 
829
 
 
830
 
 
831
def hardlinks_good():
 
832
    return sys.platform not in ('win32', 'cygwin', 'darwin')
 
833
 
 
834
 
 
835
def link_or_copy(src, dest):
 
836
    """Hardlink a file, or copy it if it can't be hardlinked."""
 
837
    if not hardlinks_good():
 
838
        shutil.copyfile(src, dest)
 
839
        return
 
840
    try:
 
841
        os.link(src, dest)
 
842
    except (OSError, IOError), e:
 
843
        if e.errno != errno.EXDEV:
 
844
            raise
 
845
        shutil.copyfile(src, dest)
 
846
 
 
847
 
 
848
# Look Before You Leap (LBYL) is appropriate here instead of Easier to Ask for
 
849
# Forgiveness than Permission (EAFP) because:
 
850
# - root can damage a solaris file system by using unlink,
 
851
# - unlink raises different exceptions on different OSes (linux: EISDIR, win32:
 
852
#   EACCES, OSX: EPERM) when invoked on a directory.
 
853
def delete_any(path):
 
854
    """Delete a file or directory."""
 
855
    if isdir(path): # Takes care of symlinks
 
856
        os.rmdir(path)
 
857
    else:
 
858
        os.unlink(path)
 
859
 
 
860
 
 
861
def has_symlinks():
 
862
    if getattr(os, 'symlink', None) is not None:
 
863
        return True
 
864
    else:
 
865
        return False
 
866
 
 
867
 
 
868
def has_hardlinks():
 
869
    if getattr(os, 'link', None) is not None:
 
870
        return True
 
871
    else:
 
872
        return False
 
873
 
 
874
 
 
875
def host_os_dereferences_symlinks():
 
876
    return (has_symlinks()
 
877
            and sys.platform not in ('cygwin', 'win32'))
 
878
 
 
879
 
 
880
def contains_whitespace(s):
 
881
    """True if there are any whitespace characters in s."""
 
882
    # string.whitespace can include '\xa0' in certain locales, because it is
 
883
    # considered "non-breaking-space" as part of ISO-8859-1. But it
 
884
    # 1) Isn't a breaking whitespace
 
885
    # 2) Isn't one of ' \t\r\n' which are characters we sometimes use as
 
886
    #    separators
 
887
    # 3) '\xa0' isn't unicode safe since it is >128.
 
888
 
 
889
    # This should *not* be a unicode set of characters in case the source
 
890
    # string is not a Unicode string. We can auto-up-cast the characters since
 
891
    # they are ascii, but we don't want to auto-up-cast the string in case it
 
892
    # is utf-8
 
893
    for ch in ' \t\n\r\v\f':
 
894
        if ch in s:
 
895
            return True
 
896
    else:
 
897
        return False
 
898
 
 
899
 
 
900
def contains_linebreaks(s):
 
901
    """True if there is any vertical whitespace in s."""
 
902
    for ch in '\f\n\r':
 
903
        if ch in s:
 
904
            return True
 
905
    else:
 
906
        return False
 
907
 
 
908
 
 
909
def relpath(base, path):
 
910
    """Return path relative to base, or raise exception.
 
911
 
 
912
    The path may be either an absolute path or a path relative to the
 
913
    current working directory.
 
914
 
 
915
    os.path.commonprefix (python2.4) has a bad bug that it works just
 
916
    on string prefixes, assuming that '/u' is a prefix of '/u2'.  This
 
917
    avoids that problem.
 
918
    """
 
919
 
 
920
    if len(base) < MIN_ABS_PATHLENGTH:
 
921
        # must have space for e.g. a drive letter
 
922
        raise ValueError('%r is too short to calculate a relative path'
 
923
            % (base,))
 
924
 
 
925
    rp = abspath(path)
 
926
 
 
927
    s = []
 
928
    head = rp
 
929
    while len(head) >= len(base):
 
930
        if head == base:
 
931
            break
 
932
        head, tail = os.path.split(head)
 
933
        if tail:
 
934
            s.insert(0, tail)
 
935
    else:
 
936
        raise errors.PathNotChild(rp, base)
 
937
 
 
938
    if s:
 
939
        return pathjoin(*s)
 
940
    else:
 
941
        return ''
 
942
 
 
943
 
 
944
def safe_unicode(unicode_or_utf8_string):
 
945
    """Coerce unicode_or_utf8_string into unicode.
 
946
 
 
947
    If it is unicode, it is returned.
 
948
    Otherwise it is decoded from utf-8. If a decoding error
 
949
    occurs, it is wrapped as a If the decoding fails, the exception is wrapped 
 
950
    as a BzrBadParameter exception.
 
951
    """
 
952
    if isinstance(unicode_or_utf8_string, unicode):
 
953
        return unicode_or_utf8_string
 
954
    try:
 
955
        return unicode_or_utf8_string.decode('utf8')
 
956
    except UnicodeDecodeError:
 
957
        raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
 
958
 
 
959
 
 
960
def safe_utf8(unicode_or_utf8_string):
 
961
    """Coerce unicode_or_utf8_string to a utf8 string.
 
962
 
 
963
    If it is a str, it is returned.
 
964
    If it is Unicode, it is encoded into a utf-8 string.
 
965
    """
 
966
    if isinstance(unicode_or_utf8_string, str):
 
967
        # TODO: jam 20070209 This is overkill, and probably has an impact on
 
968
        #       performance if we are dealing with lots of apis that want a
 
969
        #       utf-8 revision id
 
970
        try:
 
971
            # Make sure it is a valid utf-8 string
 
972
            unicode_or_utf8_string.decode('utf-8')
 
973
        except UnicodeDecodeError:
 
974
            raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
 
975
        return unicode_or_utf8_string
 
976
    return unicode_or_utf8_string.encode('utf-8')
 
977
 
 
978
 
 
979
_revision_id_warning = ('Unicode revision ids were deprecated in bzr 0.15.'
 
980
                        ' Revision id generators should be creating utf8'
 
981
                        ' revision ids.')
 
982
 
 
983
 
 
984
def safe_revision_id(unicode_or_utf8_string, warn=True):
 
985
    """Revision ids should now be utf8, but at one point they were unicode.
 
986
 
 
987
    :param unicode_or_utf8_string: A possibly Unicode revision_id. (can also be
 
988
        utf8 or None).
 
989
    :param warn: Functions that are sanitizing user data can set warn=False
 
990
    :return: None or a utf8 revision id.
 
991
    """
 
992
    if (unicode_or_utf8_string is None
 
993
        or unicode_or_utf8_string.__class__ == str):
 
994
        return unicode_or_utf8_string
 
995
    if warn:
 
996
        symbol_versioning.warn(_revision_id_warning, DeprecationWarning,
 
997
                               stacklevel=2)
 
998
    return cache_utf8.encode(unicode_or_utf8_string)
 
999
 
 
1000
 
 
1001
_file_id_warning = ('Unicode file ids were deprecated in bzr 0.15. File id'
 
1002
                    ' generators should be creating utf8 file ids.')
 
1003
 
 
1004
 
 
1005
def safe_file_id(unicode_or_utf8_string, warn=True):
 
1006
    """File ids should now be utf8, but at one point they were unicode.
 
1007
 
 
1008
    This is the same as safe_utf8, except it uses the cached encode functions
 
1009
    to save a little bit of performance.
 
1010
 
 
1011
    :param unicode_or_utf8_string: A possibly Unicode file_id. (can also be
 
1012
        utf8 or None).
 
1013
    :param warn: Functions that are sanitizing user data can set warn=False
 
1014
    :return: None or a utf8 file id.
 
1015
    """
 
1016
    if (unicode_or_utf8_string is None
 
1017
        or unicode_or_utf8_string.__class__ == str):
 
1018
        return unicode_or_utf8_string
 
1019
    if warn:
 
1020
        symbol_versioning.warn(_file_id_warning, DeprecationWarning,
 
1021
                               stacklevel=2)
 
1022
    return cache_utf8.encode(unicode_or_utf8_string)
 
1023
 
 
1024
 
 
1025
_platform_normalizes_filenames = False
 
1026
if sys.platform == 'darwin':
 
1027
    _platform_normalizes_filenames = True
 
1028
 
 
1029
 
 
1030
def normalizes_filenames():
 
1031
    """Return True if this platform normalizes unicode filenames.
 
1032
 
 
1033
    Mac OSX does, Windows/Linux do not.
 
1034
    """
 
1035
    return _platform_normalizes_filenames
 
1036
 
 
1037
 
 
1038
def _accessible_normalized_filename(path):
 
1039
    """Get the unicode normalized path, and if you can access the file.
 
1040
 
 
1041
    On platforms where the system normalizes filenames (Mac OSX),
 
1042
    you can access a file by any path which will normalize correctly.
 
1043
    On platforms where the system does not normalize filenames 
 
1044
    (Windows, Linux), you have to access a file by its exact path.
 
1045
 
 
1046
    Internally, bzr only supports NFC normalization, since that is 
 
1047
    the standard for XML documents.
 
1048
 
 
1049
    So return the normalized path, and a flag indicating if the file
 
1050
    can be accessed by that path.
 
1051
    """
 
1052
 
 
1053
    return unicodedata.normalize('NFC', unicode(path)), True
 
1054
 
 
1055
 
 
1056
def _inaccessible_normalized_filename(path):
 
1057
    __doc__ = _accessible_normalized_filename.__doc__
 
1058
 
 
1059
    normalized = unicodedata.normalize('NFC', unicode(path))
 
1060
    return normalized, normalized == path
 
1061
 
 
1062
 
 
1063
if _platform_normalizes_filenames:
 
1064
    normalized_filename = _accessible_normalized_filename
 
1065
else:
 
1066
    normalized_filename = _inaccessible_normalized_filename
 
1067
 
 
1068
 
 
1069
def terminal_width():
 
1070
    """Return estimated terminal width."""
 
1071
    if sys.platform == 'win32':
 
1072
        return win32utils.get_console_size()[0]
 
1073
    width = 0
 
1074
    try:
 
1075
        import struct, fcntl, termios
 
1076
        s = struct.pack('HHHH', 0, 0, 0, 0)
 
1077
        x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
 
1078
        width = struct.unpack('HHHH', x)[1]
 
1079
    except IOError:
 
1080
        pass
 
1081
    if width <= 0:
 
1082
        try:
 
1083
            width = int(os.environ['COLUMNS'])
 
1084
        except:
 
1085
            pass
 
1086
    if width <= 0:
 
1087
        width = 80
 
1088
 
 
1089
    return width
 
1090
 
 
1091
 
 
1092
def supports_executable():
 
1093
    return sys.platform != "win32"
 
1094
 
 
1095
 
 
1096
def supports_posix_readonly():
 
1097
    """Return True if 'readonly' has POSIX semantics, False otherwise.
 
1098
 
 
1099
    Notably, a win32 readonly file cannot be deleted, unlike POSIX where the
 
1100
    directory controls creation/deletion, etc.
 
1101
 
 
1102
    And under win32, readonly means that the directory itself cannot be
 
1103
    deleted.  The contents of a readonly directory can be changed, unlike POSIX
 
1104
    where files in readonly directories cannot be added, deleted or renamed.
 
1105
    """
 
1106
    return sys.platform != "win32"
 
1107
 
 
1108
 
 
1109
def set_or_unset_env(env_variable, value):
 
1110
    """Modify the environment, setting or removing the env_variable.
 
1111
 
 
1112
    :param env_variable: The environment variable in question
 
1113
    :param value: The value to set the environment to. If None, then
 
1114
        the variable will be removed.
 
1115
    :return: The original value of the environment variable.
 
1116
    """
 
1117
    orig_val = os.environ.get(env_variable)
 
1118
    if value is None:
 
1119
        if orig_val is not None:
 
1120
            del os.environ[env_variable]
 
1121
    else:
 
1122
        if isinstance(value, unicode):
 
1123
            value = value.encode(get_user_encoding())
 
1124
        os.environ[env_variable] = value
 
1125
    return orig_val
 
1126
 
 
1127
 
 
1128
_validWin32PathRE = re.compile(r'^([A-Za-z]:[/\\])?[^:<>*"?\|]*$')
 
1129
 
 
1130
 
 
1131
def check_legal_path(path):
 
1132
    """Check whether the supplied path is legal.  
 
1133
    This is only required on Windows, so we don't test on other platforms
 
1134
    right now.
 
1135
    """
 
1136
    if sys.platform != "win32":
 
1137
        return
 
1138
    if _validWin32PathRE.match(path) is None:
 
1139
        raise errors.IllegalPath(path)
 
1140
 
 
1141
 
 
1142
_WIN32_ERROR_DIRECTORY = 267 # Similar to errno.ENOTDIR
 
1143
 
 
1144
def _is_error_enotdir(e):
 
1145
    """Check if this exception represents ENOTDIR.
 
1146
 
 
1147
    Unfortunately, python is very inconsistent about the exception
 
1148
    here. The cases are:
 
1149
      1) Linux, Mac OSX all versions seem to set errno == ENOTDIR
 
1150
      2) Windows, Python2.4, uses errno == ERROR_DIRECTORY (267)
 
1151
         which is the windows error code.
 
1152
      3) Windows, Python2.5 uses errno == EINVAL and
 
1153
         winerror == ERROR_DIRECTORY
 
1154
 
 
1155
    :param e: An Exception object (expected to be OSError with an errno
 
1156
        attribute, but we should be able to cope with anything)
 
1157
    :return: True if this represents an ENOTDIR error. False otherwise.
 
1158
    """
 
1159
    en = getattr(e, 'errno', None)
 
1160
    if (en == errno.ENOTDIR
 
1161
        or (sys.platform == 'win32'
 
1162
            and (en == _WIN32_ERROR_DIRECTORY
 
1163
                 or (en == errno.EINVAL
 
1164
                     and getattr(e, 'winerror', None) == _WIN32_ERROR_DIRECTORY)
 
1165
        ))):
 
1166
        return True
 
1167
    return False
 
1168
 
 
1169
 
 
1170
def walkdirs(top, prefix=""):
 
1171
    """Yield data about all the directories in a tree.
 
1172
    
 
1173
    This yields all the data about the contents of a directory at a time.
 
1174
    After each directory has been yielded, if the caller has mutated the list
 
1175
    to exclude some directories, they are then not descended into.
 
1176
    
 
1177
    The data yielded is of the form:
 
1178
    ((directory-relpath, directory-path-from-top),
 
1179
    [(relpath, basename, kind, lstat, path-from-top), ...]),
 
1180
     - directory-relpath is the relative path of the directory being returned
 
1181
       with respect to top. prefix is prepended to this.
 
1182
     - directory-path-from-root is the path including top for this directory. 
 
1183
       It is suitable for use with os functions.
 
1184
     - relpath is the relative path within the subtree being walked.
 
1185
     - basename is the basename of the path
 
1186
     - kind is the kind of the file now. If unknown then the file is not
 
1187
       present within the tree - but it may be recorded as versioned. See
 
1188
       versioned_kind.
 
1189
     - lstat is the stat data *if* the file was statted.
 
1190
     - planned, not implemented: 
 
1191
       path_from_tree_root is the path from the root of the tree.
 
1192
 
 
1193
    :param prefix: Prefix the relpaths that are yielded with 'prefix'. This 
 
1194
        allows one to walk a subtree but get paths that are relative to a tree
 
1195
        rooted higher up.
 
1196
    :return: an iterator over the dirs.
 
1197
    """
 
1198
    #TODO there is a bit of a smell where the results of the directory-
 
1199
    # summary in this, and the path from the root, may not agree 
 
1200
    # depending on top and prefix - i.e. ./foo and foo as a pair leads to
 
1201
    # potentially confusing output. We should make this more robust - but
 
1202
    # not at a speed cost. RBC 20060731
 
1203
    _lstat = os.lstat
 
1204
    _directory = _directory_kind
 
1205
    _listdir = os.listdir
 
1206
    _kind_from_mode = file_kind_from_stat_mode
 
1207
    pending = [(safe_unicode(prefix), "", _directory, None, safe_unicode(top))]
 
1208
    while pending:
 
1209
        # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
 
1210
        relroot, _, _, _, top = pending.pop()
 
1211
        if relroot:
 
1212
            relprefix = relroot + u'/'
 
1213
        else:
 
1214
            relprefix = ''
 
1215
        top_slash = top + u'/'
 
1216
 
 
1217
        dirblock = []
 
1218
        append = dirblock.append
 
1219
        try:
 
1220
            names = sorted(_listdir(top))
 
1221
        except OSError, e:
 
1222
            if not _is_error_enotdir(e):
 
1223
                raise
 
1224
        else:
 
1225
            for name in names:
 
1226
                abspath = top_slash + name
 
1227
                statvalue = _lstat(abspath)
 
1228
                kind = _kind_from_mode(statvalue.st_mode)
 
1229
                append((relprefix + name, name, kind, statvalue, abspath))
 
1230
        yield (relroot, top), dirblock
 
1231
 
 
1232
        # push the user specified dirs from dirblock
 
1233
        pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
 
1234
 
 
1235
 
 
1236
class DirReader(object):
 
1237
    """An interface for reading directories."""
 
1238
 
 
1239
    def top_prefix_to_starting_dir(self, top, prefix=""):
 
1240
        """Converts top and prefix to a starting dir entry
 
1241
 
 
1242
        :param top: A utf8 path
 
1243
        :param prefix: An optional utf8 path to prefix output relative paths
 
1244
            with.
 
1245
        :return: A tuple starting with prefix, and ending with the native
 
1246
            encoding of top.
 
1247
        """
 
1248
        raise NotImplementedError(self.top_prefix_to_starting_dir)
 
1249
 
 
1250
    def read_dir(self, prefix, top):
 
1251
        """Read a specific dir.
 
1252
 
 
1253
        :param prefix: A utf8 prefix to be preprended to the path basenames.
 
1254
        :param top: A natively encoded path to read.
 
1255
        :return: A list of the directories contents. Each item contains:
 
1256
            (utf8_relpath, utf8_name, kind, lstatvalue, native_abspath)
 
1257
        """
 
1258
        raise NotImplementedError(self.read_dir)
 
1259
 
 
1260
 
 
1261
_selected_dir_reader = None
 
1262
 
 
1263
 
 
1264
def _walkdirs_utf8(top, prefix=""):
 
1265
    """Yield data about all the directories in a tree.
 
1266
 
 
1267
    This yields the same information as walkdirs() only each entry is yielded
 
1268
    in utf-8. On platforms which have a filesystem encoding of utf8 the paths
 
1269
    are returned as exact byte-strings.
 
1270
 
 
1271
    :return: yields a tuple of (dir_info, [file_info])
 
1272
        dir_info is (utf8_relpath, path-from-top)
 
1273
        file_info is (utf8_relpath, utf8_name, kind, lstat, path-from-top)
 
1274
        if top is an absolute path, path-from-top is also an absolute path.
 
1275
        path-from-top might be unicode or utf8, but it is the correct path to
 
1276
        pass to os functions to affect the file in question. (such as os.lstat)
 
1277
    """
 
1278
    global _selected_dir_reader
 
1279
    if _selected_dir_reader is None:
 
1280
        fs_encoding = _fs_enc.upper()
 
1281
        if sys.platform == "win32" and win32utils.winver == 'Windows NT':
 
1282
            # Win98 doesn't have unicode apis like FindFirstFileW
 
1283
            # TODO: We possibly could support Win98 by falling back to the
 
1284
            #       original FindFirstFile, and using TCHAR instead of WCHAR,
 
1285
            #       but that gets a bit tricky, and requires custom compiling
 
1286
            #       for win98 anyway.
 
1287
            try:
 
1288
                from bzrlib._walkdirs_win32 import Win32ReadDir
 
1289
            except ImportError:
 
1290
                _selected_dir_reader = UnicodeDirReader()
 
1291
            else:
 
1292
                _selected_dir_reader = Win32ReadDir()
 
1293
        elif fs_encoding not in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
 
1294
            # ANSI_X3.4-1968 is a form of ASCII
 
1295
            _selected_dir_reader = UnicodeDirReader()
 
1296
        else:
 
1297
            try:
 
1298
                from bzrlib._readdir_pyx import UTF8DirReader
 
1299
            except ImportError:
 
1300
                # No optimised code path
 
1301
                _selected_dir_reader = UnicodeDirReader()
 
1302
            else:
 
1303
                _selected_dir_reader = UTF8DirReader()
 
1304
    # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
 
1305
    # But we don't actually uses 1-3 in pending, so set them to None
 
1306
    pending = [[_selected_dir_reader.top_prefix_to_starting_dir(top, prefix)]]
 
1307
    read_dir = _selected_dir_reader.read_dir
 
1308
    _directory = _directory_kind
 
1309
    while pending:
 
1310
        relroot, _, _, _, top = pending[-1].pop()
 
1311
        if not pending[-1]:
 
1312
            pending.pop()
 
1313
        dirblock = sorted(read_dir(relroot, top))
 
1314
        yield (relroot, top), dirblock
 
1315
        # push the user specified dirs from dirblock
 
1316
        next = [d for d in reversed(dirblock) if d[2] == _directory]
 
1317
        if next:
 
1318
            pending.append(next)
 
1319
 
 
1320
 
 
1321
class UnicodeDirReader(DirReader):
 
1322
    """A dir reader for non-utf8 file systems, which transcodes."""
 
1323
 
 
1324
    __slots__ = ['_utf8_encode']
 
1325
 
 
1326
    def __init__(self):
 
1327
        self._utf8_encode = codecs.getencoder('utf8')
 
1328
 
 
1329
    def top_prefix_to_starting_dir(self, top, prefix=""):
 
1330
        """See DirReader.top_prefix_to_starting_dir."""
 
1331
        return (safe_utf8(prefix), None, None, None, safe_unicode(top))
 
1332
 
 
1333
    def read_dir(self, prefix, top):
 
1334
        """Read a single directory from a non-utf8 file system.
 
1335
 
 
1336
        top, and the abspath element in the output are unicode, all other paths
 
1337
        are utf8. Local disk IO is done via unicode calls to listdir etc.
 
1338
 
 
1339
        This is currently the fallback code path when the filesystem encoding is
 
1340
        not UTF-8. It may be better to implement an alternative so that we can
 
1341
        safely handle paths that are not properly decodable in the current
 
1342
        encoding.
 
1343
 
 
1344
        See DirReader.read_dir for details.
 
1345
        """
 
1346
        _utf8_encode = self._utf8_encode
 
1347
        _lstat = os.lstat
 
1348
        _listdir = os.listdir
 
1349
        _kind_from_mode = file_kind_from_stat_mode
 
1350
 
 
1351
        if prefix:
 
1352
            relprefix = prefix + '/'
 
1353
        else:
 
1354
            relprefix = ''
 
1355
        top_slash = top + u'/'
 
1356
 
 
1357
        dirblock = []
 
1358
        append = dirblock.append
 
1359
        for name in sorted(_listdir(top)):
 
1360
            try:
 
1361
                name_utf8 = _utf8_encode(name)[0]
 
1362
            except UnicodeDecodeError:
 
1363
                raise errors.BadFilenameEncoding(
 
1364
                    _utf8_encode(relprefix)[0] + name, _fs_enc)
 
1365
            abspath = top_slash + name
 
1366
            statvalue = _lstat(abspath)
 
1367
            kind = _kind_from_mode(statvalue.st_mode)
 
1368
            append((relprefix + name_utf8, name_utf8, kind, statvalue, abspath))
 
1369
        return dirblock
 
1370
 
 
1371
 
 
1372
def copy_tree(from_path, to_path, handlers={}):
 
1373
    """Copy all of the entries in from_path into to_path.
 
1374
 
 
1375
    :param from_path: The base directory to copy. 
 
1376
    :param to_path: The target directory. If it does not exist, it will
 
1377
        be created.
 
1378
    :param handlers: A dictionary of functions, which takes a source and
 
1379
        destinations for files, directories, etc.
 
1380
        It is keyed on the file kind, such as 'directory', 'symlink', or 'file'
 
1381
        'file', 'directory', and 'symlink' should always exist.
 
1382
        If they are missing, they will be replaced with 'os.mkdir()',
 
1383
        'os.readlink() + os.symlink()', and 'shutil.copy2()', respectively.
 
1384
    """
 
1385
    # Now, just copy the existing cached tree to the new location
 
1386
    # We use a cheap trick here.
 
1387
    # Absolute paths are prefixed with the first parameter
 
1388
    # relative paths are prefixed with the second.
 
1389
    # So we can get both the source and target returned
 
1390
    # without any extra work.
 
1391
 
 
1392
    def copy_dir(source, dest):
 
1393
        os.mkdir(dest)
 
1394
 
 
1395
    def copy_link(source, dest):
 
1396
        """Copy the contents of a symlink"""
 
1397
        link_to = os.readlink(source)
 
1398
        os.symlink(link_to, dest)
 
1399
 
 
1400
    real_handlers = {'file':shutil.copy2,
 
1401
                     'symlink':copy_link,
 
1402
                     'directory':copy_dir,
 
1403
                    }
 
1404
    real_handlers.update(handlers)
 
1405
 
 
1406
    if not os.path.exists(to_path):
 
1407
        real_handlers['directory'](from_path, to_path)
 
1408
 
 
1409
    for dir_info, entries in walkdirs(from_path, prefix=to_path):
 
1410
        for relpath, name, kind, st, abspath in entries:
 
1411
            real_handlers[kind](abspath, relpath)
 
1412
 
 
1413
 
 
1414
def path_prefix_key(path):
 
1415
    """Generate a prefix-order path key for path.
 
1416
 
 
1417
    This can be used to sort paths in the same way that walkdirs does.
 
1418
    """
 
1419
    return (dirname(path) , path)
 
1420
 
 
1421
 
 
1422
def compare_paths_prefix_order(path_a, path_b):
 
1423
    """Compare path_a and path_b to generate the same order walkdirs uses."""
 
1424
    key_a = path_prefix_key(path_a)
 
1425
    key_b = path_prefix_key(path_b)
 
1426
    return cmp(key_a, key_b)
 
1427
 
 
1428
 
 
1429
_cached_user_encoding = None
 
1430
 
 
1431
 
 
1432
def get_user_encoding(use_cache=True):
 
1433
    """Find out what the preferred user encoding is.
 
1434
 
 
1435
    This is generally the encoding that is used for command line parameters
 
1436
    and file contents. This may be different from the terminal encoding
 
1437
    or the filesystem encoding.
 
1438
 
 
1439
    :param  use_cache:  Enable cache for detected encoding.
 
1440
                        (This parameter is turned on by default,
 
1441
                        and required only for selftesting)
 
1442
 
 
1443
    :return: A string defining the preferred user encoding
 
1444
    """
 
1445
    global _cached_user_encoding
 
1446
    if _cached_user_encoding is not None and use_cache:
 
1447
        return _cached_user_encoding
 
1448
 
 
1449
    if sys.platform == 'darwin':
 
1450
        # python locale.getpreferredencoding() always return
 
1451
        # 'mac-roman' on darwin. That's a lie.
 
1452
        sys.platform = 'posix'
 
1453
        try:
 
1454
            if os.environ.get('LANG', None) is None:
 
1455
                # If LANG is not set, we end up with 'ascii', which is bad
 
1456
                # ('mac-roman' is more than ascii), so we set a default which
 
1457
                # will give us UTF-8 (which appears to work in all cases on
 
1458
                # OSX). Users are still free to override LANG of course, as
 
1459
                # long as it give us something meaningful. This work-around
 
1460
                # *may* not be needed with python 3k and/or OSX 10.5, but will
 
1461
                # work with them too -- vila 20080908
 
1462
                os.environ['LANG'] = 'en_US.UTF-8'
 
1463
            import locale
 
1464
        finally:
 
1465
            sys.platform = 'darwin'
 
1466
    else:
 
1467
        import locale
 
1468
 
 
1469
    try:
 
1470
        user_encoding = locale.getpreferredencoding()
 
1471
    except locale.Error, e:
 
1472
        sys.stderr.write('bzr: warning: %s\n'
 
1473
                         '  Could not determine what text encoding to use.\n'
 
1474
                         '  This error usually means your Python interpreter\n'
 
1475
                         '  doesn\'t support the locale set by $LANG (%s)\n'
 
1476
                         "  Continuing with ascii encoding.\n"
 
1477
                         % (e, os.environ.get('LANG')))
 
1478
        user_encoding = 'ascii'
 
1479
 
 
1480
    # Windows returns 'cp0' to indicate there is no code page. So we'll just
 
1481
    # treat that as ASCII, and not support printing unicode characters to the
 
1482
    # console.
 
1483
    #
 
1484
    # For python scripts run under vim, we get '', so also treat that as ASCII
 
1485
    if user_encoding in (None, 'cp0', ''):
 
1486
        user_encoding = 'ascii'
 
1487
    else:
 
1488
        # check encoding
 
1489
        try:
 
1490
            codecs.lookup(user_encoding)
 
1491
        except LookupError:
 
1492
            sys.stderr.write('bzr: warning:'
 
1493
                             ' unknown encoding %s.'
 
1494
                             ' Continuing with ascii encoding.\n'
 
1495
                             % user_encoding
 
1496
                            )
 
1497
            user_encoding = 'ascii'
 
1498
 
 
1499
    if use_cache:
 
1500
        _cached_user_encoding = user_encoding
 
1501
 
 
1502
    return user_encoding
 
1503
 
 
1504
 
 
1505
def get_host_name():
 
1506
    """Return the current unicode host name.
 
1507
 
 
1508
    This is meant to be used in place of socket.gethostname() because that
 
1509
    behaves inconsistently on different platforms.
 
1510
    """
 
1511
    if sys.platform == "win32":
 
1512
        import win32utils
 
1513
        return win32utils.get_host_name()
 
1514
    else:
 
1515
        import socket
 
1516
        return socket.gethostname().decode(get_user_encoding())
 
1517
 
 
1518
 
 
1519
def recv_all(socket, bytes):
 
1520
    """Receive an exact number of bytes.
 
1521
 
 
1522
    Regular Socket.recv() may return less than the requested number of bytes,
 
1523
    dependning on what's in the OS buffer.  MSG_WAITALL is not available
 
1524
    on all platforms, but this should work everywhere.  This will return
 
1525
    less than the requested amount if the remote end closes.
 
1526
 
 
1527
    This isn't optimized and is intended mostly for use in testing.
 
1528
    """
 
1529
    b = ''
 
1530
    while len(b) < bytes:
 
1531
        new = socket.recv(bytes - len(b))
 
1532
        if new == '':
 
1533
            break # eof
 
1534
        b += new
 
1535
    return b
 
1536
 
 
1537
 
 
1538
def send_all(socket, bytes):
 
1539
    """Send all bytes on a socket.
 
1540
 
 
1541
    Regular socket.sendall() can give socket error 10053 on Windows.  This
 
1542
    implementation sends no more than 64k at a time, which avoids this problem.
 
1543
    """
 
1544
    chunk_size = 2**16
 
1545
    for pos in xrange(0, len(bytes), chunk_size):
 
1546
        socket.sendall(bytes[pos:pos+chunk_size])
 
1547
 
 
1548
 
 
1549
def dereference_path(path):
 
1550
    """Determine the real path to a file.
 
1551
 
 
1552
    All parent elements are dereferenced.  But the file itself is not
 
1553
    dereferenced.
 
1554
    :param path: The original path.  May be absolute or relative.
 
1555
    :return: the real path *to* the file
 
1556
    """
 
1557
    parent, base = os.path.split(path)
 
1558
    # The pathjoin for '.' is a workaround for Python bug #1213894.
 
1559
    # (initial path components aren't dereferenced)
 
1560
    return pathjoin(realpath(pathjoin('.', parent)), base)
 
1561
 
 
1562
 
 
1563
def supports_mapi():
 
1564
    """Return True if we can use MAPI to launch a mail client."""
 
1565
    return sys.platform == "win32"
 
1566
 
 
1567
 
 
1568
def resource_string(package, resource_name):
 
1569
    """Load a resource from a package and return it as a string.
 
1570
 
 
1571
    Note: Only packages that start with bzrlib are currently supported.
 
1572
 
 
1573
    This is designed to be a lightweight implementation of resource
 
1574
    loading in a way which is API compatible with the same API from
 
1575
    pkg_resources. See
 
1576
    http://peak.telecommunity.com/DevCenter/PkgResources#basic-resource-access.
 
1577
    If and when pkg_resources becomes a standard library, this routine
 
1578
    can delegate to it.
 
1579
    """
 
1580
    # Check package name is within bzrlib
 
1581
    if package == "bzrlib":
 
1582
        resource_relpath = resource_name
 
1583
    elif package.startswith("bzrlib."):
 
1584
        package = package[len("bzrlib."):].replace('.', os.sep)
 
1585
        resource_relpath = pathjoin(package, resource_name)
 
1586
    else:
 
1587
        raise errors.BzrError('resource package %s not in bzrlib' % package)
 
1588
 
 
1589
    # Map the resource to a file and read its contents
 
1590
    base = dirname(bzrlib.__file__)
 
1591
    if getattr(sys, 'frozen', None):    # bzr.exe
 
1592
        base = abspath(pathjoin(base, '..', '..'))
 
1593
    filename = pathjoin(base, resource_relpath)
 
1594
    return open(filename, 'rU').read()
 
1595
 
 
1596
 
 
1597
def file_kind_from_stat_mode_thunk(mode):
 
1598
    global file_kind_from_stat_mode
 
1599
    if file_kind_from_stat_mode is file_kind_from_stat_mode_thunk:
 
1600
        try:
 
1601
            from bzrlib._readdir_pyx import UTF8DirReader
 
1602
            file_kind_from_stat_mode = UTF8DirReader().kind_from_mode
 
1603
        except ImportError:
 
1604
            from bzrlib._readdir_py import (
 
1605
                _kind_from_mode as file_kind_from_stat_mode
 
1606
                )
 
1607
    return file_kind_from_stat_mode(mode)
 
1608
file_kind_from_stat_mode = file_kind_from_stat_mode_thunk
 
1609
 
 
1610
 
 
1611
def file_kind(f, _lstat=os.lstat):
 
1612
    try:
 
1613
        return file_kind_from_stat_mode(_lstat(f).st_mode)
 
1614
    except OSError, e:
 
1615
        if getattr(e, 'errno', None) in (errno.ENOENT, errno.ENOTDIR):
 
1616
            raise errors.NoSuchFile(f)
 
1617
        raise
 
1618
 
 
1619