blob: cbc89940e44ad22edd0400902ae50dd7807556fc [file] [log] [blame]
#!/usr/bin/python -O
# Copyright 1999-2006 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
# $Id$
import sys
# This block ensures that ^C interrupts are handled quietly.
try:
import signal
def exithandler(signum,frame):
signal.signal(signal.SIGINT, signal.SIG_IGN)
signal.signal(signal.SIGTERM, signal.SIG_IGN)
sys.exit(1)
signal.signal(signal.SIGINT, exithandler)
signal.signal(signal.SIGTERM, exithandler)
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
except KeyboardInterrupt:
sys.exit(1)
import os, stat
os.environ["PORTAGE_CALLER"]="emerge"
sys.path = ["/usr/lib/portage/pym"]+sys.path
os.environ["PORTAGE_LEGACY_GLOBALS"] = "false"
import portage
del os.environ["PORTAGE_LEGACY_GLOBALS"]
import emergehelp, xpak, commands, errno, re, socket, string, time, types
from output import blue, bold, colorize, darkblue, darkgreen, darkred, green, \
havecolor, nc_len, nocolor, red, teal, turquoise, white, xtermTitle, \
xtermTitleReset, yellow
from output import create_color_func
good = create_color_func("GOOD")
bad = create_color_func("BAD")
import portage_util
import portage_locks
import portage_exception
from portage_data import secpass
if not hasattr(__builtins__, "set"):
from sets import Set as set
class stdout_spinner(object):
scroll_msgs = [
"Gentoo Rocks ("+os.uname()[0]+")",
"Thank you for using Gentoo. :)",
"Are you actually trying to read this?",
"How many times have you stared at this?",
"We are generating the cache right now",
"You are paying too much attention.",
"A theory is better than its explanation.",
"Phasers locked on target, Captain.",
"Thrashing is just virtual crashing.",
"To be is to program.",
"Real Users hate Real Programmers.",
"When all else fails, read the instructions.",
"Functionality breeds Contempt.",
"The future lies ahead.",
"3.1415926535897932384626433832795028841971694",
"Sometimes insanity is the only alternative.",
"Inaccuracy saves a world of explanation.",
]
twirl_sequence = "/-\\|/-\\|/-\\|/-\\|\\-/|\\-/|\\-/|\\-/|"
def __init__(self):
self.spinpos = 0
self.update = self.update_twirl
self.scroll_sequence = self.scroll_msgs[
int(time.time() * 100) % len(self.scroll_msgs)]
def update_basic(self):
self.spinpos = (self.spinpos + 1) % 500
if (self.spinpos % 100) == 0:
if self.spinpos == 0:
sys.stdout.write(". ")
else:
sys.stdout.write(".")
sys.stdout.flush()
def update_scroll(self):
if(self.spinpos >= len(self.scroll_sequence)):
sys.stdout.write(darkgreen(" \b\b\b" + self.scroll_sequence[
len(self.scroll_sequence) - 1 - (self.spinpos % len(self.scroll_sequence))]))
else:
sys.stdout.write(green("\b " + self.scroll_sequence[self.spinpos]))
sys.stdout.flush()
self.spinpos = (self.spinpos + 1) % (2 * len(self.scroll_sequence))
def update_twirl(self):
self.spinpos = (self.spinpos + 1) % len(self.twirl_sequence)
sys.stdout.write("\b\b " + self.twirl_sequence[self.spinpos])
sys.stdout.flush()
def update_quiet(self):
return
def normpath(mystr):
"""
os.path.normpath("//foo") returns "//foo" instead of "/foo"
We dislike this behavior so we create our own normpath func
to fix it.
"""
if mystr and (mystr[0]=='/'):
return os.path.normpath("///"+mystr)
else:
return os.path.normpath(mystr)
def userquery(prompt, responses=None, colours=None):
"""Displays a prompt and a set of responses, then waits for a response
which is checked against the responses and the first to match is
returned. An empty response will match the first value in responses. The
input buffer is *not* cleared prior to the prompt!
prompt: a String.
responses: a List of Strings.
colours: a List of Functions taking and returning a String, used to
process the responses for display. Typically these will be functions
like red() but could be e.g. lambda x: "DisplayString".
If responses is omitted, defaults to ["Yes", "No"], [green, red].
If only colours is omitted, defaults to [bold, ...].
Returns a member of the List responses. (If called without optional
arguments, returns "Yes" or "No".)
KeyboardInterrupt is converted to SystemExit to avoid tracebacks being
printed."""
if responses is None:
responses, colours = ["Yes", "No"], [green, red]
elif colours is None:
colours=[bold]
colours=(colours*len(responses))[:len(responses)]
print bold(prompt),
try:
while True:
response=raw_input("["+string.join([colours[i](responses[i]) for i in range(len(responses))],"/")+"] ")
for key in responses:
# An empty response will match the first value in responses.
if response.upper()==key[:len(response)].upper():
return key
print "Sorry, response '%s' not understood." % response,
except (EOFError, KeyboardInterrupt):
print "Interrupted."
sys.exit(1)
def sorted_versions(verlist):
ret = []
for ver in verlist:
verparts = ver.split("-")
if len(verparts) == 2:
verrev = int(verparts[1][1:])
else:
verrev = 0
x = 0
while x < len(ret):
retparts = ret[x].split("-")
verdiff = portage.vercmp(retparts[0], verparts[0])
if verdiff > 0:
break
elif verdiff == 0:
if len(retparts) == 2:
retrev = int(retparts[1][1:])
else:
retrev = 0
if retrev >= verrev:
break
x += 1
ret.insert(x, ver)
return ret
actions=[
"clean", "config", "depclean",
"info", "metadata",
"prune", "regen", "search",
"sync", "system", "unmerge", "world",
]
options=[
"--ask", "--alphabetical",
"--buildpkg", "--buildpkgonly",
"--changelog", "--columns", "--cols",
"--debug", "--deep",
"--digest",
"--emptytree",
"--fetchonly", "--fetch-all-uri",
"--getbinpkg", "--getbinpkgonly",
"--help", "--ignore-default-opts",
"--noconfmem",
"--newuse", "--nocolor",
"--nodeps", "--noreplace",
"--nospinner", "--oneshot",
"--onlydeps", "--pretend",
"--quiet", "--resume",
"--searchdesc", "--selective",
"--skipfirst", "--skip-first",
"--tree",
"--update",
"--usepkg", "--usepkgonly",
"--verbose", "--version"
]
shortmapping={
"1":"--oneshot",
"a":"--ask",
"b":"--buildpkg", "B":"--buildpkgonly",
"c":"--clean", "C":"--unmerge",
"d":"--debug", "D":"--deep",
"e":"--emptytree",
"f":"--fetchonly", "F":"--fetch-all-uri",
"g":"--getbinpkg", "G":"--getbinpkgonly",
"h":"--help",
"k":"--usepkg", "K":"--usepkgonly",
"l":"--changelog",
"n":"--noreplace", "N":"--newuse",
"o":"--onlydeps", "O":"--nodeps",
"p":"--pretend", "P":"--prune",
"q":"--quiet",
"s":"--search", "S":"--searchdesc",
't':"--tree",
"u":"--update",
"v":"--verbose", "V":"--version"
}
def emergelog(xterm_titles, mystr, short_msg=None):
if xterm_titles:
if short_msg:
xtermTitle(short_msg)
else:
xtermTitle(mystr)
try:
file_path = "/var/log/emerge.log"
mylogfile = open(file_path, "a")
portage_util.apply_secpass_permissions(file_path,
uid=portage.portage_uid, gid=portage.portage_gid,
mode=0660)
l=portage_locks.lockfile(mylogfile)
# seek because we may have gotten held up by the lock.
# if so, we may not be positioned at the end of the file.
mylogfile.seek(0,2)
mylogfile.write(str(time.time())[:10]+": "+mystr+"\n")
mylogfile.flush()
portage_locks.unlockfile(l)
mylogfile.close()
except (IOError,OSError,portage_exception.PortageException), e:
if secpass >= 1:
print >> sys.stderr, "emergelog():",e
def countdown(secs=5, doing="Starting"):
if secs:
print ">>> Waiting",secs,"seconds before starting..."
print ">>> (Control-C to abort)...\n"+doing+" in: ",
ticks=range(secs)
ticks.reverse()
for sec in ticks:
sys.stdout.write(colorize("UNMERGE_WARN", str(sec+1)+" "))
sys.stdout.flush()
time.sleep(1)
print
# formats a size given in bytes nicely
def format_size(mysize):
if type(mysize) not in [types.IntType,types.LongType]:
return str(mysize)
mystr=str(mysize/1024)
mycount=len(mystr)
while (mycount > 3):
mycount-=3
mystr=mystr[:mycount]+","+mystr[mycount:]
return mystr+" kB"
def getgccversion(chost):
"""
rtype: C{str}
return: the current in-use gcc version
"""
gcc_ver_command = 'gcc -dumpversion'
gcc_ver_prefix = 'gcc-'
gcc_not_found_error = red(
"!!! No gcc found. You probably need to 'source /etc/profile'\n" +
"!!! to update the environment of this terminal and possibly\n" +
"!!! other terminals also.\n"
)
mystatus, myoutput = commands.getstatusoutput("eselect compiler show")
if mystatus == os.EX_OK and len(myoutput.split("/")) == 2:
part1, part2 = myoutput.split("/")
if part1.startswith(chost + "-"):
return myoutput.replace(chost + "-", gcc_ver_prefix, 1)
mystatus, myoutput = commands.getstatusoutput("gcc-config -c")
if mystatus == os.EX_OK and len(myoutput.split("-")) > 0:
return gcc_ver_prefix + myoutput.split("-")[-1]
mystatus, myoutput = commands.getstatusoutput(
chost + "-" + gcc_ver_command)
if mystatus == os.EX_OK:
return gcc_ver_prefix + myoutput
mystatus, myoutput = commands.getstatusoutput(gcc_ver_command)
if mystatus == os.EX_OK:
return gcc_ver_prefix + myoutput
portage.writemsg(gcc_not_found_error, noiselevel=-1)
return "[unavailable]"
def getportageversion(portdir, target_root, profile, chost, vardb):
profilever = "unavailable"
if profile:
realpath = os.path.realpath(profile)
basepath = os.path.realpath(os.path.join(portdir, "profiles"))
if realpath.startswith(basepath):
profilever = realpath[1 + len(basepath):]
else:
try:
profilever = "!" + os.readlink(profile)
except (OSError):
pass
del realpath, basepath
libcver=[]
libclist = vardb.match("virtual/libc")
libclist += vardb.match("virtual/glibc")
libclist = portage_util.unique_array(libclist)
for x in libclist:
xs=portage.catpkgsplit(x)
if libcver:
libcver+=","+string.join(xs[1:], "-")
else:
libcver=string.join(xs[1:], "-")
if libcver==[]:
libcver="unavailable"
gccver = getgccversion(chost)
unameout=os.uname()[2]+" "+os.uname()[4]
return "Portage " + portage.VERSION +" ("+profilever+", "+gccver+", "+libcver+", "+unameout+")"
def create_depgraph_params(myopts, myaction):
#configure emerge engine parameters
#
# self: include _this_ package regardless of if it is merged.
# selective: exclude the package if it is merged
# recurse: go into the dependencies
# deep: go into the dependencies of already merged packages
# empty: pretend nothing is merged
myparams = ["recurse"]
add=[]
sub=[]
if "--update" in myopts or myaction in ("system", "world"):
add.extend(["selective"])
if "--noreplace" in myopts:
add.extend(["selective"])
if "--emptytree" in myopts:
add.extend(["empty"])
sub.extend(["selective"])
if "--nodeps" in myopts:
sub.extend(["recurse"])
if "--deep" in myopts:
add.extend(["deep"])
for x in add:
if (x not in myparams) and (x not in sub):
myparams.append(x)
for x in sub:
if x in myparams:
myparams.remove(x)
return myparams
# search functionality
class search:
#
# class constants
#
VERSION_SHORT=1
VERSION_RELEASE=2
#
# public interface
#
def __init__(self, settings, portdb, vartree, spinner, searchdesc,
verbose):
"""Searches the available and installed packages for the supplied search key.
The list of available and installed packages is created at object instantiation.
This makes successive searches faster."""
self.settings = settings
self.portdb = portdb
self.vartree = vartree
self.spinner = spinner
self.verbose = verbose
self.searchdesc = searchdesc
def execute(self,searchkey):
"""Performs the search for the supplied search key"""
match_category = 0
self.searchkey=searchkey
self.packagematches = []
if self.searchdesc:
self.searchdesc=1
self.matches = {"pkg":[], "desc":[]}
else:
self.searchdesc=0
self.matches = {"pkg":[]}
print "Searching... ",
regexsearch = False
if self.searchkey[0] == '%':
regexsearch = True
self.searchkey = self.searchkey[1:]
if self.searchkey[0] == '@':
match_category = 1
self.searchkey = self.searchkey[1:]
if regexsearch:
self.searchre=re.compile(self.searchkey,re.I)
else:
self.searchre=re.compile(re.escape(self.searchkey), re.I)
for package in self.portdb.cp_all():
self.spinner.update()
if match_category:
match_string = package[:]
else:
match_string = package.split("/")[-1]
masked=0
if self.searchre.search(match_string):
if not self.portdb.xmatch("match-visible", package):
masked=1
self.matches["pkg"].append([package,masked])
elif self.searchdesc: # DESCRIPTION searching
full_package = self.portdb.xmatch("bestmatch-visible", package)
if not full_package:
#no match found; we don't want to query description
full_package = portage.best(
self.portdb.xmatch("match-all", package))
if not full_package:
continue
else:
masked=1
try:
full_desc = self.portdb.aux_get(
full_package, ["DESCRIPTION"])[0]
except KeyError:
print "emerge: search: aux_get() failed, skipping"
continue
if self.searchre.search(full_desc):
self.matches["desc"].append([full_package,masked])
self.mlen=0
for mtype in self.matches.keys():
self.matches[mtype].sort()
self.mlen += len(self.matches[mtype])
def output(self):
"""Outputs the results of the search."""
print "\b\b \n[ Results for search key : "+white(self.searchkey)+" ]"
print "[ Applications found : "+white(str(self.mlen))+" ]"
print " "
for mtype in self.matches.keys():
for match,masked in self.matches[mtype]:
if mtype=="pkg":
catpack=match
full_package = self.portdb.xmatch(
"bestmatch-visible", match)
if not full_package:
#no match found; we don't want to query description
masked=1
full_package = portage.best(
self.portdb.xmatch("match-all",match))
else:
full_package = match
match = portage.pkgsplit(match)[0]
if full_package:
try:
desc, homepage, license = self.portdb.aux_get(
full_package, ["DESCRIPTION","HOMEPAGE","LICENSE"])
except KeyError:
print "emerge: search: aux_get() failed, skipping"
continue
if masked:
print green("*")+" "+white(match)+" "+red("[ Masked ]")
else:
print green("*")+" "+white(match)
myversion = self.getVersion(full_package, search.VERSION_RELEASE)
mysum = [0,0]
mycat = match.split("/")[0]
mypkg = match.split("/")[1]
mycpv = match + "-" + myversion
myebuild = self.portdb.findname(mycpv)
pkgdir = os.path.dirname(myebuild)
import portage_manifest
mf = portage_manifest.Manifest(
pkgdir, self.settings["DISTDIR"])
fetchlist = self.portdb.getfetchlist(mycpv,
mysettings=self.settings, all=True)[1]
try:
mysum[0] = mf.getDistfilesSize(fetchlist)
mystr = str(mysum[0]/1024)
mycount=len(mystr)
while (mycount > 3):
mycount-=3
mystr=mystr[:mycount]+","+mystr[mycount:]
mysum[0]=mystr+" kB"
except KeyError, e:
mysum[0] = "Unknown (missing digest for %s)" % str(e)
if self.verbose:
print " ", darkgreen("Latest version available:"),myversion
print " ", self.getInstallationStatus(mycat+'/'+mypkg)
print " ", darkgreen("Size of files:"),mysum[0]
print " ", darkgreen("Homepage:")+" ",homepage
print " ", darkgreen("Description:")+" ",desc
print " ", darkgreen("License:")+" ",license
print
print
#
# private interface
#
def getInstallationStatus(self,package):
installed_package = self.vartree.dep_bestmatch(package)
result = ""
version = self.getVersion(installed_package,search.VERSION_RELEASE)
if len(version) > 0:
result = darkgreen("Latest version installed:")+" "+version
else:
result = darkgreen("Latest version installed:")+" [ Not Installed ]"
return result
def getVersion(self,full_package,detail):
if len(full_package) > 1:
package_parts = portage.catpkgsplit(full_package)
if detail == search.VERSION_RELEASE and package_parts[3] != 'r0':
result = package_parts[2]+ "-" + package_parts[3]
else:
result = package_parts[2]
else:
result = ""
return result
#build our package digraph
def getlist(settings, mode):
if mode=="system":
mylines = settings.packages
elif mode=="world":
try:
file_path = os.path.join(settings["ROOT"], portage.WORLD_FILE)
myfile = open(file_path, "r")
mylines = myfile.readlines()
myfile.close()
except (OSError, IOError), e:
if e.errno == errno.ENOENT:
portage.writemsg("\n!!! World file does not exist: '%s'\n" % file_path)
mylines=[]
else:
raise
mynewlines=[]
for x in mylines:
myline=string.join(string.split(x))
if not len(myline):
continue
elif myline[0]=="#":
continue
elif mode=="system":
if myline[0]!="*":
continue
myline=myline[1:]
mynewlines.append(myline.strip())
# Remove everything that is package.provided from our list
for atom in mynewlines[:]:
for expanded_atom in portage.flatten(
portage.dep_virtual([atom], settings)):
mykey = portage.dep_getkey(expanded_atom)
if mykey in settings.pprovideddict and \
portage.match_from_list(
expanded_atom, settings.pprovideddict[mykey]):
mynewlines.remove(atom)
break
return mynewlines
def clean_world(vardb, cpv):
"""Remove a package from the world file when unmerged."""
world_filename = os.path.join(vardb.root, portage.WORLD_FILE)
worldlist = portage_util.grabfile(world_filename)
mykey = portage.cpv_getkey(cpv)
newworldlist = []
for x in worldlist:
if portage.dep_getkey(x) == mykey:
matches = vardb.match(x, use_cache=0)
if not matches:
#zap our world entry
pass
elif len(matches) == 1 and matches[0] == cpv:
#zap our world entry
pass
else:
#others are around; keep it.
newworldlist.append(x)
else:
#this doesn't match the package we're unmerging; keep it.
newworldlist.append(x)
portage_util.ensure_dirs(os.path.join(vardb.root, portage.PRIVATE_PATH),
gid=portage.portage_gid, mode=02770)
portage_util.write_atomic(world_filename, "\n".join(newworldlist))
def genericdict(mylist):
mynewdict={}
for x in mylist:
mynewdict[portage.dep_getkey(x)]=x
return mynewdict
class depgraph:
pkg_tree_map = {
"ebuild":"porttree",
"binary":"bintree",
"installed":"vartree"}
def __init__(self, settings, trees, myopts, myparams, spinner):
self.settings = settings
self.target_root = settings["ROOT"]
self.trees = trees
self.myopts = myopts
self.myparams = myparams
self.edebug = 0
if settings.get("PORTAGE_DEBUG", "") == "1":
self.edebug = 1
self.spinner = spinner
self.pkgsettings = {}
self.pkgsettings[self.target_root] = portage.config(clone=settings)
if self.target_root != "/":
self.pkgsettings["/"] = \
portage.config(clone=trees["/"]["vartree"].settings)
self.useFlags = {}
self.useFlags[self.target_root] = {}
if self.target_root != "/":
self.useFlags["/"] = {}
self.missingbins=[]
self.digraph=portage.digraph()
self.orderedkeys=[]
self.outdatedpackages=[]
self.mydbapi={}
self.mydbapi["/"] = portage.fakedbapi(settings=settings)
self.pkg_slots={"/" : {}}
allcpv = self.trees["/"]["vartree"].getallcpv()
if "empty" not in self.myparams or self.target_root != "/":
for pkg in allcpv:
self.mydbapi["/"].cpv_inject(pkg)
for pkg in allcpv:
myslot = self.trees["/"]["vartree"].dbapi.aux_get(pkg, ["SLOT"])[0]
mykey = portage.dep_getkey(pkg)
if mykey in self.pkg_slots["/"]:
self.pkg_slots["/"][mykey][myslot] = pkg
else:
self.pkg_slots["/"][mykey] = {myslot:pkg}
if self.target_root != "/":
self.pkg_slots[self.target_root] = {}
allcpv = self.trees[self.target_root]["vartree"].getallcpv()
self.mydbapi[self.target_root] = \
portage.fakedbapi(settings=settings)
if "empty" not in self.myparams:
for pkg in allcpv:
self.mydbapi[self.target_root].cpv_inject(pkg)
for pkg in allcpv:
myslot = self.trees[self.target_root]["vartree"].dbapi.aux_get(
pkg, ["SLOT"])[0]
mykey = portage.dep_getkey(pkg)
if mykey in self.pkg_slots[self.target_root]:
self.pkg_slots[self.target_root][mykey][myslot] = pkg
else:
self.pkg_slots[self.target_root][mykey] = {myslot:pkg}
if "--usepkg" in self.myopts:
trees["/"]["bintree"].populate(
"--getbinpkg" in self.myopts, "--getbinpkgonly" in self.myopts)
if self.target_root != "/":
trees[self.target_root]["bintree"].populate(
"--getbinpkg" in self.myopts,
"--getbinpkgonly" in self.myopts)
self.args_keys = []
def create(self, mybigkey, myparent=None, addme=1, myuse=None,
soft_dep=False, rev_dep=False, arg=None):
"""
Fills the digraph with nodes comprised of packages to merge.
mybigkey is the package spec of the package to merge.
myparent is the package depending on mybigkey ( or None )
addme = Should we add this package to the digraph or are we just looking at it's deps?
Think --onlydeps, we need to ignore packages in that case.
#stuff to add:
#SLOT-aware emerge
#IUSE-aware emerge -> USE DEP aware depgraph
#"no downgrade" emerge
"""
jbigkey = " ".join(mybigkey) + " merge"
if self.digraph.hasnode(jbigkey):
if addme and jbigkey != myparent:
# Refuse to make a node depend on itself so that the we don't
# don't create a bogus circular dependency in self.altlist().
if rev_dep and myparent:
self.digraph.addnode(myparent, jbigkey, soft_dep=soft_dep)
else:
self.digraph.addnode(jbigkey, myparent, soft_dep=soft_dep)
return 1
jbigkey = " ".join(mybigkey) + " nomerge"
if self.digraph.hasnode(jbigkey):
"""XXX: It's possible that this package has been explicitly
requested as a command line argument. This can be solved by
checking all args prior to marking packages as nomerge"""
if rev_dep and myparent:
self.digraph.addnode(myparent, jbigkey, soft_dep=soft_dep)
else:
self.digraph.addnode(jbigkey, myparent, soft_dep=soft_dep)
return 1
self.spinner.update()
mytype,myroot,mykey=mybigkey
if not arg:
arg = portage.best_match_to_list(mykey, self.args_keys)
# select the correct /var database that we'll be checking against
vardbapi = self.trees[myroot]["vartree"].dbapi
portdb = self.trees[myroot]["porttree"].dbapi
bindb = self.trees[myroot]["bintree"].dbapi
pkgsettings = self.pkgsettings[myroot]
# if the package is already on the system, we add a "nomerge"
# directive, otherwise we add a "merge" directive.
if mytype=="blocks":
""" We ignore blocks unless the package that is blocked is installed
We need to check vardbapi as well as the current depgraph for it.
Blocks are fatal if buildpkgonly is set. """
if addme and "--buildpkgonly" not in self.myopts and myparent:
mybigkey[1] = myparent.split()[1]
self.digraph.addnode(" ".join(mybigkey), myparent,
soft_dep=soft_dep)
return 1
else:
mydbapi = self.trees[myroot][self.pkg_tree_map[mytype]].dbapi
if addme:
myslot = mydbapi.aux_get(mykey, ["SLOT"])[0]
depkey = portage.dep_getkey(mykey)
if depkey in self.pkg_slots:
self.pkg_slots[myroot][depkey][myslot] = mykey
else:
self.pkg_slots[myroot][depkey] = {myslot : mykey}
if myuse is None:
self.pkgsettings[myroot].setcpv(mykey)
myuse = self.pkgsettings[myroot]["USE"].split()
self.useFlags[myroot][mykey] = myuse
merging=1
if addme:
# this is where we add the node to the list of packages to merge
if "selective" in self.myparams or not arg:
if "empty" not in self.myparams and vardbapi.cpv_exists(mykey):
merging=0
""" If we aren't merging, perform the --newuse check.
If the package has new iuse flags or different use flags then if
--newuse is specified, we need to merge the package. """
if merging==0 and "--newuse" in self.myopts and \
vardbapi.cpv_exists(mykey):
pkgsettings.setcpv(mykey)
forced_flags = set()
forced_flags.update(pkgsettings.useforce)
forced_flags.update(pkgsettings.puseforce)
forced_flags.update(pkgsettings.usemask)
forced_flags.update(pkgsettings.pusemask)
old_use = vardbapi.aux_get(mykey, ["USE"])[0].split()
iuses = set(mydbapi.aux_get(mykey, ["IUSE"])[0].split())
old_iuse = set(vardbapi.aux_get(mykey, ["IUSE"])[0].split())
if iuses.symmetric_difference(
old_iuse).difference(forced_flags):
merging = 1
elif old_iuse.intersection(old_use) != \
iuses.intersection(myuse):
merging=1
if addme and merging == 1:
mybigkey.append("merge")
else:
mybigkey.append("nomerge")
if merging == 0 and vardbapi.cpv_exists(mykey):
myuse = vardbapi.aux_get(mykey, ["USE"])[0].split()
self.useFlags[myroot][mykey] = myuse
""" At this point, we have either hit a blocker and returned, found the package in the
depgraph already and returned, or we are here. Whether we are merging or not; we must
add the package to the depgraph; so we do that here. """
if rev_dep and myparent:
self.digraph.addnode(myparent, " ".join(mybigkey),
soft_dep=soft_dep)
else:
self.digraph.addnode(" ".join(mybigkey), myparent,
soft_dep=soft_dep)
""" This section determines whether we go deeper into dependencies or not.
We want to go deeper on a few occasions:
Installing package A, we need to make sure package A's deps are met.
emerge --deep <pkgspec>; we need to recursively check dependencies of pkgspec
If we are in --nodeps (no recursion) mode, we obviously only check 1 level of dependencies.
"""
if "deep" not in self.myparams and not merging:
return 1
elif "recurse" not in self.myparams:
return 1
""" Check DEPEND/RDEPEND/PDEPEND/SLOT
Pull from bintree if it's binary package, porttree if it's ebuild.
Binpkg's can be either remote or local. """
edepend={}
depkeys = ["DEPEND","RDEPEND","PDEPEND"]
depvalues = mydbapi.aux_get(mykey, depkeys)
for i in xrange(len(depkeys)):
edepend[depkeys[i]] = depvalues[i]
if mytype == "binary":
edepend["DEPEND"] = ""
elif mytype == "ebuild":
if "--buildpkgonly" in self.myopts:
edepend["RDEPEND"] = ""
edepend["PDEPEND"] = ""
""" We have retrieve the dependency information, now we need to recursively
process them. DEPEND gets processed for root = "/", {R,P}DEPEND in myroot. """
mp=string.join(mybigkey)
try:
if not self.select_dep("/", edepend["DEPEND"], myparent=mp,
myuse=myuse):
return 0
"""RDEPEND is soft by definition. However, in order to ensure
correct merge order, we make it a hard dependency. Otherwise, a
build time dependency might not be usable due to it's run time
dependencies not being installed yet.
"""
if not self.select_dep(myroot,edepend["RDEPEND"], myparent=mp,
myuse=myuse, soft_deps=False):
return 0
if edepend.has_key("PDEPEND") and edepend["PDEPEND"]:
# Post Depend -- Add to the list without a parent, as it depends
# on a package being present AND must be built after that package.
if not self.select_dep(myroot, edepend["PDEPEND"], myparent=mp,
myuse=myuse, soft_deps=True, rev_deps=True):
return 0
except ValueError, e:
pkgs = e.args[0]
portage.writemsg("\n\n!!! An atom in the dependencies " + \
"is not fully-qualified. Multiple matches:\n\n", noiselevel=-1)
for cpv in pkgs:
portage.writemsg(" %s\n" % cpv, noiselevel=-1)
portage.writemsg("\n", noiselevel=-1)
if mytype == "binary":
portage.writemsg(
"!!! This binary package cannot be installed: '%s'\n" % \
mykey, noiselevel=-1)
elif mytype == "ebuild":
myebuild, mylocation = portdb.findname2(mykey)
portage.writemsg("!!! This ebuild cannot be installed: " + \
"'%s'\n" % myebuild, noiselevel=-1)
portage.writemsg("!!! Please notify the package maintainer " + \
"that atoms must be fully-qualified.\n", noiselevel=-1)
return 0
return 1
def select_files(self,myfiles):
"given a list of .tbz2s, .ebuilds and deps, create the appropriate depgraph and return a favorite list"
myfavorites=[]
myroot = self.target_root
portdb = self.trees[myroot]["porttree"].dbapi
bindb = self.trees[myroot]["bintree"].dbapi
pkgsettings = self.pkgsettings[myroot]
self.args_keys = []
raw_args = []
for x in myfiles:
ext = os.path.splitext(x)[1]
if ext==".tbz2":
if not os.path.exists(x):
if os.path.exists(
os.path.join(pkgsettings["PKGDIR"], "All", x)):
x = os.path.join(pkgsettings["PKGDIR"], "All", x)
elif os.path.exists(
os.path.join(pkgsettings["PKGDIR"], x)):
x = os.path.join(pkgsettings["PKGDIR"], x)
else:
print "\n\n!!! Binary package '"+str(x)+"' does not exist."
print "!!! Please ensure the tbz2 exists as specified.\n"
sys.exit(1)
mytbz2=xpak.tbz2(x)
mykey=mytbz2.getelements("CATEGORY")[0]+"/"+os.path.splitext(os.path.basename(x))[0]
if os.path.realpath(x) != \
os.path.realpath(self.trees[myroot]["bintree"].getname(mykey)):
print colorize("BAD", "\n*** You need to adjust PKGDIR to emerge this package.\n")
sys.exit(1)
if not self.create(["binary", myroot, mykey],
None, "--onlydeps" not in self.myopts):
return (0,myfavorites)
elif not "--oneshot" in self.myopts:
myfavorites.append(mykey)
elif ext==".ebuild":
x = os.path.realpath(x)
mykey=os.path.basename(os.path.normpath(x+"/../.."))+"/"+os.path.splitext(os.path.basename(x))[0]
ebuild_path = portdb.findname(mykey)
if ebuild_path:
if os.path.realpath(ebuild_path) != x:
print colorize("BAD", "\n*** You need to adjust PORTDIR or PORTDIR_OVERLAY to emerge this package.\n")
sys.exit(1)
if mykey not in portdb.xmatch(
"match-visible", portage.dep_getkey(mykey)):
print colorize("BAD", "\n*** You are emerging a masked package. It is MUCH better to use")
print colorize("BAD", "*** /etc/portage/package.* to accomplish this. See portage(5) man")
print colorize("BAD", "*** page for details.")
countdown(int(self.settings["EMERGE_WARNING_DELAY"]),
"Continuing...")
else:
raise portage_exception.PackageNotFound(
"%s is not in a valid portage tree hierarchy or does not exist" % x)
if not self.create(["ebuild", myroot, mykey],
None, "--onlydeps" not in self.myopts):
return (0,myfavorites)
elif not "--oneshot" in self.myopts:
myfavorites.append(mykey)
else:
if not is_valid_package_atom(x):
portage.writemsg("\n\n!!! '%s' is not a valid package atom.\n" % x,
noiselevel=-1)
portage.writemsg("!!! Please check ebuild(5) for full details.\n")
portage.writemsg("!!! (Did you specify a version but forget to prefix with '='?)\n")
return (0,[])
try:
mykey = None
if "--usepkg" in self.myopts:
mykey = portage.dep_expand(x, mydb=bindb,
settings=pkgsettings)
if (mykey and not mykey.startswith("null/")) or \
"--usepkgonly" in self.myopts:
self.args_keys.append(mykey)
raw_args.append(x)
continue
mykey = portage.dep_expand(x,
mydb=portdb, settings=pkgsettings)
self.args_keys.append(mykey)
raw_args.append(x)
except ValueError, errpkgs:
print "\n\n!!! The short ebuild name \"" + x + "\" is ambiguous. Please specify"
print "!!! one of the following fully-qualified ebuild names instead:\n"
for i in errpkgs[0]:
print " " + green(i)
print
sys.exit(1)
for i in xrange(len(self.args_keys)):
mykey = self.args_keys[i]
try:
self.mysd = self.select_dep(myroot, mykey, arg=raw_args[i])
except portage_exception.MissingSignature, e:
portage.writemsg("\n\n!!! A missing gpg signature is preventing portage from calculating the\n")
portage.writemsg("!!! required dependencies. This is a security feature enabled by the admin\n")
portage.writemsg("!!! to aid in the detection of malicious intent.\n\n")
portage.writemsg("!!! THIS IS A POSSIBLE INDICATION OF TAMPERED FILES -- CHECK CAREFULLY.\n")
portage.writemsg("!!! Affected file: %s\n" % (e), noiselevel=-1)
sys.exit(1)
except portage_exception.InvalidSignature, e:
portage.writemsg("\n\n!!! An invalid gpg signature is preventing portage from calculating the\n")
portage.writemsg("!!! required dependencies. This is a security feature enabled by the admin\n")
portage.writemsg("!!! to aid in the detection of malicious intent.\n\n")
portage.writemsg("!!! THIS IS A POSSIBLE INDICATION OF TAMPERED FILES -- CHECK CAREFULLY.\n")
portage.writemsg("!!! Affected file: %s\n" % (e), noiselevel=-1)
sys.exit(1)
except SystemExit, e:
raise # Needed else can't exit
except Exception, e:
print >> sys.stderr, "\n\n!!! Problem in '%s' dependencies." % mykey
print >> sys.stderr, "!!!", str(e), e.__module__
raise
if not self.mysd:
return (0,myfavorites)
elif not "--oneshot" in self.myopts:
myfavorites.append(portage.dep_getkey(mykey))
missing=0
if "--usepkgonly" in self.myopts:
for x in self.digraph.all_nodes():
xs = x.split()
if len(xs) >= 4 and xs[0] != "binary" and xs[3] == "merge":
if missing == 0:
print
missing += 1
print "Missing binary for:",xs[2]
self.validate_blockers()
# We're true here unless we are missing binaries.
return (not missing,myfavorites)
def is_newer_ver_installed(self,myroot,pkg,pkgver):
"if there is a version of pkg installed newer than pkgver, return it"
vardbapi = self.trees[myroot]["vartree"].dbapi
matches = self.trees[myroot]["vartree"].dbapi.match(pkg)
if matches:
myslot = self.trees[myroot]["porttree"].getslot(pkgver)
for match in matches:
if portage.pkgcmp(portage.catpkgsplit(pkgver)[1:], portage.catpkgsplit(match)[1:]) < 0:
curslot = self.trees[myroot]["vartree"].getslot(match)
if curslot == myslot:
return match
def select_dep(self, myroot, depstring, myparent=None, arg=None,
myuse=None, raise_on_missing=False, soft_deps=False, rev_deps=False):
""" Given a depstring, create the depgraph such that all dependencies are satisfied.
myroot = $ROOT from environment, where {R,P}DEPENDs are merged to.
myparent = the node whose depstring is being passed in
arg = package was specified on the command line, merge even if it's already installed
myuse = USE flags at present
raise_on_missing = Given that the depgraph is not proper, raise an exception if true
else continue trying.
return 1 on success, 0 for failure
"""
portdb = self.trees[myroot]["porttree"].dbapi
bindb = self.trees[myroot]["bintree"].dbapi
vardb = self.trees[myroot]["vartree"].dbapi
pkgsettings = self.pkgsettings[myroot]
if "--debug" in self.myopts:
print
print "Parent: ",myparent
print "Depstring:",depstring
if rev_deps:
print "Reverse:", rev_deps
if soft_deps:
print "Soft:", soft_deps
#processing dependencies
""" Call portage.dep_check to evaluate the use? conditionals and make sure all
dependencies are satisfiable. """
mycheck = portage.dep_check(depstring, self.mydbapi[myroot],
pkgsettings, myuse=myuse,
use_binaries=("--usepkgonly" in self.myopts),
myroot=myroot, trees=self.trees, return_all_deps=True)
if not mycheck[0]:
sys.stderr.write("\n\n%s\n\n" % mycheck[1])
sys.stderr.write("%s\n\n" % depstring)
return 0
mymerge = mycheck[1]
if myparent:
# In order to get past circular dependencies (in
# `emerge -e world`, for example), the parent must be allowed
# to satisfy dependencies of it's children.
# The parent is added after it's own dep_check call so that it
# isn't allowed to satisfy a direct bootstrap dependency on itself
# or an old-style virtual that it satisfies (unfortunately, this
# only works for one level of deps, so it won't work for new-style
# virtuals since they introduce an additional level of dependency
# indirection).
p_type, p_root, p_key, p_status = myparent.split()
if p_status == "merge":
""" This fakedbapi data is used in dep_check calls to determine
satisfied deps via dep_wordreduce"""
self.mydbapi[p_root].cpv_inject(p_key)
# Update old-style virtuals if this package provides any.
# These are needed for dep_virtual calls inside dep_check.
self.pkgsettings[p_root].setinst(p_key,
self.trees[p_root][self.pkg_tree_map[p_type]].dbapi)
if "--debug" in self.myopts:
print "Candidates:",mymerge
for x in mymerge:
selected_pkg = None
if x[0]=="!":
# if this package is myself, don't append it to block list.
if "--debug" in self.myopts:
print "Myparent",myparent
if (myparent):
if myparent.split()[2] in \
portdb.xmatch("match-all", x[1:]):
# myself, so exit.
continue
# adding block
selected_pkg = ["blocks", myroot, x[1:], None]
else:
#We are not processing a blocker but a normal dependency
if myparent:
"""In some cases, dep_check will return deps that shouldn't
be proccessed any further, so they are identified and
discarded here."""
if "empty" not in self.myparams and \
"deep" not in self.myparams and \
vardb.match(x):
continue
pkg_key = portage.dep_getkey(x)
if pkg_key in pkgsettings.pprovideddict and \
portage.match_from_list(
x, pkgsettings.pprovideddict[pkg_key]):
continue
# List of acceptable packages, ordered by type preference.
matched_packages = []
myeb_matches = portdb.xmatch("match-visible", x)
myeb = None
if "--usepkgonly" not in self.myopts:
myeb = portage.best(myeb_matches)
myeb_pkg=None
if "--usepkg" in self.myopts:
# The next line assumes the binarytree has been populated.
# XXX: Need to work out how we use the binary tree with roots.
myeb_pkg_matches = bindb.match(x)
if "--usepkgonly" not in self.myopts:
# Remove any binary package entries that are masked in the portage tree (#55871)
myeb_pkg_matches = [pkg for pkg in myeb_pkg_matches \
if pkg in myeb_matches or \
not portdb.cpv_exists(pkg)]
if myeb_pkg_matches:
myeb_pkg = portage.best(myeb_pkg_matches)
if myeb_pkg and "--newuse" in self.myopts:
iuses = set(bindb.aux_get(myeb_pkg, ["IUSE"])[0].split())
old_use = bindb.aux_get(myeb_pkg, ["USE"])[0].split()
pkgsettings.setcpv(myeb_pkg)
now_use = pkgsettings["USE"].split()
forced_flags = set()
forced_flags.update(pkgsettings.useforce)
forced_flags.update(pkgsettings.puseforce)
forced_flags.update(pkgsettings.usemask)
forced_flags.update(pkgsettings.pusemask)
cur_iuse = iuses
if "--usepkgonly" not in self.myopts and myeb:
cur_iuse = set(portdb.aux_get(myeb, ["IUSE"])[0].split())
if iuses.symmetric_difference(
cur_iuse).difference(forced_flags):
myeb_pkg = None
elif iuses.intersection(old_use) != \
cur_iuse.intersection(now_use):
myeb_pkg = None
if myeb_pkg:
binpkguseflags = \
self.trees[myroot]["bintree"].dbapi.aux_get(
myeb_pkg, ["USE"])[0].split()
matched_packages.append(
["binary", myroot, myeb_pkg, binpkguseflags])
if "--usepkgonly" not in self.myopts and myeb_matches:
matched_packages.append(
["ebuild", myroot, myeb, None])
if not matched_packages:
if raise_on_missing:
raise ValueError
if not arg:
xinfo='"'+x+'"'
else:
xinfo='"'+arg+'"'
if myparent:
xfrom = '(dependency required by '+green('"'+myparent.split()[2]+'"')+red(' ['+myparent.split()[0]+"]")+')'
alleb = portdb.xmatch("match-all", x)
if alleb:
if "--usepkgonly" not in self.myopts:
print "\n!!! "+red("All ebuilds that could satisfy ")+green(xinfo)+red(" have been masked.")
print "!!! One of the following masked packages is required to complete your request:"
oldcomment = ""
for p in alleb:
mreasons = portage.getmaskingstatus(p,
settings=pkgsettings, portdb=portdb)
print "- "+p+" (masked by: "+string.join(mreasons, ", ")+")"
comment = portage.getmaskingreason(p,
settings=pkgsettings, portdb=portdb)
if comment and comment != oldcomment:
print comment
oldcomment = comment
print
print "For more information, see MASKED PACKAGES section in the emerge man page or "
print "refer to the Gentoo Handbook."
else:
print "\n!!! "+red("There are no packages available to satisfy: ")+green(xinfo)
print "!!! Either add a suitable binary package or compile from an ebuild."
else:
print "\nemerge: there are no ebuilds to satisfy "+green(xinfo)+"."
if myparent:
print xfrom
print
return 0
if "--debug" in self.myopts:
for pkg in matched_packages:
print (pkg[0] + ":").rjust(10), pkg[2]
if len(matched_packages) > 1:
bestmatch = portage.best(
[pkg[2] for pkg in matched_packages])
matched_packages = [pkg for pkg in matched_packages \
if pkg[2] == bestmatch]
# ordered by type preference ("ebuild" type is the last resort)
selected_pkg = matched_packages[0]
if myparent:
#we are a dependency, so we want to be unconditionally added
soft_dep = bool(soft_deps or vardb.match(x))
if not self.create(selected_pkg[0:3], myparent,
myuse=selected_pkg[-1], soft_dep=soft_dep,
rev_dep=rev_deps, arg=arg):
return 0
else:
#if mysource is not set, then we are a command-line dependency and should not be added
#if --onlydeps is specified.
if not self.create(selected_pkg[0:3], myparent,
addme=("--onlydeps" not in self.myopts),
myuse=selected_pkg[-1], rev_dep=rev_deps, arg=arg):
return 0
if "--debug" in self.myopts:
print "Exiting...",myparent
return 1
def validate_blockers(self):
"""Remove any blockers from the digraph that do not match any of the
packages within the graph. Blockers are only matched against the
final state of the graph. Thus, it's possible that mutually blocking
packages will be installed simultaneously a some point(s) during the
transition from the initial to the final state."""
all_blockers = [node for node in self.digraph.all_nodes()
if node.split()[0] == "blocks"]
for blocker in all_blockers:
mytype, myroot, mydep = blocker.split()
"""Prior to being added to the digraph, any blockers against
old-style virtuals have been expanded to real packages via
dep_virtual calls inside dep_check."""
mykey = portage.dep_getkey(mydep)
valid = False
pkgs = self.pkg_slots[myroot].get(mykey, None)
if pkgs and portage.match_from_list(mydep,
[pkgs[myslot] for myslot in pkgs]):
valid = True
if not valid:
self.digraph.remove(blocker)
def altlist(self, reversed=False):
mygraph=self.digraph.copy()
retlist=[]
while not mygraph.empty():
if reversed:
nodes = mygraph.root_nodes()
if not nodes:
nodes = mygraph.root_nodes(ignore_soft_deps=True)
if nodes:
next_node = nodes[-1]
else:
next_node = None
else:
nodes = mygraph.leaf_nodes()
if not nodes:
nodes = mygraph.leaf_nodes(ignore_soft_deps=True)
if nodes:
next_node = nodes[0]
else:
next_node = None
if not next_node:
print "!!! Error: circular dependencies:"
print
mygraph.debug_print()
sys.exit(1)
retlist.append(next_node.split())
mygraph.remove(next_node)
return retlist
def xcreate(self,mode="system"):
world_problems = False
if mode=="system":
mylist = getlist(self.settings, "system")
else:
#world mode
worldlist = getlist(self.settings, "world")
sysdict = genericdict(getlist(self.settings, "system"))
worlddict=genericdict(worldlist)
for x in worlddict.keys():
if not portage.isvalidatom(x):
world_problems = True
elif not self.trees[self.target_root]["vartree"].dbapi.match(x):
world_problems = True
else:
sysdict[x]=worlddict[x]
mylist = sysdict.keys()
newlist = []
for atom in mylist:
if portage.dep_getkey(atom).split("/")[-1] == "portage":
newlist.insert(0, atom)
else:
newlist.append(atom)
mylist = newlist
missing_atoms = []
for mydep in mylist:
try:
if not self.select_dep(
self.target_root, mydep, raise_on_missing=True):
print >> sys.stderr, "\n\n!!! Problem resolving dependencies for", mydep
return 0
except ValueError:
missing_atoms.append(mydep)
self.validate_blockers()
if world_problems:
print >> sys.stderr, "\n!!! Problems have been detected with your world file"
print >> sys.stderr, "!!! Please run "+green("emaint --check world")+"\n"
if missing_atoms:
print >> sys.stderr, "\n" + colorize("BAD", "!!!") + \
" Ebuilds for the following packages are either all"
print >> sys.stderr, colorize("BAD", "!!!") + " masked or don't exist:"
print >> sys.stderr, " ".join(missing_atoms) + "\n"
return 1
def match(self, mydep, myroot=None, mykey=None):
# support mutual exclusive deps
if myroot is None:
myroot = self.target_root
mydep2=mydep
if mydep2[0]=="!":
mydep2=mydep[1:]
if mydep[0]=="!":
#add our blocker; it will be ignored later if necessary (if we are remerging the same pkg, for example)
myk="blocks "+myroot+" "+mydep2
else:
myeb = self.trees[myroot]["porttree"].dep_bestmatch(mydep2)
if not myeb:
if not mykey:
print "\n!!! Error: couldn't find match for",mydep
else:
print "\n!!! Error: couldn't find match for",mydep,"in",mykey
print
sys.exit(1)
if "--usepkg" in self.myopts:
mypk = self.trees[myroot]["bintree"].dep_bestmatch(mydep)
if myeb==mypk:
myk = " ".join(("binary", myroot, mypk))
else:
myk = " ".join(("ebuild", myroot, myeb))
else:
myk="ebuild "+myroot+" "+myeb
return myk
def display(self,mylist,verbosity=None):
if verbosity is None:
verbosity = ("--quiet" in self.myopts and 1 or \
"--verbose" in self.myopts and 3 or 2)
changelogs=[]
p=[]
totalsize=0
if verbosity == 1 and "--verbose" not in self.myopts:
def create_use_string(*args):
return ""
else:
def create_use_string(name, cur_iuse, iuse_forced, cur_use,
old_iuse, old_use,
is_new, all_flags=(verbosity == 3 or "--quiet" in self.myopts),
alphabetical=("--alphabetical" in self.myopts)):
enabled = []
if alphabetical:
disabled = enabled
removed = enabled
else:
disabled = []
removed = []
cur_iuse = set(cur_iuse)
enabled_flags = cur_iuse.intersection(cur_use)
removed_iuse = set(old_iuse).difference(cur_iuse)
any_iuse = cur_iuse.union(old_iuse)
any_iuse = list(any_iuse)
any_iuse.sort()
for flag in any_iuse:
flag_str = None
isEnabled = False
if flag in enabled_flags:
isEnabled = True
if is_new or flag in old_use and all_flags:
flag_str = red(flag)
elif flag not in old_iuse:
flag_str = yellow(flag) + "%*"
elif flag not in old_use:
flag_str = green(flag) + "*"
elif flag in removed_iuse:
if all_flags:
flag_str = yellow("-" + flag) + "%"
if flag in old_use:
flag_str += "*"
flag_str = "(" + flag_str + ")"
removed.append(flag_str)
continue
else:
if is_new or flag in old_iuse and flag not in old_use and all_flags:
flag_str = blue("-" + flag)
elif flag not in old_iuse:
flag_str = yellow("-" + flag)
if flag not in iuse_forced:
flag_str += "%"
elif flag in old_use:
flag_str = green("-" + flag) + "*"
if flag_str:
if flag in iuse_forced:
flag_str = "(" + flag_str + ")"
if isEnabled:
enabled.append(flag_str)
else:
disabled.append(flag_str)
if alphabetical:
ret = " ".join(enabled)
else:
ret = " ".join(enabled + disabled + removed)
if ret:
ret = '%s="%s" ' % (name, ret)
return ret
if verbosity == 3:
# FIXME: account for the possibility of different overlays in
# /etc/make.conf vs. ${PORTAGE_CONFIGROOT}/etc/make.conf
overlays = self.settings["PORTDIR_OVERLAY"].split()
overlays_real = [os.path.realpath(t) \
for t in self.settings["PORTDIR_OVERLAY"].split()]
tree_nodes = []
node_depth = {}
i = 0
depth = 0
for x in mylist:
graph_key = " ".join(x)
if "--tree" in self.myopts:
depth = len(tree_nodes)
while depth and graph_key not in \
self.digraph.child_nodes(tree_nodes[depth-1]):
depth -= 1
tree_nodes = tree_nodes[:depth]
tree_nodes.append(graph_key)
node_depth[graph_key] = depth
last_merge_depth = 0
for i in xrange(len(mylist)-1,-1,-1):
graph_key = " ".join(mylist[i])
if mylist[i][-1] != "nomerge":
last_merge_depth = node_depth[graph_key]
continue
if node_depth[graph_key] >= last_merge_depth or \
i < len(mylist) - 1 and \
node_depth[graph_key] >= node_depth[" ".join(mylist[i+1])]:
del mylist[i]
del node_depth[graph_key]
del tree_nodes
display_overlays=False
# files to fetch list - avoids counting a same file twice
# in size display (verbose mode)
myfetchlist=[]
for x in mylist:
pkg_type = x[0]
myroot = x[1]
pkg_key = x[2]
portdb = self.trees[myroot]["porttree"].dbapi
bindb = self.trees[myroot]["bintree"].dbapi
vartree = self.trees[myroot]["vartree"]
pkgsettings = self.pkgsettings[myroot]
pkgsettings.setcpv(pkg_key)
if pkg_key not in self.useFlags[myroot]:
if "binary" == pkg_type:
self.useFlags[myroot][pkg_key] = bindb.aux_get(
pkg_key, ["USE"])[0].split()
elif "ebuild" == pkg_type:
self.useFlags[myroot][pkg_key] = pkgsettings["USE"].split()
fetch=" "
if x[0]=="blocks":
addl=""+red("B")+" "+fetch+" "
resolved = self.trees[x[1]]["vartree"].resolve_key(x[2])
print "["+x[0]+" "+addl+"]",red(resolved),
block_parents = self.digraph.parent_nodes(" ".join(x))
block_parents = [pnode.split()[2] for pnode in block_parents]
block_parents = ", ".join(block_parents)
if resolved!=x[2]:
print bad("(\"%s\" is blocking %s)") % \
(pkg_key, block_parents)
else:
print bad("(is blocking %s)") % block_parents
else:
if x[0] != "binary" and \
"fetch" in portdb.aux_get(
x[2], ["RESTRICT"])[0].split():
fetch = red("F")
if portdb.fetch_check(
pkg_key, self.useFlags[myroot][pkg_key]):
fetch = green("f")
#we need to use "--emptrytree" testing here rather than "empty" param testing because "empty"
#param is used for -u, where you still *do* want to see when something is being upgraded.
myoldbest=""
if "--emptytree" not in self.myopts and \
self.trees[x[1]]["vartree"].exists_specific(x[2]):
addl=" "+yellow("R")+fetch+" "
elif "--emptytree" not in self.myopts and \
self.trees[x[1]]["vartree"].exists_specific_cat(x[2]):
if x[0] == "binary":
mynewslot = \
self.trees[myroot]["bintree"].getslot(pkg_key)
elif x[0] == "ebuild":
mynewslot = \
self.trees[myroot]["porttree"].getslot(pkg_key)
myoldlist = self.trees[x[1]]["vartree"].dbapi.match(
portage.pkgsplit(x[2])[0])
myinslotlist = [inst_pkg for inst_pkg in myoldlist
if mynewslot == vartree.getslot(inst_pkg)]
if myinslotlist:
myoldbest=portage.best(myinslotlist)
addl=" "+fetch
if portage.pkgcmp(portage.pkgsplit(x[2]), portage.pkgsplit(myoldbest)) < 0:
# Downgrade in slot
addl+=turquoise("U")+blue("D")
else:
# Update in slot
addl+=turquoise("U")+" "
else:
# New slot, mark it new.
addl=" "+green("NS")+fetch+" "
if "--changelog" in self.myopts:
changelogs.extend(self.calc_changelog(
portdb.findname(pkg_key),
self.trees[x[1]]["vartree"].dep_bestmatch(
'/'.join(portage.catpkgsplit(x[2])[:2])), x[2]))
else:
addl=" "+green("N")+" "+fetch+" "
verboseadd=""
if pkg_key in self.useFlags[myroot]:
# USE flag display
if x[0] == "binary":
cur_iuse = bindb.aux_get(pkg_key, ["IUSE"])[0].split()
elif x[0] == "ebuild":
cur_iuse = portdb.aux_get(pkg_key, ["IUSE"])[0].split()
else:
cur_iuse = []
forced_flags = set()
forced_flags.update(pkgsettings.useforce)
forced_flags.update(pkgsettings.puseforce)
forced_flags.update(pkgsettings.usemask)
forced_flags.update(pkgsettings.pusemask)
cur_iuse = portage.unique_array(cur_iuse)
cur_iuse.sort()
cur_use = self.useFlags[myroot][pkg_key]
cur_use = [flag for flag in cur_use if flag in cur_iuse]
if myoldbest:
pkg = myoldbest
else:
pkg = x[2]
if self.trees[x[1]]["vartree"].dbapi.cpv_exists(pkg):
old_iuse, old_use = \
self.trees[x[1]]["vartree"].dbapi.aux_get(
pkg, ["IUSE", "USE"])
old_iuse = portage.unique_array(old_iuse.split())
old_iuse.sort()
old_use = old_use.split()
is_new = False
else:
old_iuse = []
old_use = []
is_new = True
old_use = [flag for flag in old_use if flag in old_iuse]
use_expand = pkgsettings["USE_EXPAND"].lower().split()
use_expand.sort()
use_expand.reverse()
use_expand_hidden = \
pkgsettings["USE_EXPAND_HIDDEN"].lower().split()
def map_to_use_expand(myvals, forcedFlags=False):
ret = {}
forced = {}
for exp in use_expand:
ret[exp] = []
forced[exp] = set()
for val in myvals[:]:
if val.startswith(exp.lower()+"_"):
if val in forced_flags:
forced[exp].add(val[len(exp)+1:])
ret[exp].append(val[len(exp)+1:])
myvals.remove(val)
ret["USE"] = myvals
forced["USE"] = [val for val in myvals \
if val in forced_flags]
for exp in use_expand_hidden:
if exp in ret:
del ret[exp]
if forcedFlags:
return ret, forced
return ret
cur_iuse_map, iuse_forced = \
map_to_use_expand(cur_iuse, forcedFlags=True)
cur_use_map = map_to_use_expand(cur_use)
old_iuse_map = map_to_use_expand(old_iuse)
old_use_map = map_to_use_expand(old_use)
use_expand.sort()
use_expand.insert(0, "USE")
for key in use_expand:
if key in use_expand_hidden:
continue
verboseadd += create_use_string(key.upper(),
cur_iuse_map[key], iuse_forced[key],
cur_use_map[key], old_iuse_map[key],
old_use_map[key], is_new)
if verbosity == 3:
# size verbose
mysize=0
if x[0] == "ebuild" and x[-1]!="nomerge":
myfilesdict = portdb.getfetchsizes(
pkg_key, useflags=self.useFlags[myroot][pkg_key],
debug=self.edebug)
if myfilesdict is None:
myfilesdict="[empty/missing/bad digest]"
else:
for myfetchfile in myfilesdict.keys():
if myfetchfile not in myfetchlist:
mysize+=myfilesdict[myfetchfile]
myfetchlist.append(myfetchfile)
totalsize+=mysize
verboseadd+=format_size(mysize)+" "
# overlay verbose
# XXX: Invalid binaries have caused tracebacks here. 'if file_name'
# x = ['binary', '/', 'sys-apps/pcmcia-cs-3.2.7.2.6', 'merge']
file_name = portdb.findname(pkg_key)
if file_name: # It might not exist in the tree
dir_name=os.path.abspath(os.path.dirname(file_name)+"/../..")
if (overlays_real.count(dir_name)>0):
verboseadd+=teal("["+str(overlays_real.index(
os.path.normpath(dir_name))+1)+"]")+" "
display_overlays=True
else:
verboseadd += "[No ebuild?]"
xs=portage.pkgsplit(x[2])
if xs[2]=="r0":
xs[2]=""
else:
xs[2]="-"+xs[2]
mywidth = 130
if "COLUMNWIDTH" in self.settings:
try:
mywidth = int(self.settings["COLUMNWIDTH"])
except ValueError, e:
portage.writemsg("!!! %s\n" % str(e), noiselevel=-1)
portage.writemsg(
"!!! Unable to parse COLUMNWIDTH='%s'\n" % \
self.settings["COLUMNWIDTH"], noiselevel=-1)
del e
oldlp=mywidth-30
newlp=oldlp-30
indent = " " * node_depth[" ".join(x)]
if myoldbest:
myoldbest=portage.pkgsplit(myoldbest)[1]+"-"+portage.pkgsplit(myoldbest)[2]
if myoldbest[-3:]=="-r0":
myoldbest=myoldbest[:-3]
myoldbest=blue("["+myoldbest+"]")
if x[1]!="/":
if myoldbest:
myoldbest +=" "
if "--columns" in self.myopts:
if "--quiet" in self.myopts:
myprint=addl+" "+indent+darkgreen(xs[0])
myprint=myprint+darkblue(" "+xs[1]+xs[2])+" "
myprint=myprint+myoldbest
myprint=myprint+darkgreen("to "+x[1])
else:
myprint="["+x[0]+" "+addl+"] "+indent+darkgreen(xs[0])
if (newlp-nc_len(myprint)) > 0:
myprint=myprint+(" "*(newlp-nc_len(myprint)))
myprint=myprint+"["+darkblue(xs[1]+xs[2])+"] "
if (oldlp-nc_len(myprint)) > 0:
myprint=myprint+" "*(oldlp-nc_len(myprint))
myprint=myprint+myoldbest
myprint=myprint+darkgreen("to "+x[1])+" "+verboseadd
else:
myprint="["+x[0]+" "+addl+"] "+darkgreen(x[2])+" "+myoldbest+darkgreen("to "+x[1])+" "+verboseadd
else:
if "--columns" in self.myopts:
if "--quiet" in self.myopts:
myprint=addl+" "+indent+darkgreen(xs[0])
myprint=myprint+" "+green(xs[1]+xs[2])+" "
myprint=myprint+myoldbest
else:
myprint="["+x[0]+" "+addl+"] "+indent+darkgreen(xs[0])
if (newlp-nc_len(myprint)) > 0:
myprint=myprint+(" "*(newlp-nc_len(myprint)))
myprint=myprint+green(" ["+xs[1]+xs[2]+"] ")
if (oldlp-nc_len(myprint)) > 0:
myprint=myprint+(" "*(oldlp-nc_len(myprint)))
myprint=myprint+myoldbest+" "+verboseadd
else:
if x[3]=="nomerge":
myprint=darkblue("[nomerge ] "+indent+x[2]+" "+myoldbest+" ")+verboseadd
else:
myprint="["+x[0]+" "+addl+"] "+indent+darkgreen(x[2])+" "+myoldbest+" "+verboseadd
p.append(myprint)
mysplit = portage.pkgsplit(x[2])
if "--tree" not in self.myopts and mysplit and \
len(mysplit) == 3 and mysplit[0] == "sys-apps/portage" and \
x[1] == "/":
if mysplit[2] == "r0":
myversion = mysplit[1]
else:
myversion = "%s-%s" % (mysplit[1], mysplit[2])
if myversion != portage.VERSION :
if "--emptytree" in self.myopts:
p.append(colorize("WARN", "***")+" Please update portage to the above version before proceeding.")
p.append(" Failure to do so may result in failed or improper merges.")
p.append(" A simple '"+green("emerge portage")+"' is sufficient.")
p.append("")
elif mylist.index(x) < len(mylist) - 1 and \
"livecvsportage" not in self.settings.features:
p.append(colorize("WARN", "*** Portage will stop merging at this point and reload itself,"))
p.append(colorize("WARN", " then resume the merge."))
print
del mysplit
for x in p:
print x
if verbosity == 3:
print
print "Total size of downloads: "+format_size(totalsize)
if overlays and display_overlays:
print "Portage overlays:"
y=0
for x in overlays:
y=y+1
print " "+teal("["+str(y)+"]"),x
if "--changelog" in self.myopts:
print
for revision,text in changelogs:
print bold('*'+revision)
sys.stdout.write(text)
def calc_changelog(self,ebuildpath,current,next):
current = '-'.join(portage.catpkgsplit(current)[1:])
if current.endswith('-r0'): current = current[:-3]
next = '-'.join(portage.catpkgsplit(next)[1:])
if next.endswith('-r0'): next = next[:-3]
changelogpath = os.path.join(os.path.split(ebuildpath)[0],'ChangeLog')
try:
changelog = open(changelogpath).read()
except SystemExit, e:
raise # Needed else can't exit
except:
return []
divisions = self.find_changelog_tags(changelog)
#print 'XX from',current,'to',next
#for div,text in divisions: print 'XX',div
# skip entries for all revisions above the one we are about to emerge
for i in range(len(divisions)):
if divisions[i][0]==next:
divisions = divisions[i:]
break
# find out how many entries we are going to display
for i in range(len(divisions)):
if divisions[i][0]==current:
divisions = divisions[:i]
break
else:
# couldnt find the current revision in the list. display nothing
return []
return divisions
def find_changelog_tags(self,changelog):
divs = []
release = None
while 1:
match = re.search(r'^\*\ ?([-a-zA-Z0-9_.+]*)(?:\ .*)?\n',changelog,re.M)
if match is None:
if release is not None:
divs.append((release,changelog))
return divs
if release is not None:
divs.append((release,changelog[:match.start()]))
changelog = changelog[match.end():]
release = match.group(1)
if release.endswith('.ebuild'):
release = release[:-7]
if release.endswith('-r0'):
release = release[:-3]
def outdated(self):
return self.outdatedpackages
class MergeTask(object):
def __init__(self, settings, trees, myopts):
self.settings = settings
self.target_root = settings["ROOT"]
self.trees = trees
self.myopts = myopts
self.edebug = 0
if settings.get("PORTAGE_DEBUG", "") == "1":
self.edebug = 1
self.pkgsettings = {}
self.pkgsettings[self.target_root] = portage.config(clone=settings)
if self.target_root != "/":
self.pkgsettings["/"] = \
portage.config(clone=trees["/"]["vartree"].settings)
def merge(self, mylist, favorites, mtimedb):
returnme=0
mymergelist=[]
ldpath_mtimes = mtimedb["ldpath"]
xterm_titles = "notitles" not in self.settings.features
#check for blocking dependencies
if "--fetchonly" not in self.myopts and \
"--buildpkgonly" not in self.myopts:
for x in mylist:
if x[0]=="blocks":
print "\n!!! Error: the "+x[2]+" package conflicts with another package;"
print "!!! the two packages cannot be installed on the same system together."
print "!!! Please use 'emerge --pretend' to determine blockers."
if "--quiet" not in self.myopts:
show_blocker_docs_link()
if "--pretend" not in self.myopts:
try:
del mtimedb["resume"]
except KeyError:
pass
sys.exit(1)
#buildsyspkg: I need mysysdict also on resume (moved from the else block)
mysysdict = genericdict(getlist(self.settings, "system"))
if "--resume" in self.myopts:
# We're resuming.
print colorize("GOOD", "*** Resuming merge...")
emergelog(xterm_titles, " *** Resuming merge...")
mymergelist=mtimedb["resume"]["mergelist"][:]
if "--skipfirst" in self.myopts and mymergelist:
del mtimedb["resume"]["mergelist"][0]
del mymergelist[0]
mtimedb.commit()
validate_merge_list(self.trees, mymergelist)
else:
myfavs = portage.grabfile(
os.path.join(self.target_root, portage.WORLD_FILE))
myfavdict=genericdict(myfavs)
for x in range(len(mylist)):
if mylist[x][3]!="nomerge":
# Add to the mergelist
mymergelist.append(mylist[x])
else:
myfavkey=portage.cpv_getkey(mylist[x][2])
if "--onlydeps" in self.myopts:
continue
# Add to the world file. Since we won't be able to later.
if "--fetchonly" not in self.myopts and \
myfavkey in favorites:
#don't record if already in system profile or already recorded
if (not mysysdict.has_key(myfavkey)) and (not myfavdict.has_key(myfavkey)):
#we don't have a favorites entry for this package yet; add one
myfavdict[myfavkey]=myfavkey
print ">>> Recording",myfavkey,"in \"world\" favorites file..."
if not ("--fetchonly" in self.myopts or \
"--fetch-all-uri" in self.myopts or \
"--pretend" in self.myopts):
portage.write_atomic(
os.path.join(self.target_root, portage.WORLD_FILE),
"\n".join(myfavdict.values()))
mtimedb["resume"]["mergelist"]=mymergelist[:]
mtimedb.commit()
myfeat = self.settings.features[:]
bad_resume_opts = set(["--ask", "--tree", "--changelog", "--skipfirst",
"--resume"])
if "parallel-fetch" in myfeat and \
not ("--pretend" in self.myopts or \
"--fetch-all-uri" in self.myopts or \
"--fetchonly" in self.myopts):
if "distlocks" not in myfeat:
print red("!!!")
print red("!!!")+" parallel-fetching requires the distlocks feature enabled"
print red("!!!")+" you have it disabled, thus parallel-fetching is being disabled"
print red("!!!")
elif len(mymergelist) > 1:
print ">>> starting parallel fetching"
fetch_log = "/var/log/emerge-fetch.log"
logfile = open(fetch_log, "w")
fd_pipes = {1:logfile.fileno(), 2:logfile.fileno()}
portage_util.apply_secpass_permissions(fetch_log,
uid=portage.portage_uid, gid=portage.portage_gid,
mode=0660)
fetch_env = os.environ.copy()
fetch_env["FEATURES"] = fetch_env.get("FEATURES", "") + " -cvs"
fetch_env["PORTAGE_NICENESS"] = "0"
fetch_args = [sys.argv[0], "--resume", "--fetchonly"]
for arg in self.myopts:
if arg not in bad_resume_opts:
fetch_args.append(arg)
portage.portage_exec.spawn(fetch_args, env=fetch_env,
fd_pipes=fd_pipes, returnpid=True)
logfile.close() # belongs to the spawned process
mergecount=0
for x in mymergelist:
mergecount+=1
myroot=x[1]
pkg_key = x[2]
pkgindex=2
portdb = self.trees[myroot]["porttree"].dbapi
bindb = self.trees[myroot]["bintree"].dbapi
vartree = self.trees[myroot]["vartree"]
pkgsettings = self.pkgsettings[myroot]
if x[0]=="blocks":
pkgindex=3
y = portdb.findname(pkg_key)
if "--pretend" not in self.myopts:
print "\n>>> Emerging (" + \
colorize("MERGE_LIST_PROGRESS", str(mergecount)) + " of " + \
colorize("MERGE_LIST_PROGRESS", str(len(mymergelist))) + ") " + \
colorize("GOOD", x[pkgindex]) + " to " + x[1]
emergelog(xterm_titles, " >>> emerge ("+\
str(mergecount)+" of "+str(len(mymergelist))+\
") "+x[pkgindex]+" to "+x[1])
pkgsettings["EMERGE_FROM"] = x[0]
pkgsettings.backup_changes("EMERGE_FROM")
pkgsettings.reset()
#buildsyspkg: Check if we need to _force_ binary package creation
issyspkg = ("buildsyspkg" in myfeat) \
and x[0] != "blocks" \
and mysysdict.has_key(portage.cpv_getkey(x[2])) \
and "--buildpkg" not in self.myopts
if x[0] in ["ebuild","blocks"]:
if x[0] == "blocks" and "--fetchonly" not in self.myopts:
raise Exception, "Merging a blocker"
elif "--fetchonly" in self.myopts or \
"--fetch-all-uri" in self.myopts:
if "--fetch-all-uri" in self.myopts:
retval = portage.doebuild(y, "fetch", myroot,
pkgsettings, self.edebug,
"--pretend" in self.myopts, fetchonly=1,
fetchall=1, mydbapi=portdb, tree="porttree")
else:
retval = portage.doebuild(y, "fetch", myroot,
pkgsettings, self.edebug,
"--pretend" in self.myopts, fetchonly=1,
mydbapi=portdb, tree="porttree")
if (retval is None) or retval:
print
print "!!! Fetch for",y,"failed, continuing..."
print
returnme=1
continue
portage.doebuild_environment(y, "setup", myroot,
pkgsettings, self.edebug, 1, portdb)
portage_util.ensure_dirs(
os.path.dirname(pkgsettings["PORTAGE_BUILDDIR"]),
gid=portage.portage_gid, mode=070, mask=02)
builddir_lock = None
try:
builddir_lock = portage_locks.lockdir(
pkgsettings["PORTAGE_BUILDDIR"])
msg = " === (%s of %s) Cleaning (%s::%s)" % \
(mergecount, len(mymergelist), pkg_key, y)
short_msg = "emerge: (%s of %s) %s Clean" % \
(mergecount, len(mymergelist), pkg_key)
emergelog(xterm_titles, msg, short_msg=short_msg)
retval = portage.doebuild(y, "clean", myroot,
pkgsettings, self.edebug, cleanup=1,
mydbapi=portdb, tree="porttree")
if retval != os.EX_OK:
return retval
if "--buildpkg" in self.myopts or issyspkg:
if issyspkg:
print ">>> This is a system package, " + \
"let's pack a rescue tarball."
msg = " === (%s of %s) Compiling/Packaging (%s::%s)" % \
(mergecount, len(mymergelist), pkg_key, y)
short_msg = "emerge: (%s of %s) %s Compile" % \
(mergecount, len(mymergelist), pkg_key)
emergelog(xterm_titles, msg, short_msg=short_msg)
retval = portage.doebuild(y, "package", myroot,
pkgsettings, self.edebug, mydbapi=portdb,
tree="porttree")
if retval != os.EX_OK:
return retval
if "--buildpkgonly" not in self.myopts:
bintree = self.trees[myroot]["bintree"]
bintree.inject(pkg_key)
mytbz2 = bintree.getname(pkg_key)
msg = " === (%s of %s) Merging (%s::%s)" % \
(mergecount, len(mymergelist), pkg_key, y)
short_msg = "emerge: (%s of %s) %s Merge" % \
(mergecount, len(mymergelist), pkg_key)
emergelog(xterm_titles, msg, short_msg=short_msg)
retval = portage.merge(pkgsettings["CATEGORY"],
pkgsettings["PF"], pkgsettings["D"],
os.path.join(pkgsettings["PORTAGE_BUILDDIR"],
"build-info"), myroot, pkgsettings,
myebuild=pkgsettings["EBUILD"],
mytree="porttree", mydbapi=portdb,
vartree=vartree, prev_mtimes=ldpath_mtimes)
if retval != os.EX_OK:
return retval
elif "noclean" not in pkgsettings.features:
portage.doebuild(y, "clean", myroot,
pkgsettings, self.edebug, mydbapi=portdb,
tree="porttree")
else:
msg = " === (%s of %s) Compiling/Merging (%s::%s)" % \
(mergecount, len(mymergelist), pkg_key, y)
short_msg = "emerge: (%s of %s) %s Compile" % \
(mergecount, len(mymergelist), pkg_key)
emergelog(xterm_titles, msg, short_msg=short_msg)
retval = portage.doebuild(y, "merge", myroot,
pkgsettings, self.edebug, vartree=vartree,
mydbapi=portdb, tree="porttree",
prev_mtimes=ldpath_mtimes)
if retval != os.EX_OK:
return retval
finally:
if builddir_lock:
portage_locks.unlockdir(builddir_lock)
elif x[0]=="binary":
#merge the tbz2
mytbz2 = self.trees[myroot]["bintree"].getname(pkg_key)
if self.trees[myroot]["bintree"].isremote(pkg_key):
short_msg = "emerge: ("+str(mergecount)+" of "+str(len(mymergelist))+") "+x[pkgindex]+" Fetch"
emergelog(xterm_titles, " --- ("+str(mergecount)+\
" of "+str(len(mymergelist))+\
") Fetching Binary ("+x[pkgindex]+\
"::"+mytbz2+")", short_msg=short_msg)
if not self.trees[myroot]["bintree"].gettbz2(pkg_key):
sys.exit(1)
if "--fetchonly" in self.myopts or \
"--fetch-all-uri" in self.myopts:
continue
short_msg = "emerge: ("+str(mergecount)+" of "+str(len(mymergelist))+") "+x[pkgindex]+" Merge Binary"
emergelog(xterm_titles, " === ("+str(mergecount)+\
" of "+str(len(mymergelist))+") Merging Binary ("+\
x[pkgindex]+"::"+mytbz2+")", short_msg=short_msg)
retval = portage.pkgmerge(mytbz2, x[1], pkgsettings,
mydbapi=bindb,
vartree=self.trees[myroot]["vartree"],
prev_mtimes=ldpath_mtimes)
if retval is None:
sys.exit(1)
#need to check for errors
if "--buildpkgonly" not in self.myopts:
self.trees[x[1]]["vartree"].inject(x[2])
myfavkey=portage.cpv_getkey(x[2])
if "--fetchonly" not in self.myopts and \
"--fetch-all-uri" not in self.myopts and \
myfavkey in favorites:
myfavs = portage.grabfile(os.path.join(myroot, portage.WORLD_FILE))
myfavdict=genericdict(myfavs)
#don't record if already in system profile or already recorded
if (not mysysdict.has_key(myfavkey)) and (not myfavdict.has_key(myfavkey)):
#we don't have a favorites entry for this package yet; add one
myfavdict[myfavkey]=myfavkey
print ">>> Recording",myfavkey,"in \"world\" favorites file..."
emergelog(xterm_titles, " === ("+\
str(mergecount)+" of "+\
str(len(mymergelist))+\
") Updating world file ("+x[pkgindex]+")")
portage.write_atomic(
os.path.join(myroot, portage.WORLD_FILE),
"\n".join(myfavdict.values()))
if "--pretend" not in self.myopts and \
"--fetchonly" not in self.myopts and \
"--fetch-all-uri" not in self.myopts:
# Clean the old package that we have merged over top of it.
if pkgsettings.get("AUTOCLEAN", "yes") == "yes":
xsplit=portage.pkgsplit(x[2])
emergelog(xterm_titles, " >>> AUTOCLEAN: " + xsplit[0])
retval = unmerge(pkgsettings, self.myopts, vartree,
"clean", [xsplit[0]], ldpath_mtimes)
if not retval:
emergelog(xterm_titles,
" --- AUTOCLEAN: Nothing unmerged.")
else:
portage.writemsg_stdout(colorize("WARN", "WARNING:")
+ " AUTOCLEAN is disabled. This can cause serious"
+ " problems due to overlapping packages.\n")
# Figure out if we need a restart.
mysplit=portage.pkgsplit(x[2])
if mysplit[0] == "sys-apps/portage" and x[1] == "/":
myver=mysplit[1]+"-"+mysplit[2]
if myver[-3:]=='-r0':
myver=myver[:-3]
if (myver != portage.VERSION) and \
"livecvsportage" not in self.settings.features:
if len(mymergelist) > mergecount:
emergelog(xterm_titles,
" ::: completed emerge ("+ \
str(mergecount)+" of "+ \
str(len(mymergelist))+") "+ \
x[2]+" to "+x[1])
emergelog(xterm_titles, " *** RESTARTING " + \
"emerge via exec() after change of " + \
"portage version.")
del mtimedb["resume"]["mergelist"][0]
mtimedb.commit()
portage.run_exitfuncs()
mynewargv=[sys.argv[0],"--resume"]
for arg in self.myopts:
if arg in bad_resume_opts:
continue
mynewargv.append(arg)
# priority only needs to be adjusted on the first run
os.environ["PORTAGE_NICENESS"] = "0"
os.execv(mynewargv[0], mynewargv)
if "--pretend" not in self.myopts and \
"--fetchonly" not in self.myopts and \
"--fetch-all-uri" not in self.myopts:
if "noclean" not in self.settings.features:
short_msg = "emerge: (%s of %s) %s Clean Post" % \
(mergecount, len(mymergelist), x[pkgindex])
emergelog(xterm_titles, (" === (%s of %s) " + \
"Post-Build Cleaning (%s::%s)") % \
(mergecount, len(mymergelist), x[pkgindex], y),
short_msg=short_msg)
emergelog(xterm_titles, " ::: completed emerge ("+\
str(mergecount)+" of "+str(len(mymergelist))+") "+\
x[2]+" to "+x[1])
# Unsafe for parallel merges
del mtimedb["resume"]["mergelist"][0]
# Commit after each merge so that --resume may still work in
# in the event that portage is not allowed to exit normally
# due to power failure, SIGKILL, etc...
mtimedb.commit()
if "--pretend" not in self.myopts:
emergelog(xterm_titles, " *** Finished. Cleaning up...")
# We're out of the loop... We're done. Delete the resume data.
if mtimedb.has_key("resume"):
del mtimedb["resume"]
mtimedb.commit()
#by doing an exit this way, --fetchonly can continue to try to
#fetch everything even if a particular download fails.
if "--fetchonly" in self.myopts or "--fetch-all-uri" in self.myopts:
if returnme:
print "\n\n!!! Some fetch errors were encountered. Please see above for details.\n\n"
sys.exit(returnme)
else:
sys.exit(0)
return os.EX_OK
def unmerge(settings, myopts, vartree, unmerge_action, unmerge_files,
ldpath_mtimes, raise_on_missing=True):
candidate_catpkgs=[]
global_unmerge=0
xterm_titles = "notitles" not in settings.features
realsyslist = getlist(settings, "system")
syslist = []
for x in realsyslist:
mycp = portage.dep_getkey(x)
if mycp in settings.getvirtuals():
providers = []
for provider in settings.getvirtuals()[mycp]:
if vartree.dbapi.match(provider):
providers.append(provider)
if len(providers) == 1:
syslist.extend(providers)
else:
syslist.append(mycp)
mysettings = portage.config(clone=settings)
if not unmerge_files or "world" in unmerge_files or "system" in unmerge_files:
if "unmerge"==unmerge_action:
print
print bold("emerge unmerge")+" can only be used with specific package names, not with "+bold("world")+" or"
print bold("system")+" targets."
print
return 0
else:
global_unmerge=1
localtree = vartree
# process all arguments and add all valid db entries to candidate_catpkgs
if global_unmerge:
if not unmerge_files or "world" in unmerge_files:
candidate_catpkgs.extend(localtree.getallnodes())
elif "system" in unmerge_files:
candidate_catpkgs.extend(getlist(settings, "system"))
else:
#we've got command-line arguments
if not unmerge_files:
print "\nNo packages to unmerge have been provided.\n"
return 0
for x in unmerge_files:
arg_parts=x.split('/')
if (x[0] not in [".","/"]) and (arg_parts[-1][-7:] != ".ebuild"):
#possible cat/pkg or dep; treat as such
candidate_catpkgs.append(x)
elif unmerge_action in ["prune","clean"]:
print "\n!!! Prune and clean do not accept individual ebuilds as arguments;\n skipping.\n"
continue
else:
# it appears that the user is specifying an installed ebuild and we're in "unmerge" mode, so it's
# ok.
if not os.path.exists(x):
print "\n!!! The path '"+x+"' doesn't exist.\n"
return 0
absx = os.path.abspath(x)
sp_absx = absx.split("/")
if sp_absx[-1][-7:] == ".ebuild":
del sp_absx[-1]
absx = string.join(sp_absx,"/")
sp_absx_len = len(sp_absx)
vdb_path = os.path.join(settings["ROOT"], portage.VDB_PATH)
vdb_len = len(vdb_path)
sp_vdb = vdb_path.split("/")
sp_vdb_len = len(sp_vdb)
if not os.path.exists(absx+"/CONTENTS"):
print "!!! Not a valid db dir: "+str(absx)
return 0
if sp_absx_len <= sp_vdb_len:
# The Path is shorter... so it can't be inside the vdb.
print sp_absx
print absx
print "\n!!!",x,"cannot be inside "+vdb_path+"; aborting.\n"
return 0
for idx in range(0,sp_vdb_len):
if (idx >= sp_absx_len) or (sp_vdb[idx] != sp_absx[idx]):
print sp_absx
print absx
print "\n!!!",x,"is not inside "+vdb_path+"; aborting.\n"
return 0
print "="+string.join(sp_absx[sp_vdb_len:],"/")
candidate_catpkgs.append("="+string.join(sp_absx[sp_vdb_len:],"/"))
newline=""
if (not "--quiet" in myopts):
newline="\n"
if settings["ROOT"] != "/":
print darkgreen(newline+">>> Using system located in ROOT tree "+settings["ROOT"])
if (("--pretend" in myopts) or ("--ask" in myopts)) and not ("--quiet" in myopts):
print darkgreen(newline+">>> These are the packages that would be unmerged:")
pkgmap={}
numselected=0
for x in candidate_catpkgs:
#cycle through all our candidate deps and determine what will and will not get unmerged
try:
mymatch=localtree.dep_match(x)
except KeyError:
mymatch=None
except ValueError, errpkgs:
print "\n\n!!! The short ebuild name \"" + x + "\" is ambiguous. Please specify"
print "!!! one of the following fully-qualified ebuild names instead:\n"
for i in errpkgs[0]:
print " " + green(i)
print
sys.exit(1)
if not mymatch and x[0] not in "<>=~":
#add a "=" if missing
mymatch=localtree.dep_match("="+x)
if not mymatch:
if raise_on_missing:
raise portage_exception.PackageNotFound(x)
else:
portage.writemsg("\n--- Couldn't find '%s' to %s.\n" % \
(x, unmerge_action), noiselevel=-1)
continue
mykey = portage.key_expand(
portage.dep_getkey(
mymatch[0]), mydb=vartree.dbapi, settings=settings)
if not pkgmap.has_key(mykey):
pkgmap[mykey]={"protected":[], "selected":[], "omitted":[] }
if unmerge_action=="unmerge":
for y in mymatch:
if y not in pkgmap[mykey]["selected"]:
pkgmap[mykey]["selected"].append(y)
numselected=numselected+len(mymatch)
else:
#unmerge_action in ["prune", clean"]
slotmap={}
for mypkg in mymatch:
if unmerge_action=="clean":
myslot=localtree.getslot(mypkg)
else:
#since we're pruning, we don't care about slots and put all the pkgs in together
myslot=0
if not slotmap.has_key(myslot):
slotmap[myslot]={}
slotmap[myslot][localtree.dbapi.cpv_counter(mypkg)]=mypkg
for myslot in slotmap.keys():
counterkeys=slotmap[myslot].keys()
counterkeys.sort()
if not counterkeys:
continue
counterkeys.sort()
pkgmap[mykey]["protected"].append(slotmap[myslot][counterkeys[-1]])
del counterkeys[-1]
#be pretty and get them in order of merge:
for ckey in counterkeys:
pkgmap[mykey]["selected"].append(slotmap[myslot][ckey])
numselected=numselected+1
#ok, now the last-merged package is protected, and the rest are selected
if global_unmerge and not numselected:
print "\n>>> No outdated packages were found on your system.\n"
return 0
if not numselected:
print "\n>>> No packages selected for removal by",unmerge_action+".\n"
return 0
for x in pkgmap.keys():
for y in localtree.dep_match(x):
if y not in pkgmap[x]["omitted"] and \
y not in pkgmap[x]["selected"] and \
y not in pkgmap[x]["protected"]:
pkgmap[x]["omitted"].append(y)
if global_unmerge and not pkgmap[x]["selected"]:
#avoid cluttering the preview printout with stuff that isn't getting unmerged
continue
if not (pkgmap[x]["protected"] or pkgmap[x]["omitted"]) and (x in syslist):
print colorize("BAD","\a\n\n!!! '%s' is part of your system profile." % x)
print colorize("WARN","\a!!! Unmerging it may be damaging to your system.\n")
if "--pretend" not in myopts and "--ask" not in myopts:
countdown(int(settings["EMERGE_WARNING_DELAY"]),
colorize("UNMERGE_WARN", "Press Ctrl-C to Stop"))
print "\n "+white(x)
for mytype in ["selected","protected","omitted"]:
portage.writemsg_stdout((mytype + ": ").rjust(14), noiselevel=-1)
if pkgmap[x