/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
213
def sha_string(f):
214
    import sha
215
    s = sha.new()
216
    s.update(f)
217
    return s.hexdigest()
218
219
220
124 by mbp at sourcefrog
- check file text for past revisions is correct
221
def fingerprint_file(f):
222
    import sha
223
    s = sha.new()
126 by mbp at sourcefrog
Use just one big read to fingerprint files
224
    b = f.read()
225
    s.update(b)
226
    size = len(b)
124 by mbp at sourcefrog
- check file text for past revisions is correct
227
    return {'size': size,
228
            'sha1': s.hexdigest()}
229
230
258 by Martin Pool
- Take email from ~/.bzr.conf/email
231
def config_dir():
232
    """Return per-user configuration directory.
233
234
    By default this is ~/.bzr.conf/
235
    
236
    TODO: Global option --config-dir to override this.
237
    """
238
    return os.path.expanduser("~/.bzr.conf")
239
240
252 by Martin Pool
- Don't use host fqdn for default user name, because DNS tends
241
def _auto_user_id():
246 by mbp at sourcefrog
- unicode decoding in getting email and userid strings
242
    """Calculate automatic user identification.
243
244
    Returns (realname, email).
245
252 by Martin Pool
- Don't use host fqdn for default user name, because DNS tends
246
    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
247
252 by Martin Pool
- Don't use host fqdn for default user name, because DNS tends
248
    This previously used the FQDN as the default domain, but that can
249
    be very slow on machines where DNS is broken.  So now we simply
250
    use the hostname.
1 by mbp at sourcefrog
import from baz patch-364
251
    """
251 by mbp at sourcefrog
- factor out locale.getpreferredencoding()
252
    import socket
246 by mbp at sourcefrog
- unicode decoding in getting email and userid strings
253
254
    # XXX: Any good way to get real user name on win32?
255
1 by mbp at sourcefrog
import from baz patch-364
256
    try:
257
        import pwd
258
        uid = os.getuid()
259
        w = pwd.getpwuid(uid)
251 by mbp at sourcefrog
- factor out locale.getpreferredencoding()
260
        gecos = w.pw_gecos.decode(bzrlib.user_encoding)
261
        username = w.pw_name.decode(bzrlib.user_encoding)
25 by Martin Pool
cope when gecos field doesn't have a comma
262
        comma = gecos.find(',')
263
        if comma == -1:
264
            realname = gecos
265
        else:
266
            realname = gecos[:comma]
256 by Martin Pool
- More handling of auto-username case
267
        if not realname:
268
            realname = username
246 by mbp at sourcefrog
- unicode decoding in getting email and userid strings
269
1 by mbp at sourcefrog
import from baz patch-364
270
    except ImportError:
246 by mbp at sourcefrog
- unicode decoding in getting email and userid strings
271
        import getpass
256 by Martin Pool
- More handling of auto-username case
272
        realname = username = getpass.getuser().decode(bzrlib.user_encoding)
252 by Martin Pool
- Don't use host fqdn for default user name, because DNS tends
273
256 by Martin Pool
- More handling of auto-username case
274
    return realname, (username + '@' + socket.gethostname())
252 by Martin Pool
- Don't use host fqdn for default user name, because DNS tends
275
276
1074 by Martin Pool
- check for email address in BRANCH_ROOT/.bzr/email, so you can
277
def _get_user_id(branch):
258 by Martin Pool
- Take email from ~/.bzr.conf/email
278
    """Return the full user id from a file or environment variable.
279
1074 by Martin Pool
- check for email address in BRANCH_ROOT/.bzr/email, so you can
280
    e.g. "John Hacker <jhacker@foo.org>"
281
282
    branch
283
        A branch to use for a per-branch configuration, or None.
284
285
    The following are searched in order:
286
287
    1. $BZREMAIL
288
    2. .bzr/email for this branch.
289
    3. ~/.bzr.conf/email
290
    4. $EMAIL
291
    """
252 by Martin Pool
- Don't use host fqdn for default user name, because DNS tends
292
    v = os.environ.get('BZREMAIL')
293
    if v:
294
        return v.decode(bzrlib.user_encoding)
1074 by Martin Pool
- check for email address in BRANCH_ROOT/.bzr/email, so you can
295
296
    if branch:
297
        try:
298
            return (branch.controlfile("email", "r") 
299
                    .read()
300
                    .decode(bzrlib.user_encoding)
301
                    .rstrip("\r\n"))
302
        except IOError, e:
303
            if e.errno != errno.ENOENT:
304
                raise
305
        except BzrError, e:
306
            pass
252 by Martin Pool
- Don't use host fqdn for default user name, because DNS tends
307
    
308
    try:
258 by Martin Pool
- Take email from ~/.bzr.conf/email
309
        return (open(os.path.join(config_dir(), "email"))
252 by Martin Pool
- Don't use host fqdn for default user name, because DNS tends
310
                .read()
311
                .decode(bzrlib.user_encoding)
312
                .rstrip("\r\n"))
256 by Martin Pool
- More handling of auto-username case
313
    except IOError, e:
314
        if e.errno != errno.ENOENT:
252 by Martin Pool
- Don't use host fqdn for default user name, because DNS tends
315
            raise e
316
317
    v = os.environ.get('EMAIL')
318
    if v:
319
        return v.decode(bzrlib.user_encoding)
320
    else:    
321
        return None
246 by mbp at sourcefrog
- unicode decoding in getting email and userid strings
322
323
1074 by Martin Pool
- check for email address in BRANCH_ROOT/.bzr/email, so you can
324
def username(branch):
246 by mbp at sourcefrog
- unicode decoding in getting email and userid strings
325
    """Return email-style username.
326
327
    Something similar to 'Martin Pool <mbp@sourcefrog.net>'
328
254 by Martin Pool
- Doc cleanups from Magnus Therning
329
    TODO: Check it's reasonably well-formed.
246 by mbp at sourcefrog
- unicode decoding in getting email and userid strings
330
    """
1074 by Martin Pool
- check for email address in BRANCH_ROOT/.bzr/email, so you can
331
    v = _get_user_id(branch)
252 by Martin Pool
- Don't use host fqdn for default user name, because DNS tends
332
    if v:
333
        return v
334
    
335
    name, email = _auto_user_id()
246 by mbp at sourcefrog
- unicode decoding in getting email and userid strings
336
    if name:
337
        return '%s <%s>' % (name, email)
338
    else:
339
        return email
1 by mbp at sourcefrog
import from baz patch-364
340
341
1074 by Martin Pool
- check for email address in BRANCH_ROOT/.bzr/email, so you can
342
def user_email(branch):
1 by mbp at sourcefrog
import from baz patch-364
343
    """Return just the email component of a username."""
1074 by Martin Pool
- check for email address in BRANCH_ROOT/.bzr/email, so you can
344
    e = _get_user_id(branch)
1 by mbp at sourcefrog
import from baz patch-364
345
    if e:
1077 by Martin Pool
- avoid compiling REs at module load time
346
        m = re.search(r'[\w+.-]+@[\w+.-]+', e)
1 by mbp at sourcefrog
import from baz patch-364
347
        if not m:
694 by Martin Pool
- weed out all remaining calls to bailout() and remove the function
348
            raise BzrError("%r doesn't seem to contain a reasonable email address" % e)
1 by mbp at sourcefrog
import from baz patch-364
349
        return m.group(0)
350
252 by Martin Pool
- Don't use host fqdn for default user name, because DNS tends
351
    return _auto_user_id()[1]
1 by mbp at sourcefrog
import from baz patch-364
352
    
353
354
355
def compare_files(a, b):
356
    """Returns true if equal in contents"""
74 by mbp at sourcefrog
compare_files: read in one page at a time rather than
357
    BUFSIZE = 4096
358
    while True:
359
        ai = a.read(BUFSIZE)
360
        bi = b.read(BUFSIZE)
361
        if ai != bi:
362
            return False
363
        if ai == '':
364
            return True
1 by mbp at sourcefrog
import from baz patch-364
365
366
367
49 by mbp at sourcefrog
fix local-time-offset calculation
368
def local_time_offset(t=None):
369
    """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
370
    # python2.3 localtime() can't take None
183 by mbp at sourcefrog
pychecker fixups
371
    if t == None:
73 by mbp at sourcefrog
fix time.localtime call for python 2.3
372
        t = time.time()
373
        
49 by mbp at sourcefrog
fix local-time-offset calculation
374
    if time.localtime(t).tm_isdst and time.daylight:
8 by mbp at sourcefrog
store committer's timezone in revision and show
375
        return -time.altzone
376
    else:
377
        return -time.timezone
378
379
    
380
def format_date(t, offset=0, timezone='original'):
1 by mbp at sourcefrog
import from baz patch-364
381
    ## TODO: Perhaps a global option to use either universal or local time?
382
    ## Or perhaps just let people set $TZ?
383
    assert isinstance(t, float)
384
    
8 by mbp at sourcefrog
store committer's timezone in revision and show
385
    if timezone == 'utc':
1 by mbp at sourcefrog
import from baz patch-364
386
        tt = time.gmtime(t)
387
        offset = 0
8 by mbp at sourcefrog
store committer's timezone in revision and show
388
    elif timezone == 'original':
23 by mbp at sourcefrog
format_date: handle revisions with no timezone offset
389
        if offset == None:
390
            offset = 0
16 by mbp at sourcefrog
fix inverted calculation for original timezone -> utc
391
        tt = time.gmtime(t + offset)
12 by mbp at sourcefrog
new --timezone option for bzr log
392
    elif timezone == 'local':
1 by mbp at sourcefrog
import from baz patch-364
393
        tt = time.localtime(t)
49 by mbp at sourcefrog
fix local-time-offset calculation
394
        offset = local_time_offset(t)
12 by mbp at sourcefrog
new --timezone option for bzr log
395
    else:
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
396
        raise BzrError("unsupported timezone format %r" % timezone,
397
                       ['options are "utc", "original", "local"'])
8 by mbp at sourcefrog
store committer's timezone in revision and show
398
1 by mbp at sourcefrog
import from baz patch-364
399
    return (time.strftime("%a %Y-%m-%d %H:%M:%S", tt)
8 by mbp at sourcefrog
store committer's timezone in revision and show
400
            + ' %+03d%02d' % (offset / 3600, (offset / 60) % 60))
1 by mbp at sourcefrog
import from baz patch-364
401
402
403
def compact_date(when):
404
    return time.strftime('%Y%m%d%H%M%S', time.gmtime(when))
405
    
406
407
408
def filesize(f):
409
    """Return size of given open file."""
410
    return os.fstat(f.fileno())[ST_SIZE]
411
412
413
if hasattr(os, 'urandom'): # python 2.4 and later
414
    rand_bytes = os.urandom
444 by Martin Pool
- cope on platforms with no urandom feature
415
elif sys.platform == 'linux2':
416
    rand_bytes = file('/dev/urandom', 'rb').read
1 by mbp at sourcefrog
import from baz patch-364
417
else:
444 by Martin Pool
- cope on platforms with no urandom feature
418
    # not well seeded, but better than nothing
419
    def rand_bytes(n):
420
        import random
421
        s = ''
422
        while n:
423
            s += chr(random.randint(0, 255))
424
            n -= 1
425
        return s
1 by mbp at sourcefrog
import from baz patch-364
426
427
428
## TODO: We could later have path objects that remember their list
429
## decomposition (might be too tricksy though.)
430
431
def splitpath(p):
432
    """Turn string into list of parts.
