/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

  • Committer: Robert Collins
  • Date: 2005-09-27 07:24:40 UTC
  • mfrom: (1185.1.41)
  • Revision ID: robertc@robertcollins.net-20050927072440-1bf4d99c3e1db5b3
pair programming worx... merge integration and weave

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
# Bazaar-NG -- distributed version control
2
 
 
 
2
#
3
3
# Copyright (C) 2005 by Canonical Ltd
4
 
 
 
4
#
5
5
# This program is free software; you can redistribute it and/or modify
6
6
# it under the terms of the GNU General Public License as published by
7
7
# the Free Software Foundation; either version 2 of the License, or
8
8
# (at your option) any later version.
9
 
 
 
9
#
10
10
# This program is distributed in the hope that it will be useful,
11
11
# but WITHOUT ANY WARRANTY; without even the implied warranty of
12
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
13
# GNU General Public License for more details.
14
 
 
 
14
#
15
15
# You should have received a copy of the GNU General Public License
16
16
# along with this program; if not, write to the Free Software
17
17
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18
18
 
19
 
import os, types, re, time, errno, sys
20
 
from stat import S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE
 
19
from stat import (S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE,
 
20
                  S_ISCHR, S_ISBLK, S_ISFIFO, S_ISSOCK)
 
21
from cStringIO import StringIO
 
22
import errno
 
23
import os
 
24
import re
 
25
import sha
 
26
import sys
 
27
import time
 
28
import types
21
29
 
 
30
import bzrlib
22
31
from bzrlib.errors import BzrError
23
32
from bzrlib.trace import mutter
24
 
import bzrlib
 
33
 
25
34
 
26
35
def make_readonly(filename):
27
36
    """Make a filename read-only."""
28
 
    # TODO: probably needs to be fixed for windows
29
37
    mod = os.stat(filename).st_mode
30
38
    mod = mod & 0777555
31
39
    os.chmod(filename, mod)
37
45
    os.chmod(filename, mod)
38
46
 
39
47
 
40
 
_QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/_~-])')
 
48
_QUOTE_RE = None
41
49
 
42
 
_SLASH_RE = re.compile(r'[\\/]+')
43
50
 
44
51
def quotefn(f):
45
52
    """Return a quoted filename filename
47
54
    This previously used backslash quoting, but that works poorly on
48
55
    Windows."""
49
56
    # TODO: I'm not really sure this is the best format either.x
 
57
    global _QUOTE_RE
 
58
    if _QUOTE_RE == None:
 
59
        _QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/\\_~-])')
 
60
        
50
61
    if _QUOTE_RE.search(f):
51
62
        return '"' + f + '"'
52
63
    else:
61
72
        return 'directory'
62
73
    elif S_ISLNK(mode):
63
74
        return 'symlink'
 
75
    elif S_ISCHR(mode):
 
76
        return 'chardev'
 
77
    elif S_ISBLK(mode):
 
78
        return 'block'
 
79
    elif S_ISFIFO(mode):
 
80
        return 'fifo'
 
81
    elif S_ISSOCK(mode):
 
82
        return 'socket'
64
83
    else:
65
 
        raise BzrError("can't handle file kind with mode %o of %r" % (mode, f))
 
84
        return 'unknown'
66
85
 
67
86
 
68
87
def kind_marker(kind):
76
95
        raise BzrError('invalid file kind %r' % kind)
77
96
 
78
97
 
79
 
 
80
98
def backup_file(fn):
81
99
    """Copy a file to a backup.
82
100
 
84
102
 
85
103
    If the file is already a backup, it's not copied.
86
104
    """
87
 
    import os
88
105
    if fn[-1] == '~':
89
106
        return
90
107
    bfn = fn + '~'
101
118
    finally:
102
119
        outf.close()
103
120
 
104
 
def rename(path_from, path_to):
105
 
    """Basically the same as os.rename() just special for win32"""
106
 
    if sys.platform == 'win32':
107
 
        try:
108
 
            os.remove(path_to)
109
 
        except OSError, e:
110
 
            if e.errno != e.ENOENT:
111
 
                raise
112
 
    os.rename(path_from, path_to)
113
 
 
114
 
 
115
 
 
 
121
if os.name == 'nt':
 
122
    import shutil
 
123
    rename = shutil.move
 
124
else:
 
125
    rename = os.rename
116
126
 
117
127
 
118
128
def isdir(f):
123
133
        return False
124
134
 
125
135
 
