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
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
22
from os import listdir
26
from shutil import copyfile
28
from stat import (S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE,
29
S_ISCHR, S_ISBLK, S_ISFIFO, S_ISSOCK)
36
from ntpath import (abspath as _nt_abspath,
38
normpath as _nt_normpath,
39
realpath as _nt_realpath,
35
43
from bzrlib.errors import (BzrError,
78
mode = os.lstat(f)[ST_MODE]
86
_directory_kind = 'directory'
89
stat.S_IFDIR:_directory_kind,
90
stat.S_IFCHR:'chardev',
94
stat.S_IFLNK:'symlink',
95
stat.S_IFSOCK:'socket',
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.
102
Its performance is critical: Do not mutate without careful benchmarking.
105
return _formats[stat_mode & 0170000]
110
def file_kind(f, _lstat=os.lstat, _mapper=file_kind_from_stat_mode):
111
return _mapper(_lstat(f).st_mode)
97
114
def kind_marker(kind):
98
115
if kind == 'file':
100
elif kind == 'directory':
117
elif kind == _directory_kind:
102
119
elif kind == 'symlink':
105
122
raise BzrError('invalid file kind %r' % kind)
108
if hasattr(os.path, 'lexists'):
109
return os.path.lexists(f)
111
if hasattr(os, 'lstat'):
117
if e.errno == errno.ENOENT:
120
raise BzrError("lstat/stat of (%r): %r" % (f, e))
124
lexists = getattr(os.path, 'lexists', None)
128
if hasattr(os, 'lstat'):
134
if e.errno == errno.ENOENT:
137
raise BzrError("lstat/stat of (%r): %r" % (f, e))
122
140
def fancy_rename(old, new, rename_func, unlink_func):
123
141
"""A fancy rename, when you don't have atomic rename.
174
192
rename_func(tmp_name, new)
195
# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
196
# choke on a Unicode string containing a relative path if
197
# os.getcwd() returns a non-sys.getdefaultencoding()-encoded
199
_fs_enc = sys.getfilesystemencoding()
200
def _posix_abspath(path):
201
return os.path.abspath(path.encode(_fs_enc)).decode(_fs_enc)
202
# jam 20060426 This is another possibility which mimics
203
# os.path.abspath, only uses unicode characters instead
204
# if not os.path.isabs(path):
205
# return os.path.join(os.getcwdu(), path)
209
def _posix_realpath(path):
210
return os.path.realpath(path.encode(_fs_enc)).decode(_fs_enc)
213
def _win32_abspath(path):
214
return _nt_abspath(path.encode(_fs_enc)).decode(_fs_enc).replace('\\', '/')
217
def _win32_realpath(path):
218
return _nt_realpath(path.encode(_fs_enc)).decode(_fs_enc).replace('\\', '/')
221
def _win32_pathjoin(*args):
222
return _nt_join(*args).replace('\\', '/')
225
def _win32_normpath(path):
226
return _nt_normpath(path).replace('\\', '/')
230
return os.getcwdu().replace('\\', '/')
233
def _win32_mkdtemp(*args, **kwargs):
234
return tempfile.mkdtemp(*args, **kwargs).replace('\\', '/')
237
def _win32_rename(old, new):
238
fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
176
241
# Default is to just use the python builtins, but these can be rebound on
177
242
# particular platforms.
178
abspath = os.path.abspath
179
realpath = os.path.realpath
243
abspath = _posix_abspath
244
realpath = _posix_realpath
180
245
pathjoin = os.path.join
181
246
normpath = os.path.normpath
182
247
getcwd = os.getcwdu
189
254
MIN_ABS_PATHLENGTH = 1
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
196
_fs_enc = sys.getfilesystemencoding()
198
return os.path.abspath(path.encode(_fs_enc)).decode(_fs_enc)
201
return os.path.realpath(path.encode(_fs_enc)).decode(_fs_enc)
203
257
if sys.platform == 'win32':
204
# We need to use the Unicode-aware os.path.abspath and
205
# os.path.realpath on Windows systems.
207
return os.path.abspath(path).replace('\\', '/')
210
return os.path.realpath(path).replace('\\', '/')
213
return os.path.join(*args).replace('\\', '/')
216
return os.path.normpath(path).replace('\\', '/')
219
return os.getcwdu().replace('\\', '/')
221
def mkdtemp(*args, **kwargs):
222
return tempfile.mkdtemp(*args, **kwargs).replace('\\', '/')
224
def rename(old, new):
225
fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
258
abspath = _win32_abspath
259
realpath = _win32_realpath
260
pathjoin = _win32_pathjoin
261
normpath = _win32_normpath
262
getcwd = _win32_getcwd
263
mkdtemp = _win32_mkdtemp
264
rename = _win32_rename
227
266
MIN_ABS_PATHLENGTH = 3
394
def is_inside_or_parent_of_any(dir_list, fname):
395
"""True if fname is a child or a parent of any of the given files."""
396
for dirname in dir_list:
397
if is_inside(dirname, fname) or is_inside(fname, dirname):
355
403
def pumpfile(fromfile, tofile):
356
404
"""Copy contents of one file to another."""
666
714
raise BzrBadParameterNotUnicode(unicode_or_utf8_string)
717
_platform_normalizes_filenames = False
718
if sys.platform == 'darwin':
719
_platform_normalizes_filenames = True
722
def normalizes_filenames():
723
"""Return True if this platform normalizes unicode filenames.
725
Mac OSX does, Windows/Linux do not.
727
return _platform_normalizes_filenames
730
if _platform_normalizes_filenames:
731
def unicode_filename(path):
732
"""Make sure 'path' is a properly normalized filename.
734
On platforms where the system normalizes filenames (Mac OSX),
735
you can access a file by any path which will normalize
737
Internally, bzr only supports NFC/NFKC normalization, since
738
that is the standard for XML documents.
739
So we return an normalized path, and indicate this has been
742
:return: (path, is_normalized) Return a path which can
743
access the file, and whether or not this path is
746
return unicodedata.normalize('NFKC', path), True
748
def unicode_filename(path):
749
"""Make sure 'path' is a properly normalized filename.
751
On platforms where the system does not normalize filenames
752
(Windows, Linux), you have to access a file by its exact path.
753
Internally, bzr only supports NFC/NFKC normalization, since
754
that is the standard for XML documents.
755
So we return the original path, and indicate if this is
758
:return: (path, is_normalized) Return a path which can
759
access the file, and whether or not this path is
762
return path, unicodedata.normalize('NFKC', path) == path
669
765
def terminal_width():
670
766
"""Return estimated terminal width."""
671
767
if sys.platform == 'win32':
693
789
return sys.platform != "win32"
696
def strip_trailing_slash(path):
697
"""Strip trailing slash, except for root paths.
698
The definition of 'root path' is platform-dependent.
700
if len(path) != MIN_ABS_PATHLENGTH and path[-1] == '/':
706
792
_validWin32PathRE = re.compile(r'^([A-Za-z]:[/\\])?[^:<>*"?\|]*$')
716
802
if _validWin32PathRE.match(path) is None:
717
803
raise IllegalPath(path)
807
"""Yield data about all the directories in a tree.
809
This yields all the data about the contents of a directory at a time.
810
After each directory has been yielded, if the caller has mutated the list
811
to exclude some directories, they are then not descended into.
813
The data yielded is of the form:
814
[(relpath, basename, kind, lstat, path_from_top), ...]
816
:return: an iterator over the dirs.
820
_directory = _directory_kind
822
pending = [("", "", _directory, None, top)]
825
currentdir = pending.pop()
826
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
829
relroot = currentdir[0] + '/'
832
for name in sorted(_listdir(top)):
833
abspath = top + '/' + name
834
statvalue = lstat(abspath)
835
dirblock.append ((relroot + name, name, file_kind_from_stat_mode(statvalue.st_mode), statvalue, abspath))
837
# push the user specified dirs from dirblock
838
for dir in reversed(dirblock):
839
if dir[2] == _directory: