'''Reads a Slackware package information file

$Id: slackpack.py,v 1.2 1998/06/12 20:02:50 dan Exp $

$Log: slackpack.py,v $
Revision 1.2  1998/06/12 20:02:50  dan
Added Id and Log keywords.

96-10-20 Dan Fandrich
'''

from string import split, strip, atoi

class SlackPack:
	'''Read information from a Slackware package file

	Usage:	slack = SlackPack(open('/var/adm/packages/textutl'))
		name = slack['name']

	Valid tags are:
	'name'		Slackware package name (often 1-9 letters)
	'size'		approximate size of uncompressed package in bytes
	'compresssize'	approximate size of compressed package in bytes
	'location'	disk or file containing source of package
			(often of form 'disk[a-z][0-9]+')
	'description'	list of lines containing description
	'files'		list of file names in package
	'''

	def __init__(self, file):
		'Read package file information from file'

		def getsize(sizestr):
			'''Convert size line to integer

			e.g. '10 K' => 10240
			     '98765' => 98765
			'''
			s = split(sizestr)
			if len(s) == 2:
				size = atoi(s[0])
				if s[1] == 'K':
					size = size * 1024
			else:
				size = atoi(sizestr)
			return size

		self.name = '--noname--'
		self.size = None
		self.compresssize = None
		self.location = None
		self.description = []
		self.files = []
		finished = None

		while not finished:
			line = file.readline()
			contents = split(line,':')
			keyword = contents[0]
			param = contents[1]
			sparam = strip(param)

			if keyword == 'PACKAGE NAME':
				self.name = sparam
			elif keyword == 'UNCOMPRESSED PACKAGE SIZE':
				self.size = getsize(sparam)
			elif keyword == 'COMPRESSED PACKAGE SIZE' or \
			     keyword == 'PACKAGE SIZE':
				self.compresssize = getsize(sparam)
			elif keyword == 'PACKAGE LOCATION':
				self.location = sparam
			elif keyword == 'PACKAGE DESCRIPTION':
				pass
			elif keyword == self.name:
				# keyword of package name is part of description
				self.description.append(line[10:-1])
			elif keyword == 'FILE LIST':
				# get list of files files until file end
				while 1:
					line = file.readline()
					if not line:
						finished = 1
						break
					self.files.append(strip(line))
			else:
				raise 'UnknownKeyword', keyword

		# Remove blank lines at the end of the description
		while self.description and not self.description[-1]:
			del(self.description[-1])

	def __getitem__(self,key):
		'''Allow accessing items with the syntax slackclass['location']
		'''
		return eval('self.'+key)

	def printinfo(self):
		'Display info for debugging'
		print self.name
		print self.size
		print self.compresssize
		print self.location
		print 'DESCRIPTION:'
		for l in self.description:
			print l
		print 'FILES:'
		for l in self.files:
			print l

if __name__=='__main__':
	import sys
	for filename in sys.argv[1:]:
		file = open(filename,'r')
		sl = SlackPack(file)
		sl.printinfo()
