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