/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
2
3
# Copyright (C) 2005 by Canonical Ltd
4
5
# This program is free software; you can redistribute it and/or modify
6
# it under the terms of the GNU General Public License as published by
7
# the Free Software Foundation; either version 2 of the License, or
8
# (at your option) any later version.
9
10
# This program is distributed in the hope that it will be useful,
11
# but WITHOUT ANY WARRANTY; without even the implied warranty of
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
# GNU General Public License for more details.
14
15
# You should have received a copy of the GNU General Public License
16
# along with this program; if not, write to the Free Software
17
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18
444 by Martin Pool
- cope on platforms with no urandom feature
19
import os, types, re, time, errno, sys
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,
21
        S_ISCHR, S_ISBLK, S_ISFIFO, S_ISSOCK)
1 by mbp at sourcefrog
import from baz patch-364
22
694 by Martin Pool
- weed out all remaining calls to bailout() and remove the function
23
from bzrlib.errors import BzrError
24
from bzrlib.trace import mutter
251 by mbp at sourcefrog
- factor out locale.getpreferredencoding()
25
import bzrlib
1 by mbp at sourcefrog
import from baz patch-364
26
27
def make_readonly(filename):
28
    """Make a filename read-only."""
29
    # TODO: probably needs to be fixed for windows
30
    mod = os.stat(filename).st_mode
31
    mod = mod & 0777555
32
    os.chmod(filename, mod)
33
34
35
def make_writable(filename):
36
    mod = os.stat(filename).st_mode
37
    mod = mod | 0200
38
    os.chmod(filename, mod)
39
40
1077 by Martin Pool
- avoid compiling REs at module load time
41
_QUOTE_RE = None
969 by Martin Pool
- Add less-sucky is_within_any
42
43
1 by mbp at sourcefrog
import from baz patch-364
44
def quotefn(f):
779 by Martin Pool
- better quotefn for windows: use doublequotes for strings with
45
    """Return a quoted filename filename
46
47
    This previously used backslash quoting, but that works poorly on
48
    Windows."""
49
    # TODO: I'm not really sure this is the best format either.x
1077 by Martin Pool
- avoid compiling REs at module load time
50
    global _QUOTE_RE
51
    if _QUOTE_RE == None:
52
        _QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/_~-])')
53
        
779 by Martin Pool
- better quotefn for windows: use doublequotes for strings with
54
    if _QUOTE_RE.search(f):
55
        return '"' + f + '"'
56
    else:
57
        return f
1 by mbp at sourcefrog
import from baz patch-364
58
59
60
def file_kind(f):
61
    mode = os.lstat(f)[ST_MODE]
62
    if S_ISREG(mode):
63
        return 'file'
64
    elif S_ISDIR(mode):
65
        return 'directory'
20 by mbp at sourcefrog
don't abort on trees that happen to contain symlinks
66
    elif S_ISLNK(mode):
67
        return 'symlink'
1185.3.28 by John Arbash Meinel
Adding knowledge about fifo/block/etc, they will be unknown/ignored.
68
    elif S_ISCHR(mode):
69
        return 'chardev'
70
    elif S_ISBLK(mode):
71
        return 'block'
72
    elif S_ISFIFO(mode):
73
        return 'fifo'
74
    elif S_ISSOCK(mode):
75
        return 'socket'
1 by mbp at sourcefrog
import from baz patch-364
76
    else:
1185.3.28 by John Arbash Meinel
Adding knowledge about fifo/block/etc, they will be unknown/ignored.
77
        return 'unknown'
488 by Martin Pool
- new helper function kind_marker()
78
79
80
def kind_marker(kind):
81
    if kind == 'file':
82
        return ''
83
    elif kind == 'directory':
84
        return '/'
85
    elif kind == 'symlink':
86
        return '@'
87
    else:
88
        raise BzrError('invalid file kind %r' % kind)
