~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

  • Committer: Martin Pool
  • Date: 2005-09-16 09:56:24 UTC
  • Revision ID: mbp@sourcefrog.net-20050916095623-ca0dff452934f21f
- make progress bar more tolerant of out-of-range values

Show diffs side-by-side

added added

removed removed

Lines of Context:
17
17
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18
18
 
19
19
import os, types, re, time, errno, sys
 
20
import sha
 
21
from cStringIO import StringIO
 
22
 
20
23
from stat import S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE
21
24
 
22
25
from bzrlib.errors import BzrError
37
40
    os.chmod(filename, mod)
38
41
 
39
42
 
40
 
_QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/_~-])')
 
43
_QUOTE_RE = None
41
44
 
42
 
_SLASH_RE = re.compile(r'[\\/]+')
43
45
 
44
46
def quotefn(f):
45
47
    """Return a quoted filename filename
47
49
    This previously used backslash quoting, but that works poorly on
48
50
    Windows."""
49
51
    # TODO: I'm not really sure this is the best format either.x
 
52
    global _QUOTE_RE
 
53
    if _QUOTE_RE == None:
 
54
        _QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/_~-])')
 
55
        
50
56
    if _QUOTE_RE.search(f):
51
57
        return '"' + f + '"'
52
58
    else:
84
90
 
85
91
    If the file is already a backup, it's not copied.
86
92
    """
87
 
    import os
88
93
    if fn[-1] == '~':
89
94
        return
90
95
    bfn = fn + '~'
139
144
    that . and .. and repeated slashes are eliminated, and the separators
140
145
    are canonical for the platform.
141
146
    
 
147
    The empty string as a dir name is taken as top-of-tree and matches 
 
148
    everything.
 
149
    
142
150
    >>> is_inside('src', 'src/foo.c')
143
151
    True
144
152
    >>> is_inside('src', 'srccontrol')
147
155
    True
148
156
    >>> is_inside('foo.c', 'foo.c')
149
157
    True
 
158
    >>> is_inside('foo.c', '')
 
159
    False
 
160
    >>> is_inside('', 'foo.c')
 
161
    True
150
162
    """
151
163
    # XXX: Most callers of this can actually do something smarter by 
152
164
    # looking at the inventory
153
 
 
154
165
    if dir == fname:
155
166
        return True
156
167
    
 
168
    if dir == '':
 
169
        return True
 
170
    
157
171
    if dir[-1] != os.sep:
158
172
        dir += os.sep
159
173
    
183
197
 
184
198
 
185
199
def sha_file(f):
186
 
    import sha
187
200
    if hasattr(f, 'tell'):
188
201
        assert f.tell() == 0
189
202
    s = sha.new()
196
209
    return s.hexdigest()
197
210
 
198
211
 
 
212
 
 
213
def sha_strings(strings):
 
214
    """Return the sha-1 of concatenation of strings"""
 
215
    s = sha.new()
 
216
    map(s.update, strings)
 
217
    return s.hexdigest()
 
218
 
 
219
 
199
220
def sha_string(f):
200
 
    import sha
201
221
    s = sha.new()
202
222
    s.update(f)
203
223
    return s.hexdigest()
205
225
 
206
226
 
207
227
def fingerprint_file(f):
208
 
    import sha
209
228
    s = sha.new()
210
229
    b = f.read()
211
230
    s.update(b)
260
279
    return realname, (username + '@' + socket.gethostname())
261
280
 
262
281
 
263
 
def _get_user_id():
 
282
def _get_user_id(branch):
264
283
    """Return the full user id from a file or environment variable.
265
284
 
266
 
    TODO: Allow taking this from a file in the branch directory too
267
 
    for per-branch ids."""
 
285
    e.g. "John Hacker <jhacker@foo.org>"
 
286
 
 
287
    branch
 
288
        A branch to use for a per-branch configuration, or None.
 
289
 
 
290
    The following are searched in order:
 
291
 
 
292
    1. $BZREMAIL
 
293
    2. .bzr/email for this branch.
 
294
    3. ~/.bzr.conf/email
 
295
    4. $EMAIL
 
296
    """
268
297
    v = os.environ.get('BZREMAIL')
269
298
    if v:
270
299
        return v.decode(bzrlib.user_encoding)
 
300
 
 
301
    if branch:
 
302
        try:
 
303
            return (branch.controlfile("email", "r") 
 
304
                    .read()
 
305
                    .decode(bzrlib.user_encoding)
 
306
                    .rstrip("\r\n"))
 
307
        except IOError, e:
 
308
            if e.errno != errno.ENOENT:
 
309
                raise
 
310
        except BzrError, e:
 
311
            pass
271
312
    
272
313
    try:
273
314
        return (open(os.path.join(config_dir(), "email"))
285
326
        return None
286
327
 
287
328
 
288
 
def username():
 
329
def username(branch):
289
330
    """Return email-style username.
