# simplerfc822.py
#
# Copyright 2002 Wichert Akkerman <wichert@deephackmode.org>
#
# This file is free software; you can redistribute it and/or modify it
# under the terms of version 2 of the GNU General Public License as
# published by the Free Software Foundation.
#
# This program 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
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

"""Trivial RFC822-like parser.

Much like the rfc822 module from the standard python library, but
much simpler and faster. This module only supports simple "field: value"
style fields with the normal rfc822 line continuation. Repeated fields
are also not supported.

Assumes it reads from a TextFile so it can produce more informative error
message.
"""

__docformat__   = "epytext en"

import UserDict

class FileException(Exception):
	"""Parse error.

	@ivar file: name of file being parsed
	@type file: string
	@ivar line: linenumber on which error occured
	@type line: integer
	"""
	def __init__(self, file, line, reason):
		"""Constructur

		@param file:   name of file being parsed
		@type file:    string
		@param line:   linenumber on which error occured
		@type line:    integer
		@param reason: description of the error
		@type reason:  string
		"""
		Exception.__init__(reason)
		self.file=file
		self.line=line


	def __str__(self):
		return "%s(%d): %s" % (self.file, self.line, self.value)


class Message(UserDict.UserDict):
	"""Simple-RFC822 message object.

	This class works just like the standard python rfc822 module.
	"""
	def __init__(self, fp=None):
		UserDict.UserDict.__init__(self)

		if fp:
			self.Parse(fp)


	def Parse(self, fp):
		"""Parse a textfile

		@param fp: file to parse
		@type fp:  dpkg.textfile.TextFile instance
		"""
		self.data.clear()

		lasthdr=None
		while 1:
			line=fp.readline()

			if not line or line in [ "\r\n", "\n" ]:
				break

			line=line.rstrip()

			if line[0] in " \t":
				self.data[lasthdr]+="\n"+line[1:]
			else:
				i=line.find(":")
				if i==-1:
					raise FileException(fp.filename, fp.lineno, "Syntax error")
				
				lasthdr=line[:i]
				self.data[lasthdr]=line[(i+1):].lstrip()

