/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

Merge bzr.dev, fix minor conflict in cmd_revision_history().

Show diffs side-by-side

added added

removed removed

Lines of Context:
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
 
from shutil import copyfile
20
 
from stat import (S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE,
21
 
                  S_ISCHR, S_ISBLK, S_ISFIFO, S_ISSOCK)
22
19
from cStringIO import StringIO
23
20
import errno
24
21
import os
 
22
from os import listdir
25
23
import re
26
24
import sha
27
25
import shutil
 
26
from shutil import copyfile
 
27
import stat
 
28
from stat import (S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE,
 
29
                  S_ISCHR, S_ISBLK, S_ISFIFO, S_ISSOCK)
28
30
import string
29
31
import sys
30
32
import time
31
33
import types
32
34
import tempfile
 
35
import unicodedata
 
36
from ntpath import (abspath as _nt_abspath,
 
37
                    join as _nt_join,
 
38
                    normpath as _nt_normpath,
 
39
                    realpath as _nt_realpath,
 
40
                    )
33
41
 
34
42
import bzrlib
35
43
from bzrlib.errors import (BzrError,
38
46
                           PathNotChild,
39
47
                           IllegalPath,
40
48
                           )
 
49
from bzrlib.symbol_versioning import *
41
50
from bzrlib.trace import mutter
42
51
import bzrlib.win32console
43
52
 
74
83
        return f
75
84
 
76
85
 
77
 
def file_kind(f):
78
 
    mode = os.lstat(f)[ST_MODE]
79
 
    if S_ISREG(mode):
80
 
        return 'file'
81
 
    elif S_ISDIR(mode):
82
 
        return 'directory'
83
 
    elif S_ISLNK(mode):
84
 
        return 'symlink'
85
 
    elif S_ISCHR(mode):
86
 
        return 'chardev'
87
 
    elif S_ISBLK(mode):
88
 
        return 'block'
89
 
    elif S_ISFIFO(mode):
90
 
        return 'fifo'
91
 
    elif S_ISSOCK(mode):
92
 
        return 'socket'
93
 
    else:
94
 
        return 'unknown'
 
86
_directory_kind = 'directory'
 
87
 
 
88
_formats = {
 
89
    stat.S_IFDIR:_directory_kind,
 
90
    stat.S_IFCHR:'chardev',
 
91
    stat.S_IFBLK:'block',
 
92
    stat.S_IFREG:'file',
 
93
    stat.S_IFIFO:'fifo',
 
94
    stat.S_IFLNK:'symlink',
 
95
    stat.S_IFSOCK:'socket',
 
96
}
 
97
 
 
98
 
 
99
def file_kind_from_stat_mode(stat_mode, _formats=_formats, _unknown='unknown'):
 
100
    """Generate a file kind from a stat mode. This is used in walkdirs.
 
101
 
 
102
    Its performance is critical: Do not mutate without careful benchmarking.
 
103
    """
 
104
    try:
 
105
        return _formats[stat_mode & 0170000]
 
106
    except KeyError:
 
107
        return _unknown
 
108
 
 
109
 
 
110
def file_kind(f, _lstat=os.lstat, _mapper=file_kind_from_stat_mode):
 
111
    try:
 
112
        return _mapper(_lstat(f).st_mode)
 
113
    except OSError, e:
 
114
        if getattr(e, 'errno', None) == errno.ENOENT:
 
115
            raise bzrlib.errors.NoSuchFile(f)
 
116
        raise
95
117
 
96
118
 
97
119
def kind_marker(kind):
98
120
    if kind == 'file':
99
121
        return ''
100
 
    elif kind == 'directory':
 
122
    elif kind == _directory_kind:
101
123
        return '/'
102
124
    elif kind == 'symlink':
103
125
        return '@'
104
126
    else:
105
127
        raise BzrError('invalid file kind %r' % kind)
106
128
 
107
 