1 by mbp at sourcefrog
import from baz patch-364
89
90
91
779 by Martin Pool
- better quotefn for windows: use doublequotes for strings with
92
def backup_file(fn):
93
    """Copy a file to a backup.
94
95
    Backups are named in GNU-style, with a ~ suffix.
96
97
    If the file is already a backup, it's not copied.
98
    """
99
    import os
100
    if fn[-1] == '~':
101
        return
102
    bfn = fn + '~'
103
104
    inf = file(fn, 'rb')
105
    try:
106
        content = inf.read()
107
    finally:
108
        inf.close()
109
    
110
    outf = file(bfn, 'wb')
111
    try:
112
        outf.write(content)
113
    finally:
114
        outf.close()
115
1185.1.40 by Robert Collins
Merge what applied of Alexander Belchenko's win32 patch.
116
if os.name == 'nt':
117
    import shutil
118
    rename = shutil.move
119
else:
120
    rename = os.rename
779 by Martin Pool
- better quotefn for windows: use doublequotes for strings with
121
122
1 by mbp at sourcefrog
import from baz patch-364
123
def isdir(f):
124
    """True if f is an accessible directory."""
125
    try:
126
        return S_ISDIR(os.lstat(f)[ST_MODE])
127
    except OSError:
128
        return False
129
130
131
def isfile(f):
132
    """True if f is a regular file."""
133
    try:
134
        return S_ISREG(os.lstat(f)[ST_MODE])
135
    except OSError:
136
        return False
137
138
485 by Martin Pool
- move commit code into its own module
139
def is_inside(dir, fname):
140
    """True if fname is inside dir.
969 by Martin Pool
- Add less-sucky is_within_any
141
    
142
    The parameters should typically be passed to os.path.normpath first, so
143
    that . and .. and repeated slashes are eliminated, and the separators
144
    are canonical for the platform.
145
    
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
146
    The empty string as a dir name is taken as top-of-tree and matches 
147
    everything.
148
    
1185.1.40 by Robert Collins
Merge what applied of Alexander Belchenko's win32 patch.
149
    >>> is_inside('src', os.path.join('src', 'foo.c'))
969 by Martin Pool
- Add less-sucky is_within_any
150
    True
151
    >>> is_inside('src', 'srccontrol')
152
    False
1185.1.40 by Robert Collins
Merge what applied of Alexander Belchenko's win32 patch.
153
    >>> is_inside('src', os.path.join('src', 'a', 'a', 'a', 'foo.c'))
969 by Martin Pool
- Add less-sucky is_within_any
154
    True
155
    >>> is_inside('foo.c', 'foo.c')
156
    True
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
157
    >>> is_inside('foo.c', '')
158
    False
159
    >>> is_inside('', 'foo.c')
160
    True
485 by Martin Pool
- move commit code into its own module
161
    """
969 by Martin Pool
- Add less-sucky is_within_any
162
    # XXX: Most callers of this can actually do something smarter by 
163
    # looking at the inventory
972 by Martin Pool
- less dodgy is_inside function
164
    if dir == fname:
165
        return True
166
    
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
167
    if dir == '':
168
        return True
169
    
972 by Martin Pool
- less dodgy is_inside function
170
    if dir[-1] != os.sep:
171
        dir += os.sep
172
    
173
    return fname.startswith(dir)
174
485 by Martin Pool
- move commit code into its own module
175
176
def is_inside_any(dir_list, fname):
177
    """True if fname is inside any of given dirs."""
178
    for dirname in dir_list:
179
        if is_inside(dirname, fname):
180
            return True
181
    else:
182
        return False
183
184
1 by mbp at sourcefrog
import from baz patch-364
185
def pumpfile(fromfile, tofile):
186
    """Copy contents of one file to another."""
187
    tofile.write(fromfile.read())
188
189
190
def uuid():
191
    """Return a new UUID"""
63 by mbp at sourcefrog
fix up uuid command
192
    try:
319 by Martin Pool
- remove trivial chomp() function
193
        return file('/proc/sys/kernel/random/uuid').readline().rstrip('\n')
