~bzr-pqm/bzr/bzr.dev

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