#!@PYTHON@ -O
# Copyright 1999-2006 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
# $Id: repoman 4651 2006-10-10 21:10:33Z zmedico $

# Next to do: dep syntax checking in mask files
# Then, check to make sure deps are satisfiable (to avoid "can't find match for" problems)
# that last one is tricky because multiple profiles need to be checked.

import errno
import os
import shutil
import sys
import signal
import re
import tempfile

try:
	import cPickle as pickle
except ImportError:
	import pickle

if not hasattr(__builtins__, "set"):
	from sets import Set as set

exename=os.path.basename(sys.argv[0])	
version="1.2"	

allowed_filename_chars="a-zA-Z0-9._-+:"
allowed_filename_chars_set = {}
map(allowed_filename_chars_set.setdefault, map(chr, range(ord('a'), ord('z')+1)))
map(allowed_filename_chars_set.setdefault, map(chr, range(ord('A'), ord('Z')+1)))
map(allowed_filename_chars_set.setdefault, map(chr, range(ord('0'), ord('9')+1)))
map(allowed_filename_chars_set.setdefault, map(chr, map(ord, [".", "-", "_", "+", ":"])))

os.environ["PORTAGE_LEGACY_GLOBALS"] = "false"
try:
	import portage
except ImportError:
	from os import path as osp
	sys.path.insert(0, osp.join(osp.dirname(osp.dirname(osp.realpath(__file__))), "pym"))
	import portage
del os.environ["PORTAGE_LEGACY_GLOBALS"]

import portage.checksum
import portage.const
import portage.dep
import portage.dep
portage.dep._dep_check_strict = True
import portage.exception
from portage import cvstree
import time
import codecs

from portage.manifest import Manifest
from portage.exception import ParseError
from portage.process import find_binary, spawn

from portage.output import bold, darkgreen, darkred, green, nocolor, red, turquoise, yellow

from commands import getstatusoutput
from fileinput import input
from grp import getgrnam
from stat import S_ISDIR, ST_CTIME, ST_GID, ST_MTIME

# A sane umask is needed for files that portage creates.
os.umask(022)
repoman_settings = portage.config(local_config=False,
	config_incrementals=portage.const.INCREMENTALS)
repoman_settings.lock()

if repoman_settings.get("NOCOLOR", "").lower() in ("yes", "true") or \
	not sys.stdout.isatty():
	nocolor()

def warn(txt):
	print exename+": "+txt
def err(txt):
	warn(txt)
	sys.exit(1)

def err_help(txt):
	help(exitstatus=-1,helpfulness=0)
	warn(txt)
	sys.exit(1)

def exithandler(signum=None,frame=None):
	sys.stderr.write("\n"+exename+": Interrupted; exiting...\n")
	sys.exit(1)
	os.kill(0,signal.SIGKILL)
signal.signal(signal.SIGINT,exithandler)

shortmodes={"ci":"commit"}
modeshelp={
"scan"   : "Scan directory tree for QA issues (default)",
"manifest" : "Generate a Manifest (fetches files if necessary)",
"fix"    : "Fix simple QA issues (stray digests, missing digests)",
"full"   : "Scan directory tree for QA issues (full listing)",
"help"   : "Show this screen",
"commit" : "Scan directory tree for QA issues; if OK, commit via cvs",
"last"   : "Remember report from last run",
"lfull"  : "Remember report from last run (full listing)"
}
modes=modeshelp.keys()
repoman_options={
"--commitmsg"      : "Adds a commit message via the command line",
"--commitmsgfile"  : "Adds a commit message from the specified file",
"--help"           : "Show this screen",
"--ignore-arches"  : "Ignore arch-specific failures (where arch != host)",
"--ignore-masked"  : "Ignore masked packages (not allowed with commit mode)",
"--pretend"        : "Don't commit or fix anything; just show what would be done",
"--quiet"          : "Be less verbose about extraneous info",
"--verbose"        : "Displays every package name while checking",
"--version"        : "Show version info",
"--xmlparse"       : "Forces the metadata.xml parse check to be carried out"
}
repoman_shortoptions={
"-h" : "--help",
"-i" : "--ignore-masked",
"-I" : "--ignore-arches",
"-m" : "--commitmsg",
"-M" : "--commitmsgfile",
"-p" : "--pretend",
"-q" : "--quiet",
"-v" : "--verbose",
"-V" : "--version",
"-x" : "--xmlparse"
}
repoman_shortoptions_rev=dict([(v,k) for (k,v) in repoman_shortoptions.items()])
options=repoman_options.keys()

qahelp={
	"CVS/Entries.IO_error":"Attempting to commit, and an IO error was encountered access the Entries file",
	"digest.partial":"Digest files do not contain all corresponding URI elements",
	"digest.assumed":"Existing digest must be assumed correct (Package level only)",
	"digestentry.unused":"Digest/Manifest entry has no matching SRC_URI entry",
	"digest.fail":"Digest does not match the specified local file",
	"digest.stray":"Digest files that do not have a corresponding ebuild",
	"digest.missing":"Digest files that are missing (ebuild exists, digest doesn't)",
	"digest.disjointed":"Digests not added to cvs when the matching ebuild has been added",
	"digest.notadded":"Digests that exist but have not been added to cvs",
	"digest.unmatch":"Digests which are incomplete (please check if your USE/ARCH includes all files)",
	"ebuild.invalidname":"Ebuild files with a non-parseable or syntactically incorrect name (or using 2.1 versioning extensions)",
	"ebuild.namenomatch":"Ebuild files that do not have the same name as their parent directory",
	"changelog.missing":"Missing ChangeLog files",
	"ebuild.disjointed":"Ebuilds not added to cvs when the matching digest has been added",
	"ebuild.notadded":"Ebuilds that exist but have not been added to cvs",
	"changelog.notadded":"ChangeLogs that exist but have not been added to cvs",
	"filedir.missing":"Package lacks a files directory",
	"file.executable":"Ebuilds, digests, metadata.xml, Manifest, and ChangeLog do note need the executable bit",
	"file.size":"Files in the files directory must be under 20k",
	"file.name":"File/dir name must be composed of only the following chars: %s " % allowed_filename_chars,
	"file.UTF8":"File is not UTF8 compliant",
	"KEYWORDS.missing":"Ebuilds that have a missing or empty KEYWORDS variable",
	"KEYWORDS.stupid":"Ebuilds that use KEYWORDS=-* instead of package.mask", 
	"LICENSE.missing":"Ebuilds that have a missing or empty LICENSE variable",
	"DESCRIPTION.missing":"Ebuilds that have a missing or empty DESCRIPTION variable",
	"SLOT.missing":"Ebuilds that have a missing or empty SLOT variable",
	"HOMEPAGE.missing":"Ebuilds that have a missing or empty HOMEPAGE variable",
	"DEPEND.bad":"User-visible ebuilds with bad DEPEND settings (matched against *visible* ebuilds)",
	"RDEPEND.bad":"User-visible ebuilds with bad RDEPEND settings (matched against *visible* ebuilds)",
	"PDEPEND.bad":"User-visible ebuilds with bad PDEPEND settings (matched against *visible* ebuilds)",
	"DEPEND.badmasked":"Masked ebuilds with bad DEPEND settings (matched against *all* ebuilds)",
	"RDEPEND.badmasked":"Masked ebuilds with RDEPEND settings (matched against *all* ebuilds)",
	"PDEPEND.badmasked":"Masked ebuilds with PDEPEND settings (matched against *all* ebuilds)",
	"DEPEND.badindev":"User-visible ebuilds with bad DEPEND settings (matched against *visible* ebuilds) in developing arch",
	"RDEPEND.badindev":"User-visible ebuilds with bad RDEPEND settings (matched against *visible* ebuilds) in developing arch",
	"PDEPEND.badindev":"User-visible ebuilds with bad PDEPEND settings (matched against *visible* ebuilds) in developing arch",
	"DEPEND.badmaskedindev":"Masked ebuilds with bad DEPEND settings (matched against *all* ebuilds) in developing arch",
	"RDEPEND.badmaskedindev":"Masked ebuilds with RDEPEND settings (matched against *all* ebuilds) in developing arch",
	"PDEPEND.badmaskedindev":"Masked ebuilds with PDEPEND settings (matched against *all* ebuilds) in developing arch",
	"DEPEND.syntax":"Syntax error in DEPEND (usually an extra/missing space/parenthesis)",
	"RDEPEND.syntax":"Syntax error in RDEPEND (usually an extra/missing space/parenthesis)",
	"PDEPEND.syntax":"Syntax error in PDEPEND (usually an extra/missing space/parenthesis)",
	"LICENSE.syntax":"Syntax error in LICENSE (usually an extra/missing space/parenthesis)",
	"PROVIDE.syntax":"Syntax error in PROVIDE (usually an extra/missing space/parenthesis)",
	"RESTRICT.syntax":"Syntax error in RESTRICT (usually an extra/missing space/parenthesis)",
	"SRC_URI.syntax":"Syntax error in SRC_URI (usually an extra/missing space/parenthesis)",
	"ebuild.syntax":"Error generating cache entry for ebuild; typically caused by ebuild syntax error",
	"ebuild.output":"A simple sourcing of the ebuild produces output; this breaks ebuild policy.",
	"ebuild.nesteddie":"Placing 'die' inside ( ) prints an error, but doesn't stop the ebuild.",
	"variable.readonly":"Assigning a readonly variable",
	"LIVEVCS.stable":"This ebuild is a live checkout from a VCS but has stable keywords.",
	"IUSE.invalid":"This ebuild has a variable in IUSE that is not in the use.desc or use.local.desc file",
	"LICENSE.invalid":"This ebuild is listing a license that doesnt exist in portages license/ dir.",
	"KEYWORDS.invalid":"This ebuild contains KEYWORDS that are not listed in profiles/arch.list or for which no valid profile was found",
	"RESTRICT.invalid":"This ebuild contains invalid RESTRICT values.",
	"ebuild.nostable":"There are no ebuilds that are marked as stable for your ARCH",
	"ebuild.allmasked":"All ebuilds are masked for this package (Package level only)",
	"ebuild.majorsyn":"This ebuild has a major syntax error that may cause the ebuild to fail partially or fully",
	"ebuild.minorsyn":"This ebuild has a minor syntax error that contravenes gentoo coding style",
	"ebuild.badheader":"This ebuild has a malformed header",
	"metadata.missing":"Missing metadata.xml files",
	"metadata.bad":"Bad metadata.xml files",
	"virtual.versioned":"PROVIDE contains virtuals with versions",
	"virtual.exists":"PROVIDE contains existing package names",
	"virtual.unavailable":"PROVIDE contains a virtual which contains no profile default",
	"usage.obsolete":"The ebuild makes use of an obsolete construct"
}

