Statistics
| Revision:

svn-gvsig-desktop / tags / v1_1_Build_1012 / extensions / extScripting / scripts / jython / Lib / javapath.py @ 12987

History | View | Annotate | Download (8.65 KB)

1
"""Common pathname manipulations, JDK version.
2

3
Instead of importing this module directly, import os and refer to this
4
module as os.path.
5

6
"""
7

    
8
# Incompletely implemented:
9
# islink -- How?
10
# ismount -- How?
11
# splitdrive -- How?
12
# normcase -- How?
13

    
14
# Missing:
15
# sameopenfile -- Java doesn't have fstat nor file descriptors?
16
# samestat -- How?
17

    
18
import java
19
from java.io import File
20
from java.lang import System
21
import os
22

    
23
def _tostr(s, method):
24
    if isinstance(s, "".__class__):
25
        return s
26
    import org
27
    raise TypeError, "%s() argument must be a string object, not %s" % (
28
                method, org.python.core.Py.safeRepr(s))
29
        
30
def dirname(path):
31
    """Return the directory component of a pathname"""
32
    path = _tostr(path, "dirname")
33
    result = File(path).getParent()
34
    if not result:
35
        if isabs(path):
36
            result = path # Must be root
37
        else:
38
            result = ""
39
    return result
40

    
41
def basename(path):
42
    """Return the final component of a pathname"""
43
    path = _tostr(path, "basename")
44
    return File(path).getName()
45

    
46
def split(path):
47
    """Split a pathname.
48

49
    Return tuple "(head, tail)" where "tail" is everything after the
50
    final slash.  Either part may be empty.
51

52
    """
53
    path = _tostr(path, "split")
54
    return (dirname(path), basename(path))
55

    
56
def splitext(path):
57
    """Split the extension from a pathname.
58

59
    Extension is everything from the last dot to the end.  Return
60
    "(root, ext)", either part may be empty.
61

62
    """
63
    i = 0
64
    n = -1
65
    for c in path:
66
        if c == '.': n = i
67
        i = i+1
68
    if n < 0:
69
        return (path, "")
70
    else:
71
        return (path[:n], path[n:])
72

    
73
def splitdrive(path):
74
    """Split a pathname into drive and path.
75

76
    On JDK, drive is always empty.
77
    XXX This isn't correct for JDK on DOS/Windows!
78

79
    """
80
    return ("", path)
81

    
82
def exists(path):
83
    """Test whether a path exists.
84

85
    Returns false for broken symbolic links.
86

87
    """
88
    path = _tostr(path, "exists")
89
    return File(path).exists()
90

    
91
def isabs(path):
92
    """Test whether a path is absolute"""
93
    path = _tostr(path, "isabs")
94
    return File(path).isAbsolute()
95

    
96
def isfile(path):
97
    """Test whether a path is a regular file"""
98
    path = _tostr(path, "isfile")
99
    return File(path).isFile()
100

    
101
def isdir(path):
102
    """Test whether a path is a directory"""
103
    path = _tostr(path, "isdir")
104
    return File(path).isDirectory()
105

    
106
def join(path, *args):
107
    """Join two or more pathname components, inserting os.sep as needed"""
108
    path = _tostr(path, "join")
109
    f = File(path)
110
    for a in args:
111
        a = _tostr(a, "join")
112
        g = File(a)
113
        if g.isAbsolute() or len(f.getPath()) == 0:
114
            f = g
115
        else:
116
            f = File(f, a)
117
    return f.getPath()
118

    
119
def normcase(path):
120
    """Normalize case of pathname.
121

122
    XXX Not done right under JDK.
123

124
    """
125
    path = _tostr(path, "normcase")
126
    return File(path).getPath()
127

    
128
def commonprefix(m):
129
    "Given a list of pathnames, return the longest common leading component"
130
    if not m: return ''
131
    prefix = m[0]
132
    for item in m:
133
        for i in range(len(prefix)):
134
            if prefix[:i+1] <> item[:i+1]:
135
                prefix = prefix[:i]
136
                if i == 0: return ''
137
                break
138
    return prefix
139

    
140
def islink(path):
141
    """Test whether a path is a symbolic link.
142

143
    XXX This incorrectly always returns false under JDK.
144

145
    """
146
    return 0
147

    
148
def samefile(path, path2):
149
    """Test whether two pathnames reference the same actual file"""
150
    path = _tostr(path, "samefile")
151
    path2 = _tostr(path2, "samefile")
152
    f = File(path)
153
    f2 = File(path2)
154
    return f.getCanonicalPath() == f2.getCanonicalPath()
155

    
156
def ismount(path):
157
    """Test whether a path is a mount point.
158

159
    XXX This incorrectly always returns false under JDK.
160

161
    """
162
    return 0
163

    
164

    
165
def walk(top, func, arg):
166
    """Walk a directory tree.
167

168
    walk(top,func,args) calls func(arg, d, files) for each directory
169
    "d" in the tree rooted at "top" (including "top" itself).  "files"
170
    is a list of all the files and subdirs in directory "d".
171

172
    """
