1 # Module 'os2emxpath' -- common operations on OS/2 pathnames
2 """Common pathname manipulations, OS/2 EMX version.
4 Instead of importing this module directly, import os and refer to this
11 __all__
= ["normcase","isabs","join","splitdrive","split","splitext",
12 "basename","dirname","commonprefix","getsize","getmtime",
13 "getatime","getctime", "islink","exists","isdir","isfile","ismount",
14 "walk","expanduser","expandvars","normpath","abspath","splitunc",
15 "curdir","pardir","sep","pathsep","defpath","altsep","extsep",
16 "realpath","supports_unicode_filenames"]
18 # strings representing various path-related bits and pieces
27 # Normalize the case of a pathname and map slashes to backslashes.
28 # Other normalizations (such as optimizing '../' away) are not done
29 # (this is done by normpath).
32 """Normalize case of pathname.
34 Makes all characters lowercase and all altseps into seps."""
35 return s
.replace('\\', '/').lower()
38 # Return whether a path is absolute.
39 # Trivial in Posix, harder on the Mac or MS-DOS.
40 # For DOS it is absolute if it starts with a slash or backslash (current
41 # volume), or if a pathname after the volume letter and colon / UNC resource
42 # starts with a slash or backslash.
45 """Test whether a path is absolute"""
47 return s
!= '' and s
[:1] in '/\\'
50 # Join two (or more) paths.
53 """Join two or more pathname components, inserting sep as needed"""
58 elif path
== '' or path
[-1:] in '/\\:':
65 # Split a path in a drive specification (a drive letter followed by a
66 # colon) and the path specification.
67 # It is always true that drivespec + pathspec == p
69 """Split a pathname into drive and path specifiers. Returns a 2-tuple
70 "(drive,path)"; either part may be empty"""
78 """Split a pathname into UNC mount point and relative path specifiers.
80 Return a 2-tuple (unc, rest); either part may be empty.
81 If unc is not empty, it has the form '//host/mount' (or similar
82 using backslashes). unc+rest is always the input path.
83 Paths containing drive letters never have an UNC part.
86 return '', p
# Drive letter present
88 if firstTwo
== '/' * 2 or firstTwo
== '\\' * 2:
90 # vvvvvvvvvvvvvvvvvvvv equivalent to drive letter
91 # \\machine\mountpoint\directories...
92 # directory ^^^^^^^^^^^^^^^
94 index
= normp
.find('/', 2)
96 ##raise RuntimeError, 'illegal UNC path: "' + p + '"'
98 index
= normp
.find('/', index
+ 1)
101 return p
[:index
], p
[index
:]
105 # Split a path in head (everything up to the last '/') and tail (the
106 # rest). After the trailing '/' is stripped, the invariant
107 # join(head, tail) == p holds.
108 # The resulting head won't end in '/' unless it is the root.
113 Return tuple (head, tail) where tail is everything after the final slash.
114 Either part may be empty."""
117 # set i to index beyond p's last slash
119 while i
and p
[i
-1] not in '/\\':
121 head
, tail
= p
[:i
], p
[i
:] # now tail has no slashes
122 # remove trailing slashes from head, unless it's all slashes
124 while head2
and head2
[-1] in '/\\':
127 return d
+ head
, tail
130 # Split a path in root and extension.
131 # The extension is everything starting at the last dot in the last
132 # pathname component; the root is everything before that.
133 # It is always true that root + ext == p.
136 """Split the extension from a pathname.
138 Extension is everything from the last dot to the end.
139 Return (root, ext), either part may be empty."""
143 root
, ext
= root
+ ext
+ c
, ''
146 root
, ext
= root
+ ext
, c
156 # Return the tail (basename) part of a path.
159 """Returns the final component of a pathname"""
163 # Return the head (dirname) part of a path.
166 """Returns the directory component of a pathname"""
170 # Return the longest prefix of all list elements.
173 "Given a list of pathnames, returns the longest common leading component"
177 for i
in range(len(prefix
)):
178 if prefix
[:i
+1] != item
[:i
+1]:
185 # Get size, mtime, atime of files.
187 def getsize(filename
):
188 """Return the size of a file, reported by os.stat()"""
189 return os
.stat(filename
).st_size
191 def getmtime(filename
):
192 """Return the last modification time of a file, reported by os.stat()"""
193 return os
.stat(filename
).st_mtime
195 def getatime(filename
):
196 """Return the last access time of a file, reported by os.stat()"""
197 return os
.stat(filename
).st_atime
199 def getctime(filename
):
200 """Return the creation time of a file, reported by os.stat()."""
201 return os
.stat(filename
).st_ctime
203 # Is a path a symbolic link?
204 # This will always return false on systems where posix.lstat doesn't exist.
207 """Test for symbolic link. On OS/2 always returns false"""
212 # This is false for dangling symbolic links.
215 """Test whether a path exists"""
223 # Is a path a directory?
226 """Test whether a path is a directory"""
231 return stat
.S_ISDIR(st
.st_mode
)
234 # Is a path a regular file?
235 # This follows symbolic links, so both islink() and isdir() can be true
239 """Test whether a path is a regular file"""
244 return stat
.S_ISREG(st
.st_mode
)
247 # Is a path a mount point? Either a root (with or without drive letter)
248 # or an UNC path with at most a / or \ after the mount point.
251 """Test whether a path is a mount point (defined as root of drive)"""
252 unc
, rest
= splitunc(path
)
254 return rest
in ("", "/", "\\")
255 p
= splitdrive(path
)[1]
256 return len(p
) == 1 and p
[0] in '/\\'
259 # Directory tree walk.
260 # For each directory under top (including top itself, but excluding
261 # '.' and '..'), func(arg, dirname, filenames) is called, where
262 # dirname is the name of the directory and filenames is the list
263 # files files (and subdirectories etc.) in the directory.
264 # The func may modify the filenames list, to implement a filter,
265 # or to impose a different order of visiting.
267 def walk(top
, func
, arg
):
268 """Directory tree walk whth callback function.
270 walk(top, func, arg) calls func(arg, d, files) for each directory d
271 in the tree rooted at top (including top itself); files is a list
272 of all the files and subdirs in directory d."""
274 names
= os
.listdir(top
)
277 func(arg
, top
, names
)
278 exceptions
= ('.', '..')
280 if name
not in exceptions
:
281 name
= join(top
, name
)
283 walk(name
, func
, arg
)
286 # Expand paths beginning with '~' or '~user'.
287 # '~' means $HOME; '~user' means that user's home directory.
288 # If the path doesn't begin with '~', or if the user or $HOME is unknown,
289 # the path is returned unchanged (leaving error reporting to whatever
290 # function is called with the expanded path as argument).
291 # See also module 'glob' for expansion of *, ? and [...] in pathnames.
292 # (A function should also be defined to do full *sh-style environment
293 # variable expansion.)
295 def expanduser(path
):
296 """Expand ~ and ~user constructs.
298 If user or $HOME is unknown, do nothing."""
302 while i
< n
and path
[i
] not in '/\\':
305 if 'HOME' in os
.environ
:
306 userhome
= os
.environ
['HOME']
307 elif not 'HOMEPATH' in os
.environ
:
311 drive
= os
.environ
['HOMEDRIVE']
314 userhome
= join(drive
, os
.environ
['HOMEPATH'])
317 return userhome
+ path
[i
:]
320 # Expand paths containing shell variable substitutions.
321 # The following rules apply:
322 # - no expansion within single quotes
323 # - no escape character, except for '$$' which is translated into '$'
324 # - ${varname} is accepted.
325 # - varnames can be made out of letters, digits and the character '_'
326 # XXX With COMMAND.COM you can use any characters in a variable name,
327 # XXX except '^|<>='.
329 def expandvars(path
):
330 """Expand shell variables of form $var and ${var}.
332 Unknown variables are left unchanged."""
336 varchars
= string
.letters
+ string
.digits
+ '_-'
340 while index
< pathlen
:
342 if c
== '\'': # no expansion within single quotes
343 path
= path
[index
+ 1:]
346 index
= path
.index('\'')
347 res
= res
+ '\'' + path
[:index
+ 1]
351 elif c
== '$': # variable or '$$'
352 if path
[index
+ 1:index
+ 2] == '$':
355 elif path
[index
+ 1:index
+ 2] == '{':
356 path
= path
[index
+2:]
359 index
= path
.index('}')
361 if var
in os
.environ
:
362 res
= res
+ os
.environ
[var
]
369 c
= path
[index
:index
+ 1]
370 while c
!= '' and c
in varchars
:
373 c
= path
[index
:index
+ 1]
374 if var
in os
.environ
:
375 res
= res
+ os
.environ
[var
]
384 # Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
387 """Normalize path, eliminating double slashes, etc."""
388 path
= path
.replace('\\', '/')
389 prefix
, path
= splitdrive(path
)
390 while path
[:1] == '/':
391 prefix
= prefix
+ '/'
393 comps
= path
.split('/')
395 while i
< len(comps
):
398 elif comps
[i
] == '..' and i
> 0 and comps
[i
-1] not in ('', '..'):
401 elif comps
[i
] == '' and i
> 0 and comps
[i
-1] != '':
405 # If the path is now empty, substitute '.'
406 if not prefix
and not comps
:
408 return prefix
+ '/'.join(comps
)
411 # Return an absolute path.
413 """Return the absolute version of a path"""
415 path
= join(os
.getcwd(), path
)
416 return normpath(path
)
418 # realpath is a no-op on systems without islink support
421 supports_unicode_filenames
= False