~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

  • Committer: Aaron Bentley
  • Date: 2005-09-13 02:42:07 UTC
  • mto: (1185.1.16)
  • mto: This revision was merged to the branch mainline in revision 1390.
  • Revision ID: aaron.bentley@utoronto.ca-20050913024207-489d573af4b76c4d
Fixed issues with pull not having a default location after branch

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
2
 
#
 
1
# Bazaar-NG -- distributed version control
 
2
 
 
3
# Copyright (C) 2005 by Canonical Ltd
 
4
 
3
5
# This program is free software; you can redistribute it and/or modify
4
6
# it under the terms of the GNU General Public License as published by
5
7
# the Free Software Foundation; either version 2 of the License, or
6
8
# (at your option) any later version.
7
 
#
 
9
 
8
10
# This program is distributed in the hope that it will be useful,
9
11
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
13
# GNU General Public License for more details.
12
 
#
 
14
 
13
15
# You should have received a copy of the GNU General Public License
14
16
# along with this program; if not, write to the Free Software
15
17
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
18
 
17
 
from cStringIO import StringIO
18
 
import os
19
 
import re
20
 
import stat
21
 
from stat import (S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE,
22
 
                  S_ISCHR, S_ISBLK, S_ISFIFO, S_ISSOCK)
23
 
import sys
24
 
import time
25
 
 
26
 
from bzrlib.lazy_import import lazy_import
27
 
lazy_import(globals(), """
28
 
import codecs
29
 
from datetime import datetime
30
 
import errno
31
 
from ntpath import (abspath as _nt_abspath,
32
 
                    join as _nt_join,
33
 
                    normpath as _nt_normpath,
34
 
                    realpath as _nt_realpath,
35
 
                    splitdrive as _nt_splitdrive,
36
 
                    )
37
 
import posixpath
38
 
import sha
39
 
import shutil
40
 
from shutil import (
41
 
    rmtree,
42
 
    )
43
 
import tempfile
44
 
from tempfile import (
45
 
    mkdtemp,
46
 
    )
47
 
import unicodedata
48
 
 
49
 
from bzrlib import (
50
 
    cache_utf8,
51
 
    errors,
52
 
    win32utils,
53
 
    )
54
 
""")
55
 
 
 
19
import os, types, re, time, errno, sys
 
20
from stat import S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE
 
21
 
 
22
from bzrlib.errors import BzrError
 
23
from bzrlib.trace import mutter
56
24
import bzrlib
57
 
from bzrlib import symbol_versioning
58
 
from bzrlib.symbol_versioning import (
59
 
    deprecated_function,
60
 
    zero_nine,
61
 
    )
62
 
from bzrlib.trace import mutter
63
 
 
64
 
 
65
 
# On win32, O_BINARY is used to indicate the file should
66
 
# be opened in binary mode, rather than text mode.
67
 
# On other platforms, O_BINARY doesn't exist, because
68
 
# they always open in binary mode, so it is okay to
69
 
# OR with 0 on those platforms
70
 
O_BINARY = getattr(os, 'O_BINARY', 0)
71
 
 
72
25
 
73
26
def make_readonly(filename):
74
27
    """Make a filename read-only."""
 
28
    # TODO: probably needs to be fixed for windows
75
29
    mod = os.stat(filename).st_mode
76
30
    mod = mod & 0777555
77
31
    os.chmod(filename, mod)
93
47
    Windows."""
94
48
    # TODO: I'm not really sure this is the best format either.x
95
49
    global _QUOTE_RE
96
 
    if _QUOTE_RE is None:
97
 
        _QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/\\_~-])')
 
50
    if _QUOTE_RE == None:
 
51
        _QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/_~-])')
98
52
        
99
53
    if _QUOTE_RE.search(f):
100
54
        return '"' + f + '"'
102
56
        return f
103
57
 
104
58
 
105
 
_directory_kind = 'directory'
106
 
 
107
 
_formats = {
108
 
    stat.S_IFDIR:_directory_kind,
109
 
    stat.S_IFCHR:'chardev',
110
 
    stat.S_IFBLK:'block',
111
 
    stat.S_IFREG:'file',
112
 
    stat.S_IFIFO:'fifo',
113
 
    stat.S_IFLNK:'symlink',
114
 
    stat.S_IFSOCK:'socket',
115
 
}
116
 
 
117
 
 
118
 
def file_kind_from_stat_mode(stat_mode, _formats=_formats, _unknown='unknown'):
119
 
    """Generate a file kind from a stat mode. This is used in walkdirs.
120
 
 
121
 
    Its performance is critical: Do not mutate without careful benchmarking.
122
 
    """
123
 
    try:
124
 
        return _formats[stat_mode & 0170000]
125
 
    except KeyError:
126
 
        return _unknown
127
 
 
128
 
 
129
 
def file_kind(f, _lstat=os.lstat, _mapper=file_kind_from_stat_mode):
130
 
    try:
131
 
        return _mapper(_lstat(f).st_mode)
132
 
    except OSError, e:
133
 
        if getattr(e, 'errno', None) == errno.ENOENT:
134
 
            raise errors.NoSuchFile(f)
135
 
        raise
136
 
 
137
 
 
138
 
def get_umask():
139
 
    """Return the current umask"""
140
 
    # Assume that people aren't messing with the umask while running
141
 
    # XXX: This is not thread safe, but there is no way to get the
142
 
    #      umask without setting it
143
 
    umask = os.umask(0)
144
 
    os.umask(umask)
145
 
    return umask
146
 
 
147
 
 
148
 
_kind_marker_map = {
149
 
    "file": "",
150
 
    _directory_kind: "/",
151
 
    "symlink": "@",
152
 
    'tree-reference': '+',
153
 
}
 
59
def file_kind(f):
 
60
    mode = os.lstat(f)[ST_MODE]
 
61
    if S_ISREG(mode):
 
62
        return 'file'
 
63
    elif S_ISDIR(mode):
 
64
        return 'directory'
 
65
    elif S_ISLNK(mode):
 
66
        return 'symlink'
 
67
    else:
 
68
        raise BzrError("can't handle file kind with mode %o of %r" % (mode, f))
154
69
 
155
70
 
156
71
def kind_marker(kind):
157
 
    try:
158
 
        return _kind_marker_map[kind]
159
 
    except KeyError:
160
 
        raise errors.BzrError('invalid file kind %r' % kind)
161
 
 
162
 
 
163
 
lexists = getattr(os.path, 'lexists', None)
164
 
if lexists is None:
165
 
    def lexists(f):
166
 
        try:
167
 
            stat = getattr(os, 'lstat', os.stat)
168
 
            stat(f)
169
 
            return True
170
 
        except OSError, e:
171
 
            if e.errno == errno.ENOENT:
172
 
                return False;
173
 
            else:
174
 
                raise errors.BzrError("lstat/stat of (%r): %r" % (f, e))
175
 
 
176
 
 
177
 
def fancy_rename(old, new, rename_func, unlink_func):
178
 
    """A fancy rename, when you don't have atomic rename.
179
 
    
180
 
    :param old: The old path, to rename from
181
 
    :param new: The new path, to rename to
182
 
    :param rename_func: The potentially non-atomic rename function
183
 
    :param unlink_func: A way to delete the target file if the full rename succeeds
184
 
    """
185
 
 
186
 
    # sftp rename doesn't allow overwriting, so play tricks:
187
 
    import random
188
 
    base = os.path.basename(new)
189
 
    dirname = os.path.dirname(new)
190
 
    tmp_name = u'tmp.%s.%.9f.%d.%s' % (base, time.time(), os.getpid(), rand_chars(10))
191
 
    tmp_name = pathjoin(dirname, tmp_name)
192
 
 
193
 
    # Rename the file out of the way, but keep track if it didn't exist
194
 
    # We don't want to grab just any exception
195
 
    # something like EACCES should prevent us from continuing
196
 
    # The downside is that the rename_func has to throw an exception
197
 
    # with an errno = ENOENT, or NoSuchFile
198
 
    file_existed = False
199
 
    try:
200
 
        rename_func(new, tmp_name)
201
 
    except (errors.NoSuchFile,), e:
202
 
        pass
203
 
    except IOError, e:
204
 
        # RBC 20060103 abstraction leakage: the paramiko SFTP clients rename
205
 
        # function raises an IOError with errno is None when a rename fails.
206
 
        # This then gets caught here.
207
 
        if e.errno not in (None, errno.ENOENT, errno.ENOTDIR):
208
 
            raise
209
 
    except Exception, e:
210
 
        if (getattr(e, 'errno', None) is None
211
 
            or e.errno not in (errno.ENOENT, errno.ENOTDIR)):
212
 
            raise
213
 
    else:
214
 
        file_existed = True
215
 
 
216
 
    success = False
217
 
    try:
218
 
        # This may throw an exception, in which case success will
219
 
        # not be set.
220
 
        rename_func(old, new)
221
 
        success = True
222
 
    finally:
223
 
        if file_existed:
224
 
            # If the file used to exist, rename it back into place
225
 
            # otherwise just delete it from the tmp location
226
 
            if success:
227
 
                unlink_func(tmp_name)
228
 
            else:
229
 
                rename_func(tmp_name, new)
230
 
 
231
 
 
232
 
# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
233
 
# choke on a Unicode string containing a relative path if
234
 
# os.getcwd() returns a non-sys.getdefaultencoding()-encoded
235
 
# string.
236
 
_fs_enc = sys.getfilesystemencoding() or 'utf-8'
237
 
def _posix_abspath(path):
238
 
    # jam 20060426 rather than encoding to fsencoding
239
 
    # copy posixpath.abspath, but use os.getcwdu instead
240
 
    if not posixpath.isabs(path):
241
 
        path = posixpath.join(getcwd(), path)
242
 
    return posixpath.normpath(path)
243
 
 
244
 
 
245
 
def _posix_realpath(path):
246
 
    return posixpath.realpath(path.encode(_fs_enc)).decode(_fs_enc)
247
 
 
248
 
 
249
 
def _win32_fixdrive(path):
250
 
    """Force drive letters to be consistent.
251
 
 
252
 
    win32 is inconsistent whether it returns lower or upper case
253
 
    and even if it was consistent the user might type the other
254
 
    so we force it to uppercase
255
 
    running python.exe under cmd.exe return capital C:\\
256
 
    running win32 python inside a cygwin shell returns lowercase c:\\
257
 
    """
258
 
    drive, path = _nt_splitdrive(path)
259
 
    return drive.upper() + path
260
 
 
261
 
 
262
 
def _win32_abspath(path):
263
 
    # Real _nt_abspath doesn't have a problem with a unicode cwd
264
 
    return _win32_fixdrive(_nt_abspath(unicode(path)).replace('\\', '/'))
265
 
 
266
 
 
267
 
def _win98_abspath(path):
268
 
    """Return the absolute version of a path.
269
 
    Windows 98 safe implementation (python reimplementation
270
 
    of Win32 API function GetFullPathNameW)
271
 
    """
272
 
    # Corner cases:
273
 
    #   C:\path     => C:/path
274
 
    #   C:/path     => C:/path
275
 
    #   \\HOST\path => //HOST/path
276
 
    #   //HOST/path => //HOST/path
277
 
    #   path        => C:/cwd/path
278
 
    #   /path       => C:/path
279
 
    path = unicode(path)
280
 
    # check for absolute path
281
 
    drive = _nt_splitdrive(path)[0]
282
 
    if drive == '' and path[:2] not in('//','\\\\'):
283
 
        cwd = os.getcwdu()
284
 
        # we cannot simply os.path.join cwd and path
285
 
        # because os.path.join('C:','/path') produce '/path'
286
 
        # and this is incorrect
287
 
        if path[:1] in ('/','\\'):
288
 
            cwd = _nt_splitdrive(cwd)[0]
289
 
            path = path[1:]
290
 
        path = cwd + '\\' + path
291
 
    return _win32_fixdrive(_nt_normpath(path).replace('\\', '/'))
292
 
 
293
 
if win32utils.winver == 'Windows 98':
294
 
    _win32_abspath = _win98_abspath
295
 
 
296
 
 
297
 
def _win32_realpath(path):
298
 
    # Real _nt_realpath doesn't have a problem with a unicode cwd
299
 
    return _win32_fixdrive(_nt_realpath(unicode(path)).replace('\\', '/'))
300
 
 
301
 
 
302
 
def _win32_pathjoin(*args):
303
 
    return _nt_join(*args).replace('\\', '/')
304
 
 
305
 
 
306
 
def _win32_normpath(path):
307
 
    return _win32_fixdrive(_nt_normpath(unicode(path)).replace('\\', '/'))
308
 
 
309
 
 
310
 
def _win32_getcwd():
311
 
    return _win32_fixdrive(os.getcwdu().replace('\\', '/'))
312
 
 
313
 
 
314
 
def _win32_mkdtemp(*args, **kwargs):
315
 
    return _win32_fixdrive(tempfile.mkdtemp(*args, **kwargs).replace('\\', '/'))
316
 
 
317
 
 
318
 
def _win32_rename(old, new):
319
 
    """We expect to be able to atomically replace 'new' with old.
320
 
 
321
 
    On win32, if new exists, it must be moved out of the way first,
322
 
    and then deleted. 
323
 
    """
324
 
    try:
325
 
        fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
326
 
    except OSError, e:
327
 
        if e.errno in (errno.EPERM, errno.EACCES, errno.EBUSY, errno.EINVAL):
328
 
            # If we try to rename a non-existant file onto cwd, we get 
329
 
            # EPERM or EACCES instead of ENOENT, this will raise ENOENT 
330
 
            # if the old path doesn't exist, sometimes we get EACCES
331
 
            # On Linux, we seem to get EBUSY, on Mac we get EINVAL
332
 
            os.lstat(old)
333
 
        raise
334
 
 
335
 
 
336
 
def _mac_getcwd():
337
 
    return unicodedata.normalize('NFKC', os.getcwdu())
338
 
 
339
 
 
340
 
# Default is to just use the python builtins, but these can be rebound on
341
 
# particular platforms.
342
 
abspath = _posix_abspath
343
 
realpath = _posix_realpath
344
 
pathjoin = os.path.join
345
 
normpath = os.path.normpath
346
 
getcwd = os.getcwdu
347
 
rename = os.rename
348
 
dirname = os.path.dirname
349
 
basename = os.path.basename
350
 
split = os.path.split
351
 
splitext = os.path.splitext
352
 
# These were already imported into local scope
353
 
# mkdtemp = tempfile.mkdtemp
354
 
# rmtree = shutil.rmtree
355
 
 
356
 
MIN_ABS_PATHLENGTH = 1
357
 
 
358
 
 
359
 
if sys.platform == 'win32':
360
 
    abspath = _win32_abspath
361
 
    realpath = _win32_realpath
362
 
    pathjoin = _win32_pathjoin
363
 
    normpath = _win32_normpath
364
 
    getcwd = _win32_getcwd
365
 
    mkdtemp = _win32_mkdtemp
366
 
    rename = _win32_rename
367
 
 
368
 
    MIN_ABS_PATHLENGTH = 3
369
 
 
370
 
    def _win32_delete_readonly(function, path, excinfo):
371
 
        """Error handler for shutil.rmtree function [for win32]
372
 
        Helps to remove files and dirs marked as read-only.
373
 
        """
374
 
        exception = excinfo[1]
375
 
        if function in (os.remove, os.rmdir) \
376
 
            and isinstance(exception, OSError) \
377
 
            and exception.errno == errno.EACCES:
378
 
            make_writable(path)
379
 
            function(path)
380
 
        else:
381
 
            raise
382
 
 
383
 
    def rmtree(path, ignore_errors=False, onerror=_win32_delete_readonly):
384
 
        """Replacer for shutil.rmtree: could remove readonly dirs/files"""
385
 
        return shutil.rmtree(path, ignore_errors, onerror)
386
 
elif sys.platform == 'darwin':
387
 
    getcwd = _mac_getcwd
388
 
 
389
 
 
390
 
def get_terminal_encoding():
391
 
    """Find the best encoding for printing to the screen.