173
    try:
174
        names = os.listdir(top)
175
    except os.error:
176
        return
177
    func(arg, top, names)
178
    for name in names:
179
        name = join(top, name)
180
        if isdir(name) and not islink(name):
181
            walk(name, func, arg)
182

    
183
def expanduser(path):
184
    if path[:1] == "~":
185
        c = path[1:2]
186
        if not c:
187
            return gethome()
188
        if c == os.sep:
189
            return File(gethome(), path[2:]).getPath()
190
    return path
191

    
192
def getuser():
193
    return System.getProperty("user.name")
194

    
195
def gethome():
196
    return System.getProperty("user.home")
197

    
198

    
199
# normpath() from Python 1.5.2, with Java appropriate generalizations
200

    
201
# Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
202
# It should be understood that this may change the meaning of the path
203
# if it contains symbolic links!
204
def normpath(path):
205
    """Normalize path, eliminating double slashes, etc."""
206
    sep = os.sep
207
    if sep == '\\':
208
        path = path.replace("/", sep)
209
    curdir = os.curdir
210
    pardir = os.pardir
211
    import string
212
    # Treat initial slashes specially
213
    slashes = ''
214
    while path[:1] == sep:
215
        slashes = slashes + sep
216
        path = path[1:]
217
    comps = string.splitfields(path, sep)
218
    i = 0
219
    while i < len(comps):
220
        if comps[i] == curdir:
221
            del comps[i]
222
            while i < len(comps) and comps[i] == '':
223
                del comps[i]
224
        elif comps[i] == pardir and i > 0 and comps[i-1] not in ('', pardir):
225
            del comps[i-1:i+1]
226
            i = i-1
227
        elif comps[i] == '' and i > 0 and comps[i-1] <> '':
228
            del comps[i]
229
        else:
230
            i = i+1
231
    # If the path is now empty, substitute '.'
232
    if not comps and not slashes:
233
        comps.append(curdir)
234
    return slashes + string.joinfields(comps, sep)
235

    
236
# Return an absolute path.
237
def abspath(path):
238
    path = _tostr(path, "abspath")
239
    return File(path).getAbsolutePath()
240

    
241

    
242
def getsize(path):
243
    path = _tostr(path, "getsize")
244
    f = File(path)
245
    size = f.length()
246
    # Sadly, if the returned length is zero, we don't really know if the file
247
    # is zero sized or does not exist.
248
    if size == 0 and not f.exists():
249
        raise OSError(0, 'No such file or directory', path)
250
    return size
251

    
252
def getmtime(path):
253
    path = _tostr(path, "getmtime")
254
    f = File(path)
255
    return f.lastModified() / 1000.0
256

    
257
def getatime(path):
258
    # We can't detect access time so we return modification time. This
259
    # matches the behaviour in os.stat().
260
    path = _tostr(path, "getatime")
261
    f = File(path)
262
    return f.lastModified() / 1000.0
263

    
264

    
265
# expandvars is stolen from CPython-2.1.1's Lib/ntpath.py:
266

    
267
# Expand paths containing shell variable substitutions.
268
# The following rules apply:
269
#       - no expansion within single quotes
270
#       - no escape character, except for '$$' which is translated into '$'
271
#       - ${varname} is accepted.
272
#       - varnames can be made out of letters, digits and the character '_'
273
# XXX With COMMAND.COM you can use any characters in a variable name,
274
# XXX except '^|<>='.
275

    
276
def expandvars(path):
277
    """Expand shell variables of form $var and ${var}.
278

279
    Unknown variables are left unchanged."""
280
    if '$' not in path:
281
        return path
282
    import string
283
    varchars = string.letters + string.digits + '_-'
284
    res = ''
285
    index = 0
286
    pathlen = len(path)
287
    while index < pathlen:
288
        c = path[index]
289
        if c == '\'':   # no expansion within single quotes
290
            path = path[index + 1:]
291
            pathlen = len(path)
292
            try:
293
                index = path.index('\'')
294
                res = res + '\'' + path[:index + 1]
295
            except ValueError:
296
                res = res + path
297
                index = pathlen - 1
298
        elif c == '$':  # variable or '$$'
299
            if path[index + 1:index + 2] == '$':
300
                res = res + c
301
                index = index + 1
302
            elif path[index + 1:index + 2] == '{':
303
                path = path[index+2:]
304
                pathlen = len(path)
305
                try:
306
                    index = path.index('}')
307
                    var = path[:index]
308
                    if os.environ.has_key(var):
309
                        res = res + os.environ[var]
310
                except ValueError:
311
                    res = res + path
312
                    index = pathlen - 1
313
            else:
314
                var = ''
315
                index = index + 1
316
                c = path[index:index + 1]
317
                while c != '' and c in varchars:
318
                    var = var + c
319
                    index = index + 1
320
                    c = path[index:index + 1]
321
                if os.environ.has_key(var):
322
                    res = res + os.environ[var]
323
                if c != '':
324
                    res = res + c
325
        else:
326
            res = res + c
327
        index = index + 1
328
    return res
329

    
330

    
331