63 by mbp at sourcefrog
fix up uuid command
194
    except IOError:
195
        return chomp(os.popen('uuidgen').readline())
196
1 by mbp at sourcefrog
import from baz patch-364
197
198
def sha_file(f):
199
    import sha
200
    if hasattr(f, 'tell'):
201
        assert f.tell() == 0
202
    s = sha.new()
320 by Martin Pool
- Compute SHA-1 of files in chunks
203
    BUFSIZE = 128<<10
204
    while True:
205
        b = f.read(BUFSIZE)
206
        if not b:
207
            break
208
        s.update(b)
1 by mbp at sourcefrog
import from baz patch-364
209
    return s.hexdigest()
210
211
212
def sha_string(f):
213
    import sha
214
    s = sha.new()
215
    s.update(f)
216
    return s.hexdigest()
217
218
219
124 by mbp at sourcefrog
- check file text for past revisions is correct
220
def fingerprint_file(f):
221
    import sha
222
    s = sha.new()
126 by mbp at sourcefrog
Use just one big read to fingerprint files
223
    b = f.read()
224
    s.update(b)
225
    size = len(b)
124 by mbp at sourcefrog
- check file text for past revisions is correct
226
    return {'size': size,
227
            'sha1': s.hexdigest()}
228
229
258 by Martin Pool
- Take email from ~/.bzr.conf/email
230
def config_dir():
231
    """Return per-user configuration directory.
232
233
    By default this is ~/.bzr.conf/
234
    
235
    TODO: Global option --config-dir to override this.
236
    """
237
    return os.path.expanduser("~/.bzr.conf")
238
239
252 by Martin Pool
- Don't use host fqdn for default user name, because DNS tends
240
def _auto_user_id():
246 by mbp at sourcefrog
- unicode decoding in getting email and userid strings
241
    """Calculate automatic user identification.
242
243
    Returns (realname, email).
244
252 by Martin Pool
- Don't use host fqdn for default user name, because DNS tends
245
    Only used when none is set in the environment or the id file.
246 by mbp at sourcefrog
- unicode decoding in getting email and userid strings
246
252 by Martin Pool
- Don't use host fqdn for default user name, because DNS tends
247
    This previously used the FQDN as the default domain, but that can
248
    be very slow on machines where DNS is broken.  So now we simply
249
    use the hostname.
1 by mbp at sourcefrog
import from baz patch-364
250
    """
251 by mbp at sourcefrog
- factor out locale.getpreferredencoding()
251
    import socket
246 by mbp at sourcefrog
- unicode decoding in getting email and userid strings
252
253
    # XXX: Any good way to get real user name on win32?
254
1 by mbp at sourcefrog
import from baz patch-364
255
    try:
256
        import pwd
257
        uid = os.getuid()
258
        w = pwd.getpwuid(uid)
251 by mbp at sourcefrog
- factor out locale.getpreferredencoding()
259
        gecos = w.pw_gecos.decode(bzrlib.user_encoding)
260
        username = w.pw_name.decode(bzrlib.user_encoding)
25 by Martin Pool
cope when gecos field doesn't have a comma
261
        comma = gecos.find(',')
262
        if comma == -1:
263
            realname = gecos
264
        else:
265
            realname = gecos[:comma]
256 by Martin Pool
- More handling of auto-username case
266
        if not realname:
267
            realname = username
246 by mbp at sourcefrog
- unicode decoding in getting email and userid strings
268
1 by mbp at sourcefrog
import from baz patch-364
269
    except ImportError:
246 by mbp at sourcefrog
- unicode decoding in getting email and userid strings
270
        import getpass
256 by Martin Pool
- More handling of auto-username case
271
        realname = username = getpass.getuser().decode(bzrlib.user_encoding)
252 by Martin Pool
- Don't use host fqdn for default user name, because DNS tends
272
256 by Martin Pool
- More handling of auto-username case
273
    return realname, (username + '@' + socket.gethostname())
