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 "supports_unicode_filenames"]
17 # Normalize the case of a pathname and map slashes to backslashes.
18 # Other normalizations (such as optimizing '../' away) are not done
19 # (this is done by normpath).
22 """Normalize case of pathname.
24 Makes all characters lowercase and all altseps into seps."""
25 return s
.replace('\\', '/').lower()
28 # Return whether a path is absolute.
29 # Trivial in Posix, harder on the Mac or MS-DOS.
30 # For DOS it is absolute if it starts with a slash or backslash (current
31 # volume), or if a pathname after the volume letter and colon / UNC resource
32 # starts with a slash or backslash.
35 """Test whether a path is absolute"""
37 return s
!= '' and s
[:1] in '/\\'
40 # Join two (or more) paths.
43 """Join two or more pathname components, inserting sep as needed"""
48 elif path
== '' or path
[-1:] in '/\\:':
55 # Split a path in a drive specification (a drive letter followed by a
56 # colon) and the path specification.
57 # It is always true that drivespec + pathspec == p
59 """Split a pathname into drive and path specifiers. Returns a 2-tuple
60 "(drive,path)"; either part may be empty"""
68 """Split a pathname into UNC mount point and relative path specifiers.
70 Return a 2-tuple (unc, rest); either part may be empty.
71 If unc is not empty, it has the form '//host/mount' (or similar
72 using backslashes). unc+rest is always the input path.
73 Paths containing drive letters never have an UNC part.
76 return '', p
# Drive letter present
78 if firstTwo
== '/' * 2 or firstTwo
== '\\' * 2:
80 # vvvvvvvvvvvvvvvvvvvv equivalent to drive letter
81 # \\machine\mountpoint\directories...
82 # directory ^^^^^^^^^^^^^^^
84 index
= normp
.find('/', 2)
86 ##raise RuntimeError, 'illegal UNC path: "' + p + '"'
88 index
= normp
.find('/', index
+ 1)
91 return p
[:index
], p
[index
:]
95 # Split a path in head (everything up to the last '/') and tail (the
96 # rest). After the trailing '/' is stripped, the invariant
97 # join(head, tail) == p holds.
98 # The resulting head won't end in '/' unless it is the root.
103 Return tuple (head, tail) where tail is everything after the final slash.
104 Either part may be empty."""
107 # set i to index beyond p's last slash
109 while i
and p
[i
-1] not in '/\\':
111 head
, tail
= p
[:i
], p
[i
:] # now tail has no slashes
112 # remove trailing slashes from head, unless it's all slashes
114 while head2
and head2
[-1] in '/\\':
117 return d
+ head
, tail
120 # Split a path in root and extension.
121 # The extension is everything starting at the last dot in the last
122 # pathname component; the root is everything before that.
123 # It is always true that root + ext == p.
126 """Split the extension from a pathname.
128 Extension is everything from the last dot to the end.
129 Return (root, ext), either part may be empty."""
133 root
, ext
= root
+ ext
+ c
, ''
136 root
, ext
= root
+ ext
, c
146 # Return the tail (basename) part of a path.
149 """Returns the final component of a pathname"""
153 # Return the head (dirname) part of a path.
156 """Returns the directory component of a pathname"""
160 # Return the longest prefix of all list elements.
163 "Given a list of pathnames, returns the longest common leading component"
167 for i
in range(len(prefix
)):
168 if prefix
[:i
+1] != item
[:i
+1]:
175 # Get size, mtime, atime of files.
177 def getsize(filename
):
178 """Return the size of a file, reported by os.stat()"""
179 return os
.stat(filename
).st_size
181 def getmtime(filename
):
182 """Return the last modification time of a file, reported by os.stat()"""
183 return os
.stat(filename
).st_mtime
185 def getatime(filename
):
186 """Return the last access time of a file, reported by os.stat()"""
187 return os
.stat(filename
).st_atime
189 def getctime(filename
):
190 """Return the creation time of a file, reported by os.stat()."""
191 return os
.stat(filename
).st_ctime
193 # Is a path a symbolic link?
194 # This will always return false on systems where posix.lstat doesn't exist.
197 """Test for symbolic link. On OS/2 always returns false"""
202 # This is false for dangling symbolic links.
205 """Test whether a path exists"""
213 # Is a path a directory?
216 """Test whether a path is a directory"""
221 return stat
.S_ISDIR(st
.st_mode
)
224 # Is a path a regular file?
225 # This follows symbolic links, so both islink() and isdir() can be true
229 """Test whether a path is a regular file"""
234 return stat
.S_ISREG(st
.st_mode
)
237 # Is a path a mount point? Either a root (with or without drive letter)
238 # or an UNC path with at most a / or \ after the mount point.
241 """Test whether a path is a mount point (defined as root of drive)"""
242 unc
, rest
= splitunc(path
)
244 return rest
in ("", "/", "\\")
245 p
= splitdrive(path
)[1]
246 return len(p
) == 1 and p
[0] in '/\\'
249 # Directory tree walk.
250 # For each directory under top (including top itself, but excluding
251 # '.' and '..'), func(arg, dirname, filenames) is called, where
252 # dirname is the name of the directory and filenames is the list
253 # files files (and subdirectories etc.) in the directory.
254 # The func may modify the filenames list, to implement a filter,
255 # or to impose a different order of visiting.
257 def walk(top
, func
, arg
):
258 """Directory tree walk whth callback function.
260 walk(top, func, arg) calls func(arg, d, files) for each directory d
261 in the tree rooted at top (including top itself); files is a list
262 of all the files and subdirs in directory d."""
264 names
= os
.listdir(top
)
267 func(arg
, top
, names
)
268 exceptions
= ('.', '..')
270 if name
not in exceptions
:
271 name
= join(top
, name
)
273 walk(name
, func
, arg
)
276 # Expand paths beginning with '~' or '~user'.
277 # '~' means $HOME; '~user' means that user's home directory.
278 # If the path doesn't begin with '~', or if the user or $HOME is unknown,
279 # the path is returned unchanged (leaving error reporting to whatever
280 # function is called with the expanded path as argument).
281 # See also module 'glob' for expansion of *, ? and [...] in pathnames.
282 # (A function should also be defined to do full *sh-style environment
283 # variable expansion.)
285 def expanduser(path
):
286 """Expand ~ and ~user constructs.
288 If user or $HOME is unknown, do nothing."""
292 while i
< n
and path
[i
] not in '/\\':
295 if 'HOME' in os
.environ
:
296 userhome
= os
.environ
['HOME']
297 elif not 'HOMEPATH' in os
.environ
:
301 drive
= os
.environ
['HOMEDRIVE']
304 userhome
= join(drive
, os
.environ
['HOMEPATH'])
307 return userhome
+ path
[i
:]
310 # Expand paths containing shell variable substitutions.
311 # The following rules apply:
312 # - no expansion within single quotes
313 # - no escape character, except for '$$' which is translated into '$'
314 # - ${varname} is accepted.
315 # - varnames can be made out of letters, digits and the character '_'
316 # XXX With COMMAND.COM you can use any characters in a variable name,
317 # XXX except '^|<>='.
319 def expandvars(path
):
320 """Expand shell variables of form $var and ${var}.
322 Unknown variables are left unchanged."""
326 varchars
= string
.letters
+ string
.digits
+ '_-'
330 while index
< pathlen
:
332 if c
== '\'': # no expansion within single quotes
333 path
= path
[index
+ 1:]
336 index
= path
.index('\'')
337 res
= res
+ '\'' + path
[:index
+ 1]
341 elif c
== '$': # variable or '$$'
342 if path
[index
+ 1:index
+ 2] == '$':
345 elif path
[index
+ 1:index
+ 2] == '{':
346 path
= path
[index
+2:]
349 index
= path
.index('}')
351 if var
in os
.environ
:
352 res
= res
+ os
.environ
[var
]
359 c
= path
[index
:index
+ 1]
360 while c
!= '' and c
in varchars
:
363 c
= path
[index
:index
+ 1]
364 if var
in os
.environ
:
365 res
= res
+ os
.environ
[var
]
374 # Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
377 """Normalize path, eliminating double slashes, etc."""
378 path
= path
.replace('\\', '/')
379 prefix
, path
= splitdrive(path
)
380 while path
[:1] == '/':
381 prefix
= prefix
+ '/'
383 comps
= path
.split('/')
385 while i
< len(comps
):
388 elif comps
[i
] == '..' and i
> 0 and comps
[i
-1] not in ('', '..'):
391 elif comps
[i
] == '' and i
> 0 and comps
[i
-1] != '':
395 # If the path is now empty, substitute '.'
396 if not prefix
and not comps
:
398 return prefix
+ '/'.join(comps
)
401 # Return an absolute path.
403 """Return the absolute version of a path"""
405 path
= join(os
.getcwd(), path
)
406 return normpath(path
)
408 supports_unicode_filenames
= False