290
331
 
291
332
    Something similar to 'Martin Pool <mbp@sourcefrog.net>'
292
333
 
293
334
    TODO: Check it's reasonably well-formed.
294
335
    """
295
 
    v = _get_user_id()
 
336
    v = _get_user_id(branch)
296
337
    if v:
297
338
        return v
298
339
    
303
344
        return email
304
345
 
305
346
 
306
 
_EMAIL_RE = re.compile(r'[\w+.-]+@[\w+.-]+')
307
 
def user_email():
 
347
def user_email(branch):
308
348
    """Return just the email component of a username."""
309
 
    e = _get_user_id()
 
349
    e = _get_user_id(branch)
310
350
    if e:
311
 
        m = _EMAIL_RE.search(e)
 
351
        m = re.search(r'[\w+.-]+@[\w+.-]+', e)
312
352
        if not m:
313
353
            raise BzrError("%r doesn't seem to contain a reasonable email address" % e)
314
354
        return m.group(0)
358
398
        tt = time.localtime(t)
359
399
        offset = local_time_offset(t)
360
400
    else:
361
 
        raise BzrError("unsupported timezone format %r",
362
 
                ['options are "utc", "original", "local"'])
 
401
        raise BzrError("unsupported timezone format %r" % timezone,
 
402
                       ['options are "utc", "original", "local"'])
363
403
 
364
404
    return (time.strftime("%a %Y-%m-%d %H:%M:%S", tt)
365
405
            + ' %+03d%02d' % (offset / 3600, (offset / 60) % 60))
459
499
        raise
460
500
 
461
501
 
462
 
def _get_editor():
463
 
    """Return a sequence of possible editor binaries for the current platform"""
464
 
    e = _read_config_value("editor")
465
 
    if e is not None:
466
 
        yield e
467
 
        
468
 
    if os.name == "windows":
469
 
        yield "notepad.exe"
470
 
    elif os.name == "posix":
471
 
        try:
472
 
            yield os.environ["EDITOR"]
473
 
        except KeyError:
474
 
            yield "/usr/bin/vi"
475
 
 
476
 
 
477
 
def _run_editor(filename):
478
 
    """Try to execute an editor to edit the commit message. Returns True on success,
479
 
    False on failure"""
480
 
    for e in _get_editor():
481
 
        x = os.spawnvp(os.P_WAIT, e, (e, filename))
482
 
        if x == 0:
483
 
            return True
484
 
        elif x == 127:
485
 
            continue
486
 
        else:
487
 
            break
488
 
    raise BzrError("Could not start any editor. Please specify $EDITOR or use ~/.bzr.conf/editor")
489
 
    return False
490
 
                          
491
 
 
492
 
def get_text_message(infotext, ignoreline = "default"):
493
 
    import tempfile
 
502
 
 
503
def split_lines(s):
 
504
    """Split s into lines, but without removing the newline characters."""
 
505
    return StringIO(s).readlines()
494
506
    
495
 
    if ignoreline == "default":
496
 
        ignoreline = "-- This line and the following will be ignored --"
497
 
        
498
 
    try:
499
 
        tmp_fileno, msgfilename = tempfile.mkstemp()
500
 
        msgfile = os.close(tmp_fileno)
501
 
        if infotext is not None and infotext != "":
502
 
            hasinfo = True
503
 
            msgfile = file(msgfilename, "w")
504
 
            msgfile.write("\n\n%s\n\n%s" % (ignoreline, infotext))
505
 
            msgfile.close()
506
 
        else:
507
 
            hasinfo = False
508
 
 
509
 
        if not _run_editor(msgfilename):
510
 
            return None
511
 
        
512
 
        started = False
513
 
        msg = []
514
 
        lastline, nlines = 0, 0
515
 
        for line in file(msgfilename, "r"):
516
 
            stripped_line = line.strip()
517
 
            # strip empty line before the log message starts
518
 
            if not started:
519
 
                if stripped_line != "":
520
 
                    started = True
521
 
                else:
522
 
                    continue
523
 
            # check for the ignore line only if there
524
 
            # is additional information at the end
525
 
            if hasinfo and stripped_line == ignoreline:
526
 
                break
527
 
            nlines += 1
528
 
            # keep track of the last line that had some content
529
 
            if stripped_line != "":
530
 
                lastline = nlines
531
 
            msg.append(line)
532
 
            
533
 
        if len(msg) == 0:
534
 
            return None
535
 
        # delete empty lines at the end
536
 
        del msg[lastline:]
537
 
        # add a newline at the end, if needed
538
 
        if not msg[-1].endswith("\n"):
539
 
            return "%s%s" % ("".join(msg), "\n")
540
 
        else:
541
 
            return "".join(msg)
542
 
    finally:
543
 
        # delete the msg file in any case
544
 
        try: os.unlink(msgfilename)
545
 
        except IOError: pass