qacats = qahelp.keys()
qacats.sort()

qawarnings=[
"changelog.missing",
"changelog.notadded",
"ebuild.notadded",
"ebuild.nostable",
"ebuild.allmasked",
"ebuild.nesteddie",
"digest.assumed",
"digest.notadded",
"digest.disjointed",
"digest.missing",
"digestentry.unused",
"DEPEND.badmasked","RDEPEND.badmasked","PDEPEND.badmasked",
"DEPEND.badindev","RDEPEND.badindev","PDEPEND.badindev",
"DEPEND.badmaskedindev","RDEPEND.badmaskedindev","PDEPEND.badmaskedindev",
"IUSE.invalid",
"KEYWORDS.stupid",
"KEYWORDS.missing",
"RESTRICT.invalid",
"ebuild.minorsyn",
"ebuild.badheader",
"file.size",
"metadata.missing",
"metadata.bad",
"virtual.versioned",
"virtual.exists",
"virtual.unavailable",
"usage.obsolete",
"LIVEVCS.stable"
]

missingvars=["KEYWORDS","LICENSE","DESCRIPTION","HOMEPAGE","SLOT"]
allvars=portage.auxdbkeys
commitmessage=None
commitmessagefile=None
for x in missingvars:
	x += ".missing"
	if x not in qacats:
		print "* missingvars values need to be added to qahelp ("+x+")"
		qacats.append(x)
		qawarnings.append(x)

valid_restrict = frozenset(["binchecks", "bindist", "fetch", "mirror",
	"primaryuri", "strip", "test", "userpriv"])

verbose=0
quiet=0

def show_version():
	print exename+" "+version
	sys.exit(0)
	
def help(exitstatus=1,helpfulness=1):
	if quiet:
		helpfulness=0
	if helpfulness:
		print
		print green(exename+" "+version)
		print " \"Quality is job zero.\""
		print " Copyright 1999-2006 Gentoo Foundation"
		print " Distributed under the terms of the GNU General Public License v2"
		print
	print bold(" Usage:"),turquoise(exename),"[",green("options"),"] [",green("mode"),"]"
	if helpfulness:
		print bold(" Modes:"),turquoise("scan (default)"),
		for x in modes[1:]:
			print "|",turquoise(x),
		print
	print
	print " "+green("Options".ljust(20)+" Description")
	for x in options:
		if repoman_shortoptions_rev.has_key(x):
			shopt=repoman_shortoptions_rev[x]+", "+x
		else:
			shopt="    "+x
		print " "+shopt.ljust(20),repoman_options[x]
	print
	print " "+green("Modes".ljust(20)+" Description")
	for x in modes:
		print " "+x.ljust(20),modeshelp[x]
	if helpfulness:
		print
		print " "+green("QA keyword".ljust(20)+" Description")
		for x in qacats:
			print " "+x.ljust(20),qahelp[x]
		print
	if (exitstatus != -1):
		sys.exit(exitstatus)
	else:
		print

def last():
	try:
		#Retrieve and unpickle stats and fails from saved files
		mystats=os.path.normpath(portage.const.CACHE_DIR+'/repo.stats')
		myfails=os.path.normpath(portage.const.CACHE_DIR+'/repo.fails')
		savedf=open(mystat,'r')
		stats = pickle.load(savedf)
		savedf.close()
		savedf=open(myfails,'r')
		fails = pickle.load(savedf)
		savedf.close()
	except SystemExit, e:
		raise  # Need to propogate this
	except:
		err("Error retrieving last repoman run data; exiting.")

	#dofail will be set to 1 if we have failed in at least one non-warning category
	dofail=0
	#dowarn will be set to 1 if we tripped any warnings
	dowarn=0
	#dofull will be set if we should print a "repoman full" informational message
	dofull=0

	print
	print green("RepoMan remembers...")
	print
	for x in qacats:
		if stats[x]:
			dowarn=1
			if x not in qawarnings:
				dofail=1
		else:
			continue
		print "  "+ x.ljust(20),
		if stats[x]==0:
			print green(`stats[x]`)
			continue
		elif x in qawarnings:
			print yellow(`stats[x]`)
		else:
			print red(`stats[x]`)
		if mymode!="lfull":
			if stats[x]<12:
				for y in fails[x]:
					print "   "+y
			else:
				dofull=1
		else:
			for y in fails[x]:
				print "   "+y
	print
	if dofull:
		print bold("Note: type \"repoman lfull\" for a complete listing of repomans last run.")
		print
	if dowarn and not dofail:
		print green("RepoMan sez:"),"\"You only gave me a partial QA payment last time?\n              I took it, but I wasn't happy.\""
	elif not dofail:
		print green("RepoMan sez:"),"\"If everyone were like you, I'd be out of business!\""
	print
	sys.exit(1)

mymode=None
myoptions=[]
if len(sys.argv)>1:
	x=1
	while x < len(sys.argv):
		if sys.argv[x] in shortmodes:
			sys.argv[x]=shortmodes[sys.argv[x]]
		elif sys.argv[x] in repoman_shortoptions:
			sys.argv[x] = repoman_shortoptions[sys.argv[x]]
		if sys.argv[x] in modes:
			if mymode is None:
				mymode=sys.argv[x]
			else:
				err("Please specify either \""+mymode+"\" or \""+sys.argv[x]+"\", but not both.")
		elif sys.argv[x] in options:
			optionx=sys.argv[x]
			if (optionx=="--commitmsg") and (len(sys.argv)>=(x+1)):
				commitmessage=sys.argv[x+1]
				x=x+1
			elif (optionx=="--commitmsgfile") and (len(sys.argv)>=(x+1)):
				commitmessagefile=sys.argv[x+1]
				x=x+1
			elif (optionx=="--verbose"):
				verbose+=1
			elif (optionx=="--quiet"):
				quiet+=1
			elif optionx not in myoptions:
				myoptions.append(optionx)
		else:
			err_help("\""+sys.argv[x]+"\" is not a valid mode or option.")
		x=x+1
if mymode is None:
	mymode="scan"
if mymode=="help" or ("--help" in myoptions):
	help(exitstatus=0)
if ("--version" in myoptions):
	show_version()
if mymode=="last" or (mymode=="lfull"):
	last()
if mymode == "commit":
	while "--ignore-masked" in myoptions:
		myoptions.remove("--ignore-masked")

from portage import normalize_path
isCvs=False
myreporoot=None
if os.path.isdir("CVS"):
	isCvs = True

	try:
		isCvs=True
		myrepofile=open("CVS/Repository")
		myreporoot=myrepofile.readline()[:-1]
		myrepofile.close()
		myrepofile=open("CVS/Root")
		myreporootpath=string.split(myrepofile.readline()[:-1], ":")[-1]
		myrepofile.close()
		if myreporootpath == myreporoot[:len(myreporootpath)]:
			# goofy os x cvs co.
			myreporoot = myreporoot[len(myreporootpath):]
			while myreporoot and myreporoot[0] == '/':
				myreporoot = myreporoot[1:]
	except SystemExit, e:
		raise  # Need to propogate this
	except:
		err("Error grabbing repository information; exiting.")
	myreporootpath=os.path.normpath(myreporootpath)
	if myreporootpath=="/space/cvsroot":
		print
		print
		print red("You're using the wrong cvsroot. For Manifests to be correct, you must")
		print red("use the same base cvsroot path that the servers use. Please try the")
		print red("following script to remedy this:")
		print
		print "cd my_cvs_tree"
		print
		print "rm -Rf [a-z]*"
		print "cvs up"
		print
		if portage.userland=="BSD" or portage.userland=="Darwin":
			print "find ./ -type f -regex '.*/CVS/Root$' -print0 | xargs -0 sed \\"
		else:
			print "find ./ -type f -regex '.*/CVS/Root$' -print0 | xargs -0r sed \\"
		fi
		print "  -i 's:/space/cvsroot$:/home/cvsroot:'"
		print
		print red("You must clear and re-update your tree as all header tags will cause")
		print red("problems in manifests for all rsync and /home/cvsroot users.")
		print
		print "You should do this to any other gentoo trees your have as well,"
		print "excluding the deletions. 'gentoo-src' should be /home/cvsroot."
		print
		sys.exit(123)

isSvn=False
myreporoot=None
if os.path.isdir(".svn"):
	try:
		isSvn=True
		myrepoinfo = os.popen("svn info").readlines()
		myurl = myrepoinfo[1].split(":")[1].rstrip()
		myreproot = myrepoinfo[2].split(":")[1].rstrip()
		# This one is EVIL, but I don't know how to solve the problem of
		# getting rid of /trunk/prefix-overlay.  This only works on the
		# prefix overlay.
		myreporoot = "/".join(myurl[len(myreproot):].split("/")[2:])
		myreporootpath = "/" + "/".join(myreproot.split("/")[3:])
	except SystemExit, e:
		raise  # Need to propogate this
	except:
		err("Error grabbing repository information; exiting.")

if mymode == "commit" and \
	not isCvs and not isSvn and \
	"--pretend" not in myoptions:
	print
	print darkgreen("Not in a CVS or SVN repository; enabling pretend mode.")
	myoptions.append("--pretend");


def have_profile_dir(path, maxdepth=3):
	while path != "/" and maxdepth:
		if os.path.exists(path + "/profiles/package.mask"):
			return normalize_path(path)
		path = normalize_path(path + "/..")
		maxdepth -= 1

portdir=None
portdir_overlay=None
mydir=os.getcwd()
if "PWD" in os.environ and os.environ["PWD"] != mydir and \
	os.path.realpath(os.environ["PWD"]) == mydir:
	# getcwd() returns the canonical path but that makes it hard for repoman to
	# orient itself if the user has symlinks in their portage tree structure.
	# We use os.environ["PWD"], if available, to get the non-canonical path of
	# the current working directory (from the shell).
	mydir = os.environ["PWD"]
mydir = normalize_path(mydir)
path_ids = set()
p = mydir
s = None
while True:
	s = os.stat(p)
	path_ids.add((s.st_dev, s.st_ino))
	if p == "/":
		break
	p = os.path.dirname(p)
if mydir[-1] != "/":
	mydir += "/"

