aboutsummaryrefslogtreecommitdiffstats
path: root/lib/jython/Lib/javapath.py
blob: 8292331b99ae5c8586bece3b4f8f290d5779d475 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
"""Common pathname manipulations, JDK version.

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

"""

# Incompletely implemented:
# islink -- How?
# ismount -- How?
# splitdrive -- How?
# normcase -- How?

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

import java
from java.io import File
from java.lang import System
import os

def _tostr(s, method):
    if isinstance(s, "".__class__):
        return s
    import org
    raise TypeError, "%s() argument must be a string object, not %s" % (
                method, org.python.core.Py.safeRepr(s))
        
def dirname(path):
    """Return the directory component of a pathname"""
    path = _tostr(path, "dirname")
    result = File(path).getParent()
    if not result:
	if isabs(path):
	    result = path # Must be root
	else:
	    result = ""
    return result

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

def split(path):
    """Split a pathname.

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

    """
    path = _tostr(path, "split")
    return (dirname(path), basename(path))

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

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

    """
    i = 0
    n = -1
    for c in path:
        if c == '.': n = i
        i = i+1
    if n < 0:
        return (path, "")
    else:
        return (path[:n], path[n:])

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

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

    """
    return ("", path)

def exists(path):
    """Test whether a path exists.

    Returns false for broken symbolic links.

    """
    path = _tostr(path, "exists")
    return File(path).exists()

def isabs(path):
    """Test whether a path is absolute"""
    path = _tostr(path, "isabs")
    return File(path).isAbsolute()

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

def isdir(path):
    """Test whether a path is a directory"""
    path = _tostr(path, "isdir")
    return File(path).isDirectory()

def join(path, *args):
    """Join two or more pathname components, inserting os.sep as needed"""
    path = _tostr(path, "join")
    f = File(path)
    for a in args:
        a = _tostr(a, "join")
	g = File(a)
	if g.isAbsolute() or len(f.getPath()) == 0:
	    f = g
	else:
	    f = File(f, a)
    return f.getPath()

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

    XXX Not done right under JDK.

    """
    path = _tostr(path, "normcase")
    return File(path).getPath()

def commonprefix(m):
    "Given a list of pathnames, return the longest common leading component"
    if not m: return ''
    prefix = m[0]
    for item in m:
        for i in range(len(prefix)):
            if prefix[:i+1] <> item[:i+1]:
                prefix = prefix[:i]
                if i == 0: return ''
                break
    return prefix

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

    XXX This incorrectly always returns false under JDK.

    """
    return 0

def samefile(path, path2):
    """Test whether two pathnames reference the same actual file"""
    path = _tostr(path, "samefile")
    path2 = _tostr(path2, "samefile")
    f = File(path)
    f2 = File(path2)
    return f.getCanonicalPath() == f2.getCanonicalPath()

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

    XXX This incorrectly always returns false under JDK.

    """
    return 0


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

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

    """
    try:
        names = os.listdir(top)
    except os.error:
        return
    func(arg, top, names)
    for name in names:
	name = join(top, name)
	if isdir(name) and not islink(name):
	    walk(name, func, arg)

def expanduser(path):
    if path[:1] == "~":
	c = path[1:2]
	if not c:
	    return gethome()
	if c == os.sep:
	    return File(gethome(), path[2:]).getPath()
    return path

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

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


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

# Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
# It should be understood that this may change the meaning of the path
# if it contains symbolic links!
def normpath(path):
    """Normalize path, eliminating double slashes, etc."""
    sep = os.sep
    if sep == '\\':
        path = path.replace("/", sep)
    curdir = os.curdir
    pardir = os.pardir
    import string
    # Treat initial slashes specially
    slashes = ''
    while path[:1] == sep:
        slashes = slashes + sep
        path = path[1:]
    comps = string.splitfields(path, sep)
    i = 0
    while i < len(comps):
        if comps[i] == curdir:
            del comps[i]
            while i < len(comps) and comps[i] == '':
                del comps[i]
        elif comps[i] == pardir and i > 0 and comps[i-1] not in ('', pardir):
            del comps[i-1:i+1]
            i = i-1
        elif comps[i] == '' and i > 0 and comps[i-1] <> '':
            del comps[i]
        else:
            i = i+1
    # If the path is now empty, substitute '.'
    if not comps and not slashes:
        comps.append(curdir)
    return slashes + string.joinfields(comps, sep)

# Return an absolute path.
def abspath(path):
    path = _tostr(path, "abspath")
    return File(path).getAbsolutePath()


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

def getmtime(path):
    path = _tostr(path, "getmtime")
    f = File(path)
    return f.lastModified() / 1000.0

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


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

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

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

    Unknown variables are left unchanged."""
    if '$' not in path:
        return path
    import string
    varchars = string.letters + string.digits + '_-'
    res = ''
    index = 0
    pathlen = len(path)
    while index < pathlen:
        c = path[index]
        if c == '\'':   # no expansion within single quotes
            path = path[index + 1:]
            pathlen = len(path)
            try:
                index = path.index('\'')
                res = res + '\'' + path[:index + 1]
            except ValueError:
                res = res + path
                index = pathlen - 1
        elif c == '$':  # variable or '$$'
            if path[index + 1:index + 2] == '$':
                res = res + c
                index = index + 1
            elif path[index + 1:index + 2] == '{':
                path = path[index+2:]
                pathlen = len(path)
                try:
                    index = path.index('}')
                    var = path[:index]
                    if os.environ.has_key(var):
                        res = res + os.environ[var]
                except ValueError:
                    res = res + path
                    index = pathlen - 1
            else:
                var = ''
                index = index + 1
                c = path[index:index + 1]
                while c != '' and c in varchars:
                    var = var + c
                    index = index + 1
                    c = path[index:index + 1]
                if os.environ.has_key(var):
                    res = res + os.environ[var]
                if c != '':
                    res = res + c
        else:
            res = res + c
        index = index + 1
    return res