def lexists(f):
108
 
    if hasattr(os.path, 'lexists'):
109
 
        return os.path.lexists(f)
110
 
    try:
111
 
        if hasattr(os, 'lstat'):
112
 
            os.lstat(f)
113
 
        else:
114
 
            os.stat(f)
115
 
        return True
116
 
    except OSError,e:
117
 
        if e.errno == errno.ENOENT:
118
 
            return False;
119
 
        else:
120
 
            raise BzrError("lstat/stat of (%r): %r" % (f, e))
 
129
lexists = getattr(os.path, 'lexists', None)
 
130
if lexists is None:
 
131
    def lexists(f):
 
132
        try:
 
133
            if hasattr(os, 'lstat'):
 
134
                os.lstat(f)
 
135
            else:
 
136
                os.stat(f)
 
137
            return True
 
138
        except OSError,e:
 
139
            if e.errno == errno.ENOENT:
 
140
                return False;
 
141
            else:
 
142
                raise BzrError("lstat/stat of (%r): %r" % (f, e))
 
143
 
121
144
 
122
145
def fancy_rename(old, new, rename_func, unlink_func):
123
146
    """A fancy rename, when you don't have atomic rename.
173
196
            else:
174
197
                rename_func(tmp_name, new)
175
198
 
 
199
 
 
200
# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
 
201
# choke on a Unicode string containing a relative path if
 
202
# os.getcwd() returns a non-sys.getdefaultencoding()-encoded
 
203
# string.
 
204
_fs_enc = sys.getfilesystemencoding()
 
205
def _posix_abspath(path):
 
206
    return os.path.abspath(path.encode(_fs_enc)).decode(_fs_enc)
 
207
    # jam 20060426 This is another possibility which mimics 
 
208
    # os.path.abspath, only uses unicode characters instead
 
209
    # if not os.path.isabs(path):
 
210
    #     return os.path.join(os.getcwdu(), path)
 
211
    # return path
 
212
 
 
213
 
 
214
def _posix_realpath(path):
 
215
    return os.path.realpath(path.encode(_fs_enc)).decode(_fs_enc)
 
216
 
 
217
 
 
218
def _win32_abspath(path):
 
219
    return _nt_abspath(path.encode(_fs_enc)).decode(_fs_enc).replace('\\', '/')
 
220
 
 
221
 
 
222
def _win32_realpath(path):
 
223
    return _nt_realpath(path.encode(_fs_enc)).decode(_fs_enc).replace('\\', '/')
 
224
 
 
225
 
 
226
def _win32_pathjoin(*args):
 
227
    return _nt_join(*args).replace('\\', '/')
 
228
 
 
229
 
 
230
def _win32_normpath(path):
 
231
    return _nt_normpath(path).replace('\\', '/')
 
232
 
 
233
 
 
234
def _win32_getcwd():
 
235
    return os.getcwdu().replace('\\', '/')
 
236
 
 
237
 
 
238
def _win32_mkdtemp(*args, **kwargs):
 
239
    return tempfile.mkdtemp(*args, **kwargs).replace('\\', '/')
 
240
 
 
241
 
 
242
def _win32_rename(old, new):
 
243
    fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
 
244
 
 
245
 
176
246
# Default is to just use the python builtins, but these can be rebound on
177
247
# particular platforms.
178
 
abspath = os.path.abspath
179
 
realpath = os.path.realpath
 
248
abspath = _posix_abspath
 
249
realpath = _posix_realpath
180
250
pathjoin = os.path.join
181
251
normpath = os.path.normpath
182
252
getcwd = os.getcwdu
188
258
 
189
259
MIN_ABS_PATHLENGTH = 1
190
260
 
191
 
if os.name == "posix":
192
 
    # In Python 2.4.2 and older, os.path.abspath and os.path.realpath
193
 
    # choke on a Unicode string containing a relative path if
194
 
    # os.getcwd() returns a non-sys.getdefaultencoding()-encoded
195
 
    # string.
196
 
    _fs_enc = sys.getfilesystemencoding()
197
 
    def abspath(path):
198
 
        return os.path.abspath(path.encode(_fs_enc)).decode(_fs_enc)
199
 
 
200
 
    def realpath(path):
201
 
        return os.path.realpath(path.encode(_fs_enc)).decode(_fs_enc)
202
261
 
203
262
if sys.platform == 'win32':
204
 
    # We need to use the Unicode-aware os.path.abspath and
205
 
    # os.path.realpath on Windows systems.
206
 
    def abspath(path):
207
 
        return os.path.abspath(path).replace('\\', '/')
208
 
 
209
 
    def realpath(path):
210
 
        return os.path.realpath(path).replace('\\', '/')
211
 
 
212
 
    def pathjoin(*args):
213
 
        return os.path.join(*args).replace('\\', '/')
214
 
 
215
 
    def normpath(path):
216
 
        return os.path.normpath(path).replace('\\', '/')
217
 
 
218
 
    def getcwd():
219
 
        return os.getcwdu().replace('\\', '/')
220
 
 
221
 
    def mkdtemp(*args, **kwargs):
222
 
        return tempfile.mkdtemp(*args, **kwargs).replace('\\', '/')
223
 
 
224
 
    def rename(old, new):
225
 
        fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
 
263
    abspath = _win32_abspath
 
264
    realpath = _win32_realpath
 
265
    pathjoin = _win32_pathjoin
 
266
    normpath = _win32_normpath
 
267
    getcwd = _win32_getcwd
 
268
    mkdtemp = _win32_mkdtemp
 
269
    rename = _win32_rename
226
270
 
227
271
    MIN_ABS_PATHLENGTH = 3
228
272
 
352
396
        return False
353
397
 
354
398
 
 
399
def is_inside_or_parent_of_any(dir_list, fname):
 
400
    """True if fname is a child or a parent of any of the given files."""
 
401
    for dirname in dir_list:
 
402
        if is_inside(dirname, fname) or is_inside(fname, dirname):
 
403
            return True
 
404
    else:
 
405
        return False
 
406
 
 
407
 
355
408
def pumpfile(fromfile, tofile):
356
409
    """Copy contents of one file to another."""
357
410
    BUFSIZE = 32768
547
600
    return pathjoin(*p)
548
601
 
549
602
 
 
603
@deprecated_function(zero_nine)
550
604
def appendpath(p1, p2):
551
605
    if p1 == '':
552
606
        return p2
629
683
    assert len(base) >= MIN_ABS_PATHLENGTH, ('Length of base must be equal or'
630
684
        ' exceed the platform minimum length (which is %d)' % 
631
685
        MIN_ABS_PATHLENGTH)
 
686
 
632
687
    rp = abspath(path)
633
688
 
634
689
    s = []
640
695
        if tail:
641
696
            s.insert(0, tail)
642
697
    else:
643
 
        # XXX This should raise a NotChildPath exception, as its not tied
644
 
        # to branch anymore.
645
698
        raise PathNotChild(rp, base)
646
699
 
647
700
    if s:
666
719
        raise BzrBadParameterNotUnicode(unicode_or_utf8_string)
667
720
 
668
721
 
 
722
_platform_normalizes_filenames = False
 
723
if sys.platform == 'darwin':
 
724
    _platform_normalizes_filenames = True
 
725
 
 
726
 
 
727
def normalizes_filenames():
 
728
    """Return True if this platform normalizes unicode filenames.
 