for overlay in repoman_settings["PORTDIR_OVERLAY"].split():
	overlay = os.path.realpath(overlay)
	try:
		s = os.stat(overlay)
	except OSError:
		continue
	overlay_id = (s.st_dev, s.st_ino)
	if overlay[-1] != "/":
		overlay += "/"
	if overlay_id in path_ids:
		portdir_overlay = overlay
		subdir = mydir[len(overlay):]
		if subdir and subdir[-1] != "/":
			subdir += "/"
		if have_profile_dir(mydir, subdir.count("/")):
			portdir = portdir_overlay
		break

del p, s, path_ids

if not portdir_overlay:
	if (repoman_settings["PORTDIR"] + os.path.sep).startswith(mydir):
		portdir_overlay = repoman_settings["PORTDIR"]
	else:
		portdir_overlay = have_profile_dir(mydir)
	portdir = portdir_overlay

if not portdir_overlay:
	sys.stderr.write("Repoman is unable to determine PORTDIR or PORTDIR_OVERLAY from" + \
		" the current\nworking directory.\n")
	sys.exit(1)

if not portdir:
	portdir = repoman_settings["PORTDIR"]

portdir = normalize_path(portdir)
portdir_overlay = normalize_path(portdir_overlay)

os.environ["PORTDIR"] = portdir
if portdir_overlay != portdir:
	os.environ["PORTDIR_OVERLAY"] = portdir_overlay
else:
	os.environ["PORTDIR_OVERLAY"] = ""

if quiet < 2:
	print "\nSetting paths:"
	print "PORTDIR = \""+os.environ["PORTDIR"]+"\""
	print "PORTDIR_OVERLAY = \""+os.environ["PORTDIR_OVERLAY"]+"\""

# Now that PORTDIR_OVERLAY is properly overridden, create the portdb.
repoman_settings = portage.config(local_config=False,
	config_incrementals=portage.const.INCREMENTALS)
trees = portage.create_trees()
trees["/"]["porttree"].settings = repoman_settings
portdb = trees["/"]["porttree"].dbapi
portdb.mysettings = repoman_settings
# dep_zapdeps looks at the vardbapi, but it shouldn't for repoman.
del trees["/"]["vartree"]

if not myreporoot:
	myreporoot = os.path.basename(portdir_overlay)
	myreporoot += mydir[len(portdir_overlay):-1]

if isSvn:
	reposplit=myreporoot.split("/")
else:
	reposplit=myreporoot.split("/")
repolevel=len(reposplit)

# check if it's in $PORTDIR/$CATEGORY/$PN , otherwise bail if commiting.
# Reason for this is if they're trying to commit in just $FILESDIR/*, the Manifest needs updating.
# this check ensure that repoman knows where it is, and the manifest recommit is at least possible.
if mymode == "commit" and repolevel not in [1,2,3]:
	print red("***")+" Commit attempts *must* be from within a cvs or svn co, category, or package directory."
	print red("***")+" Attempting to commit from a packages files directory will be blocked for instance."
	print red("***")+" This is intended behaviour, to ensure the manifest is recommited for a package."
	print red("***")
	err("Unable to identify level we're commiting from for %s" % '/'.join(reposplit))

startdir = normalize_path(mydir)
repodir = startdir
for x in range(0,repolevel-1):
	repodir = os.path.dirname(repodir)

def caterror(mycat):
	err(mycat+" is not an official category.  Skipping QA checks in this directory.\nPlease ensure that you add "+catdir+" to "+repodir+"/profiles/categories\nif it is a new category.")
if mymode == "manifest":
	pass
elif "--pretend" in myoptions:
	print green("\nRepoMan does a once-over of the neighborhood...")
elif quiet < 1:
	print green("\nRepoMan scours the neighborhood...")

def parse_use_local_desc(mylines, usedict=None):
	"""returns a dict of the form {cpv:set(flags)}"""
	if usedict is None:
		usedict = {}
	lineno = 0
	for l in mylines:
		lineno += 1
		if not l or l.startswith("#"):
			continue
		mysplit = l.split(None, 1)
		if not mysplit:
			continue
		mysplit = mysplit[0].split(":")
		if len(mysplit) != 2:
			raise ParseError("line %d: Malformed input: '%s'" % \
				(lineno, l.rstrip("\n")))
		usedict.setdefault(mysplit[0], set())
		usedict[mysplit[0]].add(mysplit[1])
	return usedict

# retreive local USE list
luselist={}
try:
	f = open(os.path.join(portdir, "profiles", "use.local.desc"))
	parse_use_local_desc(f, luselist)
	f.close()
except (IOError, OSError, ParseError), e:
	print >> sys.stderr, str(e)
	err("Couldn't read from use.local.desc")

if portdir_overlay != portdir:
	filename = os.path.join(portdir_overlay, "profiles", "use.local.desc")
	if os.path.exists(filename):
		try:
			f = open(filename)
			parse_use_local_desc(f, luselist)
			f.close()
		except (IOError, OSError, ParseError), e:
			print >> sys.stderr, str(e)
			err("Couldn't read from '%s'" % filename)
	del filename

# setup a uselist from portage
uselist=[]
try:
	uselist=portage.grabfile(portdir+"/profiles/use.desc")
	for l in range(0,len(uselist)):
		uselist[l]=uselist[l].split()[0]
	for var in repoman_settings["USE_EXPAND"].split():
		vardescs = portage.grabfile(portdir+"/profiles/desc/"+var.lower()+".desc")
		for l in range(0, len(vardescs)):
			uselist.append(var.lower() + "_" + vardescs[l].split()[0])
except SystemExit, e:
	raise  # Need to propogate this
except:
	err("Couldn't read USE flags from use.desc")

# retrieve a list of current licenses in portage
liclist = set(portage.listdir(os.path.join(portdir, "licenses")))
if not liclist:
	err("Couldn't find licenses?")
if portdir_overlay != portdir:
	liclist.update(portage.listdir(os.path.join(portdir_overlay, "licenses")))

# retrieve list of offical keywords
kwlist = set(portage.grabfile(os.path.join(portdir, "profiles", "arch.list")))
if not kwlist:
	err("Couldn't read KEYWORDS from arch.list")

manifest1_compat = not os.path.exists(
	os.path.join(portdir, "manifest1_obsolete"))
if portdir_overlay != portdir:
	kwlist.update(portage.grabfile(
		os.path.join(portdir_overlay, "profiles", "arch.list")))
	manifest1_compat = not os.path.exists(
		os.path.join(portdir_overlay, "manifest1_obsolete"))

scanlist=[]
if repolevel==2:
	#we are inside a category directory
	catdir=reposplit[-1]
	if catdir not in repoman_settings.categories:
		caterror(catdir)
	mydirlist=os.listdir(startdir)
	for x in mydirlist:
		if x == "CVS" or x.startswith("."):
			continue
		if os.path.isdir(startdir+"/"+x):
			scanlist.append(catdir+"/"+x)
elif repolevel==1:
	for x in repoman_settings.categories:
		if not os.path.isdir(startdir+"/"+x):
			continue
		for y in os.listdir(startdir+"/"+x):
			if y == "CVS" or y.startswith("."):
				continue
			if os.path.isdir(startdir+"/"+x+"/"+y):
				scanlist.append(x+"/"+y)
elif repolevel==3:
	catdir = reposplit[-2]
	if catdir not in repoman_settings.categories:
		caterror(catdir)
	scanlist.append(catdir+"/"+reposplit[-1])

profiles={}
descfile=portdir+"/profiles/profiles.desc"
if os.path.exists(descfile):
	for x in portage.grabfile(descfile):
		if x[0]=="#":
			continue
		arch=x.split()
		if len(arch)!=3:
			print "wrong format: \""+red(x)+"\" in "+descfile
			continue
		if not os.path.isdir(portdir+"/profiles/"+arch[1]):
			print "Invalid "+arch[2]+" profile ("+arch[1]+") for arch "+arch[0]
			continue
		if profiles.has_key(arch[0]):
			profiles[arch[0]]+= [[arch[1], arch[2]]]
		else:
			profiles[arch[0]] = [[arch[1], arch[2]]]

	for x in repoman_settings.archlist():
		if x[0] == "~":
			continue
		if not profiles.has_key(x):
			print red("\""+x+"\" doesn't have a valid profile listed in profiles.desc.")
			print red("You need to either \"cvs update\" your profiles dir or follow this")
			print red("up with the "+x+" team.")
			print
else:
	print red("profiles.desc does not exist: "+descfile)
	print red("You need to do \"cvs update\" in profiles dir.")
	print
	sys.exit(1)


stats={}
fails={}

for x in qacats:
	stats[x]=0
	fails[x]=[]
xmllint_capable = False
metadata_dtd = os.path.join(repoman_settings["DISTDIR"], 'metadata.dtd')
if mymode == "manifest":
	pass
elif not find_binary('xmllint'):
	print red("!!! xmllint not found. Can't check metadata.xml.\n")
	if "--xmlparse" in myoptions or repolevel==3:
		print red("!!!")+" sorry, xmllint is needed.  failing\n"
		sys.exit(1)
else:
	#hardcoded paths/urls suck. :-/
	must_fetch=1
	backup_exists=0
	try:
		# if it's been over a week since fetching (or the system clock is fscked), grab an updated copy of metadata.dtd 
		# clock is fscked or it's been a week. time to grab a new one.
		ct = os.stat(metadata_dtd)[ST_CTIME]
		if abs(time.time() - ct) > (60*60*24*7):
			# don't trap the exception, we're watching for errno 2 (file not found), anything else is a bug.
			backup_exists=1
		else:
			must_fetch=0

	except (OSError,IOError), e:
		if e.errno != 2:
			print red("!!!")+" caught exception '%s' for %s/metadata.dtd, bailing" % (str(e), portage.CACHE_PATH)
			sys.exit(1)

	if must_fetch:
		print 
		print green("***")+" the local copy of metadata.dtd needs to be refetched, doing that now"
		print
		val = 0
		try:
			try:
				os.unlink(metadata_dtd)
			except OSError, e:
				if e.errno != errno.ENOENT:
					raise
				del e
			val=portage.fetch(['http://www.gentoo.org/dtd/metadata.dtd'],repoman_settings,fetchonly=0, \
				try_mirrors=0)

		except SystemExit, e:
			raise  # Need to propogate this
		except Exception,e:
			print
			print red("!!!")+" attempting to fetch 'http://www.gentoo.org/dtd/metadata.dtd', caught"
			print red("!!!")+" exception '%s' though." % str(e)
			val=0
		if not val:
			print red("!!!")+" fetching new metadata.dtd failed, aborting"
			sys.exit(1)
	#this can be problematic if xmllint changes their output
	xmllint_capable=True