252 by Martin Pool
- Don't use host fqdn for default user name, because DNS tends
274
275
1074 by Martin Pool
- check for email address in BRANCH_ROOT/.bzr/email, so you can
276
def _get_user_id(branch):
258 by Martin Pool
- Take email from ~/.bzr.conf/email
277
    """Return the full user id from a file or environment variable.
278
1074 by Martin Pool
- check for email address in BRANCH_ROOT/.bzr/email, so you can
279
    e.g. "John Hacker <jhacker@foo.org>"
280
281
    branch
282
        A branch to use for a per-branch configuration, or None.
283
284
    The following are searched in order:
285
286
    1. $BZREMAIL
287
    2. .bzr/email for this branch.
288
    3. ~/.bzr.conf/email
289
    4. $EMAIL
290
    """
252 by Martin Pool
- Don't use host fqdn for default user name, because DNS tends
291
    v = os.environ.get('BZREMAIL')
292
    if v:
293
        return v.decode(bzrlib.user_encoding)
1074 by Martin Pool
- check for email address in BRANCH_ROOT/.bzr/email, so you can
294
295
    if branch:
296
        try:
297
            return (branch.controlfile("email", "r") 
298
                    .read()
299
                    .decode(bzrlib.user_encoding)
300
                    .rstrip("\r\n"))
301
        except IOError, e:
302
            if e.errno != errno.ENOENT:
303
                raise
304
        except BzrError, e:
305
            pass
252 by Martin Pool
- Don't use host fqdn for default user name, because DNS tends
306
    
307
    try:
258 by Martin Pool
- Take email from ~/.bzr.conf/email
308
        return (open(os.path.join(config_dir(), "email"))
252 by Martin Pool
- Don't use host fqdn for default user name, because DNS tends
309
                .read()
310
                .decode(bzrlib.user_encoding)
311
                .rstrip("\r\n"))
256 by Martin Pool
- More handling of auto-username case
312
    except IOError, e:
313
        if e.errno != errno.ENOENT:
252 by Martin Pool
- Don't use host fqdn for default user name, because DNS tends
314
            raise e
315
316
    v = os.environ.get('EMAIL')
317
    if v:
318
        return v.decode(bzrlib.user_encoding)
319
    else:    
320
        return None
246 by mbp at sourcefrog
- unicode decoding in getting email and userid strings
321
322
1074 by Martin Pool
- check for email address in BRANCH_ROOT/.bzr/email, so you can
323
def username(branch):
246 by mbp at sourcefrog
- unicode decoding in getting email and userid strings
324
    """Return email-style username.
325
326
    Something similar to 'Martin Pool <mbp@sourcefrog.net>'
327
254 by Martin Pool
- Doc cleanups from Magnus Therning
328
    TODO: Check it's reasonably well-formed.
246 by mbp at sourcefrog
- unicode decoding in getting email and userid strings
329
    """
1074 by Martin Pool
- check for email address in BRANCH_ROOT/.bzr/email, so you can
330
    v = _get_user_id(branch)
252 by Martin Pool
- Don't use host fqdn for default user name, because DNS tends
331
    if v:
332
        return v
333
    
334
    name, email = _auto_user_id()
246 by mbp at sourcefrog
- unicode decoding in getting email and userid strings
335
    if name:
336
        return '%s <%s>' % (name, email)
337
    else:
338
        return email
1 by mbp at sourcefrog
import from baz patch-364
339
340
1074 by Martin Pool
- check for email address in BRANCH_ROOT/.bzr/email, so you can
341
def user_email(branch):
1 by mbp at sourcefrog
import from baz patch-364
342
    """Return just the email component of a username."""
1074 by Martin Pool
- check for email address in BRANCH_ROOT/.bzr/email, so you can
343
    e = _get_user_id(branch)
1 by mbp at sourcefrog
import from baz patch-364
344
    if e:
1077 by Martin Pool
- avoid compiling REs at module load time
345
        m = re.search(r'[\w+.-]+@[\w+.-]+', e)
1 by mbp at sourcefrog
import from baz patch-364
346
        if not m:
694 by Martin Pool
- weed out all remaining calls to bailout() and remove the function
347
            raise BzrError("%r doesn't seem to contain a reasonable email address" % e)
1 by mbp at sourcefrog
import from baz patch-364
348
        return m.group(0)
349
252 by Martin Pool
- Don't use host fqdn for default user name, because DNS tends
350
    return _auto_user_id()[1]
1 by mbp at sourcefrog
import from baz patch-364
351
    
352
353
354
def compare_files(a, b):
355
    """Returns true if equal in contents"""
74 by mbp at sourcefrog
compare_files: read in one page at a time rather than
356
    BUFSIZE = 4096
357
    while True:
358
        ai = a.read(BUFSIZE)
359
        bi = b.read(BUFSIZE)
360
        if ai != bi:
361
            return False
362
        if ai == '':
363
            return True
1 by mbp at sourcefrog
import from baz patch-364
364
365
366
49 by mbp at sourcefrog
fix local-time-offset calculation
367
def local_time_offset(t=None):
368
    """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
369
    # python2.3 localtime() can't take None
183 by mbp at sourcefrog
pychecker fixups
370
    if t == None:
73 by mbp at sourcefrog
fix time.localtime call for python 2.3
371
        t = time.time()
372
        
49 by mbp at sourcefrog
fix local-time-offset calculation
373
    if time.localtime(t).tm_isdst and time.daylight:
8 by mbp at sourcefrog
store committer's timezone in revision and show
374
        return -time.altzone
375
    else:
376
        return -time.timezone
377
378
    
379
def format_date(t, offset=0, timezone='original'):
1 by mbp at sourcefrog
import from baz patch-364
380
    ## TODO: Perhaps a global option to use either universal or local time?
381
    ## Or perhaps just let people set $TZ?
382
    assert isinstance(t, float)
383
    
8 by mbp at sourcefrog
store committer's timezone in revision and show
384
    if timezone == 'utc':
1 by mbp at sourcefrog
import from baz patch-364
385
        tt = time.gmtime(t)
386
        offset = 0
8 by mbp at sourcefrog
store committer's timezone in revision and show
387
    elif timezone == 'original':
23 by mbp at sourcefrog
format_date: handle revisions with no timezone offset
388
        if offset == None:
389
            offset = 0
16 by mbp at sourcefrog
fix inverted calculation for original timezone -> utc
390
        tt = time.gmtime(t + offset)
12 by mbp at sourcefrog
new --timezone option for bzr log
391
    elif timezone == 'local':
1 by mbp at sourcefrog
import from baz patch-364
392
        tt = time.localtime(t)
49 by mbp at sourcefrog
fix local-time-offset calculation
393
        offset = local_time_offset(t)
12 by mbp at sourcefrog
new --timezone option for bzr log
394
    else:
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
395
        raise BzrError("unsupported timezone format %r" % timezone,
396
                       ['options are "utc", "original", "local"'])
8 by mbp at sourcefrog
store committer's timezone in revision and show
397
1 by mbp at sourcefrog
import from baz patch-364
398
    return (time.strftime("%a %Y-%m-%d %H:%M:%S", tt)
8 by mbp at sourcefrog
store committer's timezone in revision and show
399
            + ' %+03d%02d' % (offset / 3600, (offset / 60) % 60))
1 by mbp at sourcefrog
import from baz patch-364
400
401
402
def compact_date(when):
403
    return time.strftime('%Y%m%d%H%M%S', time.gmtime(when))
404
    
405
406
407
def filesize(f):
408
    """Return size of given open file."""
409
    return os.fstat(f.fileno())[ST_SIZE]
410
1185.1.7 by Robert Collins
Nathaniel McCallums patch for urandom friendliness on aix.
411
# Define rand_bytes based on platform.
412
try:
413
    # Python 2.4 and later have os.urandom,
414
    # but it doesn't work on some arches
415
    os.urandom(1)
1 by mbp at sourcefrog
import from baz patch-364
416
    rand_bytes = os.urandom
1185.1.7 by Robert Collins
Nathaniel McCallums patch for urandom friendliness on aix.
417
except (NotImplementedError, AttributeError):
418
    # If python doesn't have os.urandom, or it doesn't work,
419
    # then try to first pull random data from /dev/urandom
420
    if os.path.exists("/dev/urandom"):
421
        rand_bytes = file('/dev/urandom', 'rb').read
422
    # Otherwise, use this hack as a last resort
423
    else:
424
        # not well seeded, but better than nothing
425
        def rand_bytes(n):
426
            import random
427
            s = ''
428
            while n:
429
                s += chr(random.randint(0, 255))
430
                n -= 1
431
            return s
1 by mbp at sourcefrog
import from baz patch-364
432
433
## TODO: We could later have path objects that remember their list
434
## decomposition (might be too tricksy though.)
435
436
def splitpath(p):
437
    """Turn string into list of parts.