392
 
 
393
 
    This attempts to check both sys.stdout and sys.stdin to see
394
 
    what encoding they are in, and if that fails it falls back to
395
 
    bzrlib.user_encoding.
396
 
    The problem is that on Windows, locale.getpreferredencoding()
397
 
    is not the same encoding as that used by the console:
398
 
    http://mail.python.org/pipermail/python-list/2003-May/162357.html
399
 
 
400
 
    On my standard US Windows XP, the preferred encoding is
401
 
    cp1252, but the console is cp437
402
 
    """
403
 
    output_encoding = getattr(sys.stdout, 'encoding', None)
404
 
    if not output_encoding:
405
 
        input_encoding = getattr(sys.stdin, 'encoding', None)
406
 
        if not input_encoding:
407
 
            output_encoding = bzrlib.user_encoding
408
 
            mutter('encoding stdout as bzrlib.user_encoding %r', output_encoding)
409
 
        else:
410
 
            output_encoding = input_encoding
411
 
            mutter('encoding stdout as sys.stdin encoding %r', output_encoding)
412
 
    else:
413
 
        mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
414
 
    if output_encoding == 'cp0':
415
 
        # invalid encoding (cp0 means 'no codepage' on Windows)
416
 
        output_encoding = bzrlib.user_encoding
417
 
        mutter('cp0 is invalid encoding.'
418
 
               ' encoding stdout as bzrlib.user_encoding %r', output_encoding)
419
 
    # check encoding
420
 
    try:
421
 
        codecs.lookup(output_encoding)
422
 
    except LookupError:
423
 
        sys.stderr.write('bzr: warning:'
424
 
                         ' unknown terminal encoding %s.\n'
425
 
                         '  Using encoding %s instead.\n'
426
 
                         % (output_encoding, bzrlib.user_encoding)
427
 
                        )
428
 
        output_encoding = bzrlib.user_encoding
429
 
 
430
 
    return output_encoding
431
 
 
432
 
 
433
 
def normalizepath(f):
434
 
    if getattr(os.path, 'realpath', None) is not None:
435
 
        F = realpath
436
 
    else:
437
 
        F = abspath
438
 
    [p,e] = os.path.split(f)
439
 
    if e == "" or e == "." or e == "..":
440
 
        return F(f)
441
 
    else:
442
 
        return pathjoin(F(p), e)
 
72
    if kind == 'file':
 
73
        return ''
 
74
    elif kind == 'directory':
 
75
        return '/'
 
76
    elif kind == 'symlink':
 
77
        return '@'
 
78
    else:
 
79
        raise BzrError('invalid file kind %r' % kind)
 
80
 
443
81
 
444
82
 
445
83
def backup_file(fn):
449
87
 
450
88
    If the file is already a backup, it's not copied.
451
89
    """
 
90
    import os
452
91
    if fn[-1] == '~':
453
92
        return
454
93
    bfn = fn + '~'
455
94
 
456
 
    if has_symlinks() and os.path.islink(fn):
457
 
        target = os.readlink(fn)
458
 
        os.symlink(target, bfn)
459
 
        return
460
95
    inf = file(fn, 'rb')
461
96
    try:
462
97
        content = inf.read()
469
104
    finally:
470
105
        outf.close()
471
106
 
 
107
def rename(path_from, path_to):
 
108
    """Basically the same as os.rename() just special for win32"""
 
109
    if sys.platform == 'win32':
 
110
        try:
 
111
            os.remove(path_to)
 
112
        except OSError, e:
 
113
            if e.errno != e.ENOENT:
 
114
                raise
 
115
    os.rename(path_from, path_to)
 
116
 
 
117
 
 
118
 
 
119
 
472
120
 
473
121
def isdir(f):
474
122
    """True if f is an accessible directory."""
478
126
        return False
479
127
 
480
128
 
 
129
 
481
130
def isfile(f):
482
131
    """True if f is a regular file."""
483
132
    try:
485
134
    except OSError:
486
135
        return False
487
136
 
488
 
def islink(f):
489
 
    """True if f is a symlink."""
490
 
    try:
491
 
        return S_ISLNK(os.lstat(f)[ST_MODE])
492
 
    except OSError:
493
 
        return False
494
137
 
495
138
def is_inside(dir, fname):
496
139
    """True if fname is inside dir.
497
140
    
498
 
    The parameters should typically be passed to osutils.normpath first, so
 
141
    The parameters should typically be passed to os.path.normpath first, so
499
142
    that . and .. and repeated slashes are eliminated, and the separators
500
143
    are canonical for the platform.
501
144
    
502
145
    The empty string as a dir name is taken as top-of-tree and matches 
503
146
    everything.
 
147
    
 
148
    >>> is_inside('src', 'src/foo.c')
 
149
    True
 
150
    >>> is_inside('src', 'srccontrol')
 
151
    False
 
152
    >>> is_inside('src', 'src/a/a/a/foo.c')
 
153
    True
 
154
    >>> is_inside('foo.c', 'foo.c')
 
155
    True
 
156
    >>> is_inside('foo.c', '')
 
157
    False
 
158
    >>> is_inside('', 'foo.c')
 
159
    True
504
160
    """
505
161
    # XXX: Most callers of this can actually do something smarter by 
506
162
    # looking at the inventory
509
165
    
510
166
    if dir == '':
511
167
        return True
512
 
 
513
 
    if dir[-1] != '/':
514
 
        dir += '/'
515
 
 
 
168
    
 
169
    if dir[-1] != os.sep:
 
170
        dir += os.sep
 
171
    
516
172
    return fname.startswith(dir)
517
173
 
518
174
 
521
177
    for dirname in dir_list:
522
178
        if is_inside(dirname, fname):
523
179
            return True
524
 
    return False
525
 
 
526
 
 
527
 
def is_inside_or_parent_of_any(dir_list, fname):
528
 
    """True if fname is a child or a parent of any of the given files."""
529
 
    for dirname in dir_list:
530
 
        if is_inside(dirname, fname) or is_inside(fname, dirname):
531
 
            return True
532
 
    return False
 
180
    else:
 
181
        return False
533
182
 
534
183
 
535
184
def pumpfile(fromfile, tofile):
536
185
    """Copy contents of one file to another."""
537
 
    BUFSIZE = 32768
538
 
    while True:
539
 
        b = fromfile.read(BUFSIZE)
540
 
        if not b:
541
 
            break
542
 
        tofile.write(b)
543
 
 
544
 
 
545
 
def file_iterator(input_file, readsize=32768):
546
 
    while True:
547
 
        b = input_file.read(readsize)
548
 
        if len(b) == 0:
549
 
            break
550
 
        yield b
 
186
    tofile.write(fromfile.read())
 
187
 
 
188
 
 
189
def uuid():
 
190
    """Return a new UUID"""
 
191
    try:
 
192
        return file('/proc/sys/kernel/random/uuid').readline().rstrip('\n')
 
193
    except IOError:
 
194
        return chomp(os.popen('uuidgen').readline())
551
195
 
552
196
 
553
197
def sha_file(f):
554
 
    if getattr(f, 'tell', None) is not None:
 
198
    import sha
 
199
    if hasattr(f, 'tell'):
555
200
        assert f.tell() == 0
556
201
    s = sha.new()
557
202
    BUFSIZE = 128<<10
563
208
    return s.hexdigest()
564
209
 
565
210
 
566
 
 
567
 
def sha_strings(strings):
568
 
    """Return the sha-1 of concatenation of strings"""
569
 
    s = sha.new()
570
 
    map(s.update, strings)
571
 
    return s.hexdigest()
572
 
 
573
 
 
574
211
def sha_string(f):
 
212
    import sha
575
213
    s = sha.new()
576
214
    s.update(f)
577
215
    return s.hexdigest()
578
216
 
579
217
 
 
218
 
580
219
def fingerprint_file(f):
 
220
    import sha
581
221
    s = sha.new()
582
222
    b = f.read()
583
223
    s.update(b)
586
226
            'sha1': s.hexdigest()}
587
227
 
588
228
 
 
229
def config_dir():
 
230
    """Return per-user configuration directory.
 
231
 
 
232
    By default this is ~/.bzr.conf/
 
233
    
 
234
    TODO: Global option --config-dir to override this.
 
235
    """
 
236
    return os.path.expanduser("~/.bzr.conf")
 
237
 
 
238
 
 
239
def _auto_user_id():
 
240
    """Calculate automatic user identification.
 
241
 
 
242
    Returns (realname, email).
 
243
 
 
244
    Only used when none is set in the environment or the id file.
 
245
 
 
246
    This previously used the FQDN as the default domain, but that can
 
247
    be very slow on machines where DNS is broken.  So now we simply
 
248
    use the hostname.
 
249
    """
 
250
    import socket
 
251
 
 
252
    # XXX: Any good way to get real user name on win32?
 
253
 
 
254
    try:
 
255
        import pwd
 
256
        uid = os.getuid()
 
257
        w = pwd.getpwuid(uid)
 
258
        gecos = w.pw_gecos.decode(bzrlib.user_encoding)
 
259
        username = w.pw_name.decode(bzrlib.user_encoding)
 
260
        comma = gecos.find(',')
 
261
        if comma == -1:
 
262
            realname = gecos
 
263
        else:
 
264
            realname = gecos[:comma]
 
265
        if not realname:
 
266
            realname = username
 
267
 
 
268
    except ImportError:
 
269
        import getpass
 
270
        realname = username = getpass.getuser().decode(bzrlib.user_encoding)
 
271
 
 
272
    return realname, (username + '@' + socket.gethostname())
 
273
 
 
274
 
 
275
def _get_user_id(branch):
 
276
    """Return the full user id from a file or environment variable.
 
277
 
 
278
    e.g. "John Hacker <jhacker@foo.org>"
 
279
 
 
280
    branch
 
281
        A branch to use for a per-branch configuration, or None.
 
282
 
 
283
    The following are searched in order:
 
284
 
 
285
    1. $BZREMAIL
 
286
    2. .bzr/email for this branch.
 
287
    3. ~/.bzr.conf/email
 
288
    4. $EMAIL
 
289
    """
 
290
    v = os.environ.get('BZREMAIL')
 
291
    if v:
 
292
        return v.decode(bzrlib.user_encoding)
 
293
 
 
294
    if branch:
 
295
        try:
 
296
            return (branch.controlfile("email", "r") 
 
297
                    .read()
 
298
                    .decode(bzrlib.user_encoding)
 
299
                    .rstrip("\r\n"))
 
300
        except IOError, e:
 
301
            if e.errno != errno.ENOENT:
 
302
                raise
 
303
        except BzrError, e:
 
304
            pass
 
305
    
 
306
    try:
 
307
        return (open(os.path.join(config_dir(), "email"))
 
308
                .read()
 
309
                .decode(bzrlib.user_encoding)
 
310
                .rstrip("\r\n"))
 
311
    except IOError, e:
 
312
        if e.errno != errno.ENOENT:
 
313
            raise e
 
314
 
 
315
    v = os.environ.get('EMAIL')
 
316
    if v:
 
317
        return v.decode(bzrlib.user_encoding)
 
318
    else:    
 
319
        return None
 
320
 
 
321
 
 
322
def username(branch):
 
323
    """Return email-style username.
 
324
 
 
325
    Something similar to 'Martin Pool <mbp@sourcefrog.net>'
 
326
 
 
327
    TODO: Check it's reasonably well-formed.
 
328
    """
 
329
    v = _get_user_id(branch)
 
330
    if v:
 
331
        return v
 
332
    
 
333
    name, email = _auto_user_id()
 
334
    if name:
 
335
        return '%s <%s>' % (name, email)
 
336
    else:
 
337
        return email
 
338
 
 
339
 
 
340
def user_email(branch):
 
341
    """Return just the email component of a username."""
 
342
    e = _get_user_id(branch)
 
343
    if e:
 
344
        m = re.search(r'[\w+.-]+@[\w+.-]+', e)
 
345
        if not m:
 
346
            raise BzrError("%r doesn't seem to contain a reasonable email address" % e)
 
347
        return m.group(0)
 
348
 
 
349
    return _auto_user_id()[1]
 
350
    
 
351
 
 
352
 
589
353
def compare_files(a, b):
590
354
    """Returns true if equal in contents"""
591
355
    BUFSIZE = 4096
598
362
            return True
599
363
 
600
364
 
 
365
 
601
366
def local_time_offset(t=None):
602
367
    """Return offset of local zone from GMT, either at present or at time t."""
603
 
    if t is None:
 
368
    # python2.3 localtime() can't take None
 
369
    if t == None:
604
370
        t = time.time()
605
 
    offset = datetime.fromtimestamp(t) - datetime.utcfromtimestamp(t)
606
 
    return offset.days * 86400 + offset.seconds
607
 
 
608
 
    
609
 
def format_date(t, offset=0, timezone='original', date_fmt=None,
610
 
                show_offset=True):
611
 
    """Return a formatted date string.
612
 
 
613
 
    :param t: Seconds since the epoch.
614
 
    :param offset: Timezone offset in seconds east of utc.
615
 
    :param timezone: How to display the time: 'utc', 'original' for the
616
 
         timezone specified by offset, or 'local' for the process's current
617
 
         timezone.
618
 
    :param show_offset: Whether to append the timezone.
619
 
    :param date_fmt: strftime format.
620
 
    """
 
371
        
 
372
    if time.localtime(t).tm_isdst and time.daylight:
 
373
        return -time.altzone
 
374
    else:
 
375
        return -time.timezone
 
376
 
 
377
    
 
378
def format_date(t, offset=0, timezone='original'):
 
379
    ## TODO: Perhaps a global option to use either universal or local time?
 
380
    ## Or perhaps just let people set $TZ?
 
381
    assert isinstance(t, float)
 
382
    
621
383
    if timezone == 'utc':
622
384
        tt = time.gmtime(t)
623
385
        offset = 0
624
386
    elif timezone == 'original':
625
 
        if offset is None:
 
387
        if offset == None:
626
388
            offset = 0
627
389
        tt = time.gmtime(t + offset)
628
390
    elif timezone == 'local':
629
391
        tt = time.localtime(t)
630
392
        offset = local_time_offset(t)
631
393
    else:
632
 
        raise errors.BzrError("unsupported timezone format %r" % timezone,
633
 
                              ['options are "utc", "original", "local"'])
634
 
    if date_fmt is None:
635
 
        date_fmt = "%a %Y-%m-%d %H:%M:%S"
636
 
    if show_offset:
637
 
        offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
638
 
    else:
639
 
        offset_str = ''
640
 
    return (time.strftime(date_fmt, tt) +  offset_str)
 
394
        raise BzrError("unsupported timezone format %r" % timezone,
 
395
                       ['options are "utc", "original", "local"'])
 
396
 
 
397
    return (time.strftime("%a %Y-%m-%d %H:%M:%S", tt)
 
398
            + ' %+03d%02d' % (offset / 3600, (offset / 60) % 60))
641
399
 
642
400
 
643
401
def compact_date(when):
644
402
    return time.strftime('%Y%m%d%H%M%S', time.gmtime(when))
645
403
    
646
404
 
647
 
def format_delta(delta):
648
 
    """Get a nice looking string for a time delta.
649
 
 
650
 
    :param delta: The time difference in seconds, can be positive or negative.
651
 
        positive indicates time in the past, negative indicates time in the
652
 
        future. (usually time.time() - stored_time)
653
 
    :return: String formatted to show approximate resolution
654
 
    """
655
 
    delta = int(delta)
656
 
    if delta >= 0:
657
 
        direction = 'ago'
658
 
    else:
659
 
        direction = 'in the future'
660
 
        delta = -delta
661
 
 
662
 
    seconds = delta
663
 
    if seconds < 90: # print seconds up to 90 seconds
664
 
        if seconds == 1:
665
 
            return '%d second %s' % (seconds, direction,)
666
 
        else:
667
 
            return '%d seconds %s' % (seconds, direction)
668
 
 
669
 
    minutes = int(seconds / 60)
670
 
    seconds -= 60 * minutes
671
 
    if seconds == 1:
