#!/usr/bin/env python

""" The Python Unix extended attributes bindings
*********************************************************

This is a Python extension created to manipulate extended attributes
in filesystems that support them.

I am honestly too tired to write documentation or error handling
beyond what I myself might need after this.  Please help me
in this regard.  In the meantime, "man 5 attr" is your friend.

TODO: write a dictionary-style wrapper for file objects or
something like?

"""

__all__ = [ "getfattr","setfattr", "delfattr" ]

from commandsplus import getstatusoutputerror, shell_escape

def getfattr(file,attrname):
	
	status,output,error = getstatusoutputerror("LANG=C getfattr -n %s --only-values %s"%(shell_escape(attrname),shell_escape(file)))
	if status != 0:
		raise Exception, "Error in getfattr: return code %s: %s"%(status,error)
	if output == "" and "No such attribute" in error:
		raise KeyError, "Attribute %s not present in file %s"%(attrname,file)
	return output

def setfattr(file,attrname,value):
	status,output,error = getstatusoutputerror("setfattr -n %s -v %s %s"%(shell_escape(attrname),shell_escape(value),shell_escape(file)))
	if status != 0:
		raise Exception, "Error in setfattr: return code %s: %s"%(status,error)
	
	
def delfattr(file,attrname):
	status,output,error = getstatusoutputerror("delfattr -n %s -x %s"%(shell_escape(attrname),shell_escape(file)))
	if status != 0:
		raise Exception, "Error in delfattr: return code %s: %s"%(status,error)
	if output == "" and "No such attribute" in error:
		raise KeyError, "Attribute %s not present in file %s"%(attrname,file)

	