multifil.py 3.9 KB
Newer Older
Guido van Rossum's avatar
Guido van Rossum committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
"""A readline()-style interface to the parts of a multipart message.

The MultiFile class makes each part of a multipart message "feel" like
an ordinary file, as long as you use fp.readline().  Allows recursive
use, for nested multipart messages.  Probably best used together
with module mimetools.

Suggested use:

real_fp = open(...)
fp = MultiFile(real_fp)

"read some lines from fp"
fp.push(separator)
while 1:
	"read lines from fp until it returns an empty string" (A)
	if not fp.next(): break
fp.pop()
"read remaining lines from fp until it returns an empty string"

The latter sequence may be used recursively at (A).
It is also allowed to use multiple push()...pop() sequences.

If seekable is given as 0, the class code will not do the bookeeping
it normally attempts in order to make seeks relative to the beginning of the
current file part.  This may be useful when using MultiFile with a non-
seekable stream object.
"""
29 30 31 32 33 34 35

import sys
import string

Error = 'multifile.Error'

class MultiFile:
Guido van Rossum's avatar
Guido van Rossum committed
36

Guido van Rossum's avatar
Guido van Rossum committed
37
	seekable = 0
Guido van Rossum's avatar
Guido van Rossum committed
38

Guido van Rossum's avatar
Guido van Rossum committed
39
	def __init__(self, fp, seekable=1):
40 41 42 43
		self.fp = fp
		self.stack = [] # Grows down
		self.level = 0
		self.last = 0
Guido van Rossum's avatar
Guido van Rossum committed
44 45 46 47
		if seekable:
			self.seekable = 1
			self.start = self.fp.tell()
			self.posstack = [] # Grows down
Guido van Rossum's avatar
Guido van Rossum committed
48

49 50 51 52
	def tell(self):
		if self.level > 0:
			return self.lastpos
		return self.fp.tell() - self.start
Guido van Rossum's avatar
Guido van Rossum committed
53

Guido van Rossum's avatar
Guido van Rossum committed
54 55 56 57 58 59 60 61 62 63 64
	def seek(self, pos, whence=0):
		here = self.tell()
		if whence:
			if whence == 1:
				pos = pos + here
			elif whence == 2:
				if self.level > 0:
					pos = pos + self.lastpos
				else:
					raise Error, "can't use whence=2 yet"
		if not 0 <= pos <= here or \
65 66 67 68 69
				self.level > 0 and pos > self.lastpos:
			raise Error, 'bad MultiFile.seek() call'
		self.fp.seek(pos + self.start)
		self.level = 0
		self.last = 0
Guido van Rossum's avatar
Guido van Rossum committed
70

71
	def readline(self):
Guido van Rossum's avatar
Guido van Rossum committed
72 73
		if self.level > 0:
			return ''
74
		line = self.fp.readline()
Guido van Rossum's avatar
Guido van Rossum committed
75
		# Real EOF?
76 77 78 79
		if not line:
			self.level = len(self.stack)
			self.last = (self.level > 0)
			if self.last:
Guido van Rossum's avatar
Guido van Rossum committed
80
				raise Error, 'sudden EOF in MultiFile.readline()'
81
			return ''
Guido van Rossum's avatar
Guido van Rossum committed
82 83 84 85 86 87 88 89 90 91 92 93
		assert self.level == 0
		# Fast check to see if this is just data
		if self.is_data(line):
			return line
		else:
			# Ignore trailing whitespace on marker lines 
			k = len(line) - 1;
			while line[k] in string.whitespace:
				k = k - 1
			marker = line[:k+1]
		# No?  OK, try to match a boundary.
		# Return the line (unstripped) if we don't.
94 95
		for i in range(len(self.stack)):
			sep = self.stack[i]
Guido van Rossum's avatar
Guido van Rossum committed
96
			if marker == self.section_divider(sep):
97 98
				self.last = 0
				break
Guido van Rossum's avatar
Guido van Rossum committed
99
			elif marker == self.end_marker(sep):
100 101 102 103
				self.last = 1
				break
		else:
			return line
Guido van Rossum's avatar
Guido van Rossum committed
104 105 106
		# We only get here if we see a section divider or EOM line
		if self.seekable:
			self.lastpos = self.tell() - len(line)
107 108
		self.level = i+1
		if self.level > 1:
Guido van Rossum's avatar
Guido van Rossum committed
109
			raise Error,'Missing endmarker in MultiFile.readline()'
110
		return ''
Guido van Rossum's avatar
Guido van Rossum committed
111

112 113 114 115 116 117 118
	def readlines(self):
		list = []
		while 1:
			line = self.readline()
			if not line: break
			list.append(line)
		return list
Guido van Rossum's avatar
Guido van Rossum committed
119

120 121
	def read(self): # Note: no size argument -- read until EOF only!
		return string.joinfields(self.readlines(), '')
Guido van Rossum's avatar
Guido van Rossum committed
122

123 124 125 126 127 128
	def next(self):
		while self.readline(): pass
		if self.level > 1 or self.last:
			return 0
		self.level = 0
		self.last = 0
Guido van Rossum's avatar
Guido van Rossum committed
129 130
		if self.seekable:
			self.start = self.fp.tell()
131
		return 1
Guido van Rossum's avatar
Guido van Rossum committed
132

133 134 135 136
	def push(self, sep):
		if self.level > 0:
			raise Error, 'bad MultiFile.push() call'
		self.stack.insert(0, sep)
Guido van Rossum's avatar
Guido van Rossum committed
137 138 139
		if self.seekable:
			self.posstack.insert(0, self.start)
			self.start = self.fp.tell()
Guido van Rossum's avatar
Guido van Rossum committed
140

141 142 143 144 145 146 147 148 149
	def pop(self):
		if self.stack == []:
			raise Error, 'bad MultiFile.pop() call'
		if self.level <= 1:
			self.last = 0
		else:
			abslastpos = self.lastpos + self.start
		self.level = max(0, self.level - 1)
		del self.stack[0]
Guido van Rossum's avatar
Guido van Rossum committed
150 151 152 153 154
		if self.seekable:
			self.start = self.posstack[0]
			del self.posstack[0]
			if self.level > 0:
				self.lastpos = abslastpos - self.start
Guido van Rossum's avatar
Guido van Rossum committed
155

Guido van Rossum's avatar
Guido van Rossum committed
156 157
	def is_data(self, line):
		return line[:2] <> '--'
Guido van Rossum's avatar
Guido van Rossum committed
158

Guido van Rossum's avatar
Guido van Rossum committed
159 160
	def section_divider(self, str):
		return "--" + str
Guido van Rossum's avatar
Guido van Rossum committed
161

Guido van Rossum's avatar
Guido van Rossum committed
162 163
	def end_marker(self, str):
		return "--" + str + "--"