# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is the Python XPCOM language bindings.
#
# The Initial Developer of the Original Code is
# ActiveState Tool Corp.
# Portions created by the Initial Developer are Copyright (C) 2000, 2001
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Mark Hammond <MarkH@ActiveState.com> (original author)
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
Introduction:
This module defines various class that are implemented using
Mozilla streams. This allows you to open Mozilla URI's, and
treat them as Python file object.
Example:
>>> file = URIFile("chrome://whatever")
>>> data = file.read(5) # Pass no arg to read everything.
Known Limitations:
* Not all URL schemes will work from "python.exe" - most notably
"chrome://" and "http://" URLs - this is because a simple initialization of
xpcom by Python does not load up the full set of Mozilla URL handlers.
If you can work out how to correctly initialize the chrome registry and
setup a message queue.
Known Bugs:
* Only read ("r") mode is supported. Although write ("w") mode doesnt make
sense for HTTP type URLs, it potentially does for file:// etc type ones.
* No concept of text mode vs binary mode. It appears Mozilla takes care of
this internally (ie, all "text/???" mime types are text, rest are binary)
"""
import os
# A helper function that may come in useful
"Convert a filename to an XPCOM nsIFileURL object."
# Create an nsILocalFile
# Use the IO Service to create the interface, then QI for a FileURL
# Setting the "file" attribute causes initialization...
return url
# A base class for file objects.
class _File:
if name_thingy is not None:
# The Moz file streams are not thread safe.
try:
finally:
# Not part of the xpcom interface, but handy for direct Python users.
# Not 100% faithful, but near enough for now!
return [s+"\n" for s in lines ]
try:
finally:
try:
if self.inputStream is not None:
self.inputStream = None
if self.outputStream is not None:
self.outputStream = None
finally:
try:
finally:
# A synchronous "file object" used to open a URI.
if mode != "r":
raise ValueError, "only 'r' mode supported'"
else:
# Mozilla asserts and starts saying "NULL POINTER" if this is wrong!
raise ValueError, ("The URI '%s' is invalid (no scheme)"
# A "file object" implemented using Netscape's native file support.
# Based on io.js - http://lxr.mozilla.org/seamonkey/source/xpcom/tests/utils/io.js
# You open this file using a local file name (as a string) so it really is pointless -
# you may as well be using a standard Python file object!
self.fileIO = components.classes["@mozilla.org/network/file-output-stream;1"].createInstance("nsIFileOutputStream")
if mode== "w":
elif mode=="a":
else:
assert 0, "Can't happen!"
elif mode == "r":
self.fileIO = components.classes["@mozilla.org/network/file-input-stream;1"].createInstance("nsIFileInputStream")
self.inputStream = components.classes["@mozilla.org/scriptableinputstream;1"].createInstance("nsIScriptableInputStream")
else:
raise ValueError, "Unknown mode"
##########################################################
##
## Test Code
##
##########################################################
# read in a couple of chunks, just to test that our various arg combinations work.
raise RuntimeError, "Reading '%s' failed - got %d bytes, but expected %d bytes" % (file, len(got), len(expected))
# read in a couple of chunks, just to test that our various arg combinations work.
got = ''
while 1:
# Note - we need to reach into the file object so we
# can get at the native buffer supported function.
if num == 0:
break
raise RuntimeError, "Reading '%s' failed - got %d bytes, but expected %d bytes" % (file, len(got), len(expected))
def _TestLocalFile():
data = "Hello from Python"
try:
# Make sure Python can read it OK.
f.close()
# For the sake of the test, try a re-init.
# Try reading in chunks.
# Open the same file again for writing - this should delete the old one.
raise RuntimeError, "The file '%s' does not exist, but we are explicitly testing create semantics when it does" % (fname,)
# Make sure Python can read it OK.
assert f.read() == data, "Eeek - Python could not read the data back correctly after recreating an existing file!"
f.close()
# XXX - todo - test "a" mode!
finally:
def _TestAll():
# A mini test suite.
# Get a test file, and convert it to a file:// URI.
# check what we read is the same as when
# we read this file "normally"
# convert the fname to a URI.
# First try passing a URL as a string.
# Now with a URL object.
# For the sake of testing, do our pointless, demo object!
# Now do the full test of our pointless, demo object!
print "Opened file is", test_file
if __name__=='__main__':
import sys
print "No URL specified on command line - performing self-test"
_TestAll()
else: