/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-28 04:58:18 UTC
  • mto: (1092.2.19)
  • mto: This revision was merged to the branch mainline in revision 1391.
  • Revision ID: robertc@robertcollins.net-20050928045818-c5ce6c7cc796f6fc
patch from Rob Weir to correct bzr-man.py

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
import errno
 
22
import os
 
23
import re
 
24
import sha
 
25
import sys
 
26
import time
 
27
import types
21
28
 
 
29
import bzrlib
22
30
from bzrlib.errors import BzrError
23
31
from bzrlib.trace import mutter
24
 
import bzrlib
 
32
 
25
33
 
26
34
def make_readonly(filename):
27
35
    """Make a filename read-only."""
28
 
    # TODO: probably needs to be fixed for windows
29
36
    mod = os.stat(filename).st_mode
30
37
    mod = mod & 0777555
31
38
    os.chmod(filename, mod)
37
44
    os.chmod(filename, mod)
38
45
 
39
46
 
40
 
_QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/_~-])')
 
47
_QUOTE_RE = None
41
48
 
42
 
_SLASH_RE = re.compile(r'[\\/]+')
43
49
 
44
50
def quotefn(f):
45
51
    """Return a quoted filename filename
47
53
    This previously used backslash quoting, but that works poorly on
48
54
    Windows."""
49
55
    # TODO: I'm not really sure this is the best format either.x
 
56
    global _QUOTE_RE
 
57
    if _QUOTE_RE == None:
 
58
        _QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/\\_~-])')
 
59
        
50
60
    if _QUOTE_RE.search(f):
51
61
        return '"' + f + '"'
52
62
    else:
61
71
        return 'directory'
62
72
    elif S_ISLNK(mode):
63
73
        return 'symlink'
 
74
    elif S_ISCHR(mode):
 
75
        return 'chardev'
 
76
    elif S_ISBLK(mode):
 
77
        return 'block'
 
78
    elif S_ISFIFO(mode):
 
79
        return 'fifo'
 
80
    elif S_ISSOCK(mode):
 
81
        return 'socket'
64
82
    else:
65
 
        raise BzrError("can't handle file kind with mode %o of %r" % (mode, f))
 
83
        return 'unknown'
66
84
 
67
85
 
68
86
def kind_marker(kind):
76
94
        raise BzrError('invalid file kind %r' % kind)
77
95
 
78
96
 
79
 
 
80
97
def backup_file(fn):
81
98
    """Copy a file to a backup.
82
99
 
84
101
 
85
102
    If the file is already a backup, it's not copied.
86
103
    """
87
 
    import os
88
104
    if fn[-1] == '~':
89
105
        return
90
106
    bfn = fn + '~'
101
117
    finally:
102
118
        outf.close()
103
119
 
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
 
 
 
120
if os.name == 'nt':
 
121
    import shutil
 
122
    rename = shutil.move
 
123
else:
 
124
    rename = os.rename
116
125
 
117
126
 
118
127
def isdir(f):
123
132
        return False
124
133
 
125
134
 
126
 
 
127
135
def isfile(f):
128
136
    """True if f is a regular file."""
129
137
    try:
142
150
    The empty string as a dir name is taken as top-of-tree and matches 
143
151
    everything.
144
152
    
145
 
    >>> is_inside('src', 'src/foo.c')
 
153
    >>> is_inside('src', os.path.join('src', 'foo.c'))
146
154
    True
147
155
    >>> is_inside('src', 'srccontrol')
148
156
    False
149
 
    >>> is_inside('src', 'src/a/a/a/foo.c')
 
157
    >>> is_inside('src', os.path.join('src', 'a', 'a', 'a', 'foo.c'))
150
158
    True
151
159
    >>> is_inside('foo.c', 'foo.c')
152
160
    True
162
170
    
163
171
    if dir == '':
164
172
        return True
165
 
    
 
173
 
166
174
    if dir[-1] != os.sep:
167
175
        dir += os.sep
168
 
    
 
176
 
169
177
    return fname.startswith(dir)
170
178
 
171
179
 
183
191
    tofile.write(fromfile.read())
184
192
 
185
193
 
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
194
def sha_file(f):
195
 
    import sha
196
195
    if hasattr(f, 'tell'):
197
196
        assert f.tell() == 0
198
197
    s = sha.new()
206
205
 
207
206
 
208
207
def sha_string(f):
209
 
    import sha
210
208
    s = sha.new()
211
209
    s.update(f)
212
210
    return s.hexdigest()
213
211
 
214
212
 
215
 
 
216
213
def fingerprint_file(f):
217
 
    import sha
218
214
    s = sha.new()
219
215
    b = f.read()
