/Lib/plat-riscos/rourl2path.py

http://unladen-swallow.googlecode.com/ · Python · 70 lines · 63 code · 4 blank · 3 comment · 0 complexity · 094dfcb9ff9ddcfb26d47271f874bfdb MD5 · raw file

  1. """riscos specific module for conversion between pathnames and URLs.
  2. Based on macurl2path.
  3. Do not import directly, use urllib instead."""
  4. import string
  5. import urllib
  6. __all__ = ["url2pathname","pathname2url"]
  7. __slash_dot = string.maketrans("/.", "./")
  8. def url2pathname(url):
  9. """OS-specific conversion from a relative URL of the 'file' scheme
  10. to a file system path; not recommended for general use."""
  11. tp = urllib.splittype(url)[0]
  12. if tp and tp <> 'file':
  13. raise RuntimeError, 'Cannot convert non-local URL to pathname'
  14. # Turn starting /// into /, an empty hostname means current host
  15. if url[:3] == '///':
  16. url = url[2:]
  17. elif url[:2] == '//':
  18. raise RuntimeError, 'Cannot convert non-local URL to pathname'
  19. components = string.split(url, '/')
  20. if not components[0]:
  21. if '$' in components:
  22. del components[0]
  23. else:
  24. components[0] = '$'
  25. # Remove . and embedded ..
  26. i = 0
  27. while i < len(components):
  28. if components[i] == '.':
  29. del components[i]
  30. elif components[i] == '..' and i > 0 and \
  31. components[i-1] not in ('', '..'):
  32. del components[i-1:i+1]
  33. i -= 1
  34. elif components[i] == '..':
  35. components[i] = '^'
  36. i += 1
  37. elif components[i] == '' and i > 0 and components[i-1] <> '':
  38. del components[i]
  39. else:
  40. i += 1
  41. components = map(lambda x: urllib.unquote(x).translate(__slash_dot), components)
  42. return '.'.join(components)
  43. def pathname2url(pathname):
  44. """OS-specific conversion from a file system path to a relative URL
  45. of the 'file' scheme; not recommended for general use."""
  46. return urllib.quote('///' + pathname.translate(__slash_dot), "/$:")
  47. def test():
  48. for url in ["index.html",
  49. "/SCSI::SCSI4/$/Anwendung/Comm/Apps/!Fresco/Welcome",
  50. "/SCSI::SCSI4/$/Anwendung/Comm/Apps/../!Fresco/Welcome",
  51. "../index.html",
  52. "bar/index.html",
  53. "/foo/bar/index.html",
  54. "/foo/bar/",
  55. "/"]:
  56. print '%r -> %r' % (url, url2pathname(url))
  57. print "*******************************************************"
  58. for path in ["SCSI::SCSI4.$.Anwendung",
  59. "PythonApp:Lib",
  60. "PythonApp:Lib.rourl2path/py"]:
  61. print '%r -> %r' % (path, pathname2url(path))
  62. if __name__ == '__main__':
  63. test()