def x11_deprecation_check(depstr):
	if depstr.find("virtual/x11") == -1:
		return False
	depsplit = depstr.split()
	ok_stack = []
	ok = False
	for token in depsplit:
		if token == "(":
			ok_stack.append(ok)
			ok = False
		elif token == ")":
			ok = ok_stack.pop()
		elif token == "||":
			ok = True
		else:
			ok = False
			if token.find("virtual/x11") != -1 and (not ok_stack or not ok_stack[-1]):
				return True
	return False

dofail = 0
arch_caches={}
arch_xmatch_caches = {}
for x in scanlist:
	#ebuilds and digests added to cvs respectively.
	if verbose:
		print "checking package " + x
	eadded=[]
	dadded=[]
	catdir,pkgdir=x.split("/")
	checkdir=repodir+"/"+x

	if mymode == "manifest":
		repoman_settings["O"] = checkdir
		if not portage.digestgen([], repoman_settings, myportdb=portdb):
			print "Unable to generate manifest."
			dofail = 1
		continue

	checkdirlist=os.listdir(checkdir)
	ebuildlist=[]
	for y in checkdirlist:
		if y[-7:]==".ebuild":
			ebuildlist.append(y[:-7])
		if y in ["Manifest","ChangeLog","metadata.xml"]:
			if os.stat(checkdir+"/"+y)[0] & 0x0248:
				stats["file.executable"] += 1
				fails["file.executable"].append(checkdir+"/"+y)
	digestlist=[]

	for y in checkdirlist:
		for c in y.strip(os.path.sep):
			if c not in allowed_filename_chars_set:
				stats["file.name"] += 1
				fails["file.name"].append("%s/%s: char '%s'" % (checkdir, y, c))
				break

		if not (y in ("ChangeLog", "metadata.xml") or y.endswith(".ebuild")):
			continue
		try:
			line = 1
			for l in codecs.open(checkdir+"/"+y, "r", "utf8"):
				line +=1
		except UnicodeDecodeError, ue:
			stats["file.UTF8"] += 1
			s = ue.object[:ue.start]
			l2 = s.count("\n")
			line += l2
			if l2 != 0:
				s = s[s.rfind("\n") + 1:]
			fails["file.UTF8"].append("%s/%s: line %i, just after: '%s'" % (checkdir, y, line, s))

	has_filesdir = True
	if not os.path.isdir(os.path.join(checkdir, "files")):
		has_filesdir = False
		if manifest1_compat:
			stats["filedir.missing"] += 1
			fails["filedir.missing"].append(checkdir)

	if isCvs or isSvn:
		try:
			if isCvs:
				myf=open(checkdir+"/CVS/Entries","r")
			if isSvn:
				myf=os.popen("svn update > /dev/null; svn list")
			myl=myf.readlines()	
			myf.close()
			for l in myl:
				if isCvs:
					if l[0]!="/":
						continue
					splitl=l[1:].split("/")
					if not len(splitl):
						continue
					if splitl[0][-7:]==".ebuild":
						eadded.append(splitl[0][:-7])
				if isSvn:
					l = l.rstrip();
					if l[-1:] == "/":
						continue
					if l[-7:] == ".ebuild":
						eadded.append(l[:-7])
			if isSvn:
				myf=os.popen("svn status")
				myl=myf.readlines()
				myf.close()
				for l in myl:
					if l[0] == "A":
						l = l.rstrip().split(' ')[-1]
						if l[-7:] == ".ebuild":
							eadded.append(l[:-7])
		except IOError:
			if mymode=="commit" and isCvs:
				stats["CVS/Entries.IO_error"] += 1
				fails["CVS/Entries.IO_error"].append(checkdir+"/CVS/Entries")
			if mymode=="commit" and isSvn:
				stats["svn.IO_error"] += 1
				fails["svn.IO_error"].append(checkdir+"svn info")
			continue

	if isCvs and has_filesdir:
		try:
			if isCvs:
				myf=open(checkdir+"/files/CVS/Entries","r")
			if isSvn:
				myf=os.popen("svn list "+os.path.normpath(checkdir+"/files"))
			myl=myf.readlines()
			myf.close()
			for l in myl:
				if isCvs:
					if l[0]!="/":
						continue
					splitl=l[1:].split("/")
					if not len(splitl):
						continue
					if splitl[0][:7]=="digest-":
						dadded.append(splitl[0][7:])
				if isSvn:
					l = l.rstrip();
					if l[-1:] == "/":
						continue
					if l[:7] == "digest-":
						dadded.append(l[7:])
			if isSvn:
				myf=os.popen("svn status "+os.path.normpath(checkdir+"/files"))
				myl=myf.readlines()
				myf.close()
				for l in myl:
					if l[0] == "A":
						l = l.rstrip().split(' ')[-1]
						if l[:7] == "digest-":
							dadded.append(l[7:])
		except IOError:
			if mymode=="commit" and isCvs:
				stats["CVS/Entries.IO_error"] += 1
				fails["CVS/Entries.IO_error"].append(checkdir+"/files/CVS/Entries")
			if mymode=="commit" and isSvn:
				stats["svn.IO_error"] += 1
				fails["svn.IO_error"].append(checkdir+"/files svn info")
			continue

	if mymode in ("fix", "commit") and \
		"--pretend" not in myoptions:
		repoman_settings["O"] = checkdir
		if not portage.digestgen([], repoman_settings, myportdb=portdb):
			print "Unable to generate manifest."
			sys.exit(1)

	mf = Manifest(checkdir, repoman_settings["DISTDIR"])
	mydigests=mf.getTypeDigests("DIST")

	fetchlist_dict = portage.FetchlistDict(checkdir, repoman_settings, portdb)
	myfiles_all = []
	for mykey in fetchlist_dict:
		try:
			myfiles_all.extend(fetchlist_dict[mykey])
		except portage.exception.InvalidDependString, e:
			stats["SRC_URI.syntax"] = stats["SRC_URI.syntax"] + 1
			fails["SRC_URI.syntax"].append(mykey+".ebuild SRC_URI: "+str(e))
	del fetchlist_dict
	myfiles_all = set(myfiles_all)
	for entry in mydigests:
		if entry not in myfiles_all:
			stats["digestentry.unused"] += 1
			fails["digestentry.unused"].append(checkdir+"::"+entry)
	del myfiles_all

	if os.path.exists(checkdir+"/files"):
		filesdirlist=os.listdir(checkdir+"/files")
		if manifest1_compat:
			for y in filesdirlist:
				if not y.startswith("digest-"):
					continue
				if y[7:] not in dadded:
					#digest not added to cvs or svn
					stats["digest.notadded"]=stats["digest.notadded"]+1
					fails["digest.notadded"].append(x+"/files/"+y)
					if y[7:] in eadded:
						stats["digest.disjointed"]=stats["digest.disjointed"]+1
						fails["digest.disjointed"].append(x+"/files/"+y)
						
				if os.stat(checkdir+"/files/"+y)[0] & 0x0248:
					stats["file.executable"] += 1
					fails["file.executable"].append(x+"/files/"+y)
				
				mykey = catdir + "/" + y[7:]
				if y[7:] not in ebuildlist:
					#stray digest
					if mymode=="fix":
						if isCvs:
							vcsrm="cvs rm -f"
						if isSvn:
							vcsrm="svn rm --force"
						if "--pretend" in myoptions:
								print "(cd "+repodir+"/"+x+"/files; "+vcsrm+" "+y+")"
						else:
							os.system("(cd "+repodir+"/"+x+"/files; "+vcsrm+" "+y+")")
					else:
						stats["digest.stray"]=stats["digest.stray"]+1
						fails["digest.stray"].append(x+"/files/"+y)
				else:
					# We have an ebuild
					try:
						myuris, myfiles = portdb.getfetchlist(mykey, all=True)
					except portage.exception.InvalidDependString, e:
						# Already handled above.
						continue

					uri_dict = {}
					for myu in myuris:
						myubn = os.path.basename(myu)
						if myubn not in uri_dict:
							uri_dict[myubn]  = [myu]
						else:
							uri_dict[myubn] += [myu]

					for myf in uri_dict:
						myff = repoman_settings["DISTDIR"] + "/" + myf
						if not mydigests.has_key(myf):
							uri_settings = portage.config(clone=repoman_settings)
							if mymode == "fix":
								if not portage.fetch(uri_dict[myf], uri_settings):
									stats["digest.unmatch"] += 1
									fails["digest.unmatch"].append(y+"::"+myf)
								else:
									eb_name = portdb.findname2(mykey)[0]
									portage.doebuild(eb_name, "digest", "/",
										uri_settings, tree="porttree",
										mydbapi=portdb)
							else:
								stats["digest.partial"] += 1
								fails["digest.partial"].append(y+"::"+myf)
						elif "assume-digests" not in repoman_settings.features:
							if os.path.exists(myff):
								if not portage.checksum.verify_all(myff, mydigests[myf]):
									stats["digest.fail"] += 1
									fails["digest.fail"].append(y+"::"+myf)
							elif repolevel == 3:
								stats["digest.assumed"] += 1
								fails["digest.assumed"].append(y+"::"+myf)

		# recurse through files directory
		# use filesdirlist as a stack, appending directories as needed so people can't hide > 20k files in a subdirectory.
		while filesdirlist:
			y = filesdirlist.pop(0)
			try:
				mystat = os.stat(checkdir+"/files/"+y)
			except OSError, oe:
				if oe.errno == 2:
					# don't worry about it.  it likely was removed via fix above.
					continue
				else:
					raise oe
			if S_ISDIR(mystat.st_mode):
				if y == "CVS" or y == ".svn":
					continue
				for z in os.listdir(checkdir+"/files/"+y):
					if z == "CVS" or z == ".svn":
						continue
					filesdirlist.append(y+"/"+z)
			# current policy is no files over 20k, this is the check.
			elif mystat.st_size > 20480:
				stats["file.size"] += 1
				fails["file.size"].append("("+ str(mystat.st_size/1024) + "K) "+x+"/files/"+y)

			for c in os.path.basename(y.rstrip(os.path.sep)):
				if c not in allowed_filename_chars_set:
					stats["file.name"] += 1
					fails["file.name"].append("%s/files/%s: char '%s'" % (checkdir, y, c))
					break

	del mydigests

	if "ChangeLog" not in checkdirlist:
		stats["changelog.missing"]+=1
		fails["changelog.missing"].append(x+"/ChangeLog")
	
	#metadata.xml file check
	if "metadata.xml" not in checkdirlist:
		stats["metadata.missing"]+=1
		fails["metadata.missing"].append(x+"/metadata.xml")
	#metadata.xml parse check
	else:
		#Only carry out if in package directory or check forced
		if xmllint_capable:
			# xmlint can produce garbage output even on success, so only dump
			# the ouput when it fails.
			st, out = getstatusoutput(
				"xmllint --nonet --noout --dtdvalid '%s' '%s'" % \
				 (metadata_dtd, os.path.join(checkdir, "metadata.xml")))
			if st != os.EX_OK:
				print red("!!!") + " metadata.xml is invalid:"
				for z in out.splitlines():
					print red("!!! ")+z
				stats["metadata.bad"]+=1
				fails["metadata.bad"].append(x+"/metadata.xml")

	allmasked = True

	for y in ebuildlist:
		if os.stat(checkdir+"/"+y+".ebuild")[0] & 0x0248:
			stats["file.executable"] += 1
			fails["file.executable"].append(x+"/"+y+".ebuild")
		if y not in eadded:
			#ebuild not added to cvs
			stats["ebuild.notadded"]=stats["ebuild.notadded"]+1
			fails["ebuild.notadded"].append(x+"/"+y+".ebuild")
			if y in dadded:
				stats["ebuild.disjointed"]=stats["ebuild.disjointed"]+1
				fails["ebuild.disjointed"].append(x+"/"+y+".ebuild")
		if manifest1_compat and \
			not os.path.exists(os.path.join(checkdir, "files", "digest-"+y)):
			if mymode=="fix":
				if "--pretend" in myoptions:
					print "You will need to run:"
					print "  "+portage.const.PORTAGE_BASE+"/bin/ebuild "+repodir+"/"+x+"/"+y+".ebuild digest"
				else:
					retval=os.system(portage.const.PORTAGE_BASE+"/bin/ebuild "+repodir+"/"+x+"/"+y+".ebuild digest")
					if retval:
						print "!!! Exiting on ebuild digest (shell) error code:",retval
						sys.exit(retval)
			else:
				stats["digest.missing"]=stats["digest.missing"]+1
				fails["digest.missing"].append(x+"/files/digest-"+y)
		myesplit=portage.pkgsplit(y)
		if myesplit is None or myesplit[0] != x.split("/")[-1]:
			stats["ebuild.invalidname"]=stats["ebuild.invalidname"]+1
			fails["ebuild.invalidname"].append(x+"/"+y+".ebuild")
			continue
		elif myesplit[0]!=pkgdir:
			print pkgdir,myesplit[0]
			stats["ebuild.namenomatch"]=stats["ebuild.namenomatch"]+1
			fails["ebuild.namenomatch"].append(x+"/"+y+".ebuild")
			continue
		try:
			myaux = dict(
				zip(allvars, portdb.aux_get(os.path.join(catdir, y), allvars)))
		except KeyError:
			stats["ebuild.syntax"]=stats["ebuild.syntax"]+1
			fails["ebuild.syntax"].append(x+"/"+y+".ebuild")
			continue
		except IOError:
			stats["ebuild.output"]=stats["ebuild.output"]+1
			fails["ebuild.output"].append(x+"/"+y+".ebuild")
			continue

		# Test for negative logic and bad words in the RESTRICT var.
		#for x in myaux[allvars.index("RESTRICT")].split():
		#	if x.startswith("no"):
		#		print "Bad RESTRICT value: %s" % x
		try:
			myaux["PROVIDE"] = portage.dep.use_reduce(
				portage.dep.paren_reduce(myaux["PROVIDE"]), matchall=1)
		except portage.exception.InvalidDependString, e:
			stats["PROVIDE.syntax"] = stats["PROVIDE.syntax"] + 1
			fails["PROVIDE.syntax"].append(mykey+".ebuild PROVIDE: "+str(e))
			del e
			continue
		myaux["PROVIDE"] = " ".join(portage.flatten(myaux["PROVIDE"]))
		for myprovide in myaux["PROVIDE"].split():
			prov_cp = portage.dep_getkey(myprovide)
			if prov_cp != myprovide:
				stats["virtual.versioned"]+=1
				fails["virtual.versioned"].append(x+"/"+y+".ebuild: "+myprovide)
			prov_pkg = portage.dep_getkey(
				portage.best(portdb.xmatch("match-all", prov_cp)))
			if prov_cp == prov_pkg:
				stats["virtual.exists"]+=1
				fails["virtual.exists"].append(x+"/"+y+".ebuild: "+prov_cp)

		for pos in range(0,len(missingvars)):
			if not myaux[missingvars[pos]]:
				myqakey=missingvars[pos]+".missing"
				stats[myqakey]=stats[myqakey]+1
				fails[myqakey].append(x+"/"+y+".ebuild")

		# KEYWORDS="-*" is a stupid replacement for package.mask and screws general KEYWORDS semantics
		if "-*" in myaux["KEYWORDS"].split():
			haskeyword = False
			for kw in myaux["KEYWORDS"].split():
				if kw[0] == "~":
					kw = kw[1:]
				if kw in kwlist:
					haskeyword = True
			if not haskeyword:
				stats["KEYWORDS.stupid"] += 1
				fails["KEYWORDS.stupid"].append(x+"/"+y+".ebuild")

		"""
		Ebuilds that inherit a "Live" eclasss (darcs,subversion,git,cvs,etc..) should
		not be allowed to be marked stable
		"""
		if set(["darcs","cvs","subversion","git"]).intersection(
			myaux["INHERITED"].split()):
			bad_stable_keywords = []
			for keyword in myaux["KEYWORDS"].split():
				if not keyword.startswith("~") and \
					not keyword.startswith("-"):
					bad_stable_keywords.append(keyword)
				del keyword
			if bad_stable_keywords:
				stats["LIVEVCS.stable"] += 1
				fails["LIVEVCS.stable"].append(
					x + "/" + y + ".ebuild with stable keywords:%s " % \
						bad_stable_keywords)
			del bad_stable_keywords

		if "--ignore-arches" in myoptions:
			arches = [[repoman_settings["ARCH"], repoman_settings["ARCH"],
				repoman_settings["ACCEPT_KEYWORDS"].split()]]
		else:
			arches=[]
			for keyword in myaux["KEYWORDS"].split():
				if (keyword[0]=="-"):
					continue
				elif (keyword[0]=="~"):
					arches.append([keyword, keyword[1:], [keyword[1:], keyword]])
				else:
					arches.append([keyword, keyword, [keyword]])
					allmasked = False

		baddepsyntax = False
		badlicsyntax = False
		badprovsyntax = False
		catpkg = catdir+"/"+y
		myiuse = set(repoman_settings.archlist())
		for myflag in myaux["IUSE"].split():
			if myflag.startswith("+"):
				myflag = myflag[1:]
			myiuse.add(myflag)

		operator_tokens = set(["||", "(", ")"])
		type_list, badsyntax = [], []
		for mytype in ("DEPEND", "RDEPEND", "PDEPEND", "LICENSE", "PROVIDE"):
			mydepstr = myaux[mytype]
			
			if mydepstr.find(" ?") != -1:
				badsyntax.append("'?' preceded by space")

			try:
				# Missing closing parenthesis will result in a ValueError
				mydeplist = portage.dep.paren_reduce(mydepstr)
				# Missing opening parenthesis will result in a final "" element
				if "" in mydeplist or "(" in mydeplist:
					raise ValueError
			except ValueError:
				badsyntax.append("parenthesis mismatch")
				mydeplist = []
			except portage.exception.InvalidDependString, e:
				badsyntax.append(str(e))
				del e
				mydeplist = []

			try:
				portage.dep.use_reduce(mydeplist, excludeall=myiuse)
			except portage.exception.InvalidDependString, e:
				badsyntax.append(str(e))

			for token in operator_tokens:
				if mydepstr.startswith(token+" "):
					myteststr = mydepstr[len(token):]
				else:
					myteststr = mydepstr
				if myteststr.endswith(" "+token):
					myteststr = myteststr[:-len(token)]
				while myteststr.find(" "+token+" ") != -1:
					myteststr = " ".join(myteststr.split(" "+token+" ", 1))
				if myteststr.find(token) != -1:
					badsyntax.append("'%s' not separated by space" % (token))


			if mytype in ("DEPEND", "RDEPEND", "PDEPEND"):
				for token in mydepstr.split():
					if token in operator_tokens or \
						token.endswith("?"):
						continue
					if not portage.isvalidatom(token, allow_blockers=True) or \
						":" in token and myaux["EAPI"] == "0":
						badsyntax.append("'%s' not a valid atom" % token)

			type_list.extend([mytype] * (len(badsyntax) - len(type_list)))

		for m,b in zip(type_list, badsyntax):
			stats[m+".syntax"] += 1
			fails[m+".syntax"].append(catpkg+".ebuild "+m+": "+b)

		badlicsyntax = len(filter(lambda x:x=="LICENSE", type_list))
		badprovsyntax = len(filter(lambda x:x=="PROVIDE", type_list))
		baddepsyntax = len(type_list) != badlicsyntax + badprovsyntax 
		badlicsyntax = badlicsyntax > 0
		badprovsyntax = badprovsyntax > 0

		if not baddepsyntax:
			if x11_deprecation_check(" ".join([myaux["DEPEND"], myaux["RDEPEND"], myaux["PDEPEND"]])):
				stats["usage.obsolete"] += 1
				fails["usage.obsolete"].append("%s/%s.ebuild: not migrated to modular X" % (x, y))

		for keyword,arch,groups in arches:

			if not profiles.has_key(arch):
				# A missing profile will create an error further down
				# during the KEYWORDS verification.
				continue
				
			for prof in profiles[arch]:

				profdir = portdir+"/profiles/"+prof[0]
	
				if prof[0] in arch_caches:
					dep_settings = arch_caches[prof[0]]
				else:
					dep_settings = portage.config(
						config_profile_path=profdir,
						config_incrementals=portage.const.INCREMENTALS,
						local_config=False)
					arch_caches[prof[0]] = dep_settings
					while True:
						try:
							# Protect ACCEPT_KEYWORDS from config.regenerate()
							# (just in case)
							dep_settings.incrementals.remove("ACCEPT_KEYWORDS")
						except ValueError:
							break

				xmatch_cache_key = (prof[0], tuple(groups))
				xcache = arch_xmatch_caches.get(xmatch_cache_key)
				if xcache is None:
					portdb.melt()
					portdb.freeze()
					xcache = portdb.xcache
					arch_xmatch_caches[xmatch_cache_key] = xcache

				trees["/"]["porttree"].settings = dep_settings
				portdb.mysettings = dep_settings
				portdb.xcache = xcache
				# for package.use.mask support inside dep_check
				dep_settings.setcpv("/".join((catdir, y)))
				dep_settings["ACCEPT_KEYWORDS"] = " ".join(groups)
				# just in case, prevent config.reset() from nuking these.
				dep_settings.backup_changes("ACCEPT_KEYWORDS")

				for myprovide in myaux["PROVIDE"].split():
					prov_cp = portage.dep_getkey(myprovide)
					if prov_cp not in dep_settings.getvirtuals():
						stats["virtual.unavailable"]+=1
						fails["virtual.unavailable"].append(x+"/"+y+".ebuild: "+keyword+"("+prof[0]+") "+prov_cp)

				if not baddepsyntax:
					ismasked = os.path.join(catdir, y) not in \
						portdb.xmatch("list-visible", x)
					if ismasked:
						if "--ignore-masked" in myoptions:
							continue
						#we are testing deps for a masked package; give it some lee-way
						suffix="masked"
						matchmode="match-all"
					else:
						suffix=""
						matchmode="match-visible"
	
					if prof[1] == "dev":
						suffix=suffix+"indev"

					for mytype,mypos in [["DEPEND",len(missingvars)],["RDEPEND",len(missingvars)+1],["PDEPEND",len(missingvars)+2]]:
						
						mykey=mytype+".bad"+suffix
						myvalue = myaux[mytype]
						if not myvalue:
							continue
						try:
							mydep = portage.dep_check(myvalue, portdb,
								dep_settings, use="all", mode=matchmode,
								trees=trees)
						except KeyError, e:
							stats[mykey]=stats[mykey]+1
							fails[mykey].append(x+"/"+y+".ebuild: "+keyword+"("+prof[0]+") "+repr(e[0]))
							continue
	
						if mydep[0]==1:
							if mydep[1]!=[]:
								#we have some unsolvable deps
								#remove ! deps, which always show up as unsatisfiable
								d=0
								while d<len(mydep[1]):
									if mydep[1][d][0]=="!":
										del mydep[1][d]
									else:
										d += 1
								#if we emptied out our list, continue:
								if not mydep[1]:
									continue
								stats[mykey]=stats[mykey]+1
								fails[mykey].append(x+"/"+y+".ebuild: "+keyword+"("+prof[0]+") "+repr(mydep[1]))
						else:
							stats[mykey]=stats[mykey]+1
							fails[mykey].append(x+"/"+y+".ebuild: "+keyword+"("+prof[0]+") "+repr(mydep[1]))

		# this check needs work, it won't catch (\ndie)
		if not os.system("grep -E '^[^#]*\([^)]*\<die\>' "+checkdir+"/"+y+".ebuild >/dev/null 2>&1"):
			stats["ebuild.nesteddie"]=stats["ebuild.nesteddie"]+1
			fails["ebuild.nesteddie"].append(x+"/"+y+".ebuild")
		# uselist checks - global
		myuse = []
		default_use = []
		for myflag in myaux["IUSE"].split():
			flag_name = myflag.lstrip("+-")
			if myflag != flag_name:
				default_use.append(myflag)
			if flag_name not in uselist:
				myuse.append(flag_name)

		# uselist checks - local
		mykey = portage.dep_getkey(catpkg)
		if luselist.has_key(mykey):
			for mypos in range(len(myuse)-1,-1,-1):
				if myuse[mypos] and (myuse[mypos] in luselist[mykey]):
					del myuse[mypos]
		if default_use and myaux["EAPI"] == "0":
			myuse += default_use
		for mypos in range(len(myuse)):
			stats["IUSE.invalid"]=stats["IUSE.invalid"]+1
			fails["IUSE.invalid"].append(x+"/"+y+".ebuild: %s" % myuse[mypos])	

		# license checks
		if not badlicsyntax:
			myuse = myaux["LICENSE"]
			# Parse the LICENSE variable, remove USE conditions and
			# flatten it.
			myuse=portage.dep.use_reduce(portage.dep.paren_reduce(myuse), matchall=1)
			myuse=portage.flatten(myuse)
			# Check each entry to ensure that it exists in PORTDIR's
			# license directory.
			for mypos in range(0,len(myuse)):
				# Need to check for "||" manually as no portage
				# function will remove it without removing values.
				if myuse[mypos] not in liclist and myuse[mypos] != "||":
					stats["LICENSE.invalid"]=stats["LICENSE.invalid"]+1
					fails["LICENSE.invalid"].append(x+"/"+y+".ebuild: %s" % myuse[mypos])

		#keyword checks
		myuse = myaux["KEYWORDS"].split()
		for mykey in myuse:
			myskey=mykey[:]
			if myskey[0]=="-":
				myskey=myskey[1:]
			if myskey[0]=="~":
				myskey=myskey[1:]
			if mykey!="-*":
				if myskey not in kwlist:
					stats["KEYWORDS.invalid"] += 1
					fails["KEYWORDS.invalid"].append(x+"/"+y+".ebuild: %s" % mykey)
				elif not profiles.has_key(myskey):
					stats["KEYWORDS.invalid"] += 1
					fails["KEYWORDS.invalid"].append(x+"/"+y+".ebuild: %s (profile invalid)" % mykey)

		#restrict checks
		myrestrict = None
		try:
			myrestrict = portage.dep.use_reduce(
				portage.dep.paren_reduce(myaux["RESTRICT"]), matchall=1)
		except portage.exception.InvalidDependString, e:
			stats["RESTRICT.syntax"] = stats["RESTRICT.syntax"] + 1
			fails["RESTRICT.syntax"].append(mykey+".ebuild RESTRICT: "+str(e))
			del e
		if myrestrict:
			myrestrict = set(portage.flatten(myrestrict))
			mybadrestrict = myrestrict.difference(valid_restrict)
			if mybadrestrict:
				stats["RESTRICT.invalid"] += len(mybadrestrict)
				for mybad in mybadrestrict:
					fails["RESTRICT.invalid"].append(x+"/"+y+".ebuild: %s" % mybad)

		#syntax checks
		myear = time.gmtime(os.stat(checkdir+"/"+y+".ebuild")[ST_MTIME])[0]
		gentoo_copyright = re.compile(r'^# Copyright ((1999|200\d)-)?' + str(myear) + r' Gentoo Foundation')
		gentoo_license = re.compile(r'^# Distributed under the terms of the GNU General Public License v2$')
		cvs_header = re.compile(r'^#\s*\$Header.*\$$')
		ignore_line = re.compile(r'(^$)|(^(\t)*#)')
		leading_spaces = re.compile(r'^[\S\t]')
		trailing_whitespace = re.compile(r'.*([\S]$)')
		readonly_assignment = re.compile(r'^\s*(export\s+)?(A|CATEGORY|P|PV|PN|PR|PVR|PF|D|WORKDIR|FILESDIR|FEATURES|USE)=')
		line_continuation = re.compile(r'([^#]*\S)(\s+|\t)\\$')
		linenum=0
		previous_line = None
		for line in input(checkdir+"/"+y+".ebuild"):
			linenum += 1
			# Gentoo copyright check
			if linenum == 1:
				match = gentoo_copyright.match(line)
				if not match:
					myerrormsg = "Copyright header Error. Possibly date related."
					stats["ebuild.badheader"] +=1
					fails["ebuild.badheader"].append(x+"/"+y+".ebuild: %s" % myerrormsg)
			# Gentoo license check
			elif linenum == 2:
				match = gentoo_license.match(line)
				if not match:
					myerrormsg = "Gentoo License Error."
					stats["ebuild.badheader"] +=1
					fails["ebuild.badheader"].append(x+"/"+y+".ebuild: %s" % myerrormsg)
			# CVS Header check
			elif linenum == 3:
				match = cvs_header.match(line)
				if not match:
					myerrormsg = "CVS Header Error."
					stats["ebuild.badheader"] +=1
					fails["ebuild.badheader"].append(x+"/"+y+".ebuild: %s" % myerrormsg)
			else:
				match = ignore_line.match(line)
				if not match:
					# Excluded Blank lines and full line comments. Good!
					# Leading Spaces Check
					match = leading_spaces.match(line)
					if not match:
						#Line has got leading spaces. Bad!
						myerrormsg = "Leading Space Syntax Error. Line %d" % linenum
						stats["ebuild.minorsyn"] +=1
						fails["ebuild.minorsyn"].append(x+"/"+y+".ebuild: %s" % myerrormsg)
					# Trailing whitespace check
					match = trailing_whitespace.match(line)
					if not match:
						#Line has got trailing whitespace. Bad!
						myerrormsg = "Trailing whitespace Syntax Error. Line %d" % linenum
						stats["ebuild.minorsyn"] +=1
						fails["ebuild.minorsyn"].append(x+"/"+y+".ebuild: %s" % myerrormsg)
					# Readonly variable assignment check
					match = readonly_assignment.match(line)
					# The regex can give a false positive for continued lines,
					# so we check the previous line to see if it was continued.
					if match and (not previous_line or not line_continuation.match(previous_line)):
						# invalid assignment, very bad!
						myerrormsg = "Readonly variable assignment to %s on line %d" % (match.group(2), linenum)
						stats["variable.readonly"] += 1
						fails["variable.readonly"].append(x+"/"+y+".ebuild: %s" % myerrormsg)
			previous_line = line
		del previous_line

	# Check for 'all unstable' or 'all masked' -- ACCEPT_KEYWORDS is stripped
	# XXX -- Needs to be implemented in dep code. Can't determine ~arch nicely.
	#if not portage.portdb.xmatch("bestmatch-visible",x):
	#    stats["ebuild.nostable"]+=1
	#    fails["ebuild.nostable"].append(x)
	if allmasked and repolevel == 3:
		stats["ebuild.allmasked"]+=1
		fails["ebuild.allmasked"].append(x)