126
 
 
127
136
def isfile(f):
128
137
    """True if f is a regular file."""
129
138
    try:
142
151
    The empty string as a dir name is taken as top-of-tree and matches 
143
152
    everything.
144
153
    
145
 
    >>> is_inside('src', 'src/foo.c')
 
154
    >>> is_inside('src', os.path.join('src', 'foo.c'))
146
155
    True
147
156
    >>> is_inside('src', 'srccontrol')
148
157
    False
149
 
    >>> is_inside('src', 'src/a/a/a/foo.c')
 
158
    >>> is_inside('src', os.path.join('src', 'a', 'a', 'a', 'foo.c'))
150
159
    True
151
160
    >>> is_inside('foo.c', 'foo.c')
152
161
    True
162
171
    
163
172
    if dir == '':
164
173
        return True
165
 
    
 
174
 
166
175
    if dir[-1] != os.sep:
167
176
        dir += os.sep
168
 
    
 
177
 
169
178
    return fname.startswith(dir)
170
179
 
171
180
 
183
192
    tofile.write(fromfile.read())
184
193
 
185
194
 
186
 
def uuid():
187
 
    """Return a new UUID"""
188
 
    try:
189
 
        return file('/proc/sys/kernel/random/uuid').readline().rstrip('\n')
190
 
    except IOError:
191
 
        return chomp(os.popen('uuidgen').readline())
192
 
 
193
 
 
194
195
def sha_file(f):
195
 
    import sha
196
196
    if hasattr(f, 'tell'):
197
197
        assert f.tell() == 0
198
198
    s = sha.new()
205
205
    return s.hexdigest()
206
206
 
207
207
 
 
208
 
 
209
def sha_strings(strings):
 
210
    """Return the sha-1 of concatenation of strings"""
 
211
    s = sha.new()
 
212
    map(s.update, strings)
 
213
    return s.hexdigest()
 
214
 
 
215
 
208
216
def sha_string(f):
209
 
    import sha
210
217
    s = sha.new()
211
218
    s.update(f)
212
219
    return s.hexdigest()
213
220
 
214
221
 
215
 
 
216
222
def fingerprint_file(f):
217
 
    import sha
218
223
    s = sha.new()
219
224
    b = f.read()
220
225
    s.update(b)
230
235
    
231
236
    TODO: Global option --config-dir to override this.
232
237
    """
233
 
    return os.path.expanduser("~/.bzr.conf")
 
238
    return os.path.join(os.path.expanduser("~"), ".bzr.conf")
234
239
 
235
240
 
236
241
def _auto_user_id():
269
274
    return realname, (username + '@' + socket.gethostname())
270
275
 
271
276
 
272
 
def _get_user_id():
 
277
def _get_user_id(branch):
273
278
    """Return the full user id from a file or environment variable.
274
279
 
275
 
    TODO: Allow taking this from a file in the branch directory too
276
 
    for per-branch ids."""
 
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
    """
277
292
    v = os.environ.get('BZREMAIL')
278
293
    if v:
279
294
        return v.decode(bzrlib.user_encoding)
 
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
280
307
    
281
308
    try:
282
309
        return (open(os.path.join(config_dir(), "email"))
294
321
        return None
295
322
 
296
323
 
297
 
def username():
 
324
def username(branch):
298
325
    """Return email-style username.
299
326
 
300
327
    Something similar to 'Martin Pool <mbp@sourcefrog.net>'
301
328
 
302
329
    TODO: Check it's reasonably well-formed.
303
330
    """
304
 
    v = _get_user_id()
 
331
    v = _get_user_id(branch)
305
332
    if v:
306
333
        return v
307
334
    
312
339
        return email
313
340
 
314
341
 
315
 
_EMAIL_RE = re.compile(r'[\w+.-]+@[\w+.-]+')
316
 
def user_email():
 
342
def user_email(branch):
317
343
    """Return just the email component of a username."""
318
 
    e = _get_user_id()
 
344
    e = _get_user_id(branch)
319
345
    if e:
320
 
        m = _EMAIL_RE.search(e)
 
346
        m = re.search(r'[\w+.-]+@[\w+.-]+', e)
321
347
        if not m:
322
 
            raise BzrError("%r doesn't seem to contain a reasonable email address" % e)
 
348
            raise BzrError("%r doesn't seem to contain "
 
349
                           "a reasonable email address" % e)
323
350
        return m.group(0)
324
351
 
325
352
    return _auto_user_id()[1]
326
 
    
327
353
 
328
354
 
329
355
def compare_files(a, b):
338
364
            return True
339
365
 
340
366
 
341
 
 
342
367
def local_time_offset(t=None):
343
368
    """Return offset of local zone from GMT, either at present or at time t."""
344
369
    # python2.3 localtime() can't take None
383
408
    """Return size of given open file."""
384
409
    return os.fstat(f.fileno())[ST_SIZE]
385
410
 
386
 
 
387
 
if hasattr(os, 'urandom'): # python 2.4 and later
 
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)
388
416
    rand_bytes = os.urandom
