riscospath.py 9.76 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Module 'riscospath' -- common operations on RISC OS pathnames.

# contributed by Andrew Clover  ( andrew@oaktree.co.uk )

# The "os.path" name is an alias for this module on RISC OS systems;
# on other systems (e.g. Mac, Windows), os.path provides the same
# operations in a manner specific to that platform, and is an alias
# to another module (e.g. macpath, ntpath).

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

15 16 17
# strings representing various path-related bits and pieces
curdir = '@'
pardir = '^'
18
extsep = '/'
19 20 21 22
sep = '.'
pathsep = ','
defpath = '<Run$Dir>'
altsep = None
23 24 25 26 27 28 29

# Imports - make an error-generating swi object if the swi module is not
# available (ie. we are not running on RISC OS Python)

import os, stat, string

try:
Tim Peters's avatar
Tim Peters committed
30
    import swi
31
except ImportError:
Tim Peters's avatar
Tim Peters committed
32 33 34 35 36
    class _swi:
        def swi(*a):
            raise AttributeError, 'This function only available under RISC OS'
        block= swi
    swi= _swi()
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55

[_false, _true]= range(2)

_roots= ['$', '&', '%', '@', '\\']


# _allowMOSFSNames
# After importing riscospath, set _allowMOSFSNames true if you want the module
# to understand the "-SomeFS-" notation left over from the old BBC Master MOS,
# as well as the standard "SomeFS:" notation. Set this to be fully backwards
# compatible but remember that "-SomeFS-" can also be a perfectly valid file
# name so care must be taken when splitting and joining paths.

_allowMOSFSNames= _false


## Path manipulation, RISC OS stylee.

def _split(p):
Tim Peters's avatar
Tim Peters committed
56 57 58
    """
  split filing system name (including special field) and drive specifier from rest
  of path. This is needed by many riscospath functions.
59
  """
Tim Peters's avatar
Tim Peters committed
60 61 62 63 64 65 66 67 68 69 70
    dash= _allowMOSFSNames and p[:1]=='-'
    if dash:
        q= string.find(p, '-', 1)+1
    else:
        if p[:1]==':':
            q= 0
        else:
            q= string.find(p, ':')+1 # q= index of start of non-FS portion of path
    s= string.find(p, '#')
    if s==-1 or s>q:
        s= q # find end of main FS name, not including special field
71
    else:
Tim Peters's avatar
Tim Peters committed
72
        for c in p[dash:s]:
73
            if c not in string.ascii_letters:
Tim Peters's avatar
Tim Peters committed
74 75 76 77 78 79 80 81
                q= 0
                break # disallow invalid non-special-field characters in FS name
    r= q
    if p[q:q+1]==':':
        r= string.find(p, '.', q+1)+1
        if r==0:
            r= len(p) # find end of drive name (if any) following FS name (if any)
    return (p[:q], p[q:r], p[r:])
82 83 84


def normcase(p):
Tim Peters's avatar
Tim Peters committed
85 86 87 88
    """
  Normalize the case of a pathname. This converts to lowercase as the native RISC
  OS filesystems are case-insensitive. However, not all filesystems have to be,
  and there's no simple way to find out what type an FS is argh.
89
  """
Tim Peters's avatar
Tim Peters committed
90
    return string.lower(p)
91 92 93


def isabs(p):
Tim Peters's avatar
Tim Peters committed
94 95 96 97 98 99 100
    """
  Return whether a path is absolute. Under RISC OS, a file system specifier does
  not make a path absolute, but a drive name or number does, and so does using the
  symbol for root, URD, library, CSD or PSD. This means it is perfectly possible
  to have an "absolute" URL dependent on the current working directory, and
  equally you can have a "relative" URL that's on a completely different device to
  the current one argh.
101
  """
Tim Peters's avatar
Tim Peters committed
102 103
    (fs, drive, path)= _split(p)
    return drive!='' or path[:1] in _roots
104 105 106


def join(a, *p):
Tim Peters's avatar
Tim Peters committed
107 108 109
    """
  Join path elements with the directory separator, replacing the entire path when
  an absolute or FS-changing path part is found.
110
  """
Tim Peters's avatar
Tim Peters committed
111 112 113
    j= a
    for b in p:
        (fs, drive, path)= _split(b)
114
        if j=='' or fs!='' or drive!='' or path[:1] in _roots:
Tim Peters's avatar
Tim Peters committed
115
            j= b
116 117
        elif j[-1]==':':
            j= j+b
Tim Peters's avatar
Tim Peters committed
118 119 120
        else:
            j= j+'.'+b
    return j
121 122 123