if mymode == "manifest":
	sys.exit(dofail)

#Pickle and save results for instant reuse in last and lfull
if os.access(portage.const.CACHE_PATH, os.W_OK):
	for myobj, fname in (stats, "repo.stats"), (fails, "repo.fails"):
		fpath = os.path.join(portage.const.CACHE_PATH, fname)
		savef = open(fpath, 'w')
		pickle.dump(myobj, savef)
		savef.close()
		portage.apply_secpass_permissions(fpath, gid=portage.portage_gid,
			mode=0664)
if quiet < 2:
	print
#dofail will be set to 1 if we have failed in at least one non-warning category
dofail=0
#dowarn will be set to 1 if we tripped any warnings
dowarn=0
#dofull will be set if we should print a "repoman full" informational message
dofull=0
for x in qacats:
	if not isCvs and not isSvn and (x.find("notadded") != -1):
		stats[x] = 0
	if stats[x]:
		dowarn=1
		if x not in qawarnings:
			dofail=1
	else:
		continue
	print "  "+x.ljust(30),
	if stats[x]==0:
		print green(`stats[x]`)
		continue
	elif x in qawarnings:
		print yellow(`stats[x]`)
	else:
		print red(`stats[x]`)
	if mymode!="full":
		if stats[x]<12:
			for y in fails[x]:
				print "   "+y
		else:
			dofull=1
	else:
		for y in fails[x]:
			print "   "+y

def grouplist(mylist,seperator="/"):
	"""(list,seperator="/") -- Takes a list of elements; groups them into
	same initial element categories. Returns a dict of {base:[sublist]}
	From: ["blah/foo","spork/spatula","blah/weee/splat"]
	To:   {"blah":["foo","weee/splat"], "spork":["spatula"]}"""
	mygroups={}
	for x in mylist:
		xs=x.split(seperator)
		if xs[0]==".":
			xs=xs[1:]
		if xs[0] not in mygroups:
			mygroups[xs[0]]=[seperator.join(xs[1:])]
		else:
			mygroups[xs[0]]+=[seperator.join(xs[1:])]
	return mygroups

if mymode!="commit":
	if dofull:
		print bold("Note: type \"repoman full\" for a complete listing.")
		if quiet < 1:
			print
	if dowarn and not dofail:
		if quiet < 2:
			print green("RepoMan sez:"),"\"You're only giving me a partial QA payment?\n              I'll take it this time, but I'm not happy.\""
		else:
			print green("RepoMan sez:"),"\"OK for now, but I'll be back ...\""
	elif not dofail:
		print green("RepoMan sez:"),"\"If everyone were like you, I'd be out of business!\""
	elif dofail:
		print turquoise("Please fix these important QA issues first.")
		print green("RepoMan sez:"),"\"Make your QA payment on time and you'll never see the likes of me.\"\n"
		sys.exit(1)
	if quiet < 1:
		print
