/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: Martin Pool
  • Date: 2005-09-13 08:06:58 UTC
  • Revision ID: mbp@sourcefrog.net-20050913080658-17f1ec4336b71c51
- run weave tests from bzr selftest

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
from cStringIO import StringIO
 
21
 
20
22
from stat import S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE
21
23
 
22
24
from bzrlib.errors import BzrError
37
39
    os.chmod(filename, mod)
38
40
 
39
41
 
40
 
_QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/_~-])')
 
42
_QUOTE_RE = None
41
43
 
42
 
_SLASH_RE = re.compile(r'[\\/]+')
43
44
 
44
45
def quotefn(f):
45
46
    """Return a quoted filename filename
47
48
    This previously used backslash quoting, but that works poorly on
48
49
    Windows."""
49
50
    # TODO: I'm not really sure this is the best format either.x
 
51
    global _QUOTE_RE
 
52
    if _QUOTE_RE == None:
 
53
        _QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/_~-])')
 
54
        
50
55
    if _QUOTE_RE.search(f):
51
56
        return '"' + f + '"'
52
57
    else:
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
348
            raise BzrError("%r doesn't seem to contain a reasonable email address" % e)
323
349
        return m.group(0)
468
494
        raise
469
495
 
470
496
 
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
 
497
 
 
498
def split_lines(s):
 
499
    """Split s into lines, but without removing the newline characters."""
 
500
    return StringIO(s).readlines()
503
501
    
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