672
 
        plural_seconds = ''
673
 
    else:
674
 
        plural_seconds = 's'
675
 
    if minutes < 90: # print minutes, seconds up to 90 minutes
676
 
        if minutes == 1:
677
 
            return '%d minute, %d second%s %s' % (
678
 
                    minutes, seconds, plural_seconds, direction)
679
 
        else:
680
 
            return '%d minutes, %d second%s %s' % (
681
 
                    minutes, seconds, plural_seconds, direction)
682
 
 
683
 
    hours = int(minutes / 60)
684
 
    minutes -= 60 * hours
685
 
    if minutes == 1:
686
 
        plural_minutes = ''
687
 
    else:
688
 
        plural_minutes = 's'
689
 
 
690
 
    if hours == 1:
691
 
        return '%d hour, %d minute%s %s' % (hours, minutes,
692
 
                                            plural_minutes, direction)
693
 
    return '%d hours, %d minute%s %s' % (hours, minutes,
694
 
                                         plural_minutes, direction)
695
405
 
696
406
def filesize(f):
697
407
    """Return size of given open file."""
698
408
    return os.fstat(f.fileno())[ST_SIZE]
699
409
 
700
410
 
701
 
# Define rand_bytes based on platform.
702
 
try:
703
 
    # Python 2.4 and later have os.urandom,
704
 
    # but it doesn't work on some arches
705
 
    os.urandom(1)
 
411
if hasattr(os, 'urandom'): # python 2.4 and later
706
412
    rand_bytes = os.urandom
707
 
except (NotImplementedError, AttributeError):
708
 
    # If python doesn't have os.urandom, or it doesn't work,
709
 
    # then try to first pull random data from /dev/urandom
710
 
    try:
711
 
        rand_bytes = file('/dev/urandom', 'rb').read
712
 
    # Otherwise, use this hack as a last resort
713
 
    except (IOError, OSError):
714
 
        # not well seeded, but better than nothing
715
 
        def rand_bytes(n):
716
 
            import random
717
 
            s = ''
718
 
            while n:
719
 
                s += chr(random.randint(0, 255))
720
 
                n -= 1
721
 
            return s
722
 
 
723
 
 
724
 
ALNUM = '0123456789abcdefghijklmnopqrstuvwxyz'
725
 
def rand_chars(num):
726
 
    """Return a random string of num alphanumeric characters
727
 
    
728
 
    The result only contains lowercase chars because it may be used on 
729
 
    case-insensitive filesystems.
730
 
    """
731
 
    s = ''
732
 
    for raw_byte in rand_bytes(num):
733
 
        s += ALNUM[ord(raw_byte) % 36]
734
 
    return s
 
413
elif sys.platform == 'linux2':
 
414
    rand_bytes = file('/dev/urandom', 'rb').read
 
415
else:
 
416
    # not well seeded, but better than nothing
 
417
    def rand_bytes(n):
 
418
        import random
 
419
        s = ''
 
420
        while n:
 
421
            s += chr(random.randint(0, 255))
 
422
            n -= 1
 
423
        return s
735
424
 
736
425
 
737
426
## TODO: We could later have path objects that remember their list
738
427
## decomposition (might be too tricksy though.)
739
428
 
740
429
def splitpath(p):
741
 
    """Turn string into list of parts."""
742
 
    assert isinstance(p, basestring)
 
430
    """Turn string into list of parts.
 
431
 
 
432
    >>> splitpath('a')
 
433
    ['a']
 
434
    >>> splitpath('a/b')
 
435
    ['a', 'b']
 
436
    >>> splitpath('a/./b')
 
437
    ['a', 'b']
 
438
    >>> splitpath('a/.b')
 
439
    ['a', '.b']
 
440
    >>> splitpath('a/../b')
 
441
    Traceback (most recent call last):
 
442
    ...
 
443
    BzrError: sorry, '..' not allowed in path
 
444
    """
 
445
    assert isinstance(p, types.StringTypes)
743
446
 
744
447
    # split on either delimiter because people might use either on
745
448
    # Windows
748
451
    rps = []
749
452
    for f in ps:
750
453
        if f == '..':
751
 
            raise errors.BzrError("sorry, %r not allowed in path" % f)
 
454
            raise BzrError("sorry, %r not allowed in path" % f)
752
455
        elif (f == '.') or (f == ''):
753
456
            pass
754
457
        else:
756
459
    return rps
757
460
 
758
461
def joinpath(p):
759
 
    assert isinstance(p, (list, tuple))
 
462
    assert isinstance(p, list)
760
463
    for f in p:
761
 
        if (f == '..') or (f is None) or (f == ''):
762
 
            raise errors.BzrError("sorry, %r not allowed in path" % f)
763
 
    return pathjoin(*p)
764
 
 
765
 
 
766
 
@deprecated_function(zero_nine)
 
464
        if (f == '..') or (f == None) or (f == ''):
 
465
            raise BzrError("sorry, %r not allowed in path" % f)
 
466
    return os.path.join(*p)
 
467
 
 
468
 
767
469
def appendpath(p1, p2):
768
470
    if p1 == '':
769
471
        return p2
770
472
    else:
771
 
        return pathjoin(p1, p2)
772
 
    
773
 
 
774
 
def split_lines(s):
775
 
    """Split s into lines, but without removing the newline characters."""
776
 
    lines = s.split('\n')
777
 
    result = [line + '\n' for line in lines[:-1]]
778
 
    if lines[-1]:
779
 
        result.append(lines[-1])
780
 
    return result
781
 
 
782
 
 
783
 
def hardlinks_good():
784
 
    return sys.platform not in ('win32', 'cygwin', 'darwin')
785
 
 
786
 
 
787
 
def link_or_copy(src, dest):
788
 
    """Hardlink a file, or copy it if it can't be hardlinked."""
789
 
    if not hardlinks_good():
790
 
        shutil.copyfile(src, dest)
791
 
        return
792
 
    try:
793
 
        os.link(src, dest)
794
 
    except (OSError, IOError), e:
795
 
        if e.errno != errno.EXDEV:
796
 
            raise
797
 
        shutil.copyfile(src, dest)
798
 
 
799
 
def delete_any(full_path):
800
 
    """Delete a file or directory."""
801
 
    try:
802
 
        os.unlink(full_path)
803
 
    except OSError, e:
804
 
    # We may be renaming a dangling inventory id
805
 
        if e.errno not in (errno.EISDIR, errno.EACCES, errno.EPERM):
806
 
            raise
807
 
        os.rmdir(full_path)
808
 
 
809
 
 
810
 
def has_symlinks():
811
 
    if getattr(os, 'symlink', None) is not None:
812
 
        return True
813
 
    else:
814
 
        return False
815
 
        
816
 
 
817
 
def contains_whitespace(s):
818
 
    """True if there are any whitespace characters in s."""
819
 
    # string.whitespace can include '\xa0' in certain locales, because it is
820
 
    # considered "non-breaking-space" as part of ISO-8859-1. But it
821
 
    # 1) Isn't a breaking whitespace
822
 
    # 2) Isn't one of ' \t\r\n' which are characters we sometimes use as
823
 
    #    separators
824
 
    # 3) '\xa0' isn't unicode safe since it is >128.
825
 
 
826
 
    # This should *not* be a unicode set of characters in case the source
827
 
    # string is not a Unicode string. We can auto-up-cast the characters since
828
 
    # they are ascii, but we don't want to auto-up-cast the string in case it
829
 
    # is utf-8
830
 
    for ch in ' \t\n\r\v\f':
831
 
        if ch in s:
832
 
            return True
833
 
    else:
834
 
        return False
835
 
 
836
 
 
837
 
def contains_linebreaks(s):
838
 
    """True if there is any vertical whitespace in s."""
839
 
    for ch in '\f\n\r':
840
 
        if ch in s:
841
 
            return True
842
 
    else:
843
 
        return False
844
 
 
845
 
 
846
 
def relpath(base, path):
847
 
    """Return path relative to base, or raise exception.
848
 
 
849
 
    The path may be either an absolute path or a path relative to the
850
 
    current working directory.
851
 
 
852
 
    os.path.commonprefix (python2.4) has a bad bug that it works just
853
 
    on string prefixes, assuming that '/u' is a prefix of '/u2'.  This
854
 
    avoids that problem.
855
 
    """