def split(p):
Tim Peters's avatar
Tim Peters committed
124 125 126
    """
  Split a path in head (everything up to the last '.') and tail (the rest). FS
  name must still be dealt with separately since special field may contain '.'.
127
  """
Tim Peters's avatar
Tim Peters committed
128 129 130 131 132
    (fs, drive, path)= _split(p)
    q= string.rfind(path, '.')
    if q!=-1:
        return (fs+drive+path[:q], path[q+1:])
    return ('', p)
133 134 135


def splitext(p):
Tim Peters's avatar
Tim Peters committed
136 137 138
    """
  Split a path in root and extension. This assumes the 'using slash for dot and
  dot for slash with foreign files' convention common in RISC OS is in force.
139
  """
Tim Peters's avatar
Tim Peters committed
140 141 142 143 144
    (tail, head)= split(p)
    if '/' in head:
        q= len(head)-string.rfind(head, '/')
        return (p[:-q], p[-q:])
    return (p, '')
145 146 147


def splitdrive(p):
Tim Peters's avatar
Tim Peters committed
148 149 150 151
    """
  Split a pathname into a drive specification (including FS name) and the rest of
  the path. The terminating dot of the drive name is included in the drive
  specification.
152
  """
Tim Peters's avatar
Tim Peters committed
153 154
    (fs, drive, path)= _split(p)
    return (fs+drive, p)
155 156 157


def basename(p):
Tim Peters's avatar
Tim Peters committed
158 159
    """
  Return the tail (basename) part of a path.
160
  """
Tim Peters's avatar
Tim Peters committed
161
    return split(p)[1]
162 163 164


def dirname(p):
Tim Peters's avatar
Tim Peters committed
165 166
    """
  Return the head (dirname) part of a path.
167
  """
Tim Peters's avatar
Tim Peters committed
168
    return split(p)[0]
169 170


171 172 173 174 175 176 177 178 179 180
def commonprefix(m):
    "Given a list of pathnames, returns the longest common leading component"
    if not m: return ''
    s1 = min(m)
    s2 = max(m)
    n = min(len(s1), len(s2))
    for i in xrange(n):
        if s1[i] != s2[i]:
            return s1[:i]
    return s1[:n]
181 182 183 184 185


## File access functions. Why are we in os.path?

def getsize(p):
Tim Peters's avatar
Tim Peters committed
186 187
    """
  Return the size of a file, reported by os.stat().
188
  """
Tim Peters's avatar
Tim Peters committed
189 190
    st= os.stat(p)
    return st[stat.ST_SIZE]
191 192 193


def getmtime(p):
Tim Peters's avatar
Tim Peters committed
194 195
    """
  Return the last modification time of a file, reported by os.stat().
196
  """
Tim Peters's avatar
Tim Peters committed
197 198
    st = os.stat(p)
    return st[stat.ST_MTIME]
199 200 201 202 203 204 205

getatime= getmtime


# RISC OS-specific file access functions

def exists(p):
Tim Peters's avatar
Tim Peters committed
206 207
    """
  Test whether a path exists.
208
  """
Tim Peters's avatar
Tim Peters committed
209 210 211 212
    try:
        return swi.swi('OS_File', '5s;i', p)!=0
    except swi.error:
        return 0
213

214 215
lexists = exists

216 217

def isdir(p):
Tim Peters's avatar
Tim Peters committed
218 219
    """
  Is a path a directory? Includes image files.
220
  """
Tim Peters's avatar
Tim Peters committed
221 222 223 224
    try:
        return swi.swi('OS_File', '5s;i', p) in [2, 3]
    except swi.error:
        return 0
225 226 227


def isfile(p):
Tim Peters's avatar
Tim Peters committed
228 229
    """
  Test whether a path is a file, including image files.
230
  """
Tim Peters's avatar
Tim Peters committed
231 232 233 234
    try:
        return swi.swi('OS_File', '5s;i', p) in [1, 3]
    except swi.error:
        return 0
235 236 237


def islink(p):
Tim Peters's avatar
Tim Peters committed
238 239
    """
  RISC OS has no links or mounts.
240
  """
Tim Peters's avatar
Tim Peters committed
241
    return _false
242 243 244 245 246 247 248 249 250 251 252 253

ismount= islink


# Same-file testing.

# samefile works on filename comparison since there is no ST_DEV and ST_INO is
# not reliably unique (esp. directories). First it has to normalise the
# pathnames, which it can do 'properly' using OS_FSControl since samefile can
# assume it's running on RISC OS (unlike normpath).

def samefile(fa, fb):
Tim Peters's avatar
Tim Peters committed
254 255
    """
  Test whether two pathnames reference the same actual file.
256
  """
