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","lexists","isdir","isfile",
14 "ismount","walk","expanduser","expandvars","normpath","abspath",
15 "splitunc","curdir","pardir","sep","pathsep","defpath","altsep",
16 "extsep","devnull","realpath","supports_unicode_filenames"]
18 # strings representing various path-related bits and pieces
28 # Normalize the case of a pathname and map slashes to backslashes.
29 # Other normalizations (such as optimizing '../' away) are not done
30 # (this is done by normpath).
33 """Normalize case of pathname.
35 Makes all characters lowercase and all altseps into seps."""
36 return s
.replace('\\', '/').lower()
39 # Return whether a path is absolute.
40 # Trivial in Posix, harder on the Mac or MS-DOS.
41 # For DOS it is absolute if it starts with a slash or backslash (current
42 # volume), or if a pathname after the volume letter and colon / UNC resource
43 # starts with a slash or backslash.
46 """Test whether a path is absolute"""
48 return s
!= '' and s
[:1] in '/\\'
51 # Join two (or more) paths.
54 """Join two or more pathname components, inserting sep as needed"""
59 elif path
== '' or path
[-1:] in '/\\:':
66 # Split a path in a drive specification (a drive letter followed by a
67 # colon) and the path specification.
68 # It is always true that drivespec + pathspec == p
70 """Split a pathname into drive and path specifiers. Returns a 2-tuple
71 "(drive,path)"; either part may be empty"""
79 """Split a pathname into UNC mount point and relative path specifiers.
81 Return a 2-tuple (unc, rest); either part may be empty.
82 If unc is not empty, it has the form '//host/mount' (or similar
83 using backslashes). unc+rest is always the input path.
84 Paths containing drive letters never have an UNC part.
87 return '', p
# Drive letter present
89 if firstTwo
== '/' * 2 or firstTwo
== '\\' * 2:
91 # vvvvvvvvvvvvvvvvvvvv equivalent to drive letter
92 # \\machine\mountpoint\directories...
93 # directory ^^^^^^^^^^^^^^^
95 index
= normp
.find('/', 2)
97 ##raise RuntimeError, 'illegal UNC path: "' + p + '"'
99 index
= normp
.find('/', index
+ 1)
102 return p
[:index
], p
[index
:]
106 # Split a path in head (everything up to the last '/') and tail (the
107 # rest). After the trailing '/' is stripped, the invariant
108 # join(head, tail) == p holds.
109 # The resulting head won't end in '/' unless it is the root.
114 Return tuple (head, tail) where tail is everything after the final slash.
115 Either part may be empty."""
118 # set i to index beyond p's last slash
120 while i
and p
[i
-1] not in '/\\':
122 head
, tail
= p
[:i
], p
[i
:] # now tail has no slashes
123 # remove trailing slashes from head, unless it's all slashes
125 while head2
and head2
[-1] in '/\\':
128 return d
+ head
, tail
131 # Split a path in root and extension.
132 # The extension is everything starting at the last dot in the last
133 # pathname component; the root is everything before that.
134 # It is always true that root + ext == p.
137 """Split the extension from a pathname.
139 Extension is everything from the last dot to the end.
140 Return (root, ext), either part may be empty."""
144 root
, ext
= root
+ ext
+ c
, ''
147 root
, ext
= root
+ ext
, c
157 # Return the tail (basename) part of a path.
160 """Returns the final component of a pathname"""
164 # Return the head (dirname) part of a path.
167 """Returns the directory component of a pathname"""
171 # Return the longest prefix of all list elements.
174 "Given a list of pathnames, returns the longest common leading component"
178 n
= min(len(s1
), len(s2
))
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"""
225 # Is a path a directory?
228 """Test whether a path is a directory"""
233 return stat
.S_ISDIR(st
.st_mode
)
236 # Is a path a regular file?
237 # This follows symbolic links, so both islink() and isdir() can be true
241 """Test whether a path is a regular file"""
246 return stat
.S_ISREG(st
.st_mode
)
249 # Is a path a mount point? Either a root (with or without drive letter)
250 # or an UNC path with at most a / or \ after the mount point.
253 """Test whether a path is a mount point (defined as root of drive)"""
254 unc
, rest
= splitunc(path
)
256 return rest
in ("", "/", "\\")
257 p
= splitdrive(path
)[1]
258 return len(p
) == 1 and p
[0] in '/\\'
261 # Directory tree walk.
262 # For each directory under top (including top itself, but excluding
263 # '.' and '..'), func(arg, dirname, filenames) is called, where
264 # dirname is the name of the directory and filenames is the list
265 # of files (and subdirectories etc.) in the directory.
266 # The func may modify the filenames list, to implement a filter,
267 # or to impose a different order of visiting.
269 def walk(top
, func
, arg
):
270 """Directory tree walk whth callback function.
272 walk(top, func, arg) calls func(arg, d, files) for each directory d
273 in the tree rooted at top (including top itself); files is a list
274 of all the files and subdirs in directory d."""
276 names
= os
.listdir(top
)
279 func(arg
, top
, names
)
280 exceptions
= ('.', '..')
282 if name
not in exceptions
:
283 name
= join(top
, name
)
285 walk(name
, func
, arg
)
288 # Expand paths beginning with '~' or '~user'.
289 # '~' means $HOME; '~user' means that user's home directory.
290 # If the path doesn't begin with '~', or if the user or $HOME is unknown,
291 # the path is returned unchanged (leaving error reporting to whatever
292 # function is called with the expanded path as argument).
293 # See also module 'glob' for expansion of *, ? and [...] in pathnames.
294 # (A function should also be defined to do full *sh-style environment
295 # variable expansion.)
297 def expanduser(path
):
298 """Expand ~ and ~user constructs.
300 If user or $HOME is unknown, do nothing."""
304 while i
< n
and path
[i
] not in '/\\':
307 if 'HOME' in os
.environ
:
308 userhome
= os
.environ
['HOME']
309 elif not 'HOMEPATH' in os
.environ
:
313 drive
= os
.environ
['HOMEDRIVE']
316 userhome
= join(drive
, os
.environ
['HOMEPATH'])
319 return userhome
+ path
[i
:]
322 # Expand paths containing shell variable substitutions.
323 # The following rules apply:
324 # - no expansion within single quotes
325 # - no escape character, except for '$$' which is translated into '$'
326 # - ${varname} is accepted.
327 # - varnames can be made out of letters, digits and the character '_'
328 # XXX With COMMAND.COM you can use any characters in a variable name,
329 # XXX except '^|<>='.
331 def expandvars(path
):
332 """Expand shell variables of form $var and ${var}.
334 Unknown variables are left unchanged."""
338 varchars
= string
.letters
+ string
.digits
+ '_-'
342 while index
< pathlen
:
344 if c
== '\'': # no expansion within single quotes
345 path
= path
[index
+ 1:]
348 index
= path
.index('\'')
349 res
= res
+ '\'' + path
[:index
+ 1]
353 elif c
== '$': # variable or '$$'
354 if path
[index
+ 1:index
+ 2] == '$':
357 elif path
[index
+ 1:index
+ 2] == '{':
358 path
= path
[index
+2:]
361 index
= path
.index('}')
363 if var
in os
.environ
:
364 res
= res
+ os
.environ
[var
]
371 c
= path
[index
:index
+ 1]
372 while c
!= '' and c
in varchars
:
375 c
= path
[index
:index
+ 1]
376 if var
in os
.environ
:
377 res
= res
+ os
.environ
[var
]
386 # Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
389 """Normalize path, eliminating double slashes, etc."""
390 path
= path
.replace('\\', '/')
391 prefix
, path
= splitdrive(path
)
392 while path
[:1] == '/':
393 prefix
= prefix
+ '/'
395 comps
= path
.split('/')
397 while i
< len(comps
):
400 elif comps
[i
] == '..' and i
> 0 and comps
[i
-1] not in ('', '..'):
403 elif comps
[i
] == '' and i
> 0 and comps
[i
-1] != '':
407 # If the path is now empty, substitute '.'
408 if not prefix
and not comps
:
410 return prefix
+ '/'.join(comps
)
413 # Return an absolute path.
415 """Return the absolute version of a path"""
417 path
= join(os
.getcwd(), path
)
418 return normpath(path
)
420 # realpath is a no-op on systems without islink support
423 supports_unicode_filenames
= False