/brz/remove-bazaar

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