~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

  • Committer: Martin Pool
  • Date: 2005-07-15 22:55:36 UTC
  • Revision ID: mbp@sourcefrog.net-20050715225536-47d68404108e4eb8
- shell script to set up a weave merge test case

Show diffs side-by-side

added added

removed removed

Lines of Context:
39
39
 
40
40
_QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/_~-])')
41
41
def quotefn(f):
42
 
    """Return shell-quoted filename"""
43
 
    ## We could be a bit more terse by using double-quotes etc
44
 
    f = _QUOTE_RE.sub(r'\\\1', f)
45
 
    if f[0] == '~':
46
 
        f[0:1] = r'\~' 
47
 
    return f
 
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
48
51
 
49
52
 
50
53
def file_kind(f):
71
74
 
72
75
 
73
76
 
 
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
def rename(path_from, path_to):
 
102
    """Basically the same as os.rename() just special for win32"""
 
103
    if sys.platform == 'win32':
 
104
        try:
 
105
            os.remove(path_to)
 
106
        except OSError, e:
 
107
            if e.errno != e.ENOENT:
 
108
                raise
 
109
    os.rename(path_from, path_to)
 
110
 
 
111
 
 
112
 
 
113
 
 
114
 
74
115
def isdir(f):
75
116
    """True if f is an accessible directory."""
76
117
    try:
384
425
        if not ignore_errors:
385
426
            raise BzrError('command failed')
386
427
 
 
428
 
 
429
def _read_config_value(name):
 
430
    """Read a config value from the file ~/.bzr.conf/<name>
 
431
    Return None if the file does not exist"""
 
432
    try:
 
433
        f = file(os.path.join(config_dir(), name), "r")
 
434
        return f.read().decode(bzrlib.user_encoding).rstrip("\r\n")
 
435
    except IOError, e:
 
436
        if e.errno == errno.ENOENT:
 
437
            return None
 
438
        raise
 
439
 
 
440
 
 
441
def _get_editor():
 
442
    """Return a sequence of possible editor binaries for the current platform"""
 
443
    e = _read_config_value("editor")
 
444
    if e is not None:
 
445
        yield e
 
446
        
 
447
    if os.name == "windows":
 
448
        yield "notepad.exe"
 
449
    elif os.name == "posix":
 
450
        try:
 
451
            yield os.environ["EDITOR"]
 
452
        except KeyError:
 
453
            yield "/usr/bin/vi"
 
454
 
 
455
 
 
456
def _run_editor(filename):
 
457
    """Try to execute an editor to edit the commit message. Returns True on success,
 
458
    False on failure"""
 
459
    for e in _get_editor():
 
460
        x = os.spawnvp(os.P_WAIT, e, (e, filename))
 
461
        if x == 0:
 
462
            return True
 
463
        elif x == 127:
 
464
            continue
 
465
        else:
 
466
            break
 
467
    raise BzrError("Could not start any editor. Please specify $EDITOR or use ~/.bzr.conf/editor")
 
468
    return False
 
469
                          
 
470
 
 
471
def get_text_message(infotext, ignoreline = "default"):
 
472
    import tempfile
 
473
    
 
474
    if ignoreline == "default":
 
475
        ignoreline = "-- This line and the following will be ignored --"
 
476
        
 
477
    try:
 
478
        tmp_fileno, msgfilename = tempfile.mkstemp()
 
479
        msgfile = os.close(tmp_fileno)
 
480
        if infotext is not None and infotext != "":
 
481
            hasinfo = True
 
482
            msgfile = file(msgfilename, "w")
 
483
            msgfile.write("\n\n%s\n\n%s" % (ignoreline, infotext))
 
484
            msgfile.close()
 
485
        else:
 
486
            hasinfo = False
 
487
 
 
488
        if not _run_editor(msgfilename):
 
489
            return None
 
490
        
 
491
        started = False
 
492
        msg = []
 
493
        lastline, nlines = 0, 0
 
494
        for line in file(msgfilename, "r"):
 
495
            stripped_line = line.strip()
 
496
            # strip empty line before the log message starts
 
497
            if not started:
 
498
                if stripped_line != "":
 
499
                    started = True
 
500
                else:
 
501
                    continue
 
502
            # check for the ignore line only if there
 
503
            # is additional information at the end
 
504
            if hasinfo and stripped_line == ignoreline:
 
505
                break
 
506
            nlines += 1
 
507
            # keep track of the last line that had some content
 
508
            if stripped_line != "":
 
509
                lastline = nlines
 
510
            msg.append(line)
 
511
            
 
512
        if len(msg) == 0:
 
513
            return None
 
514
        # delete empty lines at the end
 
515
        del msg[lastline:]
 
516
        # add a newline at the end, if needed
 
517
        if not msg[-1].endswith("\n"):
 
518
            return "%s%s" % ("".join(msg), "\n")
 
519
        else:
 
520
            return "".join(msg)
 
521
    finally:
 
522
        # delete the msg file in any case
 
523
        try: os.unlink(msgfilename)
 
524
        except IOError: pass