elif "--pretend" not in myoptions:
	if dofail:
		print turquoise("Please fix these important QA issues first.")
		print green("RepoMan sez:"),"\"Make your QA payment on time and you'll never see the likes of me.\"\n"
		sys.exit(1)

	if "--pretend" in myoptions:
		print green("RepoMan sez:"), "\"So, you want to play it safe. Good call.\"\n"

	if fails["digest.missing"]:
		print green("Creating missing digests...")
	for x in fails["digest.missing"]:
		xs=x.split("/")
		del xs[-2]
		myeb="/".join(xs[:-1])+"/"+xs[-1][7:]
		if "--pretend" in myoptions:
			print "(ebuild "+portdir+"/"+myeb+".ebuild digest)"
		else:
			retval=os.system("ebuild "+portdir+"/"+myeb+".ebuild digest")
			if retval:
				print "!!! Exiting on ebuild digest (shell) error code:",retval
				sys.exit(retval)

	if isCvs:
		try:
			myvcstree=portage.cvstree.getentries("./",recursive=1)
			myunadded=portage.cvstree.findunadded(myvcstree,recursive=1,basedir="./")
		except SystemExit, e:
			raise  # TODO propogate this
		except:
			err("Error retrieving CVS tree; exiting.")

	if isSvn:
		try:
			svnstatus=os.popen("svn status").readlines()
			myunadded = [ "./"+elem.rstrip().split()[1] for elem in svnstatus if elem.startswith("?") ]	
		except SystemExit, e:
			raise  # TODO propogate this
		except:
			err("Error retrieving SVN info; exiting.")
	myautoadd=[]
	if myunadded:
		for x in range(len(myunadded)-1,-1,-1):
			xs=myunadded[x].split("/")
			if xs[-1]=="files":
				print "!!! files dir is not added! Please correct this."
				sys.exit(-1)
			elif xs[-1]=="Manifest":
				# It's a manifest... auto add
				myautoadd+=[myunadded[x]]
				del myunadded[x]
			elif len(xs[-1])>=7:
				if xs[-1][:7]=="digest-":
					del xs[-2]
					myeb="/".join(xs[:-1]+[xs[-1][7:]])+".ebuild"
					if os.path.exists(myeb):
						# Ebuild exists for digest... So autoadd it.
						myautoadd+=[myunadded[x]]
						del myunadded[x]
		
	if myautoadd:
		print ">>> Auto-Adding missing digests..."
		if "--pretend" in myoptions:
			if isCvs:
				print "(cvs add "+" ".join(myautoadd)+")"
			if isSvn:
				print "(svn add "+" ".join(myautoadd)+")"
			retval=0
		else:
			if isCvs:
				retval=os.system("cvs add "+" ".join(myautoadd))
			if isSvn:
				retval=os.system("svn add "+" ".join(myautoadd))
		if retval:
			print "!!! Exiting on vcs (shell) error code:",retval
			sys.exit(retval)

	if myunadded:
		print red("!!! The following files are in your local tree but are not added to the master")
		print red("!!! tree. Please remove them from the local tree or add them to the master tree.")
		for x in myunadded:
			print "   ",x
		print
		print
		sys.exit(1)

	retval=["",""]
	if isCvs:
		print "Performing a "+green("cvs -n up")+" with a little magic grep to check for updates."
		retval=getstatusoutput("cvs -n up 2>&1 | egrep '^[^\?] .*' | egrep -v '^. .*/digest-[^/]+|^cvs server: .* -- ignored$'")
	if isSvn:
		print "Performing a "+green("svn status -u")+" with a little magic grep to check for updates."
		retval=getstatusoutput("svn status -u 2>&1 | egrep -v '^.  +.*/digest-[^/]+' | head -n-1")

	mylines=retval[1].split("\n")
	myupdates=[]
	for x in mylines:
		if not x:
			continue
		if x[0] not in "UPMARD": # Updates,Patches,Modified,Added,Removed/Replaced(svn),Deleted(svn)
			print red("!!! Please fix the following issues reported from cvs: ")+green("(U,P,M,A,R,D are ok)")
			if isCvs:
				print red("!!! Note: This is a pretend/no-modify pass...")
			if isSvn:
				print red("!!! Note: This your local checkout has been modified!")
			print retval[1]
			print
			sys.exit(1)
		elif isCvs and x[0] in ["U","P"]:
			myupdates+=[x[2:]]
		elif isSvn and x[8] == '*':
			myupdates+=[x[9:].lstrip(" 1234567890")]
	
	if myupdates:
		print green("Fetching trivial updates...")
		if "--pretend" in myoptions:
			print "(cvs/svn up "+" ".join(myupdates)+")"
			retval=0
		else:
			if isCvs:
				retval=os.system("cvs up "+" ".join(myupdates))
			elif isSvn:
				retval=os.system("svn update "+" ".join(myupdates))
		if retval!=0:
			print "!!! cvs/svn exited with an error. Terminating."
			sys.exit(retval)
	
	if isCvs:
		mycvstree=portage.cvstree.getentries("./",recursive=1)
		mychanged=portage.cvstree.findchanged(mycvstree,recursive=1,basedir="./")
		mynew=portage.cvstree.findnew(mycvstree,recursive=1,basedir="./")
		myremoved=portage.cvstree.findremoved(mycvstree,recursive=1,basedir="./")
	if isSvn:
		svnstatus = os.popen("svn status").readlines()
		mychanged = [ elem.rstrip()[7:] for elem in svnstatus if elem.startswith("M") ]
		for manifest in [ file for file in mychanged if '/Manifest' in file ]:
			mychanged.remove(manifest)
		mynew = [ elem.rstrip()[7:] for elem in svnstatus if elem.startswith("A") ]
		myremoved = [ elem.rstrip()[7:] for elem in svnstatus if elem.startswith("D") ]

	if isCvs or isSvn:
		if not (mychanged or mynew or myremoved):
			print
			print green("RepoMan sez:"), "\"Doing nothing is not always good for QA.\"\n"
			print
			print "(Didn't find any changed files...)"
			print
			sys.exit(0)

	# Manifests need to be regenerated after all other commits, so don't commit
	# them now even if they have changed.
	# However, in SVN mode, the manifest won't change, hence, if we
	# don't sign, we can commit it right away, avoiding an extra commit
	if not isSvn or "sign" in repoman_settings.features:
		mymanifests = [f for f in mychanged if "Manifest" == os.path.basename(f)]
		mychanged = [f for f in mychanged if "Manifest" != os.path.basename(f)]
	else:
		mymanifests = [] # avoid undefined error
	myupdates=mychanged+mynew
	myheaders=[]
	mydirty=[]
	headerstring="'\$(Header|Id)"
	headerstring+=".*\$'"
	for myfile in myupdates:
		myout=getstatusoutput("egrep -q "+headerstring+" "+myfile)
		if myout[0]==0:
			myheaders.append(myfile)

	print "*",green(str(len(myupdates))),"files being committed...",green(str(len(myheaders))),"have headers that will change."
	print "*","Files with headers will cause the manifests to be made and recommited."
	if quiet == 0:
		print "myupdates:",myupdates
		print "myheaders:",myheaders
		print

	if commitmessagefile:
		try:
			f = open(commitmessagefile)
			commitmessage = f.read()
			f.close()
			del f
		except (IOError, OSError), e:
			if e.errno == errno.ENOENT:
				portage.writemsg("!!! File Not Found: --commitmsgfile='%s'\n" % commitmessagefile)
			else:
				raise
		# We've read the content so the file is no longer needed.
		commitmessagefile = None
	
	if not (commitmessage or commitmessagefile):
		print "Please enter a commit message at the prompt:"
		while not commitmessage:
			try:
				commitmessage=raw_input(green("> "))
			except KeyboardInterrupt: 
				exithandler()
	try:
		unameout=getstatusoutput("uname -srp")[1]
		commitmessage+="\n(Portage "+str(portage.VERSION)+"/"
		if isCvs:
			commitmessage+="CVS"
		elif isSvn:
			commitmessage+="SVN"
		commitmessage+="/"+unameout+")"
	except AttributeError:
		print "Failed to insert portage version in message!"
		commitmessage+="\n(Portage version: Unknown)"

	if not manifest1_compat:
		myfiles = myupdates + myremoved + mymanifests
		filesdirs = set()
		if repolevel == 3:
			filesdirs.add(os.path.join(".", "files"))
		elif repolevel in (1, 2):
			for x in myfiles:
				xs = x.split(os.path.sep)
				if len(xs) < 4-repolevel:
					continue
				xs = xs[0:4-repolevel]
				xs.append("files")
				filesdirs.add(os.path.join(*xs))
		else:
			raise AssertionError("repolevel=%s" % str(repolevel))
		digest_files = []
		for x in filesdirs:
			dir_path = os.path.join(startdir, x)
			if not os.path.isdir(dir_path):
				continue
			for y in os.listdir(dir_path):
				if y.startswith("digest-"):
					digest_files.append(os.path.join(x, y))
		if digest_files:
			digest_files.sort()
			if "--pretend" in myoptions:
				if isCvs:
					print "(rm %s)" % " ".join(digest_files)
					print "(cvs remove %s)" % " ".join(digest_files)
				elif isSvn:
					print "(svn remove %s)" % " ".join(digest_files)
			else:
				if isCvs:
					for x in digest_files:
						os.unlink(os.path.join(startdir, x))
					retval = spawn(["cvs", "remove"] + digest_files,
							env=os.environ)
				elif isSvn:
					retval = spawn(["svn", "remove"] + digest_files,
							env=os.environ)
				if retval != os.EX_OK:
					print "!!! Exiting on vcs (shell) error code:",retval
					sys.exit(retval)
			myremoved.extend(digest_files)
			myremoved = list(set(myremoved))
			myremoved.sort()

	if myupdates or myremoved:
		myfiles = myupdates + myremoved
		fd, commitmessagefile = tempfile.mkstemp(".repoman.msg")
		mymsg = os.fdopen(fd, "w")
		mymsg.write(commitmessage)
		mymsg.close()

		print
		print green("Using commit message:")
		print green("------------------------------------------------------------------------------")
		print commitmessage
		print green("------------------------------------------------------------------------------")
		print

		retval = None
		if "--pretend" in myoptions:
			if isCvs:
				print "(cvs -q commit -F %s %s)" % \
					(commitmessagefile, " ".join(myfiles))
			if isSvn:
				print "(svn commit -F %s %s)" % \
					(commitmessagefile, " ".join(myfiles))
		else:
			if isCvs:
				retval = spawn(["cvs", "-q", "commit",
					"-F", commitmessagefile] + myfiles,
					env=os.environ)
			if isSvn:
				retval = spawn(["svn", "commit",
					"-F", commitmessagefile] + myfiles,
					env=os.environ)
		try:
			os.unlink(commitmessagefile)
		except OSError:
			pass
		if retval:
			print "!!! Exiting on cvs (shell) error code:",retval
			sys.exit(retval)

	# Setup the GPG commands
	def gpgsign(filename):
		if "PORTAGE_GPG_KEY" not in repoman_settings:
			raise portage.exception.MissingParameter("PORTAGE_GPG_KEY is unset!")
		if "PORTAGE_GPG_DIR" not in repoman_settings:
			if os.environ.has_key("HOME"):
				repoman_settings["PORTAGE_GPG_DIR"] = os.path.join(os.environ["HOME"], ".gnupg")
				if quiet < 1:
					print "Automatically setting PORTAGE_GPG_DIR to",repoman_settings["PORTAGE_GPG_DIR"]
			else:
				raise portage.exception.MissingParameter("PORTAGE_GPG_DIR is unset!")
		gpg_dir = repoman_settings["PORTAGE_GPG_DIR"]
		if gpg_dir.startswith("~") and "HOME" in os.environ:
			repoman_settings["PORTAGE_GPG_DIR"] = os.path.join(
				os.environ["HOME"], gpg_dir[1:].lstrip(os.path.sep))
		if not os.access(repoman_settings["PORTAGE_GPG_DIR"], os.X_OK):
			raise portage.exception.InvalidLocation(
				"Unable to access directory: PORTAGE_GPG_DIR='%s'" % \
				repoman_settings["PORTAGE_GPG_DIR"])
		gpgcmd = "gpg --sign --clearsign --yes "
		gpgcmd+= "--default-key "+repoman_settings["PORTAGE_GPG_KEY"]
		if repoman_settings.has_key("PORTAGE_GPG_DIR"):
			gpgcmd += " --homedir "+repoman_settings["PORTAGE_GPG_DIR"]
		if "--pretend" in myoptions:
			print "("+gpgcmd+" "+filename+")"
		else:
			rValue = os.system(gpgcmd+" "+filename)
			if rValue == os.EX_OK:
				os.rename(filename+".asc", filename)
			else:
				raise portage.exception.PortageException("!!! gpg exited with '" + str(rValue) + "' status")

	manifest_commit_required = True
	if myheaders or myupdates or myremoved or mynew:
		myfiles=myheaders+myupdates+myremoved+mynew
		for x in range(len(myfiles)-1, -1, -1):
			if myfiles[x].count("/") < 4-repolevel:
				del myfiles[x]
		mydone=[]
		if repolevel==3:   # In a package dir
			repoman_settings["O"] = startdir
			portage.digestgen([], repoman_settings, manifestonly=1,
				myportdb=portdb)
		elif repolevel==2: # In a category dir
			for x in myfiles:
				xs=x.split("/")
				if len(xs) < 4-repolevel:
					continue
				if xs[0]==".":
					xs=xs[1:]
				if xs[0] in mydone:
					continue
				mydone.append(xs[0])
				repoman_settings["O"] = os.path.join(startdir, xs[0])
				if not os.path.isdir(repoman_settings["O"]):
					continue
				portage.digestgen([], repoman_settings, manifestonly=1,
					myportdb=portdb)
		elif repolevel==1: # repo-cvsroot
			print green("RepoMan sez:"), "\"You're rather crazy... doing the entire repository.\"\n"
			for x in myfiles:
				xs=x.split("/")
				if len(xs) < 4-repolevel:
					continue
				if xs[0]==".":
					xs=xs[1:]
				if "/".join(xs[:2]) in mydone:
					continue
				mydone.append("/".join(xs[:2]))
				repoman_settings["O"] = os.path.join(startdir, xs[0], xs[1])
				if not os.path.isdir(repoman_settings["O"]):
					continue
				portage.digestgen([], repoman_settings, manifestonly=1,
					myportdb=portdb)
		else:
			print red("I'm confused... I don't know where I am!")
			sys.exit(1)

		# Force an unsigned commit when more than one Manifest needs to be signed.
		if repolevel < 3 and "sign" in repoman_settings.features:
			if "--pretend" in myoptions:
				print "(cvs -q commit -F commitmessagefile)"
			else:
				fd, commitmessagefile = tempfile.mkstemp(".repoman.msg")
				mymsg = os.fdopen(fd, "w")
				mymsg.write(commitmessage)
				mymsg.write("\n (Unsigned Manifest commit)")
				mymsg.close()
				retval=os.system("cvs -q commit -F "+commitmessagefile)
				try:
					os.unlink(commitmessagefile)
				except OSError:
					pass
				if retval:
					print "!!! Exiting on cvs (shell) error code:",retval
					sys.exit(retval)
			manifest_commit_required = False

	signed = False
	if "sign" in repoman_settings.features:
		signed = True
		myfiles = myupdates + myremoved + mymanifests
		try:
			if repolevel==3:   # In a package dir
				repoman_settings["O"] = "."
				gpgsign(os.path.join(repoman_settings["O"], "Manifest"))
			elif repolevel==2: # In a category dir
				mydone=[]
				for x in myfiles:
					xs=x.split("/")
					if len(xs) < 4-repolevel:
						continue
					if xs[0]==".":
						xs=xs[1:]
					if xs[0] in mydone:
						continue
					mydone.append(xs[0])
					repoman_settings["O"] = os.path.join(".", xs[0])
					if not os.path.isdir(repoman_settings["O"]):
						continue
					gpgsign(os.path.join(repoman_settings["O"], "Manifest"))
			elif repolevel==1: # repo-cvsroot
				print green("RepoMan sez:"), "\"You're rather crazy... doing the entire repository.\"\n"
				mydone=[]
				for x in myfiles:
					xs=x.split("/")
					if len(xs) < 4-repolevel:
						continue
					if xs[0]==".":
						xs=xs[1:]
					if "/".join(xs[:2]) in mydone:
						continue
					mydone.append("/".join(xs[:2]))
					repoman_settings["O"] = os.path.join(".", xs[0], xs[1])
					if not os.path.isdir(repoman_settings["O"]):
						continue
					gpgsign(os.path.join(repoman_settings["O"], "Manifest"))
		except portage.exception.PortageException, e:
			portage.writemsg("!!! %s\n" % str(e))
			portage.writemsg("!!! Disabled FEATURES='sign'\n")
			signed = False

	if manifest_commit_required or signed:
		if "--pretend" in myoptions:
			if isCvs:
				print "(cvs -q commit -F commitmessagefile)"
			if isSvn:
				print "(svn -q commit -F commitmessagefile)"
		else:
			fd, commitmessagefile = tempfile.mkstemp(".repoman.msg")
			mymsg = os.fdopen(fd, "w")
			mymsg.write(commitmessage)
			if signed:
				mymsg.write("\n (Signed Manifest commit)")
			else:
				mymsg.write("\n (Unsigned Manifest commit)")
			mymsg.close()
			if isCvs:
				retval=os.system("cvs -q commit -F "+commitmessagefile)
			if isSvn:
				retval=os.system("svn -q commit -F "+commitmessagefile)
			try:
				os.unlink(commitmessagefile)
			except OSError:
				pass
			if retval:
				print "!!! Exiting on cvs (shell) error code:",retval
				sys.exit(retval)

	print
	if isCvs or isSvn:
		print "Commit complete."
	else:
		print "repoman was too scared by not seeing any familiar version control file that he forgot to commit anything"
	print green("RepoMan sez:"), "\"If everyone were like you, I'd be out of business!\"\n"
sys.exit(0)