433
434
    >>> splitpath('a')
435
    ['a']
436
    >>> splitpath('a/b')
437
    ['a', 'b']
438
    >>> splitpath('a/./b')
439
    ['a', 'b']
440
    >>> splitpath('a/.b')
441
    ['a', '.b']
442
    >>> splitpath('a/../b')
184 by mbp at sourcefrog
pychecker fixups
443
    Traceback (most recent call last):
1 by mbp at sourcefrog
import from baz patch-364
444
    ...
694 by Martin Pool
- weed out all remaining calls to bailout() and remove the function
445
    BzrError: sorry, '..' not allowed in path
1 by mbp at sourcefrog
import from baz patch-364
446
    """
447
    assert isinstance(p, types.StringTypes)
271 by Martin Pool
- Windows path fixes
448
449
    # split on either delimiter because people might use either on
450
    # Windows
451
    ps = re.split(r'[\\/]', p)
452
453
    rps = []
1 by mbp at sourcefrog
import from baz patch-364
454
    for f in ps:
455
        if f == '..':
694 by Martin Pool
- weed out all remaining calls to bailout() and remove the function
456
            raise BzrError("sorry, %r not allowed in path" % f)
271 by Martin Pool
- Windows path fixes
457
        elif (f == '.') or (f == ''):
458
            pass
459
        else:
460
            rps.append(f)
461
    return rps
1 by mbp at sourcefrog
import from baz patch-364
462
463
def joinpath(p):
464
    assert isinstance(p, list)
465
    for f in p:
183 by mbp at sourcefrog
pychecker fixups
466
        if (f == '..') or (f == None) or (f == ''):
694 by Martin Pool
- weed out all remaining calls to bailout() and remove the function
467
            raise BzrError("sorry, %r not allowed in path" % f)
271 by Martin Pool
- Windows path fixes
468
    return os.path.join(*p)
1 by mbp at sourcefrog
import from baz patch-364
469
470
471
def appendpath(p1, p2):
472
    if p1 == '':
473
        return p2
474
    else:
271 by Martin Pool
- Windows path fixes
475
        return os.path.join(p1, p2)
1 by mbp at sourcefrog
import from baz patch-364
476
    
477
478
def extern_command(cmd, ignore_errors = False):
479
    mutter('external command: %s' % `cmd`)
480
    if os.system(cmd):
481
        if not ignore_errors:
694 by Martin Pool
- weed out all remaining calls to bailout() and remove the function
482
            raise BzrError('command failed')
1 by mbp at sourcefrog
import from baz patch-364
483
763 by Martin Pool
- Patch from Torsten Marek to take commit messages through an
484
485
def _read_config_value(name):
486
    """Read a config value from the file ~/.bzr.conf/<name>
487
    Return None if the file does not exist"""
488
    try:
489
        f = file(os.path.join(config_dir(), name), "r")
490
        return f.read().decode(bzrlib.user_encoding).rstrip("\r\n")
491
    except IOError, e:
492
        if e.errno == errno.ENOENT:
493
            return None
494
        raise
495
496
1231 by Martin Pool
- more progress on fetch on top of weaves
497
498
def split_lines(s):
499
    """Split s into lines, but without removing the newline characters."""
500
    return StringIO(s).readlines()
501