729
 
 
730
    Mac OSX does, Windows/Linux do not.
 
731
    """
 
732
    return _platform_normalizes_filenames
 
733
 
 
734
 
 
735
if _platform_normalizes_filenames:
 
736
    def unicode_filename(path):
 
737
        """Make sure 'path' is a properly normalized filename.
 
738
 
 
739
        On platforms where the system normalizes filenames (Mac OSX),
 
740
        you can access a file by any path which will normalize
 
741
        correctly.
 
742
        Internally, bzr only supports NFC/NFKC normalization, since
 
743
        that is the standard for XML documents.
 
744
        So we return an normalized path, and indicate this has been
 
745
        properly normalized.
 
746
 
 
747
        :return: (path, is_normalized) Return a path which can
 
748
                access the file, and whether or not this path is
 
749
                normalized.
 
750
        """
 
751
        return unicodedata.normalize('NFKC', path), True
 
752
else:
 
753
    def unicode_filename(path):
 
754
        """Make sure 'path' is a properly normalized filename.
 
755
 
 
756
        On platforms where the system does not normalize filenames 
 
757
        (Windows, Linux), you have to access a file by its exact path.
 
758
        Internally, bzr only supports NFC/NFKC normalization, since
 
759
        that is the standard for XML documents.
 
760
        So we return the original path, and indicate if this is
 
761
        properly normalized.
 
762
 
 
763
        :return: (path, is_normalized) Return a path which can
 
764
                access the file, and whether or not this path is
 
765
                normalized.
 
766
        """
 
767
        return path, unicodedata.normalize('NFKC', path) == path
 
768
 
 
769
 
669
770
def terminal_width():
670
771
    """Return estimated terminal width."""
671
772
    if sys.platform == 'win32':
693
794
    return sys.platform != "win32"
694
795
 
695
796
 
696
 
def strip_trailing_slash(path):
697
 
    """Strip trailing slash, except for root paths.
698
 
    The definition of 'root path' is platform-dependent.
699
 
    """
700
 
    if len(path) != MIN_ABS_PATHLENGTH and path[-1] == '/':
701
 
        return path[:-1]
702
 
    else:
703
 
        return path
704
 
 
705
 
 
706
797
_validWin32PathRE = re.compile(r'^([A-Za-z]:[/\\])?[^:<>*"?\|]*$')
707
798
 
708
799
 
715
806
        return
716
807
    if _validWin32PathRE.match(path) is None:
717
808
        raise IllegalPath(path)
 
809
 
 
810
 
 
811
def walkdirs(top, prefix=""):
 
812
    """Yield data about all the directories in a tree.
 
813
    
 
814
    This yields all the data about the contents of a directory at a time.
 
815
    After each directory has been yielded, if the caller has mutated the list
 
816
    to exclude some directories, they are then not descended into.
 
817
    
 
818
    The data yielded is of the form:
 
819
    [(relpath, basename, kind, lstat, path_from_top), ...]
 
820
 
 
821
    :param prefix: Prefix the relpaths that are yielded with 'prefix'. This 
 
822
        allows one to walk a subtree but get paths that are relative to a tree
 
823
        rooted higher up.
 
824
    :return: an iterator over the dirs.
 
825
    """
 
826
    lstat = os.lstat
 
827
    pending = []
 
828
    _directory = _directory_kind
 
829
    _listdir = listdir
 
830
    pending = [(prefix, "", _directory, None, top)]
 
831
    while pending:
 
832
        dirblock = []
 
833
        currentdir = pending.pop()
 
834
        # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
 
835
        top = currentdir[4]
 
836
        if currentdir[0]:
 
837
            relroot = currentdir[0] + '/'
 
838
        else:
 
839
            relroot = ""
 
840
        for name in sorted(_listdir(top)):
 
841
            abspath = top + '/' + name
 
842
            statvalue = lstat(abspath)
 
843
            dirblock.append ((relroot + name, name, file_kind_from_stat_mode(statvalue.st_mode), statvalue, abspath))
 
844
        yield dirblock
 
845
        # push the user specified dirs from dirblock
 
846
        for dir in reversed(dirblock):
 
847
            if dir[2] == _directory:
 
848
                pending.append(dir)