389
 
elif sys.platform == 'linux2':
390
 
    rand_bytes = file('/dev/urandom', 'rb').read
391
 
else:
392
 
    # not well seeded, but better than nothing
393
 
    def rand_bytes(n):
394
 
        import random
395
 
        s = ''
396
 
        while n:
397
 
            s += chr(random.randint(0, 255))
398
 
            n -= 1
399
 
        return s
400
 
 
 
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
401
432
 
402
433
## TODO: We could later have path objects that remember their list
403
434
## decomposition (might be too tricksy though.)
468
499
        raise
469
500
 
470
501
 
471
 
def _get_editor():
472
 
    """Return a sequence of possible editor binaries for the current platform"""
473
 
    e = _read_config_value("editor")
474
 
    if e is not None:
475
 
        yield e
476
 
        
477
 
    if os.name == "windows":
478
 
        yield "notepad.exe"
479
 
    elif os.name == "posix":
480
 
        try:
481
 
            yield os.environ["EDITOR"]
482
 
        except KeyError:
483
 
            yield "/usr/bin/vi"
484
 
 
485
 
 
486
 
def _run_editor(filename):
487
 
    """Try to execute an editor to edit the commit message. Returns True on success,
488
 
    False on failure"""
489
 
    for e in _get_editor():
490
 
        x = os.spawnvp(os.P_WAIT, e, (e, filename))
491
 
        if x == 0:
492
 
            return True
493
 
        elif x == 127:
494
 
            continue
495
 
        else:
496
 
            break
497
 
    raise BzrError("Could not start any editor. Please specify $EDITOR or use ~/.bzr.conf/editor")
498
 
    return False
499
 
                          
500
 
 
501
 
def get_text_message(infotext, ignoreline = "default"):
502
 
    import tempfile
503
 
    
504
 
    if ignoreline == "default":
505
 
        ignoreline = "-- This line and the following will be ignored --"
506
 
        
507
 
    try:
508
 
        tmp_fileno, msgfilename = tempfile.mkstemp()
509
 
        msgfile = os.close(tmp_fileno)
510
 
        if infotext is not None and infotext != "":
511
 
            hasinfo = True
512
 
            msgfile = file(msgfilename, "w")
513
 
            msgfile.write("\n\n%s\n\n%s" % (ignoreline, infotext))
514
 
            msgfile.close()
515
 
        else:
516
 
            hasinfo = False
517
 
 
518
 
        if not _run_editor(msgfilename):
519
 
            return None
520
 
        
521
 
        started = False
522
 
        msg = []
523
 
        lastline, nlines = 0, 0
524
 
        for line in file(msgfilename, "r"):
525
 
            stripped_line = line.strip()
526
 
            # strip empty line before the log message starts
527
 
            if not started:
528
 
                if stripped_line != "":
529
 
                    started = True
530
 
                else:
531
 
                    continue
532
 
            # check for the ignore line only if there
533
 
            # is additional information at the end
534
 
            if hasinfo and stripped_line == ignoreline:
535
 
                break
536
 
            nlines += 1
537
 
            # keep track of the last line that had some content
538
 
            if stripped_line != "":
539
 
                lastline = nlines
540
 
            msg.append(line)
541
 
            
542
 
        if len(msg) == 0:
543
 
            return None
544
 
        # delete empty lines at the end
545
 
        del msg[lastline:]
546
 
        # add a newline at the end, if needed
547
 
        if not msg[-1].endswith("\n"):
548
 
            return "%s%s" % ("".join(msg), "\n")
549
 
        else:
550
 
            return "".join(msg)
551
 
    finally:
552
 
        # delete the msg file in any case
553
 
        try: os.unlink(msgfilename)
554
 
        except IOError: pass
 
502
def split_lines(s):
 
503
    """Split s into lines, but without removing the newline characters."""
 
504
    return StringIO(s).readlines()