438
439
    >>> splitpath('a')
440
    ['a']
441
    >>> splitpath('a/b')
442
    ['a', 'b']
443
    >>> splitpath('a/./b')
444
    ['a', 'b']
445
    >>> splitpath('a/.b')
446
    ['a', '.b']
447
    >>> splitpath('a/../b')
184 by mbp at sourcefrog
pychecker fixups
448
    Traceback (most recent call last):
1 by mbp at sourcefrog
import from baz patch-364
449
    ...
694 by Martin Pool
- weed out all remaining calls to bailout() and remove the function
450
    BzrError: sorry, '..' not allowed in path
1 by mbp at sourcefrog
import from baz patch-364
451
    """
452
    assert isinstance(p, types.StringTypes)
271 by Martin Pool
- Windows path fixes
453
454
    # split on either delimiter because people might use either on
455
    # Windows
456
    ps = re.split(r'[\\/]', p)
457
458
    rps = []
1 by mbp at sourcefrog
import from baz patch-364
459
    for f in ps:
460
        if f == '..':
694 by Martin Pool
- weed out all remaining calls to bailout() and remove the function
461
            raise BzrError("sorry, %r not allowed in path" % f)
271 by Martin Pool
- Windows path fixes
462
        elif (f == '.') or (f == ''):
463
            pass
464
        else:
465
            rps.append(f)
466
    return rps
1 by mbp at sourcefrog
import from baz patch-364
467
468
def joinpath(p):
469
    assert isinstance(p, list)
470
    for f in p:
183 by mbp at sourcefrog
pychecker fixups
471
        if (f == '..') or (f == None) or (f == ''):
694 by Martin Pool
- weed out all remaining calls to bailout() and remove the function
472
            raise BzrError("sorry, %r not allowed in path" % f)
271 by Martin Pool
- Windows path fixes
473
    return os.path.join(*p)
1 by mbp at sourcefrog
import from baz patch-364
474
475
476
def appendpath(p1, p2):
477
    if p1 == '':
478
        return p2
479
    else:
271 by Martin Pool
- Windows path fixes
480
        return os.path.join(p1, p2)
1 by mbp at sourcefrog
import from baz patch-364
481
    
482
483
def extern_command(cmd, ignore_errors = False):
484
    mutter('external command: %s' % `cmd`)
485
    if os.system(cmd):
486
        if not ignore_errors:
694 by Martin Pool
- weed out all remaining calls to bailout() and remove the function
487
            raise BzrError('command failed')
1 by mbp at sourcefrog
import from baz patch-364
488
763 by Martin Pool
- Patch from Torsten Marek to take commit messages through an
489
490
def _read_config_value(name):
491
    """Read a config value from the file ~/.bzr.conf/<name>
492
    Return None if the file does not exist"""
493
    try:
494
        f = file(os.path.join(config_dir(), name), "r")
495
        return f.read().decode(bzrlib.user_encoding).rstrip("\r\n")
496
    except IOError, e:
497
        if e.errno == errno.ENOENT:
498
            return None
499
        raise
500
501