220
216
    s.update(b)
230
226
    
231
227
    TODO: Global option --config-dir to override this.
232
228
    """
233
 
    return os.path.expanduser("~/.bzr.conf")
 
229
    return os.path.join(os.path.expanduser("~"), ".bzr.conf")
234
230
 
235
231
 
236
232
def _auto_user_id():
269
265
    return realname, (username + '@' + socket.gethostname())
270
266
 
271
267
 
272
 
def _get_user_id():
 
268
def _get_user_id(branch):
273
269
    """Return the full user id from a file or environment variable.
274
270
 
275
 
    TODO: Allow taking this from a file in the branch directory too
276
 
    for per-branch ids."""
 
271
    e.g. "John Hacker <jhacker@foo.org>"
 
272
 
 
273
    branch
 
274
        A branch to use for a per-branch configuration, or None.
 
275
 
 
276
    The following are searched in order:
 
277
 
 
278
    1. $BZREMAIL
 
279
    2. .bzr/email for this branch.
 
280
    3. ~/.bzr.conf/email
 
281
    4. $EMAIL
 
282
    """
277
283
    v = os.environ.get('BZREMAIL')
278
284
    if v:
279
285
        return v.decode(bzrlib.user_encoding)
 
286
 
 
287
    if branch:
 
288
        try:
 
289
            return (branch.controlfile("email", "r") 
 
290
                    .read()
 
291
                    .decode(bzrlib.user_encoding)
 
292
                    .rstrip("\r\n"))
 
293
        except IOError, e:
 
294
            if e.errno != errno.ENOENT:
 
295
                raise
 
296
        except BzrError, e:
 
297
            pass
280
298
    
281
299
    try:
282
300
        return (open(os.path.join(config_dir(), "email"))
294
312
        return None
295
313
 
296
314
 
297
 
def username():
 
315
def username(branch):
298
316
    """Return email-style username.
299
317
 
300
318
    Something similar to 'Martin Pool <mbp@sourcefrog.net>'
301
319
 
302
320
    TODO: Check it's reasonably well-formed.
303
321
    """
304
 
    v = _get_user_id()
 
322
    v = _get_user_id(branch)
305
323
    if v:
306
324
        return v
307
325
    
312
330
        return email
313
331
 
314
332
 
315
 
_EMAIL_RE = re.compile(r'[\w+.-]+@[\w+.-]+')
316
 
def user_email():
 
333
def user_email(branch):
317
334
    """Return just the email component of a username."""
318
 
    e = _get_user_id()
 
335
    e = _get_user_id(branch)
319
336
    if e:
320
 
        m = _EMAIL_RE.search(e)
 
337
        m = re.search(r'[\w+.-]+@[\w+.-]+', e)
321
338
        if not m:
322
 
            raise BzrError("%r doesn't seem to contain a reasonable email address" % e)
 
339
            raise BzrError("%r doesn't seem to contain "
 
340
                           "a reasonable email address" % e)
323
341
        return m.group(0)
324
342
 
325
343
    return _auto_user_id()[1]
326
 
    
327
344
 
328
345
 
329
346
def compare_files(a, b):
338
355
            return True
339
356
 
340
357
 
341
 
 
342
358
def local_time_offset(t=None):
343
359
    """Return offset of local zone from GMT, either at present or at time t."""
344
360
    # python2.3 localtime() can't take None
383
399
    """Return size of given open file."""
384
400
    return os.fstat(f.fileno())[ST_SIZE]
385
401
 
386
 
 
387
 
if hasattr(os, 'urandom'): # python 2.4 and later
 
402
# Define rand_bytes based on platform.
 
403
try:
 
404
    # Python 2.4 and later have os.urandom,
 
405
    # but it doesn't work on some arches
 
406
    os.urandom(1)
388
407
    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
 
 
 
408
except (NotImplementedError, AttributeError):
 
409
    # If python doesn't have os.urandom, or it doesn't work,
 
410
    # then try to first pull random data from /dev/urandom
 
411
    if os.path.exists("/dev/urandom"):
 
412
        rand_bytes = file('/dev/urandom', 'rb').read
 
413
    # Otherwise, use this hack as a last resort
 
414
    else:
 
415
        # not well seeded, but better than nothing
 
416
        def rand_bytes(n):
 
417
            import random
 
418
            s = ''
 
419
            while n:
 
420
                s += chr(random.randint(0, 255))
 
421
                n -= 1
 
422
            return s
401
423
 
402
424
## TODO: We could later have path objects that remember their list
403
425
## decomposition (might be too tricksy though.)
466
488
        if e.errno == errno.ENOENT:
467
489
            return None
468
490
        raise
469
 
 
470
 
 
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