Tim Peters's avatar
Tim Peters committed
257 258 259 260 261 262 263
    l= 512
    b= swi.block(l)
    swi.swi('OS_FSControl', 'isb..i', 37, fa, b, l)
    fa= b.ctrlstring()
    swi.swi('OS_FSControl', 'isb..i', 37, fb, b, l)
    fb= b.ctrlstring()
    return fa==fb
264 265 266


def sameopenfile(a, b):
Tim Peters's avatar
Tim Peters committed
267 268
    """
  Test whether two open file objects reference the same file.
269
  """
Tim Peters's avatar
Tim Peters committed
270
    return os.fstat(a)[stat.ST_INO]==os.fstat(b)[stat.ST_INO]
271 272 273 274 275 276 277 278


## Path canonicalisation

# 'user directory' is taken as meaning the User Root Directory, which is in
# practice never used, for anything.

def expanduser(p):
Tim Peters's avatar
Tim Peters committed
279 280 281 282 283 284 285 286 287 288
    (fs, drive, path)= _split(p)
    l= 512
    b= swi.block(l)

    if path[:1]!='@':
        return p
    if fs=='':
        fsno= swi.swi('OS_Args', '00;i')
        swi.swi('OS_FSControl', 'iibi', 33, fsno, b, l)
        fsname= b.ctrlstring()
289
    else:
Tim Peters's avatar
Tim Peters committed
290 291 292 293 294 295
        if fs[:1]=='-':
            fsname= fs[1:-1]
        else:
            fsname= fs[:-1]
        fsname= string.split(fsname, '#', 1)[0] # remove special field from fs
    x= swi.swi('OS_FSControl', 'ib2s.i;.....i', 54, b, fsname, l)
296
    if x<l:
Tim Peters's avatar
Tim Peters committed
297 298 299 300 301 302 303 304
        urd= b.tostring(0, l-x-1)
    else: # no URD! try CSD
        x= swi.swi('OS_FSControl', 'ib0s.i;.....i', 54, b, fsname, l)
        if x<l:
            urd= b.tostring(0, l-x-1)
        else: # no CSD! use root
            urd= '$'
    return fsname+':'+urd+path[1:]
305 306 307 308

# Environment variables are in angle brackets.

def expandvars(p):
Tim Peters's avatar
Tim Peters committed
309 310
    """
  Expand environment variables using OS_GSTrans.
311
  """
Tim Peters's avatar
Tim Peters committed
312 313 314
    l= 512
    b= swi.block(l)
    return b.tostring(0, swi.swi('OS_GSTrans', 'sbi;..i', p, b, l))
315 316


317 318
# Return an absolute path. RISC OS' osfscontrol_canonicalise_path does this among others
abspath = os.expand
319 320


321 322 323 324
# realpath is a no-op on systems without islink support
realpath = abspath


325 326 327
# Normalize a path. Only special path element under RISC OS is "^" for "..".

def normpath(p):
Tim Peters's avatar
Tim Peters committed
328 329
    """
  Normalize path, eliminating up-directory ^s.
330
  """
Tim Peters's avatar
Tim Peters committed
331 332 333 334 335 336 337
    (fs, drive, path)= _split(p)
    rhs= ''
    ups= 0
    while path!='':
        (path, el)= split(path)
        if el=='^':
            ups= ups+1
338
        else:
Tim Peters's avatar
Tim Peters committed
339 340 341 342 343 344 345 346 347 348 349
            if ups>0:
                ups= ups-1
            else:
                if rhs=='':
                    rhs= el
                else:
                    rhs= el+'.'+rhs
    while ups>0:
        ups= ups-1
        rhs= '^.'+rhs
    return fs+drive+rhs
350 351 352 353 354 355


# Directory tree walk.
# Independent of host system. Why am I in os.path?

def walk(top, func, arg):
356 357 358 359 360 361 362 363 364 365 366 367 368 369
    """Directory tree walk with callback function.

    For each directory in the directory tree rooted at top (including top
    itself, but excluding '.' and '..'), call func(arg, dirname, fnames).
    dirname is the name of the directory, and fnames a list of the names of
    the files and subdirectories in dirname (excluding '.' and '..').  func
    may modify the fnames list in-place (e.g. via del or slice assignment),
    and walk will only recurse into the subdirectories whose names remain in
    fnames; this can be used to implement a filter, or to impose a specific
    order of visiting.  No semantics are defined for, or required of, arg,
    beyond that arg is always passed to func.  It can be used, e.g., to pass
    a filename pattern, or a mutable object designed to accumulate
    statistics.  Passing None for arg is common."""

Tim Peters's avatar
Tim Peters committed
370 371 372 373 374 375 376 377 378
    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)