Skip to content
Browse files

movd filelike into its own SVN repo

git-svn-id: file:///storage/svnroot/software/filelike/trunk@1 a5982802-4688-4032-98e1-1c42b60d9872
  • Loading branch information...
0 parents commit cc32ceb83289de40ef8b817982dcb52b511485f0 rfk committed
Showing with 2,613 additions and 0 deletions.
  1. +33 −0 ChangeLog
  2. +504 −0 LICENSE.txt
  3. +13 −0 README.txt
  4. +221 −0 ez_setup.py
  5. +526 −0 filelike/__init__.py
  6. +266 −0 filelike/pipeline.py
  7. +998 −0 filelike/wrappers.py
  8. +52 −0 setup.py
33 ChangeLog
@@ -0,0 +1,33 @@
+
+Version 0.2.2
+
+ * Several patches to Cat thanks to Alan Fairless
+
+Version 0.2.1
+
+ * Added filelike.open() functions, which tries to open files in
+ a smart manner (e.g. fetching URLs, transparent unzipping, etc)
+
+
+Version 0.2.0:
+
+ Architectural Changes:
+
+ * Moved wrapper classes into filelike.wrappers
+ * Created filelike.pipeline, which employs operator abuse to compose
+ file wrappers using a unix pipeline style
+
+ Functional Changes:
+
+ * Allow _write() to return any unwritten data, which will be cached
+ for later writing. None may be returned if all data is written.
+ Also give it a <flushing> argument to indicate when no more data
+ will be forthcoming
+ * Validate access mode before reading/writing in FileLikeBase
+ * Permit seperate reading and writing translation functions for TransFile
+ * Added the following FileWrapper subclasses:
+ * PaddedToBlockSizeFile: ensure file's contents meet a blocksize
+ * Head: similar to unix `head` command
+ * Cat: similar to unix `cat` command
+ * BZ2File: similar to that found in the std lib
+
504 LICENSE.txt
@@ -0,0 +1,504 @@
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 2.1, February 1999
+
+ Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+ 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+[This is the first released version of the Lesser GPL. It also counts
+ as the successor of the GNU Library Public License, version 2, hence
+ the version number 2.1.]
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
+
+ This license, the Lesser General Public License, applies to some
+specially designated software packages--typically libraries--of the
+Free Software Foundation and other authors who decide to use it. You
+can use it too, but we suggest you first think carefully about whether
+this license or the ordinary General Public License is the better
+strategy to use in any particular case, based on the explanations below.
+
+ When we speak of free software, we are referring to freedom of use,
+not price. Our General Public Licenses are designed to make sure that
+you have the freedom to distribute copies of free software (and charge
+for this service if you wish); that you receive source code or can get
+it if you want it; that you can change the software and use pieces of
+it in new free programs; and that you are informed that you can do
+these things.
+
+ To protect your rights, we need to make restrictions that forbid
+distributors to deny you these rights or to ask you to surrender these
+rights. These restrictions translate to certain responsibilities for
+you if you distribute copies of the library or if you modify it.
+
+ For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you. You must make sure that they, too, receive or can get the source
+code. If you link other code with the library, you must provide
+complete object files to the recipients, so that they can relink them
+with the library after making changes to the library and recompiling
+it. And you must show them these terms so they know their rights.
+
+ We protect your rights with a two-step method: (1) we copyright the
+library, and (2) we offer you this license, which gives you legal
+permission to copy, distribute and/or modify the library.
+
+ To protect each distributor, we want to make it very clear that
+there is no warranty for the free library. Also, if the library is
+modified by someone else and passed on, the recipients should know
+that what they have is not the original version, so that the original
+author's reputation will not be affected by problems that might be
+introduced by others.
+
+ Finally, software patents pose a constant threat to the existence of
+any free program. We wish to make sure that a company cannot
+effectively restrict the users of a free program by obtaining a
+restrictive license from a patent holder. Therefore, we insist that
+any patent license obtained for a version of the library must be
+consistent with the full freedom of use specified in this license.
+
+ Most GNU software, including some libraries, is covered by the
+ordinary GNU General Public License. This license, the GNU Lesser
+General Public License, applies to certain designated libraries, and
+is quite different from the ordinary General Public License. We use
+this license for certain libraries in order to permit linking those
+libraries into non-free programs.
+
+ When a program is linked with a library, whether statically or using
+a shared library, the combination of the two is legally speaking a
+combined work, a derivative of the original library. The ordinary
+General Public License therefore permits such linking only if the
+entire combination fits its criteria of freedom. The Lesser General
+Public License permits more lax criteria for linking other code with
+the library.
+
+ We call this license the "Lesser" General Public License because it
+does Less to protect the user's freedom than the ordinary General
+Public License. It also provides other free software developers Less
+of an advantage over competing non-free programs. These disadvantages
+are the reason we use the ordinary General Public License for many
+libraries. However, the Lesser license provides advantages in certain
+special circumstances.
+
+ For example, on rare occasions, there may be a special need to
+encourage the widest possible use of a certain library, so that it becomes
+a de-facto standard. To achieve this, non-free programs must be
+allowed to use the library. A more frequent case is that a free
+library does the same job as widely used non-free libraries. In this
+case, there is little to gain by limiting the free library to free
+software only, so we use the Lesser General Public License.
+
+ In other cases, permission to use a particular library in non-free
+programs enables a greater number of people to use a large body of
+free software. For example, permission to use the GNU C Library in
+non-free programs enables many more people to use the whole GNU
+operating system, as well as its variant, the GNU/Linux operating
+system.
+
+ Although the Lesser General Public License is Less protective of the
+users' freedom, it does ensure that the user of a program that is
+linked with the Library has the freedom and the wherewithal to run
+that program using a modified version of the Library.
+
+ The precise terms and conditions for copying, distribution and
+modification follow. Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library". The
+former contains code derived from the library, whereas the latter must
+be combined with the library in order to run.
+
+ GNU LESSER GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License Agreement applies to any software library or other
+program which contains a notice placed by the copyright holder or
+other authorized party saying it may be distributed under the terms of
+this Lesser General Public License (also called "this License").
+Each licensee is addressed as "you".
+
+ A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+ The "Library", below, refers to any such software library or work
+which has been distributed under these terms. A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language. (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+ "Source code" for a work means the preferred form of the work for
+making modifications to it. For a library, complete source code means
+all the source code for all modules it contains, plus any associated
+interface definition files, plus the scripts used to control compilation
+and installation of the library.
+
+ Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it). Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+
+ 1. You may copy and distribute verbatim copies of the Library's
+complete source code as you receive it, in any medium, provided that
+you conspicuously and appropriately publish on each copy an
+appropriate copyright notice and disclaimer of warranty; keep intact
+all the notices that refer to this License and to the absence of any
+warranty; and distribute a copy of this License along with the
+Library.
+
+ You may charge a fee for the physical act of transferring a copy,
+and you may at your option offer warranty protection in exchange for a
+fee.
+
+ 2. You may modify your copy or copies of the Library or any portion
+of it, thus forming a work based on the Library, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) The modified work must itself be a software library.
+
+ b) You must cause the files modified to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ c) You must cause the whole of the work to be licensed at no
+ charge to all third parties under the terms of this License.
+
+ d) If a facility in the modified Library refers to a function or a
+ table of data to be supplied by an application program that uses
+ the facility, other than as an argument passed when the facility
+ is invoked, then you must make a good faith effort to ensure that,
+ in the event an application does not supply such function or
+ table, the facility still operates, and performs whatever part of
+ its purpose remains meaningful.
+
+ (For example, a function in a library to compute square roots has
+ a purpose that is entirely well-defined independent of the
+ application. Therefore, Subsection 2d requires that any
+ application-supplied function or table used by this function must
+ be optional: if the application does not supply it, the square
+ root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Library,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Library, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote
+it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library. To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License. (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.) Do not make any other change in
+these notices.
+
+ Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+ This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+ 4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you accompany
+it with the complete corresponding machine-readable source code, which
+must be distributed under the terms of Sections 1 and 2 above on a
+medium customarily used for software interchange.
+
+ If distribution of object code is made by offering access to copy
+from a designated place, then offering equivalent access to copy the
+source code from the same place satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library". Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+ However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library". The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+ When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library. The
+threshold for this to be true is not precisely defined by law.
+
+ If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work. (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+ Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+
+ 6. As an exception to the Sections above, you may also combine or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+ You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License. You must supply a copy of this License. If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License. Also, you must do one
+of these things:
+
+ a) Accompany the work with the complete corresponding
+ machine-readable source code for the Library including whatever
+ changes were used in the work (which must be distributed under
+ Sections 1 and 2 above); and, if the work is an executable linked
+ with the Library, with the complete machine-readable "work that
+ uses the Library", as object code and/or source code, so that the
+ user can modify the Library and then relink to produce a modified
+ executable containing the modified Library. (It is understood
+ that the user who changes the contents of definitions files in the
+ Library will not necessarily be able to recompile the application
+ to use the modified definitions.)
+
+ b) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (1) uses at run time a
+ copy of the library already present on the user's computer system,
+ rather than copying library functions into the executable, and (2)
+ will operate properly with a modified version of the library, if
+ the user installs one, as long as the modified version is
+ interface-compatible with the version that the work was made with.
+
+ c) Accompany the work with a written offer, valid for at
+ least three years, to give the same user the materials
+ specified in Subsection 6a, above, for a charge no more
+ than the cost of performing this distribution.
+
+ d) If distribution of the work is made by offering access to copy
+ from a designated place, offer equivalent access to copy the above
+ specified materials from the same place.
+
+ e) Verify that the user has already received a copy of these
+ materials or that you have already sent this user a copy.
+
+ For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it. However, as a special exception,
+the materials to be distributed need not include anything that is
+normally distributed (in either source or binary form) with the major
+components (compiler, kernel, and so on) of the operating system on
+which the executable runs, unless that component itself accompanies
+the executable.
+
+ It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system. Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+
+ 7. You may place library facilities that are a work based on the
+Library side-by-side in a single library together with other library
+facilities not covered by this License, and distribute such a combined
+library, provided that the separate distribution of the work based on
+the Library and of the other library facilities is otherwise
+permitted, and provided that you do these two things:
+
+ a) Accompany the combined library with a copy of the same work
+ based on the Library, uncombined with any other library
+ facilities. This must be distributed under the terms of the
+ Sections above.
+
+ b) Give prominent notice with the combined library of the fact
+ that part of it is a work based on the Library, and explaining
+ where to find the accompanying uncombined form of the same work.
+
+ 8. You may not copy, modify, sublicense, link with, or distribute
+the Library except as expressly provided under this License. Any
+attempt otherwise to copy, modify, sublicense, link with, or
+distribute the Library is void, and will automatically terminate your
+rights under this License. However, parties who have received copies,
+or rights, from you under this License will not have their licenses
+terminated so long as such parties remain in full compliance.
+
+ 9. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Library or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+
+ 10. Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+subject to these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties with
+this License.
+
+ 11. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Library at all. For example, if a patent
+license would not permit royalty-free redistribution of the Library by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under any
+particular circumstance, the balance of the section is intended to apply,
+and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 12. If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library under this License may add
+an explicit geographical distribution limitation excluding those countries,
+so that distribution is permitted only in or among countries not thus
+excluded. In such case, this License incorporates the limitation as if
+written in the body of this License.
+
+ 13. The Free Software Foundation may publish revised and/or new
+versions of the Lesser General Public License from time to time.
+Such new versions will be similar in spirit to the present version,
+but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Library
+specifies a version number of this License which applies to it and
+"any later version", you have the option of following the terms and
+conditions either of that version or of any later version published by
+the Free Software Foundation. If the Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+
+ 14. If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+write to the author to ask for permission. For software which is
+copyrighted by the Free Software Foundation, write to the Free
+Software Foundation; we sometimes make exceptions for this. Our
+decision will be guided by the two goals of preserving the free status
+of all derivatives of our free software and of promoting the sharing
+and reuse of software generally.
+
+ NO WARRANTY
+
+ 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
+LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Libraries
+
+ If you develop a new library, and you want it to be of the greatest
+possible use to the public, we recommend making it free software that
+everyone can redistribute and change. You can do so by permitting
+redistribution under these terms (or, alternatively, under the terms of the
+ordinary General Public License).
+
+ To apply these terms, attach the following notices to the library. It is
+safest to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least the
+"copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the library's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+
+Also add information on how to contact you by electronic and paper mail.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the library, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the
+ library `Frob' (a library for tweaking knobs) written by James Random Hacker.
+
+ <signature of Ty Coon>, 1 April 1990
+ Ty Coon, President of Vice
+
+That's all there is to it!
+
+
13 README.txt
@@ -0,0 +1,13 @@
+
+This is filelike, a python module for creating and manipulating file-like
+objects. For details, enter a python shell and do the following:
+
+ >>> import filelike
+ >>> help(filelike)
+
+
+Bugs, comments, questions etc can be sent to the author at:
+
+ ryan@rfk.id.au
+
+
221 ez_setup.py
@@ -0,0 +1,221 @@
+#!python
+"""Bootstrap setuptools installation
+
+If you want to use setuptools in your package's setup.py, just include this
+file in the same directory with it, and add this to the top of your setup.py::
+
+ from ez_setup import use_setuptools
+ use_setuptools()
+
+If you want to require a specific version of setuptools, set a download
+mirror, or use an alternate download directory, you can do so by supplying
+the appropriate options to ``use_setuptools()``.
+
+This file can also be run as a script to install or upgrade setuptools.
+"""
+import sys
+DEFAULT_VERSION = "0.6a9"
+DEFAULT_URL = "http://cheeseshop.python.org/packages/%s/s/setuptools/" % sys.version[:3]
+
+md5_data = {
+ 'setuptools-0.5a13-py2.3.egg': '85edcf0ef39bab66e130d3f38f578c86',
+ 'setuptools-0.5a13-py2.4.egg': 'ede4be600e3890e06d4ee5e0148e092a',
+ 'setuptools-0.6a1-py2.3.egg': 'ee819a13b924d9696b0d6ca6d1c5833d',
+ 'setuptools-0.6a1-py2.4.egg': '8256b5f1cd9e348ea6877b5ddd56257d',
+ 'setuptools-0.6a2-py2.3.egg': 'b98da449da411267c37a738f0ab625ba',
+ 'setuptools-0.6a2-py2.4.egg': 'be5b88bc30aed63fdefd2683be135c3b',
+ 'setuptools-0.6a3-py2.3.egg': 'ee0e325de78f23aab79d33106dc2a8c8',
+ 'setuptools-0.6a3-py2.4.egg': 'd95453d525a456d6c23e7a5eea89a063',
+ 'setuptools-0.6a4-py2.3.egg': 'e958cbed4623bbf47dd1f268b99d7784',
+ 'setuptools-0.6a4-py2.4.egg': '7f33c3ac2ef1296f0ab4fac1de4767d8',
+ 'setuptools-0.6a5-py2.3.egg': '748408389c49bcd2d84f6ae0b01695b1',
+ 'setuptools-0.6a5-py2.4.egg': '999bacde623f4284bfb3ea77941d2627',
+ 'setuptools-0.6a6-py2.3.egg': '7858139f06ed0600b0d9383f36aca24c',
+ 'setuptools-0.6a6-py2.4.egg': 'c10d20d29acebce0dc76219dc578d058',
+ 'setuptools-0.6a7-py2.3.egg': 'cfc4125ddb95c07f9500adc5d6abef6f',
+ 'setuptools-0.6a7-py2.4.egg': 'c6d62dab4461f71aed943caea89e6f20',
+ 'setuptools-0.6a8-py2.3.egg': '2f18eaaa3f544f5543ead4a68f3b2e1a',
+ 'setuptools-0.6a8-py2.4.egg': '799018f2894f14c9f8bcb2b34e69b391',
+ 'setuptools-0.6a9-py2.3.egg': '8e438ad70438b07b0d8f82cae42b278f',
+ 'setuptools-0.6a9-py2.4.egg': '8f6e01fc12fb1cd006dc0d6c04327ec1',
+}
+
+import sys, os
+
+def _validate_md5(egg_name, data):
+ if egg_name in md5_data:
+ from md5 import md5
+ digest = md5(data).hexdigest()
+ if digest != md5_data[egg_name]:
+ print >>sys.stderr, (
+ "md5 validation of %s failed! (Possible download problem?)"
+ % egg_name
+ )
+ sys.exit(2)
+ return data
+
+
+def use_setuptools(
+ version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
+ download_delay=15
+):
+ """Automatically find/download setuptools and make it available on sys.path
+
+ `version` should be a valid setuptools version number that is available
+ as an egg for download under the `download_base` URL (which should end with
+ a '/'). `to_dir` is the directory where setuptools will be downloaded, if
+ it is not already available. If `download_delay` is specified, it should
+ be the number of seconds that will be paused before initiating a download,
+ should one be required. If an older version of setuptools is installed,
+ this routine will print a message to ``sys.stderr`` and raise SystemExit in
+ an attempt to abort the calling script.
+ """
+ try:
+ import setuptools
+ if setuptools.__version__ == '0.0.1':
+ print >>sys.stderr, (
+ "You have an obsolete version of setuptools installed. Please\n"
+ "remove it from your system entirely before rerunning this script."
+ )
+ sys.exit(2)
+ except ImportError:
+ egg = download_setuptools(version, download_base, to_dir, download_delay)
+ sys.path.insert(0, egg)
+ import setuptools; setuptools.bootstrap_install_from = egg
+
+ import pkg_resources
+ try:
+ pkg_resources.require("setuptools>="+version)
+
+ except pkg_resources.VersionConflict:
+ # XXX could we install in a subprocess here?
+ print >>sys.stderr, (
+ "The required version of setuptools (>=%s) is not available, and\n"
+ "can't be installed while this script is running. Please install\n"
+ " a more recent version first."
+ ) % version
+ sys.exit(2)
+
+def download_setuptools(
+ version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
+ delay = 15
+):
+ """Download setuptools from a specified location and return its filename
+
+ `version` should be a valid setuptools version number that is available
+ as an egg for download under the `download_base` URL (which should end
+ with a '/'). `to_dir` is the directory where the egg will be downloaded.
+ `delay` is the number of seconds to pause before an actual download attempt.
+ """
+ import urllib2, shutil
+ egg_name = "setuptools-%s-py%s.egg" % (version,sys.version[:3])
+ url = download_base + egg_name
+ saveto = os.path.join(to_dir, egg_name)
+ src = dst = None
+ if not os.path.exists(saveto): # Avoid repeated downloads
+ try:
+ from distutils import log
+ if delay:
+ log.warn("""
+---------------------------------------------------------------------------
+This script requires setuptools version %s to run (even to display
+help). I will attempt to download it for you (from
+%s), but
+you may need to enable firewall access for this script first.
+I will start the download in %d seconds.
+---------------------------------------------------------------------------""",
+ version, download_base, delay
+ ); from time import sleep; sleep(delay)
+ log.warn("Downloading %s", url)
+ src = urllib2.urlopen(url)
+ # Read/write all in one block, so we don't create a corrupt file
+ # if the download is interrupted.
+ data = _validate_md5(egg_name, src.read())
+ dst = open(saveto,"wb"); dst.write(data)
+ finally:
+ if src: src.close()
+ if dst: dst.close()
+ return os.path.realpath(saveto)
+
+def main(argv, version=DEFAULT_VERSION):
+ """Install or upgrade setuptools and EasyInstall"""
+
+ try:
+ import setuptools
+ except ImportError:
+ import tempfile, shutil
+ tmpdir = tempfile.mkdtemp(prefix="easy_install-")
+ try:
+ egg = download_setuptools(version, to_dir=tmpdir, delay=0)
+ sys.path.insert(0,egg)
+ from setuptools.command.easy_install import main
+ main(list(argv)+[egg])
+ finally:
+ shutil.rmtree(tmpdir)
+ else:
+ if setuptools.__version__ == '0.0.1':
+ # tell the user to uninstall obsolete version
+ use_setuptools(version)
+
+ req = "setuptools>="+version
+ import pkg_resources
+ try:
+ pkg_resources.require(req)
+ except pkg_resources.VersionConflict:
+ try:
+ from setuptools.command.easy_install import main
+ except ImportError:
+ from easy_install import main
+ main(list(argv)+[download_setuptools(delay=0)])
+ sys.exit(0) # try to force an exit
+ else:
+ if argv:
+ from setuptools.command.easy_install import main
+ main(argv)
+ else:
+ print "Setuptools version",version,"or greater has been installed."
+ print '(Run "ez_setup.py -U setuptools" to reinstall or upgrade.)'
+
+
+
+def update_md5(filenames):
+ """Update our built-in md5 registry"""
+
+ import re
+ from md5 import md5
+
+ for name in filenames:
+ base = os.path.basename(name)
+ f = open(name,'rb')
+ md5_data[base] = md5(f.read()).hexdigest()
+ f.close()
+
+ data = [" %r: %r,\n" % it for it in md5_data.items()]
+ data.sort()
+ repl = "".join(data)
+
+ import inspect
+ srcfile = inspect.getsourcefile(sys.modules[__name__])
+ f = open(srcfile, 'rb'); src = f.read(); f.close()
+
+ match = re.search("\nmd5_data = {\n([^}]+)}", src)
+ if not match:
+ print >>sys.stderr, "Internal error!"
+ sys.exit(2)
+
+ src = src[:match.start(1)] + repl + src[match.end(1):]
+ f = open(srcfile,'w')
+ f.write(src)
+ f.close()
+
+
+if __name__=='__main__':
+ if len(sys.argv)>2 and sys.argv[1]=='--md5update':
+ update_md5(sys.argv[2:])
+ else:
+ main(sys.argv[1:])
+
+
+
+
+
526 filelike/__init__.py
@@ -0,0 +1,526 @@
+# filelike.py
+#
+# Copyright (C) 2006, Ryan Kelly
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License, or (at your option) any later version.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the
+# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+# Boston, MA 02111-1307, USA.
+#
+"""
+The filelike module takes care of the groundwork for implementing and
+handling file-like objects that implement a rich file-like interface,
+including reading, writing, and iteration. It also provides a number
+of useful classes built on top of this functionality.
+
+The main class is FileLikeBase, which implements the entire file-like
+interface (currently minus seek() and tell()) on top of primitive
+_read() and _write() methods. Subclasses may implement either or
+both of these methods to obtain all the higher-level file behaviors.
+
+Two methods are provided for when code expects to deal with file-like objects:
+
+ * is_filelike(obj): checks that an object is file-like
+ * to_filelike(obj): wraps a variety of objects in a file-like interface
+
+The "wrappers" subpackage contains a collection of useful classes built on
+top of this framework. These include:
+
+ * TransFile: pass file contents through an arbitrary translation
+ function (e.g. compression, encryption, ...)
+
+ * FixedBlockSizeFile: ensure all read/write requests are aligned with
+ a given blocksize
+
+ * DecryptFile: on-the-fly reading and writing to an encrypted file
+ (using PEP272 cipher API)
+
+As an example of the type of thing this module is designed to achieve, here's
+an example of using the DecryptFile class to transparently access an encrypted
+file:
+
+ # Create the decryption key
+ from Crypto.Cipher import DES
+ cipher = DES.new('abcdefgh',DES.MODE_ECB)
+ # Open the encrypted file
+ from filelike.wrappers import DecryptFile
+ f = DecryptFile(file("some_encrypted_file.bin","r"),cipher)
+
+The object in <f> now behaves as a file-like object, transparently decrypting
+the file on-the-fly as it is read.
+
+The "pipeline" subpackage contains facilities for composing these wrappers
+in the form of a unix pipeline. In this example, <f> will read the
+first five lines of an encrypted file:
+
+ from filelike.pipeline import DecryptFile, Head
+ f = file("some_encrypted_file.bin") > DecryptFile(cipher) | Head(lines=5)
+
+
+Finally, the function filelike.open() mirrors the standard file opening function
+but tries to be clever about accessing the file - URLs are automatically fetched
+using urllib2, compressed files are decompressed on-the-fly, and so-forth.
+
+"""
+
+__ver_major__ = 0
+__ver_minor__ = 2
+__ver_patch__ = 2
+__ver_sub__ = ""
+__version__ = "%d.%d.%d%s" % (__ver_major__,__ver_minor__,
+ __ver_patch__,__ver_sub__)
+
+
+import unittest
+import StringIO
+import urllib2
+import urlparse
+
+
+class FileLikeBase:
+ """Base class for implementing file-like objects.
+
+ This class takes a lot of the legwork out of writing file-like objects
+ with a rich interface. It implements the higher-level file-like
+ methods on top of primitive _read() and _write() methods. See their
+ docstrings for precise details on how they should behave.
+ Subclasses then need only implement one or both of these methods for
+ full file-like interface compatability. They may of course override
+ other methods as desired.
+
+ NOTE: this class currently does not support seek() or tell(). It could
+ probably be added if needed, but might be very slow...
+
+ The class is missing the following attributes, which dont really make
+ sense for anything but real files:
+
+ * fileno()
+ * isatty()
+ * truncate()
+ * encoding
+ * mode
+ * name
+ * newlines
+
+ Also unlike standard file objects, all read methods share the same
+ buffer and so can be freely mixed (e.g. read(), readline(), next(), ...)
+
+ """
+
+ def __init__(self,bufsize=100):
+ """FileLikeBase Constructor.
+ The optional argument <bufsize> specifies the number of bytes to
+ read at a time when looking for a newline character. Setting this to
+ a larger number when lines are long should improve efficiency.
+ """
+ # File attributes
+ self.closed = False
+ self.softspace = 0
+ # Our own attributes
+ self._bufsize = bufsize
+ self.__rbuffer = ""
+ self.__wbuffer = ""
+
+ def _check_mode(self,mode):
+ """Check whether the file may be accessed in the given mode.
+ <mode> must be one of "r" or "w", and this function returns False
+ if the file-like object has a <mode> attribute, and it does not
+ permit access in that mode.
+ """
+ if hasattr(self,"mode"):
+ if mode == "r":
+ if "r" not in self.mode:
+ return False
+ if mode == "w":
+ if "w" not in self.mode and "a" not in self.mode:
+ return False
+ return True
+
+ def _assert_mode(self,mode):
+ """Check whether the file may be accessed in the given mode.
+ <mode> must be one of "r" or "w", and this function raises IOError
+ if the file-like object has a <mode> attribute, and it does not
+ permit access in that mode.
+ """
+ if hasattr(self,"mode"):
+ if mode == "r":
+ if "r" not in self.mode:
+ raise IOError("File not opened for reading")
+ if mode == "w":
+ if "w" not in self.mode and "a" not in self.mode:
+ raise IOError("File not opened for writing")
+
+ def seek(self,offset,whence=0):
+ """Provided only raise an IOError - FileLikeBase is not seekable."""
+ raise IOError("Object not seekable")
+
+ def tell(self):
+ """Provided only raise an IOError - FileLikeBase is not seekable."""
+ raise IOError("Object not seekable")
+
+ def flush(self):
+ """Flush internal write buffer, if necessary."""
+ if self.closed:
+ raise IOError("File has been closed")
+ if self._check_mode("w"):
+ if self.__wbuffer != "":
+ leftover = self._write(self.__wbuffer,flushing=True)
+ if leftover is not None and leftover != "":
+ raise IOError("Could not flush write buffer.")
+ self.__wbuffer = ""
+
+ def __del__(self):
+ self.close()
+
+ def close(self):
+ """Flush write buffers and close the file.
+ The file may not be accessed further once it is closed.
+ """
+ if not self.closed:
+ self.flush()
+ self.closed = True
+
+ def next(self):
+ """next() method complying with the iterator protocol.
+ File-like objects are their own iterators, with each call to
+ next() returning subsequent lines from the file.
+ """
+ ln = self.readline()
+ if ln == "":
+ raise StopIteration()
+ return ln
+
+ def __iter__(self):
+ return self
+
+ def read(self,size=-1):
+ """Read at most <size> bytes from the file.
+ Bytes are returned as a string. If <size> is negative, zero or
+ missing, the remainder of the file is read. If EOF is encountered
+ immediately, the empty string is returned.
+ """
+ if self.closed:
+ raise IOError("File has been closed")
+ self._assert_mode("r")
+ # Should the entire file be read?
+ if size <= 0:
+ data = [self.__rbuffer]
+ self.__rbuffer = ""
+ newData = self._read()
+ while newData is not None:
+ data.append(newData)
+ newData = self._read()
+ output = "".join(data)
+ # Want to return a specific amount of data
+ else:
+ newData = self.__rbuffer
+ data = [newData]
+ sizeSoFar = len(newData)
+ while sizeSoFar < size:
+ newData = self._read(size-sizeSoFar)
+ if newData is None:
+ break
+ data.append(newData)
+ sizeSoFar += len(newData)
+ data = "".join(data)
+ if sizeSoFar > size:
+ # read too many bytes, store in the buffer
+ self.__rbuffer = data[size:]
+ data = data[:size]
+ else:
+ self.__rbuffer = ""
+ output = data
+ return output
+
+ def readline(self,size=-1):
+ """Read a line from the file, or a most <size> bytes."""
+ bits = []
+ indx = -1
+ sizeSoFar = 0
+ while indx == -1:
+ nextBit = self.read(self._bufsize)
+ bits.append(nextBit)
+ sizeSoFar += len(nextBit)
+ if nextBit == "":
+ break
+ if size > 0 and sizeSoFar >= size:
+ break
+ indx = nextBit.find("\n")
+ # If not found, return whole string up to <size> length
+ # Any leftovers are pushed onto front of buffer
+ if indx == -1:
+ data = "".join(bits)
+ if size > 0 and sizeSoFar > size:
+ extra = data[size:]
+ data = data[:size]
+ self.__rbuffer = extra + self.__rbuffer
+ return data
+ # If found, push leftovers onto front of buffer
+ # Add one to preserve the newline in the return value
+ indx += 1
+ extra = bits[-1][indx:]
+ bits[-1] = bits[-1][:indx]
+ self.__rbuffer = extra + self.__rbuffer
+ return "".join(bits)
+
+ def readlines(self,sizehint=-1):
+ """Return a list of all lines in the file."""
+ return [ln for ln in self]
+
+ def xreadlines(self):
+ """Iterator over lines in the file - equivalent to iter(self)."""
+ return iter(self)
+
+ def write(self,string):
+ """Write the given string to the file."""
+ if self.closed:
+ raise IOError("File has been closed")
+ self._assert_mode("w")
+ if self.__wbuffer != "":
+ string = self.__wbuffer + string
+ leftover = self._write(string)
+ if leftover is None:
+ self.__wbuffer = ""
+ else:
+ self.__wbuffer = leftover
+
+ def writelines(self,seq):
+ """Write a sequence of lines to the file."""
+ for ln in seq:
+ self.write(ln)
+
+ def _read(self,sizehint=-1):
+ """Read approximately <sizehint> bytes from the file-like object.
+
+ This method is to be implemented by subclasses that wish to be
+ readable. It should read approximately <sizehint> bytes from the
+ file and return them as a string. If <sizehint> is missing or
+ less than or equal to zero, try to read all the remaining contents.
+
+ The method need not guarantee any particular number of bytes -
+ it may return more bytes than requested, or fewer. If needed, the
+ size hint may be completely ignored. It may even return an empty
+ string if no data is yet available.
+
+ Because of this, the method must return None to signify that EOF
+ has been reached. The higher-level methods will never indicate EOF
+ until None has been read from _read(). Once EOF is reached, it
+ should be safe to call _read() again, immediately returning None.
+
+ TODO: should we guarantee that EOF will only be reached once, and
+ cache this result at a higher level?
+ """
+ raise IOError("Object not readable")
+
+ def _write(self,string,flushing=False):
+ """Write the given string to the file-like object.
+
+ This method must be implemented by subclasses wishing to be writable.
+ It must attempt to write as much of the given data as possible to the
+ file, but need not guarantee that it is all written. It may return
+ None to indicate that all data was written, or return as a string any
+ data that could not be written.
+
+ If the keyword argument <flushing> is true, it indicates that the
+ internal write buffers are being flushed, and *all* the given data
+ is expected to be written to the file. This typically indicates
+ that no more data will be forthcoming (e.g. the file is being closed).
+ If remaining data is returned when <flushing> is true, an IOError
+ will be raised to the calling code.
+ """
+ raise IOError("Object not writable")
+
+
+class Opener:
+ """Class allowing clever opening of files.
+
+ Instances of this class are callable using inst(filename,mode),
+ and are intended as a 'smart' replacement for the standard file
+ constructor and open command. Given a filename and a mode, it returns
+ a file-like object representing that file, according to rules such
+ as:
+
+ * URLs are opened using urllib2
+ * files with names ending in ".gz" are gunzipped on the fly
+ * etc...
+
+ The precise rules that are implemented are determined by two lists
+ of functions - openers and decoders. First, each successive opener
+ function is called with the filename and mode until one returns non-None.
+ The functions must attempt to open the given filename and return it as
+ a filelike object.
+
+ Once the file has been opened, it is passed to each successive decoder
+ function. These should return non-None if they perform some decoding
+ step on the file. In this case, they must wrap and return the file-like
+ object, modifying its name if appropriate.
+ """
+
+ def __init__(self,openers=(),decoders=()):
+ self.openers = [o for o in openers]
+ self.decoders = [d for d in decoders]
+
+ def __call__(self,filename,mode="r"):
+ # Validate the mode string
+ for c in mode:
+ if c not in ("r","w","a"):
+ raise ValueError("Unexpected mode character: '%s'" % (c,))
+ # Open the file
+ for o in self.openers:
+ try:
+ f = o(filename,mode)
+ except IOError:
+ f = None
+ if f is not None:
+ break
+ else:
+ raise IOError("Could not open file %s in mode '%s'" \
+ %(filename,mode))
+ # Decode the file as many times as required
+ goAgain = True
+ while goAgain:
+ for d in self.decoders:
+ res = d(f)
+ if res is not None:
+ f = res
+ break
+ else:
+ goAgain = False
+ # Return the final file object
+ return f
+
+## Create default Opener that uses urllib2.urlopen() and file() as openers
+def _urllib_opener(filename,mode):
+ if mode != "r":
+ return None
+ comps = urlparse.urlparse(filename)
+ # ensure it's a URL
+ if comps[0] == "":
+ return None
+ f = urllib2.urlopen(filename)
+ f.name = f.geturl()
+ f.mode = mode
+ return f
+def _file_opener(filename,mode):
+ # Dont open URLS as local files
+ comps = urlparse.urlparse(filename)
+ if comps[0] != "":
+ return None
+ return file(filename,mode)
+
+open = Opener(openers=(_urllib_opener,_file_opener))
+
+
+
+def is_filelike(obj,mode="rw"):
+ """Test whether an object implements the file-like interface.
+
+ <obj> must be the object to be tested, and <mode> a file access
+ mode such as "r", "w" or "rw". This function returns True if
+ the given object implements the full reading/writing interface
+ as required by the given mode, and False otherwise.
+
+ If <mode> is not specified, it deaults to "rw" - that is,
+ checking that the full file interface is supported.
+
+ This method is not intended for checking basic functionality such as
+ existance of read(), but for ensuring the richer interface is
+ available. If only read() or write() is needed, it's probably
+ simpler to (a) catch the AttributeError, or (b) use to_filelike(obj)
+ to ensure a suitable object.
+ """
+ # Check reading interface
+ if "r" in mode:
+ # Special-case for FileLikeBase subclasses
+ if isinstance(obj,FileLikeBase):
+ if not hasattr(obj,"_read"):
+ return False
+ if obj._read.im_class is FileLikeBase:
+ return False
+ else:
+ attrs = ("read","readline","readlines","__iter__",)
+ for a in attrs:
+ if not hasattr(obj,a):
+ return False
+ # Check writing interface
+ if "w" in mode or "a" in mode:
+ # Special-case for FileLikeBase subclasses
+ if isinstance(obj,FileLikeBase):
+ if not hasattr(obj,"_write"):
+ return False
+ if obj._write.im_class is FileLikeBase:
+ return False
+ else:
+ attrs = ("write","writelines","close")
+ for a in attrs:
+ if not hasattr(obj,a):
+ return False
+ return True
+
+
+# Included here to avoid circular includes
+import filelike.wrappers
+
+def to_filelike(obj,mode="rw"):
+ """Convert <obj> to a file-like object if possible.
+
+ This method takes an arbitrary object <obj>, and attempts to
+ wrap it in a file-like interface. This will results in the
+ object itself if it is already file-like, or some sort of
+ wrapper class otherwise.
+
+ <mode>, if provided, should specify how the results object
+ will be accessed - "r" for read, "w" for write, or "rw" for
+ both.
+
+ If the object cannot be converted, ValueError is raised.
+ """
+ # File-like objects are sutiable on their own
+ if is_filelike(obj,mode):
+ return obj
+ # Strings can be wrapped using StringIO
+ if isinstance(obj,basestring):
+ return StringIO.StringIO(obj)
+ # Anything with read() and/or write() can be trivially wrapped
+ hasRead = hasattr(obj,"read")
+ hasWrite = hasattr(obj,"write")
+ if "r" in mode:
+ if "w" in mode or "a" in mode:
+ if hasRead and hasWrite:
+ return filelike.wrappers.FileWrapper(obj)
+ else:
+ if hasRead:
+ return filelike.wrappers.FileWrapper(obj)
+ if "w" in mode or "a" in mode:
+ if hasWrite:
+ return filelike.wrappers.FileWrapper(obj)
+ # TODO: lots more could be done here...
+ raise ValueError("Could not make object file-like: %s", (obj,))
+
+
+## TODO: unittests for is_filelike and to_filelike
+
+
+def testsuite():
+ suite = unittest.TestSuite()
+ from filelike import wrappers
+ suite.addTest(wrappers.testsuite())
+ from filelike import pipeline
+ suite.addTest(pipeline.testsuite())
+ return suite
+
+
+# Run regression tests when called from comand-line
+if __name__ == "__main__":
+ unittest.TextTestRunner().run(testsuite())
+
266 filelike/pipeline.py
@@ -0,0 +1,266 @@
+"""
+
+ filelike.pipeline: modify file-like objects using unix pipeline style
+
+This module utilises python's operator overloading magic to allow file-like
+wrappers such as those found in filelike.wrappers to be composed using a
+unix pipeline style.
+
+Ideas based on the following ASPN Cookbook Recipie:
+
+ http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/276960
+
+The base class PipelineEntry implements the operator magic, and a mirror
+class is provided for each wrapper in filelike.wrappers. To allow additional
+wrappers to be used, use pipeline() on the class:
+
+ class MyNewWrapper(FileWrapper):
+ ...
+
+ MyNewWrapper = pipeline(MyNewWrapper)
+
+
+As an example, here's how to print the first 20 lines of an encrypted file:
+
+ for ln in file("enc_file.bin","r") > DecryptFile(key) | Head(lines=20)
+ print ln
+
+Some folks would say this aids readability when using long combinations of
+wrappers. A lot would probably all it a horrible abuse of operator semantics.
+Mostly I consider it a fun hack.
+
+The following pipline operators are supported:
+
+ > Read or write from a wrapper into a file-like object
+ >> Write from a wrapper into a file-like object in append mode
+ | Read/write from one wrapper into another
+
+Because of the way python's operator lookup works, > is used for both read
+and write. At the beginning of a pipeline, it indicates that data is to
+be read from the file. At the end, it indicates data should be written
+to the file.
+
+TODO: more examples here
+
+"""
+
+import filelike
+
+import os
+import unittest
+import StringIO
+
+class PipelineEntry:
+ """Class implementing a step in a file-like pipeline.
+
+ Objects of this class may form a stage in a file-like pipeline. Typically
+ this will be either the first entry in the pipeline, or an entry following
+ a readable file-like object.
+
+ Each instance of this class must implement the method _create(fileobj),
+ which creates and returns an appropriate wrapper around the given
+ file-like object.
+ """
+
+ def __init__(self,cls,*args,**kwds):
+ """PipelineEntry constructor.
+ <cls> is the class of the file-like wrapper to create. Additional
+ args may be specified and will be passed in after the requisite
+ <fileobj> first argument in the class's constructor.
+ """
+ self._cls = cls
+ self._args = args
+ self._kwds = kwds
+
+ def _create(self,fileobj,mode=None):
+ """Create instance of the FileWrapper over given file object."""
+ if mode is not None and not self._kwds.has_key("mode"):
+ kwds = self._kwds.copy()
+ kwds["mode"] = mode
+ else:
+ kwds = self._kwds
+ return self._cls(fileobj,*self._args,**kwds)
+
+ def __lt__(self,obj):
+ """Implement read-from-file pipeline stage.
+
+ <obj> must not be a PipelineEntry, and must be coercable
+ to a file-like object using filelike.to_filelike() with
+ mode "r".
+
+ A new file-like object will be returned that reads from the
+ opened file-like object.
+ """
+ if isinstance(obj,PipelineEntry):
+ raise ValueError("Cannot read from existing pipeline entry.")
+ obj = filelike.to_filelike(obj,"r")
+ return self._create(obj,"r")
+
+ def __gt__(self,obj):
+ """Implement write-to-file pipeline stage.
+
+ <obj> must not be a PipelineEntry, and must be coercable
+ to a file-like object using filelike.to_filelike() with
+ mode "w".
+
+ A new file-like wrapper will be returned that writes to
+ the given object.
+ """
+ if isinstance(obj,PipelineEntry):
+ raise ValueError("Cannot write to existing pipeline entry.")
+ obj = filelike.to_filelike(obj,"w")
+ return self._create(obj,"w")
+
+ def __rshift__(self,obj):
+ """Implement append-to-file pipeline stage.
+
+ This behaves as __gt__, but opens the file in append mode.
+ """
+ if isinstance(obj,PipelineEntry):
+ raise ValueError("Cannot write to existing pipeline entry.")
+ obj = filelike.to_filelike(obj,"a")
+ return self._create(obj,"a")
+
+ def __or__(self,obj):
+ """Implement left-hand pipe segment in pipeling stage.
+
+ <obj> should be the next pipeline stage. This starts a
+ PipelineStack.
+ """
+ return PipelineStack(self,obj)
+
+class PipelineStack:
+ """Class collecting pipeline entries to be read/written to.
+
+ This class collects a stack of pipeline entries. These will
+ be converted to a filelike object in the appropriate order
+ when the write/read-to-file pipeline stage is encountered.
+ """
+
+ def __init__(self,first,second):
+ """PipelineStack constructor.
+ <first> and <second> must be the initial two stages in the
+ pipeline.
+ """
+ self._stages = [second,first]
+
+ def __or__(self,obj):
+ """Implement left-hand pipe segment in pipeling stage.
+
+ <obj> should be the next pipeline stage, which is added to the stack.
+ """
+ self._stages.append(obj)
+ return self
+
+ def __gt__(self,obj):
+ """Implement write-to-file pipeline stage.
+
+ <obj> must not be a PipelineEntry, and must be coercable
+ to a file-like object using filelike.to_filelike() with
+ mode "w".
+
+ A new file-like wrapper will be returned that writes to
+ the given object.
+ """
+ if isinstance(obj,PipelineEntry):
+ raise ValueError("Cannot write to existing pipeline entry.")
+ obj = filelike.to_filelike(obj,"w")
+ while len(self._stages) > 0:
+ next = self._stages.pop(0)
+ obj = next._create(obj,"w")
+ return obj
+
+ def __lt__(self,obj):
+ """Implement read-from-file pipeline stage.
+
+ <obj> must not be a PipelineEntry, and must be coercable
+ to a file-like object using filelike.to_filelike() with
+ mode "w".
+
+ A new file-like wrapper will be returned that writes to
+ the given object.
+ """
+ if isinstance(obj,PipelineEntry):
+ raise ValueError("Cannot read from existing pipeline entry.")
+ obj = filelike.to_filelike(obj,"r")
+ while len(self._stages) > 0:
+ next = self._stages.pop()
+ obj = next._create(obj,"r")
+ return obj
+
+ def __rshift__(self,obj):
+ """Implement append-to-file pipeline stage.
+
+ This behaves as __gt__, but opens the file in append mode.
+ """
+ if isinstance(obj,PipelineEntry):
+ raise ValueError("Cannot write to existing pipeline entry.")
+ obj = filelike.to_filelike(obj,"a")
+ while len(self._stages) > 0:
+ next = self._stages.pop(0)
+ obj = next._create(obj,"a")
+ return obj
+
+
+class Test_Pipeline(unittest.TestCase):
+ """Testcases for the construction of pipelines."""
+
+ def setUp(self):
+ from Crypto.Cipher import DES
+ # Example inspired by the PyCrypto manual
+ self.cipher = DES.new('abcdefgh',DES.MODE_ECB)
+ self.plaintextin = "Guido van Rossum is a space alien."
+ self.plaintextout = "Guido van Rossum is a space alien." + "\0"*6
+ self.ciphertext = "\x11,\xe3Nq\x8cDY\xdfT\xe2pA\xfa\xad\xc9s\x88\xf3,\xc0j\xd8\xa8\xca\xe7\xe2I\xd15w\x1d\xfe\x92\xd7\xca\xc9\xb5r\xec"
+ self.plainfile = StringIO.StringIO(self.plaintextin)
+ self.cryptfile = StringIO.StringIO(self.ciphertext)
+ self.outfile = StringIO.StringIO()
+
+ def tearDown(self):
+ pass
+
+ def test_ReaderLine(self):
+ """Test a simple reading pipeline."""
+ pf = self.ciphertext > DecryptFile(self.cipher) | Head(bytes=10)
+ txt = pf.read()
+ self.assertEquals(txt,self.plaintextout[:10])
+
+ def test_WriterLine(self):
+ """Test a simple writer pipeline."""
+ pf = DecryptFile(self.cipher) | Head(bytes=15) | FixedBlockSizeFile(10) > self.outfile
+ pf.write(self.plaintextin)
+ pf.flush()
+ txt = self.outfile.getvalue()
+ self.assertEquals(txt,self.ciphertext[:15])
+
+
+def pipeline(cls):
+ """Create a PipelineEntry factory function using given class."""
+ def create_entry(*args,**kwds):
+ return PipelineEntry(cls,*args,**kwds)
+ return create_entry
+
+## Create a PipelineEntry factory for each wrapper
+## defined in filelike.wrappers
+from filelike import wrappers
+for nm in dir(wrappers):
+ cls = getattr(wrappers,nm)
+ try:
+ if issubclass(cls,wrappers.FileWrapper):
+ if cls is not wrappers.FileWrapper:
+ globals()[nm] = pipeline(cls)
+ except TypeError:
+ pass
+
+
+
+def testsuite():
+ suite = unittest.TestSuite()
+ suite.addTest(unittest.makeSuite(Test_Pipeline))
+ return suite
+
+
+# Run regression tests when called from comand-line
+if __name__ == "__main__":
+ UnitTest.TextTestRunner().run(testsuite())
+
998 filelike/wrappers.py
@@ -0,0 +1,998 @@
+# filelike.py
+#
+# Copyright (C) 2006, Ryan Kelly
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License, or (at your option) any later version.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the
+# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+# Boston, MA 02111-1307, USA.
+#
+"""
+
+ filelike.wrappers: wrapper classes modifying file-like objects
+
+
+This module builds on the basic functionality of the filelike module to
+provide a collection of useful classes. These include:
+
+ * TransFile: pass file contents through an arbitrary translation
+ function (e.g. compression, encryption, ...)
+
+ * FixedBlockSizeFile: ensure all read/write requests are aligned with
+ a given blocksize
+
+ * DecryptFile: on-the-fly reading and writing to an encrypted file
+ (using PEP272 cipher API)
+
+ * BZ2File: on-the-fly decompression of bzip'd files
+ (like the standard library's bz2 module, but accepts
+ any file-like object)
+
+As an example of the type of thing this module is designed to achieve, here's
+an example of using the DecryptFile class to transparently access an encrypted
+file:
+
+ # Create the decryption key
+ from Crypto.Cipher import DES
+ cipher = DES.new('abcdefgh',DES.MODE_ECB)
+ # Open the encrypted file
+ f = DecryptFile(file("some_encrypted_file.bin","r"),cipher)
+
+The object in <f> now behaves as a file-like object, transparently decrypting
+the file on-the-fly as it is read.
+
+"""
+
+import filelike
+from filelike import FileLikeBase
+
+import os
+import unittest
+import StringIO
+
+
+
+class FileWrapper(FileLikeBase):
+ """Base class for objects that wrap a file-like object.
+
+ This class provides basic functionality for implementing file-like
+ objects that wrap another file-like object to alter its functionality
+ in some way. It takes care of house-keeping duties such as flushing
+ and closing the wrapped file.
+
+ Access to the wrapped file is given by the private member _fileobj.
+ By convention, the subclass's constructor should accept this as its
+ first argument and pass it to its superclass's constructor in the
+ same position.
+
+ This class provides a basic implementation of _read() and _write()
+ which just calls read() and write() on the wrapped object. Many
+ subclasses will probably want to override these.
+ """
+
+ def __init__(self,fileobj,mode=None):
+ """FileWrapper constructor.
+
+ <fileobj> must be a file-like object, which is to be wrapped
+ in another file-like object to provide additional functionality.
+
+ If given, <mode> must be the access mode string for with which
+ the wrapped file is to be accessed. If not given or None, it
+ is looked up on the wrapped file if possible. Otherwise, it
+ is not set on the object.
+ """
+ FileLikeBase.__init__(self)
+ self._fileobj = fileobj
+ if mode is None:
+ if hasattr(fileobj,"mode"):
+ self.mode = fileobj.mode
+ else:
+ self.mode = mode
+ # Copy useful attributes of the fileobj
+ if hasattr(fileobj,"name"):
+ self.name = fileobj.name
+
+ def close(self):
+ """Close the object for reading/writing."""
+ FileLikeBase.close(self)
+ if hasattr(self._fileobj,"close"):
+ self._fileobj.close()
+
+ def flush(self):
+ """Flush the write buffers of the file."""
+ FileLikeBase.flush(self)
+ if hasattr(self._fileobj,"flush"):
+ self._fileobj.flush()
+
+ def _read(self,sizehint=-1):
+ data = self._fileobj.read(sizehint)
+ if data == "":
+ return None
+ return data
+
+ def _write(self,string):
+ return self._fileobj.write(string)
+
+
+class TransFile(FileWrapper):
+ """Class implementing some translation on a file's contents.
+
+ This class wraps a file-like object in another file-like object,
+ applying a given function to translate the file's contents as it is
+ read or written. It could be used, for example, to read from a
+ gzipped source file or to encrypt a file as it's being written.
+
+ The translating function must accept a string as its only argument,
+ and return a transformed string representing the updated file contents.
+ No guarantees are made about the amount of data fed into the function
+ at a time (although another wrapper like FixedBlockSizeFile could be
+ used to do so.) If the transform needs to be flushed when reading/writing
+ is finished, it should provide a flush() method that returns either None,
+ or any data remaining to be read/written.
+
+ The default use case assumes either reading+writing with a stateless
+ translation function, or exclusive reading or writing. So, a single
+ function is used for translation on both reads and writes. Seperate
+ reading and writing translation functions may be provided using keyword
+ arguments <rfunc> and <wfunc> to the constructor.
+ """
+
+ def __init__(self,fileobj,func=None,mode=None,rfunc=None,wfunc=None):
+ """TransFile constructor.
+ <fileobj> must be the file-like object whose contents are to be
+ transformed, and <func> the callable that will transform the
+ contents. <mode> should be one of "r" or "w" to indicate whether
+ reading or writing is desired. If omitted it is determined from
+ <fileobj> where possible, otherwise it defaults to "r".
+
+ If seperate reading/writing translations are required, the
+ keyword arguments <rfunc> and <wfunc> can be used in place of
+ <func>
+ """
+ FileWrapper.__init__(self,fileobj,mode)
+ self._finished = False
+ if func is not None:
+ if rfunc is not None:
+ raise ValueError("Cannot specify both <func> and <rfunc>")
+ if wfunc is not None:
+ raise ValueError("Cannot specify both <func> and <wfunc>")
+ self._rfunc = func
+ self._wfunc = func
+ else:
+ if "r" in self.mode and rfunc is None:
+ raise ValueError("Must provide <rfunc> for readable files")
+ if "w" in self.mode or "a" in self.mode:
+ if wfunc is None:
+ raise ValueError("Must provide <wfunc> for writable files")
+ self._rfunc = rfunc
+ self._wfunc = wfunc
+
+
+ def _flush_rfunc(self):
+ """Call flush on the reading translation function, if necessary."""
+ if hasattr(self._rfunc,"flush"):
+ return self._rfunc.flush()
+ return None
+
+ def _flush_wfunc(self):
+ """Call flush on the writing translation function, if necessary."""
+ if hasattr(self._wfunc,"flush"):
+ return self._wfunc.flush()
+ return
+
+ def _read(self,sizehint=-1):
+ """Read approximately <sizehint> bytes from the file."""
+ if self._finished:
+ return None
+ data = self._fileobj.read(sizehint)
+ if data != "":
+ data = self._rfunc(data)
+ if sizehint <= 0 or len(data) < sizehint:
+ self._finished = True
+ # Flush func if necessary
+ data2 = self._flush_rfunc()
+ if data2 is None:
+ if data == "":
+ return None
+ return data
+ return data + data2
+ return data
+
+ def _write(self,data):
+ """Write the given data to the file."""
+ nData = self._wfunc(data)
+ self._fileobj.write(nData)
+
+ def flush(self):
+ # Flush func if necessary, when writing
+ data = self._flush_wfunc()
+ if data is not None:
+ self._fileobj.write(data)
+ FileWrapper.flush(self)
+
+
+class Test_TransFile(unittest.TestCase):
+ """Testcases for the TransFile class."""
+
+ def setUp(self):
+ import StringIO
+ self.testlines = ["this is a simple test\n"," file with a\n"," few lines."]
+ self.testfileR = StringIO.StringIO("".join(self.testlines))
+ self.testfileW = StringIO.StringIO()
+ def noop(string):
+ return string
+ self.f_noop = noop
+
+ def tearDown(self):
+ del self.testfileR
+ del self.testfileW
+
+ def test_read(self):
+ """Test reading the entire file"""
+ tf = TransFile(self.testfileR,self.f_noop,"r")
+ self.assert_(tf.read() == "".join(self.testlines))
+
+ def test_readbytes(self):
+ """Test reading a specific number of bytes"""
+ tf = TransFile(self.testfileR,self.f_noop,"r")
+ self.assert_(tf.read(10) == "".join(self.testlines)[:10])
+
+ def test_readlines(self):
+ """Test reading lines one at a time."""
+ tf = TransFile(self.testfileR,self.f_noop,"r")
+ self.assert_(tf.readlines() == self.testlines)
+
+ def test_write(self):
+ """Test basic behavior of writing to a file."""
+ tf = TransFile(self.testfileW,self.f_noop,"w")
+ tf.write("".join(self.testlines))
+ self.assert_(self.testfileW.getvalue() == "".join(self.testlines))
+
+ def test_writelines(self):
+ """Test writing several lines with writelines()."""
+ tf = TransFile(self.testfileW,self.f_noop,"w")
+ tf.writelines(self.testlines)
+ self.assert_(self.testfileW.getvalue() == "".join(self.testlines))
+
+
+class FixedBlockSizeFile(FileWrapper):
+ """Class reading/writing to files at a fixed block size.
+
+ This file wrapper can be used to read or write to a file-like
+ object at a specific block size. All reads request strings
+ whose length is a multiple of the block size, and all writes
+ pass on strings of a similar nature. This could be useful, for
+ example, to write data to a cipher function without manually
+ chunking text to match the cipher's block size.
+
+ If the total data written to the file when it is flushed or closed
+ is not a multiple of the blocksize, it will be padded to the
+ appropriate size with null bytes.
+ """
+
+ def __init__(self,fileobj,blocksize,mode=None):
+ FileWrapper.__init__(self,fileobj,mode)
+ self._blocksize = blocksize
+
+ def _round_up(self,num):
+ """Round <num> up to a multiple of the block size."""
+ return ((num/self._blocksize)+1) * self._blocksize
+
+ def _round_down(self,num):
+ """Round <num> down to a multiple of the block size."""
+ return (num/self._blocksize) * self._blocksize
+
+ def _pad_to_size(self,data):
+ """Add padding data to make it an appropriate size."""
+ size = self._round_up(len(data))
+ if len(data) < size:
+ data = data + ("\0"*(size-len(data)))
+ return data
+
+ def _read(self,sizehint=-1):
+ """Read approximately <sizehint> bytes from the file."""
+ if sizehint <= 0:
+ sizehint = self._bufsize
+ size = self._round_up(sizehint)
+ data = self._fileobj.read(size)
+ if data == "":
+ return None
+ return data
+
+ def _write(self,data,flushing=False):
+ """Write the given string to the file."""
+ # Pad the data if the buffers are being flushed
+ if flushing:
+ data = self._pad_to_size(data)
+ size = len(data)
+ else:
+ size = self._round_down(len(data))
+ self._fileobj.write(data[:size])
+ return data[size:]
+
+
+
+class Test_FixedBlockSizeFile(unittest.TestCase):
+ """Testcases for the FixedBlockSize class."""
+
+ def setUp(self):
+ import StringIO
+ class BSFile:
+ def __init__(s,bs):
+ s.bs = bs
+ def read(s,size=-1):
+ self.assert_(size > 0)
+ self.assert_(size%s.bs == 0)
+ return "X"*size
+ def write(s,data):
+ self.assert_(len(data)%s.bs == 0)
+ self.BSFile = BSFile
+
+ def tearDown(self):
+ del self.BSFile
+
+ def test_readbytes(self):
+ """Test reading different numbers of bytes"""
+ bsf = FixedBlockSizeFile(self.BSFile(8),8)
+ self.assert_(len(bsf.read(5)) == 5)
+ self.assert_(len(bsf.read(8)) == 8)
+ self.assert_(len(bsf.read(76)) == 76)
+ bsf = FixedBlockSizeFile(self.BSFile(5),5)
+ self.assert_(len(bsf.read(5)) == 5)
+ self.assert_(len(bsf.read(8)) == 8)
+ self.assert_(len(bsf.read(76)) == 76)
+
+ def test_write(self):
+ """Test writing different numbers of bytes"""
+ bsf = FixedBlockSizeFile(self.BSFile(8),8)
+ bsf.write("this is some text, it is")
+ bsf.write("shrt")
+ bsf.flush()
+ bsf.write("longer text, with some\n newlines in it\n yessir.")
+ bsf.close()
+
+
+class PaddedToBlockSizeFile(FileWrapper):
+ """Class padding files to a fixed block size.
+
+ This file wrapper can be used to pad a file to a specific block size.
+ If the total data written to the file when it is flushed or closed
+ is not a multiple of the blocksize, it will be padded to the
+ appropriate size by writing the following data:
+
+ * Two null bytes
+ * "PaddedToBlockSizeFile"
+ * Enough null bytes to fit the block size
+
+ This data is removed from the end of the file if it is encoutered
+ upon reading.
+
+ No guarantee is made that reads or writes are requsted at the
+ blocksize - use FixedBlockSizeFile to achieve this.
+ """
+
+ _padstr = "\0\0PaddedToBlockSizeFile"
+
+ def __init__(self,fileobj,blocksize,mode=None):
+ FileWrapper.__init__(self,fileobj,mode)
+ self._blocksize = blocksize
+ self._maxpadlen = len(self._padstr) + blocksize-1
+ self._padwritten = False
+
+ def _round_up(self,num):
+ """Round <num> up to a multiple of the block size."""
+ nm = ((num/self._blocksize)+1) * self._blocksize
+ if nm == num + self._blocksize:
+ return num
+ return nm
+
+ def _round_down(self,num):
+ """Round <num> down to a multiple of the block size."""
+ return (num/self._blocksize) * self._blocksize
+
+ def _pad_to_size(self,data):
+ """Pad data to make it an appropriate size."""
+ data = data + self._padstr
+ size = self._round_up(len(data))
+ if len(data) < size:
+ data = data + ("\0"*(size-len(data)))
+ return data
+
+ def _read(self,sizehint=-1):
+ """Read approximately <sizehint> bytes from the file."""
+ data = self._fileobj.read(sizehint)
+ # If we might be near the end, read far enough ahead to see
+ while "\0" in data[-1*self._maxpadlen:]:
+ newData = self._fileobj.read(self._maxpadlen)
+ data = data + newData
+ idx = data.rfind(self._padstr)
+ if idx != -1:
+ data = data[:idx]
+ break
+ if newData == "":
+ break
+ if data == "":
+ return None
+ return data
+
+ def _write(self,data,flushing=False):
+ """Write the given string to the file."""
+ # Writing at the block size means we dont have to count bytes written
+ # Pad the data if the buffers are being flushed
+ if flushing:
+ if self._padwritten:
+ size = 0
+ data = ""
+ else:
+ data = self._pad_to_size(data)
+ size = len(data)
+ self._padwritten = True
+ else:
+ size = self._round_down(len(data))
+ self._fileobj.write(data[:size])
+ return data[size:]
+
+ def flush(self):
+ FileWrapper.flush(self)
+ if not self._padwritten:
+ self._write("",flushing=True)
+
+
+class Test_PaddedToBlockSizeFile(unittest.TestCase):
+ """Testcases for the PaddedToBlockSizeFile class."""
+
+ def setUp(self):
+ import StringIO
+ self.textin = "this is sample text"
+ self.textout5 = "this is sample text\0\0PaddedToBlockSizeFile\0\0\0"
+ self.textout7 = "this is sample text\0\0PaddedToBlockSizeFile"
+ self.outfile = StringIO.StringIO()
+
+ def tearDown(self):
+ del self.outfile
+
+ def test_write5(self):
+ """Test writing at blocksize=5"""
+ bsf = PaddedToBlockSizeFile(self.outfile,5,mode="w")
+ bsf.write(self.textin)
+ bsf.flush()
+ self.assertEquals(self.outfile.getvalue(),self.textout5)
+
+ def test_write7(self):
+ """Test writing at blocksize=7"""
+ bsf = PaddedToBlockSizeFile(self.outfile,7,mode="w")
+ bsf.write(self.textin)
+ bsf.flush()
+ self.assertEquals(self.outfile.getvalue(),self.textout7)
+
+ def test_read5(self):
+ """Test reading at blocksize=5"""
+ inf = StringIO.StringIO(self.textout5)
+ bsf = PaddedToBlockSizeFile(inf,5,mode="r")
+ txt = bsf.read()
+ self.assertEquals(txt,self.textin)
+
+ def test_read7(self):
+ """Test reading at blocksize=7"""
+ inf = StringIO.StringIO(self.textout7)
+ bsf = PaddedToBlockSizeFile(inf,7,mode="r")
+ txt = bsf.read()
+ self.assertEquals(txt,self.textin)
+
+
+class DecryptFile(FileWrapper):
+ """Class for reading and writing to an encrypted file.
+
+ This class accesses an encrypted file using a ciphering object
+ compliant with PEP272: "API for Block Encryption Algorithms".
+ All reads from the file are automatically decrypted, while writes
+ to the file and automatically encrypted. Thus, DecryptFile(fobj)
+ can be seen as the decrypted version of the file-like object fobj.
+
+ Because this class is implemented on top of FixedBlockSizeFile,
+ the plaintext may be padded with null characters to reach a multiple
+ of the block size.
+
+ There is a dual class, EncryptFile, where all reads are encrypted
+ and all writes are decrypted. This would be used, for example, to
+ encrypt the contents of an existing file using a series of read()
+ operations.
+ """
+
+ def __init__(self,fileobj,cipher,mode=None):
+ """DecryptFile Constructor.
+ <fileobj> is the file object with encrypted contents, and <cipher>
+ is the cipher object to be used. Other arguments are passed through
+ to FileWrapper.__init__
+ """
+ self.__cipher = cipher
+ myFileObj = TransFile(fileobj,mode=mode,
+ rfunc=cipher.decrypt,
+ wfunc=cipher.encrypt)
+ myFileObj = FixedBlockSizeFile(myFileObj,cipher.block_size)
+ FileWrapper.__init__(self,myFileObj)
+
+
+class EncryptFile(FileWrapper):
+ """Class for reading and writing to an decrypted file.
+
+ This class accesses a decrypted file using a ciphering object
+ compliant with PEP272: "API for Block Encryption Algorithms".
+ All reads from the file are automatically encrypted, while writes
+ to the file are automatically decrypted. Thus, DecryptFile(fobj)
+ can be seen as the encrypted version of the file-like object fobj.
+
+ Because this class is implemented on top of FixedBlockSizeFile,
+ the plaintext may be padded with null characters to reach a multiple
+ of the block size.
+
+ There is a dual class, DecryptFile, where all reads are decrypted
+ and all writes are encrypted. This would be used, for example, to
+ decrypt the contents of an existing file using a series of read()
+ operations.
+ """
+
+ def __init__(self,fileobj,cipher,mode=None):
+ """EncryptFile Constructor.
+ <fileobj> is the file object with decrypted contents, and <cipher>
+ is the cipher object to be used. Other arguments are passed through
+ to FileWrapper.__init__
+ """
+ self.__cipher = cipher
+ myFileObj = TransFile(fileobj,mode=mode,
+ rfunc=self.__encrypt,
+ wfunc=cipher.decrypt)
+ myFileObj = FixedBlockSizeFile(myFileObj,cipher.block_size)
+ FileWrapper.__init__(self,myFileObj)
+
+ def __encrypt(self,data):
+ """Encrypt the given data.
+ This function pads any data given that is not a multiple of
+ the cipher's blocksize. Such a case would indicate that it
+ is the last data to be read.
+ """
+ if len(data) % self.__cipher.block_size != 0:
+ data = self._fileobj._pad_to_size(data)
+ return self.__cipher.encrypt(data)
+
+
+class Test_CryptFiles(unittest.TestCase):
+ """Testcases for the (En/De)CryptFile classes."""
+
+ def setUp(self):
+ import StringIO
+ from Crypto.Cipher import DES
+ # Example inspired by the PyCrypto manual
+ self.cipher = DES.new('abcdefgh',DES.MODE_ECB)
+ self.plaintextin = "Guido van Rossum is a space alien."
+ self.plaintextout = "Guido van Rossum is a space alien." + "\0"*6
+ self.ciphertext = "\x11,\xe3Nq\x8cDY\xdfT\xe2pA\xfa\xad\xc9s\x88\xf3,\xc0j\xd8\xa8\xca\xe7\xe2I\xd15w\x1d\xfe\x92\xd7\xca\xc9\xb5r\xec"
+ self.plainfile = StringIO.StringIO(self.plaintextin)
+ self.cryptfile = StringIO.StringIO(self.ciphertext)
+ self.outfile = StringIO.StringIO()
+
+ def tearDown(self):
+ pass
+
+ def test_ReadDecrypt(self):
+ """Test reading from an encrypted file."""
+ df = DecryptFile(self.cryptfile,self.cipher,"r")
+ self.assert_(df.read() == self.plaintextout)
+
+ def test_ReadEncrypt(self):
+ """Test reading from a decrypted file."""
+ ef = EncryptFile(self.plainfile,self.cipher,"r")
+ self.assert_(ef.read() == self.ciphertext)
+
+ def test_WriteDecrypt(self):
+ """Test writing to an encrypted file."""
+ df = DecryptFile(self.outfile,self.cipher,"w")
+ df.write(self.plaintextin)
+ df.flush()
+ self.assert_(self.outfile.getvalue() == self.ciphertext)
+
+ def test_WriteEncrypt(self):
+ """Test writing to a decrypted file."""
+ ef = EncryptFile(self.outfile,self.cipher,"w")
+ ef.write(self.ciphertext)
+ self.assert_(self.outfile.getvalue() == self.plaintextout)
+
+
+class Head(FileWrapper):
+ """Wrapper acting like unix "head" command.
+
+ This wrapper limits the amount of data returned from or written to the
+ underlying file based on the number of bytes and/or lines.
+
+ NOTE: no guarantees are made about the amount of data read *from*
+ the underlying file, only about the amount of data returned to
+ the calling function.
+ """
+
+ def __init__(self,fileobj,mode=None,bytes=None,lines=None):
+ """Head wrapper constructor.
+ The arguments <bytes> and <lines> specify the maximum number
+ of bytes and lines to be read or written. Reading/writing
+ will terminate when one of the given values has been exceeded.
+ Any extraneous data is simply discarded.
+ """
+ FileWrapper.__init__(self,fileobj,mode)
+ self._maxBytes = bytes
+ self._maxLines = lines
+ self._bytesR = 0
+ self._linesR = 0
+ self._bytesW = 0
+ self._linesW = 0
+ self._finishedR = False
+ self._finishedW = False
+
+ def _read(self,sizehint=-1):
+ if self._finishedR:
+ return None
+ if sizehint <= 0 or sizehint > self._bufsize:
+ sizehint = self._bufsize
+ data = self._fileobj.read(sizehint)
+ if data == "":
+ self._finishedR = True
+ return data
+ nBytes = len(data)
+ newBytes = self._bytesR + nBytes
+ if self._maxBytes is not None and newBytes >= self._maxBytes:
+ data = data[:self._maxBytes - self._bytesR]
+ self._finishedR = True
+ nLines = data.count("\n")
+ newLines = self._linesR + nLines
+ if self._maxLines is not None and newLines >= self._maxLines:
+ limit = self._maxLines - self._linesR
+ lines = data.split("\n")
+ if len(lines) > limit:
+ data = "\n".join(lines[:limit]) + "\n"
+ else:
+ data = "\n".join(lines[:limit])
+ self._finishedR = True
+ self._bytesR = newBytes
+ self._linesR = newLines
+ return data
+
+ def _write(self,data):
+ if self._finishedW:
+ return None
+ nBytes = len(data)
+ nLines = data.count("\n")
+ newBytes = self._bytesW + nBytes
+ newLines = self._linesW + nLines
+ if self._maxBytes is not None and newBytes >= self._maxBytes:
+ data = data[:self._maxBytes - self._bytesW]
+ self._finishedW = True
+ elif self._maxLines is not None and newLines >= self._maxLines:
+ limit = self._maxLines - self._linesW
+ lines = data.split("\n")
+ if len(lines) > limit:
+ data = "\n".join(lines[:limit]) + "\n"
+ else:
+ data = "\n".join(lines[:limit])
+ self._finishedW = True
+ self._bytesW = newBytes
+ self._linesW = newLines
+ self._fileobj.write(data)
+ return None
+
+
+
+class Test_Head(unittest.TestCase):
+ """Testcases for the Head wrapper class."""
+
+ def setUp(self):
+ from Crypto.Cipher import DES
+ # Example inspired by the PyCrypto manual
+ self.intext = "Guido van Rossum\n is a space\n alien."
+ self.infile = StringIO.StringIO(self.intext)
+ self.outfile = StringIO.StringIO()
+
+ def tearDown(self):
+ pass
+
+ def test_ReadHeadBytes(self):
+ """Test reading bytes from head of a file."""
+ hf = Head(self.infile,"r",bytes=10)
+ txt = hf.read()
+ self.assertEquals(len(txt),10)
+ self.assertEquals(txt,self.intext[:10])
+
+ def test_ReadHeadLongBytes(self):
+ """Test reading entirety of head of file."""
+ hf = Head(self.infile,"r",bytes=1000)
+ txt = hf.read()
+ self.assertEquals(txt,self.intext)
+
+ def test_ReadHeadLines(self):
+ """Test reading lines from head of file."""
+ hf = Head(self.infile,"r",lines=2)
+ txt = hf.read()
+ self.assertEquals(txt.count("\n"),2)
+ self.assertEquals(txt,"\n".join(self.intext.split("\n")[:2])+"\n")
+
+ def test_ReadHeadLinesExact(self):
+ """Test reading exact number of lines from head of file."""
+ hf = Head(self.infile,"r",lines=3)
+ txt = hf.read()
+ self.assertEquals(txt.count("\n"),2)
+ self.assertEquals(txt,self.intext)
+
+ def test_ReadHeadLongLines(self):
+ """Test reading all lines from head of file."""
+ hf = Head(self.infile,"r",lines=200)
+ txt = hf.read()
+ self.assertEquals(txt,self.intext)
+
+ def test_ReadBytesOverLines(self):
+ """Test reading limited by bytes, not lines"""
+ hf = Head(self.infile,"r",bytes=5,lines=2)
+ txt = hf.read()
+ self.assertEquals(len(txt),5)
+ self.assertEquals(txt,self.intext[:5])
+
+ def test_ReadLinesOverBytes(self):
+ """Test reading limited by lines, not bytes"""
+ hf = Head(self.infile,"r",bytes=500,lines=1)
+ txt = hf.read()
+ self.assertEquals(txt.count("\n"),1)
+ self.assertEquals(txt,self.intext.split("\n")[0]+"\n")
+
+ def test_WriteHeadBytes(self):
+ """Test writing bytes to head of a file."""
+ hf = Head(self.outfile,"w",bytes=10)
+ hf.write(self.intext)
+ self.assertEquals(len(self.outfile.getvalue()),10)
+ self.assertEquals(self.outfile.getvalue(),self.intext[:10])
+
+ def test_WriteHeadLongBytes(self):
+ """Test writing entirety of head of file."""
+ hf = Head(self.outfile,"w",bytes=1000)
+ hf.write(self.intext)
+ self.assertEquals(self.outfile.getvalue(),self.intext)
+
+ def test_WriteHeadLines(self):
+ """Test writing lines to head of file."""
+ hf = Head(self.outfile,"w",lines=2)
+ hf.write(self.intext)
+ self.assertEquals(self.outfile.getvalue().count("\n"),2)
+ self.assertEquals(self.outfile.getvalue(),"\n".join(self.intext.split("\n")[:2])+"\n")
+
+ def test_WriteHeadLongLines(self):
+ """Test writing all lines to head of file."""
+ hf = Head(self.outfile,"w",lines=200)
+ hf.write(self.intext)
+ self.assertEquals(self.outfile.getvalue(),self.intext)
+
+ def test_WriteBytesOverLines(self):
+ """Test writing limited by bytes, not lines"""
+ hf = Head(self.outfile,"w",bytes=5,lines=2)
+ hf.write(self.intext)
+ txt = self.outfile.getvalue()
+ self.assertEquals(len(txt),5)
+ self.assertEquals(txt,self.intext[:5])
+
+ def test_writeLinesOverBytes(self):
+ """Test writing limited by lines, not bytes"""
+ hf = Head(self.outfile,"w",bytes=500,lines=1)
+ hf.write(self.intext)
+ txt = self.outfile.getvalue()
+ self.assertEquals(txt.count("\n"),1)
+ self.assertEquals(txt,self.intext.split("\n")[0]+"\n")
+
+
+class Cat(FileWrapper):
+ """Class concatenating several file-like objects.
+
+ This is similar in functionality to the unix `cat` command.
+ Data is read from each file in turn, until all have been
+ exhausted.
+
+ Since this doesnt make sense when writing to a file, the access
+ mode is assumed to be "r" and cannot be set or modified. Each
+ file is closed at the time of closing the wrapper.
+ """
+
+ def __init__(self,*files):
+ """Cat wrapper constructor.
+ This function accepts any number of file-like objects as its
+ only arguments. Data will be read from them in the order they
+ are provided.
+ """
+ FileWrapper.__init__(self,None,"r")
+ self._files = files
+ self._curFile = 0
+
+ def close(self):
+ FileWrapper.close(self)
+ for f in self._files:
+ if hasattr(f,"close"):
+ f.close()
+
+ def _read(self,sizehint=-1):
+ if len(self._files) <= self._curFile:
+ return None
+ data = self._files[self._curFile].read(sizehint)
+ if not len(data):
+ self._curFile += 1
+ data = self._read(sizehint)
+ return data
+
+ def _write(self,data):
+ raise IOError("Cat wrappers cannot be written to.")
+
+
+class Test_Cat(unittest.TestCase):
+ """Testcases for the filelike.Cat wrapper."""
+
+ def setUp(self):
+ self.intext1 = "Guido van Rossum\n is a space\n alien."
+ self.intext2 = "But that's ok with me!"
+ self.intext3 = "What do you think?"
+ self.infile1 = StringIO.StringIO(self.intext1)
+ self.infile2 = StringIO.StringIO(self.intext2)
+ self.infile3 = StringIO.StringIO(self.intext3)
+
+ def tearDown(self):
+ pass
+
+ def test_basic(self):
+ """Test basic concatenation of files."""
+ fs = Cat(self.infile1,self.infile2,self.infile3)
+ txt = "".join(fs.readlines())
+ txtC = "".join([self.intext1,self.intext2,self.intext3])
+ self.assertEquals(txt,txtC)
+
+
+## Conditionally provide BZ2File if bz2 library is present
+try:
+ import bz2
+ class BZ2File(FileWrapper):
+ """Class for reading and writing to a bziped file.
+
+ This class behaves almost exactly like the bz2.BZ2File class from