856
 
 
857
 
    assert len(base) >= MIN_ABS_PATHLENGTH, ('Length of base must be equal or'
858
 
        ' exceed the platform minimum length (which is %d)' % 
859
 
        MIN_ABS_PATHLENGTH)
860
 
 
861
 
    rp = abspath(path)
862
 
 
863
 
    s = []
864
 
    head = rp
865
 
    while len(head) >= len(base):
866
 
        if head == base:
867
 
            break
868
 
        head, tail = os.path.split(head)
869
 
        if tail:
870
 
            s.insert(0, tail)
871
 
    else:
872
 
        raise errors.PathNotChild(rp, base)
873
 
 
874
 
    if s:
875
 
        return pathjoin(*s)
876
 
    else:
877
 
        return ''
878
 
 
879
 
 
880
 
def safe_unicode(unicode_or_utf8_string):
881
 
    """Coerce unicode_or_utf8_string into unicode.
882
 
 
883
 
    If it is unicode, it is returned.
884
 
    Otherwise it is decoded from utf-8. If a decoding error
885
 
    occurs, it is wrapped as a If the decoding fails, the exception is wrapped 
886
 
    as a BzrBadParameter exception.
887
 
    """
888
 
    if isinstance(unicode_or_utf8_string, unicode):
889
 
        return unicode_or_utf8_string
890
 
    try:
891
 
        return unicode_or_utf8_string.decode('utf8')
892
 
    except UnicodeDecodeError:
893
 
        raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
894
 
 
895
 
 
896
 
def safe_utf8(unicode_or_utf8_string):
897
 
    """Coerce unicode_or_utf8_string to a utf8 string.
898
 
 
899
 
    If it is a str, it is returned.
900
 
    If it is Unicode, it is encoded into a utf-8 string.
901
 
    """
902
 
    if isinstance(unicode_or_utf8_string, str):
903
 
        # TODO: jam 20070209 This is overkill, and probably has an impact on
904
 
        #       performance if we are dealing with lots of apis that want a
905
 
        #       utf-8 revision id
906
 
        try:
907
 
            # Make sure it is a valid utf-8 string
908
 
            unicode_or_utf8_string.decode('utf-8')
909
 
        except UnicodeDecodeError:
910
 
            raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
911
 
        return unicode_or_utf8_string
912
 
    return unicode_or_utf8_string.encode('utf-8')
913
 
 
914
 
 
915
 
_revision_id_warning = ('Unicode revision ids were deprecated in bzr 0.15.'
916
 
                        ' Revision id generators should be creating utf8'
917
 
                        ' revision ids.')
918
 
 
919
 
 
920
 
def safe_revision_id(unicode_or_utf8_string, warn=True):
921
 
    """Revision ids should now be utf8, but at one point they were unicode.
922
 
 
923
 
    :param unicode_or_utf8_string: A possibly Unicode revision_id. (can also be
924
 
        utf8 or None).
925
 
    :param warn: Functions that are sanitizing user data can set warn=False
926
 
    :return: None or a utf8 revision id.
927
 
    """
928
 
    if (unicode_or_utf8_string is None
929
 
        or unicode_or_utf8_string.__class__ == str):
930
 
        return unicode_or_utf8_string
931
 
    if warn:
932
 
        symbol_versioning.warn(_revision_id_warning, DeprecationWarning,
933
 
                               stacklevel=2)
934
 
    return cache_utf8.encode(unicode_or_utf8_string)
935
 
 
936
 
 
937
 
_file_id_warning = ('Unicode file ids were deprecated in bzr 0.15. File id'
938
 
                    ' generators should be creating utf8 file ids.')
939
 
 
940
 
 
941
 
def safe_file_id(unicode_or_utf8_string, warn=True):
942
 
    """File ids should now be utf8, but at one point they were unicode.
943
 
 
944
 
    This is the same as safe_utf8, except it uses the cached encode functions
945
 
    to save a little bit of performance.
946
 
 
947
 
    :param unicode_or_utf8_string: A possibly Unicode file_id. (can also be
948
 
        utf8 or None).
949
 
    :param warn: Functions that are sanitizing user data can set warn=False
950
 
    :return: None or a utf8 file id.
951
 
    """
952
 
    if (unicode_or_utf8_string is None
953
 
        or unicode_or_utf8_string.__class__ == str):
954
 
        return unicode_or_utf8_string
955
 
    if warn:
956
 
        symbol_versioning.warn(_file_id_warning, DeprecationWarning,
957
 
                               stacklevel=2)
958
 
    return cache_utf8.encode(unicode_or_utf8_string)
959
 
 
960
 
 
961
 
_platform_normalizes_filenames = False
962
 
if sys.platform == 'darwin':
963
 
    _platform_normalizes_filenames = True
964
 
 
965
 
 
966
 
def normalizes_filenames():
967
 
    """Return True if this platform normalizes unicode filenames.
968
 
 
969
 
    Mac OSX does, Windows/Linux do not.
970
 
    """
971
 
    return _platform_normalizes_filenames
972
 
 
973
 
 
974
 
def _accessible_normalized_filename(path):
975
 
    """Get the unicode normalized path, and if you can access the file.
976
 
 
977
 
    On platforms where the system normalizes filenames (Mac OSX),
978
 
    you can access a file by any path which will normalize correctly.
979
 
    On platforms where the system does not normalize filenames 
980
 
    (Windows, Linux), you have to access a file by its exact path.
981
 
 
982
 
    Internally, bzr only supports NFC/NFKC normalization, since that is 
983
 
    the standard for XML documents.
984
 
 
985
 
    So return the normalized path, and a flag indicating if the file
986
 
    can be accessed by that path.
987
 
    """
988
 
 
989
 
    return unicodedata.normalize('NFKC', unicode(path)), True
990
 
 
991
 
 
992
 
def _inaccessible_normalized_filename(path):
993
 
    __doc__ = _accessible_normalized_filename.__doc__
994
 
 
995
 
    normalized = unicodedata.normalize('NFKC', unicode(path))
996
 
    return normalized, normalized == path
997
 
 
998
 
 
999
 
if _platform_normalizes_filenames:
1000
 
    normalized_filename = _accessible_normalized_filename
1001
 
else:
1002
 
    normalized_filename = _inaccessible_normalized_filename
1003
 
 
1004
 
 
1005
 
def terminal_width():
1006
 
    """Return estimated terminal width."""
1007
 
    if sys.platform == 'win32':
1008
 
        return win32utils.get_console_size()[0]
1009
 
    width = 0
1010
 
    try:
1011
 
        import struct, fcntl, termios
1012
 
        s = struct.pack('HHHH', 0, 0, 0, 0)
1013
 
        x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
1014
 
        width = struct.unpack('HHHH', x)[1]
1015
 
    except IOError:
1016
 
        pass
1017
 
    if width <= 0:
1018
 
        try:
1019
 
            width = int(os.environ['COLUMNS'])
1020
 
        except:
1021
 
            pass
1022
 
    if width <= 0:
1023
 
        width = 80
1024
 
 
1025
 
    return width
1026
 
 
1027
 
 
1028
 
def supports_executable():
1029
 
    return sys.platform != "win32"
1030
 
 
1031
 
 
1032
 
def supports_posix_readonly():
1033
 
    """Return True if 'readonly' has POSIX semantics, False otherwise.
1034
 
 
1035
 
    Notably, a win32 readonly file cannot be deleted, unlike POSIX where the
1036
 
    directory controls creation/deletion, etc.
1037
 
 
1038
 
    And under win32, readonly means that the directory itself cannot be
1039
 
    deleted.  The contents of a readonly directory can be changed, unlike POSIX
1040
 
    where files in readonly directories cannot be added, deleted or renamed.
1041
 
    """
1042
 
    return sys.platform != "win32"
1043
 
 
1044
 
 
1045
 
def set_or_unset_env(env_variable, value):
1046
 
    """Modify the environment, setting or removing the env_variable.
1047
 
 
1048
 
    :param env_variable: The environment variable in question
1049
 
    :param value: The value to set the environment to. If None, then
1050
 
        the variable will be removed.
1051
 
    :return: The original value of the environment variable.
1052
 
    """
1053
 
    orig_val = os.environ.get(env_variable)
1054
 
    if value is None:
1055
 
        if orig_val is not None:
1056
 
            del os.environ[env_variable]
1057
 
    else:
1058
 
        if isinstance(value, unicode):
1059
 
            value = value.encode(bzrlib.user_encoding)
1060
 
        os.environ[env_variable] = value
1061
 
    return orig_val
1062
 
 
1063
 
 
1064
 
_validWin32PathRE = re.compile(r'^([A-Za-z]:[/\\])?[^:<>*"?\|]*$')
1065
 
 
1066
 
 
1067
 
def check_legal_path(path):
1068
 
    """Check whether the supplied path is legal.  
1069
 
    This is only required on Windows, so we don't test on other platforms
1070
 
    right now.
1071
 
    """
1072
 
    if sys.platform != "win32":
1073
 
        return
1074
 
    if _validWin32PathRE.match(path) is None:
1075
 
        raise errors.IllegalPath(path)
1076
 
 
1077
 
 
1078
 
def walkdirs(top, prefix=""):
1079
 
    """Yield data about all the directories in a tree.
1080
 
    
1081
 
    This yields all the data about the contents of a directory at a time.
1082
 
    After each directory has been yielded, if the caller has mutated the list
1083
 
    to exclude some directories, they are then not descended into.
1084
 
    
1085
 
    The data yielded is of the form:
1086
 
    ((directory-relpath, directory-path-from-top),
1087
 
    [(directory-relpath, basename, kind, lstat, path-from-top), ...]),
1088
 
     - directory-relpath is the relative path of the directory being returned
1089
 
       with respect to top. prefix is prepended to this.
1090
 
     - directory-path-from-root is the path including top for this directory. 
1091
 
       It is suitable for use with os functions.
1092
 
     - relpath is the relative path within the subtree being walked.
1093
 
     - basename is the basename of the path
1094
 
     - kind is the kind of the file now. If unknown then the file is not
1095
 
       present within the tree - but it may be recorded as versioned. See
1096
 
       versioned_kind.
1097
 
     - lstat is the stat data *if* the file was statted.
1098
 
     - planned, not implemented: 
1099
 
       path_from_tree_root is the path from the root of the tree.
1100
 
 
1101
 
    :param prefix: Prefix the relpaths that are yielded with 'prefix'. This 
1102
 
        allows one to walk a subtree but get paths that are relative to a tree
1103
 
        rooted higher up.
1104
 
    :return: an iterator over the dirs.
1105
 
    """
1106
 
    #TODO there is a bit of a smell where the results of the directory-
1107
 
    # summary in this, and the path from the root, may not agree 
1108
 
    # depending on top and prefix - i.e. ./foo and foo as a pair leads to
1109
 
    # potentially confusing output. We should make this more robust - but
1110
 
    # not at a speed cost. RBC 20060731
1111
 
    _lstat = os.lstat
1112
 
    _directory = _directory_kind
1113
 
    _listdir = os.listdir
1114
 
    _kind_from_mode = _formats.get
1115
 
    pending = [(safe_unicode(prefix), "", _directory, None, safe_unicode(top))]
1116
 
    while pending:
1117
 
        # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1118
 
        relroot, _, _, _, top = pending.pop()
1119
 
        if relroot:
1120
 
            relprefix = relroot + u'/'
1121
 
        else:
1122
 
            relprefix = ''
1123
 
        top_slash = top + u'/'
1124
 
 
1125
 
        dirblock = []
1126
 
        append = dirblock.append
1127
 
        for name in sorted(_listdir(top)):
1128
 
            abspath = top_slash + name
1129
 
            statvalue = _lstat(abspath)
1130
 
            kind = _kind_from_mode(statvalue.st_mode & 0170000, 'unknown')
1131
 
            append((relprefix + name, name, kind, statvalue, abspath))
1132
 
        yield (relroot, top), dirblock
1133
 
 
1134
 
        # push the user specified dirs from dirblock
1135
 
        pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
1136
 
 
1137
 
 
1138
 
def _walkdirs_utf8(top, prefix=""):
1139
 
    """Yield data about all the directories in a tree.
1140
 
 
1141
 
    This yields the same information as walkdirs() only each entry is yielded
1142
 
    in utf-8. On platforms which have a filesystem encoding of utf8 the paths
1143
 
    are returned as exact byte-strings.
1144
 
 
1145
 
    :return: yields a tuple of (dir_info, [file_info])
1146
 
        dir_info is (utf8_relpath, path-from-top)
1147
 
        file_info is (utf8_relpath, utf8_name, kind, lstat, path-from-top)
1148
 
        if top is an absolute path, path-from-top is also an absolute path.
1149
 
        path-from-top might be unicode or utf8, but it is the correct path to
1150
 
        pass to os functions to affect the file in question. (such as os.lstat)
1151
 
    """
1152
 
    fs_encoding = sys.getfilesystemencoding().upper()
1153
 
    if (sys.platform == 'win32' or
1154
 
        fs_encoding not in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968')): # ascii
1155
 
        return _walkdirs_unicode_to_utf8(top, prefix=prefix)
1156
 
    else:
1157
 
        return _walkdirs_fs_utf8(top, prefix=prefix)
1158
 
 
1159
 
 
1160
 
def _walkdirs_fs_utf8(top, prefix=""):
1161
 
    """See _walkdirs_utf8.
1162
 
 
1163
 
    This sub-function is called when we know the filesystem is already in utf8
1164
 
    encoding. So we don't need to transcode filenames.
1165
 
    """
1166
 
    _lstat = os.lstat
1167
 
    _directory = _directory_kind
1168
 
    _listdir = os.listdir
1169
 
    _kind_from_mode = _formats.get
1170
 
 
1171
 
    # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1172
 
    # But we don't actually uses 1-3 in pending, so set them to None
1173
 
    pending = [(safe_utf8(prefix), None, None, None, safe_utf8(top))]
1174
 
    while pending:
1175
 
        relroot, _, _, _, top = pending.pop()
1176
 
        if relroot:
1177
 
            relprefix = relroot + '/'
1178
 
        else:
1179
 
            relprefix = ''
1180
 
        top_slash = top + '/'
1181
 
 
1182
 
        dirblock = []
1183
 
        append = dirblock.append
1184
 
        for name in sorted(_listdir(top)):
1185
 
            abspath = top_slash + name
1186
 
            statvalue = _lstat(abspath)
1187
 
            kind = _kind_from_mode(statvalue.st_mode & 0170000, 'unknown')
1188
 
            append((relprefix + name, name, kind, statvalue, abspath))
1189
 
        yield (relroot, top), dirblock
1190
 
 
1191
 
        # push the user specified dirs from dirblock
1192
 
        pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
1193
 
 
1194
 
 
1195
 
def _walkdirs_unicode_to_utf8(top, prefix=""):
1196
 
    """See _walkdirs_utf8
1197
 
 
1198
 
    Because Win32 has a Unicode api, all of the 'path-from-top' entries will be
1199
 
    Unicode paths.
1200
 
    This is currently the fallback code path when the filesystem encoding is
1201
 
    not UTF-8. It may be better to implement an alternative so that we can
1202
 
    safely handle paths that are not properly decodable in the current
1203
 
    encoding.
1204
 
    """
1205
 
    _utf8_encode = codecs.getencoder('utf8')
1206
 
    _lstat = os.lstat
1207
 
    _directory = _directory_kind
1208
 
    _listdir = os.listdir
1209
 
    _kind_from_mode = _formats.get
1210
 
 
1211
 
    pending = [(safe_utf8(prefix), None, None, None, safe_unicode(top))]
1212
 
    while pending:
1213
 
        relroot, _, _, _, top = pending.pop()
1214
 
        if relroot:
1215
 
            relprefix = relroot + '/'
1216
 
        else:
1217
 
            relprefix = ''
1218
 
        top_slash = top + u'/'
1219
 
 
1220
 
        dirblock = []
1221
 
        append = dirblock.append
1222
 
        for name in sorted(_listdir(top)):
1223
 
            name_utf8 = _utf8_encode(name)[0]
1224
 
            abspath = top_slash + name
1225
 
            statvalue = _lstat(abspath)
1226
 
            kind = _kind_from_mode(statvalue.st_mode & 0170000, 'unknown')
1227
 
            append((relprefix + name_utf8, name_utf8, kind, statvalue, abspath))
1228
 
        yield (relroot, top), dirblock
1229
 
 
1230
 
        # push the user specified dirs from dirblock
1231
 
        pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
1232
 
 
1233
 
 
1234
 
def copy_tree(from_path, to_path, handlers={}):
1235
 
    """Copy all of the entries in from_path into to_path.
1236
 
 
1237
 
    :param from_path: The base directory to copy. 
1238
 
    :param to_path: The target directory. If it does not exist, it will
1239
 
        be created.
1240
 
    :param handlers: A dictionary of functions, which takes a source and
1241
 
        destinations for files, directories, etc.
1242
 
        It is keyed on the file kind, such as 'directory', 'symlink', or 'file'
1243
 
        'file', 'directory', and 'symlink' should always exist.
1244
 
        If they are missing, they will be replaced with 'os.mkdir()',
1245
 
        'os.readlink() + os.symlink()', and 'shutil.copy2()', respectively.
1246
 
    """
1247
 
    # Now, just copy the existing cached tree to the new location
1248
 
    # We use a cheap trick here.
1249
 
    # Absolute paths are prefixed with the first parameter
1250
 
    # relative paths are prefixed with the second.
1251
 
    # So we can get both the source and target returned
1252
 
    # without any extra work.
1253
 
 
1254
 
    def copy_dir(source, dest):
1255
 
        os.mkdir(dest)
1256
 
 
1257
 
    def copy_link(source, dest):
1258
 
        """Copy the contents of a symlink"""
1259
 
        link_to = os.readlink(source)
1260
 
        os.symlink(link_to, dest)
1261
 
 
1262
 
    real_handlers = {'file':shutil.copy2,
1263
 
                     'symlink':copy_link,
1264
 
                     'directory':copy_dir,
1265
 
                    }
1266
 
    real_handlers.update(handlers)
1267
 
 
1268
 
    if not os.path.exists(to_path):
1269
 
        real_handlers['directory'](from_path, to_path)
1270
 
 
1271
 
    for dir_info, entries in walkdirs(from_path, prefix=to_path):
1272
 
        for relpath, name, kind, st, abspath in entries:
1273
 
            real_handlers[kind](abspath, relpath)
1274
 
 
1275
 
 
1276
 
def path_prefix_key(path):
1277
 
    """Generate a prefix-order path key for path.
1278
 
 
1279
 
    This can be used to sort paths in the same way that walkdirs does.
1280
 
    """
1281
 
    return (dirname(path) , path)
1282
 
 
1283
 
 
1284
 
def compare_paths_prefix_order(path_a, path_b):
1285
 
    """Compare path_a and path_b to generate the same order walkdirs uses."""
1286
 
    key_a = path_prefix_key(path_a)
1287
 
    key_b = path_prefix_key(path_b)
1288
 
    return cmp(key_a, key_b)
1289
 
 
1290
 
 
1291
 
_cached_user_encoding = None
1292
 
 
1293
 
 
1294
 
def get_user_encoding(use_cache=True):
1295
 
    """Find out what the preferred user encoding is.
1296
 
 
1297
 
    This is generally the encoding that is used for command line parameters
1298
 
    and file contents. This may be different from the terminal encoding
1299
 
    or the filesystem encoding.
1300
 
 
1301
 
    :param  use_cache:  Enable cache for detected encoding.
1302
 
                        (This parameter is turned on by default,
1303
 
                        and required only for selftesting)
1304
 
 
1305
 
    :return: A string defining the preferred user encoding
1306
 
    """
1307
 
    global _cached_user_encoding
1308
 
    if _cached_user_encoding is not None and use_cache:
1309
 
        return _cached_user_encoding
1310
 
 
1311
 
    if sys.platform == 'darwin':
1312
 
        # work around egregious python 2.4 bug
1313
 
        sys.platform = 'posix'
1314
 
        try:
1315
 
            import locale
1316
 
        finally:
1317
 
            sys.platform = 'darwin'
1318
 
    else:
1319
 
        import locale
1320
 
 
1321
 
    try:
1322
 
        user_encoding = locale.getpreferredencoding()
1323
 
    except locale.Error, e:
1324
 
        sys.stderr.write('bzr: warning: %s\n'
1325
 
                         '  Could not determine what text encoding to use.\n'
1326
 
                         '  This error usually means your Python interpreter\n'
1327
 
                         '  doesn\'t support the locale set by $LANG (%s)\n'
1328
 
                         "  Continuing with ascii encoding.\n"
1329
 
                         % (e, os.environ.get('LANG')))
1330
 
        user_encoding = 'ascii'
1331
 
 
1332
 
    # Windows returns 'cp0' to indicate there is no code page. So we'll just
1333
 
    # treat that as ASCII, and not support printing unicode characters to the
1334
 
    # console.
1335
 
    if user_encoding in (None, 'cp0'):
1336
 
        user_encoding = 'ascii'
1337
 
    else:
1338
 
        # check encoding
1339
 
        try:
1340
 
            codecs.lookup(user_encoding)
1341
 
        except LookupError:
1342
 
            sys.stderr.write('bzr: warning:'
1343
 
                             ' unknown encoding %s.'
1344
 
                             ' Continuing with ascii encoding.\n'
1345
 
                             % user_encoding
1346
 
                            )
1347
 
            user_encoding = 'ascii'
1348
 
 
1349
 
    if use_cache:
1350
 
        _cached_user_encoding = user_encoding
1351
 
 
1352
 
    return user_encoding
1353
 
 
1354
 
 
1355
 
def recv_all(socket, bytes):
1356
 
    """Receive an exact number of bytes.
1357
 
 
1358
 
    Regular Socket.recv() may return less than the requested number of bytes,
1359
 
    dependning on what's in the OS buffer.  MSG_WAITALL is not available
1360
 
    on all platforms, but this should work everywhere.  This will return
1361
 
    less than the requested amount if the remote end closes.
1362
 
 
1363
 
    This isn't optimized and is intended mostly for use in testing.
1364
 
    """
1365
 
    b = ''
1366
 
    while len(b) < bytes:
1367
 
        new = socket.recv(bytes - len(b))
1368
 
        if new == '':
1369
 
            break # eof
1370
 
        b += new
1371
 
    return b
1372
 
 
1373
 
def dereference_path(path):
1374
 
    """Determine the real path to a file.
1375
 
 
1376
 
    All parent elements are dereferenced.  But the file itself is not
1377
 
    dereferenced.
1378
 
    :param path: The original path.  May be absolute or relative.
1379
 
    :return: the real path *to* the file
1380
 
    """
1381
 
    parent, base = os.path.split(path)
1382
 
    # The pathjoin for '.' is a workaround for Python bug #1213894.
1383
 
    # (initial path components aren't dereferenced)
1384
 
    return pathjoin(realpath(pathjoin('.', parent)), base)
 
473
        return os.path.join(p1, p2)
 
474
    
 
475
 
 
476
def extern_command(cmd, ignore_errors = False):
 
477
    mutter('external command: %s' % `cmd`)
 
478
    if os.system(cmd):
 
479
        if not ignore_errors:
 
480
            raise BzrError('command failed')
 
481
 
 
482
 
 
483
def _read_config_value(name):
 
484
    """Read a config value from the file ~/.bzr.conf/<name>
 
485
    Return None if the file does not exist"""
 
486
    try:
 
487
        f = file(os.path.join(config_dir(), name), "r")
 
488
        return f.read().decode(bzrlib.user_encoding).rstrip("\r\n")
 
489
    except IOError, e:
 
490
        if e.errno == errno.ENOENT:
 
491
            return None
 
492
        raise
 
493
 
 
494