code
stringlengths
1
1.72M
language
stringclasses
1 value
#!/usr/bin/env python from distutils.core import setup setup( name='flagpoll', version='0.8.2', description='Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software.', author='Daniel E. Shipton', author_email='dshipton@infiscape.com', license='GPL', url='https://realityforge.vrsource.org/view/FlagPoll/WebHome', download_url='https://realityforge.vrsource.org/view/FlagPoll/FlagpollDownloads', scripts=['flagpoll'], long_description = "Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software. Think of it as the rpm of software development. It enables developers total control over which packages, versions, architectures, etc. that they want to use meta-data from.", data_files=[('share/flagpoll', ['flagpoll.fpc']), ('share/man/man1', ['flagpoll.1']), ('share/aclocal', ['flagpoll.m4'])] )
Python
#!/usr/bin/env python # ----------------------------------------------------------------- # # Flag Poll: A tool to extract flags from installed applications # for compiling, settting variables, etc. # # Original Authors: # Daniel E. Shipton <dshipton@gmail.com> # # Flag Poll is Copyright (C) 2006 by Daniel E. Shipton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to: # Free SoftwareFoundation, Inc. # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # # ----------------------------------------------------------------- """Makes a flagpole .fpc file from user input. v0.9 coded by Jeff Groves""" import os import sys import getopt ##String prompts for the input varPrompt = """Convience variables (one 'var_name= var_definition' per line,""" + \ """ empty line when done)""" namePrompt = "Formal Name" descriptionPrompt = "Description" urlPrompt = "URL" providesPrompt = "One or more names to look package up by: (Provides)" versionPrompt = "Version (x.y.z)" architecturePrompt = "Architecture" requirePrompt = "Requires" libPrompt = "Linker Flags (-lfoo -L/usr/lib)" staticLibPrompt = "Static Linking Flags/Libs (extra private libs)" compileFlagsPrompt = "Compile/Include Flags (-I/usr -fpge -O2)" fileNamePrompt = "FPC File's Name" def usage(): """Prints a list of acceptable arguments for fpcmaker.py.""" print """ Fpcmaker.py Options: -n, --name= : Sets %s -d, --description= : Sets %s -u, --url= : Sets %s -p, --provides= : Sets %s -v, --version= : Sets %s -a, --architecture= : Sets %s -r, --requires= : Sets %s -l, --libs= : Sets %s -c, --cflags= : Sets %s -s, --static= : Sets %s -f, --file= : Sets %s """ %(namePrompt, descriptionPrompt, urlPrompt, providesPrompt, versionPrompt, architecturePrompt, requirePrompt, libPrompt, compileFlagsPrompt, staticLibPrompt, fileNamePrompt) return def checkFileName(fileName): """Checks if the fpc file name's blank, contains slashes, or exists.""" nameCleared = False writeFile = True confirms = ['y', 'Y', 'yes', 'Yes'] ##Loops until the name clears or writing the file's aborted. while(not nameCleared and writeFile): ##If it's blank, give the option of aborting the program. if fileName == "": choice = raw_input("Do you want to abort writing the" + " .fpc file? (Y/N): ") if choice not in confirms: fileName = raw_input("Please enter a different name for the" + " .fpc file: ") else: writeFile = False ##If it contains slashes, ask for another name. elif '/' in fileName or '\\' in fileName: print "I can't write to %s because it contains slashes."%(fileName) fileName = raw_input("Please enter a different name for the" + " .fpc file: ") ##If it already exists, ask if they want to overwrite. ##If not, ask for another name. elif os.path.exists(fileName): choice = raw_input("The file %s already exists." %(fileName) + " Do you want to overwrite it? (Y/N): ") if choice not in confirms: fileName = raw_input("Please enter a different name for the" + " .fpc file: ") else: nameCleared = True else: nameCleared = True return [fileName, writeFile] ##Booleans for whether that argument was sent in the command line varSet = False providesSet = False nameSet = False descriptionSet = False urlSet = False architectureSet = False versionSet = False requiresSet = False libsSet = False compileFlagsSet = False staticLibSet = False fileNameSet = False ##Get the options & arguments sent. arguments = sys.argv[1:] try: opts, args = getopt.getopt(arguments, "p:n:u:d:a:r:v:l:c:s:f:", ["provides=", "name=", "url=", "description=", "architecture=", "requires=", "version=", "libs=", "cflags=", "static=", "file="]) ##Send them usage info if they enter a wrong argument except getopt.GetoptError: usage() sys.exit(2) for opt, arg in opts: if opt in ('-p', '--provides'): providesSet = True provides = arg elif opt in ('-n', '--name'): nameSet = True name = arg elif opt in ('-v', '--version'): versionSet = True version = arg elif opt in ('-u', '--url'): urlSet = True url = arg elif opt in ('-d', '--description'): descriptionSet = True description = arg elif opt in ('-a', '--architecture'): architectureSet = True architecture = arg elif opt in ('-r', '--requires'): requiresSet = True requires = arg elif opt in ('-l', '--libs'): libsSet = True libs = arg elif opt in ('-c', '--cflags'): compileFlagsSet = True compileFlags = arg elif opt in ('-s', '--static'): staticLibSet = True staticLib = arg elif opt in ('-f', '--file'): fileNameSet = True fileName = arg ##Grab any input not passed in the arguments from the user. if not varSet: varLine = None variables = "" print "%s:" %(varPrompt) while(varLine != ""): varLine = raw_input("") variables = variables + "%s\n" %(varLine) if not nameSet: name = raw_input("%s: " %(namePrompt)) if not descriptionSet: description = raw_input("%s: " %(descriptionPrompt)) if not urlSet: url = raw_input("%s: " %(urlPrompt)) if not versionSet: version = raw_input("%s: " %(versionPrompt)) if not providesSet: provides = raw_input("%s: " %(providesPrompt)) if not requiresSet: requires = raw_input("%s: " %(requirePrompt)) if not architectureSet: architecture = raw_input("%s: " %(architecturePrompt)) if not libsSet: libs = raw_input("%s: " %(libPrompt)) if not staticLibSet: staticLib = raw_input("%s: " %(staticLibPrompt)) if not compileFlagsSet: compileFlags = raw_input("%s: " %(compileFlagsPrompt)) if not fileNameSet: fileName = raw_input("%s: " %(fileNamePrompt)) ##Check the file's name. fileName, writeFile = checkFileName(fileName) ##If they chose not to overwrite, write the file. if writeFile: fpc = open(fileName, 'w') fpc.write("%s" %(variables)) fpc.write("Name: %s\n" %(name)) fpc.write("Description: %s\n" %(description)) fpc.write("URL: %s\n" %(url)) fpc.write("Version: %s\n" %(version)) fpc.write("Provides: %s\n" %(provides)) fpc.write("Requires: %s\n" %(requires)) fpc.write("Arch: %s\n" %(architecture)) fpc.write("Libs: %s\n" %(libs)) fpc.write("Libs.private: %s\n" %(staticLib)) fpc.write("Cflags: %s\n" %(compileFlags)) fpc.close() ##TESTER: Print the file out. fpc = open(fileName, 'r') ##TESTER print fpc.read() ##TESTER fpc.close ##TESTER
Python
#!/usr/bin/env python # ----------------------------------------------------------------- # # Flagpoll: A tool to extract flags from installed applications # for compiling, settting variables, etc. # # Original Authors: # Daniel E. Shipton <dshipton@gmail.com> # # Flagpoll is Copyright (C) 2006-2007 by Daniel E. Shipton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to: # Free SoftwareFoundation, Inc. # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # # ----------------------------------------------------------------- import sys, os, glob, os.path, copy, platform pj = os.path.join #################################################################### # SNAGGED FROM PYTHON 2.4 for versions under 2.4 #################################################################### import re as _re class _multimap: """Helper class for combining multiple mappings. Used by .{safe_,}substitute() to combine the mapping and keyword arguments. """ def __init__(self, primary, secondary): self._primary = primary self._secondary = secondary def __getitem__(self, key): try: return self._primary[key] except KeyError: return self._secondary[key] class _TemplateMetaclass(type): pattern = r""" %(delim)s(?: (?P<escaped>%(delim)s) | # Escape sequence of two delimiters (?P<named>%(id)s) | # delimiter and a Python identifier {(?P<braced>%(id)s)} | # delimiter and a braced identifier (?P<invalid>) # Other ill-formed delimiter exprs ) """ def __init__(cls, name, bases, dct): super(_TemplateMetaclass, cls).__init__(name, bases, dct) if 'pattern' in dct: pattern = cls.pattern else: pattern = _TemplateMetaclass.pattern % { 'delim' : _re.escape(cls.delimiter), 'id' : cls.idpattern, } cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE) class Template: """A string class for supporting $-substitutions.""" __metaclass__ = _TemplateMetaclass delimiter = '$' idpattern = r'[_a-z][_a-z0-9]*' def __init__(self, template): self.template = template # Search for $$, $identifier, ${identifier}, and any bare $'s def _invalid(self, mo): i = mo.start('invalid') lines = self.template[:i].splitlines(True) if not lines: colno = 1 lineno = 1 else: colno = i - len(''.join(lines[:-1])) lineno = len(lines) raise ValueError('Invalid placeholder in string: line %d, col %d' % (lineno, colno)) def substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): # Check the most common path first. named = mo.group('named') or mo.group('braced') if named is not None: val = mapping[named] # We use this idiom instead of str() because the latter will # fail if val is a Unicode containing non-ASCII characters. return '%s' % val if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: self._invalid(mo) raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) def safe_substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): named = mo.group('named') if named is not None: try: # We use this idiom instead of str() because the latter # will fail if val is a Unicode containing non-ASCII return '%s' % mapping[named] except KeyError: return self.delimiter + named braced = mo.group('braced') if braced is not None: try: return '%s' % mapping[braced] except KeyError: return self.delimiter + '{' + braced + '}' if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: return self.delimiter raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) #################################################################### # End Snagging #################################################################### class Utils: # Holds collection of small utility functions EXTRA_FLAGPOLL_SEARCH_PATHS = "" EXTRA_FLAGPOLL_FILES = "" path_list_cache = None # Cache of found path lists. (only calcuate once) KEEP_DUPS = False FLAGPOLL_LIST_OF_POSSIBLE_ERRORS = [] def addPossibleError(pos_err): Utils.FLAGPOLL_LIST_OF_POSSIBLE_ERRORS.append(pos_err) addPossibleError = staticmethod(addPossibleError) def getPossibleErrors(): return Utils.stripDupInList(Utils.FLAGPOLL_LIST_OF_POSSIBLE_ERRORS) getPossibleErrors = staticmethod(getPossibleErrors) def getFlagpollVersion(): FLAGPOLL_MAJOR_VERSION = 0 FLAGPOLL_MINOR_VERSION = 8 FLAGPOLL_PATCH_VERSION = 2 return ( FLAGPOLL_MAJOR_VERSION, FLAGPOLL_MINOR_VERSION, FLAGPOLL_PATCH_VERSION ) getFlagpollVersion = staticmethod(getFlagpollVersion) def getPathList(): if None != Utils.path_list_cache: return Utils.path_list_cache #TODO: expand LD_LIBRARY_PATH to 64/32/etc??? pkg_cfg_dir = [] flg_cfg_dir = [] ld_path = [] if os.environ.has_key("PKG_CONFIG_PATH"): pkg_cfg_dir = os.environ["PKG_CONFIG_PATH"].split(os.pathsep) if os.environ.has_key("FLAGPOLL_PATH"): flg_cfg_dir = os.environ["FLAGPOLL_PATH"].split(os.pathsep) ld_dirs = ['LD_LIBRARY_PATH', 'DYLD_LIBRARY_PATH'] for d in ld_dirs: if os.environ.has_key(d): cur_path = os.environ[d].split(os.pathsep) ld_path_pkg = [pj(p,'pkgconfig') for p in cur_path] ld_path_flg = [pj(p,'flagpoll') for p in cur_path] ld_path.extend(ld_path_pkg) ld_path.extend(ld_path_flg) extra_paths = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS.split(os.pathsep) path_list = ["/usr/lib64/pkgconfig", "/usr/lib/pkgconfig", "/usr/share/pkgconfig", "/usr/lib64/flagpoll", "/usr/lib/flagpoll", "/usr/share/flagpoll"] path_list.extend(pkg_cfg_dir) path_list.extend(flg_cfg_dir) path_list.extend(extra_paths) path_list.extend(ld_path) flagDBG().out(flagDBG.VERBOSE, "Utils.getPathList", "Potential path list: " + str(path_list)) path_list = [p for p in path_list if os.path.exists(p)] flagDBG().out(flagDBG.INFO, "Utils.getPathList", "Using path list: " + str(path_list)) Utils.path_list_cache = path_list return path_list getPathList = staticmethod(getPathList) def getFileList(): flist = Utils.EXTRA_FLAGPOLL_FILES.split(":") filelist = [] for f in flist: if os.path.isfile(f): filelist.append(f) return filelist getFileList = staticmethod(getFileList) def setKeepDups(keep_dups): Utils.KEEP_DUPS = keep_dups setKeepDups = staticmethod(setKeepDups) def stripDupInList(gen_list): new_list = [] for item in gen_list: item = item.strip() if Utils.KEEP_DUPS: if len(item) > 0: new_list.append(item) continue if item not in new_list: if len(item) > 0: new_list.append(item) return new_list stripDupInList = staticmethod(stripDupInList) def stripDupLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] dir_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-L") or flg.startswith("-R"): dir_list.append(flg) else: lib_list.append(flg) new_list = dir_list + lib_list return Utils.stripDupInList(new_list) stripDupLinkerFlags = staticmethod(stripDupLinkerFlags) def stripDupIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] extra_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-I"): inc_list.append(flg) else: extra_list.append(flg) extra_list.sort() new_list = inc_list + extra_list return Utils.stripDupInList(new_list) stripDupIncludeFlags = staticmethod(stripDupIncludeFlags) def cflagsOnlyDirIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-I"): inc_list.append(flg) return Utils.stripDupInList(inc_list) cflagsOnlyDirIncludeFlags = staticmethod(cflagsOnlyDirIncludeFlags) def cflagsOnlyOtherIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though extra_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if not flg.startswith("-I"): extra_list.append(flg) return Utils.stripDupInList(extra_list) cflagsOnlyOtherIncludeFlags = staticmethod(cflagsOnlyOtherIncludeFlags) def libsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-l"): lib_list.append(flg) return Utils.stripDupInList(lib_list) libsOnlyLinkerFlags = staticmethod(libsOnlyLinkerFlags) def libsOnlyOtherLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though other_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if not flg.startswith("-l") and not flg.startswith("-L") and not flg.startswith("-R"): other_list.append(flg) return Utils.stripDupInList(other_list) libsOnlyOtherLinkerFlags = staticmethod(libsOnlyOtherLinkerFlags) def libDirsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though dir_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-L") or flg.startswith("-R"): dir_list.append(flg) return Utils.stripDupInList(dir_list) libDirsOnlyLinkerFlags = staticmethod(libDirsOnlyLinkerFlags) def printList(gen_list): list_string = "" for item in gen_list: if len(item) > 0: list_string += str(item) list_string += " " print list_string.strip() printList = staticmethod(printList) def parsePcFile(filename): lines = open(filename).readlines() fvars = {} fvars["FlagpollFilename"] = filename lokals = {} lokals["fp_file_cwd"] = str(filename[:- ((len(os.path.basename(filename) ) + 1))]) lines.append("prefix: ${prefix}") append_next = False append_dict = {} append_key = "" for line in lines: line = line.strip() if not line: continue if append_next: tmp = append_dict[append_key] tmp = tmp[:-1] + " " + line append_dict[append_key] = tmp if tmp[-1:] == "\\": append_next = True else: append_next = False continue if line.startswith("#"): continue eq_pos = line.find('=') col_pos = line.find(':') if eq_pos < col_pos and eq_pos != -1 or col_pos == -1 and eq_pos != -1: # local variable name, val = line.split('=', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(lokals) except ValueError: flagDBG().out(flagDBG.WARN, "PkgInfo.parse", "%s has an invalid metadata file" % filename) lokals[name] = val if val[-1:] == "\\": append_next = True append_dict = lokals append_key = name continue if col_pos < eq_pos and col_pos != -1 or eq_pos == -1 and col_pos != -1: # exported variable name, val = line.split(':', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(lokals) except ValueError: flagDBG().out(flagDBG.ERROR, "PkgInfo.parse", "%s has an invalid metadata file" % filename) fvars[name] = val if val[-1:] == "\\": append_next = True append_dict = fvars append_key = name return fvars parsePcFile = staticmethod(parsePcFile) class flagDBG(object): # Logging class is really easy to use # Levels: # 0 - VERBOSE # 1 - INFO # 2 - WARN # 3 - ERROR VERBOSE = 0 INFO = 1 WARN = 2 ERROR = 3 __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if flagDBG.__initialized: return flagDBG.__initialized = True self.mLevel = self.WARN self.mLevelList = ["VERBOSE", "INFO", "WARN", "ERROR"] def setLevel(self, level): if level <= 3: self.mLevel = level def out(self, level, obj, message): if level == self.ERROR: if self.mLevel == self.VERBOSE: print self.mLevelList[level] + ":" + str(obj) + ": " + str(message) else: sys.stderr.write(self.mLevelList[level] + ": " + str(message) + "\n") errs = Utils.getPossibleErrors() if len(errs) > 0: sys.stderr.write("Possible culprits:\n") for pos_err in errs: sys.stderr.write( " " + str(pos_err) + "\n" ) sys.exit(1) if level >= self.mLevel: print self.mLevelList[level] + ":" + str(obj) + ": " + str(message) class DepResolutionSystem(object): """ You add PkgAgents with Filters into system and call resolve() you can check for succes by depsSatisfied() and get the list of packages that work back by calling getPackages() """ __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if DepResolutionSystem.__initialized: return DepResolutionSystem.__initialized = True self.mResolveAgents = [] self.mAgentDict = {} self.mFilters = [] self.mResolveAgentFilters = [] self.mInvalidPackageList = [] self.mSatisfied = False self.mAgentChangeList = [] # list of those responsible for adding Filters # to agents in higher in the chain than them # these are the first agents to ask that they pick # the next best package of them self.mAgentsVisitedList = [] # list of Agents that have been visited self.mResolvedPackageList = [] # list that is generated when deps are satified self.mCheckPrivateRequires = False self.mMadeDependList = False def getFilters(self): return self.mFilters def addFilter(self, filter): self.mFilters.append(filter) def addResolveAgentFilter(self, filter): self.mResolveAgentFilters.append(filter) def makeRequireFilter(self, requires): arch_list = [] arch_list.append("no_arch") arch_list.append("") if platform.system() == "Linux": if requires == "64": arch_list.append("x86_64") if requires == "32": arch_list.append("i386") arch_list.append("i486") arch_list.append("i586") arch_list.append("i686") if platform.system() == "Darwin": if requires == "64": arch_list.append("ppc64") if requires == "32": arch_list.append("ppc") if platform.system().startswith("IRIX"): arch_list.append(requires) new_filter = Filter("Arch", lambda x,v=arch_list: x in v) self.addFilter(new_filter) def createAgent(self, name): if self.checkAgentExists(name): return self.getAgent(name) else: agent = PkgAgent(name) flagDBG().out(flagDBG.INFO, "DepResSys.createAgent", "Adding %s" % name) self.addNewAgent(agent) return agent def createResolveAgent(self, name): if self.checkAgentExists(name): return self.getAgent(name) else: agent = PkgAgent(name) flagDBG().out(flagDBG.INFO, "DepResSys.createResolveAgent", "Adding %s" % name) self.addResolveAgent(agent) return agent def setPrivateRequires( self, req ): self.mCheckPrivateRequires = req def checkPrivateRequires(self): return self.mCheckPrivateRequires def checkAgentExists(self, name): return self.mAgentDict.has_key(name) def getAgent(self, name): if self.mAgentDict.has_key(name): return self.mAgentDict[name] else: flagDBG().out(flagDBG.ERROR, "DepResSys.getAgent", "Agent %s does not exist" % name) def addNewAgent(self, agent): if not self.checkAgentExists(agent): self.mAgentDict[agent.getName()] = agent def addResolveAgent(self, agent): if agent not in self.mResolveAgents: self.mResolveAgents.append(agent) for filt in self.mResolveAgentFilters: agent.addFilter(filt) def isSatisfied(self): return self.mSatisfied def updateResolvedPackages(self): pkg_list = [] agent_list = [] for agent in self.mResolveAgents: list_of_pkgs = agent.getCurrentPackageList(agent_list) pkg_list.extend(list_of_pkgs) self.mResolvedPackageList = pkg_list def getPackages(self): flagDBG().out(flagDBG.INFO, "DepResSys.getPackages", "Generating list of valid packages ") #str([pkg.getCurrentPackage.getName() for pkg in self.mResolvedPackageList])) # If this comes back empty then there isn't a valid set of packages to use self.updateResolvedPackages() return self.mResolvedPackageList def checkFiltersChanged(self): list_to_use = [] return True in [pkg.filtersChanged(list_to_use) for pkg in self.mResolveAgents] def resolveHelper(self): self.resolveAgentsChanged = True while self.resolveAgentsChanged: for agent in self.mResolveAgents: flagDBG().out(flagDBG.INFO, "DepResSys.resolveHelper", "Updating " + agent.getName()) agent.update(self.mAgentsVisitedList, self.mAgentChangeList) self.resolveAgentsChanged = self.checkFiltersChanged() # Ask mResolveAgents if they are done(they ask sub people) unless they are # really above you in the walk # If there were changes...run update on mResolveAgents again # at the end ask for pkglist..if it comes back empty then we don't # have a usable configuration for those packages def resolveDeps(self): self.resolveHelper() if not self.mMadeDependList: for agent in self.mResolveAgents: agent.makeDependList() self.mMadeDependList = True self.updateResolvedPackages() # Check if the first round through we found something # Otherwise we need to start removing packages that aren't viable # during the loop self.mSatisfied = (len(self.mResolvedPackageList) != 0) # remove top of packages that added Filters. # then move on to resolving again # remove more if neccesary agentChangeNumber = 0 while not self.mResolvedPackageList: if(self.mAgentChangeList[agentChangeNumber]): if self.mAgentChangeList[agentChangeNumber] in self.mInvalidPackageList: agentChangeNumber += 1 else: if(self.mAgentChangeList[agentChangeNumber].getViablePackages()): flagDBG().out(flagDBG.INFO, "DepResSys.resolveDeps", "Removing bad pkg from " + self.mAgentChangeList[agentChangeNumber].getName()) self.mInvalidPackageList.append(self.mAgentChangeList[agentChangeNumber].removeCurrentPackage()) else: flagDBG().out(flagDBG.INFO, "DepResSys.resolveDeps", "No combinations.. Resetting " + self.mAgentChangeList[agentChangeNumber].getName()) self.mAgentChangeList[agentChangeNumber].reset() agentChangeNumber += 1 self.resolveHelper() self.updateResolvedPackages() self.mSatisfied = (len(self.mResolvedPackageList) != 0) return class PkgAgent: """ Agent that keeps track of the versions for a package given some filters and the addition of Filters """ # Makes a PkgAgent that finds its current package with the version reqs def __init__(self, name): if DepResolutionSystem().checkAgentExists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "Package Agent %s already exists" % self.mName) self.mName = name flagDBG().out(flagDBG.INFO, "PkgAgent", "Creating:" + str(self.mName)) if not PkgDB().exists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "No info for package: %s" % self.mName) #XXX Doesn't keep filters added for a redo... DepResolutionSystem().addNewAgent(self) self.mFilterList = [] self.mFilterList.extend(DepResolutionSystem().getFilters()) self.mBasePackageList = PkgDB().getPkgInfos(name) self.mBasePackageList.sort(lambda lhs, rhs: cmp(rhs.getVariable('Version'), lhs.getVariable('Version'))) for filt in self.mFilterList: self.mBasePackageList = filt.filter(self.mBasePackageList) if len(self.mBasePackageList) == 0: flagDBG().out(flagDBG.ERROR, "PkgAgent", "No viable packages for: %s" % self.mName) self.mViablePackageList = copy.deepcopy(self.mBasePackageList) if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mFiltersChanged = True self.mCheckDepends = True self.mAgentDependList = [] def getName(self): return self.mName def setCheckDepends(self, tf): self.mCheckDepends = tf #Filter("Version", lambda x: x == "4.5") def makeDependList(self): if not self.mCheckDepends: self.mAgentDependList = [] return dep_list = [] if self.mCurrentPackage: req_string = self.mCurrentPackage.getVariable("Requires") if DepResolutionSystem().checkPrivateRequires(): req_string = req_string + " " + self.mCurrentPackage.getVariable("Requires.private") req_string = req_string.strip() if req_string == "": return req_string = req_string.replace(',', ' ') req_string = req_string.replace('(', ' ') req_string = req_string.replace(')', ' ') space_req_string_list = req_string.split(' ') req_string_list = [] for entry in space_req_string_list: if len(entry) > 0: req_string_list.append(entry) i = 0 flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList", self.mCurrentPackage.getName() + " requires: " + str(req_string_list)) while len(req_string_list) > i: if PkgDB().exists(req_string_list[i]): new_filter = [] new_agent = DepResolutionSystem().createAgent(req_string_list[i]) if len(req_string_list) > i+1: if req_string_list[i+1] == "=": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x == v) elif req_string_list[i+1] == "<=": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x <= v) elif req_string_list[i+1] == ">=": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x >= v) elif req_string_list[i+1] == ">": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x > v) elif req_string_list[i+1] == "<": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x < v) else: i += 1 else: i += 1 dep_list.append(new_agent) if new_filter: i+=3 new_agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "PkgAgent.makeDependList", "Package %s depends on %s but does not seem to be installed." % (self.mName, str(req_string_list[i]))) flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList", str(self.mName) + " : List is:" + str([pkg.getName() for pkg in dep_list])) self.mAgentDependList = dep_list def filtersChanged(self, packageList): tf_list = [self.mFiltersChanged] if self.mName not in packageList: packageList.append(self.mName) for pkg in self.mAgentDependList: tf_list.append(pkg.filtersChanged(packageList)) return True in tf_list def getCurrentPackageList(self, packageList): pkgs = [] if self.mName not in packageList: flagDBG().out(flagDBG.INFO, "PkgAgent.getCurrentPackageList", "Package: %s" % self.mName) pkgs.append(self.mCurrentPackage) packageList.append(self.mName) # Make depend list if we are supposed to self.updateFilters() self.makeDependList() for pkg in self.mAgentDependList: pkgs.extend(pkg.getCurrentPackageList(packageList)) return pkgs # current pkginfo for me def getCurrentPkgInfo(self): return self.mCurrentPackage # Someone else usually places these on me # I keep track of those separately def addFilter(self, filter): flagDBG().out(flagDBG.INFO, "PkgAgent.addFilter", "Filter %s" % self.mName + " on %s." % filter.getVarName()) self.mFiltersChanged = True self.mFilterList.append(filter) def removeCurrentPackage(self): flagDBG().out(flagDBG.INFO, "PkgAgent.removeCurrentPackage", "Removing current package of %s" % self.mName) if self.mViablePackageList: ret_val = self.mViablePackageList[0] in self.mBasePackageList del self.mViablePackageList[0] if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] return ret_val def update(self, agentVisitedList, agentChangeList): flagDBG().out(flagDBG.INFO, "PkgAgent.update", "%s" % self.mName) if self.mName in agentVisitedList: return agentVisitedList.append(self.mName) if self.mFiltersChanged: self.mFiltersChanged = False self.updateFilters() # TODO: checkFilters and add them # if a pkg is in visitedList then add yourself to agentChangeList for pkg in self.mAgentDependList: pkg.update(agentVisitedList, agentChangeList) return def updateFilters(self): for filt in self.mFilterList: self.mViablePackageList = filt.filter(self.mViablePackageList) flagDBG().out(flagDBG.INFO, "PkgAgent.updateFilters", "%s has " % self.mName + str(len(self.mViablePackageList)) + " left") if len(self.mViablePackageList) > 0: self.mCurrentPackage = self.mViablePackageList[0] else: for f in self.mFilterList: Utils.addPossibleError(str(self.mName) + " -> " + str(f.getVarName())) self.mCurrentPackage = [] def reset(self): flagDBG().out(flagDBG.INFO, "PkgAgent.reset", "Resetting package: %s" % self.mName) self.mViablePackageList = self.mBasePackageList if self.mViablePackageList: self.mCurrentPacakge = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mFilterList = DepResolutionSystem().getFilters() self.mAgentDependList = [] self.mFiltersChanged = True return class Filter: """ A single Filter that knows how to filter the list it recieves Will be inheireted....?..? """ def __init__(self, variableName, testCallable): self.mVarName = variableName self.mTestCallable = testCallable def getVarName(self): return self.mVarName def filter(self, pkg_info_list): ret_pkg_list = [] # Filter first for pkg in pkg_info_list: var = pkg.getVariable(self.mVarName) if self.mTestCallable(var): flagDBG().out(flagDBG.INFO, "Filter", "Passed: %s:" % pkg.getName() + " %s is " % self.mVarName + str(var)) ret_pkg_list.append(pkg) else: flagDBG().out(flagDBG.INFO, "Filter", "Failed: %s:" % pkg.getName() + " %s is " % self.mVarName + str(var)) # Now sort ret_pkg_list.sort(lambda lhs, rhs: cmp(rhs.getVariable(self.mVarName), lhs.getVariable(self.mVarName))) return ret_pkg_list #requires: qt == 4.5 #Filter("Version", lambda x: x <= "4.5") #Filter("Version", lambda x: x <= "4.5") class PkgDB(object): """ Holds all the neccesary information to evaluate itself when needed. Is in charge of holding a list of PkgInfo's that contain info about the package. """ __initialized = False def __init__(self): if self.__initialized: return self.__initialized = True self.mPkgInfos = {} # {pkg_name: List of package infos} self.populatePkgInfoDBPcFiles() self.populatePkgInfoDBFpcFiles() def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def printAllPackages(self): list_of_package_names = [] for pkg in self.mPkgInfos: list_of_package_names.append(pkg) for name in list_of_package_names: print name sys.exit(0) def getVariables(self, name, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariable", "Finding " + str(variable_list) + " in " + str(name)) ret_list = [] for var in variable_list: if self.mPkgInfos.has_key(name): ret_list.extend(self.mPkgInfos[name][0].getVariable(var)) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariable", "Package %s not found." % name) return ret_list def checkPackage(self, name): flagDBG().out(flagDBG.INFO, "PkgDB.checkPackage", "Finding " + str(name)) if self.mPkgInfos.has_key(name): return True else: flagDBG().out(flagDBG.ERROR, "PkgDB.CheckPackage", "Package %s not found." % name) return False def getVariablesAndDeps(self, pkg_list, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariablesAndDeps", "Finding " + str(variable_list) + " in " + str(pkg_list)) if DepResolutionSystem().checkPrivateRequires(): temp_var_list = [] for var in variable_list: temp_var_list.append(var.join(".private")) variable_list = variable_list + temp_var_list for name in pkg_list: if self.mPkgInfos.has_key(name): agent = DepResolutionSystem().createAgent(name) DepResolutionSystem().addResolveAgent(agent) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariablesAndDeps", "Package %s not found." % name) DepResolutionSystem().resolveDeps() pkgs = DepResolutionSystem().getPackages() var_list = [] for pkg in pkgs: if pkg: for var in variable_list: var_list.extend(pkg.getVariable(var).split(' ')) return var_list def getPkgInfos(self, name): if self.mPkgInfos.has_key(name): return self.mPkgInfos[name] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getPkgInfos", "Package %s not found." % name) def exists(self, name): return self.mPkgInfos.has_key(name) def getInfo(self, name): if self.mPkgInfos.has_key(name): return [pkg.getInfo() for pkg in self.mPkgInfos[name]] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getInfo", "Package %s not found." % name) def buildPcFileDict(self): """ Builds up a dictionary of {name: list of files for name} """ pc_dict = {} for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.pc")) # List of .pc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these pc files: %s" % str(glob_list)) for g in glob_list: # Get key name and add file to value list in dictionary key = os.path.basename(g)[:-3] # Strip .pc off the filename...rstrip no worky pc_dict.setdefault(key, []).append(g) for f in Utils.getFileList(): if f.endswith(".pc"): key = os.path.basename(f)[:-3] # Strip .pc off the filename...rstrip no worky pc_dict.setdefault(key, []).append(f) return pc_dict # { "key", [ "list", "of", "corresponding", "pc", "files"] } def populatePkgInfoDBPcFiles(self): dict_to_pop_from = self.buildPcFileDict() for (pkg,files) in dict_to_pop_from.iteritems(): for f in files: self.mPkgInfos.setdefault(pkg,[]).append(PkgInfo(pkg, f, "pc")) def buildFpcFileList(self): """ Builds up a dictionary of {name: list of files for name} """ file_list = [] for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.fpc")) # List of .fpc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these fpc files: %s" % str(glob_list)) for g in glob_list: file_list.append(g) for f in Utils.getFileList(): if f.endswith(".fpc"): file_list.append(f) return file_list # [ "list", "of", "fpc", "files"] def populatePkgInfoDBFpcFiles(self): list_to_add = self.buildFpcFileList() for filename in list_to_add: var_dict = Utils.parsePcFile(filename) if not var_dict.has_key("Provides"): flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Provides" % str(filename)) continue if not var_dict.has_key("Arch"): flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Arch" % str(filename)) continue provides_string = var_dict["Provides"] provides_string = provides_string.replace(',', ' ') provides_string = provides_string.replace('(', ' ') provides_string = provides_string.replace(')', ' ') for key in provides_string.split(" "): if len(key) > 0: self.mPkgInfos.setdefault(key, []).append(PkgInfo(key, filename, "fpc", var_dict)) class PkgInfo: """ Holds the information for a package file on the system. These however are evaluated when the need arises. """ def __init__(self, name, file, type, varDict={}): self.mName = name self.mFile = file self.mIsEvaluated = False self.mType = type self.mVariableDict = varDict if self.mType == "fpc": self.mIsEvaluated = True def getVariable(self, variable): self.evaluate() return self.mVariableDict.get(variable,"") def getName(self): return self.mName def evaluate(self): if not self.mIsEvaluated: flagDBG().out(flagDBG.INFO, "PkgInfo.evaluate", "Evaluating %s" % self.mName) self.mVariableDict= Utils.parsePcFile(self.mFile) self.mIsEvaluated = True def getInfo(self): self.evaluate() return self.mVariableDict class OptionsEvaluator: def __init__(self): if len(sys.argv) < 2: self.printHelp() # This is only the args....(first arg is stripped) def evaluateArgs(self, args): # Catch any args that need to be tended to immediately # Process args in the order that they were recieved. Some options are not # shown below because they are sub-options of an option below (--strip-dups) for option in args: if option.startswith("--verbose-debug"): flagDBG().setLevel(flagDBG.VERBOSE) if option.startswith("--debug"): flagDBG().setLevel(flagDBG.INFO) elif option.startswith("--from-file"): val_start = option.find('=') + 1 file = option[val_start:] Utils.EXTRA_FLAGPOLL_FILES = Utils.EXTRA_FLAGPOLL_FILES + ":" + file elif option.startswith("--help"): self.printHelp() sys.exit(0) elif option.startswith("--version"): print "%s.%s.%s" % Utils.getFlagpollVersion() sys.exit(0) elif option.startswith("--list-all"): PkgDB().printAllPackages() continue listedAgentNames = [] agent = None num_args = len(args) curr_arg = 0 output_options = [] # (option, name/"") important_options = [] # ones that need special attention while curr_arg < num_args: if args[curr_arg].startswith("--atleast-version"): val_start = args[curr_arg].find('=') + 1 atleast_version = args[curr_arg][val_start:] atleast_filter = Filter("Version", lambda x,v=atleast_version: x >= v) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(atleast_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --at-least-version") continue if args[curr_arg].startswith("--cflags-only-I"): output_options.append(("cflags-only-I", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--cflags-only-other"): output_options.append(("cflags-only-other", "")) curr_arg = curr_arg + 1 continue #This could be the catch all for the above ones to and then filter based on what is asked... #For clarity of course... if args[curr_arg].startswith("--cflags"): output_options.append(("cflags", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--extra-paths"): val_start = args[curr_arg].find('=') + 1 paths = args[curr_arg][val_start:] Utils.EXTRA_FLAGPOLL_SEARCH_PATHS = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS + ":" + paths curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--exact-version"): val_start = args[curr_arg].find('=') + 1 exact_version = args[curr_arg][val_start:] exact_filter = Filter("Version", lambda x,v=exact_version: x == v) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(exact_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --exact-version") continue if args[curr_arg].startswith("--exists"): important_options.append("exists") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--from-file"): val_start = args[curr_arg].find('=') + 1 file = args[curr_arg][val_start:] file_filter = Filter("FlagpollFilename", lambda x,f=file: x == f) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(file_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --from-file") continue if args[curr_arg].startswith("--info"): important_options.append("info") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--print-pkg-options"): important_options.append("print-pkg-options") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--keep-dups"): Utils.setKeepDups(True) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-l"): output_options.append(("libs-only-l", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-L"): output_options.append(("libs-only-L", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-other"): output_options.append(("libs-only-other", "")) curr_arg = curr_arg + 1 continue #This could be the catch all for the above ones to and then filter based on what is asked... if args[curr_arg].startswith("--libs"): output_options.append(("libs", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--require-all"): rlen = len("--require-all") req_string = args[curr_arg][rlen:] req_string = req_string.replace('-','_') curr_arg = curr_arg + 1 if req_string.find("<=") != -1: op_start = req_string.find("<=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x <= v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find(">=") != -1: op_start = req_string.find(">=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x >= v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find(">") != -1: op_start = req_string.find(">") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x > v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("<") != -1: op_start = req_string.find("<") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x < v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("=") != -1: op_start = req_string.find("=") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x == v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("=") == -1: new_filter = Filter(req_string, lambda x: len(x) > 0) DepResolutionSystem().addFilter(new_filter) continue continue if args[curr_arg].startswith("--require-"): rlen = len("--require-") req_string = args[curr_arg][rlen:] req_string = req_string.replace('-','_') curr_arg = curr_arg + 1 if agent is None: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --require") if req_string.find("<=") != -1: op_start = req_string.find("<=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x <= v) agent.addFilter(new_filter) continue if req_string.find(">=") != -1: op_start = req_string.find(">=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x >= v) agent.addFilter(new_filter) continue if req_string.find(">") != -1: op_start = req_string.find(">") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x > v) agent.addFilter(new_filter) continue if req_string.find("<") != -1: op_start = req_string.find("<") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x < v) agent.addFilter(new_filter) continue if req_string.find("=") != -1: op_start = req_string.find("=") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x == v) agent.addFilter(new_filter) continue if req_string.find("=") == -1: new_filter = Filter(req_string, lambda x: len(x) > 0) agent.addFilter(new_filter) continue continue if args[curr_arg].startswith("--no-deps"): if agent is not None: agent.setCheckDepends(False) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --no-deps") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--require="): val_start = args[curr_arg].find('=') + 1 req_var = args[curr_arg][val_start:] curr_arg = curr_arg + 1 DepResolutionSystem().makeRequireFilter(req_var) continue if args[curr_arg].startswith("--modversion"): if agent is not None: output_options.append(("Version", agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --modversion") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--max-release"): val_start = args[curr_arg].find('=') + 1 max_release = args[curr_arg][val_start:] max_filter = Filter("Version", lambda x,v=max_release: x.startswith(v)) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(max_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --max-release") continue if args[curr_arg].startswith("--static"): DepResolutionSystem().setPrivateRequires(True) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--variable"): val_start = args[curr_arg].find('=') + 1 fetch_var = args[curr_arg][val_start:] if agent is not None: output_options.append((fetch_var, agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --variable") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--get-all"): rlen = len("--get-all-") get_string = args[curr_arg][rlen:] get_string = get_string.replace('-','_') output_options.append((get_string, "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--get"): rlen = len("--get-") get_string = args[curr_arg][rlen:] get_string = get_string.replace('-','_') if agent is not None: output_options.append((get_string, agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --get") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--concat"): important_options.append("concat") curr_arg = curr_arg + 1 continue if not args[curr_arg].startswith("--"): name = args[curr_arg] curr_arg = curr_arg + 1 if PkgDB().checkPackage(name): agent = DepResolutionSystem().createResolveAgent(name) listedAgentNames.append(name) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Package %s" % name) sys.exit(1) continue if args[curr_arg] != "--debug" and args[curr_arg] != "--verbose-debug": flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Option: %s" % args[curr_arg]) curr_arg = curr_arg + 1 DepResolutionSystem().resolveDeps() pkgs = DepResolutionSystem().getPackages() for p in pkgs: if not p: for option in important_options: if option == "exists": print "no" sys.exit(1) flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found") if len(pkgs) == 0: for option in important_options: if option == "exists": print "no" sys.exit(1) flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found") sys.exit(1) concat = False for option in important_options: if option == "exists": print "yes" return sys.exit(0) # already checked for none above if option == "concat": concat = True if option == "info": pkg_info_list = [] for pkg in pkgs: if pkg.getName() in listedAgentNames: print pkg.getName() pkg_info = pkg.getInfo() for key in pkg_info.keys(): print " %s : %s" % (key, pkg_info[key]) if option == "print-pkg-options": print "" print "All options below would start with (--get-/--get-all-/--require-/--require-all-)" print "NOTE: this list does not include the standard variables that are exported." print "" for pkg in pkgs: if pkg.getName() not in listedAgentNames: continue print "Package: " + pkg.getName() for key in pkg.getInfo().keys(): if key not in [ "Name", "Description", "URL", "Version", "Requires", "Requires.private", "Conflicts", "Libs", "Libs.private", "Cflags", "Provides", "Arch", "FlagpollFilename", "prefix" ]: print " " + key.replace('_','-') #print output_options #output_options = [] #output_single = [] #Process options here.............. concat_list = [] if concat: print_option = lambda x: concat_list.extend(x) else: print_option = lambda x: Utils.printList(x) for option in output_options: if option[0] == "cflags": print_option(Utils.stripDupIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "cflags-only-I": print_option(Utils.cflagsOnlyDirIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "cflags-only-other": print_option(Utils.cflagsOnlyOtherIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "libs-only-l": print_option(Utils.libsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs-only-L": print_option(Utils.libDirsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs-only-other": print_option(Utils.libsOnlyOtherLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs": print_option(Utils.stripDupLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) else: print_option(Utils.stripDupInList(self.getVarFromPkgs(option[0], pkgs, option[1]))) if concat: Utils.printList(Utils.stripDupInList(concat_list)) def getVarFromPkgs(self, var, pkgs, pkg_name=""): var_list = [] ext_vars = [] if var == "Libs": if DepResolutionSystem().checkPrivateRequires: ext_vars.append("Libs.private") if pkg_name == "": for pkg in pkgs: if pkg: var_list.extend(pkg.getVariable(var).split(' ')) for extra_var in ext_vars: var_list.extend(pkg.getVariable(extra_var).split(' ')) else: for pkg in pkgs: if pkg: if pkg.getName() == pkg_name: var_list.extend(pkg.getVariable(var).split(' ')) for extra_var in ext_vars: var_list.extend(pkg.getVariable(extra_var).split(' ')) return var_list def printHelp(self): print "usage: flagpoll pkg options [pkg options] [generic options]" print " " print "generic options:" print " --help show this help message and exit" print " --version output version of flagpoll" print " --list-all list all known packages" print " --debug show debug information" print " --verbose-debug show verbose debug information" print " --extra-paths=EXTRA_PATHS" print " extra paths for flagpoll to search for meta-data files" print " --concat concatenate all output and output as one line" print " --keep-dups do not strip out all duplicate info from options" print " --info show information for packages" print " --print-pkg-options show pkg specific options" print " " print "options:" print " --modversion output version for package" print " --require=REQUIRE adds additional requirements for packages ex. 32/64" print " --libs output all linker flags" print " --static output linker flags for static linking" print " --libs-only-l output -l flags" print " --libs-only-other output other libs (e.g. -pthread)" print " --libs-only-L output -L flags" print " --cflags output all pre-processor and compiler flags" print " --cflags-only-I output -I flags" print " --cflags-only-other output cflags not covered by the cflags-only-I option" print " --exists return 0 if the module(s) exist" print " --from-file=FILE use the specified FILE for the package" #print " --print-provides print which packages the package provides" #print " --print-requires print which packages the package requires" print " --no-deps do not lookup dependencies for the package" print " --atleast-version=ATLEAST_VERSION" print " return 0 if the module is at least version" print " ATLEAST_VERSION" print " --exact-version=EXACT_VERSION" print " return 0 if the module is exactly version" print " EXACT_VERSION" print " --max-release=MAX_RELEASE" print " return 0 if the module has a release that has a" print " version of MAX_RELEASE and will return the max" print " --variable=VARIABLE get the value of a variable" print " " print "dynamic options(replace VAR with a variable you want to get/filter on)" print " NOTE: replace underscores with dashes in VAR" print " NOTE: quotes are needed around <,>,= combinations" print " --get-VAR get VAR from package" print " --get-all-VAR get VAR from package and its deps" print " --require-VAR[<,>,=VAL]" print " require that a var is defined for a package" print " or optionally use equality operators against VAL" print " --require-all-VAR[<,>,=VAL]" print " require that a var is defined for all packages" print " or optionally use equality operators against VAL" print "" print "extending search path" print " FLAGPOLL_PATH environment variable that can be set to" print " extend the search path for .fpc/.pc files" sys.exit(0) def main(): # GO! # Initialize singletons and the start evaluating my_dbg = flagDBG() my_dep_system = DepResolutionSystem() opt_evaluator = OptionsEvaluator() opt_evaluator.evaluateArgs(sys.argv[1:]) sys.exit(0) if __name__ == "__main__": main()
Python
#!/usr/bin/env python from distutils.core import setup setup( name='flagpoll', version='0.8.2', description='Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software.', author='Daniel E. Shipton', author_email='dshipton@infiscape.com', license='GPL', url='https://realityforge.vrsource.org/view/FlagPoll/WebHome', download_url='https://realityforge.vrsource.org/view/FlagPoll/FlagpollDownloads', scripts=['flagpoll'], long_description = "Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software. Think of it as the rpm of software development. It enables developers total control over which packages, versions, architectures, etc. that they want to use meta-data from.", data_files=[('share/flagpoll', ['flagpoll.fpc']), ('share/man/man1', ['flagpoll.1']), ('share/aclocal', ['flagpoll.m4'])] )
Python
#!/usr/bin/env python # ----------------------------------------------------------------- # # Flagpoll: A tool to extract flags from installed applications # for compiling, settting variables, etc. # # Original Authors: # Daniel E. Shipton <dshipton@gmail.com> # # Flagpoll is Copyright (C) 2006-2007 by Daniel E. Shipton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to: # Free SoftwareFoundation, Inc. # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # # ----------------------------------------------------------------- import sys, os, glob, os.path, copy, platform pj = os.path.join #################################################################### # SNAGGED FROM PYTHON 2.4 for versions under 2.4 #################################################################### import re as _re class _multimap: """Helper class for combining multiple mappings. Used by .{safe_,}substitute() to combine the mapping and keyword arguments. """ def __init__(self, primary, secondary): self._primary = primary self._secondary = secondary def __getitem__(self, key): try: return self._primary[key] except KeyError: return self._secondary[key] class _TemplateMetaclass(type): pattern = r""" %(delim)s(?: (?P<escaped>%(delim)s) | # Escape sequence of two delimiters (?P<named>%(id)s) | # delimiter and a Python identifier {(?P<braced>%(id)s)} | # delimiter and a braced identifier (?P<invalid>) # Other ill-formed delimiter exprs ) """ def __init__(cls, name, bases, dct): super(_TemplateMetaclass, cls).__init__(name, bases, dct) if 'pattern' in dct: pattern = cls.pattern else: pattern = _TemplateMetaclass.pattern % { 'delim' : _re.escape(cls.delimiter), 'id' : cls.idpattern, } cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE) class Template: """A string class for supporting $-substitutions.""" __metaclass__ = _TemplateMetaclass delimiter = '$' idpattern = r'[_a-z][_a-z0-9]*' def __init__(self, template): self.template = template # Search for $$, $identifier, ${identifier}, and any bare $'s def _invalid(self, mo): i = mo.start('invalid') lines = self.template[:i].splitlines(True) if not lines: colno = 1 lineno = 1 else: colno = i - len(''.join(lines[:-1])) lineno = len(lines) raise ValueError('Invalid placeholder in string: line %d, col %d' % (lineno, colno)) def substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): # Check the most common path first. named = mo.group('named') or mo.group('braced') if named is not None: val = mapping[named] # We use this idiom instead of str() because the latter will # fail if val is a Unicode containing non-ASCII characters. return '%s' % val if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: self._invalid(mo) raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) def safe_substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): named = mo.group('named') if named is not None: try: # We use this idiom instead of str() because the latter # will fail if val is a Unicode containing non-ASCII return '%s' % mapping[named] except KeyError: return self.delimiter + named braced = mo.group('braced') if braced is not None: try: return '%s' % mapping[braced] except KeyError: return self.delimiter + '{' + braced + '}' if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: return self.delimiter raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) #################################################################### # End Snagging #################################################################### class Utils: # Holds collection of small utility functions EXTRA_FLAGPOLL_SEARCH_PATHS = "" EXTRA_FLAGPOLL_FILES = "" path_list_cache = None # Cache of found path lists. (only calcuate once) KEEP_DUPS = False FLAGPOLL_LIST_OF_POSSIBLE_ERRORS = [] def addPossibleError(pos_err): Utils.FLAGPOLL_LIST_OF_POSSIBLE_ERRORS.append(pos_err) addPossibleError = staticmethod(addPossibleError) def getPossibleErrors(): return Utils.stripDupInList(Utils.FLAGPOLL_LIST_OF_POSSIBLE_ERRORS) getPossibleErrors = staticmethod(getPossibleErrors) def getFlagpollVersion(): FLAGPOLL_MAJOR_VERSION = 0 FLAGPOLL_MINOR_VERSION = 8 FLAGPOLL_PATCH_VERSION = 2 return ( FLAGPOLL_MAJOR_VERSION, FLAGPOLL_MINOR_VERSION, FLAGPOLL_PATCH_VERSION ) getFlagpollVersion = staticmethod(getFlagpollVersion) def getPathList(): if None != Utils.path_list_cache: return Utils.path_list_cache #TODO: expand LD_LIBRARY_PATH to 64/32/etc??? pkg_cfg_dir = [] flg_cfg_dir = [] ld_path = [] if os.environ.has_key("PKG_CONFIG_PATH"): pkg_cfg_dir = os.environ["PKG_CONFIG_PATH"].split(os.pathsep) if os.environ.has_key("FLAGPOLL_PATH"): flg_cfg_dir = os.environ["FLAGPOLL_PATH"].split(os.pathsep) ld_dirs = ['LD_LIBRARY_PATH', 'DYLD_LIBRARY_PATH'] for d in ld_dirs: if os.environ.has_key(d): cur_path = os.environ[d].split(os.pathsep) ld_path_pkg = [pj(p,'pkgconfig') for p in cur_path] ld_path_flg = [pj(p,'flagpoll') for p in cur_path] ld_path.extend(ld_path_pkg) ld_path.extend(ld_path_flg) extra_paths = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS.split(os.pathsep) path_list = ["/usr/lib64/pkgconfig", "/usr/lib/pkgconfig", "/usr/share/pkgconfig", "/usr/lib64/flagpoll", "/usr/lib/flagpoll", "/usr/share/flagpoll"] path_list.extend(pkg_cfg_dir) path_list.extend(flg_cfg_dir) path_list.extend(extra_paths) path_list.extend(ld_path) flagDBG().out(flagDBG.VERBOSE, "Utils.getPathList", "Potential path list: " + str(path_list)) path_list = [p for p in path_list if os.path.exists(p)] flagDBG().out(flagDBG.INFO, "Utils.getPathList", "Using path list: " + str(path_list)) Utils.path_list_cache = path_list return path_list getPathList = staticmethod(getPathList) def getFileList(): flist = Utils.EXTRA_FLAGPOLL_FILES.split(":") filelist = [] for f in flist: if os.path.isfile(f): filelist.append(f) return filelist getFileList = staticmethod(getFileList) def setKeepDups(keep_dups): Utils.KEEP_DUPS = keep_dups setKeepDups = staticmethod(setKeepDups) def stripDupInList(gen_list): new_list = [] for item in gen_list: item = item.strip() if Utils.KEEP_DUPS: if len(item) > 0: new_list.append(item) continue if item not in new_list: if len(item) > 0: new_list.append(item) return new_list stripDupInList = staticmethod(stripDupInList) def stripDupLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] dir_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-L") or flg.startswith("-R"): dir_list.append(flg) else: lib_list.append(flg) new_list = dir_list + lib_list return Utils.stripDupInList(new_list) stripDupLinkerFlags = staticmethod(stripDupLinkerFlags) def stripDupIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] extra_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-I"): inc_list.append(flg) else: extra_list.append(flg) extra_list.sort() new_list = inc_list + extra_list return Utils.stripDupInList(new_list) stripDupIncludeFlags = staticmethod(stripDupIncludeFlags) def cflagsOnlyDirIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-I"): inc_list.append(flg) return Utils.stripDupInList(inc_list) cflagsOnlyDirIncludeFlags = staticmethod(cflagsOnlyDirIncludeFlags) def cflagsOnlyOtherIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though extra_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if not flg.startswith("-I"): extra_list.append(flg) return Utils.stripDupInList(extra_list) cflagsOnlyOtherIncludeFlags = staticmethod(cflagsOnlyOtherIncludeFlags) def libsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-l"): lib_list.append(flg) return Utils.stripDupInList(lib_list) libsOnlyLinkerFlags = staticmethod(libsOnlyLinkerFlags) def libsOnlyOtherLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though other_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if not flg.startswith("-l") and not flg.startswith("-L") and not flg.startswith("-R"): other_list.append(flg) return Utils.stripDupInList(other_list) libsOnlyOtherLinkerFlags = staticmethod(libsOnlyOtherLinkerFlags) def libDirsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though dir_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-L") or flg.startswith("-R"): dir_list.append(flg) return Utils.stripDupInList(dir_list) libDirsOnlyLinkerFlags = staticmethod(libDirsOnlyLinkerFlags) def printList(gen_list): list_string = "" for item in gen_list: if len(item) > 0: list_string += str(item) list_string += " " print list_string.strip() printList = staticmethod(printList) def parsePcFile(filename): lines = open(filename).readlines() fvars = {} fvars["FlagpollFilename"] = filename lokals = {} lokals["fp_file_cwd"] = str(filename[:- ((len(os.path.basename(filename) ) + 1))]) lines.append("prefix: ${prefix}") append_next = False append_dict = {} append_key = "" for line in lines: line = line.strip() if not line: continue if append_next: tmp = append_dict[append_key] tmp = tmp[:-1] + " " + line append_dict[append_key] = tmp if tmp[-1:] == "\\": append_next = True else: append_next = False continue if line.startswith("#"): continue eq_pos = line.find('=') col_pos = line.find(':') if eq_pos < col_pos and eq_pos != -1 or col_pos == -1 and eq_pos != -1: # local variable name, val = line.split('=', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(lokals) except ValueError: flagDBG().out(flagDBG.WARN, "PkgInfo.parse", "%s has an invalid metadata file" % filename) lokals[name] = val if val[-1:] == "\\": append_next = True append_dict = lokals append_key = name continue if col_pos < eq_pos and col_pos != -1 or eq_pos == -1 and col_pos != -1: # exported variable name, val = line.split(':', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(lokals) except ValueError: flagDBG().out(flagDBG.ERROR, "PkgInfo.parse", "%s has an invalid metadata file" % filename) fvars[name] = val if val[-1:] == "\\": append_next = True append_dict = fvars append_key = name return fvars parsePcFile = staticmethod(parsePcFile) class flagDBG(object): # Logging class is really easy to use # Levels: # 0 - VERBOSE # 1 - INFO # 2 - WARN # 3 - ERROR VERBOSE = 0 INFO = 1 WARN = 2 ERROR = 3 __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if flagDBG.__initialized: return flagDBG.__initialized = True self.mLevel = self.WARN self.mLevelList = ["VERBOSE", "INFO", "WARN", "ERROR"] def setLevel(self, level): if level <= 3: self.mLevel = level def out(self, level, obj, message): if level == self.ERROR: if self.mLevel == self.VERBOSE: print self.mLevelList[level] + ":" + str(obj) + ": " + str(message) else: sys.stderr.write(self.mLevelList[level] + ": " + str(message) + "\n") errs = Utils.getPossibleErrors() if len(errs) > 0: sys.stderr.write("Possible culprits:\n") for pos_err in errs: sys.stderr.write( " " + str(pos_err) + "\n" ) sys.exit(1) if level >= self.mLevel: print self.mLevelList[level] + ":" + str(obj) + ": " + str(message) class DepResolutionSystem(object): """ You add PkgAgents with Filters into system and call resolve() you can check for succes by depsSatisfied() and get the list of packages that work back by calling getPackages() """ __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if DepResolutionSystem.__initialized: return DepResolutionSystem.__initialized = True self.mResolveAgents = [] self.mAgentDict = {} self.mFilters = [] self.mResolveAgentFilters = [] self.mInvalidPackageList = [] self.mSatisfied = False self.mAgentChangeList = [] # list of those responsible for adding Filters # to agents in higher in the chain than them # these are the first agents to ask that they pick # the next best package of them self.mAgentsVisitedList = [] # list of Agents that have been visited self.mResolvedPackageList = [] # list that is generated when deps are satified self.mCheckPrivateRequires = False self.mMadeDependList = False def getFilters(self): return self.mFilters def addFilter(self, filter): self.mFilters.append(filter) def addResolveAgentFilter(self, filter): self.mResolveAgentFilters.append(filter) def makeRequireFilter(self, requires): arch_list = [] arch_list.append("no_arch") arch_list.append("") if platform.system() == "Linux": if requires == "64": arch_list.append("x86_64") if requires == "32": arch_list.append("i386") arch_list.append("i486") arch_list.append("i586") arch_list.append("i686") if platform.system() == "Darwin": if requires == "64": arch_list.append("ppc64") if requires == "32": arch_list.append("ppc") if platform.system().startswith("IRIX"): arch_list.append(requires) new_filter = Filter("Arch", lambda x,v=arch_list: x in v) self.addFilter(new_filter) def createAgent(self, name): if self.checkAgentExists(name): return self.getAgent(name) else: agent = PkgAgent(name) flagDBG().out(flagDBG.INFO, "DepResSys.createAgent", "Adding %s" % name) self.addNewAgent(agent) return agent def createResolveAgent(self, name): if self.checkAgentExists(name): return self.getAgent(name) else: agent = PkgAgent(name) flagDBG().out(flagDBG.INFO, "DepResSys.createResolveAgent", "Adding %s" % name) self.addResolveAgent(agent) return agent def setPrivateRequires( self, req ): self.mCheckPrivateRequires = req def checkPrivateRequires(self): return self.mCheckPrivateRequires def checkAgentExists(self, name): return self.mAgentDict.has_key(name) def getAgent(self, name): if self.mAgentDict.has_key(name): return self.mAgentDict[name] else: flagDBG().out(flagDBG.ERROR, "DepResSys.getAgent", "Agent %s does not exist" % name) def addNewAgent(self, agent): if not self.checkAgentExists(agent): self.mAgentDict[agent.getName()] = agent def addResolveAgent(self, agent): if agent not in self.mResolveAgents: self.mResolveAgents.append(agent) for filt in self.mResolveAgentFilters: agent.addFilter(filt) def isSatisfied(self): return self.mSatisfied def updateResolvedPackages(self): pkg_list = [] agent_list = [] for agent in self.mResolveAgents: list_of_pkgs = agent.getCurrentPackageList(agent_list) pkg_list.extend(list_of_pkgs) self.mResolvedPackageList = pkg_list def getPackages(self): flagDBG().out(flagDBG.INFO, "DepResSys.getPackages", "Generating list of valid packages ") #str([pkg.getCurrentPackage.getName() for pkg in self.mResolvedPackageList])) # If this comes back empty then there isn't a valid set of packages to use self.updateResolvedPackages() return self.mResolvedPackageList def checkFiltersChanged(self): list_to_use = [] return True in [pkg.filtersChanged(list_to_use) for pkg in self.mResolveAgents] def resolveHelper(self): self.resolveAgentsChanged = True while self.resolveAgentsChanged: for agent in self.mResolveAgents: flagDBG().out(flagDBG.INFO, "DepResSys.resolveHelper", "Updating " + agent.getName()) agent.update(self.mAgentsVisitedList, self.mAgentChangeList) self.resolveAgentsChanged = self.checkFiltersChanged() # Ask mResolveAgents if they are done(they ask sub people) unless they are # really above you in the walk # If there were changes...run update on mResolveAgents again # at the end ask for pkglist..if it comes back empty then we don't # have a usable configuration for those packages def resolveDeps(self): self.resolveHelper() if not self.mMadeDependList: for agent in self.mResolveAgents: agent.makeDependList() self.mMadeDependList = True self.updateResolvedPackages() # Check if the first round through we found something # Otherwise we need to start removing packages that aren't viable # during the loop self.mSatisfied = (len(self.mResolvedPackageList) != 0) # remove top of packages that added Filters. # then move on to resolving again # remove more if neccesary agentChangeNumber = 0 while not self.mResolvedPackageList: if(self.mAgentChangeList[agentChangeNumber]): if self.mAgentChangeList[agentChangeNumber] in self.mInvalidPackageList: agentChangeNumber += 1 else: if(self.mAgentChangeList[agentChangeNumber].getViablePackages()): flagDBG().out(flagDBG.INFO, "DepResSys.resolveDeps", "Removing bad pkg from " + self.mAgentChangeList[agentChangeNumber].getName()) self.mInvalidPackageList.append(self.mAgentChangeList[agentChangeNumber].removeCurrentPackage()) else: flagDBG().out(flagDBG.INFO, "DepResSys.resolveDeps", "No combinations.. Resetting " + self.mAgentChangeList[agentChangeNumber].getName()) self.mAgentChangeList[agentChangeNumber].reset() agentChangeNumber += 1 self.resolveHelper() self.updateResolvedPackages() self.mSatisfied = (len(self.mResolvedPackageList) != 0) return class PkgAgent: """ Agent that keeps track of the versions for a package given some filters and the addition of Filters """ # Makes a PkgAgent that finds its current package with the version reqs def __init__(self, name): if DepResolutionSystem().checkAgentExists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "Package Agent %s already exists" % self.mName) self.mName = name flagDBG().out(flagDBG.INFO, "PkgAgent", "Creating:" + str(self.mName)) if not PkgDB().exists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "No info for package: %s" % self.mName) #XXX Doesn't keep filters added for a redo... DepResolutionSystem().addNewAgent(self) self.mFilterList = [] self.mFilterList.extend(DepResolutionSystem().getFilters()) self.mBasePackageList = PkgDB().getPkgInfos(name) self.mBasePackageList.sort(lambda lhs, rhs: cmp(rhs.getVariable('Version'), lhs.getVariable('Version'))) for filt in self.mFilterList: self.mBasePackageList = filt.filter(self.mBasePackageList) if len(self.mBasePackageList) == 0: flagDBG().out(flagDBG.ERROR, "PkgAgent", "No viable packages for: %s" % self.mName) self.mViablePackageList = copy.deepcopy(self.mBasePackageList) if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mFiltersChanged = True self.mCheckDepends = True self.mAgentDependList = [] def getName(self): return self.mName def setCheckDepends(self, tf): self.mCheckDepends = tf #Filter("Version", lambda x: x == "4.5") def makeDependList(self): if not self.mCheckDepends: self.mAgentDependList = [] return dep_list = [] if self.mCurrentPackage: req_string = self.mCurrentPackage.getVariable("Requires") if DepResolutionSystem().checkPrivateRequires(): req_string = req_string + " " + self.mCurrentPackage.getVariable("Requires.private") req_string = req_string.strip() if req_string == "": return req_string = req_string.replace(',', ' ') req_string = req_string.replace('(', ' ') req_string = req_string.replace(')', ' ') space_req_string_list = req_string.split(' ') req_string_list = [] for entry in space_req_string_list: if len(entry) > 0: req_string_list.append(entry) i = 0 flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList", self.mCurrentPackage.getName() + " requires: " + str(req_string_list)) while len(req_string_list) > i: if PkgDB().exists(req_string_list[i]): new_filter = [] new_agent = DepResolutionSystem().createAgent(req_string_list[i]) if len(req_string_list) > i+1: if req_string_list[i+1] == "=": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x == v) elif req_string_list[i+1] == "<=": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x <= v) elif req_string_list[i+1] == ">=": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x >= v) elif req_string_list[i+1] == ">": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x > v) elif req_string_list[i+1] == "<": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x < v) else: i += 1 else: i += 1 dep_list.append(new_agent) if new_filter: i+=3 new_agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "PkgAgent.makeDependList", "Package %s depends on %s but does not seem to be installed." % (self.mName, str(req_string_list[i]))) flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList", str(self.mName) + " : List is:" + str([pkg.getName() for pkg in dep_list])) self.mAgentDependList = dep_list def filtersChanged(self, packageList): tf_list = [self.mFiltersChanged] if self.mName not in packageList: packageList.append(self.mName) for pkg in self.mAgentDependList: tf_list.append(pkg.filtersChanged(packageList)) return True in tf_list def getCurrentPackageList(self, packageList): pkgs = [] if self.mName not in packageList: flagDBG().out(flagDBG.INFO, "PkgAgent.getCurrentPackageList", "Package: %s" % self.mName) pkgs.append(self.mCurrentPackage) packageList.append(self.mName) # Make depend list if we are supposed to self.updateFilters() self.makeDependList() for pkg in self.mAgentDependList: pkgs.extend(pkg.getCurrentPackageList(packageList)) return pkgs # current pkginfo for me def getCurrentPkgInfo(self): return self.mCurrentPackage # Someone else usually places these on me # I keep track of those separately def addFilter(self, filter): flagDBG().out(flagDBG.INFO, "PkgAgent.addFilter", "Filter %s" % self.mName + " on %s." % filter.getVarName()) self.mFiltersChanged = True self.mFilterList.append(filter) def removeCurrentPackage(self): flagDBG().out(flagDBG.INFO, "PkgAgent.removeCurrentPackage", "Removing current package of %s" % self.mName) if self.mViablePackageList: ret_val = self.mViablePackageList[0] in self.mBasePackageList del self.mViablePackageList[0] if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] return ret_val def update(self, agentVisitedList, agentChangeList): flagDBG().out(flagDBG.INFO, "PkgAgent.update", "%s" % self.mName) if self.mName in agentVisitedList: return agentVisitedList.append(self.mName) if self.mFiltersChanged: self.mFiltersChanged = False self.updateFilters() # TODO: checkFilters and add them # if a pkg is in visitedList then add yourself to agentChangeList for pkg in self.mAgentDependList: pkg.update(agentVisitedList, agentChangeList) return def updateFilters(self): for filt in self.mFilterList: self.mViablePackageList = filt.filter(self.mViablePackageList) flagDBG().out(flagDBG.INFO, "PkgAgent.updateFilters", "%s has " % self.mName + str(len(self.mViablePackageList)) + " left") if len(self.mViablePackageList) > 0: self.mCurrentPackage = self.mViablePackageList[0] else: for f in self.mFilterList: Utils.addPossibleError(str(self.mName) + " -> " + str(f.getVarName())) self.mCurrentPackage = [] def reset(self): flagDBG().out(flagDBG.INFO, "PkgAgent.reset", "Resetting package: %s" % self.mName) self.mViablePackageList = self.mBasePackageList if self.mViablePackageList: self.mCurrentPacakge = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mFilterList = DepResolutionSystem().getFilters() self.mAgentDependList = [] self.mFiltersChanged = True return class Filter: """ A single Filter that knows how to filter the list it recieves Will be inheireted....?..? """ def __init__(self, variableName, testCallable): self.mVarName = variableName self.mTestCallable = testCallable def getVarName(self): return self.mVarName def filter(self, pkg_info_list): ret_pkg_list = [] # Filter first for pkg in pkg_info_list: var = pkg.getVariable(self.mVarName) if self.mTestCallable(var): flagDBG().out(flagDBG.INFO, "Filter", "Passed: %s:" % pkg.getName() + " %s is " % self.mVarName + str(var)) ret_pkg_list.append(pkg) else: flagDBG().out(flagDBG.INFO, "Filter", "Failed: %s:" % pkg.getName() + " %s is " % self.mVarName + str(var)) # Now sort ret_pkg_list.sort(lambda lhs, rhs: cmp(rhs.getVariable(self.mVarName), lhs.getVariable(self.mVarName))) return ret_pkg_list #requires: qt == 4.5 #Filter("Version", lambda x: x <= "4.5") #Filter("Version", lambda x: x <= "4.5") class PkgDB(object): """ Holds all the neccesary information to evaluate itself when needed. Is in charge of holding a list of PkgInfo's that contain info about the package. """ __initialized = False def __init__(self): if self.__initialized: return self.__initialized = True self.mPkgInfos = {} # {pkg_name: List of package infos} self.populatePkgInfoDBPcFiles() self.populatePkgInfoDBFpcFiles() def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def printAllPackages(self): list_of_package_names = [] for pkg in self.mPkgInfos: list_of_package_names.append(pkg) for name in list_of_package_names: print name sys.exit(0) def getVariables(self, name, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariable", "Finding " + str(variable_list) + " in " + str(name)) ret_list = [] for var in variable_list: if self.mPkgInfos.has_key(name): ret_list.extend(self.mPkgInfos[name][0].getVariable(var)) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariable", "Package %s not found." % name) return ret_list def checkPackage(self, name): flagDBG().out(flagDBG.INFO, "PkgDB.checkPackage", "Finding " + str(name)) if self.mPkgInfos.has_key(name): return True else: flagDBG().out(flagDBG.ERROR, "PkgDB.CheckPackage", "Package %s not found." % name) return False def getVariablesAndDeps(self, pkg_list, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariablesAndDeps", "Finding " + str(variable_list) + " in " + str(pkg_list)) if DepResolutionSystem().checkPrivateRequires(): temp_var_list = [] for var in variable_list: temp_var_list.append(var.join(".private")) variable_list = variable_list + temp_var_list for name in pkg_list: if self.mPkgInfos.has_key(name): agent = DepResolutionSystem().createAgent(name) DepResolutionSystem().addResolveAgent(agent) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariablesAndDeps", "Package %s not found." % name) DepResolutionSystem().resolveDeps() pkgs = DepResolutionSystem().getPackages() var_list = [] for pkg in pkgs: if pkg: for var in variable_list: var_list.extend(pkg.getVariable(var).split(' ')) return var_list def getPkgInfos(self, name): if self.mPkgInfos.has_key(name): return self.mPkgInfos[name] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getPkgInfos", "Package %s not found." % name) def exists(self, name): return self.mPkgInfos.has_key(name) def getInfo(self, name): if self.mPkgInfos.has_key(name): return [pkg.getInfo() for pkg in self.mPkgInfos[name]] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getInfo", "Package %s not found." % name) def buildPcFileDict(self): """ Builds up a dictionary of {name: list of files for name} """ pc_dict = {} for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.pc")) # List of .pc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these pc files: %s" % str(glob_list)) for g in glob_list: # Get key name and add file to value list in dictionary key = os.path.basename(g)[:-3] # Strip .pc off the filename...rstrip no worky pc_dict.setdefault(key, []).append(g) for f in Utils.getFileList(): if f.endswith(".pc"): key = os.path.basename(f)[:-3] # Strip .pc off the filename...rstrip no worky pc_dict.setdefault(key, []).append(f) return pc_dict # { "key", [ "list", "of", "corresponding", "pc", "files"] } def populatePkgInfoDBPcFiles(self): dict_to_pop_from = self.buildPcFileDict() for (pkg,files) in dict_to_pop_from.iteritems(): for f in files: self.mPkgInfos.setdefault(pkg,[]).append(PkgInfo(pkg, f, "pc")) def buildFpcFileList(self): """ Builds up a dictionary of {name: list of files for name} """ file_list = [] for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.fpc")) # List of .fpc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these fpc files: %s" % str(glob_list)) for g in glob_list: file_list.append(g) for f in Utils.getFileList(): if f.endswith(".fpc"): file_list.append(f) return file_list # [ "list", "of", "fpc", "files"] def populatePkgInfoDBFpcFiles(self): list_to_add = self.buildFpcFileList() for filename in list_to_add: var_dict = Utils.parsePcFile(filename) if not var_dict.has_key("Provides"): flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Provides" % str(filename)) continue if not var_dict.has_key("Arch"): flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Arch" % str(filename)) continue provides_string = var_dict["Provides"] provides_string = provides_string.replace(',', ' ') provides_string = provides_string.replace('(', ' ') provides_string = provides_string.replace(')', ' ') for key in provides_string.split(" "): if len(key) > 0: self.mPkgInfos.setdefault(key, []).append(PkgInfo(key, filename, "fpc", var_dict)) class PkgInfo: """ Holds the information for a package file on the system. These however are evaluated when the need arises. """ def __init__(self, name, file, type, varDict={}): self.mName = name self.mFile = file self.mIsEvaluated = False self.mType = type self.mVariableDict = varDict if self.mType == "fpc": self.mIsEvaluated = True def getVariable(self, variable): self.evaluate() return self.mVariableDict.get(variable,"") def getName(self): return self.mName def evaluate(self): if not self.mIsEvaluated: flagDBG().out(flagDBG.INFO, "PkgInfo.evaluate", "Evaluating %s" % self.mName) self.mVariableDict= Utils.parsePcFile(self.mFile) self.mIsEvaluated = True def getInfo(self): self.evaluate() return self.mVariableDict class OptionsEvaluator: def __init__(self): if len(sys.argv) < 2: self.printHelp() # This is only the args....(first arg is stripped) def evaluateArgs(self, args): # Catch any args that need to be tended to immediately # Process args in the order that they were recieved. Some options are not # shown below because they are sub-options of an option below (--strip-dups) for option in args: if option.startswith("--verbose-debug"): flagDBG().setLevel(flagDBG.VERBOSE) if option.startswith("--debug"): flagDBG().setLevel(flagDBG.INFO) elif option.startswith("--from-file"): val_start = option.find('=') + 1 file = option[val_start:] Utils.EXTRA_FLAGPOLL_FILES = Utils.EXTRA_FLAGPOLL_FILES + ":" + file elif option.startswith("--help"): self.printHelp() sys.exit(0) elif option.startswith("--version"): print "%s.%s.%s" % Utils.getFlagpollVersion() sys.exit(0) elif option.startswith("--list-all"): PkgDB().printAllPackages() continue listedAgentNames = [] agent = None num_args = len(args) curr_arg = 0 output_options = [] # (option, name/"") important_options = [] # ones that need special attention while curr_arg < num_args: if args[curr_arg].startswith("--atleast-version"): val_start = args[curr_arg].find('=') + 1 atleast_version = args[curr_arg][val_start:] atleast_filter = Filter("Version", lambda x,v=atleast_version: x >= v) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(atleast_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --at-least-version") continue if args[curr_arg].startswith("--cflags-only-I"): output_options.append(("cflags-only-I", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--cflags-only-other"): output_options.append(("cflags-only-other", "")) curr_arg = curr_arg + 1 continue #This could be the catch all for the above ones to and then filter based on what is asked... #For clarity of course... if args[curr_arg].startswith("--cflags"): output_options.append(("cflags", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--extra-paths"): val_start = args[curr_arg].find('=') + 1 paths = args[curr_arg][val_start:] Utils.EXTRA_FLAGPOLL_SEARCH_PATHS = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS + ":" + paths curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--exact-version"): val_start = args[curr_arg].find('=') + 1 exact_version = args[curr_arg][val_start:] exact_filter = Filter("Version", lambda x,v=exact_version: x == v) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(exact_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --exact-version") continue if args[curr_arg].startswith("--exists"): important_options.append("exists") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--from-file"): val_start = args[curr_arg].find('=') + 1 file = args[curr_arg][val_start:] file_filter = Filter("FlagpollFilename", lambda x,f=file: x == f) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(file_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --from-file") continue if args[curr_arg].startswith("--info"): important_options.append("info") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--print-pkg-options"): important_options.append("print-pkg-options") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--keep-dups"): Utils.setKeepDups(True) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-l"): output_options.append(("libs-only-l", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-L"): output_options.append(("libs-only-L", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-other"): output_options.append(("libs-only-other", "")) curr_arg = curr_arg + 1 continue #This could be the catch all for the above ones to and then filter based on what is asked... if args[curr_arg].startswith("--libs"): output_options.append(("libs", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--require-all"): rlen = len("--require-all") req_string = args[curr_arg][rlen:] req_string = req_string.replace('-','_') curr_arg = curr_arg + 1 if req_string.find("<=") != -1: op_start = req_string.find("<=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x <= v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find(">=") != -1: op_start = req_string.find(">=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x >= v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find(">") != -1: op_start = req_string.find(">") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x > v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("<") != -1: op_start = req_string.find("<") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x < v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("=") != -1: op_start = req_string.find("=") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x == v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("=") == -1: new_filter = Filter(req_string, lambda x: len(x) > 0) DepResolutionSystem().addFilter(new_filter) continue continue if args[curr_arg].startswith("--require-"): rlen = len("--require-") req_string = args[curr_arg][rlen:] req_string = req_string.replace('-','_') curr_arg = curr_arg + 1 if agent is None: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --require") if req_string.find("<=") != -1: op_start = req_string.find("<=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x <= v) agent.addFilter(new_filter) continue if req_string.find(">=") != -1: op_start = req_string.find(">=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x >= v) agent.addFilter(new_filter) continue if req_string.find(">") != -1: op_start = req_string.find(">") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x > v) agent.addFilter(new_filter) continue if req_string.find("<") != -1: op_start = req_string.find("<") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x < v) agent.addFilter(new_filter) continue if req_string.find("=") != -1: op_start = req_string.find("=") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x == v) agent.addFilter(new_filter) continue if req_string.find("=") == -1: new_filter = Filter(req_string, lambda x: len(x) > 0) agent.addFilter(new_filter) continue continue if args[curr_arg].startswith("--no-deps"): if agent is not None: agent.setCheckDepends(False) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --no-deps") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--require="): val_start = args[curr_arg].find('=') + 1 req_var = args[curr_arg][val_start:] curr_arg = curr_arg + 1 DepResolutionSystem().makeRequireFilter(req_var) continue if args[curr_arg].startswith("--modversion"): if agent is not None: output_options.append(("Version", agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --modversion") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--max-release"): val_start = args[curr_arg].find('=') + 1 max_release = args[curr_arg][val_start:] max_filter = Filter("Version", lambda x,v=max_release: x.startswith(v)) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(max_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --max-release") continue if args[curr_arg].startswith("--static"): DepResolutionSystem().setPrivateRequires(True) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--variable"): val_start = args[curr_arg].find('=') + 1 fetch_var = args[curr_arg][val_start:] if agent is not None: output_options.append((fetch_var, agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --variable") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--get-all"): rlen = len("--get-all-") get_string = args[curr_arg][rlen:] get_string = get_string.replace('-','_') output_options.append((get_string, "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--get"): rlen = len("--get-") get_string = args[curr_arg][rlen:] get_string = get_string.replace('-','_') if agent is not None: output_options.append((get_string, agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --get") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--concat"): important_options.append("concat") curr_arg = curr_arg + 1 continue if not args[curr_arg].startswith("--"): name = args[curr_arg] curr_arg = curr_arg + 1 if PkgDB().checkPackage(name): agent = DepResolutionSystem().createResolveAgent(name) listedAgentNames.append(name) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Package %s" % name) sys.exit(1) continue if args[curr_arg] != "--debug" and args[curr_arg] != "--verbose-debug": flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Option: %s" % args[curr_arg]) curr_arg = curr_arg + 1 DepResolutionSystem().resolveDeps() pkgs = DepResolutionSystem().getPackages() for p in pkgs: if not p: for option in important_options: if option == "exists": print "no" sys.exit(1) flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found") if len(pkgs) == 0: for option in important_options: if option == "exists": print "no" sys.exit(1) flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found") sys.exit(1) concat = False for option in important_options: if option == "exists": print "yes" return sys.exit(0) # already checked for none above if option == "concat": concat = True if option == "info": pkg_info_list = [] for pkg in pkgs: if pkg.getName() in listedAgentNames: print pkg.getName() pkg_info = pkg.getInfo() for key in pkg_info.keys(): print " %s : %s" % (key, pkg_info[key]) if option == "print-pkg-options": print "" print "All options below would start with (--get-/--get-all-/--require-/--require-all-)" print "NOTE: this list does not include the standard variables that are exported." print "" for pkg in pkgs: if pkg.getName() not in listedAgentNames: continue print "Package: " + pkg.getName() for key in pkg.getInfo().keys(): if key not in [ "Name", "Description", "URL", "Version", "Requires", "Requires.private", "Conflicts", "Libs", "Libs.private", "Cflags", "Provides", "Arch", "FlagpollFilename", "prefix" ]: print " " + key.replace('_','-') #print output_options #output_options = [] #output_single = [] #Process options here.............. concat_list = [] if concat: print_option = lambda x: concat_list.extend(x) else: print_option = lambda x: Utils.printList(x) for option in output_options: if option[0] == "cflags": print_option(Utils.stripDupIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "cflags-only-I": print_option(Utils.cflagsOnlyDirIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "cflags-only-other": print_option(Utils.cflagsOnlyOtherIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "libs-only-l": print_option(Utils.libsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs-only-L": print_option(Utils.libDirsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs-only-other": print_option(Utils.libsOnlyOtherLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs": print_option(Utils.stripDupLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) else: print_option(Utils.stripDupInList(self.getVarFromPkgs(option[0], pkgs, option[1]))) if concat: Utils.printList(Utils.stripDupInList(concat_list)) def getVarFromPkgs(self, var, pkgs, pkg_name=""): var_list = [] ext_vars = [] if var == "Libs": if DepResolutionSystem().checkPrivateRequires: ext_vars.append("Libs.private") if pkg_name == "": for pkg in pkgs: if pkg: var_list.extend(pkg.getVariable(var).split(' ')) for extra_var in ext_vars: var_list.extend(pkg.getVariable(extra_var).split(' ')) else: for pkg in pkgs: if pkg: if pkg.getName() == pkg_name: var_list.extend(pkg.getVariable(var).split(' ')) for extra_var in ext_vars: var_list.extend(pkg.getVariable(extra_var).split(' ')) return var_list def printHelp(self): print "usage: flagpoll pkg options [pkg options] [generic options]" print " " print "generic options:" print " --help show this help message and exit" print " --version output version of flagpoll" print " --list-all list all known packages" print " --debug show debug information" print " --verbose-debug show verbose debug information" print " --extra-paths=EXTRA_PATHS" print " extra paths for flagpoll to search for meta-data files" print " --concat concatenate all output and output as one line" print " --keep-dups do not strip out all duplicate info from options" print " --info show information for packages" print " --print-pkg-options show pkg specific options" print " " print "options:" print " --modversion output version for package" print " --require=REQUIRE adds additional requirements for packages ex. 32/64" print " --libs output all linker flags" print " --static output linker flags for static linking" print " --libs-only-l output -l flags" print " --libs-only-other output other libs (e.g. -pthread)" print " --libs-only-L output -L flags" print " --cflags output all pre-processor and compiler flags" print " --cflags-only-I output -I flags" print " --cflags-only-other output cflags not covered by the cflags-only-I option" print " --exists return 0 if the module(s) exist" print " --from-file=FILE use the specified FILE for the package" #print " --print-provides print which packages the package provides" #print " --print-requires print which packages the package requires" print " --no-deps do not lookup dependencies for the package" print " --atleast-version=ATLEAST_VERSION" print " return 0 if the module is at least version" print " ATLEAST_VERSION" print " --exact-version=EXACT_VERSION" print " return 0 if the module is exactly version" print " EXACT_VERSION" print " --max-release=MAX_RELEASE" print " return 0 if the module has a release that has a" print " version of MAX_RELEASE and will return the max" print " --variable=VARIABLE get the value of a variable" print " " print "dynamic options(replace VAR with a variable you want to get/filter on)" print " NOTE: replace underscores with dashes in VAR" print " NOTE: quotes are needed around <,>,= combinations" print " --get-VAR get VAR from package" print " --get-all-VAR get VAR from package and its deps" print " --require-VAR[<,>,=VAL]" print " require that a var is defined for a package" print " or optionally use equality operators against VAL" print " --require-all-VAR[<,>,=VAL]" print " require that a var is defined for all packages" print " or optionally use equality operators against VAL" print "" print "extending search path" print " FLAGPOLL_PATH environment variable that can be set to" print " extend the search path for .fpc/.pc files" sys.exit(0) def main(): # GO! # Initialize singletons and the start evaluating my_dbg = flagDBG() my_dep_system = DepResolutionSystem() opt_evaluator = OptionsEvaluator() opt_evaluator.evaluateArgs(sys.argv[1:]) sys.exit(0) if __name__ == "__main__": main()
Python
#!/usr/bin/env python # ----------------------------------------------------------------- # # Flag Poll: A tool to extract flags from installed applications # for compiling, settting variables, etc. # # Original Authors: # Daniel E. Shipton <dshipton@gmail.com> # # Flag Poll is Copyright (C) 2006 by Daniel E. Shipton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to: # Free SoftwareFoundation, Inc. # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # # ----------------------------------------------------------------- """Makes a flagpole .fpc file from user input. v0.9 coded by Jeff Groves""" import os import sys import getopt ##String prompts for the input varPrompt = """Convience variables (one 'var_name= var_definition' per line,""" + \ """ empty line when done)""" namePrompt = "Formal Name" descriptionPrompt = "Description" urlPrompt = "URL" providesPrompt = "One or more names to look package up by: (Provides)" versionPrompt = "Version (x.y.z)" architecturePrompt = "Architecture" requirePrompt = "Requires" libPrompt = "Linker Flags (-lfoo -L/usr/lib)" staticLibPrompt = "Static Linking Flags/Libs (extra private libs)" compileFlagsPrompt = "Compile/Include Flags (-I/usr -fpge -O2)" fileNamePrompt = "FPC File's Name" def usage(): """Prints a list of acceptable arguments for fpcmaker.py.""" print """ Fpcmaker.py Options: -n, --name= : Sets %s -d, --description= : Sets %s -u, --url= : Sets %s -p, --provides= : Sets %s -v, --version= : Sets %s -a, --architecture= : Sets %s -r, --requires= : Sets %s -l, --libs= : Sets %s -c, --cflags= : Sets %s -s, --static= : Sets %s -f, --file= : Sets %s """ %(namePrompt, descriptionPrompt, urlPrompt, providesPrompt, versionPrompt, architecturePrompt, requirePrompt, libPrompt, compileFlagsPrompt, staticLibPrompt, fileNamePrompt) return def checkFileName(fileName): """Checks if the fpc file name's blank, contains slashes, or exists.""" nameCleared = False writeFile = True confirms = ['y', 'Y', 'yes', 'Yes'] ##Loops until the name clears or writing the file's aborted. while(not nameCleared and writeFile): ##If it's blank, give the option of aborting the program. if fileName == "": choice = raw_input("Do you want to abort writing the" + " .fpc file? (Y/N): ") if choice not in confirms: fileName = raw_input("Please enter a different name for the" + " .fpc file: ") else: writeFile = False ##If it contains slashes, ask for another name. elif '/' in fileName or '\\' in fileName: print "I can't write to %s because it contains slashes."%(fileName) fileName = raw_input("Please enter a different name for the" + " .fpc file: ") ##If it already exists, ask if they want to overwrite. ##If not, ask for another name. elif os.path.exists(fileName): choice = raw_input("The file %s already exists." %(fileName) + " Do you want to overwrite it? (Y/N): ") if choice not in confirms: fileName = raw_input("Please enter a different name for the" + " .fpc file: ") else: nameCleared = True else: nameCleared = True return [fileName, writeFile] ##Booleans for whether that argument was sent in the command line varSet = False providesSet = False nameSet = False descriptionSet = False urlSet = False architectureSet = False versionSet = False requiresSet = False libsSet = False compileFlagsSet = False staticLibSet = False fileNameSet = False ##Get the options & arguments sent. arguments = sys.argv[1:] try: opts, args = getopt.getopt(arguments, "p:n:u:d:a:r:v:l:c:s:f:", ["provides=", "name=", "url=", "description=", "architecture=", "requires=", "version=", "libs=", "cflags=", "static=", "file="]) ##Send them usage info if they enter a wrong argument except getopt.GetoptError: usage() sys.exit(2) for opt, arg in opts: if opt in ('-p', '--provides'): providesSet = True provides = arg elif opt in ('-n', '--name'): nameSet = True name = arg elif opt in ('-v', '--version'): versionSet = True version = arg elif opt in ('-u', '--url'): urlSet = True url = arg elif opt in ('-d', '--description'): descriptionSet = True description = arg elif opt in ('-a', '--architecture'): architectureSet = True architecture = arg elif opt in ('-r', '--requires'): requiresSet = True requires = arg elif opt in ('-l', '--libs'): libsSet = True libs = arg elif opt in ('-c', '--cflags'): compileFlagsSet = True compileFlags = arg elif opt in ('-s', '--static'): staticLibSet = True staticLib = arg elif opt in ('-f', '--file'): fileNameSet = True fileName = arg ##Grab any input not passed in the arguments from the user. if not varSet: varLine = None variables = "" print "%s:" %(varPrompt) while(varLine != ""): varLine = raw_input("") variables = variables + "%s\n" %(varLine) if not nameSet: name = raw_input("%s: " %(namePrompt)) if not descriptionSet: description = raw_input("%s: " %(descriptionPrompt)) if not urlSet: url = raw_input("%s: " %(urlPrompt)) if not versionSet: version = raw_input("%s: " %(versionPrompt)) if not providesSet: provides = raw_input("%s: " %(providesPrompt)) if not requiresSet: requires = raw_input("%s: " %(requirePrompt)) if not architectureSet: architecture = raw_input("%s: " %(architecturePrompt)) if not libsSet: libs = raw_input("%s: " %(libPrompt)) if not staticLibSet: staticLib = raw_input("%s: " %(staticLibPrompt)) if not compileFlagsSet: compileFlags = raw_input("%s: " %(compileFlagsPrompt)) if not fileNameSet: fileName = raw_input("%s: " %(fileNamePrompt)) ##Check the file's name. fileName, writeFile = checkFileName(fileName) ##If they chose not to overwrite, write the file. if writeFile: fpc = open(fileName, 'w') fpc.write("%s" %(variables)) fpc.write("Name: %s\n" %(name)) fpc.write("Description: %s\n" %(description)) fpc.write("URL: %s\n" %(url)) fpc.write("Version: %s\n" %(version)) fpc.write("Provides: %s\n" %(provides)) fpc.write("Requires: %s\n" %(requires)) fpc.write("Arch: %s\n" %(architecture)) fpc.write("Libs: %s\n" %(libs)) fpc.write("Libs.private: %s\n" %(staticLib)) fpc.write("Cflags: %s\n" %(compileFlags)) fpc.close() ##TESTER: Print the file out. fpc = open(fileName, 'r') ##TESTER print fpc.read() ##TESTER fpc.close ##TESTER
Python
#!/usr/bin/env python from distutils.core import setup setup( name='flagpoll', version='0.8.3', description='Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software.', author='Daniel E. Shipton', author_email='dshipton@infiscape.com', license='GPL', url='https://realityforge.vrsource.org/view/FlagPoll/WebHome', download_url='https://realityforge.vrsource.org/view/FlagPoll/FlagpollDownloads', scripts=['flagpoll'], long_description = "Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software. Think of it as the rpm of software development. It enables developers total control over which packages, versions, architectures, etc. that they want to use meta-data from.", data_files=[('share/flagpoll', ['flagpoll.fpc']), ('share/man/man1', ['flagpoll.1']), ('share/aclocal', ['flagpoll.m4'])] )
Python
#!/usr/bin/env python # ----------------------------------------------------------------- # # Flag Poll: A tool to extract flags from installed applications # for compiling, settting variables, etc. # # Original Authors: # Daniel E. Shipton <dshipton@gmail.com> # # Flag Poll is Copyright (C) 2006 by Daniel E. Shipton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to: # Free SoftwareFoundation, Inc. # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # # ----------------------------------------------------------------- """Makes a flagpole .fpc file from user input. v0.9 coded by Jeff Groves""" import os import sys import getopt ##String prompts for the input varPrompt = """Convience variables (one 'var_name= var_definition' per line,""" + \ """ empty line when done)""" namePrompt = "Formal Name" descriptionPrompt = "Description" urlPrompt = "URL" providesPrompt = "One or more names to look package up by: (Provides)" versionPrompt = "Version (x.y.z)" architecturePrompt = "Architecture" requirePrompt = "Requires" libPrompt = "Linker Flags (-lfoo -L/usr/lib)" staticLibPrompt = "Static Linking Flags/Libs (extra private libs)" compileFlagsPrompt = "Compile/Include Flags (-I/usr -fpge -O2)" fileNamePrompt = "FPC File's Name" def usage(): """Prints a list of acceptable arguments for fpcmaker.py.""" print """ Fpcmaker.py Options: -n, --name= : Sets %s -d, --description= : Sets %s -u, --url= : Sets %s -p, --provides= : Sets %s -v, --version= : Sets %s -a, --architecture= : Sets %s -r, --requires= : Sets %s -l, --libs= : Sets %s -c, --cflags= : Sets %s -s, --static= : Sets %s -f, --file= : Sets %s """ %(namePrompt, descriptionPrompt, urlPrompt, providesPrompt, versionPrompt, architecturePrompt, requirePrompt, libPrompt, compileFlagsPrompt, staticLibPrompt, fileNamePrompt) return def checkFileName(fileName): """Checks if the fpc file name's blank, contains slashes, or exists.""" nameCleared = False writeFile = True confirms = ['y', 'Y', 'yes', 'Yes'] ##Loops until the name clears or writing the file's aborted. while(not nameCleared and writeFile): ##If it's blank, give the option of aborting the program. if fileName == "": choice = raw_input("Do you want to abort writing the" + " .fpc file? (Y/N): ") if choice not in confirms: fileName = raw_input("Please enter a different name for the" + " .fpc file: ") else: writeFile = False ##If it contains slashes, ask for another name. elif '/' in fileName or '\\' in fileName: print "I can't write to %s because it contains slashes."%(fileName) fileName = raw_input("Please enter a different name for the" + " .fpc file: ") ##If it already exists, ask if they want to overwrite. ##If not, ask for another name. elif os.path.exists(fileName): choice = raw_input("The file %s already exists." %(fileName) + " Do you want to overwrite it? (Y/N): ") if choice not in confirms: fileName = raw_input("Please enter a different name for the" + " .fpc file: ") else: nameCleared = True else: nameCleared = True return [fileName, writeFile] ##Booleans for whether that argument was sent in the command line varSet = False providesSet = False nameSet = False descriptionSet = False urlSet = False architectureSet = False versionSet = False requiresSet = False libsSet = False compileFlagsSet = False staticLibSet = False fileNameSet = False ##Get the options & arguments sent. arguments = sys.argv[1:] try: opts, args = getopt.getopt(arguments, "p:n:u:d:a:r:v:l:c:s:f:", ["provides=", "name=", "url=", "description=", "architecture=", "requires=", "version=", "libs=", "cflags=", "static=", "file="]) ##Send them usage info if they enter a wrong argument except getopt.GetoptError: usage() sys.exit(2) for opt, arg in opts: if opt in ('-p', '--provides'): providesSet = True provides = arg elif opt in ('-n', '--name'): nameSet = True name = arg elif opt in ('-v', '--version'): versionSet = True version = arg elif opt in ('-u', '--url'): urlSet = True url = arg elif opt in ('-d', '--description'): descriptionSet = True description = arg elif opt in ('-a', '--architecture'): architectureSet = True architecture = arg elif opt in ('-r', '--requires'): requiresSet = True requires = arg elif opt in ('-l', '--libs'): libsSet = True libs = arg elif opt in ('-c', '--cflags'): compileFlagsSet = True compileFlags = arg elif opt in ('-s', '--static'): staticLibSet = True staticLib = arg elif opt in ('-f', '--file'): fileNameSet = True fileName = arg ##Grab any input not passed in the arguments from the user. if not varSet: varLine = None variables = "" print "%s:" %(varPrompt) while(varLine != ""): varLine = raw_input("") variables = variables + "%s\n" %(varLine) if not nameSet: name = raw_input("%s: " %(namePrompt)) if not descriptionSet: description = raw_input("%s: " %(descriptionPrompt)) if not urlSet: url = raw_input("%s: " %(urlPrompt)) if not versionSet: version = raw_input("%s: " %(versionPrompt)) if not providesSet: provides = raw_input("%s: " %(providesPrompt)) if not requiresSet: requires = raw_input("%s: " %(requirePrompt)) if not architectureSet: architecture = raw_input("%s: " %(architecturePrompt)) if not libsSet: libs = raw_input("%s: " %(libPrompt)) if not staticLibSet: staticLib = raw_input("%s: " %(staticLibPrompt)) if not compileFlagsSet: compileFlags = raw_input("%s: " %(compileFlagsPrompt)) if not fileNameSet: fileName = raw_input("%s: " %(fileNamePrompt)) ##Check the file's name. fileName, writeFile = checkFileName(fileName) ##If they chose not to overwrite, write the file. if writeFile: fpc = open(fileName, 'w') fpc.write("%s" %(variables)) fpc.write("Name: %s\n" %(name)) fpc.write("Description: %s\n" %(description)) fpc.write("URL: %s\n" %(url)) fpc.write("Version: %s\n" %(version)) fpc.write("Provides: %s\n" %(provides)) fpc.write("Requires: %s\n" %(requires)) fpc.write("Arch: %s\n" %(architecture)) fpc.write("Libs: %s\n" %(libs)) fpc.write("Libs.private: %s\n" %(staticLib)) fpc.write("Cflags: %s\n" %(compileFlags)) fpc.close() ##TESTER: Print the file out. fpc = open(fileName, 'r') ##TESTER print fpc.read() ##TESTER fpc.close ##TESTER
Python
#!/usr/bin/env python # ----------------------------------------------------------------- # # Flagpoll: A tool to extract flags from installed applications # for compiling, settting variables, etc. # # Original Authors: # Daniel E. Shipton <dshipton@gmail.com> # # Flagpoll is Copyright (C) 2006-2007 by Daniel E. Shipton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to: # Free SoftwareFoundation, Inc. # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # # ----------------------------------------------------------------- import sys, os, glob, os.path, copy, platform pj = os.path.join #################################################################### # SNAGGED FROM PYTHON 2.4 for versions under 2.4 #################################################################### import re as _re class _multimap: """Helper class for combining multiple mappings. Used by .{safe_,}substitute() to combine the mapping and keyword arguments. """ def __init__(self, primary, secondary): self._primary = primary self._secondary = secondary def __getitem__(self, key): try: return self._primary[key] except KeyError: return self._secondary[key] class _TemplateMetaclass(type): pattern = r""" %(delim)s(?: (?P<escaped>%(delim)s) | # Escape sequence of two delimiters (?P<named>%(id)s) | # delimiter and a Python identifier {(?P<braced>%(id)s)} | # delimiter and a braced identifier (?P<invalid>) # Other ill-formed delimiter exprs ) """ def __init__(cls, name, bases, dct): super(_TemplateMetaclass, cls).__init__(name, bases, dct) if 'pattern' in dct: pattern = cls.pattern else: pattern = _TemplateMetaclass.pattern % { 'delim' : _re.escape(cls.delimiter), 'id' : cls.idpattern, } cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE) class Template: """A string class for supporting $-substitutions.""" __metaclass__ = _TemplateMetaclass delimiter = '$' idpattern = r'[_a-z][_a-z0-9]*' def __init__(self, template): self.template = template # Search for $$, $identifier, ${identifier}, and any bare $'s def _invalid(self, mo): i = mo.start('invalid') lines = self.template[:i].splitlines(True) if not lines: colno = 1 lineno = 1 else: colno = i - len(''.join(lines[:-1])) lineno = len(lines) raise ValueError('Invalid placeholder in string: line %d, col %d' % (lineno, colno)) def substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): # Check the most common path first. named = mo.group('named') or mo.group('braced') if named is not None: val = mapping[named] # We use this idiom instead of str() because the latter will # fail if val is a Unicode containing non-ASCII characters. return '%s' % val if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: self._invalid(mo) raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) def safe_substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): named = mo.group('named') if named is not None: try: # We use this idiom instead of str() because the latter # will fail if val is a Unicode containing non-ASCII return '%s' % mapping[named] except KeyError: return self.delimiter + named braced = mo.group('braced') if braced is not None: try: return '%s' % mapping[braced] except KeyError: return self.delimiter + '{' + braced + '}' if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: return self.delimiter raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) #################################################################### # End Snagging #################################################################### class Utils: # Holds collection of small utility functions EXTRA_FLAGPOLL_SEARCH_PATHS = "" EXTRA_FLAGPOLL_FILES = "" path_list_cache = None # Cache of found path lists. (only calcuate once) KEEP_DUPS = False FLAGPOLL_LIST_OF_POSSIBLE_ERRORS = [] def addPossibleError(pos_err): Utils.FLAGPOLL_LIST_OF_POSSIBLE_ERRORS.append(pos_err) addPossibleError = staticmethod(addPossibleError) def getPossibleErrors(): return Utils.stripDupInList(Utils.FLAGPOLL_LIST_OF_POSSIBLE_ERRORS) getPossibleErrors = staticmethod(getPossibleErrors) def getFlagpollVersion(): FLAGPOLL_MAJOR_VERSION = 0 FLAGPOLL_MINOR_VERSION = 8 FLAGPOLL_PATCH_VERSION = 3 return ( FLAGPOLL_MAJOR_VERSION, FLAGPOLL_MINOR_VERSION, FLAGPOLL_PATCH_VERSION ) getFlagpollVersion = staticmethod(getFlagpollVersion) def getPathList(): if None != Utils.path_list_cache: return Utils.path_list_cache #TODO: expand LD_LIBRARY_PATH to 64/32/etc??? pkg_cfg_dir = [] flg_cfg_dir = [] ld_path = [] if os.environ.has_key("PKG_CONFIG_PATH"): pkg_cfg_dir = os.environ["PKG_CONFIG_PATH"].split(os.pathsep) if os.environ.has_key("FLAGPOLL_PATH"): flg_cfg_dir = os.environ["FLAGPOLL_PATH"].split(os.pathsep) ld_dirs = ['LD_LIBRARY_PATH', 'DYLD_LIBRARY_PATH'] for d in ld_dirs: if os.environ.has_key(d): cur_path = os.environ[d].split(os.pathsep) ld_path_pkg = [pj(p,'pkgconfig') for p in cur_path] ld_path_flg = [pj(p,'flagpoll') for p in cur_path] ld_path.extend(ld_path_pkg) ld_path.extend(ld_path_flg) extra_paths = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS.split(os.pathsep) path_list = extra_paths path_list.extend(flg_cfg_dir) path_list.extend(pkg_cfg_dir) path_list.extend(ld_path) path_list.extend(["/usr/lib64/pkgconfig", "/usr/lib/pkgconfig", "/usr/share/pkgconfig", "/usr/lib64/flagpoll", "/usr/lib/flagpoll", "/usr/share/flagpoll"]) flagDBG().out(flagDBG.VERBOSE, "Utils.getPathList", "Potential path list: " + str(path_list)) path_list = [p for p in path_list if os.path.exists(p)] flagDBG().out(flagDBG.INFO, "Utils.getPathList", "Using path list: " + str(path_list)) Utils.path_list_cache = path_list return path_list getPathList = staticmethod(getPathList) def getFileList(): flist = Utils.EXTRA_FLAGPOLL_FILES.split(":") filelist = [] for f in flist: if os.path.isfile(f): filelist.append(f) return filelist getFileList = staticmethod(getFileList) def setKeepDups(keep_dups): Utils.KEEP_DUPS = keep_dups setKeepDups = staticmethod(setKeepDups) def stripDupInList(gen_list): new_list = [] list_len = len(gen_list) i = 0 while i < list_len: item = gen_list[i].strip() if Utils.KEEP_DUPS: if len(item) > 0: new_list.append(item) continue if item == '-framework': item = '%s %s' % (item, gen_list[i + 1]) i += 1 if item not in new_list: if len(item) > 0: new_list.append(item) i += 1 return new_list stripDupInList = staticmethod(stripDupInList) def stripDupLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] dir_list = [] list_len = len(flag_list) i = 0 while i < list_len: flg = flag_list[i].strip() if len(flg) > 0: if flg.startswith("-L") or flg.startswith("-R") or \ flg.startswith("-F"): dir_list.append(flg) else: if flg == "-framework": flg = "%s %s" % (flg, flag_list[i + 1]) i += 1 lib_list.append(flg) i += 1 new_list = dir_list + lib_list return Utils.stripDupInList(new_list) stripDupLinkerFlags = staticmethod(stripDupLinkerFlags) def stripDupIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] extra_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-I"): inc_list.append(flg) else: extra_list.append(flg) extra_list.sort() new_list = inc_list + extra_list return Utils.stripDupInList(new_list) stripDupIncludeFlags = staticmethod(stripDupIncludeFlags) def cflagsOnlyDirIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-I"): inc_list.append(flg) return Utils.stripDupInList(inc_list) cflagsOnlyDirIncludeFlags = staticmethod(cflagsOnlyDirIncludeFlags) def cflagsOnlyOtherIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though extra_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if not flg.startswith("-I"): extra_list.append(flg) return Utils.stripDupInList(extra_list) cflagsOnlyOtherIncludeFlags = staticmethod(cflagsOnlyOtherIncludeFlags) def libsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-l"): lib_list.append(flg) return Utils.stripDupInList(lib_list) libsOnlyLinkerFlags = staticmethod(libsOnlyLinkerFlags) def libsOnlyOtherLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though other_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if not flg.startswith("-l") and not flg.startswith("-L") and not flg.startswith("-R"): other_list.append(flg) return Utils.stripDupInList(other_list) libsOnlyOtherLinkerFlags = staticmethod(libsOnlyOtherLinkerFlags) def libDirsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though dir_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-L") or flg.startswith("-R"): dir_list.append(flg) return Utils.stripDupInList(dir_list) libDirsOnlyLinkerFlags = staticmethod(libDirsOnlyLinkerFlags) def printList(gen_list): list_string = "" for item in gen_list: if len(item) > 0: list_string += str(item) list_string += " " print list_string.strip() printList = staticmethod(printList) def parsePcFile(filename): lines = open(filename).readlines() fvars = {} fvars["FlagpollFilename"] = filename lokals = {} lokals["fp_file_cwd"] = str(filename[:- ((len(os.path.basename(filename) ) + 1))]) lines.append("prefix: ${prefix}") append_next = False append_dict = {} append_key = "" for line in lines: line = line.strip() if not line: continue if append_next: tmp = append_dict[append_key] tmp = tmp[:-1] + " " + line append_dict[append_key] = tmp if tmp[-1:] == "\\": append_next = True else: append_next = False continue if line.startswith("#"): continue eq_pos = line.find('=') col_pos = line.find(':') if eq_pos < col_pos and eq_pos != -1 or col_pos == -1 and eq_pos != -1: # local variable name, val = line.split('=', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(lokals) except ValueError: flagDBG().out(flagDBG.WARN, "PkgInfo.parse", "%s has an invalid metadata file" % filename) lokals[name] = val if val[-1:] == "\\": append_next = True append_dict = lokals append_key = name continue if col_pos < eq_pos and col_pos != -1 or eq_pos == -1 and col_pos != -1: # exported variable name, val = line.split(':', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(lokals) except ValueError: flagDBG().out(flagDBG.ERROR, "PkgInfo.parse", "%s has an invalid metadata file" % filename) fvars[name] = val if val[-1:] == "\\": append_next = True append_dict = fvars append_key = name return fvars parsePcFile = staticmethod(parsePcFile) class flagDBG(object): # Logging class is really easy to use # Levels: # 0 - VERBOSE # 1 - INFO # 2 - WARN # 3 - ERROR VERBOSE = 0 INFO = 1 WARN = 2 ERROR = 3 __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if flagDBG.__initialized: return flagDBG.__initialized = True self.mLevel = self.WARN self.mLevelList = ["VERBOSE", "INFO", "WARN", "ERROR"] def setLevel(self, level): if level <= 3: self.mLevel = level def out(self, level, obj, message): if level == self.ERROR: if self.mLevel == self.VERBOSE: print self.mLevelList[level] + ":" + str(obj) + ": " + str(message) else: sys.stderr.write(self.mLevelList[level] + ": " + str(message) + "\n") errs = Utils.getPossibleErrors() if len(errs) > 0: sys.stderr.write("Possible culprits:\n") for pos_err in errs: sys.stderr.write( " " + str(pos_err) + "\n" ) sys.exit(1) if level >= self.mLevel: print self.mLevelList[level] + ":" + str(obj) + ": " + str(message) class DepResolutionSystem(object): """ You add PkgAgents with Filters into system and call resolve() you can check for succes by depsSatisfied() and get the list of packages that work back by calling getPackages() """ __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if DepResolutionSystem.__initialized: return DepResolutionSystem.__initialized = True self.mResolveAgents = [] self.mAgentDict = {} self.mFilters = [] self.mResolveAgentFilters = [] self.mInvalidPackageList = [] self.mSatisfied = False self.mAgentChangeList = [] # list of those responsible for adding Filters # to agents in higher in the chain than them # these are the first agents to ask that they pick # the next best package of them self.mAgentsVisitedList = [] # list of Agents that have been visited self.mResolvedPackageList = [] # list that is generated when deps are satified self.mCheckPrivateRequires = False self.mMadeDependList = False def getFilters(self): return self.mFilters def addFilter(self, filter): self.mFilters.append(filter) def addResolveAgentFilter(self, filter): self.mResolveAgentFilters.append(filter) def makeRequireFilter(self, requires): arch_list = [] arch_list.append("no_arch") arch_list.append("") if platform.system() == "Linux": if requires == "64": arch_list.append("x86_64") if requires == "32": arch_list.append("i386") arch_list.append("i486") arch_list.append("i586") arch_list.append("i686") if platform.system() == "Darwin": if requires == "64": arch_list.append("ppc64") if requires == "32": arch_list.append("ppc") if platform.system().startswith("IRIX"): arch_list.append(requires) new_filter = Filter("Arch", lambda x,v=arch_list: x in v) self.addFilter(new_filter) def createAgent(self, name): if self.checkAgentExists(name): return self.getAgent(name) else: agent = PkgAgent(name) flagDBG().out(flagDBG.INFO, "DepResSys.createAgent", "Adding %s" % name) self.addNewAgent(agent) return agent def createResolveAgent(self, name): if self.checkAgentExists(name): return self.getAgent(name) else: agent = PkgAgent(name) flagDBG().out(flagDBG.INFO, "DepResSys.createResolveAgent", "Adding %s" % name) self.addResolveAgent(agent) return agent def setPrivateRequires( self, req ): self.mCheckPrivateRequires = req def checkPrivateRequires(self): return self.mCheckPrivateRequires def checkAgentExists(self, name): return self.mAgentDict.has_key(name) def getAgent(self, name): if self.mAgentDict.has_key(name): return self.mAgentDict[name] else: flagDBG().out(flagDBG.ERROR, "DepResSys.getAgent", "Agent %s does not exist" % name) def addNewAgent(self, agent): if not self.checkAgentExists(agent): self.mAgentDict[agent.getName()] = agent def addResolveAgent(self, agent): if agent not in self.mResolveAgents: self.mResolveAgents.append(agent) for filt in self.mResolveAgentFilters: agent.addFilter(filt) def isSatisfied(self): return self.mSatisfied def updateResolvedPackages(self): pkg_list = [] agent_list = [] for agent in self.mResolveAgents: list_of_pkgs = agent.getCurrentPackageList(agent_list) pkg_list.extend(list_of_pkgs) self.mResolvedPackageList = pkg_list def getPackages(self): flagDBG().out(flagDBG.INFO, "DepResSys.getPackages", "Generating list of valid packages ") #str([pkg.getCurrentPackage.getName() for pkg in self.mResolvedPackageList])) # If this comes back empty then there isn't a valid set of packages to use self.updateResolvedPackages() return self.mResolvedPackageList def checkFiltersChanged(self): list_to_use = [] return True in [pkg.filtersChanged(list_to_use) for pkg in self.mResolveAgents] def resolveHelper(self): self.resolveAgentsChanged = True while self.resolveAgentsChanged: for agent in self.mResolveAgents: flagDBG().out(flagDBG.INFO, "DepResSys.resolveHelper", "Updating " + agent.getName()) agent.update(self.mAgentsVisitedList, self.mAgentChangeList) self.resolveAgentsChanged = self.checkFiltersChanged() # Ask mResolveAgents if they are done(they ask sub people) unless they are # really above you in the walk # If there were changes...run update on mResolveAgents again # at the end ask for pkglist..if it comes back empty then we don't # have a usable configuration for those packages def resolveDeps(self): self.resolveHelper() if not self.mMadeDependList: for agent in self.mResolveAgents: agent.makeDependList() self.mMadeDependList = True self.updateResolvedPackages() # Check if the first round through we found something # Otherwise we need to start removing packages that aren't viable # during the loop self.mSatisfied = (len(self.mResolvedPackageList) != 0) # remove top of packages that added Filters. # then move on to resolving again # remove more if neccesary agentChangeNumber = 0 while not self.mResolvedPackageList: if(self.mAgentChangeList[agentChangeNumber]): if self.mAgentChangeList[agentChangeNumber] in self.mInvalidPackageList: agentChangeNumber += 1 else: if(self.mAgentChangeList[agentChangeNumber].getViablePackages()): flagDBG().out(flagDBG.INFO, "DepResSys.resolveDeps", "Removing bad pkg from " + self.mAgentChangeList[agentChangeNumber].getName()) self.mInvalidPackageList.append(self.mAgentChangeList[agentChangeNumber].removeCurrentPackage()) else: flagDBG().out(flagDBG.INFO, "DepResSys.resolveDeps", "No combinations.. Resetting " + self.mAgentChangeList[agentChangeNumber].getName()) self.mAgentChangeList[agentChangeNumber].reset() agentChangeNumber += 1 self.resolveHelper() self.updateResolvedPackages() self.mSatisfied = (len(self.mResolvedPackageList) != 0) return class PkgAgent: """ Agent that keeps track of the versions for a package given some filters and the addition of Filters """ # Makes a PkgAgent that finds its current package with the version reqs def __init__(self, name): if DepResolutionSystem().checkAgentExists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "Package Agent %s already exists" % self.mName) self.mName = name flagDBG().out(flagDBG.INFO, "PkgAgent", "Creating:" + str(self.mName)) if not PkgDB().exists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "No info for package: %s" % self.mName) #XXX Doesn't keep filters added for a redo... DepResolutionSystem().addNewAgent(self) self.mFilterList = [] self.mFilterList.extend(DepResolutionSystem().getFilters()) self.mBasePackageList = PkgDB().getPkgInfos(name) self.mBasePackageList.sort(lambda lhs, rhs: cmp(rhs.getVariable('Version'), lhs.getVariable('Version'))) for filt in self.mFilterList: self.mBasePackageList = filt.filter(self.mBasePackageList) if len(self.mBasePackageList) == 0: flagDBG().out(flagDBG.ERROR, "PkgAgent", "No viable packages for: %s" % self.mName) self.mViablePackageList = copy.deepcopy(self.mBasePackageList) if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mFiltersChanged = True self.mCheckDepends = True self.mAgentDependList = [] def getName(self): return self.mName def setCheckDepends(self, tf): self.mCheckDepends = tf #Filter("Version", lambda x: x == "4.5") def makeDependList(self): if not self.mCheckDepends: self.mAgentDependList = [] return dep_list = [] if self.mCurrentPackage: req_string = self.mCurrentPackage.getVariable("Requires") if DepResolutionSystem().checkPrivateRequires(): req_string = req_string + " " + self.mCurrentPackage.getVariable("Requires.private") req_string = req_string.strip() if req_string == "": return req_string = req_string.replace(',', ' ') req_string = req_string.replace('(', ' ') req_string = req_string.replace(')', ' ') space_req_string_list = req_string.split(' ') req_string_list = [] for entry in space_req_string_list: if len(entry) > 0: req_string_list.append(entry) i = 0 flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList", self.mCurrentPackage.getName() + " requires: " + str(req_string_list)) while len(req_string_list) > i: if PkgDB().exists(req_string_list[i]): new_filter = [] new_agent = DepResolutionSystem().createAgent(req_string_list[i]) if len(req_string_list) > i+1: if req_string_list[i+1] == "=": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x == v) elif req_string_list[i+1] == "<=": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x <= v) elif req_string_list[i+1] == ">=": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x >= v) elif req_string_list[i+1] == ">": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x > v) elif req_string_list[i+1] == "<": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x < v) else: i += 1 else: i += 1 dep_list.append(new_agent) if new_filter: i+=3 new_agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "PkgAgent.makeDependList", "Package %s depends on %s but does not seem to be installed." % (self.mName, str(req_string_list[i]))) flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList", str(self.mName) + " : List is:" + str([pkg.getName() for pkg in dep_list])) self.mAgentDependList = dep_list def filtersChanged(self, packageList): tf_list = [self.mFiltersChanged] if self.mName not in packageList: packageList.append(self.mName) for pkg in self.mAgentDependList: tf_list.append(pkg.filtersChanged(packageList)) return True in tf_list def getCurrentPackageList(self, packageList): pkgs = [] if self.mName not in packageList: flagDBG().out(flagDBG.INFO, "PkgAgent.getCurrentPackageList", "Package: %s" % self.mName) pkgs.append(self.mCurrentPackage) packageList.append(self.mName) # Make depend list if we are supposed to self.updateFilters() self.makeDependList() for pkg in self.mAgentDependList: pkgs.extend(pkg.getCurrentPackageList(packageList)) return pkgs # current pkginfo for me def getCurrentPkgInfo(self): return self.mCurrentPackage # Someone else usually places these on me # I keep track of those separately def addFilter(self, filter): flagDBG().out(flagDBG.INFO, "PkgAgent.addFilter", "Filter %s" % self.mName + " on %s." % filter.getVarName()) self.mFiltersChanged = True self.mFilterList.append(filter) def removeCurrentPackage(self): flagDBG().out(flagDBG.INFO, "PkgAgent.removeCurrentPackage", "Removing current package of %s" % self.mName) if self.mViablePackageList: ret_val = self.mViablePackageList[0] in self.mBasePackageList del self.mViablePackageList[0] if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] return ret_val def update(self, agentVisitedList, agentChangeList): flagDBG().out(flagDBG.INFO, "PkgAgent.update", "%s" % self.mName) if self.mName in agentVisitedList: return agentVisitedList.append(self.mName) if self.mFiltersChanged: self.mFiltersChanged = False self.updateFilters() # TODO: checkFilters and add them # if a pkg is in visitedList then add yourself to agentChangeList for pkg in self.mAgentDependList: pkg.update(agentVisitedList, agentChangeList) return def updateFilters(self): for filt in self.mFilterList: self.mViablePackageList = filt.filter(self.mViablePackageList) flagDBG().out(flagDBG.INFO, "PkgAgent.updateFilters", "%s has " % self.mName + str(len(self.mViablePackageList)) + " left") if len(self.mViablePackageList) > 0: self.mCurrentPackage = self.mViablePackageList[0] else: for f in self.mFilterList: Utils.addPossibleError(str(self.mName) + " -> " + str(f.getVarName())) self.mCurrentPackage = [] def reset(self): flagDBG().out(flagDBG.INFO, "PkgAgent.reset", "Resetting package: %s" % self.mName) self.mViablePackageList = self.mBasePackageList if self.mViablePackageList: self.mCurrentPacakge = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mFilterList = DepResolutionSystem().getFilters() self.mAgentDependList = [] self.mFiltersChanged = True return class Filter: """ A single Filter that knows how to filter the list it recieves Will be inheireted....?..? """ def __init__(self, variableName, testCallable): self.mVarName = variableName self.mTestCallable = testCallable def getVarName(self): return self.mVarName def filter(self, pkg_info_list): ret_pkg_list = [] # Filter first for pkg in pkg_info_list: var = pkg.getVariable(self.mVarName) if self.mTestCallable(var): flagDBG().out(flagDBG.INFO, "Filter", "Passed: %s:" % pkg.getName() + " %s is " % self.mVarName + str(var)) ret_pkg_list.append(pkg) else: flagDBG().out(flagDBG.INFO, "Filter", "Failed: %s:" % pkg.getName() + " %s is " % self.mVarName + str(var)) # Now sort ret_pkg_list.sort(lambda lhs, rhs: cmp(rhs.getVariable(self.mVarName), lhs.getVariable(self.mVarName))) return ret_pkg_list #requires: qt == 4.5 #Filter("Version", lambda x: x <= "4.5") #Filter("Version", lambda x: x <= "4.5") class PkgDB(object): """ Holds all the neccesary information to evaluate itself when needed. Is in charge of holding a list of PkgInfo's that contain info about the package. """ __initialized = False def __init__(self): if self.__initialized: return self.__initialized = True self.mPkgInfos = {} # {pkg_name: List of package infos} self.populatePkgInfoDBPcFiles() self.populatePkgInfoDBFpcFiles() def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def printAllPackages(self): list_of_package_names = [] for pkg in self.mPkgInfos: list_of_package_names.append(pkg) for name in list_of_package_names: print name sys.exit(0) def getVariables(self, name, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariable", "Finding " + str(variable_list) + " in " + str(name)) ret_list = [] for var in variable_list: if self.mPkgInfos.has_key(name): ret_list.extend(self.mPkgInfos[name][0].getVariable(var)) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariable", "Package %s not found." % name) return ret_list def checkPackage(self, name): flagDBG().out(flagDBG.INFO, "PkgDB.checkPackage", "Finding " + str(name)) if self.mPkgInfos.has_key(name): return True else: flagDBG().out(flagDBG.ERROR, "PkgDB.CheckPackage", "Package %s not found." % name) return False def getVariablesAndDeps(self, pkg_list, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariablesAndDeps", "Finding " + str(variable_list) + " in " + str(pkg_list)) if DepResolutionSystem().checkPrivateRequires(): temp_var_list = [] for var in variable_list: temp_var_list.append(var.join(".private")) variable_list = variable_list + temp_var_list for name in pkg_list: if self.mPkgInfos.has_key(name): agent = DepResolutionSystem().createAgent(name) DepResolutionSystem().addResolveAgent(agent) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariablesAndDeps", "Package %s not found." % name) DepResolutionSystem().resolveDeps() pkgs = DepResolutionSystem().getPackages() var_list = [] for pkg in pkgs: if pkg: for var in variable_list: var_list.extend(pkg.getVariable(var).split(' ')) return var_list def getPkgInfos(self, name): if self.mPkgInfos.has_key(name): return self.mPkgInfos[name] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getPkgInfos", "Package %s not found." % name) def exists(self, name): return self.mPkgInfos.has_key(name) def getInfo(self, name): if self.mPkgInfos.has_key(name): return [pkg.getInfo() for pkg in self.mPkgInfos[name]] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getInfo", "Package %s not found." % name) def buildPcFileDict(self): """ Builds up a dictionary of {name: list of files for name} """ pc_dict = {} for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.pc")) # List of .pc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these pc files: %s" % str(glob_list)) for g in glob_list: # Get key name and add file to value list in dictionary key = os.path.basename(g)[:-3] # Strip .pc off the filename...rstrip no worky pc_dict.setdefault(key, []).append(g) for f in Utils.getFileList(): if f.endswith(".pc"): key = os.path.basename(f)[:-3] # Strip .pc off the filename...rstrip no worky pc_dict.setdefault(key, []).append(f) return pc_dict # { "key", [ "list", "of", "corresponding", "pc", "files"] } def populatePkgInfoDBPcFiles(self): dict_to_pop_from = self.buildPcFileDict() for (pkg,files) in dict_to_pop_from.iteritems(): for f in files: self.mPkgInfos.setdefault(pkg,[]).append(PkgInfo(pkg, f, "pc")) def buildFpcFileList(self): """ Builds up a dictionary of {name: list of files for name} """ file_list = [] for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.fpc")) # List of .fpc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these fpc files: %s" % str(glob_list)) for g in glob_list: file_list.append(g) for f in Utils.getFileList(): if f.endswith(".fpc"): file_list.append(f) return file_list # [ "list", "of", "fpc", "files"] def populatePkgInfoDBFpcFiles(self): list_to_add = self.buildFpcFileList() for filename in list_to_add: var_dict = Utils.parsePcFile(filename) if not var_dict.has_key("Provides"): flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Provides" % str(filename)) continue if not var_dict.has_key("Arch"): flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Arch" % str(filename)) continue provides_string = var_dict["Provides"] provides_string = provides_string.replace(',', ' ') provides_string = provides_string.replace('(', ' ') provides_string = provides_string.replace(')', ' ') for key in provides_string.split(" "): if len(key) > 0: self.mPkgInfos.setdefault(key, []).append(PkgInfo(key, filename, "fpc", var_dict)) class PkgInfo: """ Holds the information for a package file on the system. These however are evaluated when the need arises. """ def __init__(self, name, file, type, varDict={}): self.mName = name self.mFile = file self.mIsEvaluated = False self.mType = type self.mVariableDict = varDict if self.mType == "fpc": self.mIsEvaluated = True def getVariable(self, variable): self.evaluate() return self.mVariableDict.get(variable,"") def getName(self): return self.mName def evaluate(self): if not self.mIsEvaluated: flagDBG().out(flagDBG.INFO, "PkgInfo.evaluate", "Evaluating %s" % self.mName) self.mVariableDict= Utils.parsePcFile(self.mFile) self.mIsEvaluated = True def getInfo(self): self.evaluate() return self.mVariableDict class OptionsEvaluator: def __init__(self): if len(sys.argv) < 2: self.printHelp() # This is only the args....(first arg is stripped) def evaluateArgs(self, args): # Catch any args that need to be tended to immediately # Process args in the order that they were recieved. Some options are not # shown below because they are sub-options of an option below (--strip-dups) for option in args: if option.startswith("--verbose-debug"): flagDBG().setLevel(flagDBG.VERBOSE) if option.startswith("--debug"): flagDBG().setLevel(flagDBG.INFO) elif option.startswith("--from-file"): val_start = option.find('=') + 1 file = option[val_start:] Utils.EXTRA_FLAGPOLL_FILES = Utils.EXTRA_FLAGPOLL_FILES + ":" + file elif option.startswith("--help"): self.printHelp() sys.exit(0) elif option.startswith("--version"): print "%s.%s.%s" % Utils.getFlagpollVersion() sys.exit(0) elif option.startswith("--list-all"): PkgDB().printAllPackages() continue listedAgentNames = [] agent = None num_args = len(args) curr_arg = 0 output_options = [] # (option, name/"") important_options = [] # ones that need special attention while curr_arg < num_args: if args[curr_arg].startswith("--atleast-version"): val_start = args[curr_arg].find('=') + 1 atleast_version = args[curr_arg][val_start:] atleast_filter = Filter("Version", lambda x,v=atleast_version: x >= v) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(atleast_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --at-least-version") continue if args[curr_arg].startswith("--cflags-only-I"): output_options.append(("cflags-only-I", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--cflags-only-other"): output_options.append(("cflags-only-other", "")) curr_arg = curr_arg + 1 continue #This could be the catch all for the above ones to and then filter based on what is asked... #For clarity of course... if args[curr_arg].startswith("--cflags"): output_options.append(("cflags", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--extra-paths"): val_start = args[curr_arg].find('=') + 1 paths = args[curr_arg][val_start:] Utils.EXTRA_FLAGPOLL_SEARCH_PATHS = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS + ":" + paths curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--exact-version"): val_start = args[curr_arg].find('=') + 1 exact_version = args[curr_arg][val_start:] exact_filter = Filter("Version", lambda x,v=exact_version: x == v) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(exact_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --exact-version") continue if args[curr_arg].startswith("--exists"): important_options.append("exists") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--from-file"): val_start = args[curr_arg].find('=') + 1 file = args[curr_arg][val_start:] file_filter = Filter("FlagpollFilename", lambda x,f=file: x == f) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(file_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --from-file") continue if args[curr_arg].startswith("--info"): important_options.append("info") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--print-pkg-options"): important_options.append("print-pkg-options") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--keep-dups"): Utils.setKeepDups(True) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-l"): output_options.append(("libs-only-l", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-L"): output_options.append(("libs-only-L", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-other"): output_options.append(("libs-only-other", "")) curr_arg = curr_arg + 1 continue #This could be the catch all for the above ones to and then filter based on what is asked... if args[curr_arg].startswith("--libs"): output_options.append(("libs", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--require-all"): rlen = len("--require-all") req_string = args[curr_arg][rlen:] req_string = req_string.replace('-','_') curr_arg = curr_arg + 1 if req_string.find("<=") != -1: op_start = req_string.find("<=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x <= v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find(">=") != -1: op_start = req_string.find(">=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x >= v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find(">") != -1: op_start = req_string.find(">") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x > v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("<") != -1: op_start = req_string.find("<") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x < v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("=") != -1: op_start = req_string.find("=") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x == v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("=") == -1: new_filter = Filter(req_string, lambda x: len(x) > 0) DepResolutionSystem().addFilter(new_filter) continue continue if args[curr_arg].startswith("--require-"): rlen = len("--require-") req_string = args[curr_arg][rlen:] req_string = req_string.replace('-','_') curr_arg = curr_arg + 1 if agent is None: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --require") if req_string.find("<=") != -1: op_start = req_string.find("<=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x <= v) agent.addFilter(new_filter) continue if req_string.find(">=") != -1: op_start = req_string.find(">=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x >= v) agent.addFilter(new_filter) continue if req_string.find(">") != -1: op_start = req_string.find(">") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x > v) agent.addFilter(new_filter) continue if req_string.find("<") != -1: op_start = req_string.find("<") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x < v) agent.addFilter(new_filter) continue if req_string.find("=") != -1: op_start = req_string.find("=") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x == v) agent.addFilter(new_filter) continue if req_string.find("=") == -1: new_filter = Filter(req_string, lambda x: len(x) > 0) agent.addFilter(new_filter) continue continue if args[curr_arg].startswith("--no-deps"): if agent is not None: agent.setCheckDepends(False) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --no-deps") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--require="): val_start = args[curr_arg].find('=') + 1 req_var = args[curr_arg][val_start:] curr_arg = curr_arg + 1 DepResolutionSystem().makeRequireFilter(req_var) continue if args[curr_arg].startswith("--modversion"): if agent is not None: output_options.append(("Version", agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --modversion") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--max-release"): val_start = args[curr_arg].find('=') + 1 max_release = args[curr_arg][val_start:] max_filter = Filter("Version", lambda x,v=max_release: x.startswith(v)) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(max_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --max-release") continue if args[curr_arg].startswith("--static"): DepResolutionSystem().setPrivateRequires(True) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--variable"): val_start = args[curr_arg].find('=') + 1 fetch_var = args[curr_arg][val_start:] if agent is not None: output_options.append((fetch_var, agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --variable") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--get-all"): rlen = len("--get-all-") get_string = args[curr_arg][rlen:] get_string = get_string.replace('-','_') output_options.append((get_string, "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--get"): rlen = len("--get-") get_string = args[curr_arg][rlen:] get_string = get_string.replace('-','_') if agent is not None: output_options.append((get_string, agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --get") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--concat"): important_options.append("concat") curr_arg = curr_arg + 1 continue if not args[curr_arg].startswith("--"): name = args[curr_arg] curr_arg = curr_arg + 1 if PkgDB().checkPackage(name): agent = DepResolutionSystem().createResolveAgent(name) listedAgentNames.append(name) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Package %s" % name) sys.exit(1) continue if args[curr_arg] != "--debug" and args[curr_arg] != "--verbose-debug": flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Option: %s" % args[curr_arg]) curr_arg = curr_arg + 1 if len(listedAgentNames) == 0: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Must specify at least one package") DepResolutionSystem().resolveDeps() pkgs = DepResolutionSystem().getPackages() for p in pkgs: if not p: for option in important_options: if option == "exists": print "no" sys.exit(1) flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found") if len(pkgs) == 0: for option in important_options: if option == "exists": print "no" sys.exit(1) flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found") sys.exit(1) concat = False for option in important_options: if option == "exists": print "yes" return sys.exit(0) # already checked for none above if option == "concat": concat = True if option == "info": pkg_info_list = [] for pkg in pkgs: if pkg.getName() in listedAgentNames: print pkg.getName() pkg_info = pkg.getInfo() for key in pkg_info.keys(): print " %s : %s" % (key, pkg_info[key]) if option == "print-pkg-options": print "" print "All options below would start with (--get-/--get-all-/--require-/--require-all-)" print "NOTE: this list does not include the standard variables that are exported." print "" for pkg in pkgs: if pkg.getName() not in listedAgentNames: continue print "Package: " + pkg.getName() for key in pkg.getInfo().keys(): if key not in [ "Name", "Description", "URL", "Version", "Requires", "Requires.private", "Conflicts", "Libs", "Libs.private", "Cflags", "Provides", "Arch", "FlagpollFilename", "prefix" ]: print " " + key.replace('_','-') #print output_options #output_options = [] #output_single = [] #Process options here.............. concat_list = [] if concat: print_option = lambda x: concat_list.extend(x) else: print_option = lambda x: Utils.printList(x) for option in output_options: if option[0] == "cflags": print_option(Utils.stripDupIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "cflags-only-I": print_option(Utils.cflagsOnlyDirIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "cflags-only-other": print_option(Utils.cflagsOnlyOtherIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "libs-only-l": print_option(Utils.libsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs-only-L": print_option(Utils.libDirsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs-only-other": print_option(Utils.libsOnlyOtherLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs": print_option(Utils.stripDupLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) else: print_option(Utils.stripDupInList(self.getVarFromPkgs(option[0], pkgs, option[1]))) if concat: Utils.printList(Utils.stripDupInList(concat_list)) def getVarFromPkgs(self, var, pkgs, pkg_name=""): var_list = [] ext_vars = [] if var == "Libs": if DepResolutionSystem().checkPrivateRequires: ext_vars.append("Libs.private") if pkg_name == "": for pkg in pkgs: if pkg: var_list.extend(pkg.getVariable(var).split(' ')) for extra_var in ext_vars: var_list.extend(pkg.getVariable(extra_var).split(' ')) else: for pkg in pkgs: if pkg: if pkg.getName() == pkg_name: var_list.extend(pkg.getVariable(var).split(' ')) for extra_var in ext_vars: var_list.extend(pkg.getVariable(extra_var).split(' ')) return var_list def printHelp(self): print "usage: flagpoll pkg options [pkg options] [generic options]" print " " print "generic options:" print " --help show this help message and exit" print " --version output version of flagpoll" print " --list-all list all known packages" print " --debug show debug information" print " --verbose-debug show verbose debug information" print " --extra-paths=EXTRA_PATHS" print " extra paths for flagpoll to search for meta-data files" print " --concat concatenate all output and output as one line" print " --keep-dups do not strip out all duplicate info from options" print " --info show information for packages" print " --print-pkg-options show pkg specific options" print " " print "options:" print " --modversion output version for package" print " --require=REQUIRE adds additional requirements for packages ex. 32/64" print " --libs output all linker flags" print " --static output linker flags for static linking" print " --libs-only-l output -l flags" print " --libs-only-other output other libs (e.g. -pthread)" print " --libs-only-L output -L flags" print " --cflags output all pre-processor and compiler flags" print " --cflags-only-I output -I flags" print " --cflags-only-other output cflags not covered by the cflags-only-I option" print " --exists return 0 if the module(s) exist" print " --from-file=FILE use the specified FILE for the package" #print " --print-provides print which packages the package provides" #print " --print-requires print which packages the package requires" print " --no-deps do not lookup dependencies for the package" print " --atleast-version=ATLEAST_VERSION" print " return 0 if the module is at least version" print " ATLEAST_VERSION" print " --exact-version=EXACT_VERSION" print " return 0 if the module is exactly version" print " EXACT_VERSION" print " --max-release=MAX_RELEASE" print " return 0 if the module has a release that has a" print " version of MAX_RELEASE and will return the max" print " --variable=VARIABLE get the value of a variable" print " " print "dynamic options(replace VAR with a variable you want to get/filter on)" print " NOTE: replace underscores with dashes in VAR" print " NOTE: quotes are needed around <,>,= combinations" print " --get-VAR get VAR from package" print " --get-all-VAR get VAR from package and its deps" print " --require-VAR[<,>,=VAL]" print " require that a var is defined for a package" print " or optionally use equality operators against VAL" print " --require-all-VAR[<,>,=VAL]" print " require that a var is defined for all packages" print " or optionally use equality operators against VAL" print "" print "extending search path" print " FLAGPOLL_PATH environment variable that can be set to" print " extend the search path for .fpc/.pc files" print "" print "" print "Send bug reports and/or feedback to flagpoll-users@vrsource.org" sys.exit(0) def main(): # GO! # Initialize singletons and the start evaluating my_dbg = flagDBG() my_dep_system = DepResolutionSystem() opt_evaluator = OptionsEvaluator() opt_evaluator.evaluateArgs(sys.argv[1:]) sys.exit(0) if __name__ == "__main__": main()
Python
#!/usr/bin/env python from distutils.core import setup setup( name='flagpoll', version='0.8.3', description='Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software.', author='Daniel E. Shipton', author_email='dshipton@infiscape.com', license='GPL', url='https://realityforge.vrsource.org/view/FlagPoll/WebHome', download_url='https://realityforge.vrsource.org/view/FlagPoll/FlagpollDownloads', scripts=['flagpoll'], long_description = "Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software. Think of it as the rpm of software development. It enables developers total control over which packages, versions, architectures, etc. that they want to use meta-data from.", data_files=[('share/flagpoll', ['flagpoll.fpc']), ('share/man/man1', ['flagpoll.1']), ('share/aclocal', ['flagpoll.m4'])] )
Python
#!/usr/bin/env python # ----------------------------------------------------------------- # # Flagpoll: A tool to extract flags from installed applications # for compiling, settting variables, etc. # # Original Authors: # Daniel E. Shipton <dshipton@gmail.com> # # Flagpoll is Copyright (C) 2006-2007 by Daniel E. Shipton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to: # Free SoftwareFoundation, Inc. # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # # ----------------------------------------------------------------- import sys, os, glob, os.path, copy, platform pj = os.path.join #################################################################### # SNAGGED FROM PYTHON 2.4 for versions under 2.4 #################################################################### import re as _re class _multimap: """Helper class for combining multiple mappings. Used by .{safe_,}substitute() to combine the mapping and keyword arguments. """ def __init__(self, primary, secondary): self._primary = primary self._secondary = secondary def __getitem__(self, key): try: return self._primary[key] except KeyError: return self._secondary[key] class _TemplateMetaclass(type): pattern = r""" %(delim)s(?: (?P<escaped>%(delim)s) | # Escape sequence of two delimiters (?P<named>%(id)s) | # delimiter and a Python identifier {(?P<braced>%(id)s)} | # delimiter and a braced identifier (?P<invalid>) # Other ill-formed delimiter exprs ) """ def __init__(cls, name, bases, dct): super(_TemplateMetaclass, cls).__init__(name, bases, dct) if 'pattern' in dct: pattern = cls.pattern else: pattern = _TemplateMetaclass.pattern % { 'delim' : _re.escape(cls.delimiter), 'id' : cls.idpattern, } cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE) class Template: """A string class for supporting $-substitutions.""" __metaclass__ = _TemplateMetaclass delimiter = '$' idpattern = r'[_a-z][_a-z0-9]*' def __init__(self, template): self.template = template # Search for $$, $identifier, ${identifier}, and any bare $'s def _invalid(self, mo): i = mo.start('invalid') lines = self.template[:i].splitlines(True) if not lines: colno = 1 lineno = 1 else: colno = i - len(''.join(lines[:-1])) lineno = len(lines) raise ValueError('Invalid placeholder in string: line %d, col %d' % (lineno, colno)) def substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): # Check the most common path first. named = mo.group('named') or mo.group('braced') if named is not None: val = mapping[named] # We use this idiom instead of str() because the latter will # fail if val is a Unicode containing non-ASCII characters. return '%s' % val if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: self._invalid(mo) raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) def safe_substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): named = mo.group('named') if named is not None: try: # We use this idiom instead of str() because the latter # will fail if val is a Unicode containing non-ASCII return '%s' % mapping[named] except KeyError: return self.delimiter + named braced = mo.group('braced') if braced is not None: try: return '%s' % mapping[braced] except KeyError: return self.delimiter + '{' + braced + '}' if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: return self.delimiter raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) #################################################################### # End Snagging #################################################################### class Utils: # Holds collection of small utility functions EXTRA_FLAGPOLL_SEARCH_PATHS = "" EXTRA_FLAGPOLL_FILES = "" path_list_cache = None # Cache of found path lists. (only calcuate once) KEEP_DUPS = False FLAGPOLL_LIST_OF_POSSIBLE_ERRORS = [] def addPossibleError(pos_err): Utils.FLAGPOLL_LIST_OF_POSSIBLE_ERRORS.append(pos_err) addPossibleError = staticmethod(addPossibleError) def getPossibleErrors(): return Utils.stripDupInList(Utils.FLAGPOLL_LIST_OF_POSSIBLE_ERRORS) getPossibleErrors = staticmethod(getPossibleErrors) def getFlagpollVersion(): FLAGPOLL_MAJOR_VERSION = 0 FLAGPOLL_MINOR_VERSION = 8 FLAGPOLL_PATCH_VERSION = 3 return ( FLAGPOLL_MAJOR_VERSION, FLAGPOLL_MINOR_VERSION, FLAGPOLL_PATCH_VERSION ) getFlagpollVersion = staticmethod(getFlagpollVersion) def getPathList(): if None != Utils.path_list_cache: return Utils.path_list_cache #TODO: expand LD_LIBRARY_PATH to 64/32/etc??? pkg_cfg_dir = [] flg_cfg_dir = [] ld_path = [] if os.environ.has_key("PKG_CONFIG_PATH"): pkg_cfg_dir = os.environ["PKG_CONFIG_PATH"].split(os.pathsep) if os.environ.has_key("FLAGPOLL_PATH"): flg_cfg_dir = os.environ["FLAGPOLL_PATH"].split(os.pathsep) ld_dirs = ['LD_LIBRARY_PATH', 'DYLD_LIBRARY_PATH'] for d in ld_dirs: if os.environ.has_key(d): cur_path = os.environ[d].split(os.pathsep) ld_path_pkg = [pj(p,'pkgconfig') for p in cur_path] ld_path_flg = [pj(p,'flagpoll') for p in cur_path] ld_path.extend(ld_path_pkg) ld_path.extend(ld_path_flg) extra_paths = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS.split(os.pathsep) path_list = extra_paths path_list.extend(flg_cfg_dir) path_list.extend(pkg_cfg_dir) path_list.extend(ld_path) path_list.extend(["/usr/lib64/pkgconfig", "/usr/lib/pkgconfig", "/usr/share/pkgconfig", "/usr/lib64/flagpoll", "/usr/lib/flagpoll", "/usr/share/flagpoll"]) flagDBG().out(flagDBG.VERBOSE, "Utils.getPathList", "Potential path list: " + str(path_list)) path_list = [p for p in path_list if os.path.exists(p)] flagDBG().out(flagDBG.INFO, "Utils.getPathList", "Using path list: " + str(path_list)) Utils.path_list_cache = path_list return path_list getPathList = staticmethod(getPathList) def getFileList(): flist = Utils.EXTRA_FLAGPOLL_FILES.split(":") filelist = [] for f in flist: if os.path.isfile(f): filelist.append(f) return filelist getFileList = staticmethod(getFileList) def setKeepDups(keep_dups): Utils.KEEP_DUPS = keep_dups setKeepDups = staticmethod(setKeepDups) def stripDupInList(gen_list): new_list = [] list_len = len(gen_list) i = 0 while i < list_len: item = gen_list[i].strip() if Utils.KEEP_DUPS: if len(item) > 0: new_list.append(item) continue if item == '-framework': item = '%s %s' % (item, gen_list[i + 1]) i += 1 if item not in new_list: if len(item) > 0: new_list.append(item) i += 1 return new_list stripDupInList = staticmethod(stripDupInList) def stripDupLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] dir_list = [] list_len = len(flag_list) i = 0 while i < list_len: flg = flag_list[i].strip() if len(flg) > 0: if flg.startswith("-L") or flg.startswith("-R") or \ flg.startswith("-F"): dir_list.append(flg) else: if flg == "-framework": flg = "%s %s" % (flg, flag_list[i + 1]) i += 1 lib_list.append(flg) i += 1 new_list = dir_list + lib_list return Utils.stripDupInList(new_list) stripDupLinkerFlags = staticmethod(stripDupLinkerFlags) def stripDupIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] extra_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-I"): inc_list.append(flg) else: extra_list.append(flg) extra_list.sort() new_list = inc_list + extra_list return Utils.stripDupInList(new_list) stripDupIncludeFlags = staticmethod(stripDupIncludeFlags) def cflagsOnlyDirIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-I"): inc_list.append(flg) return Utils.stripDupInList(inc_list) cflagsOnlyDirIncludeFlags = staticmethod(cflagsOnlyDirIncludeFlags) def cflagsOnlyOtherIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though extra_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if not flg.startswith("-I"): extra_list.append(flg) return Utils.stripDupInList(extra_list) cflagsOnlyOtherIncludeFlags = staticmethod(cflagsOnlyOtherIncludeFlags) def libsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-l"): lib_list.append(flg) return Utils.stripDupInList(lib_list) libsOnlyLinkerFlags = staticmethod(libsOnlyLinkerFlags) def libsOnlyOtherLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though other_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if not flg.startswith("-l") and not flg.startswith("-L") and not flg.startswith("-R"): other_list.append(flg) return Utils.stripDupInList(other_list) libsOnlyOtherLinkerFlags = staticmethod(libsOnlyOtherLinkerFlags) def libDirsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though dir_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-L") or flg.startswith("-R"): dir_list.append(flg) return Utils.stripDupInList(dir_list) libDirsOnlyLinkerFlags = staticmethod(libDirsOnlyLinkerFlags) def printList(gen_list): list_string = "" for item in gen_list: if len(item) > 0: list_string += str(item) list_string += " " print list_string.strip() printList = staticmethod(printList) def parsePcFile(filename): lines = open(filename).readlines() fvars = {} fvars["FlagpollFilename"] = filename lokals = {} lokals["fp_file_cwd"] = str(filename[:- ((len(os.path.basename(filename) ) + 1))]) lines.append("prefix: ${prefix}") append_next = False append_dict = {} append_key = "" for line in lines: line = line.strip() if not line: continue if append_next: tmp = append_dict[append_key] tmp = tmp[:-1] + " " + line append_dict[append_key] = tmp if tmp[-1:] == "\\": append_next = True else: append_next = False continue if line.startswith("#"): continue eq_pos = line.find('=') col_pos = line.find(':') if eq_pos < col_pos and eq_pos != -1 or col_pos == -1 and eq_pos != -1: # local variable name, val = line.split('=', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(lokals) except ValueError: flagDBG().out(flagDBG.WARN, "PkgInfo.parse", "%s has an invalid metadata file" % filename) lokals[name] = val if val[-1:] == "\\": append_next = True append_dict = lokals append_key = name continue if col_pos < eq_pos and col_pos != -1 or eq_pos == -1 and col_pos != -1: # exported variable name, val = line.split(':', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(lokals) except ValueError: flagDBG().out(flagDBG.ERROR, "PkgInfo.parse", "%s has an invalid metadata file" % filename) fvars[name] = val if val[-1:] == "\\": append_next = True append_dict = fvars append_key = name return fvars parsePcFile = staticmethod(parsePcFile) class flagDBG(object): # Logging class is really easy to use # Levels: # 0 - VERBOSE # 1 - INFO # 2 - WARN # 3 - ERROR VERBOSE = 0 INFO = 1 WARN = 2 ERROR = 3 __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if flagDBG.__initialized: return flagDBG.__initialized = True self.mLevel = self.WARN self.mLevelList = ["VERBOSE", "INFO", "WARN", "ERROR"] def setLevel(self, level): if level <= 3: self.mLevel = level def out(self, level, obj, message): if level == self.ERROR: if self.mLevel == self.VERBOSE: print self.mLevelList[level] + ":" + str(obj) + ": " + str(message) else: sys.stderr.write(self.mLevelList[level] + ": " + str(message) + "\n") errs = Utils.getPossibleErrors() if len(errs) > 0: sys.stderr.write("Possible culprits:\n") for pos_err in errs: sys.stderr.write( " " + str(pos_err) + "\n" ) sys.exit(1) if level >= self.mLevel: print self.mLevelList[level] + ":" + str(obj) + ": " + str(message) class DepResolutionSystem(object): """ You add PkgAgents with Filters into system and call resolve() you can check for succes by depsSatisfied() and get the list of packages that work back by calling getPackages() """ __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if DepResolutionSystem.__initialized: return DepResolutionSystem.__initialized = True self.mResolveAgents = [] self.mAgentDict = {} self.mFilters = [] self.mResolveAgentFilters = [] self.mInvalidPackageList = [] self.mSatisfied = False self.mAgentChangeList = [] # list of those responsible for adding Filters # to agents in higher in the chain than them # these are the first agents to ask that they pick # the next best package of them self.mAgentsVisitedList = [] # list of Agents that have been visited self.mResolvedPackageList = [] # list that is generated when deps are satified self.mCheckPrivateRequires = False self.mMadeDependList = False def getFilters(self): return self.mFilters def addFilter(self, filter): self.mFilters.append(filter) def addResolveAgentFilter(self, filter): self.mResolveAgentFilters.append(filter) def makeRequireFilter(self, requires): arch_list = [] arch_list.append("no_arch") arch_list.append("") if platform.system() == "Linux": if requires == "64": arch_list.append("x86_64") if requires == "32": arch_list.append("i386") arch_list.append("i486") arch_list.append("i586") arch_list.append("i686") if platform.system() == "Darwin": if requires == "64": arch_list.append("ppc64") if requires == "32": arch_list.append("ppc") if platform.system().startswith("IRIX"): arch_list.append(requires) new_filter = Filter("Arch", lambda x,v=arch_list: x in v) self.addFilter(new_filter) def createAgent(self, name): if self.checkAgentExists(name): return self.getAgent(name) else: agent = PkgAgent(name) flagDBG().out(flagDBG.INFO, "DepResSys.createAgent", "Adding %s" % name) self.addNewAgent(agent) return agent def createResolveAgent(self, name): if self.checkAgentExists(name): return self.getAgent(name) else: agent = PkgAgent(name) flagDBG().out(flagDBG.INFO, "DepResSys.createResolveAgent", "Adding %s" % name) self.addResolveAgent(agent) return agent def setPrivateRequires( self, req ): self.mCheckPrivateRequires = req def checkPrivateRequires(self): return self.mCheckPrivateRequires def checkAgentExists(self, name): return self.mAgentDict.has_key(name) def getAgent(self, name): if self.mAgentDict.has_key(name): return self.mAgentDict[name] else: flagDBG().out(flagDBG.ERROR, "DepResSys.getAgent", "Agent %s does not exist" % name) def addNewAgent(self, agent): if not self.checkAgentExists(agent): self.mAgentDict[agent.getName()] = agent def addResolveAgent(self, agent): if agent not in self.mResolveAgents: self.mResolveAgents.append(agent) for filt in self.mResolveAgentFilters: agent.addFilter(filt) def isSatisfied(self): return self.mSatisfied def updateResolvedPackages(self): pkg_list = [] agent_list = [] for agent in self.mResolveAgents: list_of_pkgs = agent.getCurrentPackageList(agent_list) pkg_list.extend(list_of_pkgs) self.mResolvedPackageList = pkg_list def getPackages(self): flagDBG().out(flagDBG.INFO, "DepResSys.getPackages", "Generating list of valid packages ") #str([pkg.getCurrentPackage.getName() for pkg in self.mResolvedPackageList])) # If this comes back empty then there isn't a valid set of packages to use self.updateResolvedPackages() return self.mResolvedPackageList def checkFiltersChanged(self): list_to_use = [] return True in [pkg.filtersChanged(list_to_use) for pkg in self.mResolveAgents] def resolveHelper(self): self.resolveAgentsChanged = True while self.resolveAgentsChanged: for agent in self.mResolveAgents: flagDBG().out(flagDBG.INFO, "DepResSys.resolveHelper", "Updating " + agent.getName()) agent.update(self.mAgentsVisitedList, self.mAgentChangeList) self.resolveAgentsChanged = self.checkFiltersChanged() # Ask mResolveAgents if they are done(they ask sub people) unless they are # really above you in the walk # If there were changes...run update on mResolveAgents again # at the end ask for pkglist..if it comes back empty then we don't # have a usable configuration for those packages def resolveDeps(self): self.resolveHelper() if not self.mMadeDependList: for agent in self.mResolveAgents: agent.makeDependList() self.mMadeDependList = True self.updateResolvedPackages() # Check if the first round through we found something # Otherwise we need to start removing packages that aren't viable # during the loop self.mSatisfied = (len(self.mResolvedPackageList) != 0) # remove top of packages that added Filters. # then move on to resolving again # remove more if neccesary agentChangeNumber = 0 while not self.mResolvedPackageList: if(self.mAgentChangeList[agentChangeNumber]): if self.mAgentChangeList[agentChangeNumber] in self.mInvalidPackageList: agentChangeNumber += 1 else: if(self.mAgentChangeList[agentChangeNumber].getViablePackages()): flagDBG().out(flagDBG.INFO, "DepResSys.resolveDeps", "Removing bad pkg from " + self.mAgentChangeList[agentChangeNumber].getName()) self.mInvalidPackageList.append(self.mAgentChangeList[agentChangeNumber].removeCurrentPackage()) else: flagDBG().out(flagDBG.INFO, "DepResSys.resolveDeps", "No combinations.. Resetting " + self.mAgentChangeList[agentChangeNumber].getName()) self.mAgentChangeList[agentChangeNumber].reset() agentChangeNumber += 1 self.resolveHelper() self.updateResolvedPackages() self.mSatisfied = (len(self.mResolvedPackageList) != 0) return class PkgAgent: """ Agent that keeps track of the versions for a package given some filters and the addition of Filters """ # Makes a PkgAgent that finds its current package with the version reqs def __init__(self, name): if DepResolutionSystem().checkAgentExists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "Package Agent %s already exists" % self.mName) self.mName = name flagDBG().out(flagDBG.INFO, "PkgAgent", "Creating:" + str(self.mName)) if not PkgDB().exists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "No info for package: %s" % self.mName) #XXX Doesn't keep filters added for a redo... DepResolutionSystem().addNewAgent(self) self.mFilterList = [] self.mFilterList.extend(DepResolutionSystem().getFilters()) self.mBasePackageList = PkgDB().getPkgInfos(name) self.mBasePackageList.sort(lambda lhs, rhs: cmp(rhs.getVariable('Version'), lhs.getVariable('Version'))) for filt in self.mFilterList: self.mBasePackageList = filt.filter(self.mBasePackageList) if len(self.mBasePackageList) == 0: flagDBG().out(flagDBG.ERROR, "PkgAgent", "No viable packages for: %s" % self.mName) self.mViablePackageList = copy.deepcopy(self.mBasePackageList) if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mFiltersChanged = True self.mCheckDepends = True self.mAgentDependList = [] def getName(self): return self.mName def setCheckDepends(self, tf): self.mCheckDepends = tf #Filter("Version", lambda x: x == "4.5") def makeDependList(self): if not self.mCheckDepends: self.mAgentDependList = [] return dep_list = [] if self.mCurrentPackage: req_string = self.mCurrentPackage.getVariable("Requires") if DepResolutionSystem().checkPrivateRequires(): req_string = req_string + " " + self.mCurrentPackage.getVariable("Requires.private") req_string = req_string.strip() if req_string == "": return req_string = req_string.replace(',', ' ') req_string = req_string.replace('(', ' ') req_string = req_string.replace(')', ' ') space_req_string_list = req_string.split(' ') req_string_list = [] for entry in space_req_string_list: if len(entry) > 0: req_string_list.append(entry) i = 0 flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList", self.mCurrentPackage.getName() + " requires: " + str(req_string_list)) while len(req_string_list) > i: if PkgDB().exists(req_string_list[i]): new_filter = [] new_agent = DepResolutionSystem().createAgent(req_string_list[i]) if len(req_string_list) > i+1: if req_string_list[i+1] == "=": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x == v) elif req_string_list[i+1] == "<=": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x <= v) elif req_string_list[i+1] == ">=": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x >= v) elif req_string_list[i+1] == ">": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x > v) elif req_string_list[i+1] == "<": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x < v) else: i += 1 else: i += 1 dep_list.append(new_agent) if new_filter: i+=3 new_agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "PkgAgent.makeDependList", "Package %s depends on %s but does not seem to be installed." % (self.mName, str(req_string_list[i]))) flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList", str(self.mName) + " : List is:" + str([pkg.getName() for pkg in dep_list])) self.mAgentDependList = dep_list def filtersChanged(self, packageList): tf_list = [self.mFiltersChanged] if self.mName not in packageList: packageList.append(self.mName) for pkg in self.mAgentDependList: tf_list.append(pkg.filtersChanged(packageList)) return True in tf_list def getCurrentPackageList(self, packageList): pkgs = [] if self.mName not in packageList: flagDBG().out(flagDBG.INFO, "PkgAgent.getCurrentPackageList", "Package: %s" % self.mName) pkgs.append(self.mCurrentPackage) packageList.append(self.mName) # Make depend list if we are supposed to self.updateFilters() self.makeDependList() for pkg in self.mAgentDependList: pkgs.extend(pkg.getCurrentPackageList(packageList)) return pkgs # current pkginfo for me def getCurrentPkgInfo(self): return self.mCurrentPackage # Someone else usually places these on me # I keep track of those separately def addFilter(self, filter): flagDBG().out(flagDBG.INFO, "PkgAgent.addFilter", "Filter %s" % self.mName + " on %s." % filter.getVarName()) self.mFiltersChanged = True self.mFilterList.append(filter) def removeCurrentPackage(self): flagDBG().out(flagDBG.INFO, "PkgAgent.removeCurrentPackage", "Removing current package of %s" % self.mName) if self.mViablePackageList: ret_val = self.mViablePackageList[0] in self.mBasePackageList del self.mViablePackageList[0] if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] return ret_val def update(self, agentVisitedList, agentChangeList): flagDBG().out(flagDBG.INFO, "PkgAgent.update", "%s" % self.mName) if self.mName in agentVisitedList: return agentVisitedList.append(self.mName) if self.mFiltersChanged: self.mFiltersChanged = False self.updateFilters() # TODO: checkFilters and add them # if a pkg is in visitedList then add yourself to agentChangeList for pkg in self.mAgentDependList: pkg.update(agentVisitedList, agentChangeList) return def updateFilters(self): for filt in self.mFilterList: self.mViablePackageList = filt.filter(self.mViablePackageList) flagDBG().out(flagDBG.INFO, "PkgAgent.updateFilters", "%s has " % self.mName + str(len(self.mViablePackageList)) + " left") if len(self.mViablePackageList) > 0: self.mCurrentPackage = self.mViablePackageList[0] else: for f in self.mFilterList: Utils.addPossibleError(str(self.mName) + " -> " + str(f.getVarName())) self.mCurrentPackage = [] def reset(self): flagDBG().out(flagDBG.INFO, "PkgAgent.reset", "Resetting package: %s" % self.mName) self.mViablePackageList = self.mBasePackageList if self.mViablePackageList: self.mCurrentPacakge = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mFilterList = DepResolutionSystem().getFilters() self.mAgentDependList = [] self.mFiltersChanged = True return class Filter: """ A single Filter that knows how to filter the list it recieves Will be inheireted....?..? """ def __init__(self, variableName, testCallable): self.mVarName = variableName self.mTestCallable = testCallable def getVarName(self): return self.mVarName def filter(self, pkg_info_list): ret_pkg_list = [] # Filter first for pkg in pkg_info_list: var = pkg.getVariable(self.mVarName) if self.mTestCallable(var): flagDBG().out(flagDBG.INFO, "Filter", "Passed: %s:" % pkg.getName() + " %s is " % self.mVarName + str(var)) ret_pkg_list.append(pkg) else: flagDBG().out(flagDBG.INFO, "Filter", "Failed: %s:" % pkg.getName() + " %s is " % self.mVarName + str(var)) # Now sort ret_pkg_list.sort(lambda lhs, rhs: cmp(rhs.getVariable(self.mVarName), lhs.getVariable(self.mVarName))) return ret_pkg_list #requires: qt == 4.5 #Filter("Version", lambda x: x <= "4.5") #Filter("Version", lambda x: x <= "4.5") class PkgDB(object): """ Holds all the neccesary information to evaluate itself when needed. Is in charge of holding a list of PkgInfo's that contain info about the package. """ __initialized = False def __init__(self): if self.__initialized: return self.__initialized = True self.mPkgInfos = {} # {pkg_name: List of package infos} self.populatePkgInfoDBPcFiles() self.populatePkgInfoDBFpcFiles() def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def printAllPackages(self): list_of_package_names = [] for pkg in self.mPkgInfos: list_of_package_names.append(pkg) for name in list_of_package_names: print name sys.exit(0) def getVariables(self, name, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariable", "Finding " + str(variable_list) + " in " + str(name)) ret_list = [] for var in variable_list: if self.mPkgInfos.has_key(name): ret_list.extend(self.mPkgInfos[name][0].getVariable(var)) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariable", "Package %s not found." % name) return ret_list def checkPackage(self, name): flagDBG().out(flagDBG.INFO, "PkgDB.checkPackage", "Finding " + str(name)) if self.mPkgInfos.has_key(name): return True else: flagDBG().out(flagDBG.ERROR, "PkgDB.CheckPackage", "Package %s not found." % name) return False def getVariablesAndDeps(self, pkg_list, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariablesAndDeps", "Finding " + str(variable_list) + " in " + str(pkg_list)) if DepResolutionSystem().checkPrivateRequires(): temp_var_list = [] for var in variable_list: temp_var_list.append(var.join(".private")) variable_list = variable_list + temp_var_list for name in pkg_list: if self.mPkgInfos.has_key(name): agent = DepResolutionSystem().createAgent(name) DepResolutionSystem().addResolveAgent(agent) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariablesAndDeps", "Package %s not found." % name) DepResolutionSystem().resolveDeps() pkgs = DepResolutionSystem().getPackages() var_list = [] for pkg in pkgs: if pkg: for var in variable_list: var_list.extend(pkg.getVariable(var).split(' ')) return var_list def getPkgInfos(self, name): if self.mPkgInfos.has_key(name): return self.mPkgInfos[name] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getPkgInfos", "Package %s not found." % name) def exists(self, name): return self.mPkgInfos.has_key(name) def getInfo(self, name): if self.mPkgInfos.has_key(name): return [pkg.getInfo() for pkg in self.mPkgInfos[name]] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getInfo", "Package %s not found." % name) def buildPcFileDict(self): """ Builds up a dictionary of {name: list of files for name} """ pc_dict = {} for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.pc")) # List of .pc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these pc files: %s" % str(glob_list)) for g in glob_list: # Get key name and add file to value list in dictionary key = os.path.basename(g)[:-3] # Strip .pc off the filename...rstrip no worky pc_dict.setdefault(key, []).append(g) for f in Utils.getFileList(): if f.endswith(".pc"): key = os.path.basename(f)[:-3] # Strip .pc off the filename...rstrip no worky pc_dict.setdefault(key, []).append(f) return pc_dict # { "key", [ "list", "of", "corresponding", "pc", "files"] } def populatePkgInfoDBPcFiles(self): dict_to_pop_from = self.buildPcFileDict() for (pkg,files) in dict_to_pop_from.iteritems(): for f in files: self.mPkgInfos.setdefault(pkg,[]).append(PkgInfo(pkg, f, "pc")) def buildFpcFileList(self): """ Builds up a dictionary of {name: list of files for name} """ file_list = [] for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.fpc")) # List of .fpc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these fpc files: %s" % str(glob_list)) for g in glob_list: file_list.append(g) for f in Utils.getFileList(): if f.endswith(".fpc"): file_list.append(f) return file_list # [ "list", "of", "fpc", "files"] def populatePkgInfoDBFpcFiles(self): list_to_add = self.buildFpcFileList() for filename in list_to_add: var_dict = Utils.parsePcFile(filename) if not var_dict.has_key("Provides"): flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Provides" % str(filename)) continue if not var_dict.has_key("Arch"): flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Arch" % str(filename)) continue provides_string = var_dict["Provides"] provides_string = provides_string.replace(',', ' ') provides_string = provides_string.replace('(', ' ') provides_string = provides_string.replace(')', ' ') for key in provides_string.split(" "): if len(key) > 0: self.mPkgInfos.setdefault(key, []).append(PkgInfo(key, filename, "fpc", var_dict)) class PkgInfo: """ Holds the information for a package file on the system. These however are evaluated when the need arises. """ def __init__(self, name, file, type, varDict={}): self.mName = name self.mFile = file self.mIsEvaluated = False self.mType = type self.mVariableDict = varDict if self.mType == "fpc": self.mIsEvaluated = True def getVariable(self, variable): self.evaluate() return self.mVariableDict.get(variable,"") def getName(self): return self.mName def evaluate(self): if not self.mIsEvaluated: flagDBG().out(flagDBG.INFO, "PkgInfo.evaluate", "Evaluating %s" % self.mName) self.mVariableDict= Utils.parsePcFile(self.mFile) self.mIsEvaluated = True def getInfo(self): self.evaluate() return self.mVariableDict class OptionsEvaluator: def __init__(self): if len(sys.argv) < 2: self.printHelp() # This is only the args....(first arg is stripped) def evaluateArgs(self, args): # Catch any args that need to be tended to immediately # Process args in the order that they were recieved. Some options are not # shown below because they are sub-options of an option below (--strip-dups) for option in args: if option.startswith("--verbose-debug"): flagDBG().setLevel(flagDBG.VERBOSE) if option.startswith("--debug"): flagDBG().setLevel(flagDBG.INFO) elif option.startswith("--from-file"): val_start = option.find('=') + 1 file = option[val_start:] Utils.EXTRA_FLAGPOLL_FILES = Utils.EXTRA_FLAGPOLL_FILES + ":" + file elif option.startswith("--help"): self.printHelp() sys.exit(0) elif option.startswith("--version"): print "%s.%s.%s" % Utils.getFlagpollVersion() sys.exit(0) elif option.startswith("--list-all"): PkgDB().printAllPackages() continue listedAgentNames = [] agent = None num_args = len(args) curr_arg = 0 output_options = [] # (option, name/"") important_options = [] # ones that need special attention while curr_arg < num_args: if args[curr_arg].startswith("--atleast-version"): val_start = args[curr_arg].find('=') + 1 atleast_version = args[curr_arg][val_start:] atleast_filter = Filter("Version", lambda x,v=atleast_version: x >= v) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(atleast_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --at-least-version") continue if args[curr_arg].startswith("--cflags-only-I"): output_options.append(("cflags-only-I", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--cflags-only-other"): output_options.append(("cflags-only-other", "")) curr_arg = curr_arg + 1 continue #This could be the catch all for the above ones to and then filter based on what is asked... #For clarity of course... if args[curr_arg].startswith("--cflags"): output_options.append(("cflags", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--extra-paths"): val_start = args[curr_arg].find('=') + 1 paths = args[curr_arg][val_start:] Utils.EXTRA_FLAGPOLL_SEARCH_PATHS = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS + ":" + paths curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--exact-version"): val_start = args[curr_arg].find('=') + 1 exact_version = args[curr_arg][val_start:] exact_filter = Filter("Version", lambda x,v=exact_version: x == v) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(exact_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --exact-version") continue if args[curr_arg].startswith("--exists"): important_options.append("exists") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--from-file"): val_start = args[curr_arg].find('=') + 1 file = args[curr_arg][val_start:] file_filter = Filter("FlagpollFilename", lambda x,f=file: x == f) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(file_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --from-file") continue if args[curr_arg].startswith("--info"): important_options.append("info") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--print-pkg-options"): important_options.append("print-pkg-options") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--keep-dups"): Utils.setKeepDups(True) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-l"): output_options.append(("libs-only-l", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-L"): output_options.append(("libs-only-L", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-other"): output_options.append(("libs-only-other", "")) curr_arg = curr_arg + 1 continue #This could be the catch all for the above ones to and then filter based on what is asked... if args[curr_arg].startswith("--libs"): output_options.append(("libs", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--require-all"): rlen = len("--require-all") req_string = args[curr_arg][rlen:] req_string = req_string.replace('-','_') curr_arg = curr_arg + 1 if req_string.find("<=") != -1: op_start = req_string.find("<=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x <= v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find(">=") != -1: op_start = req_string.find(">=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x >= v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find(">") != -1: op_start = req_string.find(">") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x > v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("<") != -1: op_start = req_string.find("<") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x < v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("=") != -1: op_start = req_string.find("=") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x == v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("=") == -1: new_filter = Filter(req_string, lambda x: len(x) > 0) DepResolutionSystem().addFilter(new_filter) continue continue if args[curr_arg].startswith("--require-"): rlen = len("--require-") req_string = args[curr_arg][rlen:] req_string = req_string.replace('-','_') curr_arg = curr_arg + 1 if agent is None: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --require") if req_string.find("<=") != -1: op_start = req_string.find("<=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x <= v) agent.addFilter(new_filter) continue if req_string.find(">=") != -1: op_start = req_string.find(">=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x >= v) agent.addFilter(new_filter) continue if req_string.find(">") != -1: op_start = req_string.find(">") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x > v) agent.addFilter(new_filter) continue if req_string.find("<") != -1: op_start = req_string.find("<") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x < v) agent.addFilter(new_filter) continue if req_string.find("=") != -1: op_start = req_string.find("=") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x == v) agent.addFilter(new_filter) continue if req_string.find("=") == -1: new_filter = Filter(req_string, lambda x: len(x) > 0) agent.addFilter(new_filter) continue continue if args[curr_arg].startswith("--no-deps"): if agent is not None: agent.setCheckDepends(False) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --no-deps") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--require="): val_start = args[curr_arg].find('=') + 1 req_var = args[curr_arg][val_start:] curr_arg = curr_arg + 1 DepResolutionSystem().makeRequireFilter(req_var) continue if args[curr_arg].startswith("--modversion"): if agent is not None: output_options.append(("Version", agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --modversion") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--max-release"): val_start = args[curr_arg].find('=') + 1 max_release = args[curr_arg][val_start:] max_filter = Filter("Version", lambda x,v=max_release: x.startswith(v)) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(max_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --max-release") continue if args[curr_arg].startswith("--static"): DepResolutionSystem().setPrivateRequires(True) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--variable"): val_start = args[curr_arg].find('=') + 1 fetch_var = args[curr_arg][val_start:] if agent is not None: output_options.append((fetch_var, agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --variable") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--get-all"): rlen = len("--get-all-") get_string = args[curr_arg][rlen:] get_string = get_string.replace('-','_') output_options.append((get_string, "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--get"): rlen = len("--get-") get_string = args[curr_arg][rlen:] get_string = get_string.replace('-','_') if agent is not None: output_options.append((get_string, agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --get") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--concat"): important_options.append("concat") curr_arg = curr_arg + 1 continue if not args[curr_arg].startswith("--"): name = args[curr_arg] curr_arg = curr_arg + 1 if PkgDB().checkPackage(name): agent = DepResolutionSystem().createResolveAgent(name) listedAgentNames.append(name) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Package %s" % name) sys.exit(1) continue if args[curr_arg] != "--debug" and args[curr_arg] != "--verbose-debug": flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Option: %s" % args[curr_arg]) curr_arg = curr_arg + 1 if len(listedAgentNames) == 0: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Must specify at least one package") DepResolutionSystem().resolveDeps() pkgs = DepResolutionSystem().getPackages() for p in pkgs: if not p: for option in important_options: if option == "exists": print "no" sys.exit(1) flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found") if len(pkgs) == 0: for option in important_options: if option == "exists": print "no" sys.exit(1) flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found") sys.exit(1) concat = False for option in important_options: if option == "exists": print "yes" return sys.exit(0) # already checked for none above if option == "concat": concat = True if option == "info": pkg_info_list = [] for pkg in pkgs: if pkg.getName() in listedAgentNames: print pkg.getName() pkg_info = pkg.getInfo() for key in pkg_info.keys(): print " %s : %s" % (key, pkg_info[key]) if option == "print-pkg-options": print "" print "All options below would start with (--get-/--get-all-/--require-/--require-all-)" print "NOTE: this list does not include the standard variables that are exported." print "" for pkg in pkgs: if pkg.getName() not in listedAgentNames: continue print "Package: " + pkg.getName() for key in pkg.getInfo().keys(): if key not in [ "Name", "Description", "URL", "Version", "Requires", "Requires.private", "Conflicts", "Libs", "Libs.private", "Cflags", "Provides", "Arch", "FlagpollFilename", "prefix" ]: print " " + key.replace('_','-') #print output_options #output_options = [] #output_single = [] #Process options here.............. concat_list = [] if concat: print_option = lambda x: concat_list.extend(x) else: print_option = lambda x: Utils.printList(x) for option in output_options: if option[0] == "cflags": print_option(Utils.stripDupIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "cflags-only-I": print_option(Utils.cflagsOnlyDirIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "cflags-only-other": print_option(Utils.cflagsOnlyOtherIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "libs-only-l": print_option(Utils.libsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs-only-L": print_option(Utils.libDirsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs-only-other": print_option(Utils.libsOnlyOtherLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs": print_option(Utils.stripDupLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) else: print_option(Utils.stripDupInList(self.getVarFromPkgs(option[0], pkgs, option[1]))) if concat: Utils.printList(Utils.stripDupInList(concat_list)) def getVarFromPkgs(self, var, pkgs, pkg_name=""): var_list = [] ext_vars = [] if var == "Libs": if DepResolutionSystem().checkPrivateRequires: ext_vars.append("Libs.private") if pkg_name == "": for pkg in pkgs: if pkg: var_list.extend(pkg.getVariable(var).split(' ')) for extra_var in ext_vars: var_list.extend(pkg.getVariable(extra_var).split(' ')) else: for pkg in pkgs: if pkg: if pkg.getName() == pkg_name: var_list.extend(pkg.getVariable(var).split(' ')) for extra_var in ext_vars: var_list.extend(pkg.getVariable(extra_var).split(' ')) return var_list def printHelp(self): print "usage: flagpoll pkg options [pkg options] [generic options]" print " " print "generic options:" print " --help show this help message and exit" print " --version output version of flagpoll" print " --list-all list all known packages" print " --debug show debug information" print " --verbose-debug show verbose debug information" print " --extra-paths=EXTRA_PATHS" print " extra paths for flagpoll to search for meta-data files" print " --concat concatenate all output and output as one line" print " --keep-dups do not strip out all duplicate info from options" print " --info show information for packages" print " --print-pkg-options show pkg specific options" print " " print "options:" print " --modversion output version for package" print " --require=REQUIRE adds additional requirements for packages ex. 32/64" print " --libs output all linker flags" print " --static output linker flags for static linking" print " --libs-only-l output -l flags" print " --libs-only-other output other libs (e.g. -pthread)" print " --libs-only-L output -L flags" print " --cflags output all pre-processor and compiler flags" print " --cflags-only-I output -I flags" print " --cflags-only-other output cflags not covered by the cflags-only-I option" print " --exists return 0 if the module(s) exist" print " --from-file=FILE use the specified FILE for the package" #print " --print-provides print which packages the package provides" #print " --print-requires print which packages the package requires" print " --no-deps do not lookup dependencies for the package" print " --atleast-version=ATLEAST_VERSION" print " return 0 if the module is at least version" print " ATLEAST_VERSION" print " --exact-version=EXACT_VERSION" print " return 0 if the module is exactly version" print " EXACT_VERSION" print " --max-release=MAX_RELEASE" print " return 0 if the module has a release that has a" print " version of MAX_RELEASE and will return the max" print " --variable=VARIABLE get the value of a variable" print " " print "dynamic options(replace VAR with a variable you want to get/filter on)" print " NOTE: replace underscores with dashes in VAR" print " NOTE: quotes are needed around <,>,= combinations" print " --get-VAR get VAR from package" print " --get-all-VAR get VAR from package and its deps" print " --require-VAR[<,>,=VAL]" print " require that a var is defined for a package" print " or optionally use equality operators against VAL" print " --require-all-VAR[<,>,=VAL]" print " require that a var is defined for all packages" print " or optionally use equality operators against VAL" print "" print "extending search path" print " FLAGPOLL_PATH environment variable that can be set to" print " extend the search path for .fpc/.pc files" print "" print "" print "Send bug reports and/or feedback to flagpoll-users@vrsource.org" sys.exit(0) def main(): # GO! # Initialize singletons and the start evaluating my_dbg = flagDBG() my_dep_system = DepResolutionSystem() opt_evaluator = OptionsEvaluator() opt_evaluator.evaluateArgs(sys.argv[1:]) sys.exit(0) if __name__ == "__main__": main()
Python
#!/usr/bin/env python # ----------------------------------------------------------------- # # Flag Poll: A tool to extract flags from installed applications # for compiling, settting variables, etc. # # Original Authors: # Daniel E. Shipton <dshipton@gmail.com> # # Flag Poll is Copyright (C) 2006 by Daniel E. Shipton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to: # Free SoftwareFoundation, Inc. # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # # ----------------------------------------------------------------- """Makes a flagpole .fpc file from user input. v0.9 coded by Jeff Groves""" import os import sys import getopt ##String prompts for the input varPrompt = """Convience variables (one 'var_name= var_definition' per line,""" + \ """ empty line when done)""" namePrompt = "Formal Name" descriptionPrompt = "Description" urlPrompt = "URL" providesPrompt = "One or more names to look package up by: (Provides)" versionPrompt = "Version (x.y.z)" architecturePrompt = "Architecture" requirePrompt = "Requires" libPrompt = "Linker Flags (-lfoo -L/usr/lib)" staticLibPrompt = "Static Linking Flags/Libs (extra private libs)" compileFlagsPrompt = "Compile/Include Flags (-I/usr -fpge -O2)" fileNamePrompt = "FPC File's Name" def usage(): """Prints a list of acceptable arguments for fpcmaker.py.""" print """ Fpcmaker.py Options: -n, --name= : Sets %s -d, --description= : Sets %s -u, --url= : Sets %s -p, --provides= : Sets %s -v, --version= : Sets %s -a, --architecture= : Sets %s -r, --requires= : Sets %s -l, --libs= : Sets %s -c, --cflags= : Sets %s -s, --static= : Sets %s -f, --file= : Sets %s """ %(namePrompt, descriptionPrompt, urlPrompt, providesPrompt, versionPrompt, architecturePrompt, requirePrompt, libPrompt, compileFlagsPrompt, staticLibPrompt, fileNamePrompt) return def checkFileName(fileName): """Checks if the fpc file name's blank, contains slashes, or exists.""" nameCleared = False writeFile = True confirms = ['y', 'Y', 'yes', 'Yes'] ##Loops until the name clears or writing the file's aborted. while(not nameCleared and writeFile): ##If it's blank, give the option of aborting the program. if fileName == "": choice = raw_input("Do you want to abort writing the" + " .fpc file? (Y/N): ") if choice not in confirms: fileName = raw_input("Please enter a different name for the" + " .fpc file: ") else: writeFile = False ##If it contains slashes, ask for another name. elif '/' in fileName or '\\' in fileName: print "I can't write to %s because it contains slashes."%(fileName) fileName = raw_input("Please enter a different name for the" + " .fpc file: ") ##If it already exists, ask if they want to overwrite. ##If not, ask for another name. elif os.path.exists(fileName): choice = raw_input("The file %s already exists." %(fileName) + " Do you want to overwrite it? (Y/N): ") if choice not in confirms: fileName = raw_input("Please enter a different name for the" + " .fpc file: ") else: nameCleared = True else: nameCleared = True return [fileName, writeFile] ##Booleans for whether that argument was sent in the command line varSet = False providesSet = False nameSet = False descriptionSet = False urlSet = False architectureSet = False versionSet = False requiresSet = False libsSet = False compileFlagsSet = False staticLibSet = False fileNameSet = False ##Get the options & arguments sent. arguments = sys.argv[1:] try: opts, args = getopt.getopt(arguments, "p:n:u:d:a:r:v:l:c:s:f:", ["provides=", "name=", "url=", "description=", "architecture=", "requires=", "version=", "libs=", "cflags=", "static=", "file="]) ##Send them usage info if they enter a wrong argument except getopt.GetoptError: usage() sys.exit(2) for opt, arg in opts: if opt in ('-p', '--provides'): providesSet = True provides = arg elif opt in ('-n', '--name'): nameSet = True name = arg elif opt in ('-v', '--version'): versionSet = True version = arg elif opt in ('-u', '--url'): urlSet = True url = arg elif opt in ('-d', '--description'): descriptionSet = True description = arg elif opt in ('-a', '--architecture'): architectureSet = True architecture = arg elif opt in ('-r', '--requires'): requiresSet = True requires = arg elif opt in ('-l', '--libs'): libsSet = True libs = arg elif opt in ('-c', '--cflags'): compileFlagsSet = True compileFlags = arg elif opt in ('-s', '--static'): staticLibSet = True staticLib = arg elif opt in ('-f', '--file'): fileNameSet = True fileName = arg ##Grab any input not passed in the arguments from the user. if not varSet: varLine = None variables = "" print "%s:" %(varPrompt) while(varLine != ""): varLine = raw_input("") variables = variables + "%s\n" %(varLine) if not nameSet: name = raw_input("%s: " %(namePrompt)) if not descriptionSet: description = raw_input("%s: " %(descriptionPrompt)) if not urlSet: url = raw_input("%s: " %(urlPrompt)) if not versionSet: version = raw_input("%s: " %(versionPrompt)) if not providesSet: provides = raw_input("%s: " %(providesPrompt)) if not requiresSet: requires = raw_input("%s: " %(requirePrompt)) if not architectureSet: architecture = raw_input("%s: " %(architecturePrompt)) if not libsSet: libs = raw_input("%s: " %(libPrompt)) if not staticLibSet: staticLib = raw_input("%s: " %(staticLibPrompt)) if not compileFlagsSet: compileFlags = raw_input("%s: " %(compileFlagsPrompt)) if not fileNameSet: fileName = raw_input("%s: " %(fileNamePrompt)) ##Check the file's name. fileName, writeFile = checkFileName(fileName) ##If they chose not to overwrite, write the file. if writeFile: fpc = open(fileName, 'w') fpc.write("%s" %(variables)) fpc.write("Name: %s\n" %(name)) fpc.write("Description: %s\n" %(description)) fpc.write("URL: %s\n" %(url)) fpc.write("Version: %s\n" %(version)) fpc.write("Provides: %s\n" %(provides)) fpc.write("Requires: %s\n" %(requires)) fpc.write("Arch: %s\n" %(architecture)) fpc.write("Libs: %s\n" %(libs)) fpc.write("Libs.private: %s\n" %(staticLib)) fpc.write("Cflags: %s\n" %(compileFlags)) fpc.close() ##TESTER: Print the file out. fpc = open(fileName, 'r') ##TESTER print fpc.read() ##TESTER fpc.close ##TESTER
Python
#!/usr/bin/env python from distutils.core import setup try: import py2exe except: pass setup( name='flagpoll', version='0.9.4', description='Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software.', author='Daniel E. Shipton', author_email='dshipton@infiscape.com', license='GPL', url='http://code.google.com/p/flagpoll/', download_url='http://code.google.com/p/flagpoll/downloads/list', console=['flagpoll'], scripts=['flagpoll'], long_description = "Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software. Think of it as the rpm of software development. It enables developers total control over which packages, versions, architectures, etc. that they want to use meta-data from.", data_files=[('share/flagpoll', ['flagpoll.fpc']), ('share/man/man1', ['flagpoll.1']), ('share/aclocal', ['flagpoll.m4']), ('share/html', ['flagpoll-manual.html'])] )
Python
#!/usr/bin/env python # ----------------------------------------------------------------- # # Flag Poll: A tool to extract flags from installed applications # for compiling, settting variables, etc. # # Original Authors: # Daniel E. Shipton <dshipton@gmail.com> # # Flag Poll is Copyright (C) 2006 by Daniel E. Shipton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to: # Free SoftwareFoundation, Inc. # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # # ----------------------------------------------------------------- """Makes a flagpole .fpc file from user input. v0.9 coded by Jeff Groves""" import os import sys import getopt ##String prompts for the input varPrompt = """Convience variables (one 'var_name= var_definition' per line,""" + \ """ empty line when done)""" namePrompt = "Formal Name" descriptionPrompt = "Description" urlPrompt = "URL" providesPrompt = "One or more names to look package up by: (Provides)" versionPrompt = "Version (x.y.z)" architecturePrompt = "Architecture" requirePrompt = "Requires" libPrompt = "Linker Flags (-lfoo -L/usr/lib)" staticLibPrompt = "Static Linking Flags/Libs (extra private libs)" compileFlagsPrompt = "Compile/Include Flags (-I/usr -fpge -O2)" fileNamePrompt = "FPC File's Name" def usage(): """Prints a list of acceptable arguments for fpcmaker.py.""" print """ Fpcmaker.py Options: -n, --name= : Sets %s -d, --description= : Sets %s -u, --url= : Sets %s -p, --provides= : Sets %s -v, --version= : Sets %s -a, --architecture= : Sets %s -r, --requires= : Sets %s -l, --libs= : Sets %s -c, --cflags= : Sets %s -s, --static= : Sets %s -f, --file= : Sets %s """ %(namePrompt, descriptionPrompt, urlPrompt, providesPrompt, versionPrompt, architecturePrompt, requirePrompt, libPrompt, compileFlagsPrompt, staticLibPrompt, fileNamePrompt) return def checkFileName(fileName): """Checks if the fpc file name's blank, contains slashes, or exists.""" nameCleared = False writeFile = True confirms = ['y', 'Y', 'yes', 'Yes'] ##Loops until the name clears or writing the file's aborted. while(not nameCleared and writeFile): ##If it's blank, give the option of aborting the program. if fileName == "": choice = raw_input("Do you want to abort writing the" + " .fpc file? (Y/N): ") if choice not in confirms: fileName = raw_input("Please enter a different name for the" + " .fpc file: ") else: writeFile = False ##If it contains slashes, ask for another name. elif '/' in fileName or '\\' in fileName: print "I can't write to %s because it contains slashes."%(fileName) fileName = raw_input("Please enter a different name for the" + " .fpc file: ") ##If it already exists, ask if they want to overwrite. ##If not, ask for another name. elif os.path.exists(fileName): choice = raw_input("The file %s already exists." %(fileName) + " Do you want to overwrite it? (Y/N): ") if choice not in confirms: fileName = raw_input("Please enter a different name for the" + " .fpc file: ") else: nameCleared = True else: nameCleared = True return [fileName, writeFile] ##Booleans for whether that argument was sent in the command line varSet = False providesSet = False nameSet = False descriptionSet = False urlSet = False architectureSet = False versionSet = False requiresSet = False libsSet = False compileFlagsSet = False staticLibSet = False fileNameSet = False ##Get the options & arguments sent. arguments = sys.argv[1:] try: opts, args = getopt.getopt(arguments, "p:n:u:d:a:r:v:l:c:s:f:", ["provides=", "name=", "url=", "description=", "architecture=", "requires=", "version=", "libs=", "cflags=", "static=", "file="]) ##Send them usage info if they enter a wrong argument except getopt.GetoptError: usage() sys.exit(2) for opt, arg in opts: if opt in ('-p', '--provides'): providesSet = True provides = arg elif opt in ('-n', '--name'): nameSet = True name = arg elif opt in ('-v', '--version'): versionSet = True version = arg elif opt in ('-u', '--url'): urlSet = True url = arg elif opt in ('-d', '--description'): descriptionSet = True description = arg elif opt in ('-a', '--architecture'): architectureSet = True architecture = arg elif opt in ('-r', '--requires'): requiresSet = True requires = arg elif opt in ('-l', '--libs'): libsSet = True libs = arg elif opt in ('-c', '--cflags'): compileFlagsSet = True compileFlags = arg elif opt in ('-s', '--static'): staticLibSet = True staticLib = arg elif opt in ('-f', '--file'): fileNameSet = True fileName = arg ##Grab any input not passed in the arguments from the user. if not varSet: varLine = None variables = "" print "%s:" %(varPrompt) while(varLine != ""): varLine = raw_input("") variables = variables + "%s\n" %(varLine) if not nameSet: name = raw_input("%s: " %(namePrompt)) if not descriptionSet: description = raw_input("%s: " %(descriptionPrompt)) if not urlSet: url = raw_input("%s: " %(urlPrompt)) if not versionSet: version = raw_input("%s: " %(versionPrompt)) if not providesSet: provides = raw_input("%s: " %(providesPrompt)) if not requiresSet: requires = raw_input("%s: " %(requirePrompt)) if not architectureSet: architecture = raw_input("%s: " %(architecturePrompt)) if not libsSet: libs = raw_input("%s: " %(libPrompt)) if not staticLibSet: staticLib = raw_input("%s: " %(staticLibPrompt)) if not compileFlagsSet: compileFlags = raw_input("%s: " %(compileFlagsPrompt)) if not fileNameSet: fileName = raw_input("%s: " %(fileNamePrompt)) ##Check the file's name. fileName, writeFile = checkFileName(fileName) ##If they chose not to overwrite, write the file. if writeFile: fpc = open(fileName, 'w') fpc.write("%s" %(variables)) fpc.write("Name: %s\n" %(name)) fpc.write("Description: %s\n" %(description)) fpc.write("URL: %s\n" %(url)) fpc.write("Version: %s\n" %(version)) fpc.write("Provides: %s\n" %(provides)) fpc.write("Requires: %s\n" %(requires)) fpc.write("Arch: %s\n" %(architecture)) fpc.write("Libs: %s\n" %(libs)) fpc.write("Libs.private: %s\n" %(staticLib)) fpc.write("Cflags: %s\n" %(compileFlags)) fpc.close() ##TESTER: Print the file out. fpc = open(fileName, 'r') ##TESTER print fpc.read() ##TESTER fpc.close ##TESTER
Python
#!/usr/bin/env python # ----------------------------------------------------------------- # # Flagpoll: A tool to extract flags from installed applications # for compiling, settting variables, etc. # # Original Authors: # Daniel E. Shipton <dshipton@gmail.com> # # Flagpoll is Copyright (C) 2006-2007 by Daniel E. Shipton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to: # Free SoftwareFoundation, Inc. # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # # ----------------------------------------------------------------- import sys, os, glob, os.path, copy, platform pj = os.path.join #################################################################### # SNAGGED FROM PYTHON 2.4 for versions under 2.4 #################################################################### import re as _re class _multimap: """Helper class for combining multiple mappings. Used by .{safe_,}substitute() to combine the mapping and keyword arguments. """ def __init__(self, primary, secondary): self._primary = primary self._secondary = secondary def __getitem__(self, key): try: return self._primary[key] except KeyError: return self._secondary[key] class _TemplateMetaclass(type): pattern = r""" %(delim)s(?: (?P<escaped>%(delim)s) | # Escape sequence of two delimiters (?P<named>%(id)s) | # delimiter and a Python identifier {(?P<braced>%(id)s)} | # delimiter and a braced identifier (?P<invalid>) # Other ill-formed delimiter exprs ) """ def __init__(cls, name, bases, dct): super(_TemplateMetaclass, cls).__init__(name, bases, dct) if 'pattern' in dct: pattern = cls.pattern else: pattern = _TemplateMetaclass.pattern % { 'delim' : _re.escape(cls.delimiter), 'id' : cls.idpattern, } cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE) class Template: """A string class for supporting $-substitutions.""" __metaclass__ = _TemplateMetaclass delimiter = '$' idpattern = r'[_a-z][_a-z0-9]*' def __init__(self, template): self.template = template # Search for $$, $identifier, ${identifier}, and any bare $'s def _invalid(self, mo): i = mo.start('invalid') lines = self.template[:i].splitlines(True) if not lines: colno = 1 lineno = 1 else: colno = i - len(''.join(lines[:-1])) lineno = len(lines) raise ValueError('Invalid placeholder in string: line %d, col %d' % (lineno, colno)) def substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): # Check the most common path first. named = mo.group('named') or mo.group('braced') if named is not None: val = mapping[named] # We use this idiom instead of str() because the latter will # fail if val is a Unicode containing non-ASCII characters. return '%s' % val if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: self._invalid(mo) raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) def safe_substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): named = mo.group('named') if named is not None: try: # We use this idiom instead of str() because the latter # will fail if val is a Unicode containing non-ASCII return '%s' % mapping[named] except KeyError: return self.delimiter + named braced = mo.group('braced') if braced is not None: try: return '%s' % mapping[braced] except KeyError: return self.delimiter + '{' + braced + '}' if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: return self.delimiter raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) #################################################################### # End Snagging #################################################################### def tokenize(val, split_char): val = val.strip() results = [] while len(val) > 0: sn = val.find(split_char) qn = val.find('"') #print " -> val: %s Len: %s" % (val, len(val)) # If we find a quote first, then find the space after the next quote. if qn < sn: #print " -> Found a quote first:", qn # Find next quote. qn2 = val.find('"', qn+1) #print " -> Found second quote:", qn2 sn = val.find(split_char, qn2+1) #print " -> Found next space:", sn if sn < 0: results.append(val[:]) val = "" else: results.append(val[:sn]) val = val[sn:] val = val.strip() return results class Utils: # Holds collection of small utility functions EXTRA_FLAGPOLL_SEARCH_PATHS = "" EXTRA_FLAGPOLL_FILES = "" path_list_cache = None # Cache of found path lists. (only calcuate once) KEEP_DUPS = False FLAGPOLL_LIST_OF_POSSIBLE_ERRORS = [] def addPossibleError(pos_err): Utils.FLAGPOLL_LIST_OF_POSSIBLE_ERRORS.append(pos_err) addPossibleError = staticmethod(addPossibleError) def getPossibleErrors(): return Utils.stripDupInList(Utils.FLAGPOLL_LIST_OF_POSSIBLE_ERRORS) getPossibleErrors = staticmethod(getPossibleErrors) def getFlagpollVersion(): FLAGPOLL_MAJOR_VERSION = 0 FLAGPOLL_MINOR_VERSION = 9 FLAGPOLL_PATCH_VERSION = 4 return ( FLAGPOLL_MAJOR_VERSION, FLAGPOLL_MINOR_VERSION, FLAGPOLL_PATCH_VERSION ) getFlagpollVersion = staticmethod(getFlagpollVersion) def getPathList(): if None != Utils.path_list_cache: return Utils.path_list_cache #TODO: expand LD_LIBRARY_PATH to 64/32/etc??? pkg_cfg_dir = [] flg_cfg_dir = [] ld_path = [] if os.environ.has_key("PKG_CONFIG_PATH"): pkg_cfg_dir = os.environ["PKG_CONFIG_PATH"].split(os.pathsep) if os.environ.has_key("FLAGPOLL_PATH"): flg_cfg_dir = os.environ["FLAGPOLL_PATH"].split(os.pathsep) ld_dirs = ['LD_LIBRARY_PATH', 'DYLD_LIBRARY_PATH', 'PATH'] for d in ld_dirs: if os.environ.has_key(d): cur_path = os.environ[d].split(os.pathsep) ld_path_pkg = [pj(p,'pkgconfig') for p in cur_path] ld_path_flg = [pj(p,'flagpoll') for p in cur_path] ld_path.extend(ld_path_pkg) ld_path.extend(ld_path_flg) extra_paths = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS.split(os.pathsep) path_list = extra_paths path_list.extend(flg_cfg_dir) path_list.extend(pkg_cfg_dir) path_list.extend(ld_path) default_path_list = [pj('/','usr','lib64'), pj('/','usr','lib32'), pj('/','usr','lib'), pj('/','usr','share')] default_path_pkg = [pj(p,'pkgconfig') for p in default_path_list] default_path_flg = [pj(p,'flagpoll') for p in default_path_list] path_list.extend(default_path_pkg) path_list.extend(default_path_flg) flagDBG().out(flagDBG.VERBOSE, "Utils.getPathList", "Potential path list: " + str(path_list)) clean_path_list = [] for p in path_list: if os.path.exists(p) and os.path.isdir(p) and not p in clean_path_list: clean_path_list.append(p) path_list = clean_path_list flagDBG().out(flagDBG.INFO, "Utils.getPathList", "Using path list: " + str(path_list)) Utils.path_list_cache = path_list return path_list getPathList = staticmethod(getPathList) def getFileList(): flist = Utils.EXTRA_FLAGPOLL_FILES.split(":") filelist = [] for f in flist: if os.path.isfile(f): filelist.append(f) return filelist getFileList = staticmethod(getFileList) def setKeepDups(keep_dups): Utils.KEEP_DUPS = keep_dups setKeepDups = staticmethod(setKeepDups) def stripDupInList(gen_list): new_list = [] list_len = len(gen_list) i = 0 while i < list_len: item = gen_list[i].strip() if Utils.KEEP_DUPS: if len(item) > 0: new_list.append(item) continue if item in ('-framework', '-arch', '-isysroot'): item = '%s %s' % (item, gen_list[i + 1]) i += 1 if item not in new_list: if len(item) > 0: new_list.append(item) i += 1 return new_list stripDupInList = staticmethod(stripDupInList) def stripDupLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] dir_list = [] list_len = len(flag_list) i = 0 vc_linker_flag_re = _re.compile(r'^[/-]libpath:', _re.I) other_linker_flag_re = _re.compile(r'^-[LRF]') while i < list_len: flg = flag_list[i].strip() if len(flg) > 0: if (other_linker_flag_re.match(flg) is not None\ or vc_linker_flag_re.match(flg) is not None): dir_list.append(flg) else: if flg in ("-framework", "-arch", "-isysroot"): flg = "%s %s" % (flg, flag_list[i + 1]) i += 1 lib_list.append(flg) i += 1 new_list = dir_list + lib_list return Utils.stripDupInList(new_list) stripDupLinkerFlags = staticmethod(stripDupLinkerFlags) def stripDupIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] extra_list = [] list_len = len(flag_list) i = 0 while i < list_len: flg = flag_list[i].strip() if len(flg) > 0: if flg.startswith("-I") or flg.startswith("/I"): inc_list.append(flg) elif flg in ("-arch", "-isysroot"): extra_list.append("%s %s" % (flg, flag_list[i + 1])) i += 1 else: extra_list.append(flg) i += 1 extra_list.sort() new_list = inc_list + extra_list return Utils.stripDupInList(new_list) stripDupIncludeFlags = staticmethod(stripDupIncludeFlags) def cflagsOnlyDirIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-I") or flg.startswith("/I"): inc_list.append(flg) return Utils.stripDupInList(inc_list) cflagsOnlyDirIncludeFlags = staticmethod(cflagsOnlyDirIncludeFlags) def cflagsOnlyOtherIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though extra_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if not flg.startswith("-I") and not flg.startswith("/I"): extra_list.append(flg) return Utils.stripDupInList(extra_list) cflagsOnlyOtherIncludeFlags = staticmethod(cflagsOnlyOtherIncludeFlags) def libsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-l") or flg.endswith(".lib"): lib_list.append(flg) return Utils.stripDupInList(lib_list) libsOnlyLinkerFlags = staticmethod(libsOnlyLinkerFlags) def libsOnlyOtherLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though other_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: upper_flg = flg.upper() if not flg.startswith("-l") \ and not flg.startswith("-L")\ and not flg.startswith("-R")\ and not upper_flg.startswith("/LIBPATH")\ and not upper_flg.startswith("-LIBPATH")\ and not flg.endswith(".lib"): other_list.append(flg) return Utils.stripDupInList(other_list) libsOnlyOtherLinkerFlags = staticmethod(libsOnlyOtherLinkerFlags) def libDirsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though dir_list = [] vc_linker_flag_re = _re.compile(r'^[/-]libpath:', _re.I) other_linker_flag_re = _re.compile(r'^-[LRF]') for flg in flag_list: flg = flg.strip() if len(flg) > 0: if (other_linker_flag_re.match(flg) is not None or vc_linker_flag_re.match(flg) is not None): dir_list.append(flg) return Utils.stripDupInList(dir_list) libDirsOnlyLinkerFlags = staticmethod(libDirsOnlyLinkerFlags) def printList(gen_list): list_string = "" for item in gen_list: if len(item) > 0: list_string += str(item) list_string += " " print list_string.strip() printList = staticmethod(printList) def parsePcFile(filename): lines = open(filename).readlines() fvars = {} fvars["FlagpollFilename"] = filename lokals = {} lokals["fp_file_cwd"] = str(filename[:- ((len(os.path.basename(filename) ) + 1))]) lines.append("prefix: ${prefix}") append_next = False append_dict = {} append_key = "" for line in lines: line = line.strip() if not line: continue if append_next: tmp = append_dict[append_key] tmp = tmp[:-1] + " " + line append_dict[append_key] = tmp if tmp[-1:] == "\\": append_next = True else: append_next = False continue if line.startswith("#"): continue eq_pos = line.find('=') col_pos = line.find(':') if eq_pos < col_pos and eq_pos != -1 or col_pos == -1 and eq_pos != -1: # local variable name, val = line.split('=', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(lokals) except ValueError: flagDBG().out(flagDBG.WARN, "PkgInfo.parse", "%s has an invalid metadata file" % filename) lokals[name] = val if val[-1:] == "\\": append_next = True append_dict = lokals append_key = name continue if col_pos < eq_pos and col_pos != -1 or eq_pos == -1 and col_pos != -1: # exported variable name, val = line.split(':', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(lokals) except ValueError: flagDBG().out(flagDBG.ERROR, "PkgInfo.parse", "%s has an invalid metadata file" % filename) fvars[name] = val if val[-1:] == "\\": append_next = True append_dict = fvars append_key = name return fvars parsePcFile = staticmethod(parsePcFile) class flagDBG(object): # Logging class is really easy to use # Levels: # 0 - VERBOSE # 1 - INFO # 2 - WARN # 3 - ERROR VERBOSE = 0 INFO = 1 WARN = 2 ERROR = 3 __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if flagDBG.__initialized: return flagDBG.__initialized = True self.mLevel = self.WARN self.mLevelList = ["VERBOSE", "INFO", "WARN", "ERROR"] def setLevel(self, level): if level <= 3: self.mLevel = level def out(self, level, obj, message): if level == self.ERROR: if self.mLevel == self.VERBOSE: print self.mLevelList[level] + ":" + str(obj) + ": " + str(message) else: sys.stderr.write(self.mLevelList[level] + ": " + str(message) + "\n") errs = Utils.getPossibleErrors() if len(errs) > 0: sys.stderr.write("Possible culprits:\n") for pos_err in errs: sys.stderr.write( " " + str(pos_err) + "\n" ) sys.exit(1) if level >= self.mLevel: print self.mLevelList[level] + ":" + str(obj) + ": " + str(message) class DepResolutionSystem(object): """ You add PkgAgents with Filters into system and call resolve() you can check for succes by depsSatisfied() and get the list of packages that work back by calling getPackages() """ __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if DepResolutionSystem.__initialized: return DepResolutionSystem.__initialized = True self.mResolveAgents = [] self.mAgentDict = {} self.mFilters = [] self.mResolveAgentFilters = [] self.mInvalidPackageList = [] self.mSatisfied = False self.mAgentChangeList = [] # list of those responsible for adding Filters # to agents in higher in the chain than them # these are the first agents to ask that they pick # the next best package of them self.mAgentsVisitedList = [] # list of Agents that have been visited self.mResolvedPackageList = [] # list that is generated when deps are satified self.mCheckPrivateRequires = False self.mMadeDependList = False def getFilters(self): return self.mFilters def addFilter(self, filter): self.mFilters.append(filter) def addResolveAgentFilter(self, filter): self.mResolveAgentFilters.append(filter) def makeRequireFilter(self, requires): arch_list = [] arch_list.append("no_arch") arch_list.append("") if platform.system() == "Linux": if requires == "64": arch_list.append("x86_64") arch_list.append("x64") if requires == "32": arch_list.append("i386") arch_list.append("i486") arch_list.append("i586") arch_list.append("i686") if platform.system() == "Darwin": if requires == "64": arch_list.append("ppc64") if requires == "32": arch_list.append("ppc") if platform.system().startswith("IRIX"): arch_list.append(requires) new_filter = Filter("Arch", lambda x,v=arch_list: x in v) self.addFilter(new_filter) def createAgent(self, name): if self.checkAgentExists(name): return self.getAgent(name) else: agent = PkgAgent(name) flagDBG().out(flagDBG.INFO, "DepResSys.createAgent", "Adding %s" % name) self.addNewAgent(agent) return agent def createResolveAgent(self, name): if self.checkAgentExists(name): return self.getAgent(name) else: agent = PkgAgent(name) flagDBG().out(flagDBG.INFO, "DepResSys.createResolveAgent", "Adding %s" % name) self.addResolveAgent(agent) return agent def setPrivateRequires( self, req ): self.mCheckPrivateRequires = req def checkPrivateRequires(self): return self.mCheckPrivateRequires def checkAgentExists(self, name): return self.mAgentDict.has_key(name) def getAgent(self, name): if self.mAgentDict.has_key(name): return self.mAgentDict[name] else: flagDBG().out(flagDBG.ERROR, "DepResSys.getAgent", "Agent %s does not exist" % name) def addNewAgent(self, agent): if not self.checkAgentExists(agent): self.mAgentDict[agent.getName()] = agent def addResolveAgent(self, agent): if agent not in self.mResolveAgents: self.mResolveAgents.append(agent) for filt in self.mResolveAgentFilters: agent.addFilter(filt) def isSatisfied(self): return self.mSatisfied def updateResolvedPackages(self): pkg_list = [] agent_list = [] for agent in self.mResolveAgents: list_of_pkgs = agent.getCurrentPackageList(agent_list) pkg_list.extend(list_of_pkgs) self.mResolvedPackageList = pkg_list def getPackages(self): flagDBG().out(flagDBG.INFO, "DepResSys.getPackages", "Generating list of valid packages ") #str([pkg.getCurrentPackage.getName() for pkg in self.mResolvedPackageList])) # If this comes back empty then there isn't a valid set of packages to use self.updateResolvedPackages() return self.mResolvedPackageList def checkFiltersChanged(self): list_to_use = [] return True in [pkg.filtersChanged(list_to_use) for pkg in self.mResolveAgents] def resolveHelper(self): self.resolveAgentsChanged = True while self.resolveAgentsChanged: for agent in self.mResolveAgents: flagDBG().out(flagDBG.INFO, "DepResSys.resolveHelper", "Updating " + agent.getName()) agent.update(self.mAgentsVisitedList, self.mAgentChangeList) self.resolveAgentsChanged = self.checkFiltersChanged() # Ask mResolveAgents if they are done(they ask sub people) unless they are # really above you in the walk # If there were changes...run update on mResolveAgents again # at the end ask for pkglist..if it comes back empty then we don't # have a usable configuration for those packages def resolveDeps(self): self.resolveHelper() if not self.mMadeDependList: for agent in self.mResolveAgents: agent.makeDependList() self.mMadeDependList = True self.updateResolvedPackages() # Check if the first round through we found something # Otherwise we need to start removing packages that aren't viable # during the loop self.mSatisfied = (len(self.mResolvedPackageList) != 0) # remove top of packages that added Filters. # then move on to resolving again # remove more if neccesary agentChangeNumber = 0 while not self.mResolvedPackageList: if(self.mAgentChangeList[agentChangeNumber]): if self.mAgentChangeList[agentChangeNumber] in self.mInvalidPackageList: agentChangeNumber += 1 else: if(self.mAgentChangeList[agentChangeNumber].getViablePackages()): flagDBG().out(flagDBG.INFO, "DepResSys.resolveDeps", "Removing bad pkg from " + self.mAgentChangeList[agentChangeNumber].getName()) self.mInvalidPackageList.append(self.mAgentChangeList[agentChangeNumber].removeCurrentPackage()) else: flagDBG().out(flagDBG.INFO, "DepResSys.resolveDeps", "No combinations.. Resetting " + self.mAgentChangeList[agentChangeNumber].getName()) self.mAgentChangeList[agentChangeNumber].reset() agentChangeNumber += 1 self.resolveHelper() self.updateResolvedPackages() self.mSatisfied = (len(self.mResolvedPackageList) != 0) return class PkgAgent: """ Agent that keeps track of the versions for a package given some filters and the addition of Filters """ # Makes a PkgAgent that finds its current package with the version reqs def __init__(self, name): if DepResolutionSystem().checkAgentExists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "Package Agent %s already exists" % self.mName) self.mName = name flagDBG().out(flagDBG.INFO, "PkgAgent", "Creating:" + str(self.mName)) if not PkgDB().exists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "No info for package: %s" % self.mName) #XXX Doesn't keep filters added for a redo... DepResolutionSystem().addNewAgent(self) self.mFilterList = [] self.mFilterList.extend(DepResolutionSystem().getFilters()) self.mBasePackageList = PkgDB().getPkgInfos(name) self.mBasePackageList.sort(lambda lhs, rhs: cmp(rhs.getVariable('Version'), lhs.getVariable('Version'))) for filt in self.mFilterList: self.mBasePackageList = filt.filter(self.mBasePackageList) if len(self.mBasePackageList) == 0: flagDBG().out(flagDBG.ERROR, "PkgAgent", "No viable packages for: %s" % self.mName) self.mViablePackageList = copy.deepcopy(self.mBasePackageList) if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mFiltersChanged = True self.mCheckDepends = True self.mAgentDependList = [] def getName(self): return self.mName def setCheckDepends(self, tf): self.mCheckDepends = tf #Filter("Version", lambda x: x == "4.5") def makeDependList(self): if not self.mCheckDepends: self.mAgentDependList = [] return dep_list = [] if self.mCurrentPackage: req_string = self.mCurrentPackage.getVariable("Requires") if DepResolutionSystem().checkPrivateRequires(): req_string = req_string + " " + self.mCurrentPackage.getVariable("Requires.private") req_string = req_string.strip() if req_string == "": return req_string = req_string.replace(',', ' ') req_string = req_string.replace('(', ' ') req_string = req_string.replace(')', ' ') space_req_string_list = req_string.split(' ') req_string_list = [] for entry in space_req_string_list: if len(entry) > 0: req_string_list.append(entry) i = 0 flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList", self.mCurrentPackage.getName() + " requires: " + str(req_string_list)) while len(req_string_list) > i: if PkgDB().exists(req_string_list[i]): new_filter = [] new_agent = DepResolutionSystem().createAgent(req_string_list[i]) if len(req_string_list) > i+1: if req_string_list[i+1] == "=": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x == v) elif req_string_list[i+1] == "<=": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x <= v) elif req_string_list[i+1] == ">=": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x >= v) elif req_string_list[i+1] == ">": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x > v) elif req_string_list[i+1] == "<": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x < v) else: i += 1 else: i += 1 dep_list.append(new_agent) if new_filter: i+=3 new_agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "PkgAgent.makeDependList", "Package %s depends on %s but does not seem to be installed." % (self.mName, str(req_string_list[i]))) flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList", str(self.mName) + " : List is:" + str([pkg.getName() for pkg in dep_list])) self.mAgentDependList = dep_list def filtersChanged(self, packageList): tf_list = [self.mFiltersChanged] if self.mName not in packageList: packageList.append(self.mName) for pkg in self.mAgentDependList: tf_list.append(pkg.filtersChanged(packageList)) return True in tf_list def getCurrentPackageList(self, packageList): pkgs = [] if self.mName not in packageList: flagDBG().out(flagDBG.INFO, "PkgAgent.getCurrentPackageList", "Package: %s" % self.mName) pkgs.append(self.mCurrentPackage) packageList.append(self.mName) # Make depend list if we are supposed to self.updateFilters() self.makeDependList() for pkg in self.mAgentDependList: pkgs.extend(pkg.getCurrentPackageList(packageList)) return pkgs # current pkginfo for me def getCurrentPkgInfo(self): return self.mCurrentPackage # Someone else usually places these on me # I keep track of those separately def addFilter(self, filter): flagDBG().out(flagDBG.INFO, "PkgAgent.addFilter", "Filter %s" % self.mName + " on %s." % filter.getVarName()) self.mFiltersChanged = True self.mFilterList.append(filter) def removeCurrentPackage(self): flagDBG().out(flagDBG.INFO, "PkgAgent.removeCurrentPackage", "Removing current package of %s" % self.mName) if self.mViablePackageList: ret_val = self.mViablePackageList[0] in self.mBasePackageList del self.mViablePackageList[0] if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] return ret_val def update(self, agentVisitedList, agentChangeList): flagDBG().out(flagDBG.INFO, "PkgAgent.update", "%s" % self.mName) if self.mName in agentVisitedList: return agentVisitedList.append(self.mName) if self.mFiltersChanged: self.mFiltersChanged = False self.updateFilters() # TODO: checkFilters and add them # if a pkg is in visitedList then add yourself to agentChangeList for pkg in self.mAgentDependList: pkg.update(agentVisitedList, agentChangeList) return def updateFilters(self): for filt in self.mFilterList: self.mViablePackageList = filt.filter(self.mViablePackageList) flagDBG().out(flagDBG.INFO, "PkgAgent.updateFilters", "%s has " % self.mName + str(len(self.mViablePackageList)) + " left") if len(self.mViablePackageList) > 0: self.mCurrentPackage = self.mViablePackageList[0] else: for f in self.mFilterList: Utils.addPossibleError(str(self.mName) + " -> " + str(f.getVarName())) self.mCurrentPackage = [] def reset(self): flagDBG().out(flagDBG.INFO, "PkgAgent.reset", "Resetting package: %s" % self.mName) self.mViablePackageList = self.mBasePackageList if self.mViablePackageList: self.mCurrentPacakge = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mFilterList = DepResolutionSystem().getFilters() self.mAgentDependList = [] self.mFiltersChanged = True return class Filter: """ A single Filter that knows how to filter the list it recieves Will be inheireted....?..? """ def __init__(self, variableName, testCallable): self.mVarName = variableName self.mTestCallable = testCallable def getVarName(self): return self.mVarName def filter(self, pkg_info_list): ret_pkg_list = [] # Filter first for pkg in pkg_info_list: var = pkg.getVariable(self.mVarName) if self.mTestCallable(var): flagDBG().out(flagDBG.INFO, "Filter", "Passed: %s:" % pkg.getName() + " %s is " % self.mVarName + str(var)) ret_pkg_list.append(pkg) else: flagDBG().out(flagDBG.INFO, "Filter", "Failed: %s:" % pkg.getName() + " %s is " % self.mVarName + str(var)) # Now sort ret_pkg_list.sort(lambda lhs, rhs: cmp(rhs.getVariable(self.mVarName), lhs.getVariable(self.mVarName))) return ret_pkg_list #requires: qt == 4.5 #Filter("Version", lambda x: x <= "4.5") #Filter("Version", lambda x: x <= "4.5") class PkgDB(object): """ Holds all the neccesary information to evaluate itself when needed. Is in charge of holding a list of PkgInfo's that contain info about the package. """ __initialized = False def __init__(self): if self.__initialized: return self.__initialized = True self.mPkgInfos = {} # {pkg_name: List of package infos} self.populatePkgInfoDBPcFiles() self.populatePkgInfoDBFpcFiles() def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def printAllPackages(self): list_of_package_names = [] for pkg in self.mPkgInfos: list_of_package_names.append(pkg) for name in list_of_package_names: print name sys.exit(0) def getVariables(self, name, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariable", "Finding " + str(variable_list) + " in " + str(name)) ret_list = [] for var in variable_list: if self.mPkgInfos.has_key(name): ret_list.extend(self.mPkgInfos[name][0].getVariable(var)) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariable", "Package %s not found." % name) return ret_list def checkPackage(self, name): flagDBG().out(flagDBG.INFO, "PkgDB.checkPackage", "Finding " + str(name)) if self.mPkgInfos.has_key(name): return True else: flagDBG().out(flagDBG.ERROR, "PkgDB.CheckPackage", "Package %s not found." % name) return False def getVariablesAndDeps(self, pkg_list, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariablesAndDeps", "Finding " + str(variable_list) + " in " + str(pkg_list)) if DepResolutionSystem().checkPrivateRequires(): temp_var_list = [] for var in variable_list: temp_var_list.append(var.join(".private")) variable_list = variable_list + temp_var_list for name in pkg_list: if self.mPkgInfos.has_key(name): agent = DepResolutionSystem().createAgent(name) DepResolutionSystem().addResolveAgent(agent) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariablesAndDeps", "Package %s not found." % name) DepResolutionSystem().resolveDeps() pkgs = DepResolutionSystem().getPackages() var_list = [] for pkg in pkgs: if pkg: for var in variable_list: var_list.extend(tokenize(pkg.getVariable(var), pkg.getSplitChar())) return var_list def getPkgInfos(self, name): if self.mPkgInfos.has_key(name): return self.mPkgInfos[name] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getPkgInfos", "Package %s not found." % name) def exists(self, name): return self.mPkgInfos.has_key(name) def getInfo(self, name): if self.mPkgInfos.has_key(name): return [pkg.getInfo() for pkg in self.mPkgInfos[name]] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getInfo", "Package %s not found." % name) def buildPcFileDict(self): """ Builds up a dictionary of {name: list of files for name} """ pc_dict = {} for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.pc")) # List of .pc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these pc files: %s" % str(glob_list)) for g in glob_list: # Get key name and add file to value list in dictionary key = os.path.basename(g)[:-3] # Strip .pc off the filename...rstrip no worky pc_dict.setdefault(key, []).append(g) for f in Utils.getFileList(): if f.endswith(".pc"): key = os.path.basename(f)[:-3] # Strip .pc off the filename...rstrip no worky pc_dict.setdefault(key, []).append(f) return pc_dict # { "key", [ "list", "of", "corresponding", "pc", "files"] } def populatePkgInfoDBPcFiles(self): dict_to_pop_from = self.buildPcFileDict() for (pkg,files) in dict_to_pop_from.iteritems(): for f in files: self.mPkgInfos.setdefault(pkg,[]).append(PkgInfo(pkg, f, "pc")) def buildFpcFileList(self): """ Builds up a dictionary of {name: list of files for name} """ file_list = [] for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.fpc")) # List of .fpc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these fpc files: %s" % str(glob_list)) for g in glob_list: file_list.append(g) for f in Utils.getFileList(): if f.endswith(".fpc"): file_list.append(f) return file_list # [ "list", "of", "fpc", "files"] def populatePkgInfoDBFpcFiles(self): list_to_add = self.buildFpcFileList() for filename in list_to_add: var_dict = Utils.parsePcFile(filename) if not var_dict.has_key("Provides"): flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Provides" % str(filename)) continue if not var_dict.has_key("Arch"): flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Arch" % str(filename)) continue provides_string = var_dict["Provides"] provides_string = provides_string.replace(',', ' ') provides_string = provides_string.replace('(', ' ') provides_string = provides_string.replace(')', ' ') for key in provides_string.split(" "): if len(key) > 0: self.mPkgInfos.setdefault(key, []).append(PkgInfo(key, filename, "fpc", var_dict)) class PkgInfo: """ Holds the information for a package file on the system. These however are evaluated when the need arises. """ def __init__(self, name, file, type, varDict={}): self.mName = name self.mFile = file self.mIsEvaluated = False self.mType = type self.mVariableDict = varDict if self.mType == "fpc": self.mIsEvaluated = True def getVariable(self, variable): self.evaluate() return self.mVariableDict.get(variable,"") def getName(self): return self.mName def evaluate(self): if not self.mIsEvaluated: flagDBG().out(flagDBG.INFO, "PkgInfo.evaluate", "Evaluating %s" % self.mName) self.mVariableDict= Utils.parsePcFile(self.mFile) self.mIsEvaluated = True def getInfo(self): self.evaluate() return self.mVariableDict def getSplitChar(self): self.evaluate() split_char = self.mVariableDict.get("SplitCharacter", ' ') if split_char == "": split_char = ' ' return split_char class OptionsEvaluator: def __init__(self): if len(sys.argv) < 2: self.printHelp() # This is only the args....(first arg is stripped) def evaluateArgs(self, args): # Catch any args that need to be tended to immediately # Process args in the order that they were recieved. Some options are not # shown below because they are sub-options of an option below (--strip-dups) for option in args: if option.startswith("--verbose-debug"): flagDBG().setLevel(flagDBG.VERBOSE) if option.startswith("--debug"): flagDBG().setLevel(flagDBG.INFO) elif option.startswith("--from-file"): val_start = option.find('=') + 1 file = option[val_start:] Utils.EXTRA_FLAGPOLL_FILES = Utils.EXTRA_FLAGPOLL_FILES + ":" + file elif option.startswith("--help"): self.printHelp() sys.exit(0) elif option.startswith("--version"): print "%s.%s.%s" % Utils.getFlagpollVersion() sys.exit(0) elif option.startswith("--list-all"): PkgDB().printAllPackages() continue listedAgentNames = [] agent = None num_args = len(args) curr_arg = 0 output_options = [] # (option, name/"") important_options = [] # ones that need special attention while curr_arg < num_args: if args[curr_arg].startswith("--atleast-version"): val_start = args[curr_arg].find('=') + 1 atleast_version = args[curr_arg][val_start:] atleast_filter = Filter("Version", lambda x,v=atleast_version: x >= v) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(atleast_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --at-least-version") continue if args[curr_arg].startswith("--cflags-only-I"): output_options.append(("cflags-only-I", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--cflags-only-other"): output_options.append(("cflags-only-other", "")) curr_arg = curr_arg + 1 continue #This could be the catch all for the above ones to and then filter based on what is asked... #For clarity of course... if args[curr_arg].startswith("--cflags"): output_options.append(("cflags", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--extra-paths"): val_start = args[curr_arg].find('=') + 1 paths = args[curr_arg][val_start:] Utils.EXTRA_FLAGPOLL_SEARCH_PATHS = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS + ":" + paths curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--exact-version"): val_start = args[curr_arg].find('=') + 1 exact_version = args[curr_arg][val_start:] exact_filter = Filter("Version", lambda x,v=exact_version: x == v) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(exact_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --exact-version") continue if args[curr_arg].startswith("--exists"): important_options.append("exists") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--from-file"): val_start = args[curr_arg].find('=') + 1 file = args[curr_arg][val_start:] file_filter = Filter("FlagpollFilename", lambda x,f=file: x == f) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(file_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --from-file") continue if args[curr_arg].startswith("--info"): important_options.append("info") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--print-pkg-options"): important_options.append("print-pkg-options") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--keep-dups"): Utils.setKeepDups(True) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-l"): output_options.append(("libs-only-l", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-L"): output_options.append(("libs-only-L", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-other"): output_options.append(("libs-only-other", "")) curr_arg = curr_arg + 1 continue #This could be the catch all for the above ones to and then filter based on what is asked... if args[curr_arg].startswith("--libs"): output_options.append(("libs", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--require-all"): rlen = len("--require-all") req_string = args[curr_arg][rlen:] req_string = req_string.replace('-','_') curr_arg = curr_arg + 1 if req_string.find("<=") != -1: op_start = req_string.find("<=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x <= v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find(">=") != -1: op_start = req_string.find(">=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x >= v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find(">") != -1: op_start = req_string.find(">") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x > v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("<") != -1: op_start = req_string.find("<") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x < v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("=") != -1: op_start = req_string.find("=") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x == v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("=") == -1: new_filter = Filter(req_string, lambda x: len(x) > 0) DepResolutionSystem().addFilter(new_filter) continue continue if args[curr_arg].startswith("--require-"): rlen = len("--require-") req_string = args[curr_arg][rlen:] req_string = req_string.replace('-','_') curr_arg = curr_arg + 1 if agent is None: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --require") if req_string.find("<=") != -1: op_start = req_string.find("<=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x <= v) agent.addFilter(new_filter) continue if req_string.find(">=") != -1: op_start = req_string.find(">=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x >= v) agent.addFilter(new_filter) continue if req_string.find(">") != -1: op_start = req_string.find(">") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x > v) agent.addFilter(new_filter) continue if req_string.find("<") != -1: op_start = req_string.find("<") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x < v) agent.addFilter(new_filter) continue if req_string.find("=") != -1: op_start = req_string.find("=") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x == v) agent.addFilter(new_filter) continue if req_string.find("=") == -1: new_filter = Filter(req_string, lambda x: len(x) > 0) agent.addFilter(new_filter) continue continue if args[curr_arg].startswith("--no-deps"): if agent is not None: agent.setCheckDepends(False) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --no-deps") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--require="): val_start = args[curr_arg].find('=') + 1 req_var = args[curr_arg][val_start:] curr_arg = curr_arg + 1 DepResolutionSystem().makeRequireFilter(req_var) continue if args[curr_arg].startswith("--modversion"): if agent is not None: output_options.append(("Version", agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --modversion") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--max-release"): val_start = args[curr_arg].find('=') + 1 max_release = args[curr_arg][val_start:] max_filter = Filter("Version", lambda x,v=max_release: x.startswith(v)) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(max_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --max-release") continue if args[curr_arg].startswith("--static"): DepResolutionSystem().setPrivateRequires(True) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--variable"): val_start = args[curr_arg].find('=') + 1 fetch_var = args[curr_arg][val_start:] if agent is not None: output_options.append((fetch_var, agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --variable") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--get-all"): rlen = len("--get-all-") get_string = args[curr_arg][rlen:] get_string = get_string.replace('-','_') output_options.append((get_string, "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--get"): rlen = len("--get-") get_string = args[curr_arg][rlen:] get_string = get_string.replace('-','_') if agent is not None: output_options.append((get_string, agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --get") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--concat"): important_options.append("concat") curr_arg = curr_arg + 1 continue if not args[curr_arg].startswith("--"): name = args[curr_arg] curr_arg = curr_arg + 1 if PkgDB().checkPackage(name): agent = DepResolutionSystem().createResolveAgent(name) listedAgentNames.append(name) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Package %s" % name) sys.exit(1) continue if args[curr_arg] != "--debug" and args[curr_arg] != "--verbose-debug": flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Option: %s" % args[curr_arg]) curr_arg = curr_arg + 1 if len(listedAgentNames) == 0: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Must specify at least one package") DepResolutionSystem().resolveDeps() pkgs = DepResolutionSystem().getPackages() for p in pkgs: if not p: for option in important_options: if option == "exists": print "no" sys.exit(1) flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found") if len(pkgs) == 0: for option in important_options: if option == "exists": print "no" sys.exit(1) flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found") sys.exit(1) concat = False for option in important_options: if option == "exists": print "yes" return sys.exit(0) # already checked for none above if option == "concat": concat = True if option == "info": pkg_info_list = [] for pkg in pkgs: if pkg.getName() in listedAgentNames: print pkg.getName() pkg_info = pkg.getInfo() for key in pkg_info.keys(): print " %s : %s" % (key, pkg_info[key]) if option == "print-pkg-options": print "" print "All options below would start with (--get-/--get-all-/--require-/--require-all-)" print "NOTE: this list does not include the standard variables that are exported." print "" for pkg in pkgs: if pkg.getName() not in listedAgentNames: continue print "Package: " + pkg.getName() for key in pkg.getInfo().keys(): if key not in [ "Name", "Description", "URL", "Version", "Requires", "Requires.private", "Conflicts", "Libs", "Libs.private", "Cflags", "Provides", "Arch", "FlagpollFilename", "prefix" ]: print " " + key.replace('_','-') #print output_options #output_options = [] #output_single = [] #Process options here.............. concat_list = [] if concat: print_option = lambda x: concat_list.extend(x) else: print_option = lambda x: Utils.printList(x) for option in output_options: if option[0] == "cflags": print_option(Utils.stripDupIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "cflags-only-I": print_option(Utils.cflagsOnlyDirIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "cflags-only-other": print_option(Utils.cflagsOnlyOtherIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "libs-only-l": print_option(Utils.libsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs-only-L": print_option(Utils.libDirsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs-only-other": print_option(Utils.libsOnlyOtherLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs": print_option(Utils.stripDupLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) else: print_option(Utils.stripDupInList(self.getVarFromPkgs(option[0], pkgs, option[1]))) if concat: Utils.printList(Utils.stripDupInList(concat_list)) def getVarFromPkgs(self, var, pkgs, pkg_name=""): var_list = [] ext_vars = [] if var == "Libs": if DepResolutionSystem().checkPrivateRequires: ext_vars.append("Libs.private") if pkg_name == "": for pkg in pkgs: if pkg: var_list.extend(tokenize(pkg.getVariable(var), pkg.getSplitChar())) for extra_var in ext_vars: var_list.extend(tokenize(pkg.getVariable(extra_var), pkg.getSplitChar())) else: for pkg in pkgs: if pkg: if pkg.getName() == pkg_name: var_list.extend(tokenize(pkg.getVariable(var), pkg.getSplitChar())) for extra_var in ext_vars: var_list.extend(tokenize(pkg.getVariable(extra_var), pkg.getSplitChar())) return var_list def printHelp(self): print "usage: flagpoll pkg options [pkg options] [generic options]" print " " print "generic options:" print " --help show this help message and exit" print " --version output version of flagpoll" print " --list-all list all known packages" print " --debug show debug information" print " --verbose-debug show verbose debug information" print " --extra-paths=EXTRA_PATHS" print " extra paths for flagpoll to search for meta-data files" print " --concat concatenate all output and output as one line" print " --keep-dups do not strip out all duplicate info from options" print " --info show information for packages" print " --print-pkg-options show pkg specific options" print " " print "options:" print " --modversion output version for package" print " --require=REQUIRE adds additional requirements for packages ex. 32/64" print " --libs output all linker flags" print " --static output linker flags for static linking" print " --libs-only-l output -l flags" print " --libs-only-other output other libs (e.g. -pthread)" print " --libs-only-L output -L flags" print " --cflags output all pre-processor and compiler flags" print " --cflags-only-I output -I flags" print " --cflags-only-other output cflags not covered by the cflags-only-I option" print " --exists return 0 if the module(s) exist" print " --from-file=FILE use the specified FILE for the package" #print " --print-provides print which packages the package provides" #print " --print-requires print which packages the package requires" print " --no-deps do not lookup dependencies for the package" print " --atleast-version=ATLEAST_VERSION" print " return 0 if the module is at least version" print " ATLEAST_VERSION" print " --exact-version=EXACT_VERSION" print " return 0 if the module is exactly version" print " EXACT_VERSION" print " --max-release=MAX_RELEASE" print " return 0 if the module has a release that has a" print " version of MAX_RELEASE and will return the max" print " --variable=VARIABLE get the value of a variable" print " " print "dynamic options(replace VAR with a variable you want to get/filter on)" print " NOTE: replace underscores with dashes in VAR" print " NOTE: quotes are needed around <,>,= combinations" print " --get-VAR get VAR from package" print " --get-all-VAR get VAR from package and its deps" print " --require-VAR[<,>,=VAL]" print " require that a var is defined for a package" print " or optionally use equality operators against VAL" print " --require-all-VAR[<,>,=VAL]" print " require that a var is defined for all packages" print " or optionally use equality operators against VAL" print "" print "extending search path" print " FLAGPOLL_PATH environment variable that can be set to" print " extend the search path for .fpc/.pc files" print "" print "" print "Send bug reports and/or feedback to flagpoll-users@vrsource.org" sys.exit(0) def main(): # GO! # Initialize singletons and the start evaluating my_dbg = flagDBG() my_dep_system = DepResolutionSystem() opt_evaluator = OptionsEvaluator() opt_evaluator.evaluateArgs(sys.argv[1:]) sys.exit(0) if __name__ == "__main__": main()
Python
#!/usr/bin/env python from distutils.core import setup try: import py2exe except: pass setup( name='flagpoll', version='0.9.4', description='Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software.', author='Daniel E. Shipton', author_email='dshipton@infiscape.com', license='GPL', url='http://code.google.com/p/flagpoll/', download_url='http://code.google.com/p/flagpoll/downloads/list', console=['flagpoll'], scripts=['flagpoll'], long_description = "Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software. Think of it as the rpm of software development. It enables developers total control over which packages, versions, architectures, etc. that they want to use meta-data from.", data_files=[('share/flagpoll', ['flagpoll.fpc']), ('share/man/man1', ['flagpoll.1']), ('share/aclocal', ['flagpoll.m4']), ('share/html', ['flagpoll-manual.html'])] )
Python
#!/usr/bin/env python # ----------------------------------------------------------------- # # Flagpoll: A tool to extract flags from installed applications # for compiling, settting variables, etc. # # Original Authors: # Daniel E. Shipton <dshipton@gmail.com> # # Flagpoll is Copyright (C) 2006-2007 by Daniel E. Shipton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to: # Free SoftwareFoundation, Inc. # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # # ----------------------------------------------------------------- import sys, os, glob, os.path, copy, platform pj = os.path.join #################################################################### # SNAGGED FROM PYTHON 2.4 for versions under 2.4 #################################################################### import re as _re class _multimap: """Helper class for combining multiple mappings. Used by .{safe_,}substitute() to combine the mapping and keyword arguments. """ def __init__(self, primary, secondary): self._primary = primary self._secondary = secondary def __getitem__(self, key): try: return self._primary[key] except KeyError: return self._secondary[key] class _TemplateMetaclass(type): pattern = r""" %(delim)s(?: (?P<escaped>%(delim)s) | # Escape sequence of two delimiters (?P<named>%(id)s) | # delimiter and a Python identifier {(?P<braced>%(id)s)} | # delimiter and a braced identifier (?P<invalid>) # Other ill-formed delimiter exprs ) """ def __init__(cls, name, bases, dct): super(_TemplateMetaclass, cls).__init__(name, bases, dct) if 'pattern' in dct: pattern = cls.pattern else: pattern = _TemplateMetaclass.pattern % { 'delim' : _re.escape(cls.delimiter), 'id' : cls.idpattern, } cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE) class Template: """A string class for supporting $-substitutions.""" __metaclass__ = _TemplateMetaclass delimiter = '$' idpattern = r'[_a-z][_a-z0-9]*' def __init__(self, template): self.template = template # Search for $$, $identifier, ${identifier}, and any bare $'s def _invalid(self, mo): i = mo.start('invalid') lines = self.template[:i].splitlines(True) if not lines: colno = 1 lineno = 1 else: colno = i - len(''.join(lines[:-1])) lineno = len(lines) raise ValueError('Invalid placeholder in string: line %d, col %d' % (lineno, colno)) def substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): # Check the most common path first. named = mo.group('named') or mo.group('braced') if named is not None: val = mapping[named] # We use this idiom instead of str() because the latter will # fail if val is a Unicode containing non-ASCII characters. return '%s' % val if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: self._invalid(mo) raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) def safe_substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): named = mo.group('named') if named is not None: try: # We use this idiom instead of str() because the latter # will fail if val is a Unicode containing non-ASCII return '%s' % mapping[named] except KeyError: return self.delimiter + named braced = mo.group('braced') if braced is not None: try: return '%s' % mapping[braced] except KeyError: return self.delimiter + '{' + braced + '}' if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: return self.delimiter raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) #################################################################### # End Snagging #################################################################### def tokenize(val, split_char): val = val.strip() results = [] while len(val) > 0: sn = val.find(split_char) qn = val.find('"') #print " -> val: %s Len: %s" % (val, len(val)) # If we find a quote first, then find the space after the next quote. if qn < sn: #print " -> Found a quote first:", qn # Find next quote. qn2 = val.find('"', qn+1) #print " -> Found second quote:", qn2 sn = val.find(split_char, qn2+1) #print " -> Found next space:", sn if sn < 0: results.append(val[:]) val = "" else: results.append(val[:sn]) val = val[sn:] val = val.strip() return results class Utils: # Holds collection of small utility functions EXTRA_FLAGPOLL_SEARCH_PATHS = "" EXTRA_FLAGPOLL_FILES = "" path_list_cache = None # Cache of found path lists. (only calcuate once) KEEP_DUPS = False FLAGPOLL_LIST_OF_POSSIBLE_ERRORS = [] def addPossibleError(pos_err): Utils.FLAGPOLL_LIST_OF_POSSIBLE_ERRORS.append(pos_err) addPossibleError = staticmethod(addPossibleError) def getPossibleErrors(): return Utils.stripDupInList(Utils.FLAGPOLL_LIST_OF_POSSIBLE_ERRORS) getPossibleErrors = staticmethod(getPossibleErrors) def getFlagpollVersion(): FLAGPOLL_MAJOR_VERSION = 0 FLAGPOLL_MINOR_VERSION = 9 FLAGPOLL_PATCH_VERSION = 4 return ( FLAGPOLL_MAJOR_VERSION, FLAGPOLL_MINOR_VERSION, FLAGPOLL_PATCH_VERSION ) getFlagpollVersion = staticmethod(getFlagpollVersion) def getPathList(): if None != Utils.path_list_cache: return Utils.path_list_cache #TODO: expand LD_LIBRARY_PATH to 64/32/etc??? pkg_cfg_dir = [] flg_cfg_dir = [] ld_path = [] if os.environ.has_key("PKG_CONFIG_PATH"): pkg_cfg_dir = os.environ["PKG_CONFIG_PATH"].split(os.pathsep) if os.environ.has_key("FLAGPOLL_PATH"): flg_cfg_dir = os.environ["FLAGPOLL_PATH"].split(os.pathsep) ld_dirs = ['LD_LIBRARY_PATH', 'DYLD_LIBRARY_PATH', 'PATH'] for d in ld_dirs: if os.environ.has_key(d): cur_path = os.environ[d].split(os.pathsep) ld_path_pkg = [pj(p,'pkgconfig') for p in cur_path] ld_path_flg = [pj(p,'flagpoll') for p in cur_path] ld_path.extend(ld_path_pkg) ld_path.extend(ld_path_flg) extra_paths = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS.split(os.pathsep) path_list = extra_paths path_list.extend(flg_cfg_dir) path_list.extend(pkg_cfg_dir) path_list.extend(ld_path) default_path_list = [pj('/','usr','lib64'), pj('/','usr','lib32'), pj('/','usr','lib'), pj('/','usr','share')] default_path_pkg = [pj(p,'pkgconfig') for p in default_path_list] default_path_flg = [pj(p,'flagpoll') for p in default_path_list] path_list.extend(default_path_pkg) path_list.extend(default_path_flg) flagDBG().out(flagDBG.VERBOSE, "Utils.getPathList", "Potential path list: " + str(path_list)) clean_path_list = [] for p in path_list: if os.path.exists(p) and os.path.isdir(p) and not p in clean_path_list: clean_path_list.append(p) path_list = clean_path_list flagDBG().out(flagDBG.INFO, "Utils.getPathList", "Using path list: " + str(path_list)) Utils.path_list_cache = path_list return path_list getPathList = staticmethod(getPathList) def getFileList(): flist = Utils.EXTRA_FLAGPOLL_FILES.split(":") filelist = [] for f in flist: if os.path.isfile(f): filelist.append(f) return filelist getFileList = staticmethod(getFileList) def setKeepDups(keep_dups): Utils.KEEP_DUPS = keep_dups setKeepDups = staticmethod(setKeepDups) def stripDupInList(gen_list): new_list = [] list_len = len(gen_list) i = 0 while i < list_len: item = gen_list[i].strip() if Utils.KEEP_DUPS: if len(item) > 0: new_list.append(item) continue if item in ('-framework', '-arch', '-isysroot'): item = '%s %s' % (item, gen_list[i + 1]) i += 1 if item not in new_list: if len(item) > 0: new_list.append(item) i += 1 return new_list stripDupInList = staticmethod(stripDupInList) def stripDupLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] dir_list = [] list_len = len(flag_list) i = 0 vc_linker_flag_re = _re.compile(r'^[/-]libpath:', _re.I) other_linker_flag_re = _re.compile(r'^-[LRF]') while i < list_len: flg = flag_list[i].strip() if len(flg) > 0: if (other_linker_flag_re.match(flg) is not None\ or vc_linker_flag_re.match(flg) is not None): dir_list.append(flg) else: if flg in ("-framework", "-arch", "-isysroot"): flg = "%s %s" % (flg, flag_list[i + 1]) i += 1 lib_list.append(flg) i += 1 new_list = dir_list + lib_list return Utils.stripDupInList(new_list) stripDupLinkerFlags = staticmethod(stripDupLinkerFlags) def stripDupIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] extra_list = [] list_len = len(flag_list) i = 0 while i < list_len: flg = flag_list[i].strip() if len(flg) > 0: if flg.startswith("-I") or flg.startswith("/I"): inc_list.append(flg) elif flg in ("-arch", "-isysroot"): extra_list.append("%s %s" % (flg, flag_list[i + 1])) i += 1 else: extra_list.append(flg) i += 1 extra_list.sort() new_list = inc_list + extra_list return Utils.stripDupInList(new_list) stripDupIncludeFlags = staticmethod(stripDupIncludeFlags) def cflagsOnlyDirIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-I") or flg.startswith("/I"): inc_list.append(flg) return Utils.stripDupInList(inc_list) cflagsOnlyDirIncludeFlags = staticmethod(cflagsOnlyDirIncludeFlags) def cflagsOnlyOtherIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though extra_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if not flg.startswith("-I") and not flg.startswith("/I"): extra_list.append(flg) return Utils.stripDupInList(extra_list) cflagsOnlyOtherIncludeFlags = staticmethod(cflagsOnlyOtherIncludeFlags) def libsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-l") or flg.endswith(".lib"): lib_list.append(flg) return Utils.stripDupInList(lib_list) libsOnlyLinkerFlags = staticmethod(libsOnlyLinkerFlags) def libsOnlyOtherLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though other_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: upper_flg = flg.upper() if not flg.startswith("-l") \ and not flg.startswith("-L")\ and not flg.startswith("-R")\ and not upper_flg.startswith("/LIBPATH")\ and not upper_flg.startswith("-LIBPATH")\ and not flg.endswith(".lib"): other_list.append(flg) return Utils.stripDupInList(other_list) libsOnlyOtherLinkerFlags = staticmethod(libsOnlyOtherLinkerFlags) def libDirsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though dir_list = [] vc_linker_flag_re = _re.compile(r'^[/-]libpath:', _re.I) other_linker_flag_re = _re.compile(r'^-[LRF]') for flg in flag_list: flg = flg.strip() if len(flg) > 0: if (other_linker_flag_re.match(flg) is not None or vc_linker_flag_re.match(flg) is not None): dir_list.append(flg) return Utils.stripDupInList(dir_list) libDirsOnlyLinkerFlags = staticmethod(libDirsOnlyLinkerFlags) def printList(gen_list): list_string = "" for item in gen_list: if len(item) > 0: list_string += str(item) list_string += " " print list_string.strip() printList = staticmethod(printList) def parsePcFile(filename): lines = open(filename).readlines() fvars = {} fvars["FlagpollFilename"] = filename lokals = {} lokals["fp_file_cwd"] = str(filename[:- ((len(os.path.basename(filename) ) + 1))]) lines.append("prefix: ${prefix}") append_next = False append_dict = {} append_key = "" for line in lines: line = line.strip() if not line: continue if append_next: tmp = append_dict[append_key] tmp = tmp[:-1] + " " + line append_dict[append_key] = tmp if tmp[-1:] == "\\": append_next = True else: append_next = False continue if line.startswith("#"): continue eq_pos = line.find('=') col_pos = line.find(':') if eq_pos < col_pos and eq_pos != -1 or col_pos == -1 and eq_pos != -1: # local variable name, val = line.split('=', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(lokals) except ValueError: flagDBG().out(flagDBG.WARN, "PkgInfo.parse", "%s has an invalid metadata file" % filename) lokals[name] = val if val[-1:] == "\\": append_next = True append_dict = lokals append_key = name continue if col_pos < eq_pos and col_pos != -1 or eq_pos == -1 and col_pos != -1: # exported variable name, val = line.split(':', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(lokals) except ValueError: flagDBG().out(flagDBG.ERROR, "PkgInfo.parse", "%s has an invalid metadata file" % filename) fvars[name] = val if val[-1:] == "\\": append_next = True append_dict = fvars append_key = name return fvars parsePcFile = staticmethod(parsePcFile) class flagDBG(object): # Logging class is really easy to use # Levels: # 0 - VERBOSE # 1 - INFO # 2 - WARN # 3 - ERROR VERBOSE = 0 INFO = 1 WARN = 2 ERROR = 3 __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if flagDBG.__initialized: return flagDBG.__initialized = True self.mLevel = self.WARN self.mLevelList = ["VERBOSE", "INFO", "WARN", "ERROR"] def setLevel(self, level): if level <= 3: self.mLevel = level def out(self, level, obj, message): if level == self.ERROR: if self.mLevel == self.VERBOSE: print self.mLevelList[level] + ":" + str(obj) + ": " + str(message) else: sys.stderr.write(self.mLevelList[level] + ": " + str(message) + "\n") errs = Utils.getPossibleErrors() if len(errs) > 0: sys.stderr.write("Possible culprits:\n") for pos_err in errs: sys.stderr.write( " " + str(pos_err) + "\n" ) sys.exit(1) if level >= self.mLevel: print self.mLevelList[level] + ":" + str(obj) + ": " + str(message) class DepResolutionSystem(object): """ You add PkgAgents with Filters into system and call resolve() you can check for succes by depsSatisfied() and get the list of packages that work back by calling getPackages() """ __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if DepResolutionSystem.__initialized: return DepResolutionSystem.__initialized = True self.mResolveAgents = [] self.mAgentDict = {} self.mFilters = [] self.mResolveAgentFilters = [] self.mInvalidPackageList = [] self.mSatisfied = False self.mAgentChangeList = [] # list of those responsible for adding Filters # to agents in higher in the chain than them # these are the first agents to ask that they pick # the next best package of them self.mAgentsVisitedList = [] # list of Agents that have been visited self.mResolvedPackageList = [] # list that is generated when deps are satified self.mCheckPrivateRequires = False self.mMadeDependList = False def getFilters(self): return self.mFilters def addFilter(self, filter): self.mFilters.append(filter) def addResolveAgentFilter(self, filter): self.mResolveAgentFilters.append(filter) def makeRequireFilter(self, requires): arch_list = [] arch_list.append("no_arch") arch_list.append("") if platform.system() == "Linux": if requires == "64": arch_list.append("x86_64") arch_list.append("x64") if requires == "32": arch_list.append("i386") arch_list.append("i486") arch_list.append("i586") arch_list.append("i686") if platform.system() == "Darwin": if requires == "64": arch_list.append("ppc64") if requires == "32": arch_list.append("ppc") if platform.system().startswith("IRIX"): arch_list.append(requires) new_filter = Filter("Arch", lambda x,v=arch_list: x in v) self.addFilter(new_filter) def createAgent(self, name): if self.checkAgentExists(name): return self.getAgent(name) else: agent = PkgAgent(name) flagDBG().out(flagDBG.INFO, "DepResSys.createAgent", "Adding %s" % name) self.addNewAgent(agent) return agent def createResolveAgent(self, name): if self.checkAgentExists(name): return self.getAgent(name) else: agent = PkgAgent(name) flagDBG().out(flagDBG.INFO, "DepResSys.createResolveAgent", "Adding %s" % name) self.addResolveAgent(agent) return agent def setPrivateRequires( self, req ): self.mCheckPrivateRequires = req def checkPrivateRequires(self): return self.mCheckPrivateRequires def checkAgentExists(self, name): return self.mAgentDict.has_key(name) def getAgent(self, name): if self.mAgentDict.has_key(name): return self.mAgentDict[name] else: flagDBG().out(flagDBG.ERROR, "DepResSys.getAgent", "Agent %s does not exist" % name) def addNewAgent(self, agent): if not self.checkAgentExists(agent): self.mAgentDict[agent.getName()] = agent def addResolveAgent(self, agent): if agent not in self.mResolveAgents: self.mResolveAgents.append(agent) for filt in self.mResolveAgentFilters: agent.addFilter(filt) def isSatisfied(self): return self.mSatisfied def updateResolvedPackages(self): pkg_list = [] agent_list = [] for agent in self.mResolveAgents: list_of_pkgs = agent.getCurrentPackageList(agent_list) pkg_list.extend(list_of_pkgs) self.mResolvedPackageList = pkg_list def getPackages(self): flagDBG().out(flagDBG.INFO, "DepResSys.getPackages", "Generating list of valid packages ") #str([pkg.getCurrentPackage.getName() for pkg in self.mResolvedPackageList])) # If this comes back empty then there isn't a valid set of packages to use self.updateResolvedPackages() return self.mResolvedPackageList def checkFiltersChanged(self): list_to_use = [] return True in [pkg.filtersChanged(list_to_use) for pkg in self.mResolveAgents] def resolveHelper(self): self.resolveAgentsChanged = True while self.resolveAgentsChanged: for agent in self.mResolveAgents: flagDBG().out(flagDBG.INFO, "DepResSys.resolveHelper", "Updating " + agent.getName()) agent.update(self.mAgentsVisitedList, self.mAgentChangeList) self.resolveAgentsChanged = self.checkFiltersChanged() # Ask mResolveAgents if they are done(they ask sub people) unless they are # really above you in the walk # If there were changes...run update on mResolveAgents again # at the end ask for pkglist..if it comes back empty then we don't # have a usable configuration for those packages def resolveDeps(self): self.resolveHelper() if not self.mMadeDependList: for agent in self.mResolveAgents: agent.makeDependList() self.mMadeDependList = True self.updateResolvedPackages() # Check if the first round through we found something # Otherwise we need to start removing packages that aren't viable # during the loop self.mSatisfied = (len(self.mResolvedPackageList) != 0) # remove top of packages that added Filters. # then move on to resolving again # remove more if neccesary agentChangeNumber = 0 while not self.mResolvedPackageList: if(self.mAgentChangeList[agentChangeNumber]): if self.mAgentChangeList[agentChangeNumber] in self.mInvalidPackageList: agentChangeNumber += 1 else: if(self.mAgentChangeList[agentChangeNumber].getViablePackages()): flagDBG().out(flagDBG.INFO, "DepResSys.resolveDeps", "Removing bad pkg from " + self.mAgentChangeList[agentChangeNumber].getName()) self.mInvalidPackageList.append(self.mAgentChangeList[agentChangeNumber].removeCurrentPackage()) else: flagDBG().out(flagDBG.INFO, "DepResSys.resolveDeps", "No combinations.. Resetting " + self.mAgentChangeList[agentChangeNumber].getName()) self.mAgentChangeList[agentChangeNumber].reset() agentChangeNumber += 1 self.resolveHelper() self.updateResolvedPackages() self.mSatisfied = (len(self.mResolvedPackageList) != 0) return class PkgAgent: """ Agent that keeps track of the versions for a package given some filters and the addition of Filters """ # Makes a PkgAgent that finds its current package with the version reqs def __init__(self, name): if DepResolutionSystem().checkAgentExists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "Package Agent %s already exists" % self.mName) self.mName = name flagDBG().out(flagDBG.INFO, "PkgAgent", "Creating:" + str(self.mName)) if not PkgDB().exists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "No info for package: %s" % self.mName) #XXX Doesn't keep filters added for a redo... DepResolutionSystem().addNewAgent(self) self.mFilterList = [] self.mFilterList.extend(DepResolutionSystem().getFilters()) self.mBasePackageList = PkgDB().getPkgInfos(name) self.mBasePackageList.sort(lambda lhs, rhs: cmp(rhs.getVariable('Version'), lhs.getVariable('Version'))) for filt in self.mFilterList: self.mBasePackageList = filt.filter(self.mBasePackageList) if len(self.mBasePackageList) == 0: flagDBG().out(flagDBG.ERROR, "PkgAgent", "No viable packages for: %s" % self.mName) self.mViablePackageList = copy.deepcopy(self.mBasePackageList) if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mFiltersChanged = True self.mCheckDepends = True self.mAgentDependList = [] def getName(self): return self.mName def setCheckDepends(self, tf): self.mCheckDepends = tf #Filter("Version", lambda x: x == "4.5") def makeDependList(self): if not self.mCheckDepends: self.mAgentDependList = [] return dep_list = [] if self.mCurrentPackage: req_string = self.mCurrentPackage.getVariable("Requires") if DepResolutionSystem().checkPrivateRequires(): req_string = req_string + " " + self.mCurrentPackage.getVariable("Requires.private") req_string = req_string.strip() if req_string == "": return req_string = req_string.replace(',', ' ') req_string = req_string.replace('(', ' ') req_string = req_string.replace(')', ' ') space_req_string_list = req_string.split(' ') req_string_list = [] for entry in space_req_string_list: if len(entry) > 0: req_string_list.append(entry) i = 0 flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList", self.mCurrentPackage.getName() + " requires: " + str(req_string_list)) while len(req_string_list) > i: if PkgDB().exists(req_string_list[i]): new_filter = [] new_agent = DepResolutionSystem().createAgent(req_string_list[i]) if len(req_string_list) > i+1: if req_string_list[i+1] == "=": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x == v) elif req_string_list[i+1] == "<=": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x <= v) elif req_string_list[i+1] == ">=": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x >= v) elif req_string_list[i+1] == ">": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x > v) elif req_string_list[i+1] == "<": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x < v) else: i += 1 else: i += 1 dep_list.append(new_agent) if new_filter: i+=3 new_agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "PkgAgent.makeDependList", "Package %s depends on %s but does not seem to be installed." % (self.mName, str(req_string_list[i]))) flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList", str(self.mName) + " : List is:" + str([pkg.getName() for pkg in dep_list])) self.mAgentDependList = dep_list def filtersChanged(self, packageList): tf_list = [self.mFiltersChanged] if self.mName not in packageList: packageList.append(self.mName) for pkg in self.mAgentDependList: tf_list.append(pkg.filtersChanged(packageList)) return True in tf_list def getCurrentPackageList(self, packageList): pkgs = [] if self.mName not in packageList: flagDBG().out(flagDBG.INFO, "PkgAgent.getCurrentPackageList", "Package: %s" % self.mName) pkgs.append(self.mCurrentPackage) packageList.append(self.mName) # Make depend list if we are supposed to self.updateFilters() self.makeDependList() for pkg in self.mAgentDependList: pkgs.extend(pkg.getCurrentPackageList(packageList)) return pkgs # current pkginfo for me def getCurrentPkgInfo(self): return self.mCurrentPackage # Someone else usually places these on me # I keep track of those separately def addFilter(self, filter): flagDBG().out(flagDBG.INFO, "PkgAgent.addFilter", "Filter %s" % self.mName + " on %s." % filter.getVarName()) self.mFiltersChanged = True self.mFilterList.append(filter) def removeCurrentPackage(self): flagDBG().out(flagDBG.INFO, "PkgAgent.removeCurrentPackage", "Removing current package of %s" % self.mName) if self.mViablePackageList: ret_val = self.mViablePackageList[0] in self.mBasePackageList del self.mViablePackageList[0] if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] return ret_val def update(self, agentVisitedList, agentChangeList): flagDBG().out(flagDBG.INFO, "PkgAgent.update", "%s" % self.mName) if self.mName in agentVisitedList: return agentVisitedList.append(self.mName) if self.mFiltersChanged: self.mFiltersChanged = False self.updateFilters() # TODO: checkFilters and add them # if a pkg is in visitedList then add yourself to agentChangeList for pkg in self.mAgentDependList: pkg.update(agentVisitedList, agentChangeList) return def updateFilters(self): for filt in self.mFilterList: self.mViablePackageList = filt.filter(self.mViablePackageList) flagDBG().out(flagDBG.INFO, "PkgAgent.updateFilters", "%s has " % self.mName + str(len(self.mViablePackageList)) + " left") if len(self.mViablePackageList) > 0: self.mCurrentPackage = self.mViablePackageList[0] else: for f in self.mFilterList: Utils.addPossibleError(str(self.mName) + " -> " + str(f.getVarName())) self.mCurrentPackage = [] def reset(self): flagDBG().out(flagDBG.INFO, "PkgAgent.reset", "Resetting package: %s" % self.mName) self.mViablePackageList = self.mBasePackageList if self.mViablePackageList: self.mCurrentPacakge = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mFilterList = DepResolutionSystem().getFilters() self.mAgentDependList = [] self.mFiltersChanged = True return class Filter: """ A single Filter that knows how to filter the list it recieves Will be inheireted....?..? """ def __init__(self, variableName, testCallable): self.mVarName = variableName self.mTestCallable = testCallable def getVarName(self): return self.mVarName def filter(self, pkg_info_list): ret_pkg_list = [] # Filter first for pkg in pkg_info_list: var = pkg.getVariable(self.mVarName) if self.mTestCallable(var): flagDBG().out(flagDBG.INFO, "Filter", "Passed: %s:" % pkg.getName() + " %s is " % self.mVarName + str(var)) ret_pkg_list.append(pkg) else: flagDBG().out(flagDBG.INFO, "Filter", "Failed: %s:" % pkg.getName() + " %s is " % self.mVarName + str(var)) # Now sort ret_pkg_list.sort(lambda lhs, rhs: cmp(rhs.getVariable(self.mVarName), lhs.getVariable(self.mVarName))) return ret_pkg_list #requires: qt == 4.5 #Filter("Version", lambda x: x <= "4.5") #Filter("Version", lambda x: x <= "4.5") class PkgDB(object): """ Holds all the neccesary information to evaluate itself when needed. Is in charge of holding a list of PkgInfo's that contain info about the package. """ __initialized = False def __init__(self): if self.__initialized: return self.__initialized = True self.mPkgInfos = {} # {pkg_name: List of package infos} self.populatePkgInfoDBPcFiles() self.populatePkgInfoDBFpcFiles() def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def printAllPackages(self): list_of_package_names = [] for pkg in self.mPkgInfos: list_of_package_names.append(pkg) for name in list_of_package_names: print name sys.exit(0) def getVariables(self, name, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariable", "Finding " + str(variable_list) + " in " + str(name)) ret_list = [] for var in variable_list: if self.mPkgInfos.has_key(name): ret_list.extend(self.mPkgInfos[name][0].getVariable(var)) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariable", "Package %s not found." % name) return ret_list def checkPackage(self, name): flagDBG().out(flagDBG.INFO, "PkgDB.checkPackage", "Finding " + str(name)) if self.mPkgInfos.has_key(name): return True else: flagDBG().out(flagDBG.ERROR, "PkgDB.CheckPackage", "Package %s not found." % name) return False def getVariablesAndDeps(self, pkg_list, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariablesAndDeps", "Finding " + str(variable_list) + " in " + str(pkg_list)) if DepResolutionSystem().checkPrivateRequires(): temp_var_list = [] for var in variable_list: temp_var_list.append(var.join(".private")) variable_list = variable_list + temp_var_list for name in pkg_list: if self.mPkgInfos.has_key(name): agent = DepResolutionSystem().createAgent(name) DepResolutionSystem().addResolveAgent(agent) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariablesAndDeps", "Package %s not found." % name) DepResolutionSystem().resolveDeps() pkgs = DepResolutionSystem().getPackages() var_list = [] for pkg in pkgs: if pkg: for var in variable_list: var_list.extend(tokenize(pkg.getVariable(var), pkg.getSplitChar())) return var_list def getPkgInfos(self, name): if self.mPkgInfos.has_key(name): return self.mPkgInfos[name] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getPkgInfos", "Package %s not found." % name) def exists(self, name): return self.mPkgInfos.has_key(name) def getInfo(self, name): if self.mPkgInfos.has_key(name): return [pkg.getInfo() for pkg in self.mPkgInfos[name]] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getInfo", "Package %s not found." % name) def buildPcFileDict(self): """ Builds up a dictionary of {name: list of files for name} """ pc_dict = {} for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.pc")) # List of .pc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these pc files: %s" % str(glob_list)) for g in glob_list: # Get key name and add file to value list in dictionary key = os.path.basename(g)[:-3] # Strip .pc off the filename...rstrip no worky pc_dict.setdefault(key, []).append(g) for f in Utils.getFileList(): if f.endswith(".pc"): key = os.path.basename(f)[:-3] # Strip .pc off the filename...rstrip no worky pc_dict.setdefault(key, []).append(f) return pc_dict # { "key", [ "list", "of", "corresponding", "pc", "files"] } def populatePkgInfoDBPcFiles(self): dict_to_pop_from = self.buildPcFileDict() for (pkg,files) in dict_to_pop_from.iteritems(): for f in files: self.mPkgInfos.setdefault(pkg,[]).append(PkgInfo(pkg, f, "pc")) def buildFpcFileList(self): """ Builds up a dictionary of {name: list of files for name} """ file_list = [] for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.fpc")) # List of .fpc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these fpc files: %s" % str(glob_list)) for g in glob_list: file_list.append(g) for f in Utils.getFileList(): if f.endswith(".fpc"): file_list.append(f) return file_list # [ "list", "of", "fpc", "files"] def populatePkgInfoDBFpcFiles(self): list_to_add = self.buildFpcFileList() for filename in list_to_add: var_dict = Utils.parsePcFile(filename) if not var_dict.has_key("Provides"): flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Provides" % str(filename)) continue if not var_dict.has_key("Arch"): flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Arch" % str(filename)) continue provides_string = var_dict["Provides"] provides_string = provides_string.replace(',', ' ') provides_string = provides_string.replace('(', ' ') provides_string = provides_string.replace(')', ' ') for key in provides_string.split(" "): if len(key) > 0: self.mPkgInfos.setdefault(key, []).append(PkgInfo(key, filename, "fpc", var_dict)) class PkgInfo: """ Holds the information for a package file on the system. These however are evaluated when the need arises. """ def __init__(self, name, file, type, varDict={}): self.mName = name self.mFile = file self.mIsEvaluated = False self.mType = type self.mVariableDict = varDict if self.mType == "fpc": self.mIsEvaluated = True def getVariable(self, variable): self.evaluate() return self.mVariableDict.get(variable,"") def getName(self): return self.mName def evaluate(self): if not self.mIsEvaluated: flagDBG().out(flagDBG.INFO, "PkgInfo.evaluate", "Evaluating %s" % self.mName) self.mVariableDict= Utils.parsePcFile(self.mFile) self.mIsEvaluated = True def getInfo(self): self.evaluate() return self.mVariableDict def getSplitChar(self): self.evaluate() split_char = self.mVariableDict.get("SplitCharacter", ' ') if split_char == "": split_char = ' ' return split_char class OptionsEvaluator: def __init__(self): if len(sys.argv) < 2: self.printHelp() # This is only the args....(first arg is stripped) def evaluateArgs(self, args): # Catch any args that need to be tended to immediately # Process args in the order that they were recieved. Some options are not # shown below because they are sub-options of an option below (--strip-dups) for option in args: if option.startswith("--verbose-debug"): flagDBG().setLevel(flagDBG.VERBOSE) if option.startswith("--debug"): flagDBG().setLevel(flagDBG.INFO) elif option.startswith("--from-file"): val_start = option.find('=') + 1 file = option[val_start:] Utils.EXTRA_FLAGPOLL_FILES = Utils.EXTRA_FLAGPOLL_FILES + ":" + file elif option.startswith("--help"): self.printHelp() sys.exit(0) elif option.startswith("--version"): print "%s.%s.%s" % Utils.getFlagpollVersion() sys.exit(0) elif option.startswith("--list-all"): PkgDB().printAllPackages() continue listedAgentNames = [] agent = None num_args = len(args) curr_arg = 0 output_options = [] # (option, name/"") important_options = [] # ones that need special attention while curr_arg < num_args: if args[curr_arg].startswith("--atleast-version"): val_start = args[curr_arg].find('=') + 1 atleast_version = args[curr_arg][val_start:] atleast_filter = Filter("Version", lambda x,v=atleast_version: x >= v) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(atleast_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --at-least-version") continue if args[curr_arg].startswith("--cflags-only-I"): output_options.append(("cflags-only-I", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--cflags-only-other"): output_options.append(("cflags-only-other", "")) curr_arg = curr_arg + 1 continue #This could be the catch all for the above ones to and then filter based on what is asked... #For clarity of course... if args[curr_arg].startswith("--cflags"): output_options.append(("cflags", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--extra-paths"): val_start = args[curr_arg].find('=') + 1 paths = args[curr_arg][val_start:] Utils.EXTRA_FLAGPOLL_SEARCH_PATHS = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS + ":" + paths curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--exact-version"): val_start = args[curr_arg].find('=') + 1 exact_version = args[curr_arg][val_start:] exact_filter = Filter("Version", lambda x,v=exact_version: x == v) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(exact_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --exact-version") continue if args[curr_arg].startswith("--exists"): important_options.append("exists") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--from-file"): val_start = args[curr_arg].find('=') + 1 file = args[curr_arg][val_start:] file_filter = Filter("FlagpollFilename", lambda x,f=file: x == f) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(file_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --from-file") continue if args[curr_arg].startswith("--info"): important_options.append("info") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--print-pkg-options"): important_options.append("print-pkg-options") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--keep-dups"): Utils.setKeepDups(True) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-l"): output_options.append(("libs-only-l", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-L"): output_options.append(("libs-only-L", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-other"): output_options.append(("libs-only-other", "")) curr_arg = curr_arg + 1 continue #This could be the catch all for the above ones to and then filter based on what is asked... if args[curr_arg].startswith("--libs"): output_options.append(("libs", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--require-all"): rlen = len("--require-all") req_string = args[curr_arg][rlen:] req_string = req_string.replace('-','_') curr_arg = curr_arg + 1 if req_string.find("<=") != -1: op_start = req_string.find("<=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x <= v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find(">=") != -1: op_start = req_string.find(">=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x >= v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find(">") != -1: op_start = req_string.find(">") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x > v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("<") != -1: op_start = req_string.find("<") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x < v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("=") != -1: op_start = req_string.find("=") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x == v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("=") == -1: new_filter = Filter(req_string, lambda x: len(x) > 0) DepResolutionSystem().addFilter(new_filter) continue continue if args[curr_arg].startswith("--require-"): rlen = len("--require-") req_string = args[curr_arg][rlen:] req_string = req_string.replace('-','_') curr_arg = curr_arg + 1 if agent is None: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --require") if req_string.find("<=") != -1: op_start = req_string.find("<=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x <= v) agent.addFilter(new_filter) continue if req_string.find(">=") != -1: op_start = req_string.find(">=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x >= v) agent.addFilter(new_filter) continue if req_string.find(">") != -1: op_start = req_string.find(">") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x > v) agent.addFilter(new_filter) continue if req_string.find("<") != -1: op_start = req_string.find("<") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x < v) agent.addFilter(new_filter) continue if req_string.find("=") != -1: op_start = req_string.find("=") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x == v) agent.addFilter(new_filter) continue if req_string.find("=") == -1: new_filter = Filter(req_string, lambda x: len(x) > 0) agent.addFilter(new_filter) continue continue if args[curr_arg].startswith("--no-deps"): if agent is not None: agent.setCheckDepends(False) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --no-deps") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--require="): val_start = args[curr_arg].find('=') + 1 req_var = args[curr_arg][val_start:] curr_arg = curr_arg + 1 DepResolutionSystem().makeRequireFilter(req_var) continue if args[curr_arg].startswith("--modversion"): if agent is not None: output_options.append(("Version", agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --modversion") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--max-release"): val_start = args[curr_arg].find('=') + 1 max_release = args[curr_arg][val_start:] max_filter = Filter("Version", lambda x,v=max_release: x.startswith(v)) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(max_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --max-release") continue if args[curr_arg].startswith("--static"): DepResolutionSystem().setPrivateRequires(True) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--variable"): val_start = args[curr_arg].find('=') + 1 fetch_var = args[curr_arg][val_start:] if agent is not None: output_options.append((fetch_var, agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --variable") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--get-all"): rlen = len("--get-all-") get_string = args[curr_arg][rlen:] get_string = get_string.replace('-','_') output_options.append((get_string, "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--get"): rlen = len("--get-") get_string = args[curr_arg][rlen:] get_string = get_string.replace('-','_') if agent is not None: output_options.append((get_string, agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --get") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--concat"): important_options.append("concat") curr_arg = curr_arg + 1 continue if not args[curr_arg].startswith("--"): name = args[curr_arg] curr_arg = curr_arg + 1 if PkgDB().checkPackage(name): agent = DepResolutionSystem().createResolveAgent(name) listedAgentNames.append(name) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Package %s" % name) sys.exit(1) continue if args[curr_arg] != "--debug" and args[curr_arg] != "--verbose-debug": flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Option: %s" % args[curr_arg]) curr_arg = curr_arg + 1 if len(listedAgentNames) == 0: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Must specify at least one package") DepResolutionSystem().resolveDeps() pkgs = DepResolutionSystem().getPackages() for p in pkgs: if not p: for option in important_options: if option == "exists": print "no" sys.exit(1) flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found") if len(pkgs) == 0: for option in important_options: if option == "exists": print "no" sys.exit(1) flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found") sys.exit(1) concat = False for option in important_options: if option == "exists": print "yes" return sys.exit(0) # already checked for none above if option == "concat": concat = True if option == "info": pkg_info_list = [] for pkg in pkgs: if pkg.getName() in listedAgentNames: print pkg.getName() pkg_info = pkg.getInfo() for key in pkg_info.keys(): print " %s : %s" % (key, pkg_info[key]) if option == "print-pkg-options": print "" print "All options below would start with (--get-/--get-all-/--require-/--require-all-)" print "NOTE: this list does not include the standard variables that are exported." print "" for pkg in pkgs: if pkg.getName() not in listedAgentNames: continue print "Package: " + pkg.getName() for key in pkg.getInfo().keys(): if key not in [ "Name", "Description", "URL", "Version", "Requires", "Requires.private", "Conflicts", "Libs", "Libs.private", "Cflags", "Provides", "Arch", "FlagpollFilename", "prefix" ]: print " " + key.replace('_','-') #print output_options #output_options = [] #output_single = [] #Process options here.............. concat_list = [] if concat: print_option = lambda x: concat_list.extend(x) else: print_option = lambda x: Utils.printList(x) for option in output_options: if option[0] == "cflags": print_option(Utils.stripDupIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "cflags-only-I": print_option(Utils.cflagsOnlyDirIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "cflags-only-other": print_option(Utils.cflagsOnlyOtherIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "libs-only-l": print_option(Utils.libsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs-only-L": print_option(Utils.libDirsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs-only-other": print_option(Utils.libsOnlyOtherLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs": print_option(Utils.stripDupLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) else: print_option(Utils.stripDupInList(self.getVarFromPkgs(option[0], pkgs, option[1]))) if concat: Utils.printList(Utils.stripDupInList(concat_list)) def getVarFromPkgs(self, var, pkgs, pkg_name=""): var_list = [] ext_vars = [] if var == "Libs": if DepResolutionSystem().checkPrivateRequires: ext_vars.append("Libs.private") if pkg_name == "": for pkg in pkgs: if pkg: var_list.extend(tokenize(pkg.getVariable(var), pkg.getSplitChar())) for extra_var in ext_vars: var_list.extend(tokenize(pkg.getVariable(extra_var), pkg.getSplitChar())) else: for pkg in pkgs: if pkg: if pkg.getName() == pkg_name: var_list.extend(tokenize(pkg.getVariable(var), pkg.getSplitChar())) for extra_var in ext_vars: var_list.extend(tokenize(pkg.getVariable(extra_var), pkg.getSplitChar())) return var_list def printHelp(self): print "usage: flagpoll pkg options [pkg options] [generic options]" print " " print "generic options:" print " --help show this help message and exit" print " --version output version of flagpoll" print " --list-all list all known packages" print " --debug show debug information" print " --verbose-debug show verbose debug information" print " --extra-paths=EXTRA_PATHS" print " extra paths for flagpoll to search for meta-data files" print " --concat concatenate all output and output as one line" print " --keep-dups do not strip out all duplicate info from options" print " --info show information for packages" print " --print-pkg-options show pkg specific options" print " " print "options:" print " --modversion output version for package" print " --require=REQUIRE adds additional requirements for packages ex. 32/64" print " --libs output all linker flags" print " --static output linker flags for static linking" print " --libs-only-l output -l flags" print " --libs-only-other output other libs (e.g. -pthread)" print " --libs-only-L output -L flags" print " --cflags output all pre-processor and compiler flags" print " --cflags-only-I output -I flags" print " --cflags-only-other output cflags not covered by the cflags-only-I option" print " --exists return 0 if the module(s) exist" print " --from-file=FILE use the specified FILE for the package" #print " --print-provides print which packages the package provides" #print " --print-requires print which packages the package requires" print " --no-deps do not lookup dependencies for the package" print " --atleast-version=ATLEAST_VERSION" print " return 0 if the module is at least version" print " ATLEAST_VERSION" print " --exact-version=EXACT_VERSION" print " return 0 if the module is exactly version" print " EXACT_VERSION" print " --max-release=MAX_RELEASE" print " return 0 if the module has a release that has a" print " version of MAX_RELEASE and will return the max" print " --variable=VARIABLE get the value of a variable" print " " print "dynamic options(replace VAR with a variable you want to get/filter on)" print " NOTE: replace underscores with dashes in VAR" print " NOTE: quotes are needed around <,>,= combinations" print " --get-VAR get VAR from package" print " --get-all-VAR get VAR from package and its deps" print " --require-VAR[<,>,=VAL]" print " require that a var is defined for a package" print " or optionally use equality operators against VAL" print " --require-all-VAR[<,>,=VAL]" print " require that a var is defined for all packages" print " or optionally use equality operators against VAL" print "" print "extending search path" print " FLAGPOLL_PATH environment variable that can be set to" print " extend the search path for .fpc/.pc files" print "" print "" print "Send bug reports and/or feedback to flagpoll-users@vrsource.org" sys.exit(0) def main(): # GO! # Initialize singletons and the start evaluating my_dbg = flagDBG() my_dep_system = DepResolutionSystem() opt_evaluator = OptionsEvaluator() opt_evaluator.evaluateArgs(sys.argv[1:]) sys.exit(0) if __name__ == "__main__": main()
Python
#!/usr/bin/env python # ----------------------------------------------------------------- # # Flag Poll: A tool to extract flags from installed applications # for compiling, settting variables, etc. # # Original Authors: # Daniel E. Shipton <dshipton@gmail.com> # # Flag Poll is Copyright (C) 2006 by Daniel E. Shipton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to: # Free SoftwareFoundation, Inc. # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # # ----------------------------------------------------------------- """Makes a flagpole .fpc file from user input. v0.9 coded by Jeff Groves""" import os import sys import getopt ##String prompts for the input varPrompt = """Convience variables (one 'var_name= var_definition' per line,""" + \ """ empty line when done)""" namePrompt = "Formal Name" descriptionPrompt = "Description" urlPrompt = "URL" providesPrompt = "One or more names to look package up by: (Provides)" versionPrompt = "Version (x.y.z)" architecturePrompt = "Architecture" requirePrompt = "Requires" libPrompt = "Linker Flags (-lfoo -L/usr/lib)" staticLibPrompt = "Static Linking Flags/Libs (extra private libs)" compileFlagsPrompt = "Compile/Include Flags (-I/usr -fpge -O2)" fileNamePrompt = "FPC File's Name" def usage(): """Prints a list of acceptable arguments for fpcmaker.py.""" print """ Fpcmaker.py Options: -n, --name= : Sets %s -d, --description= : Sets %s -u, --url= : Sets %s -p, --provides= : Sets %s -v, --version= : Sets %s -a, --architecture= : Sets %s -r, --requires= : Sets %s -l, --libs= : Sets %s -c, --cflags= : Sets %s -s, --static= : Sets %s -f, --file= : Sets %s """ %(namePrompt, descriptionPrompt, urlPrompt, providesPrompt, versionPrompt, architecturePrompt, requirePrompt, libPrompt, compileFlagsPrompt, staticLibPrompt, fileNamePrompt) return def checkFileName(fileName): """Checks if the fpc file name's blank, contains slashes, or exists.""" nameCleared = False writeFile = True confirms = ['y', 'Y', 'yes', 'Yes'] ##Loops until the name clears or writing the file's aborted. while(not nameCleared and writeFile): ##If it's blank, give the option of aborting the program. if fileName == "": choice = raw_input("Do you want to abort writing the" + " .fpc file? (Y/N): ") if choice not in confirms: fileName = raw_input("Please enter a different name for the" + " .fpc file: ") else: writeFile = False ##If it contains slashes, ask for another name. elif '/' in fileName or '\\' in fileName: print "I can't write to %s because it contains slashes."%(fileName) fileName = raw_input("Please enter a different name for the" + " .fpc file: ") ##If it already exists, ask if they want to overwrite. ##If not, ask for another name. elif os.path.exists(fileName): choice = raw_input("The file %s already exists." %(fileName) + " Do you want to overwrite it? (Y/N): ") if choice not in confirms: fileName = raw_input("Please enter a different name for the" + " .fpc file: ") else: nameCleared = True else: nameCleared = True return [fileName, writeFile] ##Booleans for whether that argument was sent in the command line varSet = False providesSet = False nameSet = False descriptionSet = False urlSet = False architectureSet = False versionSet = False requiresSet = False libsSet = False compileFlagsSet = False staticLibSet = False fileNameSet = False ##Get the options & arguments sent. arguments = sys.argv[1:] try: opts, args = getopt.getopt(arguments, "p:n:u:d:a:r:v:l:c:s:f:", ["provides=", "name=", "url=", "description=", "architecture=", "requires=", "version=", "libs=", "cflags=", "static=", "file="]) ##Send them usage info if they enter a wrong argument except getopt.GetoptError: usage() sys.exit(2) for opt, arg in opts: if opt in ('-p', '--provides'): providesSet = True provides = arg elif opt in ('-n', '--name'): nameSet = True name = arg elif opt in ('-v', '--version'): versionSet = True version = arg elif opt in ('-u', '--url'): urlSet = True url = arg elif opt in ('-d', '--description'): descriptionSet = True description = arg elif opt in ('-a', '--architecture'): architectureSet = True architecture = arg elif opt in ('-r', '--requires'): requiresSet = True requires = arg elif opt in ('-l', '--libs'): libsSet = True libs = arg elif opt in ('-c', '--cflags'): compileFlagsSet = True compileFlags = arg elif opt in ('-s', '--static'): staticLibSet = True staticLib = arg elif opt in ('-f', '--file'): fileNameSet = True fileName = arg ##Grab any input not passed in the arguments from the user. if not varSet: varLine = None variables = "" print "%s:" %(varPrompt) while(varLine != ""): varLine = raw_input("") variables = variables + "%s\n" %(varLine) if not nameSet: name = raw_input("%s: " %(namePrompt)) if not descriptionSet: description = raw_input("%s: " %(descriptionPrompt)) if not urlSet: url = raw_input("%s: " %(urlPrompt)) if not versionSet: version = raw_input("%s: " %(versionPrompt)) if not providesSet: provides = raw_input("%s: " %(providesPrompt)) if not requiresSet: requires = raw_input("%s: " %(requirePrompt)) if not architectureSet: architecture = raw_input("%s: " %(architecturePrompt)) if not libsSet: libs = raw_input("%s: " %(libPrompt)) if not staticLibSet: staticLib = raw_input("%s: " %(staticLibPrompt)) if not compileFlagsSet: compileFlags = raw_input("%s: " %(compileFlagsPrompt)) if not fileNameSet: fileName = raw_input("%s: " %(fileNamePrompt)) ##Check the file's name. fileName, writeFile = checkFileName(fileName) ##If they chose not to overwrite, write the file. if writeFile: fpc = open(fileName, 'w') fpc.write("%s" %(variables)) fpc.write("Name: %s\n" %(name)) fpc.write("Description: %s\n" %(description)) fpc.write("URL: %s\n" %(url)) fpc.write("Version: %s\n" %(version)) fpc.write("Provides: %s\n" %(provides)) fpc.write("Requires: %s\n" %(requires)) fpc.write("Arch: %s\n" %(architecture)) fpc.write("Libs: %s\n" %(libs)) fpc.write("Libs.private: %s\n" %(staticLib)) fpc.write("Cflags: %s\n" %(compileFlags)) fpc.close() ##TESTER: Print the file out. fpc = open(fileName, 'r') ##TESTER print fpc.read() ##TESTER fpc.close ##TESTER
Python
#!/usr/bin/env python # ----------------------------------------------------------------- # # Flag Poll: A tool to extract flags from installed applications # for compiling, settting variables, etc. # # Original Authors: # Daniel E. Shipton <dshipton@gmail.com> # # Flag Poll is Copyright (C) 2006 by Daniel E. Shipton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to: # Free SoftwareFoundation, Inc. # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # # ----------------------------------------------------------------- from optparse import OptionParser import sys, os, glob, os.path, copy, platform pj = os.path.join #################################################################### # SNAGGED FROM PYTHON 2.4 for versions under 2.4 #################################################################### import re as _re class _multimap: """Helper class for combining multiple mappings. Used by .{safe_,}substitute() to combine the mapping and keyword arguments. """ def __init__(self, primary, secondary): self._primary = primary self._secondary = secondary def __getitem__(self, key): try: return self._primary[key] except KeyError: return self._secondary[key] class _TemplateMetaclass(type): pattern = r""" %(delim)s(?: (?P<escaped>%(delim)s) | # Escape sequence of two delimiters (?P<named>%(id)s) | # delimiter and a Python identifier {(?P<braced>%(id)s)} | # delimiter and a braced identifier (?P<invalid>) # Other ill-formed delimiter exprs ) """ def __init__(cls, name, bases, dct): super(_TemplateMetaclass, cls).__init__(name, bases, dct) if 'pattern' in dct: pattern = cls.pattern else: pattern = _TemplateMetaclass.pattern % { 'delim' : _re.escape(cls.delimiter), 'id' : cls.idpattern, } cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE) class Template: """A string class for supporting $-substitutions.""" __metaclass__ = _TemplateMetaclass delimiter = '$' idpattern = r'[_a-z][_a-z0-9]*' def __init__(self, template): self.template = template # Search for $$, $identifier, ${identifier}, and any bare $'s def _invalid(self, mo): i = mo.start('invalid') lines = self.template[:i].splitlines(True) if not lines: colno = 1 lineno = 1 else: colno = i - len(''.join(lines[:-1])) lineno = len(lines) raise ValueError('Invalid placeholder in string: line %d, col %d' % (lineno, colno)) def substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): # Check the most common path first. named = mo.group('named') or mo.group('braced') if named is not None: val = mapping[named] # We use this idiom instead of str() because the latter will # fail if val is a Unicode containing non-ASCII characters. return '%s' % val if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: self._invalid(mo) raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) def safe_substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): named = mo.group('named') if named is not None: try: # We use this idiom instead of str() because the latter # will fail if val is a Unicode containing non-ASCII return '%s' % mapping[named] except KeyError: return self.delimiter + named braced = mo.group('braced') if braced is not None: try: return '%s' % mapping[braced] except KeyError: return self.delimiter + '{' + braced + '}' if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: return self.delimiter raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) #################################################################### # End Snagging #################################################################### class Utils: # Holds collection of small utility functions def getFlagpollVersion(): FLAGPOLL_MAJOR_VERSION = 0 FLAGPOLL_MINOR_VERSION = 1 FLAGPOLL_PATCH_VERSION = 5 return ( FLAGPOLL_MAJOR_VERSION, FLAGPOLL_MINOR_VERSION, FLAGPOLL_PATCH_VERSION ) getFlagpollVersion = staticmethod(getFlagpollVersion) def getPathList(): #TODO: expand LD_LIBRARY_PATH to 64/32/etc??? pkg_cfg_dir = [] flg_cfg_dir = [] ld_path = [] if os.environ.has_key("PKG_CONFIG_DIR"): pkg_cfg_dir = os.environ["PKG_CONFIG_DIR"].split(os.pathsep) if os.environ.has_key("FLG_CONFIG_DIR"): flg_cfg_dir = os.environ["FLG_CONFIG_DIR"].split(os.pathsep) if os.environ.has_key("LD_LIBRARY_PATH"): ld_path = os.environ["LD_LIBRARY_PATH"].split(os.pathsep) ld_path = [pj(p,'pkgconfig') for p in ld_path if os.path.exists(p)] path_list = ["/usr/lib64/pkgconfig", "/usr/lib/pkgconfig", "/usr/share/pkgconfig"] path_list = [p for p in path_list if os.path.exists(p)] path_list.extend(pkg_cfg_dir) path_list.extend(flg_cfg_dir) path_list.extend(ld_path) flagDBG().out(flagDBG.INFO, "Utils.getPathList", "Using path list: " + str(path_list)) return path_list getPathList = staticmethod(getPathList) def stripDupInList(gen_list): new_list = [] for item in gen_list: if item not in new_list: if len(item) > 0: new_list.append(item) return new_list stripDupInList = staticmethod(stripDupInList) def stripDupLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] dir_list = [] for flg in flag_list: flg = flg.strip() if flg not in lib_list and flg not in dir_list: if len(flg) > 0: if flg.startswith("-L") or flg.startswith("-R"): dir_list.append(flg) else: lib_list.append(flg) new_list = dir_list + lib_list return new_list stripDupLinkerFlags = staticmethod(stripDupLinkerFlags) def stripDupIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] extra_list = [] for flg in flag_list: flg = flg.strip() if flg not in inc_list and flg not in extra_list: if len(flg) > 0: if flg.startswith("-I"): inc_list.append(flg) else: extra_list.append(flg) extra_list.sort() new_list = inc_list + extra_list return new_list stripDupIncludeFlags = staticmethod(stripDupIncludeFlags) def cflagsOnlyDirIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] for flg in flag_list: flg = flg.strip() if flg not in inc_list: if len(flg) > 0: if flg.startswith("-I"): inc_list.append(flg) return inc_list cflagsOnlyDirIncludeFlags = staticmethod(cflagsOnlyDirIncludeFlags) def cflagsOnlyOtherIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though extra_list = [] for flg in flag_list: flg = flg.strip() if flg not in extra_list: if len(flg) > 0: if not flg.startswith("-I"): extra_list.append(flg) return extra_list cflagsOnlyOtherIncludeFlags = staticmethod(cflagsOnlyOtherIncludeFlags) def libsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] for flg in flag_list: flg = flg.strip() if flg not in lib_list: if len(flg) > 0: if flg.startswith("-l"): lib_list.append(flg) return lib_list libsOnlyLinkerFlags = staticmethod(libsOnlyLinkerFlags) def libsOnlyOtherLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though other_list = [] for flg in flag_list: flg = flg.strip() if flg not in other_list: if len(flg) > 0: if not flg.startswith("-l") and not flg.startswith("-L") and not flag.startswith("-R"): other_list.append(flg) return other_list libsOnlyOtherLinkerFlags = staticmethod(libsOnlyOtherLinkerFlags) def libDirsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though dir_list = [] for flg in flag_list: flg = flg.strip() if flg not in dir_list: if len(flg) > 0: if flg.startswith("-L") or flg.startswith("-R"): dir_list.append(flg) return dir_list libDirsOnlyLinkerFlags = staticmethod(libDirsOnlyLinkerFlags) def printList(gen_list): list_string = "" for item in gen_list: if len(item) > 0: list_string+=str(item) list_string+=" " print list_string printList = staticmethod(printList) def parsePcFile(filename): lines = open(filename).readlines() vars = {} locals = {} for line in lines: line = line.strip() if not line: continue elif ':' in line: # exported variable name, val = line.split(':', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(locals) except ValueError: flagDBG().out(flagDBG.ERROR, "PkgInfo.parse", "%s has an invalid .pc file" % self.mName) vars[name] = val elif '=' in line: # local variable name, val = line.split('=', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(locals) except ValueError: flagDBG().out(flagDBG.ERROR, "PkgInfo.parse", "%s has an invalid .pc file" % self.mName) locals[name] = val return vars parsePcFile = staticmethod(parsePcFile) class flagDBG(object): # Logging class is really easy to use # Levels: # 0 - VERBOSE # 1 - INFO # 2 - WARN # 3 - ERROR VERBOSE=0 INFO=1 WARN=2 ERROR=3 __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if flagDBG.__initialized: return flagDBG.__initialized = True self.mLevel = self.WARN self.mLevelList = ["VERBOSE","INFO","WARN","ERROR"] def setLevel(self, level): if level <= 3: self.mLevel = level def out(self, level, obj, message): if level >= self.mLevel: print self.mLevelList[level] + ":" + str(obj) + ": " + str(message) if level == self.ERROR: sys.exit(1) class DepResolutionSystem(object): """ You add PkgAgents with Filters into system and call resolve() you can check for succes by depsSatisfied() and get the list of packages that work back by calling getPackages() """ __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if DepResolutionSystem.__initialized: return DepResolutionSystem.__initialized = True self.mResolveAgents = [] self.mAgentDict = {} self.mFilters = [] self.mResolveAgentFilters = [] self.mInvalidPackageList = [] self.mSatisfied = False self.mAgentChangeList = [] # list of those responsible for adding Filters # to agents in higher in the chain than them # these are the first agents to ask that they pick # the next best package of them self.mAgentsVisitedList = [] # list of Agents that have been visited self.mResolvedPackageList = [] # list that is generated when deps are satified self.mCheckPrivateRequires = False def getFilters(self): return self.mFilters def addFilter(self, filter): self.mFilters.append(filter) def addResolveAgentFilter(self, filter): self.mResolveAgentFilters.append(filter) def makeRequireFilter(self, requires): arch_list = [] arch_list.append("no_arch") arch_list.append("") if platform.system() == "Linux": if requires == "64": arch_list.append("x86_64") if requires == "32": arch_list.append("i386") arch_list.append("i586") arch_list.append("i686") if platform.system() == "Darwin": if requires == "64": arch_list.append("ppc64") if requires == "32": arch_list.append("ppc") new_filter = Filter("Arch", lambda x: x in arch_list) self.addFilter(new_filter) def createAgent(self, name): if self.checkAgentExists(name): return self.getAgent(name) else: agent = PkgAgent(name) flagDBG().out(flagDBG.INFO, "DepResSys.createAgent", "Adding %s" % name) self.addNewAgent(agent) return agent def setPrivateRequires( self, req ): self.mCheckPrivateRequires = req def checkPrivateRequires(self): return self.mCheckPrivateRequires def checkAgentExists(self, name): return self.mAgentDict.has_key(name) def getAgent(self, name): if self.mAgentDict.has_key(name): return self.mAgentDict[name] else: flagDBG().out(flagDBG.ERROR, "DepResSys.getAgent", "Agent %s does not exist" % name) def addNewAgent(self, agent): self.mAgentDict[agent.getName()] = agent def addResolveAgent(self, agent): if agent not in self.mResolveAgents: self.mResolveAgents.append(agent) for filt in self.mResolveAgentFilters: agent.addFilter(filt) def isSatisfied(self): return self.mSatisfied def updateResolvedPackages(self): pkg_list = [] agent_list = [] for agent in self.mResolveAgents: list = agent.getCurrentPackageList(agent_list) pkg_list.extend(list) self.mResolvedPackageList = pkg_list def getPackages(self): flagDBG().out(flagDBG.VERBOSE, "DepResSys.getPackages", "Generating list of valid packages ") #str([pkg.getCurrentPa.getName() for pkg in self.mResolvedPackageList])) # If this comes back empty then there isn't a valid set of packages to use self.updateResolvedPackages() return self.mResolvedPackageList def checkFiltersChanged(self): list_to_use = [] return True in [pkg.filtersChanged(list_to_use) for pkg in self.mResolveAgents] def resolveHelper(self): self.resolveAgentsChanged = True while self.resolveAgentsChanged: for agent in self.mResolveAgents: flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveHelper", "Updating " + agent.getName()) agent.update(self.mAgentsVisitedList, self.mAgentChangeList) self.resolveAgentsChanged = self.checkFiltersChanged() # Ask mResolveAgents if they are done(they ask sub people) unless they are # really above you in the walk # If there were changes...run update on mResolveAgents again # at the end ask for pkglist..if it comes back empty then we don't # have a usable configuration for those packages def resolveDeps(self): self.resolveHelper() self.updateResolvedPackages() # Check if the first round through we found something # Otherwise we need to start removing packages that aren't viable # during the loop self.mSatisfied = (len(self.mResolvedPackageList) != 0) # remove top of packages that added Filters. # then move on to resolving again # remove more if neccesary agentChangeNumber = 0 while not self.mResolvedPackageList: if(self.mAgentChangeList[agentChangeNumber]): if self.mAgentChangeList[agentChangeNumber] in self.mInvalidPackageList: agentChangeNumber+=1 else: if(self.mAgentChangeList[agentChangeNumber].getViablePackages()): flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveDeps", "Removing bad pkg from " + self.mAgentChangeList[agentChangeNumber].getName()) self.mInvalidPackageList.append(self.mAgentChangeList[agentChangeNumber].removeCurrentPackage()) else: flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveDeps", "No combinations.. Resetting " + self.mAgentChangeList[agentChangeNumber].getName()) self.mAgentChangeList[agentChangeNumber].reset() agentChangeNumber+=1 self.resolveHelper() self.updateResolvedPackages() self.mSatisfied = (len(self.mResolvedPackageList) != 0) return class PkgAgent: """ Agent that keeps track of the versions for a package given some filters and the addition of Filters """ # Makes a PkgAgent that finds its current package with the version reqs def __init__(self, name): if DepResolutionSystem().checkAgentExists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "Package Agent %s already exists" % self.mName) self.mName = name flagDBG().out(flagDBG.VERBOSE, "PkgAgent", "Creating:" + str(self.mName)) if not PkgDB().exists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "No info for package: %s" % self.mName) DepResolutionSystem().addNewAgent(self) self.mFilterList = DepResolutionSystem().getFilters() self.mBasePackageList = PkgDB().getPkgInfos(name) for filt in self.mFilterList: self.mBasePackageList = filt.filter(self.mBasePackageList) if len(self.mBasePackageList) == 0: flagDBG().out(flagDBG.ERROR, "PkgAgent", "No viable packages for: %s" % self.mName) self.mViablePackageList = copy.deepcopy(self.mBasePackageList) if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mAgentDependList = [] # Agents that it depends on/needs to update self.makeDependList() self.mFiltersChanged = True def getName(self): return self.mName #Filter("Version", lambda x: x == "4.5") def makeDependList(self): dep_list = [] if self.mCurrentPackage: req_string = self.mCurrentPackage.getVariable("Requires") if DepResolutionSystem().checkPrivateRequires(): req_string = req_string + " " + self.mCurrentPackage.getVariable("Requires.private") req_string = req_string.strip() if req_string == "": return req_string = req_string.replace(',', ' ') req_string = req_string.replace('(', ' ') req_string = req_string.replace(')', ' ') space_req_string_list = req_string.split(' ') req_string_list = [] for entry in space_req_string_list: if len(entry) > 0: req_string_list.append(entry) i = 0 flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList", self.mCurrentPackage.getName() + " requires: " + str(req_string_list)) while len(req_string_list) > i: if PkgDB().exists(req_string_list[i]): new_filter = [] new_agent = DepResolutionSystem().createAgent(req_string_list[i]) if len(req_string_list) > i+1: if req_string_list[i+1] == "=": ver_to_filt = req_string_list[i+2] new_filter = Filter("Version", lambda x: x == ver_to_filt) elif req_string_list[i+1] == "<=": ver_to_filt = req_string_list[i+2] new_filter = Filter("Version", lambda x: x <= ver_to_filt) elif req_string_list[i+1] == ">=": ver_to_filt = req_string_list[i+2] new_filter = Filter("Version", lambda x: x >= ver_to_filt) else: i+=1 else: i+=1 dep_list.append(new_agent) if new_filter: i+=3 new_agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "PkgAgent.makeDependList", "Package %s depends on %s but is not seem to be installed." % (self.mName, str(req_string_list[i]))) flagDBG().out(flagDBG.VERBOSE, "PkgAgent.makeDependList", "List is:" + str([pkg.getName() for pkg in dep_list])) self.mAgentDependList = dep_list def filtersChanged(self,packageList): tf_list = [self.mFiltersChanged] if self.mName not in packageList: packageList.append(self.mName) for pkg in self.mAgentDependList: tf_list.append(pkg.filtersChanged(packageList)) return True in tf_list def getCurrentPackageList(self, packageList): pkgs = [] if self.mName not in packageList: flagDBG().out(flagDBG.VERBOSE, "PkgAgent.getCurrentPackageList", "Package: %s" % self.mName) pkgs.append(self.mCurrentPackage) packageList.append(self.mName) for pkg in self.mAgentDependList: pkgs.extend(pkg.getCurrentPackageList(packageList)) return pkgs # current pkginfo for me def getCurrentPkgInfo(self): return self.mCurrentPackage # Someone else usually places these on me # I keep track of those separately def addFilter(self, filter): flagDBG().out(flagDBG.VERBOSE, "PkgAgent.addFilter", "Adding a Filter to %s" % self.mName) self.mFiltersChanged = True self.mFilterList.append(filter) def removeCurrentPackage(self): flagDBG().out(flagDBG.VERBOSE, "PkgAgent.removeCurrentPackage", "Removing current package of %s" % self.mName) if self.mViablePackageList: ret_val = self.mViablePackageList[0] in self.mBasePackageList del mViablePackageList[0] if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] return ret_val def update(self, agentVisitedList, agentChangeList): if self.mName in agentVisitedList: return agentVisitedList.append(self.mName) if self.mFiltersChanged: self.mFiltersChanged = False self.updateFilters() # TODO: checkFilters and add them # if a pkg is in visitedList then add yourself to agentChangeList for pkg in self.mAgentDependList: pkg.update(agentVisitedList, agentChangeList) return def updateFilters(self): for filt in self.mFilterList: self.mViablePackageList = filt.filter(self.mViablePackageList) if len(self.mViablePackageList) > 0: self.mCurrentPackage = self.mViablePackageList[0] else: self.mCurrentPackage = [] def reset(self): flagDBG().out(flagDBG.VERBOSE, "PkgAgent.reset", "Resetting package: %s" % self.mName) self.mViablePackageList = self.mBasePackageList if self.mViablePackageList: self.mCurrentPacakge = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mFilterList = self.mBaseFilters self.mAgentDependList = [] self.mFiltersChanged = True return class Filter: """ A single Filter that knows how to filter the list it recieves Will be inheireted....?..? """ def __init__(self, variableName, testCallable): self.mVarName = variableName self.mTestCallable = testCallable def filter(self, pkg_info_list): ret_pkg_list = [] # Filter first for pkg in pkg_info_list: var = pkg.getVariable(self.mVarName) if self.mTestCallable(var): ret_pkg_list.append(pkg) # Now sort ret_pkg_list.sort(lambda lhs,rhs: cmp(lhs.getVariable(self.mVarName), rhs.getVariable(self.mVarName))) return ret_pkg_list #requires: qt == 4.5 #Filter("Version", lambda x: x <= "4.5") #Filter("Version", lambda x: x <= "4.5") class PkgDB(object): """ Holds all the neccesary information to evaluate itself when needed. Is in charge of holding a list of PkgInfo's that contain info about the package. """ __initialized = False def __init__(self): if self.__initialized: return self.__initialized = True self.mPkgInfos = {} # {pkg_name: List of package infos} self.populatePkgInfoDBPcFiles() self.populatePkgInfoDBFpcFiles() def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def getVariables(self, name, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariable", "Finding " + str(variable_list) + " in " + str(name)) ret_list = [] for var in variable_list: if self.mPkgInfos.has_key(name): ret_list.extend(self.mPkgInfos[name][0].getVariable(var)) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariable", "Package %s not found." % name) return ret_list def getVariablesAndDeps(self, pkg_list, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariablesAndDeps", "Finding " + str(variable_list) + " in " + str(pkg_list)) if DepResolutionSystem().checkPrivateRequires(): temp_var_list = [] for var in variable_list: temp_var_list.append(var.join(".private")) variable_list = variable_list + temp_var_list for name in pkg_list: if self.mPkgInfos.has_key(name): agent = DepResolutionSystem().createAgent(name) DepResolutionSystem().addResolveAgent(agent) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariablesAndDeps", "Package %s not found." % name) DepResolutionSystem().resolveDeps() pkgs = DepResolutionSystem().getPackages() var_list = [] for pkg in pkgs: if pkg: for var in variable_list: var_list.extend(pkg.getVariable(var).split(' ')) return var_list def getPkgInfos(self, name): if self.mPkgInfos.has_key(name): return self.mPkgInfos[name] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getPkgInfos", "Package %s not found." % name) def exists(self, name): return self.mPkgInfos.has_key(name) def getInfo(self, name): if self.mPkgInfos.has_key(name): return [pkg.getInfo() for pkg in self.mPkgInfos[name]] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getInfo", "Package %s not found." % name) def buildPcFileDict(self): """ Builds up a dictionary of {name: list of files for name} """ pc_dict = {} for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.pc")) # List of .pc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these pc files: %s" % str(glob_list)) for g in glob_list: # Get key name and add file to value list in dictionary key = os.path.basename(g)[:-3] # Strip .pc off the filename...rstrip no worky pc_dict.setdefault(key,[]).append(g) return pc_dict # { "key", [ "list", "of", "corresponding", "pc", "files"] } def populatePkgInfoDBPcFiles(self): dict_to_pop_from = self.buildPcFileDict() for (pkg,files) in dict_to_pop_from.iteritems(): self.mPkgInfos.setdefault(pkg,[]).append(PkgInfo(pkg, files[0], "pc")) def buildFpcFileList(self): """ Builds up a dictionary of {name: list of files for name} """ file_list = [] for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.fpc")) # List of .pc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these fpc files: %s" % str(glob_list)) for g in glob_list: file_list.append(g) return file_list # [ "list", "of", "fpc", "files"] def populatePkgInfoDBFpcFiles(self): list_to_add = self.buildFpcFileList() for file in list_to_add: var_dict = Utils.parsePcFile(file) if not var_dict.has_key("Provides"): flagDBG().out(flagDBG.ERROR, "PkgDB.populate", "%s missing Provides" % str(file)) if not var_dict.has_key("Arch"): flagDBG().out(flagDBG.ERROR, "PkgDB.populate", "%s missing Arch" % str(file)) provides_string = var_dict["Provides"] provides_string = provides_string.replace(',', ' ') provides_string = provides_string.replace('(', ' ') provides_string = provides_string.replace(')', ' ') for key in provides_string.split(" "): if len(key) > 0: self.mPkgInfos.setdefault(key,[]).append(PkgInfo(key, file, "fpc", var_dict)) class PkgInfo: """ Holds the information for a package file on the system. These however are evaluated when the need arises. """ def __init__(self, name, file, type, varDict={}): self.mName = name self.mFile = file self.mIsEvaluated = False self.mType = type self.mVariableDict = varDict if self.mType == "fpc": self.mIsEvaluated = True def getVariable(self, variable): self.evaluate() return self.mVariableDict.get(variable,"") def getName(self): return self.mName def evaluate(self): if not self.mIsEvaluated: flagDBG().out(flagDBG.INFO, "PkgInfo.evaluate", "Evaluating %s" % self.mName) self.mVariableDict= Utils.parsePcFile(self.mFile) self.mIsEvaluated = True def getInfo(self): self.evaluate() return self.mVariableDict class OptionsEvaluator: def __init__(self): self.mOptParser = self.GetOptionParser() (self.mOptions, self.mArgs) = self.mOptParser.parse_args() if self.mOptions.version: print "%s.%s.%s" % Utils.getFlagpollVersion() sys.exit(0) if len(self.mArgs) < 1: self.mOptParser.print_help() sys.exit(1) def evaluateArgs(self): if self.mOptions.debug: flagDBG().setLevel(flagDBG.VERBOSE) Utils.printList(PkgDB().getInfo(self.mArgs[0])) if self.mOptions.require: DepResolutionSystem().makeRequireFilter(self.mOptions.require) if self.mOptions.exists: print PkgDB().exists(self.mArgs[0]) if self.mOptions.info: for pkg in self.mArgs: Utils.printList(PkgDB().getInfo(pkg)) if self.mOptions.variable: Utils.printList(Utils.stripDupInList(PkgDB().getVariablesAndDeps(self.mArgs, [self.mOptions.variable]))) if self.mOptions.static: DepResolutionSystem().setPrivateRequires(True) if self.mOptions.atleast_version: atleast_version = self.mOptions.atleast_version atleast_filter = Filter("Version", lambda x: x >= atleast_version) DepResolutionSystem().addResolveAgentFilter(atleast_filter) if self.mOptions.max_release: max_release = self.mOptions.max_release max_filter = Filter("Version", lambda x: x.startswith(max_release)) DepResolutionSystem().addResolveAgentFilter(max_filter) if self.mOptions.exact_version: exact_version = self.mOptions.exact_version exact_filter = Filter("Version", lambda x: x == exact_version) DepResolutionSystem().addResolveAgentFilter(exact_filter) if self.mOptions.modversion: print PkgDB().getVariables(self.mArgs[0], ["Version"]) if self.mOptions.libs: Utils.printList(Utils.stripDupLinkerFlags(PkgDB().getVariablesAndDeps(self.mArgs, ["Libs"]))) if self.mOptions.libs_only_l: Utils.printList(Utils.libsOnlyLinkerFlags(PkgDB().getVariablesAndDeps(self.mArgs, ["Libs"]))) if self.mOptions.libs_only_L: Utils.printList(Utils.libDirsOnlyLinkerFlags(PkgDB().getVariablesAndDeps(self.mArgs, ["Libs"]))) if self.mOptions.libs_only_other: Utils.printList(Utils.libsOnlyOtherLinkerFlags(PkgDB().getVariablesAndDeps(self.mArgs, ["Libs"]))) if self.mOptions.cflags: Utils.printList(Utils.stripDupIncludeFlags(PkgDB().getVariablesAndDeps(self.mArgs, ["Cflags"]))) if self.mOptions.cflags_only_I: Utils.printList(Utils.cflagsOnlyDirIncludeFlags(PkgDB().getVariablesAndDeps(self.mArgs, ["Cflags"]))) if self.mOptions.cflags_only_other: Utils.printList(Utils.cflagsOnlyOtherIncludeFlags(PkgDB().getVariablesAndDeps(self.mArgs, ["Cflags"]))) # if not self.mOptions.list_all: # print PkgDB().getPkgList def GetOptionParser(self): parser = OptionParser() parser.add_option("--modversion", action="store_true", dest="modversion", help="output version for package") parser.add_option("--version", action="store_true", dest="version", help="output version of pkg-config") parser.add_option("--require", dest="require", help="adds additional requirements for packages ex. 32/64") parser.add_option("--libs", action="store_true", dest="libs", help="output all linker flags") parser.add_option("--static", action="store_true", dest="static", help="output linker flags for static linking") #parser.add_option("--short-errors", action="store_true", dest="short_errors", # help="print short errors") parser.add_option("--libs-only-l", action="store_true", dest="libs_only_l", help="output -l flags") parser.add_option("--libs-only-other", action="store_true", dest="libs_only_other", help="output other libs (e.g. -pthread)") parser.add_option("--libs-only-L", action="store_true", dest="libs_only_L", help="output -L flags") parser.add_option("--cflags", action="store_true", dest="cflags", help="output all pre-processor and compiler flags") parser.add_option("--cflags-only-I", action="store_true", dest="cflags_only_I", help="output -I flags") parser.add_option("--cflags-only-other ", action="store_true", dest="cflags_only_other", help="output cflags not covered by the cflags-only-I option") parser.add_option("--exists", action="store_true", dest="exists", help="return 0 if the module(s) exist") #parser.add_option("--list-all", action="store_true", dest="list_all", # help="list all known packages") parser.add_option("--debug", action="store_true", dest="debug", help="show verbose debug information") parser.add_option("--info", action="store_true", dest="info", help="show information for packages") #parser.add_option("--print-errors", action="store_true", dest="print_errors", # help="show verbose information about missing or conflicting packages") #parser.add_option("--silence-errors", action="store_true", dest="silence_errors", # help="show no information about missing or conflicting packages") #parser.add_option("--uninstalled", action="store_true", dest="uninstalled", # help="return 0 if the uninstalled version of one or more module(s) or their dependencies will be used") #parser.add_option("--errors-to-stdout", action="store_true", dest="errors_to_stdout", # help="print errors from --print-errors to stdout not stderr") #parser.add_option("--print-provides", action="store_true", dest="print_provides", # help="print which packages the package provides") #parser.add_option("--print-requires", action="store_true", dest="print_requires", # help="print which packages the package requires") parser.add_option("--atleast-version", dest="atleast_version", help="return 0 if the module is at least version ATLEAST_VERSION") parser.add_option("--exact-version", dest="exact_version", help="return 0 if the module is exactly version EXACT_VERSION") parser.add_option("--max-release", dest="max_release", help="return 0 if the module has a release that has a version of MAX_RELEASE and will return the max") #parser.add_option("--atleast-pkgconfig-version=VERSION", dest="atleast_pkgconfig_version", # help="require given version of pkg-config") parser.add_option("--variable", dest="variable", help="get the value of a variable") #parser.add_option("--define-variable", dest="define_variable", # help="set the value of a variable") return parser def main(): # GO! # Initialize singletons and the start evaluating my_dbg = flagDBG() my_dep_system = DepResolutionSystem() opt_evaluator = OptionsEvaluator() opt_evaluator.evaluateArgs() sys.exit(0) if __name__ == "__main__": main()
Python
import os, string, sys import distutils.sysconfig import distutils.util import SCons import SCons.Util opts = Options() opts.Add(PathOption('prefix', 'Directory to install under', '/usr')) env = Environment() opts.Update(env); opts.Save('.scons.conf', env) from SCons.Script.SConscript import SConsEnvironment SConsEnvironment.Chmod = SCons.Action.ActionFactory(os.chmod, lambda dest, mode: 'Chmod("%s", 0%o)' % (dest, mode)) def InstallPerm(env, dest, files, perm): obj = env.InstallAs(dest, files) for i in obj: env.AddPostAction(i, env.Chmod(str(i), perm)) SConsEnvironment.InstallPerm = InstallPerm # define wrappers SConsEnvironment.InstallProgram = lambda env, dest, files: InstallPerm(env, dest, files, 0755) SConsEnvironment.InstallData = lambda env, dest, files: InstallPerm(env, dest, files, 0644) flagpoll_py = File('flagpoll.py') flagpoll_fpc = File('flagpoll.fpc') # Here are our installation paths: inst_prefix = '$prefix' inst_bin = '$prefix/bin' inst_data = '$prefix/share/flagpoll' Export('env inst_prefix inst_bin inst_data') fpc_obj = env.InstallData(os.path.join(inst_data, 'flagpoll.fpc'), flagpoll_fpc) flg_bin = env.InstallProgram(os.path.join(inst_bin, 'flagpoll'), flagpoll_py) env.Alias('install', inst_prefix)
Python
#!/usr/bin/env python # ----------------------------------------------------------------- # # Flag Poll: A tool to extract flags from installed applications # for compiling, settting variables, etc. # # Original Authors: # Daniel E. Shipton <dshipton@gmail.com> # # Flag Poll is Copyright (C) 2006 by Daniel E. Shipton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to: # Free SoftwareFoundation, Inc. # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # # ----------------------------------------------------------------- from optparse import OptionParser import sys, os, glob, os.path, copy, platform pj = os.path.join #################################################################### # SNAGGED FROM PYTHON 2.4 for versions under 2.4 #################################################################### import re as _re class _multimap: """Helper class for combining multiple mappings. Used by .{safe_,}substitute() to combine the mapping and keyword arguments. """ def __init__(self, primary, secondary): self._primary = primary self._secondary = secondary def __getitem__(self, key): try: return self._primary[key] except KeyError: return self._secondary[key] class _TemplateMetaclass(type): pattern = r""" %(delim)s(?: (?P<escaped>%(delim)s) | # Escape sequence of two delimiters (?P<named>%(id)s) | # delimiter and a Python identifier {(?P<braced>%(id)s)} | # delimiter and a braced identifier (?P<invalid>) # Other ill-formed delimiter exprs ) """ def __init__(cls, name, bases, dct): super(_TemplateMetaclass, cls).__init__(name, bases, dct) if 'pattern' in dct: pattern = cls.pattern else: pattern = _TemplateMetaclass.pattern % { 'delim' : _re.escape(cls.delimiter), 'id' : cls.idpattern, } cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE) class Template: """A string class for supporting $-substitutions.""" __metaclass__ = _TemplateMetaclass delimiter = '$' idpattern = r'[_a-z][_a-z0-9]*' def __init__(self, template): self.template = template # Search for $$, $identifier, ${identifier}, and any bare $'s def _invalid(self, mo): i = mo.start('invalid') lines = self.template[:i].splitlines(True) if not lines: colno = 1 lineno = 1 else: colno = i - len(''.join(lines[:-1])) lineno = len(lines) raise ValueError('Invalid placeholder in string: line %d, col %d' % (lineno, colno)) def substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): # Check the most common path first. named = mo.group('named') or mo.group('braced') if named is not None: val = mapping[named] # We use this idiom instead of str() because the latter will # fail if val is a Unicode containing non-ASCII characters. return '%s' % val if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: self._invalid(mo) raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) def safe_substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): named = mo.group('named') if named is not None: try: # We use this idiom instead of str() because the latter # will fail if val is a Unicode containing non-ASCII return '%s' % mapping[named] except KeyError: return self.delimiter + named braced = mo.group('braced') if braced is not None: try: return '%s' % mapping[braced] except KeyError: return self.delimiter + '{' + braced + '}' if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: return self.delimiter raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) #################################################################### # End Snagging #################################################################### class Utils: # Holds collection of small utility functions def getFlagpollVersion(): FLAGPOLL_MAJOR_VERSION = 0 FLAGPOLL_MINOR_VERSION = 1 FLAGPOLL_PATCH_VERSION = 5 return ( FLAGPOLL_MAJOR_VERSION, FLAGPOLL_MINOR_VERSION, FLAGPOLL_PATCH_VERSION ) getFlagpollVersion = staticmethod(getFlagpollVersion) def getPathList(): #TODO: expand LD_LIBRARY_PATH to 64/32/etc??? pkg_cfg_dir = [] flg_cfg_dir = [] ld_path = [] if os.environ.has_key("PKG_CONFIG_DIR"): pkg_cfg_dir = os.environ["PKG_CONFIG_DIR"].split(os.pathsep) if os.environ.has_key("FLG_CONFIG_DIR"): flg_cfg_dir = os.environ["FLG_CONFIG_DIR"].split(os.pathsep) if os.environ.has_key("LD_LIBRARY_PATH"): ld_path = os.environ["LD_LIBRARY_PATH"].split(os.pathsep) ld_path = [pj(p,'pkgconfig') for p in ld_path if os.path.exists(p)] path_list = ["/usr/lib64/pkgconfig", "/usr/lib/pkgconfig", "/usr/share/pkgconfig"] path_list = [p for p in path_list if os.path.exists(p)] path_list.extend(pkg_cfg_dir) path_list.extend(flg_cfg_dir) path_list.extend(ld_path) flagDBG().out(flagDBG.INFO, "Utils.getPathList", "Using path list: " + str(path_list)) return path_list getPathList = staticmethod(getPathList) def stripDupInList(gen_list): new_list = [] for item in gen_list: if item not in new_list: if len(item) > 0: new_list.append(item) return new_list stripDupInList = staticmethod(stripDupInList) def stripDupLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] dir_list = [] for flg in flag_list: flg = flg.strip() if flg not in lib_list and flg not in dir_list: if len(flg) > 0: if flg.startswith("-L") or flg.startswith("-R"): dir_list.append(flg) else: lib_list.append(flg) new_list = dir_list + lib_list return new_list stripDupLinkerFlags = staticmethod(stripDupLinkerFlags) def stripDupIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] extra_list = [] for flg in flag_list: flg = flg.strip() if flg not in inc_list and flg not in extra_list: if len(flg) > 0: if flg.startswith("-I"): inc_list.append(flg) else: extra_list.append(flg) extra_list.sort() new_list = inc_list + extra_list return new_list stripDupIncludeFlags = staticmethod(stripDupIncludeFlags) def cflagsOnlyDirIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] for flg in flag_list: flg = flg.strip() if flg not in inc_list: if len(flg) > 0: if flg.startswith("-I"): inc_list.append(flg) return inc_list cflagsOnlyDirIncludeFlags = staticmethod(cflagsOnlyDirIncludeFlags) def cflagsOnlyOtherIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though extra_list = [] for flg in flag_list: flg = flg.strip() if flg not in extra_list: if len(flg) > 0: if not flg.startswith("-I"): extra_list.append(flg) return extra_list cflagsOnlyOtherIncludeFlags = staticmethod(cflagsOnlyOtherIncludeFlags) def libsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] for flg in flag_list: flg = flg.strip() if flg not in lib_list: if len(flg) > 0: if flg.startswith("-l"): lib_list.append(flg) return lib_list libsOnlyLinkerFlags = staticmethod(libsOnlyLinkerFlags) def libsOnlyOtherLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though other_list = [] for flg in flag_list: flg = flg.strip() if flg not in other_list: if len(flg) > 0: if not flg.startswith("-l") and not flg.startswith("-L") and not flag.startswith("-R"): other_list.append(flg) return other_list libsOnlyOtherLinkerFlags = staticmethod(libsOnlyOtherLinkerFlags) def libDirsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though dir_list = [] for flg in flag_list: flg = flg.strip() if flg not in dir_list: if len(flg) > 0: if flg.startswith("-L") or flg.startswith("-R"): dir_list.append(flg) return dir_list libDirsOnlyLinkerFlags = staticmethod(libDirsOnlyLinkerFlags) def printList(gen_list): list_string = "" for item in gen_list: if len(item) > 0: list_string+=str(item) list_string+=" " print list_string printList = staticmethod(printList) def parsePcFile(filename): lines = open(filename).readlines() vars = {} locals = {} for line in lines: line = line.strip() if not line: continue elif ':' in line: # exported variable name, val = line.split(':', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(locals) except ValueError: flagDBG().out(flagDBG.ERROR, "PkgInfo.parse", "%s has an invalid .pc file" % self.mName) vars[name] = val elif '=' in line: # local variable name, val = line.split('=', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(locals) except ValueError: flagDBG().out(flagDBG.ERROR, "PkgInfo.parse", "%s has an invalid .pc file" % self.mName) locals[name] = val return vars parsePcFile = staticmethod(parsePcFile) class flagDBG(object): # Logging class is really easy to use # Levels: # 0 - VERBOSE # 1 - INFO # 2 - WARN # 3 - ERROR VERBOSE=0 INFO=1 WARN=2 ERROR=3 __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if flagDBG.__initialized: return flagDBG.__initialized = True self.mLevel = self.WARN self.mLevelList = ["VERBOSE","INFO","WARN","ERROR"] def setLevel(self, level): if level <= 3: self.mLevel = level def out(self, level, obj, message): if level >= self.mLevel: print self.mLevelList[level] + ":" + str(obj) + ": " + str(message) if level == self.ERROR: sys.exit(1) class DepResolutionSystem(object): """ You add PkgAgents with Filters into system and call resolve() you can check for succes by depsSatisfied() and get the list of packages that work back by calling getPackages() """ __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if DepResolutionSystem.__initialized: return DepResolutionSystem.__initialized = True self.mResolveAgents = [] self.mAgentDict = {} self.mFilters = [] self.mResolveAgentFilters = [] self.mInvalidPackageList = [] self.mSatisfied = False self.mAgentChangeList = [] # list of those responsible for adding Filters # to agents in higher in the chain than them # these are the first agents to ask that they pick # the next best package of them self.mAgentsVisitedList = [] # list of Agents that have been visited self.mResolvedPackageList = [] # list that is generated when deps are satified self.mCheckPrivateRequires = False def getFilters(self): return self.mFilters def addFilter(self, filter): self.mFilters.append(filter) def addResolveAgentFilter(self, filter): self.mResolveAgentFilters.append(filter) def makeRequireFilter(self, requires): arch_list = [] arch_list.append("no_arch") arch_list.append("") if platform.system() == "Linux": if requires == "64": arch_list.append("x86_64") if requires == "32": arch_list.append("i386") arch_list.append("i586") arch_list.append("i686") if platform.system() == "Darwin": if requires == "64": arch_list.append("ppc64") if requires == "32": arch_list.append("ppc") new_filter = Filter("Arch", lambda x: x in arch_list) self.addFilter(new_filter) def createAgent(self, name): if self.checkAgentExists(name): return self.getAgent(name) else: agent = PkgAgent(name) flagDBG().out(flagDBG.INFO, "DepResSys.createAgent", "Adding %s" % name) self.addNewAgent(agent) return agent def setPrivateRequires( self, req ): self.mCheckPrivateRequires = req def checkPrivateRequires(self): return self.mCheckPrivateRequires def checkAgentExists(self, name): return self.mAgentDict.has_key(name) def getAgent(self, name): if self.mAgentDict.has_key(name): return self.mAgentDict[name] else: flagDBG().out(flagDBG.ERROR, "DepResSys.getAgent", "Agent %s does not exist" % name) def addNewAgent(self, agent): self.mAgentDict[agent.getName()] = agent def addResolveAgent(self, agent): if agent not in self.mResolveAgents: self.mResolveAgents.append(agent) for filt in self.mResolveAgentFilters: agent.addFilter(filt) def isSatisfied(self): return self.mSatisfied def updateResolvedPackages(self): pkg_list = [] agent_list = [] for agent in self.mResolveAgents: list = agent.getCurrentPackageList(agent_list) pkg_list.extend(list) self.mResolvedPackageList = pkg_list def getPackages(self): flagDBG().out(flagDBG.VERBOSE, "DepResSys.getPackages", "Generating list of valid packages ") #str([pkg.getCurrentPa.getName() for pkg in self.mResolvedPackageList])) # If this comes back empty then there isn't a valid set of packages to use self.updateResolvedPackages() return self.mResolvedPackageList def checkFiltersChanged(self): list_to_use = [] return True in [pkg.filtersChanged(list_to_use) for pkg in self.mResolveAgents] def resolveHelper(self): self.resolveAgentsChanged = True while self.resolveAgentsChanged: for agent in self.mResolveAgents: flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveHelper", "Updating " + agent.getName()) agent.update(self.mAgentsVisitedList, self.mAgentChangeList) self.resolveAgentsChanged = self.checkFiltersChanged() # Ask mResolveAgents if they are done(they ask sub people) unless they are # really above you in the walk # If there were changes...run update on mResolveAgents again # at the end ask for pkglist..if it comes back empty then we don't # have a usable configuration for those packages def resolveDeps(self): self.resolveHelper() self.updateResolvedPackages() # Check if the first round through we found something # Otherwise we need to start removing packages that aren't viable # during the loop self.mSatisfied = (len(self.mResolvedPackageList) != 0) # remove top of packages that added Filters. # then move on to resolving again # remove more if neccesary agentChangeNumber = 0 while not self.mResolvedPackageList: if(self.mAgentChangeList[agentChangeNumber]): if self.mAgentChangeList[agentChangeNumber] in self.mInvalidPackageList: agentChangeNumber+=1 else: if(self.mAgentChangeList[agentChangeNumber].getViablePackages()): flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveDeps", "Removing bad pkg from " + self.mAgentChangeList[agentChangeNumber].getName()) self.mInvalidPackageList.append(self.mAgentChangeList[agentChangeNumber].removeCurrentPackage()) else: flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveDeps", "No combinations.. Resetting " + self.mAgentChangeList[agentChangeNumber].getName()) self.mAgentChangeList[agentChangeNumber].reset() agentChangeNumber+=1 self.resolveHelper() self.updateResolvedPackages() self.mSatisfied = (len(self.mResolvedPackageList) != 0) return class PkgAgent: """ Agent that keeps track of the versions for a package given some filters and the addition of Filters """ # Makes a PkgAgent that finds its current package with the version reqs def __init__(self, name): if DepResolutionSystem().checkAgentExists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "Package Agent %s already exists" % self.mName) self.mName = name flagDBG().out(flagDBG.VERBOSE, "PkgAgent", "Creating:" + str(self.mName)) if not PkgDB().exists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "No info for package: %s" % self.mName) DepResolutionSystem().addNewAgent(self) self.mFilterList = DepResolutionSystem().getFilters() self.mBasePackageList = PkgDB().getPkgInfos(name) for filt in self.mFilterList: self.mBasePackageList = filt.filter(self.mBasePackageList) if len(self.mBasePackageList) == 0: flagDBG().out(flagDBG.ERROR, "PkgAgent", "No viable packages for: %s" % self.mName) self.mViablePackageList = copy.deepcopy(self.mBasePackageList) if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mAgentDependList = [] # Agents that it depends on/needs to update self.makeDependList() self.mFiltersChanged = True def getName(self): return self.mName #Filter("Version", lambda x: x == "4.5") def makeDependList(self): dep_list = [] if self.mCurrentPackage: req_string = self.mCurrentPackage.getVariable("Requires") if DepResolutionSystem().checkPrivateRequires(): req_string = req_string + " " + self.mCurrentPackage.getVariable("Requires.private") req_string = req_string.strip() if req_string == "": return req_string = req_string.replace(',', ' ') req_string = req_string.replace('(', ' ') req_string = req_string.replace(')', ' ') space_req_string_list = req_string.split(' ') req_string_list = [] for entry in space_req_string_list: if len(entry) > 0: req_string_list.append(entry) i = 0 flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList", self.mCurrentPackage.getName() + " requires: " + str(req_string_list)) while len(req_string_list) > i: if PkgDB().exists(req_string_list[i]): new_filter = [] new_agent = DepResolutionSystem().createAgent(req_string_list[i]) if len(req_string_list) > i+1: if req_string_list[i+1] == "=": ver_to_filt = req_string_list[i+2] new_filter = Filter("Version", lambda x: x == ver_to_filt) elif req_string_list[i+1] == "<=": ver_to_filt = req_string_list[i+2] new_filter = Filter("Version", lambda x: x <= ver_to_filt) elif req_string_list[i+1] == ">=": ver_to_filt = req_string_list[i+2] new_filter = Filter("Version", lambda x: x >= ver_to_filt) else: i+=1 else: i+=1 dep_list.append(new_agent) if new_filter: i+=3 new_agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "PkgAgent.makeDependList", "Package %s depends on %s but is not seem to be installed." % (self.mName, str(req_string_list[i]))) flagDBG().out(flagDBG.VERBOSE, "PkgAgent.makeDependList", "List is:" + str([pkg.getName() for pkg in dep_list])) self.mAgentDependList = dep_list def filtersChanged(self,packageList): tf_list = [self.mFiltersChanged] if self.mName not in packageList: packageList.append(self.mName) for pkg in self.mAgentDependList: tf_list.append(pkg.filtersChanged(packageList)) return True in tf_list def getCurrentPackageList(self, packageList): pkgs = [] if self.mName not in packageList: flagDBG().out(flagDBG.VERBOSE, "PkgAgent.getCurrentPackageList", "Package: %s" % self.mName) pkgs.append(self.mCurrentPackage) packageList.append(self.mName) for pkg in self.mAgentDependList: pkgs.extend(pkg.getCurrentPackageList(packageList)) return pkgs # current pkginfo for me def getCurrentPkgInfo(self): return self.mCurrentPackage # Someone else usually places these on me # I keep track of those separately def addFilter(self, filter): flagDBG().out(flagDBG.VERBOSE, "PkgAgent.addFilter", "Adding a Filter to %s" % self.mName) self.mFiltersChanged = True self.mFilterList.append(filter) def removeCurrentPackage(self): flagDBG().out(flagDBG.VERBOSE, "PkgAgent.removeCurrentPackage", "Removing current package of %s" % self.mName) if self.mViablePackageList: ret_val = self.mViablePackageList[0] in self.mBasePackageList del mViablePackageList[0] if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] return ret_val def update(self, agentVisitedList, agentChangeList): if self.mName in agentVisitedList: return agentVisitedList.append(self.mName) if self.mFiltersChanged: self.mFiltersChanged = False self.updateFilters() # TODO: checkFilters and add them # if a pkg is in visitedList then add yourself to agentChangeList for pkg in self.mAgentDependList: pkg.update(agentVisitedList, agentChangeList) return def updateFilters(self): for filt in self.mFilterList: self.mViablePackageList = filt.filter(self.mViablePackageList) if len(self.mViablePackageList) > 0: self.mCurrentPackage = self.mViablePackageList[0] else: self.mCurrentPackage = [] def reset(self): flagDBG().out(flagDBG.VERBOSE, "PkgAgent.reset", "Resetting package: %s" % self.mName) self.mViablePackageList = self.mBasePackageList if self.mViablePackageList: self.mCurrentPacakge = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mFilterList = self.mBaseFilters self.mAgentDependList = [] self.mFiltersChanged = True return class Filter: """ A single Filter that knows how to filter the list it recieves Will be inheireted....?..? """ def __init__(self, variableName, testCallable): self.mVarName = variableName self.mTestCallable = testCallable def filter(self, pkg_info_list): ret_pkg_list = [] # Filter first for pkg in pkg_info_list: var = pkg.getVariable(self.mVarName) if self.mTestCallable(var): ret_pkg_list.append(pkg) # Now sort ret_pkg_list.sort(lambda lhs,rhs: cmp(lhs.getVariable(self.mVarName), rhs.getVariable(self.mVarName))) return ret_pkg_list #requires: qt == 4.5 #Filter("Version", lambda x: x <= "4.5") #Filter("Version", lambda x: x <= "4.5") class PkgDB(object): """ Holds all the neccesary information to evaluate itself when needed. Is in charge of holding a list of PkgInfo's that contain info about the package. """ __initialized = False def __init__(self): if self.__initialized: return self.__initialized = True self.mPkgInfos = {} # {pkg_name: List of package infos} self.populatePkgInfoDBPcFiles() self.populatePkgInfoDBFpcFiles() def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def getVariables(self, name, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariable", "Finding " + str(variable_list) + " in " + str(name)) ret_list = [] for var in variable_list: if self.mPkgInfos.has_key(name): ret_list.extend(self.mPkgInfos[name][0].getVariable(var)) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariable", "Package %s not found." % name) return ret_list def getVariablesAndDeps(self, pkg_list, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariablesAndDeps", "Finding " + str(variable_list) + " in " + str(pkg_list)) if DepResolutionSystem().checkPrivateRequires(): temp_var_list = [] for var in variable_list: temp_var_list.append(var.join(".private")) variable_list = variable_list + temp_var_list for name in pkg_list: if self.mPkgInfos.has_key(name): agent = DepResolutionSystem().createAgent(name) DepResolutionSystem().addResolveAgent(agent) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariablesAndDeps", "Package %s not found." % name) DepResolutionSystem().resolveDeps() pkgs = DepResolutionSystem().getPackages() var_list = [] for pkg in pkgs: if pkg: for var in variable_list: var_list.extend(pkg.getVariable(var).split(' ')) return var_list def getPkgInfos(self, name): if self.mPkgInfos.has_key(name): return self.mPkgInfos[name] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getPkgInfos", "Package %s not found." % name) def exists(self, name): return self.mPkgInfos.has_key(name) def getInfo(self, name): if self.mPkgInfos.has_key(name): return [pkg.getInfo() for pkg in self.mPkgInfos[name]] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getInfo", "Package %s not found." % name) def buildPcFileDict(self): """ Builds up a dictionary of {name: list of files for name} """ pc_dict = {} for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.pc")) # List of .pc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these pc files: %s" % str(glob_list)) for g in glob_list: # Get key name and add file to value list in dictionary key = os.path.basename(g)[:-3] # Strip .pc off the filename...rstrip no worky pc_dict.setdefault(key,[]).append(g) return pc_dict # { "key", [ "list", "of", "corresponding", "pc", "files"] } def populatePkgInfoDBPcFiles(self): dict_to_pop_from = self.buildPcFileDict() for (pkg,files) in dict_to_pop_from.iteritems(): self.mPkgInfos.setdefault(pkg,[]).append(PkgInfo(pkg, files[0], "pc")) def buildFpcFileList(self): """ Builds up a dictionary of {name: list of files for name} """ file_list = [] for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.fpc")) # List of .pc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these fpc files: %s" % str(glob_list)) for g in glob_list: file_list.append(g) return file_list # [ "list", "of", "fpc", "files"] def populatePkgInfoDBFpcFiles(self): list_to_add = self.buildFpcFileList() for file in list_to_add: var_dict = Utils.parsePcFile(file) if not var_dict.has_key("Provides"): flagDBG().out(flagDBG.ERROR, "PkgDB.populate", "%s missing Provides" % str(file)) if not var_dict.has_key("Arch"): flagDBG().out(flagDBG.ERROR, "PkgDB.populate", "%s missing Arch" % str(file)) provides_string = var_dict["Provides"] provides_string = provides_string.replace(',', ' ') provides_string = provides_string.replace('(', ' ') provides_string = provides_string.replace(')', ' ') for key in provides_string.split(" "): if len(key) > 0: self.mPkgInfos.setdefault(key,[]).append(PkgInfo(key, file, "fpc", var_dict)) class PkgInfo: """ Holds the information for a package file on the system. These however are evaluated when the need arises. """ def __init__(self, name, file, type, varDict={}): self.mName = name self.mFile = file self.mIsEvaluated = False self.mType = type self.mVariableDict = varDict if self.mType == "fpc": self.mIsEvaluated = True def getVariable(self, variable): self.evaluate() return self.mVariableDict.get(variable,"") def getName(self): return self.mName def evaluate(self): if not self.mIsEvaluated: flagDBG().out(flagDBG.INFO, "PkgInfo.evaluate", "Evaluating %s" % self.mName) self.mVariableDict= Utils.parsePcFile(self.mFile) self.mIsEvaluated = True def getInfo(self): self.evaluate() return self.mVariableDict class OptionsEvaluator: def __init__(self): self.mOptParser = self.GetOptionParser() (self.mOptions, self.mArgs) = self.mOptParser.parse_args() if self.mOptions.version: print "%s.%s.%s" % Utils.getFlagpollVersion() sys.exit(0) if len(self.mArgs) < 1: self.mOptParser.print_help() sys.exit(1) def evaluateArgs(self): if self.mOptions.debug: flagDBG().setLevel(flagDBG.VERBOSE) Utils.printList(PkgDB().getInfo(self.mArgs[0])) if self.mOptions.require: DepResolutionSystem().makeRequireFilter(self.mOptions.require) if self.mOptions.exists: print PkgDB().exists(self.mArgs[0]) if self.mOptions.info: for pkg in self.mArgs: Utils.printList(PkgDB().getInfo(pkg)) if self.mOptions.variable: Utils.printList(Utils.stripDupInList(PkgDB().getVariablesAndDeps(self.mArgs, [self.mOptions.variable]))) if self.mOptions.static: DepResolutionSystem().setPrivateRequires(True) if self.mOptions.atleast_version: atleast_version = self.mOptions.atleast_version atleast_filter = Filter("Version", lambda x: x >= atleast_version) DepResolutionSystem().addResolveAgentFilter(atleast_filter) if self.mOptions.max_release: max_release = self.mOptions.max_release max_filter = Filter("Version", lambda x: x.startswith(max_release)) DepResolutionSystem().addResolveAgentFilter(max_filter) if self.mOptions.exact_version: exact_version = self.mOptions.exact_version exact_filter = Filter("Version", lambda x: x == exact_version) DepResolutionSystem().addResolveAgentFilter(exact_filter) if self.mOptions.modversion: print PkgDB().getVariables(self.mArgs[0], ["Version"]) if self.mOptions.libs: Utils.printList(Utils.stripDupLinkerFlags(PkgDB().getVariablesAndDeps(self.mArgs, ["Libs"]))) if self.mOptions.libs_only_l: Utils.printList(Utils.libsOnlyLinkerFlags(PkgDB().getVariablesAndDeps(self.mArgs, ["Libs"]))) if self.mOptions.libs_only_L: Utils.printList(Utils.libDirsOnlyLinkerFlags(PkgDB().getVariablesAndDeps(self.mArgs, ["Libs"]))) if self.mOptions.libs_only_other: Utils.printList(Utils.libsOnlyOtherLinkerFlags(PkgDB().getVariablesAndDeps(self.mArgs, ["Libs"]))) if self.mOptions.cflags: Utils.printList(Utils.stripDupIncludeFlags(PkgDB().getVariablesAndDeps(self.mArgs, ["Cflags"]))) if self.mOptions.cflags_only_I: Utils.printList(Utils.cflagsOnlyDirIncludeFlags(PkgDB().getVariablesAndDeps(self.mArgs, ["Cflags"]))) if self.mOptions.cflags_only_other: Utils.printList(Utils.cflagsOnlyOtherIncludeFlags(PkgDB().getVariablesAndDeps(self.mArgs, ["Cflags"]))) # if not self.mOptions.list_all: # print PkgDB().getPkgList def GetOptionParser(self): parser = OptionParser() parser.add_option("--modversion", action="store_true", dest="modversion", help="output version for package") parser.add_option("--version", action="store_true", dest="version", help="output version of pkg-config") parser.add_option("--require", dest="require", help="adds additional requirements for packages ex. 32/64") parser.add_option("--libs", action="store_true", dest="libs", help="output all linker flags") parser.add_option("--static", action="store_true", dest="static", help="output linker flags for static linking") #parser.add_option("--short-errors", action="store_true", dest="short_errors", # help="print short errors") parser.add_option("--libs-only-l", action="store_true", dest="libs_only_l", help="output -l flags") parser.add_option("--libs-only-other", action="store_true", dest="libs_only_other", help="output other libs (e.g. -pthread)") parser.add_option("--libs-only-L", action="store_true", dest="libs_only_L", help="output -L flags") parser.add_option("--cflags", action="store_true", dest="cflags", help="output all pre-processor and compiler flags") parser.add_option("--cflags-only-I", action="store_true", dest="cflags_only_I", help="output -I flags") parser.add_option("--cflags-only-other ", action="store_true", dest="cflags_only_other", help="output cflags not covered by the cflags-only-I option") parser.add_option("--exists", action="store_true", dest="exists", help="return 0 if the module(s) exist") #parser.add_option("--list-all", action="store_true", dest="list_all", # help="list all known packages") parser.add_option("--debug", action="store_true", dest="debug", help="show verbose debug information") parser.add_option("--info", action="store_true", dest="info", help="show information for packages") #parser.add_option("--print-errors", action="store_true", dest="print_errors", # help="show verbose information about missing or conflicting packages") #parser.add_option("--silence-errors", action="store_true", dest="silence_errors", # help="show no information about missing or conflicting packages") #parser.add_option("--uninstalled", action="store_true", dest="uninstalled", # help="return 0 if the uninstalled version of one or more module(s) or their dependencies will be used") #parser.add_option("--errors-to-stdout", action="store_true", dest="errors_to_stdout", # help="print errors from --print-errors to stdout not stderr") #parser.add_option("--print-provides", action="store_true", dest="print_provides", # help="print which packages the package provides") #parser.add_option("--print-requires", action="store_true", dest="print_requires", # help="print which packages the package requires") parser.add_option("--atleast-version", dest="atleast_version", help="return 0 if the module is at least version ATLEAST_VERSION") parser.add_option("--exact-version", dest="exact_version", help="return 0 if the module is exactly version EXACT_VERSION") parser.add_option("--max-release", dest="max_release", help="return 0 if the module has a release that has a version of MAX_RELEASE and will return the max") #parser.add_option("--atleast-pkgconfig-version=VERSION", dest="atleast_pkgconfig_version", # help="require given version of pkg-config") parser.add_option("--variable", dest="variable", help="get the value of a variable") #parser.add_option("--define-variable", dest="define_variable", # help="set the value of a variable") return parser def main(): # GO! # Initialize singletons and the start evaluating my_dbg = flagDBG() my_dep_system = DepResolutionSystem() opt_evaluator = OptionsEvaluator() opt_evaluator.evaluateArgs() sys.exit(0) if __name__ == "__main__": main()
Python
#!/usr/bin/env python from distutils.core import setup setup( name='flagpoll', version='0.6.1', description='Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software.', author='Daniel E. Shipton', author_email='dshipton@infiscape.com', license='GPL', url='https://realityforge.vrsource.org/view/FlagPoll/WebHome', download_url='https://realityforge.vrsource.org/view/FlagPoll/FlagpollDownloads', scripts=['flagpoll'], long_description = "Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software. Think of it as the rpm of software development. It enables developers total control over which packages, versions, architectures, etc. that they want to use meta-data from.", data_files=[('share/flagpoll', ['flagpoll.fpc']), ('share/man/man1', ['flagpoll.1']), ('share/aclocal', ['flagpoll.m4'])] )
Python
#!/usr/bin/env python # ----------------------------------------------------------------- # # Flag Poll: A tool to extract flags from installed applications # for compiling, settting variables, etc. # # Original Authors: # Daniel E. Shipton <dshipton@gmail.com> # # Flag Poll is Copyright (C) 2006 by Daniel E. Shipton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to: # Free SoftwareFoundation, Inc. # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # # ----------------------------------------------------------------- """Makes a flagpole .fpc file from user input. v0.9 coded by Jeff Groves""" import os import sys import getopt ##String prompts for the input varPrompt = """Convience variables (one 'var_name= var_definition' per line,""" + \ """ empty line when done)""" namePrompt = "Formal Name" descriptionPrompt = "Description" urlPrompt = "URL" providesPrompt = "One or more names to look package up by: (Provides)" versionPrompt = "Version (x.y.z)" architecturePrompt = "Architecture" requirePrompt = "Requires" libPrompt = "Linker Flags (-lfoo -L/usr/lib)" staticLibPrompt = "Static Linking Flags/Libs (extra private libs)" compileFlagsPrompt = "Compile/Include Flags (-I/usr -fpge -O2)" fileNamePrompt = "FPC File's Name" def usage(): """Prints a list of acceptable arguments for fpcmaker.py.""" print """ Fpcmaker.py Options: -n, --name= : Sets %s -d, --description= : Sets %s -u, --url= : Sets %s -p, --provides= : Sets %s -v, --version= : Sets %s -a, --architecture= : Sets %s -r, --requires= : Sets %s -l, --libs= : Sets %s -c, --cflags= : Sets %s -s, --static= : Sets %s -f, --file= : Sets %s """ %(namePrompt, descriptionPrompt, urlPrompt, providesPrompt, versionPrompt, architecturePrompt, requirePrompt, libPrompt, compileFlagsPrompt, staticLibPrompt, fileNamePrompt) return def checkFileName(fileName): """Checks if the fpc file name's blank, contains slashes, or exists.""" nameCleared = False writeFile = True confirms = ['y', 'Y', 'yes', 'Yes'] ##Loops until the name clears or writing the file's aborted. while(not nameCleared and writeFile): ##If it's blank, give the option of aborting the program. if fileName == "": choice = raw_input("Do you want to abort writing the" + " .fpc file? (Y/N): ") if choice not in confirms: fileName = raw_input("Please enter a different name for the" + " .fpc file: ") else: writeFile = False ##If it contains slashes, ask for another name. elif '/' in fileName or '\\' in fileName: print "I can't write to %s because it contains slashes."%(fileName) fileName = raw_input("Please enter a different name for the" + " .fpc file: ") ##If it already exists, ask if they want to overwrite. ##If not, ask for another name. elif os.path.exists(fileName): choice = raw_input("The file %s already exists." %(fileName) + " Do you want to overwrite it? (Y/N): ") if choice not in confirms: fileName = raw_input("Please enter a different name for the" + " .fpc file: ") else: nameCleared = True else: nameCleared = True return [fileName, writeFile] ##Booleans for whether that argument was sent in the command line varSet = False providesSet = False nameSet = False descriptionSet = False urlSet = False architectureSet = False versionSet = False requiresSet = False libsSet = False compileFlagsSet = False staticLibSet = False fileNameSet = False ##Get the options & arguments sent. arguments = sys.argv[1:] try: opts, args = getopt.getopt(arguments, "p:n:u:d:a:r:v:l:c:s:f:", ["provides=", "name=", "url=", "description=", "architecture=", "requires=", "version=", "libs=", "cflags=", "static=", "file="]) ##Send them usage info if they enter a wrong argument except getopt.GetoptError: usage() sys.exit(2) for opt, arg in opts: if opt in ('-p', '--provides'): providesSet = True provides = arg elif opt in ('-n', '--name'): nameSet = True name = arg elif opt in ('-v', '--version'): versionSet = True version = arg elif opt in ('-u', '--url'): urlSet = True url = arg elif opt in ('-d', '--description'): descriptionSet = True description = arg elif opt in ('-a', '--architecture'): architectureSet = True architecture = arg elif opt in ('-r', '--requires'): requiresSet = True requires = arg elif opt in ('-l', '--libs'): libsSet = True libs = arg elif opt in ('-c', '--cflags'): compileFlagsSet = True compileFlags = arg elif opt in ('-s', '--static'): staticLibSet = True staticLib = arg elif opt in ('-f', '--file'): fileNameSet = True fileName = arg ##Grab any input not passed in the arguments from the user. if not varSet: varLine = None variables = "" print "%s:" %(varPrompt) while(varLine != ""): varLine = raw_input("") variables = variables + "%s\n" %(varLine) if not nameSet: name = raw_input("%s: " %(namePrompt)) if not descriptionSet: description = raw_input("%s: " %(descriptionPrompt)) if not urlSet: url = raw_input("%s: " %(urlPrompt)) if not versionSet: version = raw_input("%s: " %(versionPrompt)) if not providesSet: provides = raw_input("%s: " %(providesPrompt)) if not requiresSet: requires = raw_input("%s: " %(requirePrompt)) if not architectureSet: architecture = raw_input("%s: " %(architecturePrompt)) if not libsSet: libs = raw_input("%s: " %(libPrompt)) if not staticLibSet: staticLib = raw_input("%s: " %(staticLibPrompt)) if not compileFlagsSet: compileFlags = raw_input("%s: " %(compileFlagsPrompt)) if not fileNameSet: fileName = raw_input("%s: " %(fileNamePrompt)) ##Check the file's name. fileName, writeFile = checkFileName(fileName) ##If they chose not to overwrite, write the file. if writeFile: fpc = open(fileName, 'w') fpc.write("%s" %(variables)) fpc.write("Name: %s\n" %(name)) fpc.write("Description: %s\n" %(description)) fpc.write("URL: %s\n" %(url)) fpc.write("Version: %s\n" %(version)) fpc.write("Provides: %s\n" %(provides)) fpc.write("Requires: %s\n" %(requires)) fpc.write("Arch: %s\n" %(architecture)) fpc.write("Libs: %s\n" %(libs)) fpc.write("Libs.private: %s\n" %(staticLib)) fpc.write("Cflags: %s\n" %(compileFlags)) fpc.close() ##TESTER: Print the file out. fpc = open(fileName, 'r') ##TESTER print fpc.read() ##TESTER fpc.close ##TESTER
Python
#!/usr/bin/env python # ----------------------------------------------------------------- # # Flagpoll: A tool to extract flags from installed applications # for compiling, settting variables, etc. # # Original Authors: # Daniel E. Shipton <dshipton@gmail.com> # # Flagpoll is Copyright (C) 2006 by Daniel E. Shipton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to: # Free SoftwareFoundation, Inc. # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # # ----------------------------------------------------------------- from optparse import OptionParser import sys, os, glob, os.path, copy, platform pj = os.path.join #################################################################### # SNAGGED FROM PYTHON 2.4 for versions under 2.4 #################################################################### import re as _re class _multimap: """Helper class for combining multiple mappings. Used by .{safe_,}substitute() to combine the mapping and keyword arguments. """ def __init__(self, primary, secondary): self._primary = primary self._secondary = secondary def __getitem__(self, key): try: return self._primary[key] except KeyError: return self._secondary[key] class _TemplateMetaclass(type): pattern = r""" %(delim)s(?: (?P<escaped>%(delim)s) | # Escape sequence of two delimiters (?P<named>%(id)s) | # delimiter and a Python identifier {(?P<braced>%(id)s)} | # delimiter and a braced identifier (?P<invalid>) # Other ill-formed delimiter exprs ) """ def __init__(cls, name, bases, dct): super(_TemplateMetaclass, cls).__init__(name, bases, dct) if 'pattern' in dct: pattern = cls.pattern else: pattern = _TemplateMetaclass.pattern % { 'delim' : _re.escape(cls.delimiter), 'id' : cls.idpattern, } cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE) class Template: """A string class for supporting $-substitutions.""" __metaclass__ = _TemplateMetaclass delimiter = '$' idpattern = r'[_a-z][_a-z0-9]*' def __init__(self, template): self.template = template # Search for $$, $identifier, ${identifier}, and any bare $'s def _invalid(self, mo): i = mo.start('invalid') lines = self.template[:i].splitlines(True) if not lines: colno = 1 lineno = 1 else: colno = i - len(''.join(lines[:-1])) lineno = len(lines) raise ValueError('Invalid placeholder in string: line %d, col %d' % (lineno, colno)) def substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): # Check the most common path first. named = mo.group('named') or mo.group('braced') if named is not None: val = mapping[named] # We use this idiom instead of str() because the latter will # fail if val is a Unicode containing non-ASCII characters. return '%s' % val if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: self._invalid(mo) raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) def safe_substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): named = mo.group('named') if named is not None: try: # We use this idiom instead of str() because the latter # will fail if val is a Unicode containing non-ASCII return '%s' % mapping[named] except KeyError: return self.delimiter + named braced = mo.group('braced') if braced is not None: try: return '%s' % mapping[braced] except KeyError: return self.delimiter + '{' + braced + '}' if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: return self.delimiter raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) #################################################################### # End Snagging #################################################################### class Utils: # Holds collection of small utility functions EXTRA_FLAGPOLL_SEARCH_PATHS = "" EXTRA_FLAGPOLL_FILES = "" path_list_cache = None # Cache of found path lists. (only calcuate once) KEEP_DUPS = False def getFlagpollVersion(): FLAGPOLL_MAJOR_VERSION = 0 FLAGPOLL_MINOR_VERSION = 6 FLAGPOLL_PATCH_VERSION = 1 return ( FLAGPOLL_MAJOR_VERSION, FLAGPOLL_MINOR_VERSION, FLAGPOLL_PATCH_VERSION ) getFlagpollVersion = staticmethod(getFlagpollVersion) def getPathList(): if None != Utils.path_list_cache: return Utils.path_list_cache #TODO: expand LD_LIBRARY_PATH to 64/32/etc??? pkg_cfg_dir = [] flg_cfg_dir = [] ld_path = [] if os.environ.has_key("PKG_CONFIG_PATH"): pkg_cfg_dir = os.environ["PKG_CONFIG_PATH"].split(os.pathsep) if os.environ.has_key("FLAGPOLL_PATH"): flg_cfg_dir = os.environ["FLAGPOLL_PATH"].split(os.pathsep) if os.environ.has_key("LD_LIBRARY_PATH"): ld_path = os.environ["LD_LIBRARY_PATH"].split(os.pathsep) ld_path_pkg = [pj(p,'pkgconfig') for p in ld_path] ld_path_flg = [pj(p,'flagpoll') for p in ld_path] ld_path = [] ld_path.extend(ld_path_pkg) ld_path.extend(ld_path_flg) extra_paths = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS.split(os.pathsep) path_list = ["/usr/lib64/pkgconfig", "/usr/lib/pkgconfig", "/usr/share/pkgconfig", "/usr/lib64/flagpoll", "/usr/lib/flagpoll", "/usr/share/flagpoll"] path_list.extend(pkg_cfg_dir) path_list.extend(flg_cfg_dir) path_list.extend(extra_paths) path_list.extend(ld_path) flagDBG().out(flagDBG.VERBOSE, "Utils.getPathList", "Potential path list: " + str(path_list)) path_list = [p for p in path_list if os.path.exists(p)] flagDBG().out(flagDBG.INFO, "Utils.getPathList", "Using path list: " + str(path_list)) Utils.path_list_cache = path_list return path_list getPathList = staticmethod(getPathList) def getFileList(): flist = Utils.EXTRA_FLAGPOLL_FILES.split(":") filelist = [] for f in flist: if os.path.isfile(f): filelist.append(f) return filelist getFileList = staticmethod(getFileList) def setKeepDups(keep_dups): Utils.KEEP_DUPS = keep_dups setKeepDups = staticmethod(setKeepDups) def stripDupInList(gen_list): new_list = [] for item in gen_list: item = item.strip() if Utils.KEEP_DUPS: if len(item) > 0: new_list.append(item) continue if item not in new_list: if len(item) > 0: new_list.append(item) return new_list stripDupInList = staticmethod(stripDupInList) def stripDupLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] dir_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-L") or flg.startswith("-R"): dir_list.append(flg) else: lib_list.append(flg) new_list = dir_list + lib_list return Utils.stripDupInList(new_list) stripDupLinkerFlags = staticmethod(stripDupLinkerFlags) def stripDupIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] extra_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-I"): inc_list.append(flg) else: extra_list.append(flg) extra_list.sort() new_list = inc_list + extra_list return Utils.stripDupInList(new_list) stripDupIncludeFlags = staticmethod(stripDupIncludeFlags) def cflagsOnlyDirIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-I"): inc_list.append(flg) return Utils.stripDupInList(inc_list) cflagsOnlyDirIncludeFlags = staticmethod(cflagsOnlyDirIncludeFlags) def cflagsOnlyOtherIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though extra_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if not flg.startswith("-I"): extra_list.append(flg) return Utils.stripDupInList(extra_list) cflagsOnlyOtherIncludeFlags = staticmethod(cflagsOnlyOtherIncludeFlags) def libsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-l"): lib_list.append(flg) return Utils.stripDupInList(lib_list) libsOnlyLinkerFlags = staticmethod(libsOnlyLinkerFlags) def libsOnlyOtherLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though other_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if not flg.startswith("-l") and not flg.startswith("-L") and not flg.startswith("-R"): other_list.append(flg) return Utils.stripDupInList(other_list) libsOnlyOtherLinkerFlags = staticmethod(libsOnlyOtherLinkerFlags) def libDirsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though dir_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-L") or flg.startswith("-R"): dir_list.append(flg) return Utils.stripDupInList(dir_list) libDirsOnlyLinkerFlags = staticmethod(libDirsOnlyLinkerFlags) def printList(gen_list): list_string = "" for item in gen_list: if len(item) > 0: list_string+=str(item) list_string+=" " print list_string.strip() printList = staticmethod(printList) def parsePcFile(filename): lines = open(filename).readlines() fvars = {} fvars["XXFlagpollFilenameXX"] = filename lokals = {} lokals["fp_file_cwd"] = str(filename[:- ((len(os.path.basename(filename) ) + 1))]) lines.append("prefix: ${prefix}") for line in lines: line = line.strip() if not line: continue if line.startswith("#"): continue eq_pos = line.find('=') col_pos = line.find(':') if eq_pos < col_pos and eq_pos != -1 or col_pos == -1 and eq_pos !=-1: # local variable name, val = line.split('=', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(lokals) except ValueError: flagDBG().out(flagDBG.WARN, "PkgInfo.parse", "%s has an invalid metadata file" % filename) lokals[name] = val if col_pos < eq_pos and col_pos != -1 or eq_pos == -1 and col_pos !=-1: # exported variable name, val = line.split(':', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(lokals) except ValueError: flagDBG().out(flagDBG.ERROR, "PkgInfo.parse", "%s has an invalid metadata file" % filename) fvars[name] = val return fvars parsePcFile = staticmethod(parsePcFile) class flagDBG(object): # Logging class is really easy to use # Levels: # 0 - VERBOSE # 1 - INFO # 2 - WARN # 3 - ERROR VERBOSE=0 INFO=1 WARN=2 ERROR=3 __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if flagDBG.__initialized: return flagDBG.__initialized = True self.mLevel = self.WARN self.mLevelList = ["VERBOSE","INFO","WARN","ERROR"] def setLevel(self, level): if level <= 3: self.mLevel = level def out(self, level, obj, message): if level == self.ERROR: if self.mLevel == self.VERBOSE: print self.mLevelList[level] + ":" + str(obj) + ": " + str(message) else: print self.mLevelList[level] + ": " + str(message) sys.exit(1) if level >= self.mLevel: print self.mLevelList[level] + ":" + str(obj) + ": " + str(message) class DepResolutionSystem(object): """ You add PkgAgents with Filters into system and call resolve() you can check for succes by depsSatisfied() and get the list of packages that work back by calling getPackages() """ __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if DepResolutionSystem.__initialized: return DepResolutionSystem.__initialized = True self.mResolveAgents = [] self.mAgentDict = {} self.mFilters = [] self.mResolveAgentFilters = [] self.mInvalidPackageList = [] self.mSatisfied = False self.mAgentChangeList = [] # list of those responsible for adding Filters # to agents in higher in the chain than them # these are the first agents to ask that they pick # the next best package of them self.mAgentsVisitedList = [] # list of Agents that have been visited self.mResolvedPackageList = [] # list that is generated when deps are satified self.mCheckPrivateRequires = False self.mMadeDependList = False def getFilters(self): return self.mFilters def addFilter(self, filter): self.mFilters.append(filter) def addResolveAgentFilter(self, filter): self.mResolveAgentFilters.append(filter) def makeRequireFilter(self, requires): arch_list = [] arch_list.append("no_arch") arch_list.append("") if platform.system() == "Linux": if requires == "64": arch_list.append("x86_64") if requires == "32": arch_list.append("i386") arch_list.append("i586") arch_list.append("i686") if platform.system() == "Darwin": if requires == "64": arch_list.append("ppc64") if requires == "32": arch_list.append("ppc") new_filter = Filter("Arch", lambda x: x in arch_list) self.addFilter(new_filter) def createAgent(self, name): if self.checkAgentExists(name): return self.getAgent(name) else: agent = PkgAgent(name) flagDBG().out(flagDBG.INFO, "DepResSys.createAgent", "Adding %s" % name) self.addNewAgent(agent) return agent def createResolveAgent(self, name): if self.checkAgentExists(name): return self.getAgent(name) else: agent = PkgAgent(name) flagDBG().out(flagDBG.INFO, "DepResSys.createResloveAgent", "Adding %s" % name) self.addResolveAgent(agent) return agent def setPrivateRequires( self, req ): self.mCheckPrivateRequires = req def checkPrivateRequires(self): return self.mCheckPrivateRequires def checkAgentExists(self, name): return self.mAgentDict.has_key(name) def getAgent(self, name): if self.mAgentDict.has_key(name): return self.mAgentDict[name] else: flagDBG().out(flagDBG.ERROR, "DepResSys.getAgent", "Agent %s does not exist" % name) def addNewAgent(self, agent): if not self.checkAgentExists(agent): self.mAgentDict[agent.getName()] = agent def addResolveAgent(self, agent): if agent not in self.mResolveAgents: self.mResolveAgents.append(agent) for filt in self.mResolveAgentFilters: agent.addFilter(filt) def isSatisfied(self): return self.mSatisfied def updateResolvedPackages(self): pkg_list = [] agent_list = [] for agent in self.mResolveAgents: list_of_pkgs = agent.getCurrentPackageList(agent_list) pkg_list.extend(list_of_pkgs) self.mResolvedPackageList = pkg_list def getPackages(self): flagDBG().out(flagDBG.VERBOSE, "DepResSys.getPackages", "Generating list of valid packages ") #str([pkg.getCurrentPa.getName() for pkg in self.mResolvedPackageList])) # If this comes back empty then there isn't a valid set of packages to use self.updateResolvedPackages() return self.mResolvedPackageList def checkFiltersChanged(self): list_to_use = [] return True in [pkg.filtersChanged(list_to_use) for pkg in self.mResolveAgents] def resolveHelper(self): self.resolveAgentsChanged = True while self.resolveAgentsChanged: for agent in self.mResolveAgents: flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveHelper", "Updating " + agent.getName()) agent.update(self.mAgentsVisitedList, self.mAgentChangeList) self.resolveAgentsChanged = self.checkFiltersChanged() # Ask mResolveAgents if they are done(they ask sub people) unless they are # really above you in the walk # If there were changes...run update on mResolveAgents again # at the end ask for pkglist..if it comes back empty then we don't # have a usable configuration for those packages def resolveDeps(self): if not self.mMadeDependList: for agent in self.mResolveAgents: agent.makeDependList() self.mMadeDependList = True self.resolveHelper() self.updateResolvedPackages() # Check if the first round through we found something # Otherwise we need to start removing packages that aren't viable # during the loop self.mSatisfied = (len(self.mResolvedPackageList) != 0) # remove top of packages that added Filters. # then move on to resolving again # remove more if neccesary agentChangeNumber = 0 while not self.mResolvedPackageList: if(self.mAgentChangeList[agentChangeNumber]): if self.mAgentChangeList[agentChangeNumber] in self.mInvalidPackageList: agentChangeNumber+=1 else: if(self.mAgentChangeList[agentChangeNumber].getViablePackages()): flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveDeps", "Removing bad pkg from " + self.mAgentChangeList[agentChangeNumber].getName()) self.mInvalidPackageList.append(self.mAgentChangeList[agentChangeNumber].removeCurrentPackage()) else: flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveDeps", "No combinations.. Resetting " + self.mAgentChangeList[agentChangeNumber].getName()) self.mAgentChangeList[agentChangeNumber].reset() agentChangeNumber+=1 self.resolveHelper() self.updateResolvedPackages() self.mSatisfied = (len(self.mResolvedPackageList) != 0) return class PkgAgent: """ Agent that keeps track of the versions for a package given some filters and the addition of Filters """ # Makes a PkgAgent that finds its current package with the version reqs def __init__(self, name): if DepResolutionSystem().checkAgentExists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "Package Agent %s already exists" % self.mName) self.mName = name flagDBG().out(flagDBG.VERBOSE, "PkgAgent", "Creating:" + str(self.mName)) if not PkgDB().exists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "No info for package: %s" % self.mName) #XXX Doesn't keep filters added for a redo... DepResolutionSystem().addNewAgent(self) self.mFilterList = [] self.mFilterList.extend(DepResolutionSystem().getFilters()) self.mBasePackageList = PkgDB().getPkgInfos(name) for filt in self.mFilterList: self.mBasePackageList = filt.filter(self.mBasePackageList) if len(self.mBasePackageList) == 0: flagDBG().out(flagDBG.ERROR, "PkgAgent", "No viable packages for: %s" % self.mName) self.mViablePackageList = copy.deepcopy(self.mBasePackageList) if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mAgentDependList = [] # Agents that it depends on/needs to update #self.makeDependList() self.mFiltersChanged = True self.mCheckDepends = True def getName(self): return self.mName def setCheckDepends(self, tf): self.mCheckDepends = tf #Filter("Version", lambda x: x == "4.5") def makeDependList(self): if not self.mCheckDepends: self.mAgentDependList = [] return dep_list = [] if self.mCurrentPackage: req_string = self.mCurrentPackage.getVariable("Requires") if DepResolutionSystem().checkPrivateRequires(): req_string = req_string + " " + self.mCurrentPackage.getVariable("Requires.private") req_string = req_string.strip() if req_string == "": return req_string = req_string.replace(',', ' ') req_string = req_string.replace('(', ' ') req_string = req_string.replace(')', ' ') space_req_string_list = req_string.split(' ') req_string_list = [] for entry in space_req_string_list: if len(entry) > 0: req_string_list.append(entry) i = 0 flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList", self.mCurrentPackage.getName() + " requires: " + str(req_string_list)) while len(req_string_list) > i: if PkgDB().exists(req_string_list[i]): new_filter = [] new_agent = DepResolutionSystem().createAgent(req_string_list[i]) if len(req_string_list) > i+1: if req_string_list[i+1] == "=": ver_to_filt = req_string_list[i+2] new_filter = Filter("Version", lambda x: x == ver_to_filt) elif req_string_list[i+1] == "<=": ver_to_filt = req_string_list[i+2] new_filter = Filter("Version", lambda x: x <= ver_to_filt) elif req_string_list[i+1] == ">=": ver_to_filt = req_string_list[i+2] new_filter = Filter("Version", lambda x: x >= ver_to_filt) else: i+=1 else: i+=1 dep_list.append(new_agent) if new_filter: i+=3 new_agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "PkgAgent.makeDependList", "Package %s depends on %s but does not seem to be installed." % (self.mName, str(req_string_list[i]))) flagDBG().out(flagDBG.VERBOSE, "PkgAgent.makeDependList", "List is:" + str([pkg.getName() for pkg in dep_list])) self.mAgentDependList = dep_list def filtersChanged(self,packageList): tf_list = [self.mFiltersChanged] if self.mName not in packageList: packageList.append(self.mName) for pkg in self.mAgentDependList: tf_list.append(pkg.filtersChanged(packageList)) return True in tf_list def getCurrentPackageList(self, packageList): pkgs = [] if self.mName not in packageList: flagDBG().out(flagDBG.VERBOSE, "PkgAgent.getCurrentPackageList", "Package: %s" % self.mName) pkgs.append(self.mCurrentPackage) packageList.append(self.mName) for pkg in self.mAgentDependList: pkgs.extend(pkg.getCurrentPackageList(packageList)) return pkgs # current pkginfo for me def getCurrentPkgInfo(self): return self.mCurrentPackage # Someone else usually places these on me # I keep track of those separately def addFilter(self, filter): flagDBG().out(flagDBG.VERBOSE, "PkgAgent.addFilter", "Adding a Filter to %s" % self.mName) self.mFiltersChanged = True self.mFilterList.append(filter) def removeCurrentPackage(self): flagDBG().out(flagDBG.VERBOSE, "PkgAgent.removeCurrentPackage", "Removing current package of %s" % self.mName) if self.mViablePackageList: ret_val = self.mViablePackageList[0] in self.mBasePackageList del self.mViablePackageList[0] if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] return ret_val def update(self, agentVisitedList, agentChangeList): if self.mName in agentVisitedList: return agentVisitedList.append(self.mName) if self.mFiltersChanged: self.mFiltersChanged = False self.updateFilters() # TODO: checkFilters and add them # if a pkg is in visitedList then add yourself to agentChangeList for pkg in self.mAgentDependList: pkg.update(agentVisitedList, agentChangeList) return def updateFilters(self): for filt in self.mFilterList: self.mViablePackageList = filt.filter(self.mViablePackageList) if len(self.mViablePackageList) > 0: self.mCurrentPackage = self.mViablePackageList[0] else: self.mCurrentPackage = [] def reset(self): flagDBG().out(flagDBG.VERBOSE, "PkgAgent.reset", "Resetting package: %s" % self.mName) self.mViablePackageList = self.mBasePackageList if self.mViablePackageList: self.mCurrentPacakge = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mFilterList = DepResolutionSystem().getFilters() self.mAgentDependList = [] self.mFiltersChanged = True return class Filter: """ A single Filter that knows how to filter the list it recieves Will be inheireted....?..? """ def __init__(self, variableName, testCallable): self.mVarName = variableName self.mTestCallable = testCallable def filter(self, pkg_info_list): ret_pkg_list = [] # Filter first for pkg in pkg_info_list: var = pkg.getVariable(self.mVarName) if self.mTestCallable(var): ret_pkg_list.append(pkg) # Now sort ret_pkg_list.sort(lambda lhs,rhs: cmp(lhs.getVariable(self.mVarName), rhs.getVariable(self.mVarName))) return ret_pkg_list #requires: qt == 4.5 #Filter("Version", lambda x: x <= "4.5") #Filter("Version", lambda x: x <= "4.5") class PkgDB(object): """ Holds all the neccesary information to evaluate itself when needed. Is in charge of holding a list of PkgInfo's that contain info about the package. """ __initialized = False def __init__(self): if self.__initialized: return self.__initialized = True self.mPkgInfos = {} # {pkg_name: List of package infos} self.populatePkgInfoDBPcFiles() self.populatePkgInfoDBFpcFiles() def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def printAllPackages(self): list_of_package_names = [] for pkg in self.mPkgInfos: list_of_package_names.append(pkg) for name in list_of_package_names: print name sys.exit(0) def getVariables(self, name, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariable", "Finding " + str(variable_list) + " in " + str(name)) ret_list = [] for var in variable_list: if self.mPkgInfos.has_key(name): ret_list.extend(self.mPkgInfos[name][0].getVariable(var)) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariable", "Package %s not found." % name) return ret_list def checkPackage(self, name): flagDBG().out(flagDBG.INFO, "PkgDB.checkPackage", "Finding " + str(name)) if self.mPkgInfos.has_key(name): return True else: flagDBG().out(flagDBG.ERROR, "PkgDB.CheckPackage", "Package %s not found." % name) return False def getVariablesAndDeps(self, pkg_list, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariablesAndDeps", "Finding " + str(variable_list) + " in " + str(pkg_list)) if DepResolutionSystem().checkPrivateRequires(): temp_var_list = [] for var in variable_list: temp_var_list.append(var.join(".private")) variable_list = variable_list + temp_var_list for name in pkg_list: if self.mPkgInfos.has_key(name): agent = DepResolutionSystem().createAgent(name) DepResolutionSystem().addResolveAgent(agent) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariablesAndDeps", "Package %s not found." % name) DepResolutionSystem().resolveDeps() pkgs = DepResolutionSystem().getPackages() var_list = [] for pkg in pkgs: if pkg: for var in variable_list: var_list.extend(pkg.getVariable(var).split(' ')) return var_list def getPkgInfos(self, name): if self.mPkgInfos.has_key(name): return self.mPkgInfos[name] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getPkgInfos", "Package %s not found." % name) def exists(self, name): return self.mPkgInfos.has_key(name) def getInfo(self, name): if self.mPkgInfos.has_key(name): return [pkg.getInfo() for pkg in self.mPkgInfos[name]] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getInfo", "Package %s not found." % name) def buildPcFileDict(self): """ Builds up a dictionary of {name: list of files for name} """ pc_dict = {} for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.pc")) # List of .pc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these pc files: %s" % str(glob_list)) for g in glob_list: # Get key name and add file to value list in dictionary key = os.path.basename(g)[:-3] # Strip .pc off the filename...rstrip no worky pc_dict.setdefault(key,[]).append(g) for f in Utils.getFileList(): if f.endswith(".pc"): key = os.path.basename(f)[:-3] # Strip .pc off the filename...rstrip no worky pc_dict.setdefault(key,[]).append(f) return pc_dict # { "key", [ "list", "of", "corresponding", "pc", "files"] } def populatePkgInfoDBPcFiles(self): dict_to_pop_from = self.buildPcFileDict() for (pkg,files) in dict_to_pop_from.iteritems(): for f in files: self.mPkgInfos.setdefault(pkg,[]).append(PkgInfo(pkg, f, "pc")) def buildFpcFileList(self): """ Builds up a dictionary of {name: list of files for name} """ file_list = [] for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.fpc")) # List of .fpc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these fpc files: %s" % str(glob_list)) for g in glob_list: file_list.append(g) for f in Utils.getFileList(): if f.endswith(".fpc"): file_list.append(f) return file_list # [ "list", "of", "fpc", "files"] def populatePkgInfoDBFpcFiles(self): list_to_add = self.buildFpcFileList() for filename in list_to_add: var_dict = Utils.parsePcFile(filename) if not var_dict.has_key("Provides"): flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Provides" % str(filename)) continue if not var_dict.has_key("Arch"): flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Arch" % str(filename)) continue provides_string = var_dict["Provides"] provides_string = provides_string.replace(',', ' ') provides_string = provides_string.replace('(', ' ') provides_string = provides_string.replace(')', ' ') for key in provides_string.split(" "): if len(key) > 0: self.mPkgInfos.setdefault(key,[]).append(PkgInfo(key, filename, "fpc", var_dict)) class PkgInfo: """ Holds the information for a package file on the system. These however are evaluated when the need arises. """ def __init__(self, name, file, type, varDict={}): self.mName = name self.mFile = file self.mIsEvaluated = False self.mType = type self.mVariableDict = varDict if self.mType == "fpc": self.mIsEvaluated = True def getVariable(self, variable): self.evaluate() return self.mVariableDict.get(variable,"") def getName(self): return self.mName def evaluate(self): if not self.mIsEvaluated: flagDBG().out(flagDBG.INFO, "PkgInfo.evaluate", "Evaluating %s" % self.mName) self.mVariableDict= Utils.parsePcFile(self.mFile) self.mIsEvaluated = True def getInfo(self): self.evaluate() return self.mVariableDict class OptionsEvaluator: def __init__(self): #self.mOptParser = self.GetOptionParser() #self.mOptParser.print_help() if len(sys.argv) < 2: self.printHelp() #(self.mOptions, self.mArgs) = self.mOptParser.parse_args() #if self.mOptions.version: # print "%s.%s.%s" % Utils.getFlagpollVersion() # sys.exit(0) #if len(self.mArgs) < 1: # self.mOptParser.print_help() # sys.exit(1) # This is only the args....(first arg is stripped) def evaluateArgs(self, args): # Catch any args that need to be tended to immediately # Process args in the order that they were recieved. Some options are not # shown below because they are sub-options of an option below (--strip-dups) for option in args: if option.startswith("--debug"): flagDBG().setLevel(flagDBG.VERBOSE) elif option.startswith("--from-file"): val_start = option.find('=') + 1 file = option[val_start:] Utils.EXTRA_FLAGPOLL_FILES = Utils.EXTRA_FLAGPOLL_FILES + ":" + file elif option.startswith("--help"): self.printHelp() sys.exit(0) elif option.startswith("--version"): print "%s.%s.%s" % Utils.getFlagpollVersion() sys.exit(0) elif option.startswith("--list-all"): PkgDB().printAllPackages() continue agent = None num_args = len(args) curr_arg = 0 output_options = [] # (option, name/"") important_options = [] # ones that need special attention while curr_arg < num_args: if args[curr_arg].startswith("--atleast-version"): val_start = args[curr_arg].find('=') + 1 atleast_version = args[curr_arg][val_start:] atleast_filter = Filter("Version", lambda x: x >= atleast_version) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(atleast_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --at-least-version") continue if args[curr_arg].startswith("--cflags-only-I"): output_options.append(("cflags-only-I", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--cflags-only-other"): output_options.append(("cflags-only-other", "")) curr_arg = curr_arg + 1 continue #This could be the catch all for the above ones to and then filter based on what is asked... #For clarity of course... if args[curr_arg].startswith("--cflags"): output_options.append(("cflags", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--extra-paths"): val_start = args[curr_arg].find('=') + 1 paths = args[curr_arg][val_start:] Utils.EXTRA_FLAGPOLL_SEARCH_PATHS = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS + ":" + paths curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--exact-version"): val_start = args[curr_arg].find('=') + 1 exact_version = args[curr_arg][val_start:] exact_filter = Filter("Version", lambda x: x == exact_version) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(exact_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --exact-version") continue if args[curr_arg].startswith("--exists"): important_options.append("exists") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--from-file"): val_start = args[curr_arg].find('=') + 1 file = args[curr_arg][val_start:] file_filter = Filter("XXFlagpollFilenameXX", lambda x: x == file) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(file_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --from-file") continue if args[curr_arg].startswith("--info"): important_options.append("info") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--keep-dups"): Utils.setKeepDups(True) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-l"): output_options.append(("libs-only-l", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-L"): output_options.append(("libs-only-L", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-other"): output_options.append(("libs-only-other", "")) curr_arg = curr_arg + 1 continue #This could be the catch all for the above ones to and then filter based on what is asked... if args[curr_arg].startswith("--libs"): output_options.append(("libs", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--require-all"): rlen = len("--require-all") req_string = args[curr_arg][rlen:] req_string = req_string.replace('-','_') curr_arg = curr_arg + 1 if req_string.find("<=") != -1: op_start = req_string.find("<=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x: x <= req_val) DepResolutionSystem().addFilter(new_filter) continue if req_string.find(">=") != -1: op_start = req_string.find(">=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x: x >= req_val) DepResolutionSystem().addFilter(new_filter) continue if req_string.find(">") != -1: op_start = req_string.find(">") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x > req_val) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("<") != -1: op_start = req_string.find("<") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x < req_val) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("=") != -1: op_start = req_string.find("=") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x == req_val) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("=") == -1: new_filter = Filter(req_string, lambda x: len(x) > 0) DepResolutionSystem().addFilter(new_filter) continue continue if args[curr_arg].startswith("--require-"): rlen = len("--require-") req_string = args[curr_arg][rlen:] req_string = req_string.replace('-','_') curr_arg = curr_arg + 1 if agent is None: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --require") if req_string.find("<=") != -1: op_start = req_string.find("<=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x: x <= req_val) agent.addFilter(new_filter) continue if req_string.find(">=") != -1: op_start = req_string.find(">=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x: x >= req_val) agent.addFilter(new_filter) continue if req_string.find(">") != -1: op_start = req_string.find(">") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x > req_val) agent.addFilter(new_filter) continue if req_string.find("<") != -1: op_start = req_string.find("<") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x < req_val) agent.addFilter(new_filter) continue if req_string.find("=") != -1: op_start = req_string.find("=") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x == req_val) agent.addFilter(new_filter) continue if req_string.find("=") == -1: new_filter = Filter(req_string, lambda x: len(x) > 0) agent.addFilter(new_filter) continue continue if args[curr_arg].startswith("--no-deps"): if agent is not None: agent.setCheckDepends(False) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --no-deps") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--require="): val_start = args[curr_arg].find('=') + 1 req_var = args[curr_arg][val_start:] curr_arg = curr_arg + 1 DepResolutionSystem().makeRequireFilter(req_var) continue if args[curr_arg].startswith("--modversion"): if agent is not None: output_options.append(("Version", agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --modversion") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--max-release"): val_start = args[curr_arg].find('=') + 1 max_release = args[curr_arg][val_start:] max_filter = Filter("Version", lambda x: x.startswith(max_release)) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(max_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --max-release") continue if args[curr_arg].startswith("--static"): DepResolutionSystem().setPrivateRequires(True) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--variable"): val_start = args[curr_arg].find('=') + 1 fetch_var = args[curr_arg][val_start:] if agent is not None: output_options.append((fetch_var, agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --variable") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--get-all"): rlen = len("--get-all-") get_string = args[curr_arg][rlen:] get_string = get_string.replace('-','_') output_options.append((get_string, "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--get"): rlen = len("--get-") get_string = args[curr_arg][rlen:] get_string = get_string.replace('-','_') if agent is not None: output_options.append((get_string, agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --get") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--concat"): important_options.append("concat") curr_arg = curr_arg + 1 continue if not args[curr_arg].startswith("--"): name = args[curr_arg] curr_arg = curr_arg + 1 if PkgDB().checkPackage(name): agent = DepResolutionSystem().createResolveAgent(name) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Package %s" % name) sys.exit(1) continue if args[curr_arg] != "--debug": flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Option: %s" % args[curr_arg]) curr_arg = curr_arg + 1 DepResolutionSystem().resolveDeps() pkgs = DepResolutionSystem().getPackages() for p in pkgs: if not p: for option in important_options: if option == "exists": print "no" sys.exit(1) flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found") if len(pkgs) == 0: for option in important_options: if option == "exists": print "no" sys.exit(1) flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found") sys.exit(1) concat = False for option in important_options: if option == "exists": print "yes" return sys.exit(0) # already checked for none above if option == "concat": concat = True if option == "info": pkg_info_list = [] for pkg in pkgs: #MAKE PRETTY print pkg.getInfo() #print output_options #output_options = [] #output_single = [] #Process options here.............. concat_list = [] if concat: print_option = lambda x: concat_list.extend(x) else: print_option = lambda x: Utils.printList(x) for option in output_options: if option[0] == "cflags": print_option(Utils.stripDupIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "cflags-only-I": print_option(Utils.cflagsOnlyDirIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "cflags-only-other": print_option(Utils.cflagsOnlyOtherIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "libs-only-l": print_option(Utils.libsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs-only-L": print_option(Utils.libDirsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs-only-other": print_option(Utils.libsOnlyOtherLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs": print_option(Utils.stripDupLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) else: print_option(Utils.stripDupInList(self.getVarFromPkgs(option[0], pkgs, option[1]))) if concat: Utils.printList(Utils.stripDupInList(concat_list)) def getVarFromPkgs(self, var, pkgs, pkg_name=""): var_list = [] ext_vars = [] if var == "Libs": if DepResolutionSystem().checkPrivateRequires: ext_vars.append("Libs.private") if pkg_name == "": for pkg in pkgs: if pkg: var_list.extend(pkg.getVariable(var).split(' ')) for extra_var in ext_vars: var_list.extend(pkg.getVariable(extra_var).split(' ')) else: for pkg in pkgs: if pkg: if pkg.getName() == pkg_name: var_list.extend(pkg.getVariable(var).split(' ')) for extra_var in ext_vars: var_list.extend(pkg.getVariable(extra_var).split(' ')) return var_list def printHelp(self): print "usage: flagpoll pkg options [pkg options] [generic options]" print " " print "generic options:" print " --help show this help message and exit" print " --version output version of flagpoll" print " --list-all list all known packages" print " --debug show verbose debug information" print " --extra-paths=EXTRA_PATHS" print " extra paths for flagpoll to search for meta-data files" print " --concat concatenate all output and output as one line" print " --keep-dups do not strip out all duplicate info from options" print " --info show information for packages" print " " print "options:" print " --modversion output version for package" print " --require=REQUIRE adds additional requirements for packages ex. 32/64" print " --libs output all linker flags" print " --static output linker flags for static linking" print " --libs-only-l output -l flags" print " --libs-only-other output other libs (e.g. -pthread)" print " --libs-only-L output -L flags" print " --cflags output all pre-processor and compiler flags" print " --cflags-only-I output -I flags" print " --cflags-only-other output cflags not covered by the cflags-only-I option" print " --exists return 0 if the module(s) exist" print " --from-file=FILE use the specified FILE for the package" #print " --print-provides print which packages the package provides" #print " --print-requires print which packages the package requires" print " --no-deps do not lookup dependencies for the package" print " --atleast-version=ATLEAST_VERSION" print " return 0 if the module is at least version" print " ATLEAST_VERSION" print " --exact-version=EXACT_VERSION" print " return 0 if the module is exactly version" print " EXACT_VERSION" print " --max-release=MAX_RELEASE" print " return 0 if the module has a release that has a" print " version of MAX_RELEASE and will return the max" print " --variable=VARIABLE get the value of a variable" print " " print "dynamic options(replace VAR with a variable you want to get/filter on)" print " NOTE: replace underscores with dashes in VAR" print " NOTE: quotes are needed around <,>,= combinations" print " --get-VAR get VAR from package" print " --get-all-VAR get VAR from package and its deps" print " --require-VAR[<,>,=VAL]" print " require that a var is defined for a package" print " or optionally use equality operators against VAL" print " --require-all-VAR[<,>,=VAL]" print " require that a var is defined for all packages" print " or optionally use equality operators against VAL" sys.exit(0) def main(): # GO! # Initialize singletons and the start evaluating #print sys.argv[1:] my_dbg = flagDBG() my_dep_system = DepResolutionSystem() opt_evaluator = OptionsEvaluator() opt_evaluator.evaluateArgs(sys.argv[1:]) sys.exit(0) if __name__ == "__main__": main()
Python
#!/usr/bin/env python from distutils.core import setup setup( name='flagpoll', version='0.6.1', description='Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software.', author='Daniel E. Shipton', author_email='dshipton@infiscape.com', license='GPL', url='https://realityforge.vrsource.org/view/FlagPoll/WebHome', download_url='https://realityforge.vrsource.org/view/FlagPoll/FlagpollDownloads', scripts=['flagpoll'], long_description = "Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software. Think of it as the rpm of software development. It enables developers total control over which packages, versions, architectures, etc. that they want to use meta-data from.", data_files=[('share/flagpoll', ['flagpoll.fpc']), ('share/man/man1', ['flagpoll.1']), ('share/aclocal', ['flagpoll.m4'])] )
Python
#!/usr/bin/env python # ----------------------------------------------------------------- # # Flagpoll: A tool to extract flags from installed applications # for compiling, settting variables, etc. # # Original Authors: # Daniel E. Shipton <dshipton@gmail.com> # # Flagpoll is Copyright (C) 2006 by Daniel E. Shipton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to: # Free SoftwareFoundation, Inc. # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # # ----------------------------------------------------------------- from optparse import OptionParser import sys, os, glob, os.path, copy, platform pj = os.path.join #################################################################### # SNAGGED FROM PYTHON 2.4 for versions under 2.4 #################################################################### import re as _re class _multimap: """Helper class for combining multiple mappings. Used by .{safe_,}substitute() to combine the mapping and keyword arguments. """ def __init__(self, primary, secondary): self._primary = primary self._secondary = secondary def __getitem__(self, key): try: return self._primary[key] except KeyError: return self._secondary[key] class _TemplateMetaclass(type): pattern = r""" %(delim)s(?: (?P<escaped>%(delim)s) | # Escape sequence of two delimiters (?P<named>%(id)s) | # delimiter and a Python identifier {(?P<braced>%(id)s)} | # delimiter and a braced identifier (?P<invalid>) # Other ill-formed delimiter exprs ) """ def __init__(cls, name, bases, dct): super(_TemplateMetaclass, cls).__init__(name, bases, dct) if 'pattern' in dct: pattern = cls.pattern else: pattern = _TemplateMetaclass.pattern % { 'delim' : _re.escape(cls.delimiter), 'id' : cls.idpattern, } cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE) class Template: """A string class for supporting $-substitutions.""" __metaclass__ = _TemplateMetaclass delimiter = '$' idpattern = r'[_a-z][_a-z0-9]*' def __init__(self, template): self.template = template # Search for $$, $identifier, ${identifier}, and any bare $'s def _invalid(self, mo): i = mo.start('invalid') lines = self.template[:i].splitlines(True) if not lines: colno = 1 lineno = 1 else: colno = i - len(''.join(lines[:-1])) lineno = len(lines) raise ValueError('Invalid placeholder in string: line %d, col %d' % (lineno, colno)) def substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): # Check the most common path first. named = mo.group('named') or mo.group('braced') if named is not None: val = mapping[named] # We use this idiom instead of str() because the latter will # fail if val is a Unicode containing non-ASCII characters. return '%s' % val if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: self._invalid(mo) raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) def safe_substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): named = mo.group('named') if named is not None: try: # We use this idiom instead of str() because the latter # will fail if val is a Unicode containing non-ASCII return '%s' % mapping[named] except KeyError: return self.delimiter + named braced = mo.group('braced') if braced is not None: try: return '%s' % mapping[braced] except KeyError: return self.delimiter + '{' + braced + '}' if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: return self.delimiter raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) #################################################################### # End Snagging #################################################################### class Utils: # Holds collection of small utility functions EXTRA_FLAGPOLL_SEARCH_PATHS = "" EXTRA_FLAGPOLL_FILES = "" path_list_cache = None # Cache of found path lists. (only calcuate once) KEEP_DUPS = False def getFlagpollVersion(): FLAGPOLL_MAJOR_VERSION = 0 FLAGPOLL_MINOR_VERSION = 6 FLAGPOLL_PATCH_VERSION = 1 return ( FLAGPOLL_MAJOR_VERSION, FLAGPOLL_MINOR_VERSION, FLAGPOLL_PATCH_VERSION ) getFlagpollVersion = staticmethod(getFlagpollVersion) def getPathList(): if None != Utils.path_list_cache: return Utils.path_list_cache #TODO: expand LD_LIBRARY_PATH to 64/32/etc??? pkg_cfg_dir = [] flg_cfg_dir = [] ld_path = [] if os.environ.has_key("PKG_CONFIG_PATH"): pkg_cfg_dir = os.environ["PKG_CONFIG_PATH"].split(os.pathsep) if os.environ.has_key("FLAGPOLL_PATH"): flg_cfg_dir = os.environ["FLAGPOLL_PATH"].split(os.pathsep) if os.environ.has_key("LD_LIBRARY_PATH"): ld_path = os.environ["LD_LIBRARY_PATH"].split(os.pathsep) ld_path_pkg = [pj(p,'pkgconfig') for p in ld_path] ld_path_flg = [pj(p,'flagpoll') for p in ld_path] ld_path = [] ld_path.extend(ld_path_pkg) ld_path.extend(ld_path_flg) extra_paths = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS.split(os.pathsep) path_list = ["/usr/lib64/pkgconfig", "/usr/lib/pkgconfig", "/usr/share/pkgconfig", "/usr/lib64/flagpoll", "/usr/lib/flagpoll", "/usr/share/flagpoll"] path_list.extend(pkg_cfg_dir) path_list.extend(flg_cfg_dir) path_list.extend(extra_paths) path_list.extend(ld_path) flagDBG().out(flagDBG.VERBOSE, "Utils.getPathList", "Potential path list: " + str(path_list)) path_list = [p for p in path_list if os.path.exists(p)] flagDBG().out(flagDBG.INFO, "Utils.getPathList", "Using path list: " + str(path_list)) Utils.path_list_cache = path_list return path_list getPathList = staticmethod(getPathList) def getFileList(): flist = Utils.EXTRA_FLAGPOLL_FILES.split(":") filelist = [] for f in flist: if os.path.isfile(f): filelist.append(f) return filelist getFileList = staticmethod(getFileList) def setKeepDups(keep_dups): Utils.KEEP_DUPS = keep_dups setKeepDups = staticmethod(setKeepDups) def stripDupInList(gen_list): new_list = [] for item in gen_list: item = item.strip() if Utils.KEEP_DUPS: if len(item) > 0: new_list.append(item) continue if item not in new_list: if len(item) > 0: new_list.append(item) return new_list stripDupInList = staticmethod(stripDupInList) def stripDupLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] dir_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-L") or flg.startswith("-R"): dir_list.append(flg) else: lib_list.append(flg) new_list = dir_list + lib_list return Utils.stripDupInList(new_list) stripDupLinkerFlags = staticmethod(stripDupLinkerFlags) def stripDupIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] extra_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-I"): inc_list.append(flg) else: extra_list.append(flg) extra_list.sort() new_list = inc_list + extra_list return Utils.stripDupInList(new_list) stripDupIncludeFlags = staticmethod(stripDupIncludeFlags) def cflagsOnlyDirIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-I"): inc_list.append(flg) return Utils.stripDupInList(inc_list) cflagsOnlyDirIncludeFlags = staticmethod(cflagsOnlyDirIncludeFlags) def cflagsOnlyOtherIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though extra_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if not flg.startswith("-I"): extra_list.append(flg) return Utils.stripDupInList(extra_list) cflagsOnlyOtherIncludeFlags = staticmethod(cflagsOnlyOtherIncludeFlags) def libsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-l"): lib_list.append(flg) return Utils.stripDupInList(lib_list) libsOnlyLinkerFlags = staticmethod(libsOnlyLinkerFlags) def libsOnlyOtherLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though other_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if not flg.startswith("-l") and not flg.startswith("-L") and not flg.startswith("-R"): other_list.append(flg) return Utils.stripDupInList(other_list) libsOnlyOtherLinkerFlags = staticmethod(libsOnlyOtherLinkerFlags) def libDirsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though dir_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-L") or flg.startswith("-R"): dir_list.append(flg) return Utils.stripDupInList(dir_list) libDirsOnlyLinkerFlags = staticmethod(libDirsOnlyLinkerFlags) def printList(gen_list): list_string = "" for item in gen_list: if len(item) > 0: list_string+=str(item) list_string+=" " print list_string.strip() printList = staticmethod(printList) def parsePcFile(filename): lines = open(filename).readlines() fvars = {} fvars["XXFlagpollFilenameXX"] = filename lokals = {} lokals["fp_file_cwd"] = str(filename[:- ((len(os.path.basename(filename) ) + 1))]) lines.append("prefix: ${prefix}") for line in lines: line = line.strip() if not line: continue if line.startswith("#"): continue eq_pos = line.find('=') col_pos = line.find(':') if eq_pos < col_pos and eq_pos != -1 or col_pos == -1 and eq_pos !=-1: # local variable name, val = line.split('=', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(lokals) except ValueError: flagDBG().out(flagDBG.WARN, "PkgInfo.parse", "%s has an invalid metadata file" % filename) lokals[name] = val if col_pos < eq_pos and col_pos != -1 or eq_pos == -1 and col_pos !=-1: # exported variable name, val = line.split(':', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(lokals) except ValueError: flagDBG().out(flagDBG.ERROR, "PkgInfo.parse", "%s has an invalid metadata file" % filename) fvars[name] = val return fvars parsePcFile = staticmethod(parsePcFile) class flagDBG(object): # Logging class is really easy to use # Levels: # 0 - VERBOSE # 1 - INFO # 2 - WARN # 3 - ERROR VERBOSE=0 INFO=1 WARN=2 ERROR=3 __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if flagDBG.__initialized: return flagDBG.__initialized = True self.mLevel = self.WARN self.mLevelList = ["VERBOSE","INFO","WARN","ERROR"] def setLevel(self, level): if level <= 3: self.mLevel = level def out(self, level, obj, message): if level == self.ERROR: if self.mLevel == self.VERBOSE: print self.mLevelList[level] + ":" + str(obj) + ": " + str(message) else: print self.mLevelList[level] + ": " + str(message) sys.exit(1) if level >= self.mLevel: print self.mLevelList[level] + ":" + str(obj) + ": " + str(message) class DepResolutionSystem(object): """ You add PkgAgents with Filters into system and call resolve() you can check for succes by depsSatisfied() and get the list of packages that work back by calling getPackages() """ __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if DepResolutionSystem.__initialized: return DepResolutionSystem.__initialized = True self.mResolveAgents = [] self.mAgentDict = {} self.mFilters = [] self.mResolveAgentFilters = [] self.mInvalidPackageList = [] self.mSatisfied = False self.mAgentChangeList = [] # list of those responsible for adding Filters # to agents in higher in the chain than them # these are the first agents to ask that they pick # the next best package of them self.mAgentsVisitedList = [] # list of Agents that have been visited self.mResolvedPackageList = [] # list that is generated when deps are satified self.mCheckPrivateRequires = False self.mMadeDependList = False def getFilters(self): return self.mFilters def addFilter(self, filter): self.mFilters.append(filter) def addResolveAgentFilter(self, filter): self.mResolveAgentFilters.append(filter) def makeRequireFilter(self, requires): arch_list = [] arch_list.append("no_arch") arch_list.append("") if platform.system() == "Linux": if requires == "64": arch_list.append("x86_64") if requires == "32": arch_list.append("i386") arch_list.append("i586") arch_list.append("i686") if platform.system() == "Darwin": if requires == "64": arch_list.append("ppc64") if requires == "32": arch_list.append("ppc") new_filter = Filter("Arch", lambda x: x in arch_list) self.addFilter(new_filter) def createAgent(self, name): if self.checkAgentExists(name): return self.getAgent(name) else: agent = PkgAgent(name) flagDBG().out(flagDBG.INFO, "DepResSys.createAgent", "Adding %s" % name) self.addNewAgent(agent) return agent def createResolveAgent(self, name): if self.checkAgentExists(name): return self.getAgent(name) else: agent = PkgAgent(name) flagDBG().out(flagDBG.INFO, "DepResSys.createResloveAgent", "Adding %s" % name) self.addResolveAgent(agent) return agent def setPrivateRequires( self, req ): self.mCheckPrivateRequires = req def checkPrivateRequires(self): return self.mCheckPrivateRequires def checkAgentExists(self, name): return self.mAgentDict.has_key(name) def getAgent(self, name): if self.mAgentDict.has_key(name): return self.mAgentDict[name] else: flagDBG().out(flagDBG.ERROR, "DepResSys.getAgent", "Agent %s does not exist" % name) def addNewAgent(self, agent): if not self.checkAgentExists(agent): self.mAgentDict[agent.getName()] = agent def addResolveAgent(self, agent): if agent not in self.mResolveAgents: self.mResolveAgents.append(agent) for filt in self.mResolveAgentFilters: agent.addFilter(filt) def isSatisfied(self): return self.mSatisfied def updateResolvedPackages(self): pkg_list = [] agent_list = [] for agent in self.mResolveAgents: list_of_pkgs = agent.getCurrentPackageList(agent_list) pkg_list.extend(list_of_pkgs) self.mResolvedPackageList = pkg_list def getPackages(self): flagDBG().out(flagDBG.VERBOSE, "DepResSys.getPackages", "Generating list of valid packages ") #str([pkg.getCurrentPa.getName() for pkg in self.mResolvedPackageList])) # If this comes back empty then there isn't a valid set of packages to use self.updateResolvedPackages() return self.mResolvedPackageList def checkFiltersChanged(self): list_to_use = [] return True in [pkg.filtersChanged(list_to_use) for pkg in self.mResolveAgents] def resolveHelper(self): self.resolveAgentsChanged = True while self.resolveAgentsChanged: for agent in self.mResolveAgents: flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveHelper", "Updating " + agent.getName()) agent.update(self.mAgentsVisitedList, self.mAgentChangeList) self.resolveAgentsChanged = self.checkFiltersChanged() # Ask mResolveAgents if they are done(they ask sub people) unless they are # really above you in the walk # If there were changes...run update on mResolveAgents again # at the end ask for pkglist..if it comes back empty then we don't # have a usable configuration for those packages def resolveDeps(self): if not self.mMadeDependList: for agent in self.mResolveAgents: agent.makeDependList() self.mMadeDependList = True self.resolveHelper() self.updateResolvedPackages() # Check if the first round through we found something # Otherwise we need to start removing packages that aren't viable # during the loop self.mSatisfied = (len(self.mResolvedPackageList) != 0) # remove top of packages that added Filters. # then move on to resolving again # remove more if neccesary agentChangeNumber = 0 while not self.mResolvedPackageList: if(self.mAgentChangeList[agentChangeNumber]): if self.mAgentChangeList[agentChangeNumber] in self.mInvalidPackageList: agentChangeNumber+=1 else: if(self.mAgentChangeList[agentChangeNumber].getViablePackages()): flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveDeps", "Removing bad pkg from " + self.mAgentChangeList[agentChangeNumber].getName()) self.mInvalidPackageList.append(self.mAgentChangeList[agentChangeNumber].removeCurrentPackage()) else: flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveDeps", "No combinations.. Resetting " + self.mAgentChangeList[agentChangeNumber].getName()) self.mAgentChangeList[agentChangeNumber].reset() agentChangeNumber+=1 self.resolveHelper() self.updateResolvedPackages() self.mSatisfied = (len(self.mResolvedPackageList) != 0) return class PkgAgent: """ Agent that keeps track of the versions for a package given some filters and the addition of Filters """ # Makes a PkgAgent that finds its current package with the version reqs def __init__(self, name): if DepResolutionSystem().checkAgentExists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "Package Agent %s already exists" % self.mName) self.mName = name flagDBG().out(flagDBG.VERBOSE, "PkgAgent", "Creating:" + str(self.mName)) if not PkgDB().exists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "No info for package: %s" % self.mName) #XXX Doesn't keep filters added for a redo... DepResolutionSystem().addNewAgent(self) self.mFilterList = [] self.mFilterList.extend(DepResolutionSystem().getFilters()) self.mBasePackageList = PkgDB().getPkgInfos(name) for filt in self.mFilterList: self.mBasePackageList = filt.filter(self.mBasePackageList) if len(self.mBasePackageList) == 0: flagDBG().out(flagDBG.ERROR, "PkgAgent", "No viable packages for: %s" % self.mName) self.mViablePackageList = copy.deepcopy(self.mBasePackageList) if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mAgentDependList = [] # Agents that it depends on/needs to update #self.makeDependList() self.mFiltersChanged = True self.mCheckDepends = True def getName(self): return self.mName def setCheckDepends(self, tf): self.mCheckDepends = tf #Filter("Version", lambda x: x == "4.5") def makeDependList(self): if not self.mCheckDepends: self.mAgentDependList = [] return dep_list = [] if self.mCurrentPackage: req_string = self.mCurrentPackage.getVariable("Requires") if DepResolutionSystem().checkPrivateRequires(): req_string = req_string + " " + self.mCurrentPackage.getVariable("Requires.private") req_string = req_string.strip() if req_string == "": return req_string = req_string.replace(',', ' ') req_string = req_string.replace('(', ' ') req_string = req_string.replace(')', ' ') space_req_string_list = req_string.split(' ') req_string_list = [] for entry in space_req_string_list: if len(entry) > 0: req_string_list.append(entry) i = 0 flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList", self.mCurrentPackage.getName() + " requires: " + str(req_string_list)) while len(req_string_list) > i: if PkgDB().exists(req_string_list[i]): new_filter = [] new_agent = DepResolutionSystem().createAgent(req_string_list[i]) if len(req_string_list) > i+1: if req_string_list[i+1] == "=": ver_to_filt = req_string_list[i+2] new_filter = Filter("Version", lambda x: x == ver_to_filt) elif req_string_list[i+1] == "<=": ver_to_filt = req_string_list[i+2] new_filter = Filter("Version", lambda x: x <= ver_to_filt) elif req_string_list[i+1] == ">=": ver_to_filt = req_string_list[i+2] new_filter = Filter("Version", lambda x: x >= ver_to_filt) else: i+=1 else: i+=1 dep_list.append(new_agent) if new_filter: i+=3 new_agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "PkgAgent.makeDependList", "Package %s depends on %s but does not seem to be installed." % (self.mName, str(req_string_list[i]))) flagDBG().out(flagDBG.VERBOSE, "PkgAgent.makeDependList", "List is:" + str([pkg.getName() for pkg in dep_list])) self.mAgentDependList = dep_list def filtersChanged(self,packageList): tf_list = [self.mFiltersChanged] if self.mName not in packageList: packageList.append(self.mName) for pkg in self.mAgentDependList: tf_list.append(pkg.filtersChanged(packageList)) return True in tf_list def getCurrentPackageList(self, packageList): pkgs = [] if self.mName not in packageList: flagDBG().out(flagDBG.VERBOSE, "PkgAgent.getCurrentPackageList", "Package: %s" % self.mName) pkgs.append(self.mCurrentPackage) packageList.append(self.mName) for pkg in self.mAgentDependList: pkgs.extend(pkg.getCurrentPackageList(packageList)) return pkgs # current pkginfo for me def getCurrentPkgInfo(self): return self.mCurrentPackage # Someone else usually places these on me # I keep track of those separately def addFilter(self, filter): flagDBG().out(flagDBG.VERBOSE, "PkgAgent.addFilter", "Adding a Filter to %s" % self.mName) self.mFiltersChanged = True self.mFilterList.append(filter) def removeCurrentPackage(self): flagDBG().out(flagDBG.VERBOSE, "PkgAgent.removeCurrentPackage", "Removing current package of %s" % self.mName) if self.mViablePackageList: ret_val = self.mViablePackageList[0] in self.mBasePackageList del self.mViablePackageList[0] if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] return ret_val def update(self, agentVisitedList, agentChangeList): if self.mName in agentVisitedList: return agentVisitedList.append(self.mName) if self.mFiltersChanged: self.mFiltersChanged = False self.updateFilters() # TODO: checkFilters and add them # if a pkg is in visitedList then add yourself to agentChangeList for pkg in self.mAgentDependList: pkg.update(agentVisitedList, agentChangeList) return def updateFilters(self): for filt in self.mFilterList: self.mViablePackageList = filt.filter(self.mViablePackageList) if len(self.mViablePackageList) > 0: self.mCurrentPackage = self.mViablePackageList[0] else: self.mCurrentPackage = [] def reset(self): flagDBG().out(flagDBG.VERBOSE, "PkgAgent.reset", "Resetting package: %s" % self.mName) self.mViablePackageList = self.mBasePackageList if self.mViablePackageList: self.mCurrentPacakge = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mFilterList = DepResolutionSystem().getFilters() self.mAgentDependList = [] self.mFiltersChanged = True return class Filter: """ A single Filter that knows how to filter the list it recieves Will be inheireted....?..? """ def __init__(self, variableName, testCallable): self.mVarName = variableName self.mTestCallable = testCallable def filter(self, pkg_info_list): ret_pkg_list = [] # Filter first for pkg in pkg_info_list: var = pkg.getVariable(self.mVarName) if self.mTestCallable(var): ret_pkg_list.append(pkg) # Now sort ret_pkg_list.sort(lambda lhs,rhs: cmp(lhs.getVariable(self.mVarName), rhs.getVariable(self.mVarName))) return ret_pkg_list #requires: qt == 4.5 #Filter("Version", lambda x: x <= "4.5") #Filter("Version", lambda x: x <= "4.5") class PkgDB(object): """ Holds all the neccesary information to evaluate itself when needed. Is in charge of holding a list of PkgInfo's that contain info about the package. """ __initialized = False def __init__(self): if self.__initialized: return self.__initialized = True self.mPkgInfos = {} # {pkg_name: List of package infos} self.populatePkgInfoDBPcFiles() self.populatePkgInfoDBFpcFiles() def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def printAllPackages(self): list_of_package_names = [] for pkg in self.mPkgInfos: list_of_package_names.append(pkg) for name in list_of_package_names: print name sys.exit(0) def getVariables(self, name, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariable", "Finding " + str(variable_list) + " in " + str(name)) ret_list = [] for var in variable_list: if self.mPkgInfos.has_key(name): ret_list.extend(self.mPkgInfos[name][0].getVariable(var)) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariable", "Package %s not found." % name) return ret_list def checkPackage(self, name): flagDBG().out(flagDBG.INFO, "PkgDB.checkPackage", "Finding " + str(name)) if self.mPkgInfos.has_key(name): return True else: flagDBG().out(flagDBG.ERROR, "PkgDB.CheckPackage", "Package %s not found." % name) return False def getVariablesAndDeps(self, pkg_list, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariablesAndDeps", "Finding " + str(variable_list) + " in " + str(pkg_list)) if DepResolutionSystem().checkPrivateRequires(): temp_var_list = [] for var in variable_list: temp_var_list.append(var.join(".private")) variable_list = variable_list + temp_var_list for name in pkg_list: if self.mPkgInfos.has_key(name): agent = DepResolutionSystem().createAgent(name) DepResolutionSystem().addResolveAgent(agent) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariablesAndDeps", "Package %s not found." % name) DepResolutionSystem().resolveDeps() pkgs = DepResolutionSystem().getPackages() var_list = [] for pkg in pkgs: if pkg: for var in variable_list: var_list.extend(pkg.getVariable(var).split(' ')) return var_list def getPkgInfos(self, name): if self.mPkgInfos.has_key(name): return self.mPkgInfos[name] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getPkgInfos", "Package %s not found." % name) def exists(self, name): return self.mPkgInfos.has_key(name) def getInfo(self, name): if self.mPkgInfos.has_key(name): return [pkg.getInfo() for pkg in self.mPkgInfos[name]] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getInfo", "Package %s not found." % name) def buildPcFileDict(self): """ Builds up a dictionary of {name: list of files for name} """ pc_dict = {} for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.pc")) # List of .pc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these pc files: %s" % str(glob_list)) for g in glob_list: # Get key name and add file to value list in dictionary key = os.path.basename(g)[:-3] # Strip .pc off the filename...rstrip no worky pc_dict.setdefault(key,[]).append(g) for f in Utils.getFileList(): if f.endswith(".pc"): key = os.path.basename(f)[:-3] # Strip .pc off the filename...rstrip no worky pc_dict.setdefault(key,[]).append(f) return pc_dict # { "key", [ "list", "of", "corresponding", "pc", "files"] } def populatePkgInfoDBPcFiles(self): dict_to_pop_from = self.buildPcFileDict() for (pkg,files) in dict_to_pop_from.iteritems(): for f in files: self.mPkgInfos.setdefault(pkg,[]).append(PkgInfo(pkg, f, "pc")) def buildFpcFileList(self): """ Builds up a dictionary of {name: list of files for name} """ file_list = [] for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.fpc")) # List of .fpc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these fpc files: %s" % str(glob_list)) for g in glob_list: file_list.append(g) for f in Utils.getFileList(): if f.endswith(".fpc"): file_list.append(f) return file_list # [ "list", "of", "fpc", "files"] def populatePkgInfoDBFpcFiles(self): list_to_add = self.buildFpcFileList() for filename in list_to_add: var_dict = Utils.parsePcFile(filename) if not var_dict.has_key("Provides"): flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Provides" % str(filename)) continue if not var_dict.has_key("Arch"): flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Arch" % str(filename)) continue provides_string = var_dict["Provides"] provides_string = provides_string.replace(',', ' ') provides_string = provides_string.replace('(', ' ') provides_string = provides_string.replace(')', ' ') for key in provides_string.split(" "): if len(key) > 0: self.mPkgInfos.setdefault(key,[]).append(PkgInfo(key, filename, "fpc", var_dict)) class PkgInfo: """ Holds the information for a package file on the system. These however are evaluated when the need arises. """ def __init__(self, name, file, type, varDict={}): self.mName = name self.mFile = file self.mIsEvaluated = False self.mType = type self.mVariableDict = varDict if self.mType == "fpc": self.mIsEvaluated = True def getVariable(self, variable): self.evaluate() return self.mVariableDict.get(variable,"") def getName(self): return self.mName def evaluate(self): if not self.mIsEvaluated: flagDBG().out(flagDBG.INFO, "PkgInfo.evaluate", "Evaluating %s" % self.mName) self.mVariableDict= Utils.parsePcFile(self.mFile) self.mIsEvaluated = True def getInfo(self): self.evaluate() return self.mVariableDict class OptionsEvaluator: def __init__(self): #self.mOptParser = self.GetOptionParser() #self.mOptParser.print_help() if len(sys.argv) < 2: self.printHelp() #(self.mOptions, self.mArgs) = self.mOptParser.parse_args() #if self.mOptions.version: # print "%s.%s.%s" % Utils.getFlagpollVersion() # sys.exit(0) #if len(self.mArgs) < 1: # self.mOptParser.print_help() # sys.exit(1) # This is only the args....(first arg is stripped) def evaluateArgs(self, args): # Catch any args that need to be tended to immediately # Process args in the order that they were recieved. Some options are not # shown below because they are sub-options of an option below (--strip-dups) for option in args: if option.startswith("--debug"): flagDBG().setLevel(flagDBG.VERBOSE) elif option.startswith("--from-file"): val_start = option.find('=') + 1 file = option[val_start:] Utils.EXTRA_FLAGPOLL_FILES = Utils.EXTRA_FLAGPOLL_FILES + ":" + file elif option.startswith("--help"): self.printHelp() sys.exit(0) elif option.startswith("--version"): print "%s.%s.%s" % Utils.getFlagpollVersion() sys.exit(0) elif option.startswith("--list-all"): PkgDB().printAllPackages() continue agent = None num_args = len(args) curr_arg = 0 output_options = [] # (option, name/"") important_options = [] # ones that need special attention while curr_arg < num_args: if args[curr_arg].startswith("--atleast-version"): val_start = args[curr_arg].find('=') + 1 atleast_version = args[curr_arg][val_start:] atleast_filter = Filter("Version", lambda x: x >= atleast_version) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(atleast_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --at-least-version") continue if args[curr_arg].startswith("--cflags-only-I"): output_options.append(("cflags-only-I", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--cflags-only-other"): output_options.append(("cflags-only-other", "")) curr_arg = curr_arg + 1 continue #This could be the catch all for the above ones to and then filter based on what is asked... #For clarity of course... if args[curr_arg].startswith("--cflags"): output_options.append(("cflags", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--extra-paths"): val_start = args[curr_arg].find('=') + 1 paths = args[curr_arg][val_start:] Utils.EXTRA_FLAGPOLL_SEARCH_PATHS = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS + ":" + paths curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--exact-version"): val_start = args[curr_arg].find('=') + 1 exact_version = args[curr_arg][val_start:] exact_filter = Filter("Version", lambda x: x == exact_version) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(exact_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --exact-version") continue if args[curr_arg].startswith("--exists"): important_options.append("exists") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--from-file"): val_start = args[curr_arg].find('=') + 1 file = args[curr_arg][val_start:] file_filter = Filter("XXFlagpollFilenameXX", lambda x: x == file) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(file_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --from-file") continue if args[curr_arg].startswith("--info"): important_options.append("info") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--keep-dups"): Utils.setKeepDups(True) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-l"): output_options.append(("libs-only-l", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-L"): output_options.append(("libs-only-L", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-other"): output_options.append(("libs-only-other", "")) curr_arg = curr_arg + 1 continue #This could be the catch all for the above ones to and then filter based on what is asked... if args[curr_arg].startswith("--libs"): output_options.append(("libs", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--require-all"): rlen = len("--require-all") req_string = args[curr_arg][rlen:] req_string = req_string.replace('-','_') curr_arg = curr_arg + 1 if req_string.find("<=") != -1: op_start = req_string.find("<=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x: x <= req_val) DepResolutionSystem().addFilter(new_filter) continue if req_string.find(">=") != -1: op_start = req_string.find(">=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x: x >= req_val) DepResolutionSystem().addFilter(new_filter) continue if req_string.find(">") != -1: op_start = req_string.find(">") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x > req_val) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("<") != -1: op_start = req_string.find("<") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x < req_val) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("=") != -1: op_start = req_string.find("=") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x == req_val) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("=") == -1: new_filter = Filter(req_string, lambda x: len(x) > 0) DepResolutionSystem().addFilter(new_filter) continue continue if args[curr_arg].startswith("--require-"): rlen = len("--require-") req_string = args[curr_arg][rlen:] req_string = req_string.replace('-','_') curr_arg = curr_arg + 1 if agent is None: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --require") if req_string.find("<=") != -1: op_start = req_string.find("<=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x: x <= req_val) agent.addFilter(new_filter) continue if req_string.find(">=") != -1: op_start = req_string.find(">=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x: x >= req_val) agent.addFilter(new_filter) continue if req_string.find(">") != -1: op_start = req_string.find(">") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x > req_val) agent.addFilter(new_filter) continue if req_string.find("<") != -1: op_start = req_string.find("<") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x < req_val) agent.addFilter(new_filter) continue if req_string.find("=") != -1: op_start = req_string.find("=") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x == req_val) agent.addFilter(new_filter) continue if req_string.find("=") == -1: new_filter = Filter(req_string, lambda x: len(x) > 0) agent.addFilter(new_filter) continue continue if args[curr_arg].startswith("--no-deps"): if agent is not None: agent.setCheckDepends(False) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --no-deps") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--require="): val_start = args[curr_arg].find('=') + 1 req_var = args[curr_arg][val_start:] curr_arg = curr_arg + 1 DepResolutionSystem().makeRequireFilter(req_var) continue if args[curr_arg].startswith("--modversion"): if agent is not None: output_options.append(("Version", agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --modversion") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--max-release"): val_start = args[curr_arg].find('=') + 1 max_release = args[curr_arg][val_start:] max_filter = Filter("Version", lambda x: x.startswith(max_release)) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(max_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --max-release") continue if args[curr_arg].startswith("--static"): DepResolutionSystem().setPrivateRequires(True) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--variable"): val_start = args[curr_arg].find('=') + 1 fetch_var = args[curr_arg][val_start:] if agent is not None: output_options.append((fetch_var, agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --variable") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--get-all"): rlen = len("--get-all-") get_string = args[curr_arg][rlen:] get_string = get_string.replace('-','_') output_options.append((get_string, "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--get"): rlen = len("--get-") get_string = args[curr_arg][rlen:] get_string = get_string.replace('-','_') if agent is not None: output_options.append((get_string, agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --get") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--concat"): important_options.append("concat") curr_arg = curr_arg + 1 continue if not args[curr_arg].startswith("--"): name = args[curr_arg] curr_arg = curr_arg + 1 if PkgDB().checkPackage(name): agent = DepResolutionSystem().createResolveAgent(name) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Package %s" % name) sys.exit(1) continue if args[curr_arg] != "--debug": flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Option: %s" % args[curr_arg]) curr_arg = curr_arg + 1 DepResolutionSystem().resolveDeps() pkgs = DepResolutionSystem().getPackages() for p in pkgs: if not p: for option in important_options: if option == "exists": print "no" sys.exit(1) flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found") if len(pkgs) == 0: for option in important_options: if option == "exists": print "no" sys.exit(1) flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found") sys.exit(1) concat = False for option in important_options: if option == "exists": print "yes" return sys.exit(0) # already checked for none above if option == "concat": concat = True if option == "info": pkg_info_list = [] for pkg in pkgs: #MAKE PRETTY print pkg.getInfo() #print output_options #output_options = [] #output_single = [] #Process options here.............. concat_list = [] if concat: print_option = lambda x: concat_list.extend(x) else: print_option = lambda x: Utils.printList(x) for option in output_options: if option[0] == "cflags": print_option(Utils.stripDupIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "cflags-only-I": print_option(Utils.cflagsOnlyDirIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "cflags-only-other": print_option(Utils.cflagsOnlyOtherIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "libs-only-l": print_option(Utils.libsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs-only-L": print_option(Utils.libDirsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs-only-other": print_option(Utils.libsOnlyOtherLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs": print_option(Utils.stripDupLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) else: print_option(Utils.stripDupInList(self.getVarFromPkgs(option[0], pkgs, option[1]))) if concat: Utils.printList(Utils.stripDupInList(concat_list)) def getVarFromPkgs(self, var, pkgs, pkg_name=""): var_list = [] ext_vars = [] if var == "Libs": if DepResolutionSystem().checkPrivateRequires: ext_vars.append("Libs.private") if pkg_name == "": for pkg in pkgs: if pkg: var_list.extend(pkg.getVariable(var).split(' ')) for extra_var in ext_vars: var_list.extend(pkg.getVariable(extra_var).split(' ')) else: for pkg in pkgs: if pkg: if pkg.getName() == pkg_name: var_list.extend(pkg.getVariable(var).split(' ')) for extra_var in ext_vars: var_list.extend(pkg.getVariable(extra_var).split(' ')) return var_list def printHelp(self): print "usage: flagpoll pkg options [pkg options] [generic options]" print " " print "generic options:" print " --help show this help message and exit" print " --version output version of flagpoll" print " --list-all list all known packages" print " --debug show verbose debug information" print " --extra-paths=EXTRA_PATHS" print " extra paths for flagpoll to search for meta-data files" print " --concat concatenate all output and output as one line" print " --keep-dups do not strip out all duplicate info from options" print " --info show information for packages" print " " print "options:" print " --modversion output version for package" print " --require=REQUIRE adds additional requirements for packages ex. 32/64" print " --libs output all linker flags" print " --static output linker flags for static linking" print " --libs-only-l output -l flags" print " --libs-only-other output other libs (e.g. -pthread)" print " --libs-only-L output -L flags" print " --cflags output all pre-processor and compiler flags" print " --cflags-only-I output -I flags" print " --cflags-only-other output cflags not covered by the cflags-only-I option" print " --exists return 0 if the module(s) exist" print " --from-file=FILE use the specified FILE for the package" #print " --print-provides print which packages the package provides" #print " --print-requires print which packages the package requires" print " --no-deps do not lookup dependencies for the package" print " --atleast-version=ATLEAST_VERSION" print " return 0 if the module is at least version" print " ATLEAST_VERSION" print " --exact-version=EXACT_VERSION" print " return 0 if the module is exactly version" print " EXACT_VERSION" print " --max-release=MAX_RELEASE" print " return 0 if the module has a release that has a" print " version of MAX_RELEASE and will return the max" print " --variable=VARIABLE get the value of a variable" print " " print "dynamic options(replace VAR with a variable you want to get/filter on)" print " NOTE: replace underscores with dashes in VAR" print " NOTE: quotes are needed around <,>,= combinations" print " --get-VAR get VAR from package" print " --get-all-VAR get VAR from package and its deps" print " --require-VAR[<,>,=VAL]" print " require that a var is defined for a package" print " or optionally use equality operators against VAL" print " --require-all-VAR[<,>,=VAL]" print " require that a var is defined for all packages" print " or optionally use equality operators against VAL" sys.exit(0) def main(): # GO! # Initialize singletons and the start evaluating #print sys.argv[1:] my_dbg = flagDBG() my_dep_system = DepResolutionSystem() opt_evaluator = OptionsEvaluator() opt_evaluator.evaluateArgs(sys.argv[1:]) sys.exit(0) if __name__ == "__main__": main()
Python
#!/usr/bin/env python # ----------------------------------------------------------------- # # Flag Poll: A tool to extract flags from installed applications # for compiling, settting variables, etc. # # Original Authors: # Daniel E. Shipton <dshipton@gmail.com> # # Flag Poll is Copyright (C) 2006 by Daniel E. Shipton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to: # Free SoftwareFoundation, Inc. # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # # ----------------------------------------------------------------- """Makes a flagpole .fpc file from user input. v0.9 coded by Jeff Groves""" import os import sys import getopt ##String prompts for the input varPrompt = """Convience variables (one 'var_name= var_definition' per line,""" + \ """ empty line when done)""" namePrompt = "Formal Name" descriptionPrompt = "Description" urlPrompt = "URL" providesPrompt = "One or more names to look package up by: (Provides)" versionPrompt = "Version (x.y.z)" architecturePrompt = "Architecture" requirePrompt = "Requires" libPrompt = "Linker Flags (-lfoo -L/usr/lib)" staticLibPrompt = "Static Linking Flags/Libs (extra private libs)" compileFlagsPrompt = "Compile/Include Flags (-I/usr -fpge -O2)" fileNamePrompt = "FPC File's Name" def usage(): """Prints a list of acceptable arguments for fpcmaker.py.""" print """ Fpcmaker.py Options: -n, --name= : Sets %s -d, --description= : Sets %s -u, --url= : Sets %s -p, --provides= : Sets %s -v, --version= : Sets %s -a, --architecture= : Sets %s -r, --requires= : Sets %s -l, --libs= : Sets %s -c, --cflags= : Sets %s -s, --static= : Sets %s -f, --file= : Sets %s """ %(namePrompt, descriptionPrompt, urlPrompt, providesPrompt, versionPrompt, architecturePrompt, requirePrompt, libPrompt, compileFlagsPrompt, staticLibPrompt, fileNamePrompt) return def checkFileName(fileName): """Checks if the fpc file name's blank, contains slashes, or exists.""" nameCleared = False writeFile = True confirms = ['y', 'Y', 'yes', 'Yes'] ##Loops until the name clears or writing the file's aborted. while(not nameCleared and writeFile): ##If it's blank, give the option of aborting the program. if fileName == "": choice = raw_input("Do you want to abort writing the" + " .fpc file? (Y/N): ") if choice not in confirms: fileName = raw_input("Please enter a different name for the" + " .fpc file: ") else: writeFile = False ##If it contains slashes, ask for another name. elif '/' in fileName or '\\' in fileName: print "I can't write to %s because it contains slashes."%(fileName) fileName = raw_input("Please enter a different name for the" + " .fpc file: ") ##If it already exists, ask if they want to overwrite. ##If not, ask for another name. elif os.path.exists(fileName): choice = raw_input("The file %s already exists." %(fileName) + " Do you want to overwrite it? (Y/N): ") if choice not in confirms: fileName = raw_input("Please enter a different name for the" + " .fpc file: ") else: nameCleared = True else: nameCleared = True return [fileName, writeFile] ##Booleans for whether that argument was sent in the command line varSet = False providesSet = False nameSet = False descriptionSet = False urlSet = False architectureSet = False versionSet = False requiresSet = False libsSet = False compileFlagsSet = False staticLibSet = False fileNameSet = False ##Get the options & arguments sent. arguments = sys.argv[1:] try: opts, args = getopt.getopt(arguments, "p:n:u:d:a:r:v:l:c:s:f:", ["provides=", "name=", "url=", "description=", "architecture=", "requires=", "version=", "libs=", "cflags=", "static=", "file="]) ##Send them usage info if they enter a wrong argument except getopt.GetoptError: usage() sys.exit(2) for opt, arg in opts: if opt in ('-p', '--provides'): providesSet = True provides = arg elif opt in ('-n', '--name'): nameSet = True name = arg elif opt in ('-v', '--version'): versionSet = True version = arg elif opt in ('-u', '--url'): urlSet = True url = arg elif opt in ('-d', '--description'): descriptionSet = True description = arg elif opt in ('-a', '--architecture'): architectureSet = True architecture = arg elif opt in ('-r', '--requires'): requiresSet = True requires = arg elif opt in ('-l', '--libs'): libsSet = True libs = arg elif opt in ('-c', '--cflags'): compileFlagsSet = True compileFlags = arg elif opt in ('-s', '--static'): staticLibSet = True staticLib = arg elif opt in ('-f', '--file'): fileNameSet = True fileName = arg ##Grab any input not passed in the arguments from the user. if not varSet: varLine = None variables = "" print "%s:" %(varPrompt) while(varLine != ""): varLine = raw_input("") variables = variables + "%s\n" %(varLine) if not nameSet: name = raw_input("%s: " %(namePrompt)) if not descriptionSet: description = raw_input("%s: " %(descriptionPrompt)) if not urlSet: url = raw_input("%s: " %(urlPrompt)) if not versionSet: version = raw_input("%s: " %(versionPrompt)) if not providesSet: provides = raw_input("%s: " %(providesPrompt)) if not requiresSet: requires = raw_input("%s: " %(requirePrompt)) if not architectureSet: architecture = raw_input("%s: " %(architecturePrompt)) if not libsSet: libs = raw_input("%s: " %(libPrompt)) if not staticLibSet: staticLib = raw_input("%s: " %(staticLibPrompt)) if not compileFlagsSet: compileFlags = raw_input("%s: " %(compileFlagsPrompt)) if not fileNameSet: fileName = raw_input("%s: " %(fileNamePrompt)) ##Check the file's name. fileName, writeFile = checkFileName(fileName) ##If they chose not to overwrite, write the file. if writeFile: fpc = open(fileName, 'w') fpc.write("%s" %(variables)) fpc.write("Name: %s\n" %(name)) fpc.write("Description: %s\n" %(description)) fpc.write("URL: %s\n" %(url)) fpc.write("Version: %s\n" %(version)) fpc.write("Provides: %s\n" %(provides)) fpc.write("Requires: %s\n" %(requires)) fpc.write("Arch: %s\n" %(architecture)) fpc.write("Libs: %s\n" %(libs)) fpc.write("Libs.private: %s\n" %(staticLib)) fpc.write("Cflags: %s\n" %(compileFlags)) fpc.close() ##TESTER: Print the file out. fpc = open(fileName, 'r') ##TESTER print fpc.read() ##TESTER fpc.close ##TESTER
Python
#!/usr/bin/env python from distutils.core import setup setup( name='flagpoll', version='0.3.0', description='Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software.', author='Daniel E. Shipton', author_email='dshipton@infiscape.com', license='GPL', url='https://realityforge.vrsource.org/view/FlagPoll/WebHome', download_url='https://realityforge.vrsource.org/view/FlagPoll/FlagpollDownloads', scripts=['flagpoll'], long_description = "Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software. Think of it as the rpm of software development. It enables developers total control over which packages, versions, architectures, etc. that they want to use meta-data from.", data_files=[('share/flagpoll', ['flagpoll.fpc']), ('share/man/man1', ['flagpoll.1'])] )
Python
#!/usr/bin/env python # ----------------------------------------------------------------- # # Flag Poll: A tool to extract flags from installed applications # for compiling, settting variables, etc. # # Original Authors: # Daniel E. Shipton <dshipton@gmail.com> # # Flag Poll is Copyright (C) 2006 by Daniel E. Shipton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to: # Free SoftwareFoundation, Inc. # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # # ----------------------------------------------------------------- """Makes a flagpole .fpc file from user input. v0.9 coded by Jeff Groves""" import os import sys import getopt ##String prompts for the input varPrompt = """Convience variables (one 'var_name= var_definition' per line,""" + \ """ empty line when done)""" namePrompt = "Formal Name" descriptionPrompt = "Description" urlPrompt = "URL" providesPrompt = "One or more names to look package up by: (Provides)" versionPrompt = "Version (x.y.z)" architecturePrompt = "Architecture" requirePrompt = "Requires" libPrompt = "Linker Flags (-lfoo -L/usr/lib)" staticLibPrompt = "Static Linking Flags/Libs (extra private libs)" compileFlagsPrompt = "Compile/Include Flags (-I/usr -fpge -O2)" fileNamePrompt = "FPC File's Name" def usage(): """Prints a list of acceptable arguments for fpcmaker.py.""" print """ Fpcmaker.py Options: -n, --name= : Sets %s -d, --description= : Sets %s -u, --url= : Sets %s -p, --provides= : Sets %s -v, --version= : Sets %s -a, --architecture= : Sets %s -r, --requires= : Sets %s -l, --libs= : Sets %s -c, --cflags= : Sets %s -s, --static= : Sets %s -f, --file= : Sets %s """ %(namePrompt, descriptionPrompt, urlPrompt, providesPrompt, versionPrompt, architecturePrompt, requirePrompt, libPrompt, compileFlagsPrompt, staticLibPrompt, fileNamePrompt) return def checkFileName(fileName): """Checks if the fpc file name's blank, contains slashes, or exists.""" nameCleared = False writeFile = True confirms = ['y', 'Y', 'yes', 'Yes'] ##Loops until the name clears or writing the file's aborted. while(not nameCleared and writeFile): ##If it's blank, give the option of aborting the program. if fileName == "": choice = raw_input("Do you want to abort writing the" + " .fpc file? (Y/N): ") if choice not in confirms: fileName = raw_input("Please enter a different name for the" + " .fpc file: ") else: writeFile = False ##If it contains slashes, ask for another name. elif '/' in fileName or '\\' in fileName: print "I can't write to %s because it contains slashes."%(fileName) fileName = raw_input("Please enter a different name for the" + " .fpc file: ") ##If it already exists, ask if they want to overwrite. ##If not, ask for another name. elif os.path.exists(fileName): choice = raw_input("The file %s already exists." %(fileName) + " Do you want to overwrite it? (Y/N): ") if choice not in confirms: fileName = raw_input("Please enter a different name for the" + " .fpc file: ") else: nameCleared = True else: nameCleared = True return [fileName, writeFile] ##Booleans for whether that argument was sent in the command line varSet = False providesSet = False nameSet = False descriptionSet = False urlSet = False architectureSet = False versionSet = False requiresSet = False libsSet = False compileFlagsSet = False staticLibSet = False fileNameSet = False ##Get the options & arguments sent. arguments = sys.argv[1:] try: opts, args = getopt.getopt(arguments, "p:n:u:d:a:r:v:l:c:s:f:", ["provides=", "name=", "url=", "description=", "architecture=", "requires=", "version=", "libs=", "cflags=", "static=", "file="]) ##Send them usage info if they enter a wrong argument except getopt.GetoptError: usage() sys.exit(2) for opt, arg in opts: if opt in ('-p', '--provides'): providesSet = True provides = arg elif opt in ('-n', '--name'): nameSet = True name = arg elif opt in ('-v', '--version'): versionSet = True version = arg elif opt in ('-u', '--url'): urlSet = True url = arg elif opt in ('-d', '--description'): descriptionSet = True description = arg elif opt in ('-a', '--architecture'): architectureSet = True architecture = arg elif opt in ('-r', '--requires'): requiresSet = True requires = arg elif opt in ('-l', '--libs'): libsSet = True libs = arg elif opt in ('-c', '--cflags'): compileFlagsSet = True compileFlags = arg elif opt in ('-s', '--static'): staticLibSet = True staticLib = arg elif opt in ('-f', '--file'): fileNameSet = True fileName = arg ##Grab any input not passed in the arguments from the user. if not varSet: varLine = None variables = "" print "%s:" %(varPrompt) while(varLine != ""): varLine = raw_input("") variables = variables + "%s\n" %(varLine) if not nameSet: name = raw_input("%s: " %(namePrompt)) if not descriptionSet: description = raw_input("%s: " %(descriptionPrompt)) if not urlSet: url = raw_input("%s: " %(urlPrompt)) if not versionSet: version = raw_input("%s: " %(versionPrompt)) if not providesSet: provides = raw_input("%s: " %(providesPrompt)) if not requiresSet: requires = raw_input("%s: " %(requirePrompt)) if not architectureSet: architecture = raw_input("%s: " %(architecturePrompt)) if not libsSet: libs = raw_input("%s: " %(libPrompt)) if not staticLibSet: staticLib = raw_input("%s: " %(staticLibPrompt)) if not compileFlagsSet: compileFlags = raw_input("%s: " %(compileFlagsPrompt)) if not fileNameSet: fileName = raw_input("%s: " %(fileNamePrompt)) ##Check the file's name. fileName, writeFile = checkFileName(fileName) ##If they chose not to overwrite, write the file. if writeFile: fpc = open(fileName, 'w') fpc.write("%s" %(variables)) fpc.write("Name: %s\n" %(name)) fpc.write("Description: %s\n" %(description)) fpc.write("URL: %s\n" %(url)) fpc.write("Version: %s\n" %(version)) fpc.write("Provides: %s\n" %(provides)) fpc.write("Requires: %s\n" %(requires)) fpc.write("Arch: %s\n" %(architecture)) fpc.write("Libs: %s\n" %(libs)) fpc.write("Libs.private: %s\n" %(staticLib)) fpc.write("Cflags: %s\n" %(compileFlags)) fpc.close() ##TESTER: Print the file out. fpc = open(fileName, 'r') ##TESTER print fpc.read() ##TESTER fpc.close ##TESTER
Python
#!/usr/bin/env python # ----------------------------------------------------------------- # # Flagpoll: A tool to extract flags from installed applications # for compiling, settting variables, etc. # # Original Authors: # Daniel E. Shipton <dshipton@gmail.com> # # Flagpoll is Copyright (C) 2006 by Daniel E. Shipton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to: # Free SoftwareFoundation, Inc. # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # # ----------------------------------------------------------------- from optparse import OptionParser import sys, os, glob, os.path, copy, platform pj = os.path.join #################################################################### # SNAGGED FROM PYTHON 2.4 for versions under 2.4 #################################################################### import re as _re class _multimap: """Helper class for combining multiple mappings. Used by .{safe_,}substitute() to combine the mapping and keyword arguments. """ def __init__(self, primary, secondary): self._primary = primary self._secondary = secondary def __getitem__(self, key): try: return self._primary[key] except KeyError: return self._secondary[key] class _TemplateMetaclass(type): pattern = r""" %(delim)s(?: (?P<escaped>%(delim)s) | # Escape sequence of two delimiters (?P<named>%(id)s) | # delimiter and a Python identifier {(?P<braced>%(id)s)} | # delimiter and a braced identifier (?P<invalid>) # Other ill-formed delimiter exprs ) """ def __init__(cls, name, bases, dct): super(_TemplateMetaclass, cls).__init__(name, bases, dct) if 'pattern' in dct: pattern = cls.pattern else: pattern = _TemplateMetaclass.pattern % { 'delim' : _re.escape(cls.delimiter), 'id' : cls.idpattern, } cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE) class Template: """A string class for supporting $-substitutions.""" __metaclass__ = _TemplateMetaclass delimiter = '$' idpattern = r'[_a-z][_a-z0-9]*' def __init__(self, template): self.template = template # Search for $$, $identifier, ${identifier}, and any bare $'s def _invalid(self, mo): i = mo.start('invalid') lines = self.template[:i].splitlines(True) if not lines: colno = 1 lineno = 1 else: colno = i - len(''.join(lines[:-1])) lineno = len(lines) raise ValueError('Invalid placeholder in string: line %d, col %d' % (lineno, colno)) def substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): # Check the most common path first. named = mo.group('named') or mo.group('braced') if named is not None: val = mapping[named] # We use this idiom instead of str() because the latter will # fail if val is a Unicode containing non-ASCII characters. return '%s' % val if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: self._invalid(mo) raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) def safe_substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): named = mo.group('named') if named is not None: try: # We use this idiom instead of str() because the latter # will fail if val is a Unicode containing non-ASCII return '%s' % mapping[named] except KeyError: return self.delimiter + named braced = mo.group('braced') if braced is not None: try: return '%s' % mapping[braced] except KeyError: return self.delimiter + '{' + braced + '}' if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: return self.delimiter raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) #################################################################### # End Snagging #################################################################### class Utils: # Holds collection of small utility functions EXTRA_FLAGPOLL_SEARCH_PATHS = "" EXTRA_FLAGPOLL_FILES = "" path_list_cache = None # Cache of found path lists. (only calcuate once) KEEP_DUPS = False def getFlagpollVersion(): FLAGPOLL_MAJOR_VERSION = 0 FLAGPOLL_MINOR_VERSION = 3 FLAGPOLL_PATCH_VERSION = 0 return ( FLAGPOLL_MAJOR_VERSION, FLAGPOLL_MINOR_VERSION, FLAGPOLL_PATCH_VERSION ) getFlagpollVersion = staticmethod(getFlagpollVersion) def getPathList(): if None != Utils.path_list_cache: return Utils.path_list_cache #TODO: expand LD_LIBRARY_PATH to 64/32/etc??? pkg_cfg_dir = [] flg_cfg_dir = [] ld_path = [] if os.environ.has_key("PKG_CONFIG_DIR"): pkg_cfg_dir = os.environ["PKG_CONFIG_DIR"].split(os.pathsep) if os.environ.has_key("FLG_CONFIG_DIR"): flg_cfg_dir = os.environ["FLG_CONFIG_DIR"].split(os.pathsep) if os.environ.has_key("LD_LIBRARY_PATH"): ld_path = os.environ["LD_LIBRARY_PATH"].split(os.pathsep) ld_path = [pj(p,'pkgconfig') for p in ld_path] extra_paths = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS.split(os.pathsep) path_list = ["/usr/lib64/pkgconfig", "/usr/lib/pkgconfig", "/usr/share/pkgconfig"] path_list.extend(pkg_cfg_dir) path_list.extend(flg_cfg_dir) path_list.extend(extra_paths) path_list.extend(ld_path) flagDBG().out(flagDBG.VERBOSE, "Utils.getPathList", "Potential path list: " + str(path_list)) path_list = [p for p in path_list if os.path.exists(p)] flagDBG().out(flagDBG.INFO, "Utils.getPathList", "Using path list: " + str(path_list)) Utils.path_list_cache = path_list return path_list getPathList = staticmethod(getPathList) def getFileList(): flist = Utils.EXTRA_FLAGPOLL_FILES.split(":") filelist = [] for f in flist: if os.path.isfile(f): filelist.append(f) return filelist getFileList = staticmethod(getFileList) def setKeepDups(keep_dups): Utils.KEEP_DUPS = keep_dups setKeepDups = staticmethod(setKeepDups) def stripDupInList(gen_list): new_list = [] for item in gen_list: item = item.strip() if Utils.KEEP_DUPS: if len(item) > 0: new_list.append(item) continue if item not in new_list: if len(item) > 0: new_list.append(item) return new_list stripDupInList = staticmethod(stripDupInList) def stripDupLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] dir_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-L") or flg.startswith("-R"): dir_list.append(flg) else: lib_list.append(flg) new_list = dir_list + lib_list return Utils.stripDupInList(new_list) stripDupLinkerFlags = staticmethod(stripDupLinkerFlags) def stripDupIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] extra_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-I"): inc_list.append(flg) else: extra_list.append(flg) extra_list.sort() new_list = inc_list + extra_list return Utils.stripDupInList(new_list) stripDupIncludeFlags = staticmethod(stripDupIncludeFlags) def cflagsOnlyDirIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-I"): inc_list.append(flg) return Utils.stripDupInList(inc_list) cflagsOnlyDirIncludeFlags = staticmethod(cflagsOnlyDirIncludeFlags) def cflagsOnlyOtherIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though extra_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if not flg.startswith("-I"): extra_list.append(flg) return Utils.stripDupInList(extra_list) cflagsOnlyOtherIncludeFlags = staticmethod(cflagsOnlyOtherIncludeFlags) def libsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-l"): lib_list.append(flg) return Utils.stripDupInList(lib_list) libsOnlyLinkerFlags = staticmethod(libsOnlyLinkerFlags) def libsOnlyOtherLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though other_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if not flg.startswith("-l") and not flg.startswith("-L") and not flg.startswith("-R"): other_list.append(flg) return Utils.stripDupInList(other_list) libsOnlyOtherLinkerFlags = staticmethod(libsOnlyOtherLinkerFlags) def libDirsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though dir_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-L") or flg.startswith("-R"): dir_list.append(flg) return Utils.stripDupInList(dir_list) libDirsOnlyLinkerFlags = staticmethod(libDirsOnlyLinkerFlags) def printList(gen_list): list_string = "" for item in gen_list: if len(item) > 0: list_string+=str(item) list_string+=" " print list_string.strip() printList = staticmethod(printList) def parsePcFile(filename): lines = open(filename).readlines() fvars = {} lokals = {} for line in lines: line = line.strip() if not line: continue if line.startswith("#"): continue eq_pos = line.find('=') col_pos = line.find(':') if eq_pos < col_pos and eq_pos != -1 or col_pos == -1 and eq_pos !=-1: # local variable name, val = line.split('=', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(lokals) except ValueError: flagDBG().out(flagDBG.WARN, "PkgInfo.parse", "%s has an invalid metadata file" % filename) lokals[name] = val if col_pos < eq_pos and col_pos != -1 or eq_pos == -1 and col_pos !=-1: # exported variable name, val = line.split(':', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(lokals) except ValueError: flagDBG().out(flagDBG.ERROR, "PkgInfo.parse", "%s has an invalid metadata file" % filename) fvars[name] = val fvars["XXFlagpollFilenameXX"] = filename fvars["fp_file_cwd"] = str(filename[:- len(os.path.basename(filename))]) return fvars parsePcFile = staticmethod(parsePcFile) class flagDBG(object): # Logging class is really easy to use # Levels: # 0 - VERBOSE # 1 - INFO # 2 - WARN # 3 - ERROR VERBOSE=0 INFO=1 WARN=2 ERROR=3 __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if flagDBG.__initialized: return flagDBG.__initialized = True self.mLevel = self.WARN self.mLevelList = ["VERBOSE","INFO","WARN","ERROR"] def setLevel(self, level): if level <= 3: self.mLevel = level def out(self, level, obj, message): if level == self.ERROR: if self.mLevel == self.VERBOSE: print self.mLevelList[level] + ":" + str(obj) + ": " + str(message) else: print self.mLevelList[level] + ": " + str(message) sys.exit(1) if level >= self.mLevel: print self.mLevelList[level] + ":" + str(obj) + ": " + str(message) class DepResolutionSystem(object): """ You add PkgAgents with Filters into system and call resolve() you can check for succes by depsSatisfied() and get the list of packages that work back by calling getPackages() """ __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if DepResolutionSystem.__initialized: return DepResolutionSystem.__initialized = True self.mResolveAgents = [] self.mAgentDict = {} self.mFilters = [] self.mResolveAgentFilters = [] self.mInvalidPackageList = [] self.mSatisfied = False self.mAgentChangeList = [] # list of those responsible for adding Filters # to agents in higher in the chain than them # these are the first agents to ask that they pick # the next best package of them self.mAgentsVisitedList = [] # list of Agents that have been visited self.mResolvedPackageList = [] # list that is generated when deps are satified self.mCheckPrivateRequires = False self.mMadeDependList = False def getFilters(self): return self.mFilters def addFilter(self, filter): self.mFilters.append(filter) def addResolveAgentFilter(self, filter): self.mResolveAgentFilters.append(filter) def makeRequireFilter(self, requires): arch_list = [] arch_list.append("no_arch") arch_list.append("") if platform.system() == "Linux": if requires == "64": arch_list.append("x86_64") if requires == "32": arch_list.append("i386") arch_list.append("i586") arch_list.append("i686") if platform.system() == "Darwin": if requires == "64": arch_list.append("ppc64") if requires == "32": arch_list.append("ppc") new_filter = Filter("Arch", lambda x: x in arch_list) self.addFilter(new_filter) def createAgent(self, name): if self.checkAgentExists(name): return self.getAgent(name) else: agent = PkgAgent(name) flagDBG().out(flagDBG.INFO, "DepResSys.createAgent", "Adding %s" % name) self.addNewAgent(agent) return agent def createResolveAgent(self, name): if self.checkAgentExists(name): return self.getAgent(name) else: agent = PkgAgent(name) flagDBG().out(flagDBG.INFO, "DepResSys.createResloveAgent", "Adding %s" % name) self.addResolveAgent(agent) return agent def setPrivateRequires( self, req ): self.mCheckPrivateRequires = req def checkPrivateRequires(self): return self.mCheckPrivateRequires def checkAgentExists(self, name): return self.mAgentDict.has_key(name) def getAgent(self, name): if self.mAgentDict.has_key(name): return self.mAgentDict[name] else: flagDBG().out(flagDBG.ERROR, "DepResSys.getAgent", "Agent %s does not exist" % name) def addNewAgent(self, agent): if not self.checkAgentExists(agent): self.mAgentDict[agent.getName()] = agent def addResolveAgent(self, agent): if agent not in self.mResolveAgents: self.mResolveAgents.append(agent) for filt in self.mResolveAgentFilters: agent.addFilter(filt) def isSatisfied(self): return self.mSatisfied def updateResolvedPackages(self): pkg_list = [] agent_list = [] for agent in self.mResolveAgents: list_of_pkgs = agent.getCurrentPackageList(agent_list) pkg_list.extend(list_of_pkgs) self.mResolvedPackageList = pkg_list def getPackages(self): flagDBG().out(flagDBG.VERBOSE, "DepResSys.getPackages", "Generating list of valid packages ") #str([pkg.getCurrentPa.getName() for pkg in self.mResolvedPackageList])) # If this comes back empty then there isn't a valid set of packages to use self.updateResolvedPackages() return self.mResolvedPackageList def checkFiltersChanged(self): list_to_use = [] return True in [pkg.filtersChanged(list_to_use) for pkg in self.mResolveAgents] def resolveHelper(self): self.resolveAgentsChanged = True while self.resolveAgentsChanged: for agent in self.mResolveAgents: flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveHelper", "Updating " + agent.getName()) agent.update(self.mAgentsVisitedList, self.mAgentChangeList) self.resolveAgentsChanged = self.checkFiltersChanged() # Ask mResolveAgents if they are done(they ask sub people) unless they are # really above you in the walk # If there were changes...run update on mResolveAgents again # at the end ask for pkglist..if it comes back empty then we don't # have a usable configuration for those packages def resolveDeps(self): if not self.mMadeDependList: for agent in self.mResolveAgents: agent.makeDependList() self.mMadeDependList = True self.resolveHelper() self.updateResolvedPackages() # Check if the first round through we found something # Otherwise we need to start removing packages that aren't viable # during the loop self.mSatisfied = (len(self.mResolvedPackageList) != 0) # remove top of packages that added Filters. # then move on to resolving again # remove more if neccesary agentChangeNumber = 0 while not self.mResolvedPackageList: if(self.mAgentChangeList[agentChangeNumber]): if self.mAgentChangeList[agentChangeNumber] in self.mInvalidPackageList: agentChangeNumber+=1 else: if(self.mAgentChangeList[agentChangeNumber].getViablePackages()): flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveDeps", "Removing bad pkg from " + self.mAgentChangeList[agentChangeNumber].getName()) self.mInvalidPackageList.append(self.mAgentChangeList[agentChangeNumber].removeCurrentPackage()) else: flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveDeps", "No combinations.. Resetting " + self.mAgentChangeList[agentChangeNumber].getName()) self.mAgentChangeList[agentChangeNumber].reset() agentChangeNumber+=1 self.resolveHelper() self.updateResolvedPackages() self.mSatisfied = (len(self.mResolvedPackageList) != 0) return class PkgAgent: """ Agent that keeps track of the versions for a package given some filters and the addition of Filters """ # Makes a PkgAgent that finds its current package with the version reqs def __init__(self, name): if DepResolutionSystem().checkAgentExists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "Package Agent %s already exists" % self.mName) self.mName = name flagDBG().out(flagDBG.VERBOSE, "PkgAgent", "Creating:" + str(self.mName)) if not PkgDB().exists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "No info for package: %s" % self.mName) #XXX Doesn't keep filters added for a redo... DepResolutionSystem().addNewAgent(self) self.mFilterList = [] self.mFilterList.extend(DepResolutionSystem().getFilters()) self.mBasePackageList = PkgDB().getPkgInfos(name) for filt in self.mFilterList: self.mBasePackageList = filt.filter(self.mBasePackageList) if len(self.mBasePackageList) == 0: flagDBG().out(flagDBG.ERROR, "PkgAgent", "No viable packages for: %s" % self.mName) self.mViablePackageList = copy.deepcopy(self.mBasePackageList) if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mAgentDependList = [] # Agents that it depends on/needs to update #self.makeDependList() self.mFiltersChanged = True self.mCheckDepends = True def getName(self): return self.mName def setCheckDepends(self, tf): self.mCheckDepends = tf #Filter("Version", lambda x: x == "4.5") def makeDependList(self): if not self.mCheckDepends: self.mAgentDependList = [] return dep_list = [] if self.mCurrentPackage: req_string = self.mCurrentPackage.getVariable("Requires") if DepResolutionSystem().checkPrivateRequires(): req_string = req_string + " " + self.mCurrentPackage.getVariable("Requires.private") req_string = req_string.strip() if req_string == "": return req_string = req_string.replace(',', ' ') req_string = req_string.replace('(', ' ') req_string = req_string.replace(')', ' ') space_req_string_list = req_string.split(' ') req_string_list = [] for entry in space_req_string_list: if len(entry) > 0: req_string_list.append(entry) i = 0 flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList", self.mCurrentPackage.getName() + " requires: " + str(req_string_list)) while len(req_string_list) > i: if PkgDB().exists(req_string_list[i]): new_filter = [] new_agent = DepResolutionSystem().createAgent(req_string_list[i]) if len(req_string_list) > i+1: if req_string_list[i+1] == "=": ver_to_filt = req_string_list[i+2] new_filter = Filter("Version", lambda x: x == ver_to_filt) elif req_string_list[i+1] == "<=": ver_to_filt = req_string_list[i+2] new_filter = Filter("Version", lambda x: x <= ver_to_filt) elif req_string_list[i+1] == ">=": ver_to_filt = req_string_list[i+2] new_filter = Filter("Version", lambda x: x >= ver_to_filt) else: i+=1 else: i+=1 dep_list.append(new_agent) if new_filter: i+=3 new_agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "PkgAgent.makeDependList", "Package %s depends on %s but does not seem to be installed." % (self.mName, str(req_string_list[i]))) flagDBG().out(flagDBG.VERBOSE, "PkgAgent.makeDependList", "List is:" + str([pkg.getName() for pkg in dep_list])) self.mAgentDependList = dep_list def filtersChanged(self,packageList): tf_list = [self.mFiltersChanged] if self.mName not in packageList: packageList.append(self.mName) for pkg in self.mAgentDependList: tf_list.append(pkg.filtersChanged(packageList)) return True in tf_list def getCurrentPackageList(self, packageList): pkgs = [] if self.mName not in packageList: flagDBG().out(flagDBG.VERBOSE, "PkgAgent.getCurrentPackageList", "Package: %s" % self.mName) pkgs.append(self.mCurrentPackage) packageList.append(self.mName) for pkg in self.mAgentDependList: pkgs.extend(pkg.getCurrentPackageList(packageList)) return pkgs # current pkginfo for me def getCurrentPkgInfo(self): return self.mCurrentPackage # Someone else usually places these on me # I keep track of those separately def addFilter(self, filter): flagDBG().out(flagDBG.VERBOSE, "PkgAgent.addFilter", "Adding a Filter to %s" % self.mName) self.mFiltersChanged = True self.mFilterList.append(filter) def removeCurrentPackage(self): flagDBG().out(flagDBG.VERBOSE, "PkgAgent.removeCurrentPackage", "Removing current package of %s" % self.mName) if self.mViablePackageList: ret_val = self.mViablePackageList[0] in self.mBasePackageList del self.mViablePackageList[0] if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] return ret_val def update(self, agentVisitedList, agentChangeList): if self.mName in agentVisitedList: return agentVisitedList.append(self.mName) if self.mFiltersChanged: self.mFiltersChanged = False self.updateFilters() # TODO: checkFilters and add them # if a pkg is in visitedList then add yourself to agentChangeList for pkg in self.mAgentDependList: pkg.update(agentVisitedList, agentChangeList) return def updateFilters(self): for filt in self.mFilterList: self.mViablePackageList = filt.filter(self.mViablePackageList) if len(self.mViablePackageList) > 0: self.mCurrentPackage = self.mViablePackageList[0] else: self.mCurrentPackage = [] def reset(self): flagDBG().out(flagDBG.VERBOSE, "PkgAgent.reset", "Resetting package: %s" % self.mName) self.mViablePackageList = self.mBasePackageList if self.mViablePackageList: self.mCurrentPacakge = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mFilterList = DepResolutionSystem().getFilters() self.mAgentDependList = [] self.mFiltersChanged = True return class Filter: """ A single Filter that knows how to filter the list it recieves Will be inheireted....?..? """ def __init__(self, variableName, testCallable): self.mVarName = variableName self.mTestCallable = testCallable def filter(self, pkg_info_list): ret_pkg_list = [] # Filter first for pkg in pkg_info_list: var = pkg.getVariable(self.mVarName) if self.mTestCallable(var): ret_pkg_list.append(pkg) # Now sort ret_pkg_list.sort(lambda lhs,rhs: cmp(lhs.getVariable(self.mVarName), rhs.getVariable(self.mVarName))) return ret_pkg_list #requires: qt == 4.5 #Filter("Version", lambda x: x <= "4.5") #Filter("Version", lambda x: x <= "4.5") class PkgDB(object): """ Holds all the neccesary information to evaluate itself when needed. Is in charge of holding a list of PkgInfo's that contain info about the package. """ __initialized = False def __init__(self): if self.__initialized: return self.__initialized = True self.mPkgInfos = {} # {pkg_name: List of package infos} self.populatePkgInfoDBPcFiles() self.populatePkgInfoDBFpcFiles() def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def getVariables(self, name, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariable", "Finding " + str(variable_list) + " in " + str(name)) ret_list = [] for var in variable_list: if self.mPkgInfos.has_key(name): ret_list.extend(self.mPkgInfos[name][0].getVariable(var)) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariable", "Package %s not found." % name) return ret_list def checkPackage(self, name): flagDBG().out(flagDBG.INFO, "PkgDB.checkPackage", "Finding " + str(name)) if self.mPkgInfos.has_key(name): return True else: flagDBG().out(flagDBG.ERROR, "PkgDB.CheckPackage", "Package %s not found." % name) return False def getVariablesAndDeps(self, pkg_list, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariablesAndDeps", "Finding " + str(variable_list) + " in " + str(pkg_list)) if DepResolutionSystem().checkPrivateRequires(): temp_var_list = [] for var in variable_list: temp_var_list.append(var.join(".private")) variable_list = variable_list + temp_var_list for name in pkg_list: if self.mPkgInfos.has_key(name): agent = DepResolutionSystem().createAgent(name) DepResolutionSystem().addResolveAgent(agent) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariablesAndDeps", "Package %s not found." % name) DepResolutionSystem().resolveDeps() pkgs = DepResolutionSystem().getPackages() var_list = [] for pkg in pkgs: if pkg: for var in variable_list: var_list.extend(pkg.getVariable(var).split(' ')) return var_list def getPkgInfos(self, name): if self.mPkgInfos.has_key(name): return self.mPkgInfos[name] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getPkgInfos", "Package %s not found." % name) def exists(self, name): return self.mPkgInfos.has_key(name) def getInfo(self, name): if self.mPkgInfos.has_key(name): return [pkg.getInfo() for pkg in self.mPkgInfos[name]] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getInfo", "Package %s not found." % name) def buildPcFileDict(self): """ Builds up a dictionary of {name: list of files for name} """ pc_dict = {} for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.pc")) # List of .pc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these pc files: %s" % str(glob_list)) for g in glob_list: # Get key name and add file to value list in dictionary key = os.path.basename(g)[:-3] # Strip .pc off the filename...rstrip no worky pc_dict.setdefault(key,[]).append(g) for f in Utils.getFileList(): if f.endswith(".pc"): key = os.path.basename(f)[:-3] # Strip .pc off the filename...rstrip no worky pc_dict.setdefault(key,[]).append(f) return pc_dict # { "key", [ "list", "of", "corresponding", "pc", "files"] } def populatePkgInfoDBPcFiles(self): dict_to_pop_from = self.buildPcFileDict() for (pkg,files) in dict_to_pop_from.iteritems(): for f in files: self.mPkgInfos.setdefault(pkg,[]).append(PkgInfo(pkg, f, "pc")) def buildFpcFileList(self): """ Builds up a dictionary of {name: list of files for name} """ file_list = [] for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.fpc")) # List of .fpc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these fpc files: %s" % str(glob_list)) for g in glob_list: file_list.append(g) for f in Utils.getFileList(): if f.endswith(".fpc"): file_list.append(f) return file_list # [ "list", "of", "fpc", "files"] def populatePkgInfoDBFpcFiles(self): list_to_add = self.buildFpcFileList() for filename in list_to_add: var_dict = Utils.parsePcFile(filename) if not var_dict.has_key("Provides"): flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Provides" % str(filename)) continue if not var_dict.has_key("Arch"): flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Arch" % str(filename)) continue provides_string = var_dict["Provides"] provides_string = provides_string.replace(',', ' ') provides_string = provides_string.replace('(', ' ') provides_string = provides_string.replace(')', ' ') for key in provides_string.split(" "): if len(key) > 0: self.mPkgInfos.setdefault(key,[]).append(PkgInfo(key, filename, "fpc", var_dict)) class PkgInfo: """ Holds the information for a package file on the system. These however are evaluated when the need arises. """ def __init__(self, name, file, type, varDict={}): self.mName = name self.mFile = file self.mIsEvaluated = False self.mType = type self.mVariableDict = varDict if self.mType == "fpc": self.mIsEvaluated = True def getVariable(self, variable): self.evaluate() return self.mVariableDict.get(variable,"") def getName(self): return self.mName def evaluate(self): if not self.mIsEvaluated: flagDBG().out(flagDBG.INFO, "PkgInfo.evaluate", "Evaluating %s" % self.mName) self.mVariableDict= Utils.parsePcFile(self.mFile) self.mIsEvaluated = True def getInfo(self): self.evaluate() return self.mVariableDict class OptionsEvaluator: def __init__(self): #self.mOptParser = self.GetOptionParser() #self.mOptParser.print_help() if len(sys.argv) < 2: self.printHelp() #(self.mOptions, self.mArgs) = self.mOptParser.parse_args() #if self.mOptions.version: # print "%s.%s.%s" % Utils.getFlagpollVersion() # sys.exit(0) #if len(self.mArgs) < 1: # self.mOptParser.print_help() # sys.exit(1) # This is only the args....(first arg is stripped) def evaluateArgs(self, args): # Catch any args that need to be tended to immediately # Process args in the order that they were recieved. Some options are not # shown below because they are sub-options of an option below (--strip-dups) for option in args: if option.startswith("--debug"): flagDBG().setLevel(flagDBG.VERBOSE) elif option.startswith("--from-file"): val_start = option.find('=') + 1 file = option[val_start:] Utils.EXTRA_FLAGPOLL_FILES = Utils.EXTRA_FLAGPOLL_FILES + ":" + file elif option.startswith("--help"): self.printHelp() sys.exit(0) elif option.startswith("--version"): print "%s.%s.%s" % Utils.getFlagpollVersion() sys.exit(0) agent = None num_args = len(args) curr_arg = 0 output_options = [] # (option, name/"") important_options = [] # ones that need special attention while curr_arg < num_args: if args[curr_arg].startswith("--atleast-version"): val_start = args[curr_arg].find('=') + 1 atleast_version = args[curr_arg][val_start:] atleast_filter = Filter("Version", lambda x: x >= atleast_version) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(atleast_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue if args[curr_arg].startswith("--cflags-only-I"): output_options.append(("cflags-only-I", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--cflags-only-other"): output_options.append(("cflags-only-other", "")) curr_arg = curr_arg + 1 continue #This could be the catch all for the above ones to and then filter based on what is asked... #For clarity of course... if args[curr_arg].startswith("--cflags"): output_options.append(("cflags", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--extra-paths"): val_start = args[curr_arg].find('=') + 1 paths = args[curr_arg][val_start:] Utils.EXTRA_FLAGPOLL_SEARCH_PATHS = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS + ":" + paths curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--exact-version"): val_start = args[curr_arg].find('=') + 1 exact_version = args[curr_arg][val_start:] exact_filter = Filter("Version", lambda x: x == exact_version) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(exact_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue if args[curr_arg].startswith("--exists"): important_options.append("exists") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--from-file"): val_start = args[curr_arg].find('=') + 1 file = args[curr_arg][val_start:] file_filter = Filter("XXFlagpollFilenameXX", lambda x: x == file) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(file_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue if args[curr_arg].startswith("--info"): output_options.append(("info", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--keep-dups"): Utils.setKeepDups(True) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-l"): output_options.append(("libs-only-l", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-L"): output_options.append(("libs-only-L", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-other"): output_options.append(("libs-only-other", "")) curr_arg = curr_arg + 1 continue #This could be the catch all for the above ones to and then filter based on what is asked... if args[curr_arg].startswith("--libs"): output_options.append(("libs", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--list-all"): curr_arg = curr_arg + 1 PkgDB().printAllPackages() continue if args[curr_arg].startswith("--require-all"): rlen = len("--require-all") req_string = args[curr_arg][rlen:] req_string = req_string.replace('-','_') curr_arg = curr_arg + 1 if req_string.find("<=") != -1: op_start = req_string.find("<=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x: x <= req_val) DepResolutionSystem().addFilter(new_filter) continue if req_string.find(">=") != -1: op_start = req_string.find(">=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x: x >= req_val) DepResolutionSystem().addFilter(new_filter) continue if req_string.find(">") != -1: op_start = req_string.find(">") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x > req_val) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("<") != -1: op_start = req_string.find("<") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x < req_val) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("=") != -1: op_start = req_string.find("=") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x == req_val) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("=") == -1: new_filter = Filter(req_string, lambda x: len(x) > 0) DepResolutionSystem().addFilter(new_filter) continue continue if args[curr_arg].startswith("--require-"): rlen = len("--require-") req_string = args[curr_arg][rlen:] req_string = req_string.replace('-','_') curr_arg = curr_arg + 1 if req_string.find("<=") != -1: op_start = req_string.find("<=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x: x <= req_val) if agent is not None: agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue if req_string.find(">=") != -1: op_start = req_string.find(">=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x: x >= req_val) if agent is not None: agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue if req_string.find(">") != -1: op_start = req_string.find(">") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x > req_val) if agent is not None: agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue if req_string.find("<") != -1: op_start = req_string.find("<") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x < req_val) if agent is not None: agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue if req_string.find("=") != -1: op_start = req_string.find("=") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x == req_val) if agent is not None: agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue if req_string.find("=") == -1: new_filter = Filter(req_string, lambda x: len(x) > 0) if agent is not None: agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue continue if args[curr_arg].startswith("--no-deps"): if agent is not None: agent.setCheckDepends(False) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") if args[curr_arg].startswith("--require="): val_start = args[curr_arg].find('=') + 1 req_var = args[curr_arg][val_start:] curr_arg = curr_arg + 1 DepResolutionSystem().makeRequireFilter(req_var) continue if args[curr_arg].startswith("--modversion"): if agent is not None: output_options.append(("Version", agent.getName())) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--exact-version"): val_start = args[curr_arg].find('=') + 1 exact_version = args[curr_arg][val_start:] exact_filter = Filter("Version", lambda x: x == exact_version) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(exact_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue if args[curr_arg].startswith("--max-release"): val_start = args[curr_arg].find('=') + 1 max_release = args[curr_arg][val_start:] max_filter = Filter("Version", lambda x: x.startswith(max_release)) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(max_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue if args[curr_arg].startswith("--static"): DepResolutionSystem().setPrivateRequires(True) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--variable"): val_start = args[curr_arg].find('=') + 1 fetch_var = args[curr_arg][val_start:] if agent is not None: output_options.append((fetch_var, agent.getName())) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--get-all"): rlen = len("--get-all-") get_string = args[curr_arg][rlen:] get_string = get_string.replace('-','_') output_options.append((get_string, "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--get"): rlen = len("--get-") get_string = args[curr_arg][rlen:] get_string = get_string.replace('-','_') if agent is not None: output_options.append((get_string, agent.getName())) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--concat"): important_options.append("concat") curr_arg = curr_arg + 1 continue if not args[curr_arg].startswith("--"): name = args[curr_arg] curr_arg = curr_arg + 1 if PkgDB().checkPackage(name): agent = DepResolutionSystem().createResolveAgent(name) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Package %s" % name) sys.exit(1) continue #flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Option: %s" % args[curr_arg]) curr_arg = curr_arg + 1 DepResolutionSystem().resolveDeps() pkgs = DepResolutionSystem().getPackages() for p in pkgs: if not p: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found") if len(pkgs) == 0: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found") sys.exit(1) concat = False for option in important_options: if option == "exists": return sys.exit(0) # already checked for none above if option == "concat": concat = True #print output_options #output_options = [] #output_single = [] #Process options here.............. concat_list = [] if concat: print_option = lambda x: concat_list.extend(x) else: print_option = lambda x: Utils.printList(x) for option in output_options: if option[0] == "cflags": print_option(Utils.stripDupIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "cflags-only-I": print_option(Utils.cflagsOnlyDirIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "cflags-only-other": print_option(Utils.cflagsOnlyOtherIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "libs-only-l": print_option(Utils.libsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs-only-L": print_option(Utils.libDirsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs-only-other": print_option(Utils.libsOnlyOtherLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs": print_option(Utils.stripDupLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) else: print_option(Utils.stripDupInList(self.getVarFromPkgs(option[0], pkgs, option[1]))) if concat: Utils.printList(Utils.stripDupInList(concat_list)) def getVarFromPkgs(self, var, pkgs, pkg_name=""): var_list = [] ext_vars = [] if var == "Libs": if DepResolutionSystem().checkPrivateRequires: ext_vars.append("Libs.private") if pkg_name == "": for pkg in pkgs: if pkg: var_list.extend(pkg.getVariable(var).split(' ')) for extra_var in ext_vars: var_list.extend(pkg.getVariable(extra_var).split(' ')) else: for pkg in pkgs: if pkg: if pkg.getName() == pkg_name: var_list.extend(pkg.getVariable(var).split(' ')) for extra_var in ext_vars: var_list.extend(pkg.getVariable(extra_var).split(' ')) return var_list def printHelp(self): print "usage: flagpoll pkg options [pkg options] [generic options]" print " " print "generic options:" print " --help show this help message and exit" print " --version output version of flagpoll" print " --list-all list all known packages" print " --debug show verbose debug information" print " --extra-paths=EXTRA_PATHS" print " extra paths for flagpoll to search for meta-data files" print " --concat concatenate all output and output as one line" print " --keep-dups do not strip out all duplicate info from options" print " " print "options:" print " --modversion output version for package" print " --require=REQUIRE adds additional requirements for packages ex. 32/64" print " --libs output all linker flags" print " --static output linker flags for static linking" print " --libs-only-l output -l flags" print " --libs-only-other output other libs (e.g. -pthread)" print " --libs-only-L output -L flags" print " --cflags output all pre-processor and compiler flags" print " --cflags-only-I output -I flags" print " --cflags-only-other output cflags not covered by the cflags-only-I option" print " --exists return 0 if the module(s) exist" print " --from-file=FILE use the specified FILE for the package" print " --info show information for packages" print " --print-provides print which packages the package provides" print " --print-requires print which packages the package requires" print " --no-deps do not lookup dependencies for the package" print " --atleast-version=ATLEAST_VERSION" print " return 0 if the module is at least version" print " ATLEAST_VERSION" print " --exact-version=EXACT_VERSION" print " return 0 if the module is exactly version" print " EXACT_VERSION" print " --max-release=MAX_RELEASE" print " return 0 if the module has a release that has a" print " version of MAX_RELEASE and will return the max" print " --variable=VARIABLE get the value of a variable" print " " print "dynamic options(replace VAR with a variable you want to get/filter on)" print " NOTE: replace underscores with dashes in VAR" print " NOTE: quotes are needed around <,>,= combinations" print " --get-VAR get VAR from package" print " --get-all-VAR get VAR from package and its deps" print " --require-VAR[<,>,=VAL]" print " require that a var is defined for a package" print " or optionally use equality operators against VAL" print " --require-all-VAR[<,>,=VAL]" print " require that a var is defined for all packages" print " or optionally use equality operators against VAL" sys.exit(0) def main(): # GO! # Initialize singletons and the start evaluating #print sys.argv[1:] my_dbg = flagDBG() my_dep_system = DepResolutionSystem() opt_evaluator = OptionsEvaluator() opt_evaluator.evaluateArgs(sys.argv[1:]) sys.exit(0) if __name__ == "__main__": main()
Python
#!/usr/bin/env python from distutils.core import setup setup( name='flagpoll', version='0.3.0', description='Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software.', author='Daniel E. Shipton', author_email='dshipton@infiscape.com', license='GPL', url='https://realityforge.vrsource.org/view/FlagPoll/WebHome', download_url='https://realityforge.vrsource.org/view/FlagPoll/FlagpollDownloads', scripts=['flagpoll'], long_description = "Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software. Think of it as the rpm of software development. It enables developers total control over which packages, versions, architectures, etc. that they want to use meta-data from.", data_files=[('share/flagpoll', ['flagpoll.fpc']), ('share/man/man1', ['flagpoll.1'])] )
Python
#!/usr/bin/env python # ----------------------------------------------------------------- # # Flagpoll: A tool to extract flags from installed applications # for compiling, settting variables, etc. # # Original Authors: # Daniel E. Shipton <dshipton@gmail.com> # # Flagpoll is Copyright (C) 2006 by Daniel E. Shipton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to: # Free SoftwareFoundation, Inc. # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # # ----------------------------------------------------------------- from optparse import OptionParser import sys, os, glob, os.path, copy, platform pj = os.path.join #################################################################### # SNAGGED FROM PYTHON 2.4 for versions under 2.4 #################################################################### import re as _re class _multimap: """Helper class for combining multiple mappings. Used by .{safe_,}substitute() to combine the mapping and keyword arguments. """ def __init__(self, primary, secondary): self._primary = primary self._secondary = secondary def __getitem__(self, key): try: return self._primary[key] except KeyError: return self._secondary[key] class _TemplateMetaclass(type): pattern = r""" %(delim)s(?: (?P<escaped>%(delim)s) | # Escape sequence of two delimiters (?P<named>%(id)s) | # delimiter and a Python identifier {(?P<braced>%(id)s)} | # delimiter and a braced identifier (?P<invalid>) # Other ill-formed delimiter exprs ) """ def __init__(cls, name, bases, dct): super(_TemplateMetaclass, cls).__init__(name, bases, dct) if 'pattern' in dct: pattern = cls.pattern else: pattern = _TemplateMetaclass.pattern % { 'delim' : _re.escape(cls.delimiter), 'id' : cls.idpattern, } cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE) class Template: """A string class for supporting $-substitutions.""" __metaclass__ = _TemplateMetaclass delimiter = '$' idpattern = r'[_a-z][_a-z0-9]*' def __init__(self, template): self.template = template # Search for $$, $identifier, ${identifier}, and any bare $'s def _invalid(self, mo): i = mo.start('invalid') lines = self.template[:i].splitlines(True) if not lines: colno = 1 lineno = 1 else: colno = i - len(''.join(lines[:-1])) lineno = len(lines) raise ValueError('Invalid placeholder in string: line %d, col %d' % (lineno, colno)) def substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): # Check the most common path first. named = mo.group('named') or mo.group('braced') if named is not None: val = mapping[named] # We use this idiom instead of str() because the latter will # fail if val is a Unicode containing non-ASCII characters. return '%s' % val if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: self._invalid(mo) raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) def safe_substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): named = mo.group('named') if named is not None: try: # We use this idiom instead of str() because the latter # will fail if val is a Unicode containing non-ASCII return '%s' % mapping[named] except KeyError: return self.delimiter + named braced = mo.group('braced') if braced is not None: try: return '%s' % mapping[braced] except KeyError: return self.delimiter + '{' + braced + '}' if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: return self.delimiter raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) #################################################################### # End Snagging #################################################################### class Utils: # Holds collection of small utility functions EXTRA_FLAGPOLL_SEARCH_PATHS = "" EXTRA_FLAGPOLL_FILES = "" path_list_cache = None # Cache of found path lists. (only calcuate once) KEEP_DUPS = False def getFlagpollVersion(): FLAGPOLL_MAJOR_VERSION = 0 FLAGPOLL_MINOR_VERSION = 3 FLAGPOLL_PATCH_VERSION = 0 return ( FLAGPOLL_MAJOR_VERSION, FLAGPOLL_MINOR_VERSION, FLAGPOLL_PATCH_VERSION ) getFlagpollVersion = staticmethod(getFlagpollVersion) def getPathList(): if None != Utils.path_list_cache: return Utils.path_list_cache #TODO: expand LD_LIBRARY_PATH to 64/32/etc??? pkg_cfg_dir = [] flg_cfg_dir = [] ld_path = [] if os.environ.has_key("PKG_CONFIG_DIR"): pkg_cfg_dir = os.environ["PKG_CONFIG_DIR"].split(os.pathsep) if os.environ.has_key("FLG_CONFIG_DIR"): flg_cfg_dir = os.environ["FLG_CONFIG_DIR"].split(os.pathsep) if os.environ.has_key("LD_LIBRARY_PATH"): ld_path = os.environ["LD_LIBRARY_PATH"].split(os.pathsep) ld_path = [pj(p,'pkgconfig') for p in ld_path] extra_paths = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS.split(os.pathsep) path_list = ["/usr/lib64/pkgconfig", "/usr/lib/pkgconfig", "/usr/share/pkgconfig"] path_list.extend(pkg_cfg_dir) path_list.extend(flg_cfg_dir) path_list.extend(extra_paths) path_list.extend(ld_path) flagDBG().out(flagDBG.VERBOSE, "Utils.getPathList", "Potential path list: " + str(path_list)) path_list = [p for p in path_list if os.path.exists(p)] flagDBG().out(flagDBG.INFO, "Utils.getPathList", "Using path list: " + str(path_list)) Utils.path_list_cache = path_list return path_list getPathList = staticmethod(getPathList) def getFileList(): flist = Utils.EXTRA_FLAGPOLL_FILES.split(":") filelist = [] for f in flist: if os.path.isfile(f): filelist.append(f) return filelist getFileList = staticmethod(getFileList) def setKeepDups(keep_dups): Utils.KEEP_DUPS = keep_dups setKeepDups = staticmethod(setKeepDups) def stripDupInList(gen_list): new_list = [] for item in gen_list: item = item.strip() if Utils.KEEP_DUPS: if len(item) > 0: new_list.append(item) continue if item not in new_list: if len(item) > 0: new_list.append(item) return new_list stripDupInList = staticmethod(stripDupInList) def stripDupLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] dir_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-L") or flg.startswith("-R"): dir_list.append(flg) else: lib_list.append(flg) new_list = dir_list + lib_list return Utils.stripDupInList(new_list) stripDupLinkerFlags = staticmethod(stripDupLinkerFlags) def stripDupIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] extra_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-I"): inc_list.append(flg) else: extra_list.append(flg) extra_list.sort() new_list = inc_list + extra_list return Utils.stripDupInList(new_list) stripDupIncludeFlags = staticmethod(stripDupIncludeFlags) def cflagsOnlyDirIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-I"): inc_list.append(flg) return Utils.stripDupInList(inc_list) cflagsOnlyDirIncludeFlags = staticmethod(cflagsOnlyDirIncludeFlags) def cflagsOnlyOtherIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though extra_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if not flg.startswith("-I"): extra_list.append(flg) return Utils.stripDupInList(extra_list) cflagsOnlyOtherIncludeFlags = staticmethod(cflagsOnlyOtherIncludeFlags) def libsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-l"): lib_list.append(flg) return Utils.stripDupInList(lib_list) libsOnlyLinkerFlags = staticmethod(libsOnlyLinkerFlags) def libsOnlyOtherLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though other_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if not flg.startswith("-l") and not flg.startswith("-L") and not flg.startswith("-R"): other_list.append(flg) return Utils.stripDupInList(other_list) libsOnlyOtherLinkerFlags = staticmethod(libsOnlyOtherLinkerFlags) def libDirsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though dir_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-L") or flg.startswith("-R"): dir_list.append(flg) return Utils.stripDupInList(dir_list) libDirsOnlyLinkerFlags = staticmethod(libDirsOnlyLinkerFlags) def printList(gen_list): list_string = "" for item in gen_list: if len(item) > 0: list_string+=str(item) list_string+=" " print list_string.strip() printList = staticmethod(printList) def parsePcFile(filename): lines = open(filename).readlines() fvars = {} lokals = {} for line in lines: line = line.strip() if not line: continue if line.startswith("#"): continue eq_pos = line.find('=') col_pos = line.find(':') if eq_pos < col_pos and eq_pos != -1 or col_pos == -1 and eq_pos !=-1: # local variable name, val = line.split('=', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(lokals) except ValueError: flagDBG().out(flagDBG.WARN, "PkgInfo.parse", "%s has an invalid metadata file" % filename) lokals[name] = val if col_pos < eq_pos and col_pos != -1 or eq_pos == -1 and col_pos !=-1: # exported variable name, val = line.split(':', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(lokals) except ValueError: flagDBG().out(flagDBG.ERROR, "PkgInfo.parse", "%s has an invalid metadata file" % filename) fvars[name] = val fvars["XXFlagpollFilenameXX"] = filename fvars["fp_file_cwd"] = str(filename[:- len(os.path.basename(filename))]) return fvars parsePcFile = staticmethod(parsePcFile) class flagDBG(object): # Logging class is really easy to use # Levels: # 0 - VERBOSE # 1 - INFO # 2 - WARN # 3 - ERROR VERBOSE=0 INFO=1 WARN=2 ERROR=3 __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if flagDBG.__initialized: return flagDBG.__initialized = True self.mLevel = self.WARN self.mLevelList = ["VERBOSE","INFO","WARN","ERROR"] def setLevel(self, level): if level <= 3: self.mLevel = level def out(self, level, obj, message): if level == self.ERROR: if self.mLevel == self.VERBOSE: print self.mLevelList[level] + ":" + str(obj) + ": " + str(message) else: print self.mLevelList[level] + ": " + str(message) sys.exit(1) if level >= self.mLevel: print self.mLevelList[level] + ":" + str(obj) + ": " + str(message) class DepResolutionSystem(object): """ You add PkgAgents with Filters into system and call resolve() you can check for succes by depsSatisfied() and get the list of packages that work back by calling getPackages() """ __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if DepResolutionSystem.__initialized: return DepResolutionSystem.__initialized = True self.mResolveAgents = [] self.mAgentDict = {} self.mFilters = [] self.mResolveAgentFilters = [] self.mInvalidPackageList = [] self.mSatisfied = False self.mAgentChangeList = [] # list of those responsible for adding Filters # to agents in higher in the chain than them # these are the first agents to ask that they pick # the next best package of them self.mAgentsVisitedList = [] # list of Agents that have been visited self.mResolvedPackageList = [] # list that is generated when deps are satified self.mCheckPrivateRequires = False self.mMadeDependList = False def getFilters(self): return self.mFilters def addFilter(self, filter): self.mFilters.append(filter) def addResolveAgentFilter(self, filter): self.mResolveAgentFilters.append(filter) def makeRequireFilter(self, requires): arch_list = [] arch_list.append("no_arch") arch_list.append("") if platform.system() == "Linux": if requires == "64": arch_list.append("x86_64") if requires == "32": arch_list.append("i386") arch_list.append("i586") arch_list.append("i686") if platform.system() == "Darwin": if requires == "64": arch_list.append("ppc64") if requires == "32": arch_list.append("ppc") new_filter = Filter("Arch", lambda x: x in arch_list) self.addFilter(new_filter) def createAgent(self, name): if self.checkAgentExists(name): return self.getAgent(name) else: agent = PkgAgent(name) flagDBG().out(flagDBG.INFO, "DepResSys.createAgent", "Adding %s" % name) self.addNewAgent(agent) return agent def createResolveAgent(self, name): if self.checkAgentExists(name): return self.getAgent(name) else: agent = PkgAgent(name) flagDBG().out(flagDBG.INFO, "DepResSys.createResloveAgent", "Adding %s" % name) self.addResolveAgent(agent) return agent def setPrivateRequires( self, req ): self.mCheckPrivateRequires = req def checkPrivateRequires(self): return self.mCheckPrivateRequires def checkAgentExists(self, name): return self.mAgentDict.has_key(name) def getAgent(self, name): if self.mAgentDict.has_key(name): return self.mAgentDict[name] else: flagDBG().out(flagDBG.ERROR, "DepResSys.getAgent", "Agent %s does not exist" % name) def addNewAgent(self, agent): if not self.checkAgentExists(agent): self.mAgentDict[agent.getName()] = agent def addResolveAgent(self, agent): if agent not in self.mResolveAgents: self.mResolveAgents.append(agent) for filt in self.mResolveAgentFilters: agent.addFilter(filt) def isSatisfied(self): return self.mSatisfied def updateResolvedPackages(self): pkg_list = [] agent_list = [] for agent in self.mResolveAgents: list_of_pkgs = agent.getCurrentPackageList(agent_list) pkg_list.extend(list_of_pkgs) self.mResolvedPackageList = pkg_list def getPackages(self): flagDBG().out(flagDBG.VERBOSE, "DepResSys.getPackages", "Generating list of valid packages ") #str([pkg.getCurrentPa.getName() for pkg in self.mResolvedPackageList])) # If this comes back empty then there isn't a valid set of packages to use self.updateResolvedPackages() return self.mResolvedPackageList def checkFiltersChanged(self): list_to_use = [] return True in [pkg.filtersChanged(list_to_use) for pkg in self.mResolveAgents] def resolveHelper(self): self.resolveAgentsChanged = True while self.resolveAgentsChanged: for agent in self.mResolveAgents: flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveHelper", "Updating " + agent.getName()) agent.update(self.mAgentsVisitedList, self.mAgentChangeList) self.resolveAgentsChanged = self.checkFiltersChanged() # Ask mResolveAgents if they are done(they ask sub people) unless they are # really above you in the walk # If there were changes...run update on mResolveAgents again # at the end ask for pkglist..if it comes back empty then we don't # have a usable configuration for those packages def resolveDeps(self): if not self.mMadeDependList: for agent in self.mResolveAgents: agent.makeDependList() self.mMadeDependList = True self.resolveHelper() self.updateResolvedPackages() # Check if the first round through we found something # Otherwise we need to start removing packages that aren't viable # during the loop self.mSatisfied = (len(self.mResolvedPackageList) != 0) # remove top of packages that added Filters. # then move on to resolving again # remove more if neccesary agentChangeNumber = 0 while not self.mResolvedPackageList: if(self.mAgentChangeList[agentChangeNumber]): if self.mAgentChangeList[agentChangeNumber] in self.mInvalidPackageList: agentChangeNumber+=1 else: if(self.mAgentChangeList[agentChangeNumber].getViablePackages()): flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveDeps", "Removing bad pkg from " + self.mAgentChangeList[agentChangeNumber].getName()) self.mInvalidPackageList.append(self.mAgentChangeList[agentChangeNumber].removeCurrentPackage()) else: flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveDeps", "No combinations.. Resetting " + self.mAgentChangeList[agentChangeNumber].getName()) self.mAgentChangeList[agentChangeNumber].reset() agentChangeNumber+=1 self.resolveHelper() self.updateResolvedPackages() self.mSatisfied = (len(self.mResolvedPackageList) != 0) return class PkgAgent: """ Agent that keeps track of the versions for a package given some filters and the addition of Filters """ # Makes a PkgAgent that finds its current package with the version reqs def __init__(self, name): if DepResolutionSystem().checkAgentExists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "Package Agent %s already exists" % self.mName) self.mName = name flagDBG().out(flagDBG.VERBOSE, "PkgAgent", "Creating:" + str(self.mName)) if not PkgDB().exists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "No info for package: %s" % self.mName) #XXX Doesn't keep filters added for a redo... DepResolutionSystem().addNewAgent(self) self.mFilterList = [] self.mFilterList.extend(DepResolutionSystem().getFilters()) self.mBasePackageList = PkgDB().getPkgInfos(name) for filt in self.mFilterList: self.mBasePackageList = filt.filter(self.mBasePackageList) if len(self.mBasePackageList) == 0: flagDBG().out(flagDBG.ERROR, "PkgAgent", "No viable packages for: %s" % self.mName) self.mViablePackageList = copy.deepcopy(self.mBasePackageList) if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mAgentDependList = [] # Agents that it depends on/needs to update #self.makeDependList() self.mFiltersChanged = True self.mCheckDepends = True def getName(self): return self.mName def setCheckDepends(self, tf): self.mCheckDepends = tf #Filter("Version", lambda x: x == "4.5") def makeDependList(self): if not self.mCheckDepends: self.mAgentDependList = [] return dep_list = [] if self.mCurrentPackage: req_string = self.mCurrentPackage.getVariable("Requires") if DepResolutionSystem().checkPrivateRequires(): req_string = req_string + " " + self.mCurrentPackage.getVariable("Requires.private") req_string = req_string.strip() if req_string == "": return req_string = req_string.replace(',', ' ') req_string = req_string.replace('(', ' ') req_string = req_string.replace(')', ' ') space_req_string_list = req_string.split(' ') req_string_list = [] for entry in space_req_string_list: if len(entry) > 0: req_string_list.append(entry) i = 0 flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList", self.mCurrentPackage.getName() + " requires: " + str(req_string_list)) while len(req_string_list) > i: if PkgDB().exists(req_string_list[i]): new_filter = [] new_agent = DepResolutionSystem().createAgent(req_string_list[i]) if len(req_string_list) > i+1: if req_string_list[i+1] == "=": ver_to_filt = req_string_list[i+2] new_filter = Filter("Version", lambda x: x == ver_to_filt) elif req_string_list[i+1] == "<=": ver_to_filt = req_string_list[i+2] new_filter = Filter("Version", lambda x: x <= ver_to_filt) elif req_string_list[i+1] == ">=": ver_to_filt = req_string_list[i+2] new_filter = Filter("Version", lambda x: x >= ver_to_filt) else: i+=1 else: i+=1 dep_list.append(new_agent) if new_filter: i+=3 new_agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "PkgAgent.makeDependList", "Package %s depends on %s but does not seem to be installed." % (self.mName, str(req_string_list[i]))) flagDBG().out(flagDBG.VERBOSE, "PkgAgent.makeDependList", "List is:" + str([pkg.getName() for pkg in dep_list])) self.mAgentDependList = dep_list def filtersChanged(self,packageList): tf_list = [self.mFiltersChanged] if self.mName not in packageList: packageList.append(self.mName) for pkg in self.mAgentDependList: tf_list.append(pkg.filtersChanged(packageList)) return True in tf_list def getCurrentPackageList(self, packageList): pkgs = [] if self.mName not in packageList: flagDBG().out(flagDBG.VERBOSE, "PkgAgent.getCurrentPackageList", "Package: %s" % self.mName) pkgs.append(self.mCurrentPackage) packageList.append(self.mName) for pkg in self.mAgentDependList: pkgs.extend(pkg.getCurrentPackageList(packageList)) return pkgs # current pkginfo for me def getCurrentPkgInfo(self): return self.mCurrentPackage # Someone else usually places these on me # I keep track of those separately def addFilter(self, filter): flagDBG().out(flagDBG.VERBOSE, "PkgAgent.addFilter", "Adding a Filter to %s" % self.mName) self.mFiltersChanged = True self.mFilterList.append(filter) def removeCurrentPackage(self): flagDBG().out(flagDBG.VERBOSE, "PkgAgent.removeCurrentPackage", "Removing current package of %s" % self.mName) if self.mViablePackageList: ret_val = self.mViablePackageList[0] in self.mBasePackageList del self.mViablePackageList[0] if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] return ret_val def update(self, agentVisitedList, agentChangeList): if self.mName in agentVisitedList: return agentVisitedList.append(self.mName) if self.mFiltersChanged: self.mFiltersChanged = False self.updateFilters() # TODO: checkFilters and add them # if a pkg is in visitedList then add yourself to agentChangeList for pkg in self.mAgentDependList: pkg.update(agentVisitedList, agentChangeList) return def updateFilters(self): for filt in self.mFilterList: self.mViablePackageList = filt.filter(self.mViablePackageList) if len(self.mViablePackageList) > 0: self.mCurrentPackage = self.mViablePackageList[0] else: self.mCurrentPackage = [] def reset(self): flagDBG().out(flagDBG.VERBOSE, "PkgAgent.reset", "Resetting package: %s" % self.mName) self.mViablePackageList = self.mBasePackageList if self.mViablePackageList: self.mCurrentPacakge = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mFilterList = DepResolutionSystem().getFilters() self.mAgentDependList = [] self.mFiltersChanged = True return class Filter: """ A single Filter that knows how to filter the list it recieves Will be inheireted....?..? """ def __init__(self, variableName, testCallable): self.mVarName = variableName self.mTestCallable = testCallable def filter(self, pkg_info_list): ret_pkg_list = [] # Filter first for pkg in pkg_info_list: var = pkg.getVariable(self.mVarName) if self.mTestCallable(var): ret_pkg_list.append(pkg) # Now sort ret_pkg_list.sort(lambda lhs,rhs: cmp(lhs.getVariable(self.mVarName), rhs.getVariable(self.mVarName))) return ret_pkg_list #requires: qt == 4.5 #Filter("Version", lambda x: x <= "4.5") #Filter("Version", lambda x: x <= "4.5") class PkgDB(object): """ Holds all the neccesary information to evaluate itself when needed. Is in charge of holding a list of PkgInfo's that contain info about the package. """ __initialized = False def __init__(self): if self.__initialized: return self.__initialized = True self.mPkgInfos = {} # {pkg_name: List of package infos} self.populatePkgInfoDBPcFiles() self.populatePkgInfoDBFpcFiles() def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def getVariables(self, name, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariable", "Finding " + str(variable_list) + " in " + str(name)) ret_list = [] for var in variable_list: if self.mPkgInfos.has_key(name): ret_list.extend(self.mPkgInfos[name][0].getVariable(var)) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariable", "Package %s not found." % name) return ret_list def checkPackage(self, name): flagDBG().out(flagDBG.INFO, "PkgDB.checkPackage", "Finding " + str(name)) if self.mPkgInfos.has_key(name): return True else: flagDBG().out(flagDBG.ERROR, "PkgDB.CheckPackage", "Package %s not found." % name) return False def getVariablesAndDeps(self, pkg_list, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariablesAndDeps", "Finding " + str(variable_list) + " in " + str(pkg_list)) if DepResolutionSystem().checkPrivateRequires(): temp_var_list = [] for var in variable_list: temp_var_list.append(var.join(".private")) variable_list = variable_list + temp_var_list for name in pkg_list: if self.mPkgInfos.has_key(name): agent = DepResolutionSystem().createAgent(name) DepResolutionSystem().addResolveAgent(agent) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariablesAndDeps", "Package %s not found." % name) DepResolutionSystem().resolveDeps() pkgs = DepResolutionSystem().getPackages() var_list = [] for pkg in pkgs: if pkg: for var in variable_list: var_list.extend(pkg.getVariable(var).split(' ')) return var_list def getPkgInfos(self, name): if self.mPkgInfos.has_key(name): return self.mPkgInfos[name] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getPkgInfos", "Package %s not found." % name) def exists(self, name): return self.mPkgInfos.has_key(name) def getInfo(self, name): if self.mPkgInfos.has_key(name): return [pkg.getInfo() for pkg in self.mPkgInfos[name]] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getInfo", "Package %s not found." % name) def buildPcFileDict(self): """ Builds up a dictionary of {name: list of files for name} """ pc_dict = {} for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.pc")) # List of .pc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these pc files: %s" % str(glob_list)) for g in glob_list: # Get key name and add file to value list in dictionary key = os.path.basename(g)[:-3] # Strip .pc off the filename...rstrip no worky pc_dict.setdefault(key,[]).append(g) for f in Utils.getFileList(): if f.endswith(".pc"): key = os.path.basename(f)[:-3] # Strip .pc off the filename...rstrip no worky pc_dict.setdefault(key,[]).append(f) return pc_dict # { "key", [ "list", "of", "corresponding", "pc", "files"] } def populatePkgInfoDBPcFiles(self): dict_to_pop_from = self.buildPcFileDict() for (pkg,files) in dict_to_pop_from.iteritems(): for f in files: self.mPkgInfos.setdefault(pkg,[]).append(PkgInfo(pkg, f, "pc")) def buildFpcFileList(self): """ Builds up a dictionary of {name: list of files for name} """ file_list = [] for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.fpc")) # List of .fpc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these fpc files: %s" % str(glob_list)) for g in glob_list: file_list.append(g) for f in Utils.getFileList(): if f.endswith(".fpc"): file_list.append(f) return file_list # [ "list", "of", "fpc", "files"] def populatePkgInfoDBFpcFiles(self): list_to_add = self.buildFpcFileList() for filename in list_to_add: var_dict = Utils.parsePcFile(filename) if not var_dict.has_key("Provides"): flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Provides" % str(filename)) continue if not var_dict.has_key("Arch"): flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Arch" % str(filename)) continue provides_string = var_dict["Provides"] provides_string = provides_string.replace(',', ' ') provides_string = provides_string.replace('(', ' ') provides_string = provides_string.replace(')', ' ') for key in provides_string.split(" "): if len(key) > 0: self.mPkgInfos.setdefault(key,[]).append(PkgInfo(key, filename, "fpc", var_dict)) class PkgInfo: """ Holds the information for a package file on the system. These however are evaluated when the need arises. """ def __init__(self, name, file, type, varDict={}): self.mName = name self.mFile = file self.mIsEvaluated = False self.mType = type self.mVariableDict = varDict if self.mType == "fpc": self.mIsEvaluated = True def getVariable(self, variable): self.evaluate() return self.mVariableDict.get(variable,"") def getName(self): return self.mName def evaluate(self): if not self.mIsEvaluated: flagDBG().out(flagDBG.INFO, "PkgInfo.evaluate", "Evaluating %s" % self.mName) self.mVariableDict= Utils.parsePcFile(self.mFile) self.mIsEvaluated = True def getInfo(self): self.evaluate() return self.mVariableDict class OptionsEvaluator: def __init__(self): #self.mOptParser = self.GetOptionParser() #self.mOptParser.print_help() if len(sys.argv) < 2: self.printHelp() #(self.mOptions, self.mArgs) = self.mOptParser.parse_args() #if self.mOptions.version: # print "%s.%s.%s" % Utils.getFlagpollVersion() # sys.exit(0) #if len(self.mArgs) < 1: # self.mOptParser.print_help() # sys.exit(1) # This is only the args....(first arg is stripped) def evaluateArgs(self, args): # Catch any args that need to be tended to immediately # Process args in the order that they were recieved. Some options are not # shown below because they are sub-options of an option below (--strip-dups) for option in args: if option.startswith("--debug"): flagDBG().setLevel(flagDBG.VERBOSE) elif option.startswith("--from-file"): val_start = option.find('=') + 1 file = option[val_start:] Utils.EXTRA_FLAGPOLL_FILES = Utils.EXTRA_FLAGPOLL_FILES + ":" + file elif option.startswith("--help"): self.printHelp() sys.exit(0) elif option.startswith("--version"): print "%s.%s.%s" % Utils.getFlagpollVersion() sys.exit(0) agent = None num_args = len(args) curr_arg = 0 output_options = [] # (option, name/"") important_options = [] # ones that need special attention while curr_arg < num_args: if args[curr_arg].startswith("--atleast-version"): val_start = args[curr_arg].find('=') + 1 atleast_version = args[curr_arg][val_start:] atleast_filter = Filter("Version", lambda x: x >= atleast_version) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(atleast_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue if args[curr_arg].startswith("--cflags-only-I"): output_options.append(("cflags-only-I", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--cflags-only-other"): output_options.append(("cflags-only-other", "")) curr_arg = curr_arg + 1 continue #This could be the catch all for the above ones to and then filter based on what is asked... #For clarity of course... if args[curr_arg].startswith("--cflags"): output_options.append(("cflags", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--extra-paths"): val_start = args[curr_arg].find('=') + 1 paths = args[curr_arg][val_start:] Utils.EXTRA_FLAGPOLL_SEARCH_PATHS = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS + ":" + paths curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--exact-version"): val_start = args[curr_arg].find('=') + 1 exact_version = args[curr_arg][val_start:] exact_filter = Filter("Version", lambda x: x == exact_version) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(exact_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue if args[curr_arg].startswith("--exists"): important_options.append("exists") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--from-file"): val_start = args[curr_arg].find('=') + 1 file = args[curr_arg][val_start:] file_filter = Filter("XXFlagpollFilenameXX", lambda x: x == file) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(file_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue if args[curr_arg].startswith("--info"): output_options.append(("info", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--keep-dups"): Utils.setKeepDups(True) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-l"): output_options.append(("libs-only-l", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-L"): output_options.append(("libs-only-L", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-other"): output_options.append(("libs-only-other", "")) curr_arg = curr_arg + 1 continue #This could be the catch all for the above ones to and then filter based on what is asked... if args[curr_arg].startswith("--libs"): output_options.append(("libs", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--list-all"): curr_arg = curr_arg + 1 PkgDB().printAllPackages() continue if args[curr_arg].startswith("--require-all"): rlen = len("--require-all") req_string = args[curr_arg][rlen:] req_string = req_string.replace('-','_') curr_arg = curr_arg + 1 if req_string.find("<=") != -1: op_start = req_string.find("<=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x: x <= req_val) DepResolutionSystem().addFilter(new_filter) continue if req_string.find(">=") != -1: op_start = req_string.find(">=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x: x >= req_val) DepResolutionSystem().addFilter(new_filter) continue if req_string.find(">") != -1: op_start = req_string.find(">") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x > req_val) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("<") != -1: op_start = req_string.find("<") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x < req_val) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("=") != -1: op_start = req_string.find("=") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x == req_val) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("=") == -1: new_filter = Filter(req_string, lambda x: len(x) > 0) DepResolutionSystem().addFilter(new_filter) continue continue if args[curr_arg].startswith("--require-"): rlen = len("--require-") req_string = args[curr_arg][rlen:] req_string = req_string.replace('-','_') curr_arg = curr_arg + 1 if req_string.find("<=") != -1: op_start = req_string.find("<=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x: x <= req_val) if agent is not None: agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue if req_string.find(">=") != -1: op_start = req_string.find(">=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x: x >= req_val) if agent is not None: agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue if req_string.find(">") != -1: op_start = req_string.find(">") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x > req_val) if agent is not None: agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue if req_string.find("<") != -1: op_start = req_string.find("<") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x < req_val) if agent is not None: agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue if req_string.find("=") != -1: op_start = req_string.find("=") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x == req_val) if agent is not None: agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue if req_string.find("=") == -1: new_filter = Filter(req_string, lambda x: len(x) > 0) if agent is not None: agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue continue if args[curr_arg].startswith("--no-deps"): if agent is not None: agent.setCheckDepends(False) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") if args[curr_arg].startswith("--require="): val_start = args[curr_arg].find('=') + 1 req_var = args[curr_arg][val_start:] curr_arg = curr_arg + 1 DepResolutionSystem().makeRequireFilter(req_var) continue if args[curr_arg].startswith("--modversion"): if agent is not None: output_options.append(("Version", agent.getName())) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--exact-version"): val_start = args[curr_arg].find('=') + 1 exact_version = args[curr_arg][val_start:] exact_filter = Filter("Version", lambda x: x == exact_version) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(exact_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue if args[curr_arg].startswith("--max-release"): val_start = args[curr_arg].find('=') + 1 max_release = args[curr_arg][val_start:] max_filter = Filter("Version", lambda x: x.startswith(max_release)) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(max_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue if args[curr_arg].startswith("--static"): DepResolutionSystem().setPrivateRequires(True) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--variable"): val_start = args[curr_arg].find('=') + 1 fetch_var = args[curr_arg][val_start:] if agent is not None: output_options.append((fetch_var, agent.getName())) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--get-all"): rlen = len("--get-all-") get_string = args[curr_arg][rlen:] get_string = get_string.replace('-','_') output_options.append((get_string, "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--get"): rlen = len("--get-") get_string = args[curr_arg][rlen:] get_string = get_string.replace('-','_') if agent is not None: output_options.append((get_string, agent.getName())) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--concat"): important_options.append("concat") curr_arg = curr_arg + 1 continue if not args[curr_arg].startswith("--"): name = args[curr_arg] curr_arg = curr_arg + 1 if PkgDB().checkPackage(name): agent = DepResolutionSystem().createResolveAgent(name) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Package %s" % name) sys.exit(1) continue #flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Option: %s" % args[curr_arg]) curr_arg = curr_arg + 1 DepResolutionSystem().resolveDeps() pkgs = DepResolutionSystem().getPackages() for p in pkgs: if not p: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found") if len(pkgs) == 0: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found") sys.exit(1) concat = False for option in important_options: if option == "exists": return sys.exit(0) # already checked for none above if option == "concat": concat = True #print output_options #output_options = [] #output_single = [] #Process options here.............. concat_list = [] if concat: print_option = lambda x: concat_list.extend(x) else: print_option = lambda x: Utils.printList(x) for option in output_options: if option[0] == "cflags": print_option(Utils.stripDupIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "cflags-only-I": print_option(Utils.cflagsOnlyDirIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "cflags-only-other": print_option(Utils.cflagsOnlyOtherIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "libs-only-l": print_option(Utils.libsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs-only-L": print_option(Utils.libDirsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs-only-other": print_option(Utils.libsOnlyOtherLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs": print_option(Utils.stripDupLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) else: print_option(Utils.stripDupInList(self.getVarFromPkgs(option[0], pkgs, option[1]))) if concat: Utils.printList(Utils.stripDupInList(concat_list)) def getVarFromPkgs(self, var, pkgs, pkg_name=""): var_list = [] ext_vars = [] if var == "Libs": if DepResolutionSystem().checkPrivateRequires: ext_vars.append("Libs.private") if pkg_name == "": for pkg in pkgs: if pkg: var_list.extend(pkg.getVariable(var).split(' ')) for extra_var in ext_vars: var_list.extend(pkg.getVariable(extra_var).split(' ')) else: for pkg in pkgs: if pkg: if pkg.getName() == pkg_name: var_list.extend(pkg.getVariable(var).split(' ')) for extra_var in ext_vars: var_list.extend(pkg.getVariable(extra_var).split(' ')) return var_list def printHelp(self): print "usage: flagpoll pkg options [pkg options] [generic options]" print " " print "generic options:" print " --help show this help message and exit" print " --version output version of flagpoll" print " --list-all list all known packages" print " --debug show verbose debug information" print " --extra-paths=EXTRA_PATHS" print " extra paths for flagpoll to search for meta-data files" print " --concat concatenate all output and output as one line" print " --keep-dups do not strip out all duplicate info from options" print " " print "options:" print " --modversion output version for package" print " --require=REQUIRE adds additional requirements for packages ex. 32/64" print " --libs output all linker flags" print " --static output linker flags for static linking" print " --libs-only-l output -l flags" print " --libs-only-other output other libs (e.g. -pthread)" print " --libs-only-L output -L flags" print " --cflags output all pre-processor and compiler flags" print " --cflags-only-I output -I flags" print " --cflags-only-other output cflags not covered by the cflags-only-I option" print " --exists return 0 if the module(s) exist" print " --from-file=FILE use the specified FILE for the package" print " --info show information for packages" print " --print-provides print which packages the package provides" print " --print-requires print which packages the package requires" print " --no-deps do not lookup dependencies for the package" print " --atleast-version=ATLEAST_VERSION" print " return 0 if the module is at least version" print " ATLEAST_VERSION" print " --exact-version=EXACT_VERSION" print " return 0 if the module is exactly version" print " EXACT_VERSION" print " --max-release=MAX_RELEASE" print " return 0 if the module has a release that has a" print " version of MAX_RELEASE and will return the max" print " --variable=VARIABLE get the value of a variable" print " " print "dynamic options(replace VAR with a variable you want to get/filter on)" print " NOTE: replace underscores with dashes in VAR" print " NOTE: quotes are needed around <,>,= combinations" print " --get-VAR get VAR from package" print " --get-all-VAR get VAR from package and its deps" print " --require-VAR[<,>,=VAL]" print " require that a var is defined for a package" print " or optionally use equality operators against VAL" print " --require-all-VAR[<,>,=VAL]" print " require that a var is defined for all packages" print " or optionally use equality operators against VAL" sys.exit(0) def main(): # GO! # Initialize singletons and the start evaluating #print sys.argv[1:] my_dbg = flagDBG() my_dep_system = DepResolutionSystem() opt_evaluator = OptionsEvaluator() opt_evaluator.evaluateArgs(sys.argv[1:]) sys.exit(0) if __name__ == "__main__": main()
Python
#!/usr/bin/env python # ----------------------------------------------------------------- # # Flag Poll: A tool to extract flags from installed applications # for compiling, settting variables, etc. # # Original Authors: # Daniel E. Shipton <dshipton@gmail.com> # # Flag Poll is Copyright (C) 2006 by Daniel E. Shipton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to: # Free SoftwareFoundation, Inc. # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # # ----------------------------------------------------------------- """Makes a flagpole .fpc file from user input. v0.9 coded by Jeff Groves""" import os import sys import getopt ##String prompts for the input varPrompt = """Convience variables (one 'var_name= var_definition' per line,""" + \ """ empty line when done)""" namePrompt = "Formal Name" descriptionPrompt = "Description" urlPrompt = "URL" providesPrompt = "One or more names to look package up by: (Provides)" versionPrompt = "Version (x.y.z)" architecturePrompt = "Architecture" requirePrompt = "Requires" libPrompt = "Linker Flags (-lfoo -L/usr/lib)" staticLibPrompt = "Static Linking Flags/Libs (extra private libs)" compileFlagsPrompt = "Compile/Include Flags (-I/usr -fpge -O2)" fileNamePrompt = "FPC File's Name" def usage(): """Prints a list of acceptable arguments for fpcmaker.py.""" print """ Fpcmaker.py Options: -n, --name= : Sets %s -d, --description= : Sets %s -u, --url= : Sets %s -p, --provides= : Sets %s -v, --version= : Sets %s -a, --architecture= : Sets %s -r, --requires= : Sets %s -l, --libs= : Sets %s -c, --cflags= : Sets %s -s, --static= : Sets %s -f, --file= : Sets %s """ %(namePrompt, descriptionPrompt, urlPrompt, providesPrompt, versionPrompt, architecturePrompt, requirePrompt, libPrompt, compileFlagsPrompt, staticLibPrompt, fileNamePrompt) return def checkFileName(fileName): """Checks if the fpc file name's blank, contains slashes, or exists.""" nameCleared = False writeFile = True confirms = ['y', 'Y', 'yes', 'Yes'] ##Loops until the name clears or writing the file's aborted. while(not nameCleared and writeFile): ##If it's blank, give the option of aborting the program. if fileName == "": choice = raw_input("Do you want to abort writing the" + " .fpc file? (Y/N): ") if choice not in confirms: fileName = raw_input("Please enter a different name for the" + " .fpc file: ") else: writeFile = False ##If it contains slashes, ask for another name. elif '/' in fileName or '\\' in fileName: print "I can't write to %s because it contains slashes."%(fileName) fileName = raw_input("Please enter a different name for the" + " .fpc file: ") ##If it already exists, ask if they want to overwrite. ##If not, ask for another name. elif os.path.exists(fileName): choice = raw_input("The file %s already exists." %(fileName) + " Do you want to overwrite it? (Y/N): ") if choice not in confirms: fileName = raw_input("Please enter a different name for the" + " .fpc file: ") else: nameCleared = True else: nameCleared = True return [fileName, writeFile] ##Booleans for whether that argument was sent in the command line varSet = False providesSet = False nameSet = False descriptionSet = False urlSet = False architectureSet = False versionSet = False requiresSet = False libsSet = False compileFlagsSet = False staticLibSet = False fileNameSet = False ##Get the options & arguments sent. arguments = sys.argv[1:] try: opts, args = getopt.getopt(arguments, "p:n:u:d:a:r:v:l:c:s:f:", ["provides=", "name=", "url=", "description=", "architecture=", "requires=", "version=", "libs=", "cflags=", "static=", "file="]) ##Send them usage info if they enter a wrong argument except getopt.GetoptError: usage() sys.exit(2) for opt, arg in opts: if opt in ('-p', '--provides'): providesSet = True provides = arg elif opt in ('-n', '--name'): nameSet = True name = arg elif opt in ('-v', '--version'): versionSet = True version = arg elif opt in ('-u', '--url'): urlSet = True url = arg elif opt in ('-d', '--description'): descriptionSet = True description = arg elif opt in ('-a', '--architecture'): architectureSet = True architecture = arg elif opt in ('-r', '--requires'): requiresSet = True requires = arg elif opt in ('-l', '--libs'): libsSet = True libs = arg elif opt in ('-c', '--cflags'): compileFlagsSet = True compileFlags = arg elif opt in ('-s', '--static'): staticLibSet = True staticLib = arg elif opt in ('-f', '--file'): fileNameSet = True fileName = arg ##Grab any input not passed in the arguments from the user. if not varSet: varLine = None variables = "" print "%s:" %(varPrompt) while(varLine != ""): varLine = raw_input("") variables = variables + "%s\n" %(varLine) if not nameSet: name = raw_input("%s: " %(namePrompt)) if not descriptionSet: description = raw_input("%s: " %(descriptionPrompt)) if not urlSet: url = raw_input("%s: " %(urlPrompt)) if not versionSet: version = raw_input("%s: " %(versionPrompt)) if not providesSet: provides = raw_input("%s: " %(providesPrompt)) if not requiresSet: requires = raw_input("%s: " %(requirePrompt)) if not architectureSet: architecture = raw_input("%s: " %(architecturePrompt)) if not libsSet: libs = raw_input("%s: " %(libPrompt)) if not staticLibSet: staticLib = raw_input("%s: " %(staticLibPrompt)) if not compileFlagsSet: compileFlags = raw_input("%s: " %(compileFlagsPrompt)) if not fileNameSet: fileName = raw_input("%s: " %(fileNamePrompt)) ##Check the file's name. fileName, writeFile = checkFileName(fileName) ##If they chose not to overwrite, write the file. if writeFile: fpc = open(fileName, 'w') fpc.write("%s" %(variables)) fpc.write("Name: %s\n" %(name)) fpc.write("Description: %s\n" %(description)) fpc.write("URL: %s\n" %(url)) fpc.write("Version: %s\n" %(version)) fpc.write("Provides: %s\n" %(provides)) fpc.write("Requires: %s\n" %(requires)) fpc.write("Arch: %s\n" %(architecture)) fpc.write("Libs: %s\n" %(libs)) fpc.write("Libs.private: %s\n" %(staticLib)) fpc.write("Cflags: %s\n" %(compileFlags)) fpc.close() ##TESTER: Print the file out. fpc = open(fileName, 'r') ##TESTER print fpc.read() ##TESTER fpc.close ##TESTER
Python
#!/usr/bin/env python from distutils.core import setup setup( name='flagpoll', version='0.8.1', description='Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software.', author='Daniel E. Shipton', author_email='dshipton@infiscape.com', license='GPL', url='https://realityforge.vrsource.org/view/FlagPoll/WebHome', download_url='https://realityforge.vrsource.org/view/FlagPoll/FlagpollDownloads', scripts=['flagpoll'], long_description = "Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software. Think of it as the rpm of software development. It enables developers total control over which packages, versions, architectures, etc. that they want to use meta-data from.", data_files=[('share/flagpoll', ['flagpoll.fpc']), ('share/man/man1', ['flagpoll.1']), ('share/aclocal', ['flagpoll.m4'])] )
Python
#!/usr/bin/env python # ----------------------------------------------------------------- # # Flag Poll: A tool to extract flags from installed applications # for compiling, settting variables, etc. # # Original Authors: # Daniel E. Shipton <dshipton@gmail.com> # # Flag Poll is Copyright (C) 2006 by Daniel E. Shipton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to: # Free SoftwareFoundation, Inc. # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # # ----------------------------------------------------------------- """Makes a flagpole .fpc file from user input. v0.9 coded by Jeff Groves""" import os import sys import getopt ##String prompts for the input varPrompt = """Convience variables (one 'var_name= var_definition' per line,""" + \ """ empty line when done)""" namePrompt = "Formal Name" descriptionPrompt = "Description" urlPrompt = "URL" providesPrompt = "One or more names to look package up by: (Provides)" versionPrompt = "Version (x.y.z)" architecturePrompt = "Architecture" requirePrompt = "Requires" libPrompt = "Linker Flags (-lfoo -L/usr/lib)" staticLibPrompt = "Static Linking Flags/Libs (extra private libs)" compileFlagsPrompt = "Compile/Include Flags (-I/usr -fpge -O2)" fileNamePrompt = "FPC File's Name" def usage(): """Prints a list of acceptable arguments for fpcmaker.py.""" print """ Fpcmaker.py Options: -n, --name= : Sets %s -d, --description= : Sets %s -u, --url= : Sets %s -p, --provides= : Sets %s -v, --version= : Sets %s -a, --architecture= : Sets %s -r, --requires= : Sets %s -l, --libs= : Sets %s -c, --cflags= : Sets %s -s, --static= : Sets %s -f, --file= : Sets %s """ %(namePrompt, descriptionPrompt, urlPrompt, providesPrompt, versionPrompt, architecturePrompt, requirePrompt, libPrompt, compileFlagsPrompt, staticLibPrompt, fileNamePrompt) return def checkFileName(fileName): """Checks if the fpc file name's blank, contains slashes, or exists.""" nameCleared = False writeFile = True confirms = ['y', 'Y', 'yes', 'Yes'] ##Loops until the name clears or writing the file's aborted. while(not nameCleared and writeFile): ##If it's blank, give the option of aborting the program. if fileName == "": choice = raw_input("Do you want to abort writing the" + " .fpc file? (Y/N): ") if choice not in confirms: fileName = raw_input("Please enter a different name for the" + " .fpc file: ") else: writeFile = False ##If it contains slashes, ask for another name. elif '/' in fileName or '\\' in fileName: print "I can't write to %s because it contains slashes."%(fileName) fileName = raw_input("Please enter a different name for the" + " .fpc file: ") ##If it already exists, ask if they want to overwrite. ##If not, ask for another name. elif os.path.exists(fileName): choice = raw_input("The file %s already exists." %(fileName) + " Do you want to overwrite it? (Y/N): ") if choice not in confirms: fileName = raw_input("Please enter a different name for the" + " .fpc file: ") else: nameCleared = True else: nameCleared = True return [fileName, writeFile] ##Booleans for whether that argument was sent in the command line varSet = False providesSet = False nameSet = False descriptionSet = False urlSet = False architectureSet = False versionSet = False requiresSet = False libsSet = False compileFlagsSet = False staticLibSet = False fileNameSet = False ##Get the options & arguments sent. arguments = sys.argv[1:] try: opts, args = getopt.getopt(arguments, "p:n:u:d:a:r:v:l:c:s:f:", ["provides=", "name=", "url=", "description=", "architecture=", "requires=", "version=", "libs=", "cflags=", "static=", "file="]) ##Send them usage info if they enter a wrong argument except getopt.GetoptError: usage() sys.exit(2) for opt, arg in opts: if opt in ('-p', '--provides'): providesSet = True provides = arg elif opt in ('-n', '--name'): nameSet = True name = arg elif opt in ('-v', '--version'): versionSet = True version = arg elif opt in ('-u', '--url'): urlSet = True url = arg elif opt in ('-d', '--description'): descriptionSet = True description = arg elif opt in ('-a', '--architecture'): architectureSet = True architecture = arg elif opt in ('-r', '--requires'): requiresSet = True requires = arg elif opt in ('-l', '--libs'): libsSet = True libs = arg elif opt in ('-c', '--cflags'): compileFlagsSet = True compileFlags = arg elif opt in ('-s', '--static'): staticLibSet = True staticLib = arg elif opt in ('-f', '--file'): fileNameSet = True fileName = arg ##Grab any input not passed in the arguments from the user. if not varSet: varLine = None variables = "" print "%s:" %(varPrompt) while(varLine != ""): varLine = raw_input("") variables = variables + "%s\n" %(varLine) if not nameSet: name = raw_input("%s: " %(namePrompt)) if not descriptionSet: description = raw_input("%s: " %(descriptionPrompt)) if not urlSet: url = raw_input("%s: " %(urlPrompt)) if not versionSet: version = raw_input("%s: " %(versionPrompt)) if not providesSet: provides = raw_input("%s: " %(providesPrompt)) if not requiresSet: requires = raw_input("%s: " %(requirePrompt)) if not architectureSet: architecture = raw_input("%s: " %(architecturePrompt)) if not libsSet: libs = raw_input("%s: " %(libPrompt)) if not staticLibSet: staticLib = raw_input("%s: " %(staticLibPrompt)) if not compileFlagsSet: compileFlags = raw_input("%s: " %(compileFlagsPrompt)) if not fileNameSet: fileName = raw_input("%s: " %(fileNamePrompt)) ##Check the file's name. fileName, writeFile = checkFileName(fileName) ##If they chose not to overwrite, write the file. if writeFile: fpc = open(fileName, 'w') fpc.write("%s" %(variables)) fpc.write("Name: %s\n" %(name)) fpc.write("Description: %s\n" %(description)) fpc.write("URL: %s\n" %(url)) fpc.write("Version: %s\n" %(version)) fpc.write("Provides: %s\n" %(provides)) fpc.write("Requires: %s\n" %(requires)) fpc.write("Arch: %s\n" %(architecture)) fpc.write("Libs: %s\n" %(libs)) fpc.write("Libs.private: %s\n" %(staticLib)) fpc.write("Cflags: %s\n" %(compileFlags)) fpc.close() ##TESTER: Print the file out. fpc = open(fileName, 'r') ##TESTER print fpc.read() ##TESTER fpc.close ##TESTER
Python
#!/usr/bin/env python # ----------------------------------------------------------------- # # Flagpoll: A tool to extract flags from installed applications # for compiling, settting variables, etc. # # Original Authors: # Daniel E. Shipton <dshipton@gmail.com> # # Flagpoll is Copyright (C) 2006 by Daniel E. Shipton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to: # Free SoftwareFoundation, Inc. # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # # ----------------------------------------------------------------- import sys, os, glob, os.path, copy, platform pj = os.path.join #################################################################### # SNAGGED FROM PYTHON 2.4 for versions under 2.4 #################################################################### import re as _re class _multimap: """Helper class for combining multiple mappings. Used by .{safe_,}substitute() to combine the mapping and keyword arguments. """ def __init__(self, primary, secondary): self._primary = primary self._secondary = secondary def __getitem__(self, key): try: return self._primary[key] except KeyError: return self._secondary[key] class _TemplateMetaclass(type): pattern = r""" %(delim)s(?: (?P<escaped>%(delim)s) | # Escape sequence of two delimiters (?P<named>%(id)s) | # delimiter and a Python identifier {(?P<braced>%(id)s)} | # delimiter and a braced identifier (?P<invalid>) # Other ill-formed delimiter exprs ) """ def __init__(cls, name, bases, dct): super(_TemplateMetaclass, cls).__init__(name, bases, dct) if 'pattern' in dct: pattern = cls.pattern else: pattern = _TemplateMetaclass.pattern % { 'delim' : _re.escape(cls.delimiter), 'id' : cls.idpattern, } cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE) class Template: """A string class for supporting $-substitutions.""" __metaclass__ = _TemplateMetaclass delimiter = '$' idpattern = r'[_a-z][_a-z0-9]*' def __init__(self, template): self.template = template # Search for $$, $identifier, ${identifier}, and any bare $'s def _invalid(self, mo): i = mo.start('invalid') lines = self.template[:i].splitlines(True) if not lines: colno = 1 lineno = 1 else: colno = i - len(''.join(lines[:-1])) lineno = len(lines) raise ValueError('Invalid placeholder in string: line %d, col %d' % (lineno, colno)) def substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): # Check the most common path first. named = mo.group('named') or mo.group('braced') if named is not None: val = mapping[named] # We use this idiom instead of str() because the latter will # fail if val is a Unicode containing non-ASCII characters. return '%s' % val if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: self._invalid(mo) raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) def safe_substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): named = mo.group('named') if named is not None: try: # We use this idiom instead of str() because the latter # will fail if val is a Unicode containing non-ASCII return '%s' % mapping[named] except KeyError: return self.delimiter + named braced = mo.group('braced') if braced is not None: try: return '%s' % mapping[braced] except KeyError: return self.delimiter + '{' + braced + '}' if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: return self.delimiter raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) #################################################################### # End Snagging #################################################################### class Utils: # Holds collection of small utility functions EXTRA_FLAGPOLL_SEARCH_PATHS = "" EXTRA_FLAGPOLL_FILES = "" path_list_cache = None # Cache of found path lists. (only calcuate once) KEEP_DUPS = False def getFlagpollVersion(): FLAGPOLL_MAJOR_VERSION = 0 FLAGPOLL_MINOR_VERSION = 8 FLAGPOLL_PATCH_VERSION = 1 return ( FLAGPOLL_MAJOR_VERSION, FLAGPOLL_MINOR_VERSION, FLAGPOLL_PATCH_VERSION ) getFlagpollVersion = staticmethod(getFlagpollVersion) def getPathList(): if None != Utils.path_list_cache: return Utils.path_list_cache #TODO: expand LD_LIBRARY_PATH to 64/32/etc??? pkg_cfg_dir = [] flg_cfg_dir = [] ld_path = [] if os.environ.has_key("PKG_CONFIG_PATH"): pkg_cfg_dir = os.environ["PKG_CONFIG_PATH"].split(os.pathsep) if os.environ.has_key("FLAGPOLL_PATH"): flg_cfg_dir = os.environ["FLAGPOLL_PATH"].split(os.pathsep) ld_dirs = ['LD_LIBRARY_PATH', 'DYLD_LIBRARY_PATH'] for d in ld_dirs: if os.environ.has_key(d): cur_path = os.environ[d].split(os.pathsep) ld_path_pkg = [pj(p,'pkgconfig') for p in cur_path] ld_path_flg = [pj(p,'flagpoll') for p in cur_path] ld_path.extend(ld_path_pkg) ld_path.extend(ld_path_flg) extra_paths = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS.split(os.pathsep) path_list = ["/usr/lib64/pkgconfig", "/usr/lib/pkgconfig", "/usr/share/pkgconfig", "/usr/lib64/flagpoll", "/usr/lib/flagpoll", "/usr/share/flagpoll"] path_list.extend(pkg_cfg_dir) path_list.extend(flg_cfg_dir) path_list.extend(extra_paths) path_list.extend(ld_path) flagDBG().out(flagDBG.VERBOSE, "Utils.getPathList", "Potential path list: " + str(path_list)) path_list = [p for p in path_list if os.path.exists(p)] flagDBG().out(flagDBG.INFO, "Utils.getPathList", "Using path list: " + str(path_list)) Utils.path_list_cache = path_list return path_list getPathList = staticmethod(getPathList) def getFileList(): flist = Utils.EXTRA_FLAGPOLL_FILES.split(":") filelist = [] for f in flist: if os.path.isfile(f): filelist.append(f) return filelist getFileList = staticmethod(getFileList) def setKeepDups(keep_dups): Utils.KEEP_DUPS = keep_dups setKeepDups = staticmethod(setKeepDups) def stripDupInList(gen_list): new_list = [] for item in gen_list: item = item.strip() if Utils.KEEP_DUPS: if len(item) > 0: new_list.append(item) continue if item not in new_list: if len(item) > 0: new_list.append(item) return new_list stripDupInList = staticmethod(stripDupInList) def stripDupLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] dir_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-L") or flg.startswith("-R"): dir_list.append(flg) else: lib_list.append(flg) new_list = dir_list + lib_list return Utils.stripDupInList(new_list) stripDupLinkerFlags = staticmethod(stripDupLinkerFlags) def stripDupIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] extra_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-I"): inc_list.append(flg) else: extra_list.append(flg) extra_list.sort() new_list = inc_list + extra_list return Utils.stripDupInList(new_list) stripDupIncludeFlags = staticmethod(stripDupIncludeFlags) def cflagsOnlyDirIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-I"): inc_list.append(flg) return Utils.stripDupInList(inc_list) cflagsOnlyDirIncludeFlags = staticmethod(cflagsOnlyDirIncludeFlags) def cflagsOnlyOtherIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though extra_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if not flg.startswith("-I"): extra_list.append(flg) return Utils.stripDupInList(extra_list) cflagsOnlyOtherIncludeFlags = staticmethod(cflagsOnlyOtherIncludeFlags) def libsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-l"): lib_list.append(flg) return Utils.stripDupInList(lib_list) libsOnlyLinkerFlags = staticmethod(libsOnlyLinkerFlags) def libsOnlyOtherLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though other_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if not flg.startswith("-l") and not flg.startswith("-L") and not flg.startswith("-R"): other_list.append(flg) return Utils.stripDupInList(other_list) libsOnlyOtherLinkerFlags = staticmethod(libsOnlyOtherLinkerFlags) def libDirsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though dir_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-L") or flg.startswith("-R"): dir_list.append(flg) return Utils.stripDupInList(dir_list) libDirsOnlyLinkerFlags = staticmethod(libDirsOnlyLinkerFlags) def printList(gen_list): list_string = "" for item in gen_list: if len(item) > 0: list_string += str(item) list_string += " " print list_string.strip() printList = staticmethod(printList) def parsePcFile(filename): lines = open(filename).readlines() fvars = {} fvars["FlagpollFilename"] = filename lokals = {} lokals["fp_file_cwd"] = str(filename[:- ((len(os.path.basename(filename) ) + 1))]) lines.append("prefix: ${prefix}") append_next = False append_dict = {} append_key = "" for line in lines: line = line.strip() if not line: continue if append_next: tmp = append_dict[append_key] tmp = tmp[:-1] + " " + line append_dict[append_key] = tmp if tmp[-1:] == "\\": append_next = True else: append_next = False continue if line.startswith("#"): continue eq_pos = line.find('=') col_pos = line.find(':') if eq_pos < col_pos and eq_pos != -1 or col_pos == -1 and eq_pos != -1: # local variable name, val = line.split('=', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(lokals) except ValueError: flagDBG().out(flagDBG.WARN, "PkgInfo.parse", "%s has an invalid metadata file" % filename) lokals[name] = val if val[-1:] == "\\": append_next = True append_dict = lokals append_key = name continue if col_pos < eq_pos and col_pos != -1 or eq_pos == -1 and col_pos != -1: # exported variable name, val = line.split(':', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(lokals) except ValueError: flagDBG().out(flagDBG.ERROR, "PkgInfo.parse", "%s has an invalid metadata file" % filename) fvars[name] = val if val[-1:] == "\\": append_next = True append_dict = fvars append_key = name return fvars parsePcFile = staticmethod(parsePcFile) class flagDBG(object): # Logging class is really easy to use # Levels: # 0 - VERBOSE # 1 - INFO # 2 - WARN # 3 - ERROR VERBOSE = 0 INFO = 1 WARN = 2 ERROR = 3 __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if flagDBG.__initialized: return flagDBG.__initialized = True self.mLevel = self.WARN self.mLevelList = ["VERBOSE", "INFO", "WARN", "ERROR"] def setLevel(self, level): if level <= 3: self.mLevel = level def out(self, level, obj, message): if level == self.ERROR: if self.mLevel == self.VERBOSE: print self.mLevelList[level] + ":" + str(obj) + ": " + str(message) else: print self.mLevelList[level] + ": " + str(message) sys.exit(1) if level >= self.mLevel: print self.mLevelList[level] + ":" + str(obj) + ": " + str(message) class DepResolutionSystem(object): """ You add PkgAgents with Filters into system and call resolve() you can check for succes by depsSatisfied() and get the list of packages that work back by calling getPackages() """ __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if DepResolutionSystem.__initialized: return DepResolutionSystem.__initialized = True self.mResolveAgents = [] self.mAgentDict = {} self.mFilters = [] self.mResolveAgentFilters = [] self.mInvalidPackageList = [] self.mSatisfied = False self.mAgentChangeList = [] # list of those responsible for adding Filters # to agents in higher in the chain than them # these are the first agents to ask that they pick # the next best package of them self.mAgentsVisitedList = [] # list of Agents that have been visited self.mResolvedPackageList = [] # list that is generated when deps are satified self.mCheckPrivateRequires = False self.mMadeDependList = False def getFilters(self): return self.mFilters def addFilter(self, filter): self.mFilters.append(filter) def addResolveAgentFilter(self, filter): self.mResolveAgentFilters.append(filter) def makeRequireFilter(self, requires): arch_list = [] arch_list.append("no_arch") arch_list.append("") if platform.system() == "Linux": if requires == "64": arch_list.append("x86_64") if requires == "32": arch_list.append("i386") arch_list.append("i486") arch_list.append("i586") arch_list.append("i686") if platform.system() == "Darwin": if requires == "64": arch_list.append("ppc64") if requires == "32": arch_list.append("ppc") if platform.system().startswith("IRIX"): arch_list.append(requires) new_filter = Filter("Arch", lambda x,v=arch_list: x in v) self.addFilter(new_filter) def createAgent(self, name): if self.checkAgentExists(name): return self.getAgent(name) else: agent = PkgAgent(name) flagDBG().out(flagDBG.INFO, "DepResSys.createAgent", "Adding %s" % name) self.addNewAgent(agent) return agent def createResolveAgent(self, name): if self.checkAgentExists(name): return self.getAgent(name) else: agent = PkgAgent(name) flagDBG().out(flagDBG.INFO, "DepResSys.createResolveAgent", "Adding %s" % name) self.addResolveAgent(agent) return agent def setPrivateRequires( self, req ): self.mCheckPrivateRequires = req def checkPrivateRequires(self): return self.mCheckPrivateRequires def checkAgentExists(self, name): return self.mAgentDict.has_key(name) def getAgent(self, name): if self.mAgentDict.has_key(name): return self.mAgentDict[name] else: flagDBG().out(flagDBG.ERROR, "DepResSys.getAgent", "Agent %s does not exist" % name) def addNewAgent(self, agent): if not self.checkAgentExists(agent): self.mAgentDict[agent.getName()] = agent def addResolveAgent(self, agent): if agent not in self.mResolveAgents: self.mResolveAgents.append(agent) for filt in self.mResolveAgentFilters: agent.addFilter(filt) def isSatisfied(self): return self.mSatisfied def updateResolvedPackages(self): pkg_list = [] agent_list = [] for agent in self.mResolveAgents: list_of_pkgs = agent.getCurrentPackageList(agent_list) pkg_list.extend(list_of_pkgs) self.mResolvedPackageList = pkg_list def getPackages(self): flagDBG().out(flagDBG.INFO, "DepResSys.getPackages", "Generating list of valid packages ") #str([pkg.getCurrentPackage.getName() for pkg in self.mResolvedPackageList])) # If this comes back empty then there isn't a valid set of packages to use self.updateResolvedPackages() return self.mResolvedPackageList def checkFiltersChanged(self): list_to_use = [] return True in [pkg.filtersChanged(list_to_use) for pkg in self.mResolveAgents] def resolveHelper(self): self.resolveAgentsChanged = True while self.resolveAgentsChanged: for agent in self.mResolveAgents: flagDBG().out(flagDBG.INFO, "DepResSys.resolveHelper", "Updating " + agent.getName()) agent.update(self.mAgentsVisitedList, self.mAgentChangeList) self.resolveAgentsChanged = self.checkFiltersChanged() # Ask mResolveAgents if they are done(they ask sub people) unless they are # really above you in the walk # If there were changes...run update on mResolveAgents again # at the end ask for pkglist..if it comes back empty then we don't # have a usable configuration for those packages def resolveDeps(self): self.resolveHelper() if not self.mMadeDependList: for agent in self.mResolveAgents: agent.makeDependList() self.mMadeDependList = True self.updateResolvedPackages() # Check if the first round through we found something # Otherwise we need to start removing packages that aren't viable # during the loop self.mSatisfied = (len(self.mResolvedPackageList) != 0) # remove top of packages that added Filters. # then move on to resolving again # remove more if neccesary agentChangeNumber = 0 while not self.mResolvedPackageList: if(self.mAgentChangeList[agentChangeNumber]): if self.mAgentChangeList[agentChangeNumber] in self.mInvalidPackageList: agentChangeNumber += 1 else: if(self.mAgentChangeList[agentChangeNumber].getViablePackages()): flagDBG().out(flagDBG.INFO, "DepResSys.resolveDeps", "Removing bad pkg from " + self.mAgentChangeList[agentChangeNumber].getName()) self.mInvalidPackageList.append(self.mAgentChangeList[agentChangeNumber].removeCurrentPackage()) else: flagDBG().out(flagDBG.INFO, "DepResSys.resolveDeps", "No combinations.. Resetting " + self.mAgentChangeList[agentChangeNumber].getName()) self.mAgentChangeList[agentChangeNumber].reset() agentChangeNumber += 1 self.resolveHelper() self.updateResolvedPackages() self.mSatisfied = (len(self.mResolvedPackageList) != 0) return class PkgAgent: """ Agent that keeps track of the versions for a package given some filters and the addition of Filters """ # Makes a PkgAgent that finds its current package with the version reqs def __init__(self, name): if DepResolutionSystem().checkAgentExists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "Package Agent %s already exists" % self.mName) self.mName = name flagDBG().out(flagDBG.INFO, "PkgAgent", "Creating:" + str(self.mName)) if not PkgDB().exists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "No info for package: %s" % self.mName) #XXX Doesn't keep filters added for a redo... DepResolutionSystem().addNewAgent(self) self.mFilterList = [] self.mFilterList.extend(DepResolutionSystem().getFilters()) self.mBasePackageList = PkgDB().getPkgInfos(name) self.mBasePackageList.sort(lambda lhs, rhs: cmp(rhs.getVariable('Version'), lhs.getVariable('Version'))) for filt in self.mFilterList: self.mBasePackageList = filt.filter(self.mBasePackageList) if len(self.mBasePackageList) == 0: flagDBG().out(flagDBG.ERROR, "PkgAgent", "No viable packages for: %s" % self.mName) self.mViablePackageList = copy.deepcopy(self.mBasePackageList) if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mFiltersChanged = True self.mCheckDepends = True self.mAgentDependList = [] def getName(self): return self.mName def setCheckDepends(self, tf): self.mCheckDepends = tf #Filter("Version", lambda x: x == "4.5") def makeDependList(self): if not self.mCheckDepends: self.mAgentDependList = [] return dep_list = [] if self.mCurrentPackage: req_string = self.mCurrentPackage.getVariable("Requires") if DepResolutionSystem().checkPrivateRequires(): req_string = req_string + " " + self.mCurrentPackage.getVariable("Requires.private") req_string = req_string.strip() if req_string == "": return req_string = req_string.replace(',', ' ') req_string = req_string.replace('(', ' ') req_string = req_string.replace(')', ' ') space_req_string_list = req_string.split(' ') req_string_list = [] for entry in space_req_string_list: if len(entry) > 0: req_string_list.append(entry) i = 0 flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList", self.mCurrentPackage.getName() + " requires: " + str(req_string_list)) while len(req_string_list) > i: if PkgDB().exists(req_string_list[i]): new_filter = [] new_agent = DepResolutionSystem().createAgent(req_string_list[i]) if len(req_string_list) > i+1: if req_string_list[i+1] == "=": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x == v) elif req_string_list[i+1] == "<=": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x <= v) elif req_string_list[i+1] == ">=": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x >= v) elif req_string_list[i+1] == ">": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x > v) elif req_string_list[i+1] == "<": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x < v) else: i += 1 else: i += 1 dep_list.append(new_agent) if new_filter: i+=3 new_agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "PkgAgent.makeDependList", "Package %s depends on %s but does not seem to be installed." % (self.mName, str(req_string_list[i]))) flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList", str(self.mName) + " : List is:" + str([pkg.getName() for pkg in dep_list])) self.mAgentDependList = dep_list def filtersChanged(self, packageList): tf_list = [self.mFiltersChanged] if self.mName not in packageList: packageList.append(self.mName) for pkg in self.mAgentDependList: tf_list.append(pkg.filtersChanged(packageList)) return True in tf_list def getCurrentPackageList(self, packageList): pkgs = [] if self.mName not in packageList: flagDBG().out(flagDBG.INFO, "PkgAgent.getCurrentPackageList", "Package: %s" % self.mName) pkgs.append(self.mCurrentPackage) packageList.append(self.mName) # Make depend list if we are supposed to self.updateFilters() self.makeDependList() for pkg in self.mAgentDependList: pkgs.extend(pkg.getCurrentPackageList(packageList)) return pkgs # current pkginfo for me def getCurrentPkgInfo(self): return self.mCurrentPackage # Someone else usually places these on me # I keep track of those separately def addFilter(self, filter): flagDBG().out(flagDBG.INFO, "PkgAgent.addFilter", "Filter %s" % self.mName + " on %s." % filter.getVarName()) self.mFiltersChanged = True self.mFilterList.append(filter) def removeCurrentPackage(self): flagDBG().out(flagDBG.INFO, "PkgAgent.removeCurrentPackage", "Removing current package of %s" % self.mName) if self.mViablePackageList: ret_val = self.mViablePackageList[0] in self.mBasePackageList del self.mViablePackageList[0] if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] return ret_val def update(self, agentVisitedList, agentChangeList): flagDBG().out(flagDBG.INFO, "PkgAgent.update", "%s" % self.mName) if self.mName in agentVisitedList: return agentVisitedList.append(self.mName) if self.mFiltersChanged: self.mFiltersChanged = False self.updateFilters() # TODO: checkFilters and add them # if a pkg is in visitedList then add yourself to agentChangeList for pkg in self.mAgentDependList: pkg.update(agentVisitedList, agentChangeList) return def updateFilters(self): for filt in self.mFilterList: self.mViablePackageList = filt.filter(self.mViablePackageList) flagDBG().out(flagDBG.INFO, "PkgAgent.updateFilters", "%s has " % self.mName + str(len(self.mViablePackageList)) + " left") if len(self.mViablePackageList) > 0: self.mCurrentPackage = self.mViablePackageList[0] else: self.mCurrentPackage = [] def reset(self): flagDBG().out(flagDBG.INFO, "PkgAgent.reset", "Resetting package: %s" % self.mName) self.mViablePackageList = self.mBasePackageList if self.mViablePackageList: self.mCurrentPacakge = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mFilterList = DepResolutionSystem().getFilters() self.mAgentDependList = [] self.mFiltersChanged = True return class Filter: """ A single Filter that knows how to filter the list it recieves Will be inheireted....?..? """ def __init__(self, variableName, testCallable): self.mVarName = variableName self.mTestCallable = testCallable def getVarName(self): return self.mVarName def filter(self, pkg_info_list): ret_pkg_list = [] # Filter first for pkg in pkg_info_list: var = pkg.getVariable(self.mVarName) if self.mTestCallable(var): flagDBG().out(flagDBG.INFO, "Filter", "Passed: %s:" % pkg.getName() + " %s is " % self.mVarName + str(var)) ret_pkg_list.append(pkg) else: flagDBG().out(flagDBG.INFO, "Filter", "Failed: %s:" % pkg.getName() + " %s is " % self.mVarName + str(var)) # Now sort ret_pkg_list.sort(lambda lhs, rhs: cmp(rhs.getVariable(self.mVarName), lhs.getVariable(self.mVarName))) return ret_pkg_list #requires: qt == 4.5 #Filter("Version", lambda x: x <= "4.5") #Filter("Version", lambda x: x <= "4.5") class PkgDB(object): """ Holds all the neccesary information to evaluate itself when needed. Is in charge of holding a list of PkgInfo's that contain info about the package. """ __initialized = False def __init__(self): if self.__initialized: return self.__initialized = True self.mPkgInfos = {} # {pkg_name: List of package infos} self.populatePkgInfoDBPcFiles() self.populatePkgInfoDBFpcFiles() def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def printAllPackages(self): list_of_package_names = [] for pkg in self.mPkgInfos: list_of_package_names.append(pkg) for name in list_of_package_names: print name sys.exit(0) def getVariables(self, name, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariable", "Finding " + str(variable_list) + " in " + str(name)) ret_list = [] for var in variable_list: if self.mPkgInfos.has_key(name): ret_list.extend(self.mPkgInfos[name][0].getVariable(var)) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariable", "Package %s not found." % name) return ret_list def checkPackage(self, name): flagDBG().out(flagDBG.INFO, "PkgDB.checkPackage", "Finding " + str(name)) if self.mPkgInfos.has_key(name): return True else: flagDBG().out(flagDBG.ERROR, "PkgDB.CheckPackage", "Package %s not found." % name) return False def getVariablesAndDeps(self, pkg_list, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariablesAndDeps", "Finding " + str(variable_list) + " in " + str(pkg_list)) if DepResolutionSystem().checkPrivateRequires(): temp_var_list = [] for var in variable_list: temp_var_list.append(var.join(".private")) variable_list = variable_list + temp_var_list for name in pkg_list: if self.mPkgInfos.has_key(name): agent = DepResolutionSystem().createAgent(name) DepResolutionSystem().addResolveAgent(agent) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariablesAndDeps", "Package %s not found." % name) DepResolutionSystem().resolveDeps() pkgs = DepResolutionSystem().getPackages() var_list = [] for pkg in pkgs: if pkg: for var in variable_list: var_list.extend(pkg.getVariable(var).split(' ')) return var_list def getPkgInfos(self, name): if self.mPkgInfos.has_key(name): return self.mPkgInfos[name] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getPkgInfos", "Package %s not found." % name) def exists(self, name): return self.mPkgInfos.has_key(name) def getInfo(self, name): if self.mPkgInfos.has_key(name): return [pkg.getInfo() for pkg in self.mPkgInfos[name]] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getInfo", "Package %s not found." % name) def buildPcFileDict(self): """ Builds up a dictionary of {name: list of files for name} """ pc_dict = {} for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.pc")) # List of .pc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these pc files: %s" % str(glob_list)) for g in glob_list: # Get key name and add file to value list in dictionary key = os.path.basename(g)[:-3] # Strip .pc off the filename...rstrip no worky pc_dict.setdefault(key, []).append(g) for f in Utils.getFileList(): if f.endswith(".pc"): key = os.path.basename(f)[:-3] # Strip .pc off the filename...rstrip no worky pc_dict.setdefault(key, []).append(f) return pc_dict # { "key", [ "list", "of", "corresponding", "pc", "files"] } def populatePkgInfoDBPcFiles(self): dict_to_pop_from = self.buildPcFileDict() for (pkg,files) in dict_to_pop_from.iteritems(): for f in files: self.mPkgInfos.setdefault(pkg,[]).append(PkgInfo(pkg, f, "pc")) def buildFpcFileList(self): """ Builds up a dictionary of {name: list of files for name} """ file_list = [] for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.fpc")) # List of .fpc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these fpc files: %s" % str(glob_list)) for g in glob_list: file_list.append(g) for f in Utils.getFileList(): if f.endswith(".fpc"): file_list.append(f) return file_list # [ "list", "of", "fpc", "files"] def populatePkgInfoDBFpcFiles(self): list_to_add = self.buildFpcFileList() for filename in list_to_add: var_dict = Utils.parsePcFile(filename) if not var_dict.has_key("Provides"): flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Provides" % str(filename)) continue if not var_dict.has_key("Arch"): flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Arch" % str(filename)) continue provides_string = var_dict["Provides"] provides_string = provides_string.replace(',', ' ') provides_string = provides_string.replace('(', ' ') provides_string = provides_string.replace(')', ' ') for key in provides_string.split(" "): if len(key) > 0: self.mPkgInfos.setdefault(key, []).append(PkgInfo(key, filename, "fpc", var_dict)) class PkgInfo: """ Holds the information for a package file on the system. These however are evaluated when the need arises. """ def __init__(self, name, file, type, varDict={}): self.mName = name self.mFile = file self.mIsEvaluated = False self.mType = type self.mVariableDict = varDict if self.mType == "fpc": self.mIsEvaluated = True def getVariable(self, variable): self.evaluate() return self.mVariableDict.get(variable,"") def getName(self): return self.mName def evaluate(self): if not self.mIsEvaluated: flagDBG().out(flagDBG.INFO, "PkgInfo.evaluate", "Evaluating %s" % self.mName) self.mVariableDict= Utils.parsePcFile(self.mFile) self.mIsEvaluated = True def getInfo(self): self.evaluate() return self.mVariableDict class OptionsEvaluator: def __init__(self): if len(sys.argv) < 2: self.printHelp() # This is only the args....(first arg is stripped) def evaluateArgs(self, args): # Catch any args that need to be tended to immediately # Process args in the order that they were recieved. Some options are not # shown below because they are sub-options of an option below (--strip-dups) for option in args: if option.startswith("--verbose-debug"): flagDBG().setLevel(flagDBG.VERBOSE) if option.startswith("--debug"): flagDBG().setLevel(flagDBG.INFO) elif option.startswith("--from-file"): val_start = option.find('=') + 1 file = option[val_start:] Utils.EXTRA_FLAGPOLL_FILES = Utils.EXTRA_FLAGPOLL_FILES + ":" + file elif option.startswith("--help"): self.printHelp() sys.exit(0) elif option.startswith("--version"): print "%s.%s.%s" % Utils.getFlagpollVersion() sys.exit(0) elif option.startswith("--list-all"): PkgDB().printAllPackages() continue listedAgentNames = [] agent = None num_args = len(args) curr_arg = 0 output_options = [] # (option, name/"") important_options = [] # ones that need special attention while curr_arg < num_args: if args[curr_arg].startswith("--atleast-version"): val_start = args[curr_arg].find('=') + 1 atleast_version = args[curr_arg][val_start:] atleast_filter = Filter("Version", lambda x,v=atleast_version: x >= v) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(atleast_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --at-least-version") continue if args[curr_arg].startswith("--cflags-only-I"): output_options.append(("cflags-only-I", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--cflags-only-other"): output_options.append(("cflags-only-other", "")) curr_arg = curr_arg + 1 continue #This could be the catch all for the above ones to and then filter based on what is asked... #For clarity of course... if args[curr_arg].startswith("--cflags"): output_options.append(("cflags", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--extra-paths"): val_start = args[curr_arg].find('=') + 1 paths = args[curr_arg][val_start:] Utils.EXTRA_FLAGPOLL_SEARCH_PATHS = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS + ":" + paths curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--exact-version"): val_start = args[curr_arg].find('=') + 1 exact_version = args[curr_arg][val_start:] exact_filter = Filter("Version", lambda x,v=exact_version: x == v) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(exact_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --exact-version") continue if args[curr_arg].startswith("--exists"): important_options.append("exists") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--from-file"): val_start = args[curr_arg].find('=') + 1 file = args[curr_arg][val_start:] file_filter = Filter("FlagpollFilename", lambda x,f=file: x == f) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(file_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --from-file") continue if args[curr_arg].startswith("--info"): important_options.append("info") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--print-pkg-options"): important_options.append("print-pkg-options") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--keep-dups"): Utils.setKeepDups(True) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-l"): output_options.append(("libs-only-l", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-L"): output_options.append(("libs-only-L", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-other"): output_options.append(("libs-only-other", "")) curr_arg = curr_arg + 1 continue #This could be the catch all for the above ones to and then filter based on what is asked... if args[curr_arg].startswith("--libs"): output_options.append(("libs", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--require-all"): rlen = len("--require-all") req_string = args[curr_arg][rlen:] req_string = req_string.replace('-','_') curr_arg = curr_arg + 1 if req_string.find("<=") != -1: op_start = req_string.find("<=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x <= v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find(">=") != -1: op_start = req_string.find(">=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x >= v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find(">") != -1: op_start = req_string.find(">") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x > v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("<") != -1: op_start = req_string.find("<") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x < v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("=") != -1: op_start = req_string.find("=") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x == v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("=") == -1: new_filter = Filter(req_string, lambda x: len(x) > 0) DepResolutionSystem().addFilter(new_filter) continue continue if args[curr_arg].startswith("--require-"): rlen = len("--require-") req_string = args[curr_arg][rlen:] req_string = req_string.replace('-','_') curr_arg = curr_arg + 1 if agent is None: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --require") if req_string.find("<=") != -1: op_start = req_string.find("<=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x <= v) agent.addFilter(new_filter) continue if req_string.find(">=") != -1: op_start = req_string.find(">=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x >= v) agent.addFilter(new_filter) continue if req_string.find(">") != -1: op_start = req_string.find(">") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x > v) agent.addFilter(new_filter) continue if req_string.find("<") != -1: op_start = req_string.find("<") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x < v) agent.addFilter(new_filter) continue if req_string.find("=") != -1: op_start = req_string.find("=") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x == v) agent.addFilter(new_filter) continue if req_string.find("=") == -1: new_filter = Filter(req_string, lambda x: len(x) > 0) agent.addFilter(new_filter) continue continue if args[curr_arg].startswith("--no-deps"): if agent is not None: agent.setCheckDepends(False) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --no-deps") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--require="): val_start = args[curr_arg].find('=') + 1 req_var = args[curr_arg][val_start:] curr_arg = curr_arg + 1 DepResolutionSystem().makeRequireFilter(req_var) continue if args[curr_arg].startswith("--modversion"): if agent is not None: output_options.append(("Version", agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --modversion") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--max-release"): val_start = args[curr_arg].find('=') + 1 max_release = args[curr_arg][val_start:] max_filter = Filter("Version", lambda x,v=max_release: x.startswith(v)) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(max_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --max-release") continue if args[curr_arg].startswith("--static"): DepResolutionSystem().setPrivateRequires(True) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--variable"): val_start = args[curr_arg].find('=') + 1 fetch_var = args[curr_arg][val_start:] if agent is not None: output_options.append((fetch_var, agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --variable") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--get-all"): rlen = len("--get-all-") get_string = args[curr_arg][rlen:] get_string = get_string.replace('-','_') output_options.append((get_string, "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--get"): rlen = len("--get-") get_string = args[curr_arg][rlen:] get_string = get_string.replace('-','_') if agent is not None: output_options.append((get_string, agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --get") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--concat"): important_options.append("concat") curr_arg = curr_arg + 1 continue if not args[curr_arg].startswith("--"): name = args[curr_arg] curr_arg = curr_arg + 1 if PkgDB().checkPackage(name): agent = DepResolutionSystem().createResolveAgent(name) listedAgentNames.append(name) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Package %s" % name) sys.exit(1) continue if args[curr_arg] != "--debug": flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Option: %s" % args[curr_arg]) curr_arg = curr_arg + 1 DepResolutionSystem().resolveDeps() pkgs = DepResolutionSystem().getPackages() for p in pkgs: if not p: for option in important_options: if option == "exists": print "no" sys.exit(1) flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found") if len(pkgs) == 0: for option in important_options: if option == "exists": print "no" sys.exit(1) flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found") sys.exit(1) concat = False for option in important_options: if option == "exists": print "yes" return sys.exit(0) # already checked for none above if option == "concat": concat = True if option == "info": pkg_info_list = [] for pkg in pkgs: if pkg.getName() in listedAgentNames: print pkg.getName() pkg_info = pkg.getInfo() for key in pkg_info.keys(): print " %s : %s" % (key, pkg_info[key]) if option == "print-pkg-options": print "" print "All options below would start with (--get-/--get-all-/--require-/--require-all-)" print "NOTE: this list does not include the standard variables that are exported." print "" for pkg in pkgs: if pkg.getName() not in listedAgentNames: continue print "Package: " + pkg.getName() for key in pkg.getInfo().keys(): if key not in [ "Name", "Description", "URL", "Version", "Requires", "Requires.private", "Conflicts", "Libs", "Libs.private", "Cflags", "Provides", "Arch", "FlagpollFilename", "prefix" ]: print " " + key.replace('_','-') #print output_options #output_options = [] #output_single = [] #Process options here.............. concat_list = [] if concat: print_option = lambda x: concat_list.extend(x) else: print_option = lambda x: Utils.printList(x) for option in output_options: if option[0] == "cflags": print_option(Utils.stripDupIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "cflags-only-I": print_option(Utils.cflagsOnlyDirIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "cflags-only-other": print_option(Utils.cflagsOnlyOtherIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "libs-only-l": print_option(Utils.libsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs-only-L": print_option(Utils.libDirsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs-only-other": print_option(Utils.libsOnlyOtherLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs": print_option(Utils.stripDupLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) else: print_option(Utils.stripDupInList(self.getVarFromPkgs(option[0], pkgs, option[1]))) if concat: Utils.printList(Utils.stripDupInList(concat_list)) def getVarFromPkgs(self, var, pkgs, pkg_name=""): var_list = [] ext_vars = [] if var == "Libs": if DepResolutionSystem().checkPrivateRequires: ext_vars.append("Libs.private") if pkg_name == "": for pkg in pkgs: if pkg: var_list.extend(pkg.getVariable(var).split(' ')) for extra_var in ext_vars: var_list.extend(pkg.getVariable(extra_var).split(' ')) else: for pkg in pkgs: if pkg: if pkg.getName() == pkg_name: var_list.extend(pkg.getVariable(var).split(' ')) for extra_var in ext_vars: var_list.extend(pkg.getVariable(extra_var).split(' ')) return var_list def printHelp(self): print "usage: flagpoll pkg options [pkg options] [generic options]" print " " print "generic options:" print " --help show this help message and exit" print " --version output version of flagpoll" print " --list-all list all known packages" print " --debug show debug information" print " --verbose-debug show verbose debug information" print " --extra-paths=EXTRA_PATHS" print " extra paths for flagpoll to search for meta-data files" print " --concat concatenate all output and output as one line" print " --keep-dups do not strip out all duplicate info from options" print " --info show information for packages" print " --print-pkg-options show pkg specific options" print " " print "options:" print " --modversion output version for package" print " --require=REQUIRE adds additional requirements for packages ex. 32/64" print " --libs output all linker flags" print " --static output linker flags for static linking" print " --libs-only-l output -l flags" print " --libs-only-other output other libs (e.g. -pthread)" print " --libs-only-L output -L flags" print " --cflags output all pre-processor and compiler flags" print " --cflags-only-I output -I flags" print " --cflags-only-other output cflags not covered by the cflags-only-I option" print " --exists return 0 if the module(s) exist" print " --from-file=FILE use the specified FILE for the package" #print " --print-provides print which packages the package provides" #print " --print-requires print which packages the package requires" print " --no-deps do not lookup dependencies for the package" print " --atleast-version=ATLEAST_VERSION" print " return 0 if the module is at least version" print " ATLEAST_VERSION" print " --exact-version=EXACT_VERSION" print " return 0 if the module is exactly version" print " EXACT_VERSION" print " --max-release=MAX_RELEASE" print " return 0 if the module has a release that has a" print " version of MAX_RELEASE and will return the max" print " --variable=VARIABLE get the value of a variable" print " " print "dynamic options(replace VAR with a variable you want to get/filter on)" print " NOTE: replace underscores with dashes in VAR" print " NOTE: quotes are needed around <,>,= combinations" print " --get-VAR get VAR from package" print " --get-all-VAR get VAR from package and its deps" print " --require-VAR[<,>,=VAL]" print " require that a var is defined for a package" print " or optionally use equality operators against VAL" print " --require-all-VAR[<,>,=VAL]" print " require that a var is defined for all packages" print " or optionally use equality operators against VAL" print "" print "extending search path" print " FLAGPOLL_PATH environment variable that can be set to" print " extend the search path for .fpc/.pc files" sys.exit(0) def main(): # GO! # Initialize singletons and the start evaluating my_dbg = flagDBG() my_dep_system = DepResolutionSystem() opt_evaluator = OptionsEvaluator() opt_evaluator.evaluateArgs(sys.argv[1:]) sys.exit(0) if __name__ == "__main__": main()
Python
#!/usr/bin/env python from distutils.core import setup setup( name='flagpoll', version='0.8.1', description='Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software.', author='Daniel E. Shipton', author_email='dshipton@infiscape.com', license='GPL', url='https://realityforge.vrsource.org/view/FlagPoll/WebHome', download_url='https://realityforge.vrsource.org/view/FlagPoll/FlagpollDownloads', scripts=['flagpoll'], long_description = "Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software. Think of it as the rpm of software development. It enables developers total control over which packages, versions, architectures, etc. that they want to use meta-data from.", data_files=[('share/flagpoll', ['flagpoll.fpc']), ('share/man/man1', ['flagpoll.1']), ('share/aclocal', ['flagpoll.m4'])] )
Python
#!/usr/bin/env python # ----------------------------------------------------------------- # # Flagpoll: A tool to extract flags from installed applications # for compiling, settting variables, etc. # # Original Authors: # Daniel E. Shipton <dshipton@gmail.com> # # Flagpoll is Copyright (C) 2006 by Daniel E. Shipton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to: # Free SoftwareFoundation, Inc. # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # # ----------------------------------------------------------------- import sys, os, glob, os.path, copy, platform pj = os.path.join #################################################################### # SNAGGED FROM PYTHON 2.4 for versions under 2.4 #################################################################### import re as _re class _multimap: """Helper class for combining multiple mappings. Used by .{safe_,}substitute() to combine the mapping and keyword arguments. """ def __init__(self, primary, secondary): self._primary = primary self._secondary = secondary def __getitem__(self, key): try: return self._primary[key] except KeyError: return self._secondary[key] class _TemplateMetaclass(type): pattern = r""" %(delim)s(?: (?P<escaped>%(delim)s) | # Escape sequence of two delimiters (?P<named>%(id)s) | # delimiter and a Python identifier {(?P<braced>%(id)s)} | # delimiter and a braced identifier (?P<invalid>) # Other ill-formed delimiter exprs ) """ def __init__(cls, name, bases, dct): super(_TemplateMetaclass, cls).__init__(name, bases, dct) if 'pattern' in dct: pattern = cls.pattern else: pattern = _TemplateMetaclass.pattern % { 'delim' : _re.escape(cls.delimiter), 'id' : cls.idpattern, } cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE) class Template: """A string class for supporting $-substitutions.""" __metaclass__ = _TemplateMetaclass delimiter = '$' idpattern = r'[_a-z][_a-z0-9]*' def __init__(self, template): self.template = template # Search for $$, $identifier, ${identifier}, and any bare $'s def _invalid(self, mo): i = mo.start('invalid') lines = self.template[:i].splitlines(True) if not lines: colno = 1 lineno = 1 else: colno = i - len(''.join(lines[:-1])) lineno = len(lines) raise ValueError('Invalid placeholder in string: line %d, col %d' % (lineno, colno)) def substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): # Check the most common path first. named = mo.group('named') or mo.group('braced') if named is not None: val = mapping[named] # We use this idiom instead of str() because the latter will # fail if val is a Unicode containing non-ASCII characters. return '%s' % val if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: self._invalid(mo) raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) def safe_substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): named = mo.group('named') if named is not None: try: # We use this idiom instead of str() because the latter # will fail if val is a Unicode containing non-ASCII return '%s' % mapping[named] except KeyError: return self.delimiter + named braced = mo.group('braced') if braced is not None: try: return '%s' % mapping[braced] except KeyError: return self.delimiter + '{' + braced + '}' if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: return self.delimiter raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) #################################################################### # End Snagging #################################################################### class Utils: # Holds collection of small utility functions EXTRA_FLAGPOLL_SEARCH_PATHS = "" EXTRA_FLAGPOLL_FILES = "" path_list_cache = None # Cache of found path lists. (only calcuate once) KEEP_DUPS = False def getFlagpollVersion(): FLAGPOLL_MAJOR_VERSION = 0 FLAGPOLL_MINOR_VERSION = 8 FLAGPOLL_PATCH_VERSION = 1 return ( FLAGPOLL_MAJOR_VERSION, FLAGPOLL_MINOR_VERSION, FLAGPOLL_PATCH_VERSION ) getFlagpollVersion = staticmethod(getFlagpollVersion) def getPathList(): if None != Utils.path_list_cache: return Utils.path_list_cache #TODO: expand LD_LIBRARY_PATH to 64/32/etc??? pkg_cfg_dir = [] flg_cfg_dir = [] ld_path = [] if os.environ.has_key("PKG_CONFIG_PATH"): pkg_cfg_dir = os.environ["PKG_CONFIG_PATH"].split(os.pathsep) if os.environ.has_key("FLAGPOLL_PATH"): flg_cfg_dir = os.environ["FLAGPOLL_PATH"].split(os.pathsep) ld_dirs = ['LD_LIBRARY_PATH', 'DYLD_LIBRARY_PATH'] for d in ld_dirs: if os.environ.has_key(d): cur_path = os.environ[d].split(os.pathsep) ld_path_pkg = [pj(p,'pkgconfig') for p in cur_path] ld_path_flg = [pj(p,'flagpoll') for p in cur_path] ld_path.extend(ld_path_pkg) ld_path.extend(ld_path_flg) extra_paths = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS.split(os.pathsep) path_list = ["/usr/lib64/pkgconfig", "/usr/lib/pkgconfig", "/usr/share/pkgconfig", "/usr/lib64/flagpoll", "/usr/lib/flagpoll", "/usr/share/flagpoll"] path_list.extend(pkg_cfg_dir) path_list.extend(flg_cfg_dir) path_list.extend(extra_paths) path_list.extend(ld_path) flagDBG().out(flagDBG.VERBOSE, "Utils.getPathList", "Potential path list: " + str(path_list)) path_list = [p for p in path_list if os.path.exists(p)] flagDBG().out(flagDBG.INFO, "Utils.getPathList", "Using path list: " + str(path_list)) Utils.path_list_cache = path_list return path_list getPathList = staticmethod(getPathList) def getFileList(): flist = Utils.EXTRA_FLAGPOLL_FILES.split(":") filelist = [] for f in flist: if os.path.isfile(f): filelist.append(f) return filelist getFileList = staticmethod(getFileList) def setKeepDups(keep_dups): Utils.KEEP_DUPS = keep_dups setKeepDups = staticmethod(setKeepDups) def stripDupInList(gen_list): new_list = [] for item in gen_list: item = item.strip() if Utils.KEEP_DUPS: if len(item) > 0: new_list.append(item) continue if item not in new_list: if len(item) > 0: new_list.append(item) return new_list stripDupInList = staticmethod(stripDupInList) def stripDupLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] dir_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-L") or flg.startswith("-R"): dir_list.append(flg) else: lib_list.append(flg) new_list = dir_list + lib_list return Utils.stripDupInList(new_list) stripDupLinkerFlags = staticmethod(stripDupLinkerFlags) def stripDupIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] extra_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-I"): inc_list.append(flg) else: extra_list.append(flg) extra_list.sort() new_list = inc_list + extra_list return Utils.stripDupInList(new_list) stripDupIncludeFlags = staticmethod(stripDupIncludeFlags) def cflagsOnlyDirIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-I"): inc_list.append(flg) return Utils.stripDupInList(inc_list) cflagsOnlyDirIncludeFlags = staticmethod(cflagsOnlyDirIncludeFlags) def cflagsOnlyOtherIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though extra_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if not flg.startswith("-I"): extra_list.append(flg) return Utils.stripDupInList(extra_list) cflagsOnlyOtherIncludeFlags = staticmethod(cflagsOnlyOtherIncludeFlags) def libsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-l"): lib_list.append(flg) return Utils.stripDupInList(lib_list) libsOnlyLinkerFlags = staticmethod(libsOnlyLinkerFlags) def libsOnlyOtherLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though other_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if not flg.startswith("-l") and not flg.startswith("-L") and not flg.startswith("-R"): other_list.append(flg) return Utils.stripDupInList(other_list) libsOnlyOtherLinkerFlags = staticmethod(libsOnlyOtherLinkerFlags) def libDirsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though dir_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-L") or flg.startswith("-R"): dir_list.append(flg) return Utils.stripDupInList(dir_list) libDirsOnlyLinkerFlags = staticmethod(libDirsOnlyLinkerFlags) def printList(gen_list): list_string = "" for item in gen_list: if len(item) > 0: list_string += str(item) list_string += " " print list_string.strip() printList = staticmethod(printList) def parsePcFile(filename): lines = open(filename).readlines() fvars = {} fvars["FlagpollFilename"] = filename lokals = {} lokals["fp_file_cwd"] = str(filename[:- ((len(os.path.basename(filename) ) + 1))]) lines.append("prefix: ${prefix}") append_next = False append_dict = {} append_key = "" for line in lines: line = line.strip() if not line: continue if append_next: tmp = append_dict[append_key] tmp = tmp[:-1] + " " + line append_dict[append_key] = tmp if tmp[-1:] == "\\": append_next = True else: append_next = False continue if line.startswith("#"): continue eq_pos = line.find('=') col_pos = line.find(':') if eq_pos < col_pos and eq_pos != -1 or col_pos == -1 and eq_pos != -1: # local variable name, val = line.split('=', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(lokals) except ValueError: flagDBG().out(flagDBG.WARN, "PkgInfo.parse", "%s has an invalid metadata file" % filename) lokals[name] = val if val[-1:] == "\\": append_next = True append_dict = lokals append_key = name continue if col_pos < eq_pos and col_pos != -1 or eq_pos == -1 and col_pos != -1: # exported variable name, val = line.split(':', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(lokals) except ValueError: flagDBG().out(flagDBG.ERROR, "PkgInfo.parse", "%s has an invalid metadata file" % filename) fvars[name] = val if val[-1:] == "\\": append_next = True append_dict = fvars append_key = name return fvars parsePcFile = staticmethod(parsePcFile) class flagDBG(object): # Logging class is really easy to use # Levels: # 0 - VERBOSE # 1 - INFO # 2 - WARN # 3 - ERROR VERBOSE = 0 INFO = 1 WARN = 2 ERROR = 3 __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if flagDBG.__initialized: return flagDBG.__initialized = True self.mLevel = self.WARN self.mLevelList = ["VERBOSE", "INFO", "WARN", "ERROR"] def setLevel(self, level): if level <= 3: self.mLevel = level def out(self, level, obj, message): if level == self.ERROR: if self.mLevel == self.VERBOSE: print self.mLevelList[level] + ":" + str(obj) + ": " + str(message) else: print self.mLevelList[level] + ": " + str(message) sys.exit(1) if level >= self.mLevel: print self.mLevelList[level] + ":" + str(obj) + ": " + str(message) class DepResolutionSystem(object): """ You add PkgAgents with Filters into system and call resolve() you can check for succes by depsSatisfied() and get the list of packages that work back by calling getPackages() """ __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if DepResolutionSystem.__initialized: return DepResolutionSystem.__initialized = True self.mResolveAgents = [] self.mAgentDict = {} self.mFilters = [] self.mResolveAgentFilters = [] self.mInvalidPackageList = [] self.mSatisfied = False self.mAgentChangeList = [] # list of those responsible for adding Filters # to agents in higher in the chain than them # these are the first agents to ask that they pick # the next best package of them self.mAgentsVisitedList = [] # list of Agents that have been visited self.mResolvedPackageList = [] # list that is generated when deps are satified self.mCheckPrivateRequires = False self.mMadeDependList = False def getFilters(self): return self.mFilters def addFilter(self, filter): self.mFilters.append(filter) def addResolveAgentFilter(self, filter): self.mResolveAgentFilters.append(filter) def makeRequireFilter(self, requires): arch_list = [] arch_list.append("no_arch") arch_list.append("") if platform.system() == "Linux": if requires == "64": arch_list.append("x86_64") if requires == "32": arch_list.append("i386") arch_list.append("i486") arch_list.append("i586") arch_list.append("i686") if platform.system() == "Darwin": if requires == "64": arch_list.append("ppc64") if requires == "32": arch_list.append("ppc") if platform.system().startswith("IRIX"): arch_list.append(requires) new_filter = Filter("Arch", lambda x,v=arch_list: x in v) self.addFilter(new_filter) def createAgent(self, name): if self.checkAgentExists(name): return self.getAgent(name) else: agent = PkgAgent(name) flagDBG().out(flagDBG.INFO, "DepResSys.createAgent", "Adding %s" % name) self.addNewAgent(agent) return agent def createResolveAgent(self, name): if self.checkAgentExists(name): return self.getAgent(name) else: agent = PkgAgent(name) flagDBG().out(flagDBG.INFO, "DepResSys.createResolveAgent", "Adding %s" % name) self.addResolveAgent(agent) return agent def setPrivateRequires( self, req ): self.mCheckPrivateRequires = req def checkPrivateRequires(self): return self.mCheckPrivateRequires def checkAgentExists(self, name): return self.mAgentDict.has_key(name) def getAgent(self, name): if self.mAgentDict.has_key(name): return self.mAgentDict[name] else: flagDBG().out(flagDBG.ERROR, "DepResSys.getAgent", "Agent %s does not exist" % name) def addNewAgent(self, agent): if not self.checkAgentExists(agent): self.mAgentDict[agent.getName()] = agent def addResolveAgent(self, agent): if agent not in self.mResolveAgents: self.mResolveAgents.append(agent) for filt in self.mResolveAgentFilters: agent.addFilter(filt) def isSatisfied(self): return self.mSatisfied def updateResolvedPackages(self): pkg_list = [] agent_list = [] for agent in self.mResolveAgents: list_of_pkgs = agent.getCurrentPackageList(agent_list) pkg_list.extend(list_of_pkgs) self.mResolvedPackageList = pkg_list def getPackages(self): flagDBG().out(flagDBG.INFO, "DepResSys.getPackages", "Generating list of valid packages ") #str([pkg.getCurrentPackage.getName() for pkg in self.mResolvedPackageList])) # If this comes back empty then there isn't a valid set of packages to use self.updateResolvedPackages() return self.mResolvedPackageList def checkFiltersChanged(self): list_to_use = [] return True in [pkg.filtersChanged(list_to_use) for pkg in self.mResolveAgents] def resolveHelper(self): self.resolveAgentsChanged = True while self.resolveAgentsChanged: for agent in self.mResolveAgents: flagDBG().out(flagDBG.INFO, "DepResSys.resolveHelper", "Updating " + agent.getName()) agent.update(self.mAgentsVisitedList, self.mAgentChangeList) self.resolveAgentsChanged = self.checkFiltersChanged() # Ask mResolveAgents if they are done(they ask sub people) unless they are # really above you in the walk # If there were changes...run update on mResolveAgents again # at the end ask for pkglist..if it comes back empty then we don't # have a usable configuration for those packages def resolveDeps(self): self.resolveHelper() if not self.mMadeDependList: for agent in self.mResolveAgents: agent.makeDependList() self.mMadeDependList = True self.updateResolvedPackages() # Check if the first round through we found something # Otherwise we need to start removing packages that aren't viable # during the loop self.mSatisfied = (len(self.mResolvedPackageList) != 0) # remove top of packages that added Filters. # then move on to resolving again # remove more if neccesary agentChangeNumber = 0 while not self.mResolvedPackageList: if(self.mAgentChangeList[agentChangeNumber]): if self.mAgentChangeList[agentChangeNumber] in self.mInvalidPackageList: agentChangeNumber += 1 else: if(self.mAgentChangeList[agentChangeNumber].getViablePackages()): flagDBG().out(flagDBG.INFO, "DepResSys.resolveDeps", "Removing bad pkg from " + self.mAgentChangeList[agentChangeNumber].getName()) self.mInvalidPackageList.append(self.mAgentChangeList[agentChangeNumber].removeCurrentPackage()) else: flagDBG().out(flagDBG.INFO, "DepResSys.resolveDeps", "No combinations.. Resetting " + self.mAgentChangeList[agentChangeNumber].getName()) self.mAgentChangeList[agentChangeNumber].reset() agentChangeNumber += 1 self.resolveHelper() self.updateResolvedPackages() self.mSatisfied = (len(self.mResolvedPackageList) != 0) return class PkgAgent: """ Agent that keeps track of the versions for a package given some filters and the addition of Filters """ # Makes a PkgAgent that finds its current package with the version reqs def __init__(self, name): if DepResolutionSystem().checkAgentExists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "Package Agent %s already exists" % self.mName) self.mName = name flagDBG().out(flagDBG.INFO, "PkgAgent", "Creating:" + str(self.mName)) if not PkgDB().exists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "No info for package: %s" % self.mName) #XXX Doesn't keep filters added for a redo... DepResolutionSystem().addNewAgent(self) self.mFilterList = [] self.mFilterList.extend(DepResolutionSystem().getFilters()) self.mBasePackageList = PkgDB().getPkgInfos(name) self.mBasePackageList.sort(lambda lhs, rhs: cmp(rhs.getVariable('Version'), lhs.getVariable('Version'))) for filt in self.mFilterList: self.mBasePackageList = filt.filter(self.mBasePackageList) if len(self.mBasePackageList) == 0: flagDBG().out(flagDBG.ERROR, "PkgAgent", "No viable packages for: %s" % self.mName) self.mViablePackageList = copy.deepcopy(self.mBasePackageList) if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mFiltersChanged = True self.mCheckDepends = True self.mAgentDependList = [] def getName(self): return self.mName def setCheckDepends(self, tf): self.mCheckDepends = tf #Filter("Version", lambda x: x == "4.5") def makeDependList(self): if not self.mCheckDepends: self.mAgentDependList = [] return dep_list = [] if self.mCurrentPackage: req_string = self.mCurrentPackage.getVariable("Requires") if DepResolutionSystem().checkPrivateRequires(): req_string = req_string + " " + self.mCurrentPackage.getVariable("Requires.private") req_string = req_string.strip() if req_string == "": return req_string = req_string.replace(',', ' ') req_string = req_string.replace('(', ' ') req_string = req_string.replace(')', ' ') space_req_string_list = req_string.split(' ') req_string_list = [] for entry in space_req_string_list: if len(entry) > 0: req_string_list.append(entry) i = 0 flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList", self.mCurrentPackage.getName() + " requires: " + str(req_string_list)) while len(req_string_list) > i: if PkgDB().exists(req_string_list[i]): new_filter = [] new_agent = DepResolutionSystem().createAgent(req_string_list[i]) if len(req_string_list) > i+1: if req_string_list[i+1] == "=": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x == v) elif req_string_list[i+1] == "<=": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x <= v) elif req_string_list[i+1] == ">=": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x >= v) elif req_string_list[i+1] == ">": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x > v) elif req_string_list[i+1] == "<": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x < v) else: i += 1 else: i += 1 dep_list.append(new_agent) if new_filter: i+=3 new_agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "PkgAgent.makeDependList", "Package %s depends on %s but does not seem to be installed." % (self.mName, str(req_string_list[i]))) flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList", str(self.mName) + " : List is:" + str([pkg.getName() for pkg in dep_list])) self.mAgentDependList = dep_list def filtersChanged(self, packageList): tf_list = [self.mFiltersChanged] if self.mName not in packageList: packageList.append(self.mName) for pkg in self.mAgentDependList: tf_list.append(pkg.filtersChanged(packageList)) return True in tf_list def getCurrentPackageList(self, packageList): pkgs = [] if self.mName not in packageList: flagDBG().out(flagDBG.INFO, "PkgAgent.getCurrentPackageList", "Package: %s" % self.mName) pkgs.append(self.mCurrentPackage) packageList.append(self.mName) # Make depend list if we are supposed to self.updateFilters() self.makeDependList() for pkg in self.mAgentDependList: pkgs.extend(pkg.getCurrentPackageList(packageList)) return pkgs # current pkginfo for me def getCurrentPkgInfo(self): return self.mCurrentPackage # Someone else usually places these on me # I keep track of those separately def addFilter(self, filter): flagDBG().out(flagDBG.INFO, "PkgAgent.addFilter", "Filter %s" % self.mName + " on %s." % filter.getVarName()) self.mFiltersChanged = True self.mFilterList.append(filter) def removeCurrentPackage(self): flagDBG().out(flagDBG.INFO, "PkgAgent.removeCurrentPackage", "Removing current package of %s" % self.mName) if self.mViablePackageList: ret_val = self.mViablePackageList[0] in self.mBasePackageList del self.mViablePackageList[0] if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] return ret_val def update(self, agentVisitedList, agentChangeList): flagDBG().out(flagDBG.INFO, "PkgAgent.update", "%s" % self.mName) if self.mName in agentVisitedList: return agentVisitedList.append(self.mName) if self.mFiltersChanged: self.mFiltersChanged = False self.updateFilters() # TODO: checkFilters and add them # if a pkg is in visitedList then add yourself to agentChangeList for pkg in self.mAgentDependList: pkg.update(agentVisitedList, agentChangeList) return def updateFilters(self): for filt in self.mFilterList: self.mViablePackageList = filt.filter(self.mViablePackageList) flagDBG().out(flagDBG.INFO, "PkgAgent.updateFilters", "%s has " % self.mName + str(len(self.mViablePackageList)) + " left") if len(self.mViablePackageList) > 0: self.mCurrentPackage = self.mViablePackageList[0] else: self.mCurrentPackage = [] def reset(self): flagDBG().out(flagDBG.INFO, "PkgAgent.reset", "Resetting package: %s" % self.mName) self.mViablePackageList = self.mBasePackageList if self.mViablePackageList: self.mCurrentPacakge = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mFilterList = DepResolutionSystem().getFilters() self.mAgentDependList = [] self.mFiltersChanged = True return class Filter: """ A single Filter that knows how to filter the list it recieves Will be inheireted....?..? """ def __init__(self, variableName, testCallable): self.mVarName = variableName self.mTestCallable = testCallable def getVarName(self): return self.mVarName def filter(self, pkg_info_list): ret_pkg_list = [] # Filter first for pkg in pkg_info_list: var = pkg.getVariable(self.mVarName) if self.mTestCallable(var): flagDBG().out(flagDBG.INFO, "Filter", "Passed: %s:" % pkg.getName() + " %s is " % self.mVarName + str(var)) ret_pkg_list.append(pkg) else: flagDBG().out(flagDBG.INFO, "Filter", "Failed: %s:" % pkg.getName() + " %s is " % self.mVarName + str(var)) # Now sort ret_pkg_list.sort(lambda lhs, rhs: cmp(rhs.getVariable(self.mVarName), lhs.getVariable(self.mVarName))) return ret_pkg_list #requires: qt == 4.5 #Filter("Version", lambda x: x <= "4.5") #Filter("Version", lambda x: x <= "4.5") class PkgDB(object): """ Holds all the neccesary information to evaluate itself when needed. Is in charge of holding a list of PkgInfo's that contain info about the package. """ __initialized = False def __init__(self): if self.__initialized: return self.__initialized = True self.mPkgInfos = {} # {pkg_name: List of package infos} self.populatePkgInfoDBPcFiles() self.populatePkgInfoDBFpcFiles() def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def printAllPackages(self): list_of_package_names = [] for pkg in self.mPkgInfos: list_of_package_names.append(pkg) for name in list_of_package_names: print name sys.exit(0) def getVariables(self, name, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariable", "Finding " + str(variable_list) + " in " + str(name)) ret_list = [] for var in variable_list: if self.mPkgInfos.has_key(name): ret_list.extend(self.mPkgInfos[name][0].getVariable(var)) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariable", "Package %s not found." % name) return ret_list def checkPackage(self, name): flagDBG().out(flagDBG.INFO, "PkgDB.checkPackage", "Finding " + str(name)) if self.mPkgInfos.has_key(name): return True else: flagDBG().out(flagDBG.ERROR, "PkgDB.CheckPackage", "Package %s not found." % name) return False def getVariablesAndDeps(self, pkg_list, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariablesAndDeps", "Finding " + str(variable_list) + " in " + str(pkg_list)) if DepResolutionSystem().checkPrivateRequires(): temp_var_list = [] for var in variable_list: temp_var_list.append(var.join(".private")) variable_list = variable_list + temp_var_list for name in pkg_list: if self.mPkgInfos.has_key(name): agent = DepResolutionSystem().createAgent(name) DepResolutionSystem().addResolveAgent(agent) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariablesAndDeps", "Package %s not found." % name) DepResolutionSystem().resolveDeps() pkgs = DepResolutionSystem().getPackages() var_list = [] for pkg in pkgs: if pkg: for var in variable_list: var_list.extend(pkg.getVariable(var).split(' ')) return var_list def getPkgInfos(self, name): if self.mPkgInfos.has_key(name): return self.mPkgInfos[name] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getPkgInfos", "Package %s not found." % name) def exists(self, name): return self.mPkgInfos.has_key(name) def getInfo(self, name): if self.mPkgInfos.has_key(name): return [pkg.getInfo() for pkg in self.mPkgInfos[name]] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getInfo", "Package %s not found." % name) def buildPcFileDict(self): """ Builds up a dictionary of {name: list of files for name} """ pc_dict = {} for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.pc")) # List of .pc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these pc files: %s" % str(glob_list)) for g in glob_list: # Get key name and add file to value list in dictionary key = os.path.basename(g)[:-3] # Strip .pc off the filename...rstrip no worky pc_dict.setdefault(key, []).append(g) for f in Utils.getFileList(): if f.endswith(".pc"): key = os.path.basename(f)[:-3] # Strip .pc off the filename...rstrip no worky pc_dict.setdefault(key, []).append(f) return pc_dict # { "key", [ "list", "of", "corresponding", "pc", "files"] } def populatePkgInfoDBPcFiles(self): dict_to_pop_from = self.buildPcFileDict() for (pkg,files) in dict_to_pop_from.iteritems(): for f in files: self.mPkgInfos.setdefault(pkg,[]).append(PkgInfo(pkg, f, "pc")) def buildFpcFileList(self): """ Builds up a dictionary of {name: list of files for name} """ file_list = [] for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.fpc")) # List of .fpc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these fpc files: %s" % str(glob_list)) for g in glob_list: file_list.append(g) for f in Utils.getFileList(): if f.endswith(".fpc"): file_list.append(f) return file_list # [ "list", "of", "fpc", "files"] def populatePkgInfoDBFpcFiles(self): list_to_add = self.buildFpcFileList() for filename in list_to_add: var_dict = Utils.parsePcFile(filename) if not var_dict.has_key("Provides"): flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Provides" % str(filename)) continue if not var_dict.has_key("Arch"): flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Arch" % str(filename)) continue provides_string = var_dict["Provides"] provides_string = provides_string.replace(',', ' ') provides_string = provides_string.replace('(', ' ') provides_string = provides_string.replace(')', ' ') for key in provides_string.split(" "): if len(key) > 0: self.mPkgInfos.setdefault(key, []).append(PkgInfo(key, filename, "fpc", var_dict)) class PkgInfo: """ Holds the information for a package file on the system. These however are evaluated when the need arises. """ def __init__(self, name, file, type, varDict={}): self.mName = name self.mFile = file self.mIsEvaluated = False self.mType = type self.mVariableDict = varDict if self.mType == "fpc": self.mIsEvaluated = True def getVariable(self, variable): self.evaluate() return self.mVariableDict.get(variable,"") def getName(self): return self.mName def evaluate(self): if not self.mIsEvaluated: flagDBG().out(flagDBG.INFO, "PkgInfo.evaluate", "Evaluating %s" % self.mName) self.mVariableDict= Utils.parsePcFile(self.mFile) self.mIsEvaluated = True def getInfo(self): self.evaluate() return self.mVariableDict class OptionsEvaluator: def __init__(self): if len(sys.argv) < 2: self.printHelp() # This is only the args....(first arg is stripped) def evaluateArgs(self, args): # Catch any args that need to be tended to immediately # Process args in the order that they were recieved. Some options are not # shown below because they are sub-options of an option below (--strip-dups) for option in args: if option.startswith("--verbose-debug"): flagDBG().setLevel(flagDBG.VERBOSE) if option.startswith("--debug"): flagDBG().setLevel(flagDBG.INFO) elif option.startswith("--from-file"): val_start = option.find('=') + 1 file = option[val_start:] Utils.EXTRA_FLAGPOLL_FILES = Utils.EXTRA_FLAGPOLL_FILES + ":" + file elif option.startswith("--help"): self.printHelp() sys.exit(0) elif option.startswith("--version"): print "%s.%s.%s" % Utils.getFlagpollVersion() sys.exit(0) elif option.startswith("--list-all"): PkgDB().printAllPackages() continue listedAgentNames = [] agent = None num_args = len(args) curr_arg = 0 output_options = [] # (option, name/"") important_options = [] # ones that need special attention while curr_arg < num_args: if args[curr_arg].startswith("--atleast-version"): val_start = args[curr_arg].find('=') + 1 atleast_version = args[curr_arg][val_start:] atleast_filter = Filter("Version", lambda x,v=atleast_version: x >= v) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(atleast_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --at-least-version") continue if args[curr_arg].startswith("--cflags-only-I"): output_options.append(("cflags-only-I", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--cflags-only-other"): output_options.append(("cflags-only-other", "")) curr_arg = curr_arg + 1 continue #This could be the catch all for the above ones to and then filter based on what is asked... #For clarity of course... if args[curr_arg].startswith("--cflags"): output_options.append(("cflags", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--extra-paths"): val_start = args[curr_arg].find('=') + 1 paths = args[curr_arg][val_start:] Utils.EXTRA_FLAGPOLL_SEARCH_PATHS = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS + ":" + paths curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--exact-version"): val_start = args[curr_arg].find('=') + 1 exact_version = args[curr_arg][val_start:] exact_filter = Filter("Version", lambda x,v=exact_version: x == v) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(exact_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --exact-version") continue if args[curr_arg].startswith("--exists"): important_options.append("exists") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--from-file"): val_start = args[curr_arg].find('=') + 1 file = args[curr_arg][val_start:] file_filter = Filter("FlagpollFilename", lambda x,f=file: x == f) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(file_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --from-file") continue if args[curr_arg].startswith("--info"): important_options.append("info") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--print-pkg-options"): important_options.append("print-pkg-options") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--keep-dups"): Utils.setKeepDups(True) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-l"): output_options.append(("libs-only-l", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-L"): output_options.append(("libs-only-L", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-other"): output_options.append(("libs-only-other", "")) curr_arg = curr_arg + 1 continue #This could be the catch all for the above ones to and then filter based on what is asked... if args[curr_arg].startswith("--libs"): output_options.append(("libs", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--require-all"): rlen = len("--require-all") req_string = args[curr_arg][rlen:] req_string = req_string.replace('-','_') curr_arg = curr_arg + 1 if req_string.find("<=") != -1: op_start = req_string.find("<=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x <= v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find(">=") != -1: op_start = req_string.find(">=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x >= v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find(">") != -1: op_start = req_string.find(">") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x > v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("<") != -1: op_start = req_string.find("<") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x < v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("=") != -1: op_start = req_string.find("=") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x == v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("=") == -1: new_filter = Filter(req_string, lambda x: len(x) > 0) DepResolutionSystem().addFilter(new_filter) continue continue if args[curr_arg].startswith("--require-"): rlen = len("--require-") req_string = args[curr_arg][rlen:] req_string = req_string.replace('-','_') curr_arg = curr_arg + 1 if agent is None: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --require") if req_string.find("<=") != -1: op_start = req_string.find("<=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x <= v) agent.addFilter(new_filter) continue if req_string.find(">=") != -1: op_start = req_string.find(">=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x >= v) agent.addFilter(new_filter) continue if req_string.find(">") != -1: op_start = req_string.find(">") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x > v) agent.addFilter(new_filter) continue if req_string.find("<") != -1: op_start = req_string.find("<") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x < v) agent.addFilter(new_filter) continue if req_string.find("=") != -1: op_start = req_string.find("=") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x == v) agent.addFilter(new_filter) continue if req_string.find("=") == -1: new_filter = Filter(req_string, lambda x: len(x) > 0) agent.addFilter(new_filter) continue continue if args[curr_arg].startswith("--no-deps"): if agent is not None: agent.setCheckDepends(False) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --no-deps") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--require="): val_start = args[curr_arg].find('=') + 1 req_var = args[curr_arg][val_start:] curr_arg = curr_arg + 1 DepResolutionSystem().makeRequireFilter(req_var) continue if args[curr_arg].startswith("--modversion"): if agent is not None: output_options.append(("Version", agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --modversion") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--max-release"): val_start = args[curr_arg].find('=') + 1 max_release = args[curr_arg][val_start:] max_filter = Filter("Version", lambda x,v=max_release: x.startswith(v)) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(max_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --max-release") continue if args[curr_arg].startswith("--static"): DepResolutionSystem().setPrivateRequires(True) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--variable"): val_start = args[curr_arg].find('=') + 1 fetch_var = args[curr_arg][val_start:] if agent is not None: output_options.append((fetch_var, agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --variable") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--get-all"): rlen = len("--get-all-") get_string = args[curr_arg][rlen:] get_string = get_string.replace('-','_') output_options.append((get_string, "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--get"): rlen = len("--get-") get_string = args[curr_arg][rlen:] get_string = get_string.replace('-','_') if agent is not None: output_options.append((get_string, agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --get") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--concat"): important_options.append("concat") curr_arg = curr_arg + 1 continue if not args[curr_arg].startswith("--"): name = args[curr_arg] curr_arg = curr_arg + 1 if PkgDB().checkPackage(name): agent = DepResolutionSystem().createResolveAgent(name) listedAgentNames.append(name) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Package %s" % name) sys.exit(1) continue if args[curr_arg] != "--debug": flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Option: %s" % args[curr_arg]) curr_arg = curr_arg + 1 DepResolutionSystem().resolveDeps() pkgs = DepResolutionSystem().getPackages() for p in pkgs: if not p: for option in important_options: if option == "exists": print "no" sys.exit(1) flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found") if len(pkgs) == 0: for option in important_options: if option == "exists": print "no" sys.exit(1) flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found") sys.exit(1) concat = False for option in important_options: if option == "exists": print "yes" return sys.exit(0) # already checked for none above if option == "concat": concat = True if option == "info": pkg_info_list = [] for pkg in pkgs: if pkg.getName() in listedAgentNames: print pkg.getName() pkg_info = pkg.getInfo() for key in pkg_info.keys(): print " %s : %s" % (key, pkg_info[key]) if option == "print-pkg-options": print "" print "All options below would start with (--get-/--get-all-/--require-/--require-all-)" print "NOTE: this list does not include the standard variables that are exported." print "" for pkg in pkgs: if pkg.getName() not in listedAgentNames: continue print "Package: " + pkg.getName() for key in pkg.getInfo().keys(): if key not in [ "Name", "Description", "URL", "Version", "Requires", "Requires.private", "Conflicts", "Libs", "Libs.private", "Cflags", "Provides", "Arch", "FlagpollFilename", "prefix" ]: print " " + key.replace('_','-') #print output_options #output_options = [] #output_single = [] #Process options here.............. concat_list = [] if concat: print_option = lambda x: concat_list.extend(x) else: print_option = lambda x: Utils.printList(x) for option in output_options: if option[0] == "cflags": print_option(Utils.stripDupIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "cflags-only-I": print_option(Utils.cflagsOnlyDirIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "cflags-only-other": print_option(Utils.cflagsOnlyOtherIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "libs-only-l": print_option(Utils.libsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs-only-L": print_option(Utils.libDirsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs-only-other": print_option(Utils.libsOnlyOtherLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs": print_option(Utils.stripDupLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) else: print_option(Utils.stripDupInList(self.getVarFromPkgs(option[0], pkgs, option[1]))) if concat: Utils.printList(Utils.stripDupInList(concat_list)) def getVarFromPkgs(self, var, pkgs, pkg_name=""): var_list = [] ext_vars = [] if var == "Libs": if DepResolutionSystem().checkPrivateRequires: ext_vars.append("Libs.private") if pkg_name == "": for pkg in pkgs: if pkg: var_list.extend(pkg.getVariable(var).split(' ')) for extra_var in ext_vars: var_list.extend(pkg.getVariable(extra_var).split(' ')) else: for pkg in pkgs: if pkg: if pkg.getName() == pkg_name: var_list.extend(pkg.getVariable(var).split(' ')) for extra_var in ext_vars: var_list.extend(pkg.getVariable(extra_var).split(' ')) return var_list def printHelp(self): print "usage: flagpoll pkg options [pkg options] [generic options]" print " " print "generic options:" print " --help show this help message and exit" print " --version output version of flagpoll" print " --list-all list all known packages" print " --debug show debug information" print " --verbose-debug show verbose debug information" print " --extra-paths=EXTRA_PATHS" print " extra paths for flagpoll to search for meta-data files" print " --concat concatenate all output and output as one line" print " --keep-dups do not strip out all duplicate info from options" print " --info show information for packages" print " --print-pkg-options show pkg specific options" print " " print "options:" print " --modversion output version for package" print " --require=REQUIRE adds additional requirements for packages ex. 32/64" print " --libs output all linker flags" print " --static output linker flags for static linking" print " --libs-only-l output -l flags" print " --libs-only-other output other libs (e.g. -pthread)" print " --libs-only-L output -L flags" print " --cflags output all pre-processor and compiler flags" print " --cflags-only-I output -I flags" print " --cflags-only-other output cflags not covered by the cflags-only-I option" print " --exists return 0 if the module(s) exist" print " --from-file=FILE use the specified FILE for the package" #print " --print-provides print which packages the package provides" #print " --print-requires print which packages the package requires" print " --no-deps do not lookup dependencies for the package" print " --atleast-version=ATLEAST_VERSION" print " return 0 if the module is at least version" print " ATLEAST_VERSION" print " --exact-version=EXACT_VERSION" print " return 0 if the module is exactly version" print " EXACT_VERSION" print " --max-release=MAX_RELEASE" print " return 0 if the module has a release that has a" print " version of MAX_RELEASE and will return the max" print " --variable=VARIABLE get the value of a variable" print " " print "dynamic options(replace VAR with a variable you want to get/filter on)" print " NOTE: replace underscores with dashes in VAR" print " NOTE: quotes are needed around <,>,= combinations" print " --get-VAR get VAR from package" print " --get-all-VAR get VAR from package and its deps" print " --require-VAR[<,>,=VAL]" print " require that a var is defined for a package" print " or optionally use equality operators against VAL" print " --require-all-VAR[<,>,=VAL]" print " require that a var is defined for all packages" print " or optionally use equality operators against VAL" print "" print "extending search path" print " FLAGPOLL_PATH environment variable that can be set to" print " extend the search path for .fpc/.pc files" sys.exit(0) def main(): # GO! # Initialize singletons and the start evaluating my_dbg = flagDBG() my_dep_system = DepResolutionSystem() opt_evaluator = OptionsEvaluator() opt_evaluator.evaluateArgs(sys.argv[1:]) sys.exit(0) if __name__ == "__main__": main()
Python
#!/usr/bin/env python # ----------------------------------------------------------------- # # Flag Poll: A tool to extract flags from installed applications # for compiling, settting variables, etc. # # Original Authors: # Daniel E. Shipton <dshipton@gmail.com> # # Flag Poll is Copyright (C) 2006 by Daniel E. Shipton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to: # Free SoftwareFoundation, Inc. # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # # ----------------------------------------------------------------- """Makes a flagpole .fpc file from user input. v0.9 coded by Jeff Groves""" import os import sys import getopt ##String prompts for the input varPrompt = """Convience variables (one 'var_name= var_definition' per line,""" + \ """ empty line when done)""" namePrompt = "Formal Name" descriptionPrompt = "Description" urlPrompt = "URL" providesPrompt = "One or more names to look package up by: (Provides)" versionPrompt = "Version (x.y.z)" architecturePrompt = "Architecture" requirePrompt = "Requires" libPrompt = "Linker Flags (-lfoo -L/usr/lib)" staticLibPrompt = "Static Linking Flags/Libs (extra private libs)" compileFlagsPrompt = "Compile/Include Flags (-I/usr -fpge -O2)" fileNamePrompt = "FPC File's Name" def usage(): """Prints a list of acceptable arguments for fpcmaker.py.""" print """ Fpcmaker.py Options: -n, --name= : Sets %s -d, --description= : Sets %s -u, --url= : Sets %s -p, --provides= : Sets %s -v, --version= : Sets %s -a, --architecture= : Sets %s -r, --requires= : Sets %s -l, --libs= : Sets %s -c, --cflags= : Sets %s -s, --static= : Sets %s -f, --file= : Sets %s """ %(namePrompt, descriptionPrompt, urlPrompt, providesPrompt, versionPrompt, architecturePrompt, requirePrompt, libPrompt, compileFlagsPrompt, staticLibPrompt, fileNamePrompt) return def checkFileName(fileName): """Checks if the fpc file name's blank, contains slashes, or exists.""" nameCleared = False writeFile = True confirms = ['y', 'Y', 'yes', 'Yes'] ##Loops until the name clears or writing the file's aborted. while(not nameCleared and writeFile): ##If it's blank, give the option of aborting the program. if fileName == "": choice = raw_input("Do you want to abort writing the" + " .fpc file? (Y/N): ") if choice not in confirms: fileName = raw_input("Please enter a different name for the" + " .fpc file: ") else: writeFile = False ##If it contains slashes, ask for another name. elif '/' in fileName or '\\' in fileName: print "I can't write to %s because it contains slashes."%(fileName) fileName = raw_input("Please enter a different name for the" + " .fpc file: ") ##If it already exists, ask if they want to overwrite. ##If not, ask for another name. elif os.path.exists(fileName): choice = raw_input("The file %s already exists." %(fileName) + " Do you want to overwrite it? (Y/N): ") if choice not in confirms: fileName = raw_input("Please enter a different name for the" + " .fpc file: ") else: nameCleared = True else: nameCleared = True return [fileName, writeFile] ##Booleans for whether that argument was sent in the command line varSet = False providesSet = False nameSet = False descriptionSet = False urlSet = False architectureSet = False versionSet = False requiresSet = False libsSet = False compileFlagsSet = False staticLibSet = False fileNameSet = False ##Get the options & arguments sent. arguments = sys.argv[1:] try: opts, args = getopt.getopt(arguments, "p:n:u:d:a:r:v:l:c:s:f:", ["provides=", "name=", "url=", "description=", "architecture=", "requires=", "version=", "libs=", "cflags=", "static=", "file="]) ##Send them usage info if they enter a wrong argument except getopt.GetoptError: usage() sys.exit(2) for opt, arg in opts: if opt in ('-p', '--provides'): providesSet = True provides = arg elif opt in ('-n', '--name'): nameSet = True name = arg elif opt in ('-v', '--version'): versionSet = True version = arg elif opt in ('-u', '--url'): urlSet = True url = arg elif opt in ('-d', '--description'): descriptionSet = True description = arg elif opt in ('-a', '--architecture'): architectureSet = True architecture = arg elif opt in ('-r', '--requires'): requiresSet = True requires = arg elif opt in ('-l', '--libs'): libsSet = True libs = arg elif opt in ('-c', '--cflags'): compileFlagsSet = True compileFlags = arg elif opt in ('-s', '--static'): staticLibSet = True staticLib = arg elif opt in ('-f', '--file'): fileNameSet = True fileName = arg ##Grab any input not passed in the arguments from the user. if not varSet: varLine = None variables = "" print "%s:" %(varPrompt) while(varLine != ""): varLine = raw_input("") variables = variables + "%s\n" %(varLine) if not nameSet: name = raw_input("%s: " %(namePrompt)) if not descriptionSet: description = raw_input("%s: " %(descriptionPrompt)) if not urlSet: url = raw_input("%s: " %(urlPrompt)) if not versionSet: version = raw_input("%s: " %(versionPrompt)) if not providesSet: provides = raw_input("%s: " %(providesPrompt)) if not requiresSet: requires = raw_input("%s: " %(requirePrompt)) if not architectureSet: architecture = raw_input("%s: " %(architecturePrompt)) if not libsSet: libs = raw_input("%s: " %(libPrompt)) if not staticLibSet: staticLib = raw_input("%s: " %(staticLibPrompt)) if not compileFlagsSet: compileFlags = raw_input("%s: " %(compileFlagsPrompt)) if not fileNameSet: fileName = raw_input("%s: " %(fileNamePrompt)) ##Check the file's name. fileName, writeFile = checkFileName(fileName) ##If they chose not to overwrite, write the file. if writeFile: fpc = open(fileName, 'w') fpc.write("%s" %(variables)) fpc.write("Name: %s\n" %(name)) fpc.write("Description: %s\n" %(description)) fpc.write("URL: %s\n" %(url)) fpc.write("Version: %s\n" %(version)) fpc.write("Provides: %s\n" %(provides)) fpc.write("Requires: %s\n" %(requires)) fpc.write("Arch: %s\n" %(architecture)) fpc.write("Libs: %s\n" %(libs)) fpc.write("Libs.private: %s\n" %(staticLib)) fpc.write("Cflags: %s\n" %(compileFlags)) fpc.close() ##TESTER: Print the file out. fpc = open(fileName, 'r') ##TESTER print fpc.read() ##TESTER fpc.close ##TESTER
Python
#!/usr/bin/env python from distutils.core import setup setup( name='flagpoll', version='0.2.1', description='Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software.', author='Daniel E. Shipton', author_email='dshipton@infiscape.com', license='GPL', url='https://realityforge.vrsource.org/view/FlagPoll/WebHome', download_url='https://realityforge.vrsource.org/view/FlagPoll/FlagpollDownloads', scripts=['flagpoll'], long_description = "Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software. Think of it as the rpm of software development. It enables developers total control over which packages, versions, architectures, etc. that they want to use meta-data from.", data_files=[('share/flagpoll', ['flagpoll.fpc']), ('share/man/man1', ['flagpoll.1'])] )
Python
#!/usr/bin/env python # ----------------------------------------------------------------- # # Flag Poll: A tool to extract flags from installed applications # for compiling, settting variables, etc. # # Original Authors: # Daniel E. Shipton <dshipton@gmail.com> # # Flag Poll is Copyright (C) 2006 by Daniel E. Shipton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to: # Free SoftwareFoundation, Inc. # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # # ----------------------------------------------------------------- """Makes a flagpole .fpc file from user input. v0.9 coded by Jeff Groves""" import os import sys import getopt ##String prompts for the input varPrompt = """Convience variables (one 'var_name= var_definition' per line,""" + \ """ empty line when done)""" namePrompt = "Formal Name" descriptionPrompt = "Description" urlPrompt = "URL" providesPrompt = "One or more names to look package up by: (Provides)" versionPrompt = "Version (x.y.z)" architecturePrompt = "Architecture" requirePrompt = "Requires" libPrompt = "Linker Flags (-lfoo -L/usr/lib)" staticLibPrompt = "Static Linking Flags/Libs (extra private libs)" compileFlagsPrompt = "Compile/Include Flags (-I/usr -fpge -O2)" fileNamePrompt = "FPC File's Name" def usage(): """Prints a list of acceptable arguments for fpcmaker.py.""" print """ Fpcmaker.py Options: -n, --name= : Sets %s -d, --description= : Sets %s -u, --url= : Sets %s -p, --provides= : Sets %s -v, --version= : Sets %s -a, --architecture= : Sets %s -r, --requires= : Sets %s -l, --libs= : Sets %s -c, --cflags= : Sets %s -s, --static= : Sets %s -f, --file= : Sets %s """ %(namePrompt, descriptionPrompt, urlPrompt, providesPrompt, versionPrompt, architecturePrompt, requirePrompt, libPrompt, compileFlagsPrompt, staticLibPrompt, fileNamePrompt) return def checkFileName(fileName): """Checks if the fpc file name's blank, contains slashes, or exists.""" nameCleared = False writeFile = True confirms = ['y', 'Y', 'yes', 'Yes'] ##Loops until the name clears or writing the file's aborted. while(not nameCleared and writeFile): ##If it's blank, give the option of aborting the program. if fileName == "": choice = raw_input("Do you want to abort writing the" + " .fpc file? (Y/N): ") if choice not in confirms: fileName = raw_input("Please enter a different name for the" + " .fpc file: ") else: writeFile = False ##If it contains slashes, ask for another name. elif '/' in fileName or '\\' in fileName: print "I can't write to %s because it contains slashes."%(fileName) fileName = raw_input("Please enter a different name for the" + " .fpc file: ") ##If it already exists, ask if they want to overwrite. ##If not, ask for another name. elif os.path.exists(fileName): choice = raw_input("The file %s already exists." %(fileName) + " Do you want to overwrite it? (Y/N): ") if choice not in confirms: fileName = raw_input("Please enter a different name for the" + " .fpc file: ") else: nameCleared = True else: nameCleared = True return [fileName, writeFile] ##Booleans for whether that argument was sent in the command line varSet = False providesSet = False nameSet = False descriptionSet = False urlSet = False architectureSet = False versionSet = False requiresSet = False libsSet = False compileFlagsSet = False staticLibSet = False fileNameSet = False ##Get the options & arguments sent. arguments = sys.argv[1:] try: opts, args = getopt.getopt(arguments, "p:n:u:d:a:r:v:l:c:s:f:", ["provides=", "name=", "url=", "description=", "architecture=", "requires=", "version=", "libs=", "cflags=", "static=", "file="]) ##Send them usage info if they enter a wrong argument except getopt.GetoptError: usage() sys.exit(2) for opt, arg in opts: if opt in ('-p', '--provides'): providesSet = True provides = arg elif opt in ('-n', '--name'): nameSet = True name = arg elif opt in ('-v', '--version'): versionSet = True version = arg elif opt in ('-u', '--url'): urlSet = True url = arg elif opt in ('-d', '--description'): descriptionSet = True description = arg elif opt in ('-a', '--architecture'): architectureSet = True architecture = arg elif opt in ('-r', '--requires'): requiresSet = True requires = arg elif opt in ('-l', '--libs'): libsSet = True libs = arg elif opt in ('-c', '--cflags'): compileFlagsSet = True compileFlags = arg elif opt in ('-s', '--static'): staticLibSet = True staticLib = arg elif opt in ('-f', '--file'): fileNameSet = True fileName = arg ##Grab any input not passed in the arguments from the user. if not varSet: varLine = None variables = "" print "%s:" %(varPrompt) while(varLine != ""): varLine = raw_input("") variables = variables + "%s\n" %(varLine) if not nameSet: name = raw_input("%s: " %(namePrompt)) if not descriptionSet: description = raw_input("%s: " %(descriptionPrompt)) if not urlSet: url = raw_input("%s: " %(urlPrompt)) if not versionSet: version = raw_input("%s: " %(versionPrompt)) if not providesSet: provides = raw_input("%s: " %(providesPrompt)) if not requiresSet: requires = raw_input("%s: " %(requirePrompt)) if not architectureSet: architecture = raw_input("%s: " %(architecturePrompt)) if not libsSet: libs = raw_input("%s: " %(libPrompt)) if not staticLibSet: staticLib = raw_input("%s: " %(staticLibPrompt)) if not compileFlagsSet: compileFlags = raw_input("%s: " %(compileFlagsPrompt)) if not fileNameSet: fileName = raw_input("%s: " %(fileNamePrompt)) ##Check the file's name. fileName, writeFile = checkFileName(fileName) ##If they chose not to overwrite, write the file. if writeFile: fpc = open(fileName, 'w') fpc.write("%s" %(variables)) fpc.write("Name: %s\n" %(name)) fpc.write("Description: %s\n" %(description)) fpc.write("URL: %s\n" %(url)) fpc.write("Version: %s\n" %(version)) fpc.write("Provides: %s\n" %(provides)) fpc.write("Requires: %s\n" %(requires)) fpc.write("Arch: %s\n" %(architecture)) fpc.write("Libs: %s\n" %(libs)) fpc.write("Libs.private: %s\n" %(staticLib)) fpc.write("Cflags: %s\n" %(compileFlags)) fpc.close() ##TESTER: Print the file out. fpc = open(fileName, 'r') ##TESTER print fpc.read() ##TESTER fpc.close ##TESTER
Python
#!/usr/bin/env python # ----------------------------------------------------------------- # # Flagpoll: A tool to extract flags from installed applications # for compiling, settting variables, etc. # # Original Authors: # Daniel E. Shipton <dshipton@gmail.com> # # Flagpoll is Copyright (C) 2006 by Daniel E. Shipton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to: # Free SoftwareFoundation, Inc. # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # # ----------------------------------------------------------------- from optparse import OptionParser import sys, os, glob, os.path, copy, platform pj = os.path.join #################################################################### # SNAGGED FROM PYTHON 2.4 for versions under 2.4 #################################################################### import re as _re class _multimap: """Helper class for combining multiple mappings. Used by .{safe_,}substitute() to combine the mapping and keyword arguments. """ def __init__(self, primary, secondary): self._primary = primary self._secondary = secondary def __getitem__(self, key): try: return self._primary[key] except KeyError: return self._secondary[key] class _TemplateMetaclass(type): pattern = r""" %(delim)s(?: (?P<escaped>%(delim)s) | # Escape sequence of two delimiters (?P<named>%(id)s) | # delimiter and a Python identifier {(?P<braced>%(id)s)} | # delimiter and a braced identifier (?P<invalid>) # Other ill-formed delimiter exprs ) """ def __init__(cls, name, bases, dct): super(_TemplateMetaclass, cls).__init__(name, bases, dct) if 'pattern' in dct: pattern = cls.pattern else: pattern = _TemplateMetaclass.pattern % { 'delim' : _re.escape(cls.delimiter), 'id' : cls.idpattern, } cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE) class Template: """A string class for supporting $-substitutions.""" __metaclass__ = _TemplateMetaclass delimiter = '$' idpattern = r'[_a-z][_a-z0-9]*' def __init__(self, template): self.template = template # Search for $$, $identifier, ${identifier}, and any bare $'s def _invalid(self, mo): i = mo.start('invalid') lines = self.template[:i].splitlines(True) if not lines: colno = 1 lineno = 1 else: colno = i - len(''.join(lines[:-1])) lineno = len(lines) raise ValueError('Invalid placeholder in string: line %d, col %d' % (lineno, colno)) def substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): # Check the most common path first. named = mo.group('named') or mo.group('braced') if named is not None: val = mapping[named] # We use this idiom instead of str() because the latter will # fail if val is a Unicode containing non-ASCII characters. return '%s' % val if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: self._invalid(mo) raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) def safe_substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): named = mo.group('named') if named is not None: try: # We use this idiom instead of str() because the latter # will fail if val is a Unicode containing non-ASCII return '%s' % mapping[named] except KeyError: return self.delimiter + named braced = mo.group('braced') if braced is not None: try: return '%s' % mapping[braced] except KeyError: return self.delimiter + '{' + braced + '}' if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: return self.delimiter raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) #################################################################### # End Snagging #################################################################### class Utils: # Holds collection of small utility functions EXTRA_FLAGPOLL_SEARCH_PATHS = "" EXTRA_FLAGPOLL_FILES = "" path_list_cache = None # Cache of found path lists. (only calcuate once) def getFlagpollVersion(): FLAGPOLL_MAJOR_VERSION = 0 FLAGPOLL_MINOR_VERSION = 2 FLAGPOLL_PATCH_VERSION = 1 return ( FLAGPOLL_MAJOR_VERSION, FLAGPOLL_MINOR_VERSION, FLAGPOLL_PATCH_VERSION ) getFlagpollVersion = staticmethod(getFlagpollVersion) def getPathList(): if None != Utils.path_list_cache: return Utils.path_list_cache #TODO: expand LD_LIBRARY_PATH to 64/32/etc??? pkg_cfg_dir = [] flg_cfg_dir = [] ld_path = [] if os.environ.has_key("PKG_CONFIG_DIR"): pkg_cfg_dir = os.environ["PKG_CONFIG_DIR"].split(os.pathsep) if os.environ.has_key("FLG_CONFIG_DIR"): flg_cfg_dir = os.environ["FLG_CONFIG_DIR"].split(os.pathsep) if os.environ.has_key("LD_LIBRARY_PATH"): ld_path = os.environ["LD_LIBRARY_PATH"].split(os.pathsep) ld_path = [pj(p,'pkgconfig') for p in ld_path] extra_paths = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS.split(os.pathsep) path_list = ["/usr/lib64/pkgconfig", "/usr/lib/pkgconfig", "/usr/share/pkgconfig"] path_list.extend(pkg_cfg_dir) path_list.extend(flg_cfg_dir) path_list.extend(extra_paths) path_list.extend(ld_path) flagDBG().out(flagDBG.VERBOSE, "Utils.getPathList", "Potential path list: " + str(path_list)) path_list = [p for p in path_list if os.path.exists(p)] flagDBG().out(flagDBG.INFO, "Utils.getPathList", "Using path list: " + str(path_list)) Utils.path_list_cache = path_list return path_list getPathList = staticmethod(getPathList) def getFileList(): flist = Utils.EXTRA_FLAGPOLL_FILES.split(":") filelist = [] for f in flist: if os.path.isfile(f): filelist.append(f) return filelist getFileList = staticmethod(getFileList) def stripDupInList(gen_list): new_list = [] for item in gen_list: if item not in new_list: if len(item) > 0: new_list.append(item) return new_list stripDupInList = staticmethod(stripDupInList) def stripDupLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] dir_list = [] for flg in flag_list: flg = flg.strip() if flg not in lib_list and flg not in dir_list: if len(flg) > 0: if flg.startswith("-L") or flg.startswith("-R"): dir_list.append(flg) else: lib_list.append(flg) new_list = dir_list + lib_list return new_list stripDupLinkerFlags = staticmethod(stripDupLinkerFlags) def stripDupIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] extra_list = [] for flg in flag_list: flg = flg.strip() if flg not in inc_list and flg not in extra_list: if len(flg) > 0: if flg.startswith("-I"): inc_list.append(flg) else: extra_list.append(flg) extra_list.sort() new_list = inc_list + extra_list return new_list stripDupIncludeFlags = staticmethod(stripDupIncludeFlags) def cflagsOnlyDirIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] for flg in flag_list: flg = flg.strip() if flg not in inc_list: if len(flg) > 0: if flg.startswith("-I"): inc_list.append(flg) return inc_list cflagsOnlyDirIncludeFlags = staticmethod(cflagsOnlyDirIncludeFlags) def cflagsOnlyOtherIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though extra_list = [] for flg in flag_list: flg = flg.strip() if flg not in extra_list: if len(flg) > 0: if not flg.startswith("-I"): extra_list.append(flg) return extra_list cflagsOnlyOtherIncludeFlags = staticmethod(cflagsOnlyOtherIncludeFlags) def libsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] for flg in flag_list: flg = flg.strip() if flg not in lib_list: if len(flg) > 0: if flg.startswith("-l"): lib_list.append(flg) return lib_list libsOnlyLinkerFlags = staticmethod(libsOnlyLinkerFlags) def libsOnlyOtherLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though other_list = [] for flg in flag_list: flg = flg.strip() if flg not in other_list: if len(flg) > 0: if not flg.startswith("-l") and not flg.startswith("-L") and not flg.startswith("-R"): other_list.append(flg) return other_list libsOnlyOtherLinkerFlags = staticmethod(libsOnlyOtherLinkerFlags) def libDirsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though dir_list = [] for flg in flag_list: flg = flg.strip() if flg not in dir_list: if len(flg) > 0: if flg.startswith("-L") or flg.startswith("-R"): dir_list.append(flg) return dir_list libDirsOnlyLinkerFlags = staticmethod(libDirsOnlyLinkerFlags) def printList(gen_list): list_string = "" for item in gen_list: if len(item) > 0: list_string+=str(item) list_string+=" " print list_string printList = staticmethod(printList) def parsePcFile(filename): lines = open(filename).readlines() fvars = {} lokals = {} for line in lines: line = line.strip() if not line: continue elif ':' in line: # exported variable name, val = line.split(':', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(lokals) except ValueError: flagDBG().out(flagDBG.ERROR, "PkgInfo.parse", "%s has an invalid .pc file" % filename) fvars[name] = val elif '=' in line: # local variable name, val = line.split('=', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(lokals) except ValueError: flagDBG().out(flagDBG.WARN, "PkgInfo.parse", "%s has an invalid .pc file" % filename) lokals[name] = val fvars["XXFlagpollFilenameXX"] = filename return fvars parsePcFile = staticmethod(parsePcFile) class flagDBG(object): # Logging class is really easy to use # Levels: # 0 - VERBOSE # 1 - INFO # 2 - WARN # 3 - ERROR VERBOSE=0 INFO=1 WARN=2 ERROR=3 __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if flagDBG.__initialized: return flagDBG.__initialized = True self.mLevel = self.WARN self.mLevelList = ["VERBOSE","INFO","WARN","ERROR"] def setLevel(self, level): if level <= 3: self.mLevel = level def out(self, level, obj, message): if level >= self.mLevel: print self.mLevelList[level] + ":" + str(obj) + ": " + str(message) if level == self.ERROR: sys.exit(1) class DepResolutionSystem(object): """ You add PkgAgents with Filters into system and call resolve() you can check for succes by depsSatisfied() and get the list of packages that work back by calling getPackages() """ __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if DepResolutionSystem.__initialized: return DepResolutionSystem.__initialized = True self.mResolveAgents = [] self.mAgentDict = {} self.mFilters = [] self.mResolveAgentFilters = [] self.mInvalidPackageList = [] self.mSatisfied = False self.mAgentChangeList = [] # list of those responsible for adding Filters # to agents in higher in the chain than them # these are the first agents to ask that they pick # the next best package of them self.mAgentsVisitedList = [] # list of Agents that have been visited self.mResolvedPackageList = [] # list that is generated when deps are satified self.mCheckPrivateRequires = False def getFilters(self): return self.mFilters def addFilter(self, filter): self.mFilters.append(filter) def addResolveAgentFilter(self, filter): self.mResolveAgentFilters.append(filter) def makeRequireFilter(self, requires): arch_list = [] arch_list.append("no_arch") arch_list.append("") if platform.system() == "Linux": if requires == "64": arch_list.append("x86_64") if requires == "32": arch_list.append("i386") arch_list.append("i586") arch_list.append("i686") if platform.system() == "Darwin": if requires == "64": arch_list.append("ppc64") if requires == "32": arch_list.append("ppc") new_filter = Filter("Arch", lambda x: x in arch_list) self.addFilter(new_filter) def createAgent(self, name): if self.checkAgentExists(name): return self.getAgent(name) else: agent = PkgAgent(name) flagDBG().out(flagDBG.INFO, "DepResSys.createAgent", "Adding %s" % name) self.addNewAgent(agent) return agent def createResolveAgent(self, name): if self.checkAgentExists(name): return self.getAgent(name) else: agent = PkgAgent(name) flagDBG().out(flagDBG.INFO, "DepResSys.createResloveAgent", "Adding %s" % name) self.addResolveAgent(agent) return agent def setPrivateRequires( self, req ): self.mCheckPrivateRequires = req def checkPrivateRequires(self): return self.mCheckPrivateRequires def checkAgentExists(self, name): return self.mAgentDict.has_key(name) def getAgent(self, name): if self.mAgentDict.has_key(name): return self.mAgentDict[name] else: flagDBG().out(flagDBG.ERROR, "DepResSys.getAgent", "Agent %s does not exist" % name) def addNewAgent(self, agent): if not self.checkAgentExists(agent): self.mAgentDict[agent.getName()] = agent def addResolveAgent(self, agent): if agent not in self.mResolveAgents: self.mResolveAgents.append(agent) for filt in self.mResolveAgentFilters: agent.addFilter(filt) def isSatisfied(self): return self.mSatisfied def updateResolvedPackages(self): pkg_list = [] agent_list = [] for agent in self.mResolveAgents: list_of_pkgs = agent.getCurrentPackageList(agent_list) pkg_list.extend(list_of_pkgs) self.mResolvedPackageList = pkg_list def getPackages(self): flagDBG().out(flagDBG.VERBOSE, "DepResSys.getPackages", "Generating list of valid packages ") #str([pkg.getCurrentPa.getName() for pkg in self.mResolvedPackageList])) # If this comes back empty then there isn't a valid set of packages to use self.updateResolvedPackages() return self.mResolvedPackageList def checkFiltersChanged(self): list_to_use = [] return True in [pkg.filtersChanged(list_to_use) for pkg in self.mResolveAgents] def resolveHelper(self): self.resolveAgentsChanged = True while self.resolveAgentsChanged: for agent in self.mResolveAgents: flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveHelper", "Updating " + agent.getName()) agent.update(self.mAgentsVisitedList, self.mAgentChangeList) self.resolveAgentsChanged = self.checkFiltersChanged() # Ask mResolveAgents if they are done(they ask sub people) unless they are # really above you in the walk # If there were changes...run update on mResolveAgents again # at the end ask for pkglist..if it comes back empty then we don't # have a usable configuration for those packages def resolveDeps(self): self.resolveHelper() self.updateResolvedPackages() # Check if the first round through we found something # Otherwise we need to start removing packages that aren't viable # during the loop self.mSatisfied = (len(self.mResolvedPackageList) != 0) # remove top of packages that added Filters. # then move on to resolving again # remove more if neccesary agentChangeNumber = 0 while not self.mResolvedPackageList: if(self.mAgentChangeList[agentChangeNumber]): if self.mAgentChangeList[agentChangeNumber] in self.mInvalidPackageList: agentChangeNumber+=1 else: if(self.mAgentChangeList[agentChangeNumber].getViablePackages()): flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveDeps", "Removing bad pkg from " + self.mAgentChangeList[agentChangeNumber].getName()) self.mInvalidPackageList.append(self.mAgentChangeList[agentChangeNumber].removeCurrentPackage()) else: flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveDeps", "No combinations.. Resetting " + self.mAgentChangeList[agentChangeNumber].getName()) self.mAgentChangeList[agentChangeNumber].reset() agentChangeNumber+=1 self.resolveHelper() self.updateResolvedPackages() self.mSatisfied = (len(self.mResolvedPackageList) != 0) return class PkgAgent: """ Agent that keeps track of the versions for a package given some filters and the addition of Filters """ # Makes a PkgAgent that finds its current package with the version reqs def __init__(self, name): if DepResolutionSystem().checkAgentExists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "Package Agent %s already exists" % self.mName) self.mName = name flagDBG().out(flagDBG.VERBOSE, "PkgAgent", "Creating:" + str(self.mName)) if not PkgDB().exists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "No info for package: %s" % self.mName) #XXX Doesn't keep filters added for a redo... DepResolutionSystem().addNewAgent(self) self.mFilterList = [] self.mFilterList.extend(DepResolutionSystem().getFilters()) self.mBasePackageList = PkgDB().getPkgInfos(name) for filt in self.mFilterList: self.mBasePackageList = filt.filter(self.mBasePackageList) if len(self.mBasePackageList) == 0: flagDBG().out(flagDBG.ERROR, "PkgAgent", "No viable packages for: %s" % self.mName) self.mViablePackageList = copy.deepcopy(self.mBasePackageList) if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mAgentDependList = [] # Agents that it depends on/needs to update self.makeDependList() self.mFiltersChanged = True def getName(self): return self.mName #Filter("Version", lambda x: x == "4.5") def makeDependList(self): dep_list = [] if self.mCurrentPackage: req_string = self.mCurrentPackage.getVariable("Requires") if DepResolutionSystem().checkPrivateRequires(): req_string = req_string + " " + self.mCurrentPackage.getVariable("Requires.private") req_string = req_string.strip() if req_string == "": return req_string = req_string.replace(',', ' ') req_string = req_string.replace('(', ' ') req_string = req_string.replace(')', ' ') space_req_string_list = req_string.split(' ') req_string_list = [] for entry in space_req_string_list: if len(entry) > 0: req_string_list.append(entry) i = 0 flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList", self.mCurrentPackage.getName() + " requires: " + str(req_string_list)) while len(req_string_list) > i: if PkgDB().exists(req_string_list[i]): new_filter = [] new_agent = DepResolutionSystem().createAgent(req_string_list[i]) if len(req_string_list) > i+1: if req_string_list[i+1] == "=": ver_to_filt = req_string_list[i+2] new_filter = Filter("Version", lambda x: x == ver_to_filt) elif req_string_list[i+1] == "<=": ver_to_filt = req_string_list[i+2] new_filter = Filter("Version", lambda x: x <= ver_to_filt) elif req_string_list[i+1] == ">=": ver_to_filt = req_string_list[i+2] new_filter = Filter("Version", lambda x: x >= ver_to_filt) else: i+=1 else: i+=1 dep_list.append(new_agent) if new_filter: i+=3 new_agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "PkgAgent.makeDependList", "Package %s depends on %s but is not seem to be installed." % (self.mName, str(req_string_list[i]))) flagDBG().out(flagDBG.VERBOSE, "PkgAgent.makeDependList", "List is:" + str([pkg.getName() for pkg in dep_list])) self.mAgentDependList = dep_list def filtersChanged(self,packageList): tf_list = [self.mFiltersChanged] if self.mName not in packageList: packageList.append(self.mName) for pkg in self.mAgentDependList: tf_list.append(pkg.filtersChanged(packageList)) return True in tf_list def getCurrentPackageList(self, packageList): pkgs = [] if self.mName not in packageList: flagDBG().out(flagDBG.VERBOSE, "PkgAgent.getCurrentPackageList", "Package: %s" % self.mName) pkgs.append(self.mCurrentPackage) packageList.append(self.mName) for pkg in self.mAgentDependList: pkgs.extend(pkg.getCurrentPackageList(packageList)) return pkgs # current pkginfo for me def getCurrentPkgInfo(self): return self.mCurrentPackage # Someone else usually places these on me # I keep track of those separately def addFilter(self, filter): flagDBG().out(flagDBG.VERBOSE, "PkgAgent.addFilter", "Adding a Filter to %s" % self.mName) self.mFiltersChanged = True self.mFilterList.append(filter) def removeCurrentPackage(self): flagDBG().out(flagDBG.VERBOSE, "PkgAgent.removeCurrentPackage", "Removing current package of %s" % self.mName) if self.mViablePackageList: ret_val = self.mViablePackageList[0] in self.mBasePackageList del self.mViablePackageList[0] if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] return ret_val def update(self, agentVisitedList, agentChangeList): if self.mName in agentVisitedList: return agentVisitedList.append(self.mName) if self.mFiltersChanged: self.mFiltersChanged = False self.updateFilters() # TODO: checkFilters and add them # if a pkg is in visitedList then add yourself to agentChangeList for pkg in self.mAgentDependList: pkg.update(agentVisitedList, agentChangeList) return def updateFilters(self): for filt in self.mFilterList: self.mViablePackageList = filt.filter(self.mViablePackageList) if len(self.mViablePackageList) > 0: self.mCurrentPackage = self.mViablePackageList[0] else: self.mCurrentPackage = [] def reset(self): flagDBG().out(flagDBG.VERBOSE, "PkgAgent.reset", "Resetting package: %s" % self.mName) self.mViablePackageList = self.mBasePackageList if self.mViablePackageList: self.mCurrentPacakge = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mFilterList = DepResolutionSystem().getFilters() self.mAgentDependList = [] self.mFiltersChanged = True return class Filter: """ A single Filter that knows how to filter the list it recieves Will be inheireted....?..? """ def __init__(self, variableName, testCallable): self.mVarName = variableName self.mTestCallable = testCallable def filter(self, pkg_info_list): ret_pkg_list = [] # Filter first for pkg in pkg_info_list: var = pkg.getVariable(self.mVarName) if self.mTestCallable(var): ret_pkg_list.append(pkg) # Now sort ret_pkg_list.sort(lambda lhs,rhs: cmp(lhs.getVariable(self.mVarName), rhs.getVariable(self.mVarName))) return ret_pkg_list #requires: qt == 4.5 #Filter("Version", lambda x: x <= "4.5") #Filter("Version", lambda x: x <= "4.5") class PkgDB(object): """ Holds all the neccesary information to evaluate itself when needed. Is in charge of holding a list of PkgInfo's that contain info about the package. """ __initialized = False def __init__(self): if self.__initialized: return self.__initialized = True self.mPkgInfos = {} # {pkg_name: List of package infos} self.populatePkgInfoDBPcFiles() self.populatePkgInfoDBFpcFiles() def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def getVariables(self, name, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariable", "Finding " + str(variable_list) + " in " + str(name)) ret_list = [] for var in variable_list: if self.mPkgInfos.has_key(name): ret_list.extend(self.mPkgInfos[name][0].getVariable(var)) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariable", "Package %s not found." % name) return ret_list def checkPackage(self, name): flagDBG().out(flagDBG.INFO, "PkgDB.checkPackage", "Finding " + str(name)) if self.mPkgInfos.has_key(name): return True else: flagDBG().out(flagDBG.ERROR, "PkgDB.CheckPackage", "Package %s not found." % name) return False def getVariablesAndDeps(self, pkg_list, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariablesAndDeps", "Finding " + str(variable_list) + " in " + str(pkg_list)) if DepResolutionSystem().checkPrivateRequires(): temp_var_list = [] for var in variable_list: temp_var_list.append(var.join(".private")) variable_list = variable_list + temp_var_list for name in pkg_list: if self.mPkgInfos.has_key(name): agent = DepResolutionSystem().createAgent(name) DepResolutionSystem().addResolveAgent(agent) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariablesAndDeps", "Package %s not found." % name) DepResolutionSystem().resolveDeps() pkgs = DepResolutionSystem().getPackages() var_list = [] for pkg in pkgs: if pkg: for var in variable_list: var_list.extend(pkg.getVariable(var).split(' ')) return var_list def getPkgInfos(self, name): if self.mPkgInfos.has_key(name): return self.mPkgInfos[name] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getPkgInfos", "Package %s not found." % name) def exists(self, name): return self.mPkgInfos.has_key(name) def getInfo(self, name): if self.mPkgInfos.has_key(name): return [pkg.getInfo() for pkg in self.mPkgInfos[name]] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getInfo", "Package %s not found." % name) def buildPcFileDict(self): """ Builds up a dictionary of {name: list of files for name} """ pc_dict = {} for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.pc")) # List of .pc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these pc files: %s" % str(glob_list)) for g in glob_list: # Get key name and add file to value list in dictionary key = os.path.basename(g)[:-3] # Strip .pc off the filename...rstrip no worky pc_dict.setdefault(key,[]).append(g) for f in Utils.getFileList(): if f.endswith(".pc"): key = os.path.basename(f)[:-3] # Strip .pc off the filename...rstrip no worky pc_dict.setdefault(key,[]).append(f) return pc_dict # { "key", [ "list", "of", "corresponding", "pc", "files"] } def populatePkgInfoDBPcFiles(self): dict_to_pop_from = self.buildPcFileDict() for (pkg,files) in dict_to_pop_from.iteritems(): for f in files: self.mPkgInfos.setdefault(pkg,[]).append(PkgInfo(pkg, f, "pc")) def buildFpcFileList(self): """ Builds up a dictionary of {name: list of files for name} """ file_list = [] for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.fpc")) # List of .fpc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these fpc files: %s" % str(glob_list)) for g in glob_list: file_list.append(g) for f in Utils.getFileList(): if f.endswith(".fpc"): file_list.append(f) return file_list # [ "list", "of", "fpc", "files"] def populatePkgInfoDBFpcFiles(self): list_to_add = self.buildFpcFileList() for filename in list_to_add: var_dict = Utils.parsePcFile(filename) if not var_dict.has_key("Provides"): flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Provides" % str(filename)) continue if not var_dict.has_key("Arch"): flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Arch" % str(filename)) continue provides_string = var_dict["Provides"] provides_string = provides_string.replace(',', ' ') provides_string = provides_string.replace('(', ' ') provides_string = provides_string.replace(')', ' ') for key in provides_string.split(" "): if len(key) > 0: self.mPkgInfos.setdefault(key,[]).append(PkgInfo(key, filename, "fpc", var_dict)) class PkgInfo: """ Holds the information for a package file on the system. These however are evaluated when the need arises. """ def __init__(self, name, file, type, varDict={}): self.mName = name self.mFile = file self.mIsEvaluated = False self.mType = type self.mVariableDict = varDict if self.mType == "fpc": self.mIsEvaluated = True def getVariable(self, variable): self.evaluate() return self.mVariableDict.get(variable,"") def getName(self): return self.mName def evaluate(self): if not self.mIsEvaluated: flagDBG().out(flagDBG.INFO, "PkgInfo.evaluate", "Evaluating %s" % self.mName) self.mVariableDict= Utils.parsePcFile(self.mFile) self.mIsEvaluated = True def getInfo(self): self.evaluate() return self.mVariableDict class OptionsEvaluator: def __init__(self): #self.mOptParser = self.GetOptionParser() #self.mOptParser.print_help() if sys.argv < 1: self.printHelp() #(self.mOptions, self.mArgs) = self.mOptParser.parse_args() #if self.mOptions.version: # print "%s.%s.%s" % Utils.getFlagpollVersion() # sys.exit(0) #if len(self.mArgs) < 1: # self.mOptParser.print_help() # sys.exit(1) # This is only the args....(first arg is stripped) def evaluateArgs(self, args): # Catch any args that need to be tended to immediately # Process args in the order that they were recieved. Some options are not # shown below because they are sub-options of an option below (--strip-dups) for option in args: if option.startswith("--debug"): flagDBG().setLevel(flagDBG.VERBOSE) elif option.startswith("--from-file"): val_start = option.find('=') + 1 file = option[val_start:] Utils.EXTRA_FLAGPOLL_FILES = Utils.EXTRA_FLAGPOLL_FILES + ":" + file elif option.startswith("--help"): self.printHelp() sys.exit(0) elif option.startswith("--version"): print "%s.%s.%s" % Utils.getFlagpollVersion() sys.exit(0) agent = None num_args = len(args) curr_arg = 0 output_options = [] # (option, name/"") important_options = [] # ones that need special attention while curr_arg < num_args: if args[curr_arg].startswith("--atleast-version"): val_start = args[curr_arg].find('=') + 1 atleast_version = args[curr_arg][val_start:] atleast_filter = Filter("Version", lambda x: x >= atleast_version) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(atleast_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue if args[curr_arg].startswith("--cflags-only-I"): output_options.append(("cflags-only-I", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--cflags-only-other"): output_options.append(("cflags-only-other", "")) curr_arg = curr_arg + 1 continue #This could be the catch all for the above ones to and then filter based on what is asked... #For clarity of course... if args[curr_arg].startswith("--cflags"): output_options.append(("cflags", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--extra-paths"): val_start = args[curr_arg].find('=') + 1 paths = args[curr_arg][val_start:] Utils.EXTRA_FLAGPOLL_SEARCH_PATHS = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS + ":" + paths curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--exact-version"): val_start = args[curr_arg].find('=') + 1 exact_version = args[curr_arg][val_start:] exact_filter = Filter("Version", lambda x: x == exact_version) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(exact_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue if args[curr_arg].startswith("--exists"): important_options.append("exists") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--from-file"): val_start = args[curr_arg].find('=') + 1 file = args[curr_arg][val_start:] file_filter = Filter("XXFlagpollFilenameXX", lambda x: x == file) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(file_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue if args[curr_arg].startswith("--info"): output_options.append(("info", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-l"): output_options.append(("libs-only-l", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-L"): output_options.append(("libs-only-L", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-other"): output_options.append(("libs-only-other", "")) curr_arg = curr_arg + 1 continue #This could be the catch all for the above ones to and then filter based on what is asked... if args[curr_arg].startswith("--libs"): output_options.append(("libs", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--list-all"): curr_arg = curr_arg + 1 PkgDB().printAllPackages() continue if args[curr_arg].startswith("--require-all"): rlen = len("--require-all") req_string = args[curr_arg][rlen:] req_string = req_string.replace('-','_') curr_arg = curr_arg + 1 if req_string.find("<=") != -1: op_start = req_string.find("<=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x: x <= req_val) DepResolutionSystem().addFilter(new_filter) continue if req_string.find(">=") != -1: op_start = req_string.find(">=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x: x >= req_val) DepResolutionSystem().addFilter(new_filter) continue if req_string.find(">") != -1: op_start = req_string.find(">") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x > req_val) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("<") != -1: op_start = req_string.find("<") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x < req_val) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("=") != -1: op_start = req_string.find("=") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x == req_val) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("=") == -1: new_filter = Filter(req_string, lambda x: len(x) > 0) DepResolutionSystem().addFilter(new_filter) continue continue if args[curr_arg].startswith("--require-"): rlen = len("--require-") req_string = args[curr_arg][rlen:] req_string = req_string.replace('-','_') curr_arg = curr_arg + 1 if req_string.find("<=") != -1: op_start = req_string.find("<=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x: x <= req_val) if agent is not None: agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue if req_string.find(">=") != -1: op_start = req_string.find(">=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x: x >= req_val) if agent is not None: agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue if req_string.find(">") != -1: op_start = req_string.find(">") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x > req_val) if agent is not None: agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue if req_string.find("<") != -1: op_start = req_string.find("<") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x < req_val) if agent is not None: agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue if req_string.find("=") != -1: op_start = req_string.find("=") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x == req_val) if agent is not None: agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue if req_string.find("=") == -1: new_filter = Filter(req_string, lambda x: len(x) > 0) if agent is not None: agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue continue if args[curr_arg].startswith("--require="): val_start = args[curr_arg].find('=') + 1 req_var = args[curr_arg][val_start:] curr_arg = curr_arg + 1 DepResolutionSystem().makeRequireFilter(req_var) continue if args[curr_arg].startswith("--modversion"): if agent is not None: output_options.append(("Version", agent.getName())) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--exact-version"): val_start = args[curr_arg].find('=') + 1 exact_version = args[curr_arg][val_start:] exact_filter = Filter("Version", lambda x: x == exact_version) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(exact_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue if args[curr_arg].startswith("--max-release"): val_start = args[curr_arg].find('=') + 1 max_release = args[curr_arg][val_start:] max_filter = Filter("Version", lambda x: x.startswith(max_release)) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(max_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue if args[curr_arg].startswith("--static"): DepResolutionSystem().setPrivateRequires(True) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--variable"): val_start = args[curr_arg].find('=') + 1 fetch_var = args[curr_arg][val_start:] if agent is not None: output_options.append((fetch_var, agent.getName())) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--get-all"): rlen = len("--get-all-") get_string = args[curr_arg][rlen:] get_string = get_string.replace('-','_') output_options.append((get_string, "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--get"): rlen = len("--get-") get_string = args[curr_arg][rlen:] get_string = get_string.replace('-','_') if agent is not None: output_options.append((get_string, agent.getName())) curr_arg = curr_arg + 1 continue if not args[curr_arg].startswith("--"): name = args[curr_arg] curr_arg = curr_arg + 1 if PkgDB().checkPackage(name): agent = DepResolutionSystem().createResolveAgent(name) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Package %s" % name) sys.exit(1) continue #flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Option: %s" % args[curr_arg]) curr_arg = curr_arg + 1 DepResolutionSystem().resolveDeps() pkgs = DepResolutionSystem().getPackages() for p in pkgs: if not p: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found") if len(pkgs) == 0: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found") sys.exit(1) for option in important_options: if option == "exists": return sys.exit(0) # already checked for none above #print output_options #output_options = [] #output_single = [] #Process options here.............. for option in output_options: if option[0] == "cflags": Utils.printList(Utils.stripDupIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "cflags-only-I": Utils.printList(Utils.cflagsOnlyDirIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "cflags-only-other": Utils.printList(Utils.cflagsOnlyOtherIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "libs-only-l": Utils.printList(Utils.libsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs-only-L": Utils.printList(Utils.libDirsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs-only-other": Utils.printList(Utils.libsOnlyOtherLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs": Utils.printList(Utils.stripDupLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) else: Utils.printList(Utils.stripDupInList(self.getVarFromPkgs(option[0], pkgs, option[1]))) def getVarFromPkgs(self, var, pkgs, pkg_name=""): var_list = [] ext_vars = [] if var == "Libs": if DepResolutionSystem().checkPrivateRequires: ext_vars.append("Libs.private") if pkg_name == "": for pkg in pkgs: if pkg: var_list.extend(pkg.getVariable(var).split(' ')) for extra_var in ext_vars: var_list.extend(pkg.getVariable(extra_var).split(' ')) else: for pkg in pkgs: if pkg: if pkg.getName() == pkg_name: var_list.extend(pkg.getVariable(var).split(' ')) for extra_var in ext_vars: var_list.extend(pkg.getVariable(extra_var).split(' ')) return var_list def printHelp(self): print "usage: flagpoll pkg options [pkg options] [generic options]" print " " print "generic options:" print " --help show this help message and exit" print " --version output version of flagpoll" print " --list-all list all known packages" print " --debug show verbose debug information" print " --extra-paths=EXTRA_PATHS" print " extra paths for flagpoll to search for meta-data files" print " " print "options:" print " --modversion output version for package" print " --require=REQUIRE adds additional requirements for packages ex. 32/64" print " --libs output all linker flags" print " --static output linker flags for static linking" print " --libs-only-l output -l flags" print " --libs-only-other output other libs (e.g. -pthread)" print " --libs-only-L output -L flags" print " --cflags output all pre-processor and compiler flags" print " --cflags-only-I output -I flags" print " --cflags-only-other output cflags not covered by the cflags-only-I option" print " --exists return 0 if the module(s) exist" print " --from-file=FILE use the specified FILE for the package" print " --info show information for packages" print " --print-provides print which packages the package provides" print " --print-requires print which packages the package requires" print " --atleast-version=ATLEAST_VERSION" print " return 0 if the module is at least version" print " ATLEAST_VERSION" print " --exact-version=EXACT_VERSION" print " return 0 if the module is exactly version" print " EXACT_VERSION" print " --max-release=MAX_RELEASE" print " return 0 if the module has a release that has a" print " version of MAX_RELEASE and will return the max" print " --variable=VARIABLE get the value of a variable" print " " print "dynamic options(replace VAR with a variable you want to get/filter on)" print " NOTE: replace underscores with dashes in VAR" print " NOTE: quotes are needed around <,>,= combinations" print " --get-VAR get VAR from package" print " --get-all-VAR get VAR from package and its deps" print " --require-VAR[<,>,=VAL]" print " require that a var is defined for a package" print " or optionally use equality operators against VAL" print " --require-all-VAR[<,>,=VAL]" print " require that a var is defined for all packages" print " or optionally use equality operators against VAL" def main(): # GO! # Initialize singletons and the start evaluating #print sys.argv[1:] my_dbg = flagDBG() my_dep_system = DepResolutionSystem() opt_evaluator = OptionsEvaluator() opt_evaluator.evaluateArgs(sys.argv[1:]) sys.exit(0) if __name__ == "__main__": main()
Python
#!/usr/bin/env python from distutils.core import setup setup( name='flagpoll', version='0.2.1', description='Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software.', author='Daniel E. Shipton', author_email='dshipton@infiscape.com', license='GPL', url='https://realityforge.vrsource.org/view/FlagPoll/WebHome', download_url='https://realityforge.vrsource.org/view/FlagPoll/FlagpollDownloads', scripts=['flagpoll'], long_description = "Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software. Think of it as the rpm of software development. It enables developers total control over which packages, versions, architectures, etc. that they want to use meta-data from.", data_files=[('share/flagpoll', ['flagpoll.fpc']), ('share/man/man1', ['flagpoll.1'])] )
Python
#!/usr/bin/env python # ----------------------------------------------------------------- # # Flagpoll: A tool to extract flags from installed applications # for compiling, settting variables, etc. # # Original Authors: # Daniel E. Shipton <dshipton@gmail.com> # # Flagpoll is Copyright (C) 2006 by Daniel E. Shipton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to: # Free SoftwareFoundation, Inc. # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # # ----------------------------------------------------------------- from optparse import OptionParser import sys, os, glob, os.path, copy, platform pj = os.path.join #################################################################### # SNAGGED FROM PYTHON 2.4 for versions under 2.4 #################################################################### import re as _re class _multimap: """Helper class for combining multiple mappings. Used by .{safe_,}substitute() to combine the mapping and keyword arguments. """ def __init__(self, primary, secondary): self._primary = primary self._secondary = secondary def __getitem__(self, key): try: return self._primary[key] except KeyError: return self._secondary[key] class _TemplateMetaclass(type): pattern = r""" %(delim)s(?: (?P<escaped>%(delim)s) | # Escape sequence of two delimiters (?P<named>%(id)s) | # delimiter and a Python identifier {(?P<braced>%(id)s)} | # delimiter and a braced identifier (?P<invalid>) # Other ill-formed delimiter exprs ) """ def __init__(cls, name, bases, dct): super(_TemplateMetaclass, cls).__init__(name, bases, dct) if 'pattern' in dct: pattern = cls.pattern else: pattern = _TemplateMetaclass.pattern % { 'delim' : _re.escape(cls.delimiter), 'id' : cls.idpattern, } cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE) class Template: """A string class for supporting $-substitutions.""" __metaclass__ = _TemplateMetaclass delimiter = '$' idpattern = r'[_a-z][_a-z0-9]*' def __init__(self, template): self.template = template # Search for $$, $identifier, ${identifier}, and any bare $'s def _invalid(self, mo): i = mo.start('invalid') lines = self.template[:i].splitlines(True) if not lines: colno = 1 lineno = 1 else: colno = i - len(''.join(lines[:-1])) lineno = len(lines) raise ValueError('Invalid placeholder in string: line %d, col %d' % (lineno, colno)) def substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): # Check the most common path first. named = mo.group('named') or mo.group('braced') if named is not None: val = mapping[named] # We use this idiom instead of str() because the latter will # fail if val is a Unicode containing non-ASCII characters. return '%s' % val if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: self._invalid(mo) raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) def safe_substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): named = mo.group('named') if named is not None: try: # We use this idiom instead of str() because the latter # will fail if val is a Unicode containing non-ASCII return '%s' % mapping[named] except KeyError: return self.delimiter + named braced = mo.group('braced') if braced is not None: try: return '%s' % mapping[braced] except KeyError: return self.delimiter + '{' + braced + '}' if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: return self.delimiter raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) #################################################################### # End Snagging #################################################################### class Utils: # Holds collection of small utility functions EXTRA_FLAGPOLL_SEARCH_PATHS = "" EXTRA_FLAGPOLL_FILES = "" path_list_cache = None # Cache of found path lists. (only calcuate once) def getFlagpollVersion(): FLAGPOLL_MAJOR_VERSION = 0 FLAGPOLL_MINOR_VERSION = 2 FLAGPOLL_PATCH_VERSION = 1 return ( FLAGPOLL_MAJOR_VERSION, FLAGPOLL_MINOR_VERSION, FLAGPOLL_PATCH_VERSION ) getFlagpollVersion = staticmethod(getFlagpollVersion) def getPathList(): if None != Utils.path_list_cache: return Utils.path_list_cache #TODO: expand LD_LIBRARY_PATH to 64/32/etc??? pkg_cfg_dir = [] flg_cfg_dir = [] ld_path = [] if os.environ.has_key("PKG_CONFIG_DIR"): pkg_cfg_dir = os.environ["PKG_CONFIG_DIR"].split(os.pathsep) if os.environ.has_key("FLG_CONFIG_DIR"): flg_cfg_dir = os.environ["FLG_CONFIG_DIR"].split(os.pathsep) if os.environ.has_key("LD_LIBRARY_PATH"): ld_path = os.environ["LD_LIBRARY_PATH"].split(os.pathsep) ld_path = [pj(p,'pkgconfig') for p in ld_path] extra_paths = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS.split(os.pathsep) path_list = ["/usr/lib64/pkgconfig", "/usr/lib/pkgconfig", "/usr/share/pkgconfig"] path_list.extend(pkg_cfg_dir) path_list.extend(flg_cfg_dir) path_list.extend(extra_paths) path_list.extend(ld_path) flagDBG().out(flagDBG.VERBOSE, "Utils.getPathList", "Potential path list: " + str(path_list)) path_list = [p for p in path_list if os.path.exists(p)] flagDBG().out(flagDBG.INFO, "Utils.getPathList", "Using path list: " + str(path_list)) Utils.path_list_cache = path_list return path_list getPathList = staticmethod(getPathList) def getFileList(): flist = Utils.EXTRA_FLAGPOLL_FILES.split(":") filelist = [] for f in flist: if os.path.isfile(f): filelist.append(f) return filelist getFileList = staticmethod(getFileList) def stripDupInList(gen_list): new_list = [] for item in gen_list: if item not in new_list: if len(item) > 0: new_list.append(item) return new_list stripDupInList = staticmethod(stripDupInList) def stripDupLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] dir_list = [] for flg in flag_list: flg = flg.strip() if flg not in lib_list and flg not in dir_list: if len(flg) > 0: if flg.startswith("-L") or flg.startswith("-R"): dir_list.append(flg) else: lib_list.append(flg) new_list = dir_list + lib_list return new_list stripDupLinkerFlags = staticmethod(stripDupLinkerFlags) def stripDupIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] extra_list = [] for flg in flag_list: flg = flg.strip() if flg not in inc_list and flg not in extra_list: if len(flg) > 0: if flg.startswith("-I"): inc_list.append(flg) else: extra_list.append(flg) extra_list.sort() new_list = inc_list + extra_list return new_list stripDupIncludeFlags = staticmethod(stripDupIncludeFlags) def cflagsOnlyDirIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] for flg in flag_list: flg = flg.strip() if flg not in inc_list: if len(flg) > 0: if flg.startswith("-I"): inc_list.append(flg) return inc_list cflagsOnlyDirIncludeFlags = staticmethod(cflagsOnlyDirIncludeFlags) def cflagsOnlyOtherIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though extra_list = [] for flg in flag_list: flg = flg.strip() if flg not in extra_list: if len(flg) > 0: if not flg.startswith("-I"): extra_list.append(flg) return extra_list cflagsOnlyOtherIncludeFlags = staticmethod(cflagsOnlyOtherIncludeFlags) def libsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] for flg in flag_list: flg = flg.strip() if flg not in lib_list: if len(flg) > 0: if flg.startswith("-l"): lib_list.append(flg) return lib_list libsOnlyLinkerFlags = staticmethod(libsOnlyLinkerFlags) def libsOnlyOtherLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though other_list = [] for flg in flag_list: flg = flg.strip() if flg not in other_list: if len(flg) > 0: if not flg.startswith("-l") and not flg.startswith("-L") and not flg.startswith("-R"): other_list.append(flg) return other_list libsOnlyOtherLinkerFlags = staticmethod(libsOnlyOtherLinkerFlags) def libDirsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though dir_list = [] for flg in flag_list: flg = flg.strip() if flg not in dir_list: if len(flg) > 0: if flg.startswith("-L") or flg.startswith("-R"): dir_list.append(flg) return dir_list libDirsOnlyLinkerFlags = staticmethod(libDirsOnlyLinkerFlags) def printList(gen_list): list_string = "" for item in gen_list: if len(item) > 0: list_string+=str(item) list_string+=" " print list_string printList = staticmethod(printList) def parsePcFile(filename): lines = open(filename).readlines() fvars = {} lokals = {} for line in lines: line = line.strip() if not line: continue elif ':' in line: # exported variable name, val = line.split(':', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(lokals) except ValueError: flagDBG().out(flagDBG.ERROR, "PkgInfo.parse", "%s has an invalid .pc file" % filename) fvars[name] = val elif '=' in line: # local variable name, val = line.split('=', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(lokals) except ValueError: flagDBG().out(flagDBG.WARN, "PkgInfo.parse", "%s has an invalid .pc file" % filename) lokals[name] = val fvars["XXFlagpollFilenameXX"] = filename return fvars parsePcFile = staticmethod(parsePcFile) class flagDBG(object): # Logging class is really easy to use # Levels: # 0 - VERBOSE # 1 - INFO # 2 - WARN # 3 - ERROR VERBOSE=0 INFO=1 WARN=2 ERROR=3 __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if flagDBG.__initialized: return flagDBG.__initialized = True self.mLevel = self.WARN self.mLevelList = ["VERBOSE","INFO","WARN","ERROR"] def setLevel(self, level): if level <= 3: self.mLevel = level def out(self, level, obj, message): if level >= self.mLevel: print self.mLevelList[level] + ":" + str(obj) + ": " + str(message) if level == self.ERROR: sys.exit(1) class DepResolutionSystem(object): """ You add PkgAgents with Filters into system and call resolve() you can check for succes by depsSatisfied() and get the list of packages that work back by calling getPackages() """ __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if DepResolutionSystem.__initialized: return DepResolutionSystem.__initialized = True self.mResolveAgents = [] self.mAgentDict = {} self.mFilters = [] self.mResolveAgentFilters = [] self.mInvalidPackageList = [] self.mSatisfied = False self.mAgentChangeList = [] # list of those responsible for adding Filters # to agents in higher in the chain than them # these are the first agents to ask that they pick # the next best package of them self.mAgentsVisitedList = [] # list of Agents that have been visited self.mResolvedPackageList = [] # list that is generated when deps are satified self.mCheckPrivateRequires = False def getFilters(self): return self.mFilters def addFilter(self, filter): self.mFilters.append(filter) def addResolveAgentFilter(self, filter): self.mResolveAgentFilters.append(filter) def makeRequireFilter(self, requires): arch_list = [] arch_list.append("no_arch") arch_list.append("") if platform.system() == "Linux": if requires == "64": arch_list.append("x86_64") if requires == "32": arch_list.append("i386") arch_list.append("i586") arch_list.append("i686") if platform.system() == "Darwin": if requires == "64": arch_list.append("ppc64") if requires == "32": arch_list.append("ppc") new_filter = Filter("Arch", lambda x: x in arch_list) self.addFilter(new_filter) def createAgent(self, name): if self.checkAgentExists(name): return self.getAgent(name) else: agent = PkgAgent(name) flagDBG().out(flagDBG.INFO, "DepResSys.createAgent", "Adding %s" % name) self.addNewAgent(agent) return agent def createResolveAgent(self, name): if self.checkAgentExists(name): return self.getAgent(name) else: agent = PkgAgent(name) flagDBG().out(flagDBG.INFO, "DepResSys.createResloveAgent", "Adding %s" % name) self.addResolveAgent(agent) return agent def setPrivateRequires( self, req ): self.mCheckPrivateRequires = req def checkPrivateRequires(self): return self.mCheckPrivateRequires def checkAgentExists(self, name): return self.mAgentDict.has_key(name) def getAgent(self, name): if self.mAgentDict.has_key(name): return self.mAgentDict[name] else: flagDBG().out(flagDBG.ERROR, "DepResSys.getAgent", "Agent %s does not exist" % name) def addNewAgent(self, agent): if not self.checkAgentExists(agent): self.mAgentDict[agent.getName()] = agent def addResolveAgent(self, agent): if agent not in self.mResolveAgents: self.mResolveAgents.append(agent) for filt in self.mResolveAgentFilters: agent.addFilter(filt) def isSatisfied(self): return self.mSatisfied def updateResolvedPackages(self): pkg_list = [] agent_list = [] for agent in self.mResolveAgents: list_of_pkgs = agent.getCurrentPackageList(agent_list) pkg_list.extend(list_of_pkgs) self.mResolvedPackageList = pkg_list def getPackages(self): flagDBG().out(flagDBG.VERBOSE, "DepResSys.getPackages", "Generating list of valid packages ") #str([pkg.getCurrentPa.getName() for pkg in self.mResolvedPackageList])) # If this comes back empty then there isn't a valid set of packages to use self.updateResolvedPackages() return self.mResolvedPackageList def checkFiltersChanged(self): list_to_use = [] return True in [pkg.filtersChanged(list_to_use) for pkg in self.mResolveAgents] def resolveHelper(self): self.resolveAgentsChanged = True while self.resolveAgentsChanged: for agent in self.mResolveAgents: flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveHelper", "Updating " + agent.getName()) agent.update(self.mAgentsVisitedList, self.mAgentChangeList) self.resolveAgentsChanged = self.checkFiltersChanged() # Ask mResolveAgents if they are done(they ask sub people) unless they are # really above you in the walk # If there were changes...run update on mResolveAgents again # at the end ask for pkglist..if it comes back empty then we don't # have a usable configuration for those packages def resolveDeps(self): self.resolveHelper() self.updateResolvedPackages() # Check if the first round through we found something # Otherwise we need to start removing packages that aren't viable # during the loop self.mSatisfied = (len(self.mResolvedPackageList) != 0) # remove top of packages that added Filters. # then move on to resolving again # remove more if neccesary agentChangeNumber = 0 while not self.mResolvedPackageList: if(self.mAgentChangeList[agentChangeNumber]): if self.mAgentChangeList[agentChangeNumber] in self.mInvalidPackageList: agentChangeNumber+=1 else: if(self.mAgentChangeList[agentChangeNumber].getViablePackages()): flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveDeps", "Removing bad pkg from " + self.mAgentChangeList[agentChangeNumber].getName()) self.mInvalidPackageList.append(self.mAgentChangeList[agentChangeNumber].removeCurrentPackage()) else: flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveDeps", "No combinations.. Resetting " + self.mAgentChangeList[agentChangeNumber].getName()) self.mAgentChangeList[agentChangeNumber].reset() agentChangeNumber+=1 self.resolveHelper() self.updateResolvedPackages() self.mSatisfied = (len(self.mResolvedPackageList) != 0) return class PkgAgent: """ Agent that keeps track of the versions for a package given some filters and the addition of Filters """ # Makes a PkgAgent that finds its current package with the version reqs def __init__(self, name): if DepResolutionSystem().checkAgentExists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "Package Agent %s already exists" % self.mName) self.mName = name flagDBG().out(flagDBG.VERBOSE, "PkgAgent", "Creating:" + str(self.mName)) if not PkgDB().exists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "No info for package: %s" % self.mName) #XXX Doesn't keep filters added for a redo... DepResolutionSystem().addNewAgent(self) self.mFilterList = [] self.mFilterList.extend(DepResolutionSystem().getFilters()) self.mBasePackageList = PkgDB().getPkgInfos(name) for filt in self.mFilterList: self.mBasePackageList = filt.filter(self.mBasePackageList) if len(self.mBasePackageList) == 0: flagDBG().out(flagDBG.ERROR, "PkgAgent", "No viable packages for: %s" % self.mName) self.mViablePackageList = copy.deepcopy(self.mBasePackageList) if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mAgentDependList = [] # Agents that it depends on/needs to update self.makeDependList() self.mFiltersChanged = True def getName(self): return self.mName #Filter("Version", lambda x: x == "4.5") def makeDependList(self): dep_list = [] if self.mCurrentPackage: req_string = self.mCurrentPackage.getVariable("Requires") if DepResolutionSystem().checkPrivateRequires(): req_string = req_string + " " + self.mCurrentPackage.getVariable("Requires.private") req_string = req_string.strip() if req_string == "": return req_string = req_string.replace(',', ' ') req_string = req_string.replace('(', ' ') req_string = req_string.replace(')', ' ') space_req_string_list = req_string.split(' ') req_string_list = [] for entry in space_req_string_list: if len(entry) > 0: req_string_list.append(entry) i = 0 flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList", self.mCurrentPackage.getName() + " requires: " + str(req_string_list)) while len(req_string_list) > i: if PkgDB().exists(req_string_list[i]): new_filter = [] new_agent = DepResolutionSystem().createAgent(req_string_list[i]) if len(req_string_list) > i+1: if req_string_list[i+1] == "=": ver_to_filt = req_string_list[i+2] new_filter = Filter("Version", lambda x: x == ver_to_filt) elif req_string_list[i+1] == "<=": ver_to_filt = req_string_list[i+2] new_filter = Filter("Version", lambda x: x <= ver_to_filt) elif req_string_list[i+1] == ">=": ver_to_filt = req_string_list[i+2] new_filter = Filter("Version", lambda x: x >= ver_to_filt) else: i+=1 else: i+=1 dep_list.append(new_agent) if new_filter: i+=3 new_agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "PkgAgent.makeDependList", "Package %s depends on %s but is not seem to be installed." % (self.mName, str(req_string_list[i]))) flagDBG().out(flagDBG.VERBOSE, "PkgAgent.makeDependList", "List is:" + str([pkg.getName() for pkg in dep_list])) self.mAgentDependList = dep_list def filtersChanged(self,packageList): tf_list = [self.mFiltersChanged] if self.mName not in packageList: packageList.append(self.mName) for pkg in self.mAgentDependList: tf_list.append(pkg.filtersChanged(packageList)) return True in tf_list def getCurrentPackageList(self, packageList): pkgs = [] if self.mName not in packageList: flagDBG().out(flagDBG.VERBOSE, "PkgAgent.getCurrentPackageList", "Package: %s" % self.mName) pkgs.append(self.mCurrentPackage) packageList.append(self.mName) for pkg in self.mAgentDependList: pkgs.extend(pkg.getCurrentPackageList(packageList)) return pkgs # current pkginfo for me def getCurrentPkgInfo(self): return self.mCurrentPackage # Someone else usually places these on me # I keep track of those separately def addFilter(self, filter): flagDBG().out(flagDBG.VERBOSE, "PkgAgent.addFilter", "Adding a Filter to %s" % self.mName) self.mFiltersChanged = True self.mFilterList.append(filter) def removeCurrentPackage(self): flagDBG().out(flagDBG.VERBOSE, "PkgAgent.removeCurrentPackage", "Removing current package of %s" % self.mName) if self.mViablePackageList: ret_val = self.mViablePackageList[0] in self.mBasePackageList del self.mViablePackageList[0] if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] return ret_val def update(self, agentVisitedList, agentChangeList): if self.mName in agentVisitedList: return agentVisitedList.append(self.mName) if self.mFiltersChanged: self.mFiltersChanged = False self.updateFilters() # TODO: checkFilters and add them # if a pkg is in visitedList then add yourself to agentChangeList for pkg in self.mAgentDependList: pkg.update(agentVisitedList, agentChangeList) return def updateFilters(self): for filt in self.mFilterList: self.mViablePackageList = filt.filter(self.mViablePackageList) if len(self.mViablePackageList) > 0: self.mCurrentPackage = self.mViablePackageList[0] else: self.mCurrentPackage = [] def reset(self): flagDBG().out(flagDBG.VERBOSE, "PkgAgent.reset", "Resetting package: %s" % self.mName) self.mViablePackageList = self.mBasePackageList if self.mViablePackageList: self.mCurrentPacakge = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mFilterList = DepResolutionSystem().getFilters() self.mAgentDependList = [] self.mFiltersChanged = True return class Filter: """ A single Filter that knows how to filter the list it recieves Will be inheireted....?..? """ def __init__(self, variableName, testCallable): self.mVarName = variableName self.mTestCallable = testCallable def filter(self, pkg_info_list): ret_pkg_list = [] # Filter first for pkg in pkg_info_list: var = pkg.getVariable(self.mVarName) if self.mTestCallable(var): ret_pkg_list.append(pkg) # Now sort ret_pkg_list.sort(lambda lhs,rhs: cmp(lhs.getVariable(self.mVarName), rhs.getVariable(self.mVarName))) return ret_pkg_list #requires: qt == 4.5 #Filter("Version", lambda x: x <= "4.5") #Filter("Version", lambda x: x <= "4.5") class PkgDB(object): """ Holds all the neccesary information to evaluate itself when needed. Is in charge of holding a list of PkgInfo's that contain info about the package. """ __initialized = False def __init__(self): if self.__initialized: return self.__initialized = True self.mPkgInfos = {} # {pkg_name: List of package infos} self.populatePkgInfoDBPcFiles() self.populatePkgInfoDBFpcFiles() def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def getVariables(self, name, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariable", "Finding " + str(variable_list) + " in " + str(name)) ret_list = [] for var in variable_list: if self.mPkgInfos.has_key(name): ret_list.extend(self.mPkgInfos[name][0].getVariable(var)) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariable", "Package %s not found." % name) return ret_list def checkPackage(self, name): flagDBG().out(flagDBG.INFO, "PkgDB.checkPackage", "Finding " + str(name)) if self.mPkgInfos.has_key(name): return True else: flagDBG().out(flagDBG.ERROR, "PkgDB.CheckPackage", "Package %s not found." % name) return False def getVariablesAndDeps(self, pkg_list, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariablesAndDeps", "Finding " + str(variable_list) + " in " + str(pkg_list)) if DepResolutionSystem().checkPrivateRequires(): temp_var_list = [] for var in variable_list: temp_var_list.append(var.join(".private")) variable_list = variable_list + temp_var_list for name in pkg_list: if self.mPkgInfos.has_key(name): agent = DepResolutionSystem().createAgent(name) DepResolutionSystem().addResolveAgent(agent) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariablesAndDeps", "Package %s not found." % name) DepResolutionSystem().resolveDeps() pkgs = DepResolutionSystem().getPackages() var_list = [] for pkg in pkgs: if pkg: for var in variable_list: var_list.extend(pkg.getVariable(var).split(' ')) return var_list def getPkgInfos(self, name): if self.mPkgInfos.has_key(name): return self.mPkgInfos[name] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getPkgInfos", "Package %s not found." % name) def exists(self, name): return self.mPkgInfos.has_key(name) def getInfo(self, name): if self.mPkgInfos.has_key(name): return [pkg.getInfo() for pkg in self.mPkgInfos[name]] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getInfo", "Package %s not found." % name) def buildPcFileDict(self): """ Builds up a dictionary of {name: list of files for name} """ pc_dict = {} for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.pc")) # List of .pc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these pc files: %s" % str(glob_list)) for g in glob_list: # Get key name and add file to value list in dictionary key = os.path.basename(g)[:-3] # Strip .pc off the filename...rstrip no worky pc_dict.setdefault(key,[]).append(g) for f in Utils.getFileList(): if f.endswith(".pc"): key = os.path.basename(f)[:-3] # Strip .pc off the filename...rstrip no worky pc_dict.setdefault(key,[]).append(f) return pc_dict # { "key", [ "list", "of", "corresponding", "pc", "files"] } def populatePkgInfoDBPcFiles(self): dict_to_pop_from = self.buildPcFileDict() for (pkg,files) in dict_to_pop_from.iteritems(): for f in files: self.mPkgInfos.setdefault(pkg,[]).append(PkgInfo(pkg, f, "pc")) def buildFpcFileList(self): """ Builds up a dictionary of {name: list of files for name} """ file_list = [] for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.fpc")) # List of .fpc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these fpc files: %s" % str(glob_list)) for g in glob_list: file_list.append(g) for f in Utils.getFileList(): if f.endswith(".fpc"): file_list.append(f) return file_list # [ "list", "of", "fpc", "files"] def populatePkgInfoDBFpcFiles(self): list_to_add = self.buildFpcFileList() for filename in list_to_add: var_dict = Utils.parsePcFile(filename) if not var_dict.has_key("Provides"): flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Provides" % str(filename)) continue if not var_dict.has_key("Arch"): flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Arch" % str(filename)) continue provides_string = var_dict["Provides"] provides_string = provides_string.replace(',', ' ') provides_string = provides_string.replace('(', ' ') provides_string = provides_string.replace(')', ' ') for key in provides_string.split(" "): if len(key) > 0: self.mPkgInfos.setdefault(key,[]).append(PkgInfo(key, filename, "fpc", var_dict)) class PkgInfo: """ Holds the information for a package file on the system. These however are evaluated when the need arises. """ def __init__(self, name, file, type, varDict={}): self.mName = name self.mFile = file self.mIsEvaluated = False self.mType = type self.mVariableDict = varDict if self.mType == "fpc": self.mIsEvaluated = True def getVariable(self, variable): self.evaluate() return self.mVariableDict.get(variable,"") def getName(self): return self.mName def evaluate(self): if not self.mIsEvaluated: flagDBG().out(flagDBG.INFO, "PkgInfo.evaluate", "Evaluating %s" % self.mName) self.mVariableDict= Utils.parsePcFile(self.mFile) self.mIsEvaluated = True def getInfo(self): self.evaluate() return self.mVariableDict class OptionsEvaluator: def __init__(self): #self.mOptParser = self.GetOptionParser() #self.mOptParser.print_help() if sys.argv < 1: self.printHelp() #(self.mOptions, self.mArgs) = self.mOptParser.parse_args() #if self.mOptions.version: # print "%s.%s.%s" % Utils.getFlagpollVersion() # sys.exit(0) #if len(self.mArgs) < 1: # self.mOptParser.print_help() # sys.exit(1) # This is only the args....(first arg is stripped) def evaluateArgs(self, args): # Catch any args that need to be tended to immediately # Process args in the order that they were recieved. Some options are not # shown below because they are sub-options of an option below (--strip-dups) for option in args: if option.startswith("--debug"): flagDBG().setLevel(flagDBG.VERBOSE) elif option.startswith("--from-file"): val_start = option.find('=') + 1 file = option[val_start:] Utils.EXTRA_FLAGPOLL_FILES = Utils.EXTRA_FLAGPOLL_FILES + ":" + file elif option.startswith("--help"): self.printHelp() sys.exit(0) elif option.startswith("--version"): print "%s.%s.%s" % Utils.getFlagpollVersion() sys.exit(0) agent = None num_args = len(args) curr_arg = 0 output_options = [] # (option, name/"") important_options = [] # ones that need special attention while curr_arg < num_args: if args[curr_arg].startswith("--atleast-version"): val_start = args[curr_arg].find('=') + 1 atleast_version = args[curr_arg][val_start:] atleast_filter = Filter("Version", lambda x: x >= atleast_version) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(atleast_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue if args[curr_arg].startswith("--cflags-only-I"): output_options.append(("cflags-only-I", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--cflags-only-other"): output_options.append(("cflags-only-other", "")) curr_arg = curr_arg + 1 continue #This could be the catch all for the above ones to and then filter based on what is asked... #For clarity of course... if args[curr_arg].startswith("--cflags"): output_options.append(("cflags", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--extra-paths"): val_start = args[curr_arg].find('=') + 1 paths = args[curr_arg][val_start:] Utils.EXTRA_FLAGPOLL_SEARCH_PATHS = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS + ":" + paths curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--exact-version"): val_start = args[curr_arg].find('=') + 1 exact_version = args[curr_arg][val_start:] exact_filter = Filter("Version", lambda x: x == exact_version) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(exact_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue if args[curr_arg].startswith("--exists"): important_options.append("exists") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--from-file"): val_start = args[curr_arg].find('=') + 1 file = args[curr_arg][val_start:] file_filter = Filter("XXFlagpollFilenameXX", lambda x: x == file) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(file_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue if args[curr_arg].startswith("--info"): output_options.append(("info", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-l"): output_options.append(("libs-only-l", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-L"): output_options.append(("libs-only-L", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-other"): output_options.append(("libs-only-other", "")) curr_arg = curr_arg + 1 continue #This could be the catch all for the above ones to and then filter based on what is asked... if args[curr_arg].startswith("--libs"): output_options.append(("libs", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--list-all"): curr_arg = curr_arg + 1 PkgDB().printAllPackages() continue if args[curr_arg].startswith("--require-all"): rlen = len("--require-all") req_string = args[curr_arg][rlen:] req_string = req_string.replace('-','_') curr_arg = curr_arg + 1 if req_string.find("<=") != -1: op_start = req_string.find("<=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x: x <= req_val) DepResolutionSystem().addFilter(new_filter) continue if req_string.find(">=") != -1: op_start = req_string.find(">=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x: x >= req_val) DepResolutionSystem().addFilter(new_filter) continue if req_string.find(">") != -1: op_start = req_string.find(">") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x > req_val) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("<") != -1: op_start = req_string.find("<") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x < req_val) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("=") != -1: op_start = req_string.find("=") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x == req_val) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("=") == -1: new_filter = Filter(req_string, lambda x: len(x) > 0) DepResolutionSystem().addFilter(new_filter) continue continue if args[curr_arg].startswith("--require-"): rlen = len("--require-") req_string = args[curr_arg][rlen:] req_string = req_string.replace('-','_') curr_arg = curr_arg + 1 if req_string.find("<=") != -1: op_start = req_string.find("<=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x: x <= req_val) if agent is not None: agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue if req_string.find(">=") != -1: op_start = req_string.find(">=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x: x >= req_val) if agent is not None: agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue if req_string.find(">") != -1: op_start = req_string.find(">") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x > req_val) if agent is not None: agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue if req_string.find("<") != -1: op_start = req_string.find("<") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x < req_val) if agent is not None: agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue if req_string.find("=") != -1: op_start = req_string.find("=") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x == req_val) if agent is not None: agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue if req_string.find("=") == -1: new_filter = Filter(req_string, lambda x: len(x) > 0) if agent is not None: agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue continue if args[curr_arg].startswith("--require="): val_start = args[curr_arg].find('=') + 1 req_var = args[curr_arg][val_start:] curr_arg = curr_arg + 1 DepResolutionSystem().makeRequireFilter(req_var) continue if args[curr_arg].startswith("--modversion"): if agent is not None: output_options.append(("Version", agent.getName())) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--exact-version"): val_start = args[curr_arg].find('=') + 1 exact_version = args[curr_arg][val_start:] exact_filter = Filter("Version", lambda x: x == exact_version) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(exact_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue if args[curr_arg].startswith("--max-release"): val_start = args[curr_arg].find('=') + 1 max_release = args[curr_arg][val_start:] max_filter = Filter("Version", lambda x: x.startswith(max_release)) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(max_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified") continue if args[curr_arg].startswith("--static"): DepResolutionSystem().setPrivateRequires(True) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--variable"): val_start = args[curr_arg].find('=') + 1 fetch_var = args[curr_arg][val_start:] if agent is not None: output_options.append((fetch_var, agent.getName())) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--get-all"): rlen = len("--get-all-") get_string = args[curr_arg][rlen:] get_string = get_string.replace('-','_') output_options.append((get_string, "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--get"): rlen = len("--get-") get_string = args[curr_arg][rlen:] get_string = get_string.replace('-','_') if agent is not None: output_options.append((get_string, agent.getName())) curr_arg = curr_arg + 1 continue if not args[curr_arg].startswith("--"): name = args[curr_arg] curr_arg = curr_arg + 1 if PkgDB().checkPackage(name): agent = DepResolutionSystem().createResolveAgent(name) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Package %s" % name) sys.exit(1) continue #flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Option: %s" % args[curr_arg]) curr_arg = curr_arg + 1 DepResolutionSystem().resolveDeps() pkgs = DepResolutionSystem().getPackages() for p in pkgs: if not p: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found") if len(pkgs) == 0: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found") sys.exit(1) for option in important_options: if option == "exists": return sys.exit(0) # already checked for none above #print output_options #output_options = [] #output_single = [] #Process options here.............. for option in output_options: if option[0] == "cflags": Utils.printList(Utils.stripDupIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "cflags-only-I": Utils.printList(Utils.cflagsOnlyDirIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "cflags-only-other": Utils.printList(Utils.cflagsOnlyOtherIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "libs-only-l": Utils.printList(Utils.libsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs-only-L": Utils.printList(Utils.libDirsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs-only-other": Utils.printList(Utils.libsOnlyOtherLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs": Utils.printList(Utils.stripDupLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) else: Utils.printList(Utils.stripDupInList(self.getVarFromPkgs(option[0], pkgs, option[1]))) def getVarFromPkgs(self, var, pkgs, pkg_name=""): var_list = [] ext_vars = [] if var == "Libs": if DepResolutionSystem().checkPrivateRequires: ext_vars.append("Libs.private") if pkg_name == "": for pkg in pkgs: if pkg: var_list.extend(pkg.getVariable(var).split(' ')) for extra_var in ext_vars: var_list.extend(pkg.getVariable(extra_var).split(' ')) else: for pkg in pkgs: if pkg: if pkg.getName() == pkg_name: var_list.extend(pkg.getVariable(var).split(' ')) for extra_var in ext_vars: var_list.extend(pkg.getVariable(extra_var).split(' ')) return var_list def printHelp(self): print "usage: flagpoll pkg options [pkg options] [generic options]" print " " print "generic options:" print " --help show this help message and exit" print " --version output version of flagpoll" print " --list-all list all known packages" print " --debug show verbose debug information" print " --extra-paths=EXTRA_PATHS" print " extra paths for flagpoll to search for meta-data files" print " " print "options:" print " --modversion output version for package" print " --require=REQUIRE adds additional requirements for packages ex. 32/64" print " --libs output all linker flags" print " --static output linker flags for static linking" print " --libs-only-l output -l flags" print " --libs-only-other output other libs (e.g. -pthread)" print " --libs-only-L output -L flags" print " --cflags output all pre-processor and compiler flags" print " --cflags-only-I output -I flags" print " --cflags-only-other output cflags not covered by the cflags-only-I option" print " --exists return 0 if the module(s) exist" print " --from-file=FILE use the specified FILE for the package" print " --info show information for packages" print " --print-provides print which packages the package provides" print " --print-requires print which packages the package requires" print " --atleast-version=ATLEAST_VERSION" print " return 0 if the module is at least version" print " ATLEAST_VERSION" print " --exact-version=EXACT_VERSION" print " return 0 if the module is exactly version" print " EXACT_VERSION" print " --max-release=MAX_RELEASE" print " return 0 if the module has a release that has a" print " version of MAX_RELEASE and will return the max" print " --variable=VARIABLE get the value of a variable" print " " print "dynamic options(replace VAR with a variable you want to get/filter on)" print " NOTE: replace underscores with dashes in VAR" print " NOTE: quotes are needed around <,>,= combinations" print " --get-VAR get VAR from package" print " --get-all-VAR get VAR from package and its deps" print " --require-VAR[<,>,=VAL]" print " require that a var is defined for a package" print " or optionally use equality operators against VAL" print " --require-all-VAR[<,>,=VAL]" print " require that a var is defined for all packages" print " or optionally use equality operators against VAL" def main(): # GO! # Initialize singletons and the start evaluating #print sys.argv[1:] my_dbg = flagDBG() my_dep_system = DepResolutionSystem() opt_evaluator = OptionsEvaluator() opt_evaluator.evaluateArgs(sys.argv[1:]) sys.exit(0) if __name__ == "__main__": main()
Python
#!/usr/bin/env python # ----------------------------------------------------------------- # # Flag Poll: A tool to extract flags from installed applications # for compiling, settting variables, etc. # # Original Authors: # Daniel E. Shipton <dshipton@gmail.com> # # Flag Poll is Copyright (C) 2006 by Daniel E. Shipton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to: # Free SoftwareFoundation, Inc. # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # # ----------------------------------------------------------------- """Makes a flagpole .fpc file from user input. v0.9 coded by Jeff Groves""" import os import sys import getopt ##String prompts for the input varPrompt = """Convience variables (one 'var_name= var_definition' per line,""" + \ """ empty line when done)""" namePrompt = "Formal Name" descriptionPrompt = "Description" urlPrompt = "URL" providesPrompt = "One or more names to look package up by: (Provides)" versionPrompt = "Version (x.y.z)" architecturePrompt = "Architecture" requirePrompt = "Requires" libPrompt = "Linker Flags (-lfoo -L/usr/lib)" staticLibPrompt = "Static Linking Flags/Libs (extra private libs)" compileFlagsPrompt = "Compile/Include Flags (-I/usr -fpge -O2)" fileNamePrompt = "FPC File's Name" def usage(): """Prints a list of acceptable arguments for fpcmaker.py.""" print """ Fpcmaker.py Options: -n, --name= : Sets %s -d, --description= : Sets %s -u, --url= : Sets %s -p, --provides= : Sets %s -v, --version= : Sets %s -a, --architecture= : Sets %s -r, --requires= : Sets %s -l, --libs= : Sets %s -c, --cflags= : Sets %s -s, --static= : Sets %s -f, --file= : Sets %s """ %(namePrompt, descriptionPrompt, urlPrompt, providesPrompt, versionPrompt, architecturePrompt, requirePrompt, libPrompt, compileFlagsPrompt, staticLibPrompt, fileNamePrompt) return def checkFileName(fileName): """Checks if the fpc file name's blank, contains slashes, or exists.""" nameCleared = False writeFile = True confirms = ['y', 'Y', 'yes', 'Yes'] ##Loops until the name clears or writing the file's aborted. while(not nameCleared and writeFile): ##If it's blank, give the option of aborting the program. if fileName == "": choice = raw_input("Do you want to abort writing the" + " .fpc file? (Y/N): ") if choice not in confirms: fileName = raw_input("Please enter a different name for the" + " .fpc file: ") else: writeFile = False ##If it contains slashes, ask for another name. elif '/' in fileName or '\\' in fileName: print "I can't write to %s because it contains slashes."%(fileName) fileName = raw_input("Please enter a different name for the" + " .fpc file: ") ##If it already exists, ask if they want to overwrite. ##If not, ask for another name. elif os.path.exists(fileName): choice = raw_input("The file %s already exists." %(fileName) + " Do you want to overwrite it? (Y/N): ") if choice not in confirms: fileName = raw_input("Please enter a different name for the" + " .fpc file: ") else: nameCleared = True else: nameCleared = True return [fileName, writeFile] ##Booleans for whether that argument was sent in the command line varSet = False providesSet = False nameSet = False descriptionSet = False urlSet = False architectureSet = False versionSet = False requiresSet = False libsSet = False compileFlagsSet = False staticLibSet = False fileNameSet = False ##Get the options & arguments sent. arguments = sys.argv[1:] try: opts, args = getopt.getopt(arguments, "p:n:u:d:a:r:v:l:c:s:f:", ["provides=", "name=", "url=", "description=", "architecture=", "requires=", "version=", "libs=", "cflags=", "static=", "file="]) ##Send them usage info if they enter a wrong argument except getopt.GetoptError: usage() sys.exit(2) for opt, arg in opts: if opt in ('-p', '--provides'): providesSet = True provides = arg elif opt in ('-n', '--name'): nameSet = True name = arg elif opt in ('-v', '--version'): versionSet = True version = arg elif opt in ('-u', '--url'): urlSet = True url = arg elif opt in ('-d', '--description'): descriptionSet = True description = arg elif opt in ('-a', '--architecture'): architectureSet = True architecture = arg elif opt in ('-r', '--requires'): requiresSet = True requires = arg elif opt in ('-l', '--libs'): libsSet = True libs = arg elif opt in ('-c', '--cflags'): compileFlagsSet = True compileFlags = arg elif opt in ('-s', '--static'): staticLibSet = True staticLib = arg elif opt in ('-f', '--file'): fileNameSet = True fileName = arg ##Grab any input not passed in the arguments from the user. if not varSet: varLine = None variables = "" print "%s:" %(varPrompt) while(varLine != ""): varLine = raw_input("") variables = variables + "%s\n" %(varLine) if not nameSet: name = raw_input("%s: " %(namePrompt)) if not descriptionSet: description = raw_input("%s: " %(descriptionPrompt)) if not urlSet: url = raw_input("%s: " %(urlPrompt)) if not versionSet: version = raw_input("%s: " %(versionPrompt)) if not providesSet: provides = raw_input("%s: " %(providesPrompt)) if not requiresSet: requires = raw_input("%s: " %(requirePrompt)) if not architectureSet: architecture = raw_input("%s: " %(architecturePrompt)) if not libsSet: libs = raw_input("%s: " %(libPrompt)) if not staticLibSet: staticLib = raw_input("%s: " %(staticLibPrompt)) if not compileFlagsSet: compileFlags = raw_input("%s: " %(compileFlagsPrompt)) if not fileNameSet: fileName = raw_input("%s: " %(fileNamePrompt)) ##Check the file's name. fileName, writeFile = checkFileName(fileName) ##If they chose not to overwrite, write the file. if writeFile: fpc = open(fileName, 'w') fpc.write("%s" %(variables)) fpc.write("Name: %s\n" %(name)) fpc.write("Description: %s\n" %(description)) fpc.write("URL: %s\n" %(url)) fpc.write("Version: %s\n" %(version)) fpc.write("Provides: %s\n" %(provides)) fpc.write("Requires: %s\n" %(requires)) fpc.write("Arch: %s\n" %(architecture)) fpc.write("Libs: %s\n" %(libs)) fpc.write("Libs.private: %s\n" %(staticLib)) fpc.write("Cflags: %s\n" %(compileFlags)) fpc.close() ##TESTER: Print the file out. fpc = open(fileName, 'r') ##TESTER print fpc.read() ##TESTER fpc.close ##TESTER
Python
#!/usr/bin/env python from distutils.core import setup try: import py2exe except: pass setup( name='flagpoll', version='0.9.1', description='Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software.', author='Daniel E. Shipton', author_email='dshipton@infiscape.com', license='GPL', url='https://realityforge.vrsource.org/view/FlagPoll/WebHome', download_url='https://realityforge.vrsource.org/view/FlagPoll/FlagpollDownloads', console=['flagpoll'], scripts=['flagpoll'], long_description = "Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software. Think of it as the rpm of software development. It enables developers total control over which packages, versions, architectures, etc. that they want to use meta-data from.", data_files=[('share/flagpoll', ['flagpoll.fpc']), ('share/man/man1', ['flagpoll.1']), ('share/aclocal', ['flagpoll.m4']), ('share/html', ['flagpoll-manual.html'])] )
Python
#!/usr/bin/env python # ----------------------------------------------------------------- # # Flag Poll: A tool to extract flags from installed applications # for compiling, settting variables, etc. # # Original Authors: # Daniel E. Shipton <dshipton@gmail.com> # # Flag Poll is Copyright (C) 2006 by Daniel E. Shipton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to: # Free SoftwareFoundation, Inc. # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # # ----------------------------------------------------------------- """Makes a flagpole .fpc file from user input. v0.9 coded by Jeff Groves""" import os import sys import getopt ##String prompts for the input varPrompt = """Convience variables (one 'var_name= var_definition' per line,""" + \ """ empty line when done)""" namePrompt = "Formal Name" descriptionPrompt = "Description" urlPrompt = "URL" providesPrompt = "One or more names to look package up by: (Provides)" versionPrompt = "Version (x.y.z)" architecturePrompt = "Architecture" requirePrompt = "Requires" libPrompt = "Linker Flags (-lfoo -L/usr/lib)" staticLibPrompt = "Static Linking Flags/Libs (extra private libs)" compileFlagsPrompt = "Compile/Include Flags (-I/usr -fpge -O2)" fileNamePrompt = "FPC File's Name" def usage(): """Prints a list of acceptable arguments for fpcmaker.py.""" print """ Fpcmaker.py Options: -n, --name= : Sets %s -d, --description= : Sets %s -u, --url= : Sets %s -p, --provides= : Sets %s -v, --version= : Sets %s -a, --architecture= : Sets %s -r, --requires= : Sets %s -l, --libs= : Sets %s -c, --cflags= : Sets %s -s, --static= : Sets %s -f, --file= : Sets %s """ %(namePrompt, descriptionPrompt, urlPrompt, providesPrompt, versionPrompt, architecturePrompt, requirePrompt, libPrompt, compileFlagsPrompt, staticLibPrompt, fileNamePrompt) return def checkFileName(fileName): """Checks if the fpc file name's blank, contains slashes, or exists.""" nameCleared = False writeFile = True confirms = ['y', 'Y', 'yes', 'Yes'] ##Loops until the name clears or writing the file's aborted. while(not nameCleared and writeFile): ##If it's blank, give the option of aborting the program. if fileName == "": choice = raw_input("Do you want to abort writing the" + " .fpc file? (Y/N): ") if choice not in confirms: fileName = raw_input("Please enter a different name for the" + " .fpc file: ") else: writeFile = False ##If it contains slashes, ask for another name. elif '/' in fileName or '\\' in fileName: print "I can't write to %s because it contains slashes."%(fileName) fileName = raw_input("Please enter a different name for the" + " .fpc file: ") ##If it already exists, ask if they want to overwrite. ##If not, ask for another name. elif os.path.exists(fileName): choice = raw_input("The file %s already exists." %(fileName) + " Do you want to overwrite it? (Y/N): ") if choice not in confirms: fileName = raw_input("Please enter a different name for the" + " .fpc file: ") else: nameCleared = True else: nameCleared = True return [fileName, writeFile] ##Booleans for whether that argument was sent in the command line varSet = False providesSet = False nameSet = False descriptionSet = False urlSet = False architectureSet = False versionSet = False requiresSet = False libsSet = False compileFlagsSet = False staticLibSet = False fileNameSet = False ##Get the options & arguments sent. arguments = sys.argv[1:] try: opts, args = getopt.getopt(arguments, "p:n:u:d:a:r:v:l:c:s:f:", ["provides=", "name=", "url=", "description=", "architecture=", "requires=", "version=", "libs=", "cflags=", "static=", "file="]) ##Send them usage info if they enter a wrong argument except getopt.GetoptError: usage() sys.exit(2) for opt, arg in opts: if opt in ('-p', '--provides'): providesSet = True provides = arg elif opt in ('-n', '--name'): nameSet = True name = arg elif opt in ('-v', '--version'): versionSet = True version = arg elif opt in ('-u', '--url'): urlSet = True url = arg elif opt in ('-d', '--description'): descriptionSet = True description = arg elif opt in ('-a', '--architecture'): architectureSet = True architecture = arg elif opt in ('-r', '--requires'): requiresSet = True requires = arg elif opt in ('-l', '--libs'): libsSet = True libs = arg elif opt in ('-c', '--cflags'): compileFlagsSet = True compileFlags = arg elif opt in ('-s', '--static'): staticLibSet = True staticLib = arg elif opt in ('-f', '--file'): fileNameSet = True fileName = arg ##Grab any input not passed in the arguments from the user. if not varSet: varLine = None variables = "" print "%s:" %(varPrompt) while(varLine != ""): varLine = raw_input("") variables = variables + "%s\n" %(varLine) if not nameSet: name = raw_input("%s: " %(namePrompt)) if not descriptionSet: description = raw_input("%s: " %(descriptionPrompt)) if not urlSet: url = raw_input("%s: " %(urlPrompt)) if not versionSet: version = raw_input("%s: " %(versionPrompt)) if not providesSet: provides = raw_input("%s: " %(providesPrompt)) if not requiresSet: requires = raw_input("%s: " %(requirePrompt)) if not architectureSet: architecture = raw_input("%s: " %(architecturePrompt)) if not libsSet: libs = raw_input("%s: " %(libPrompt)) if not staticLibSet: staticLib = raw_input("%s: " %(staticLibPrompt)) if not compileFlagsSet: compileFlags = raw_input("%s: " %(compileFlagsPrompt)) if not fileNameSet: fileName = raw_input("%s: " %(fileNamePrompt)) ##Check the file's name. fileName, writeFile = checkFileName(fileName) ##If they chose not to overwrite, write the file. if writeFile: fpc = open(fileName, 'w') fpc.write("%s" %(variables)) fpc.write("Name: %s\n" %(name)) fpc.write("Description: %s\n" %(description)) fpc.write("URL: %s\n" %(url)) fpc.write("Version: %s\n" %(version)) fpc.write("Provides: %s\n" %(provides)) fpc.write("Requires: %s\n" %(requires)) fpc.write("Arch: %s\n" %(architecture)) fpc.write("Libs: %s\n" %(libs)) fpc.write("Libs.private: %s\n" %(staticLib)) fpc.write("Cflags: %s\n" %(compileFlags)) fpc.close() ##TESTER: Print the file out. fpc = open(fileName, 'r') ##TESTER print fpc.read() ##TESTER fpc.close ##TESTER
Python
#!/usr/bin/env python # ----------------------------------------------------------------- # # Flagpoll: A tool to extract flags from installed applications # for compiling, settting variables, etc. # # Original Authors: # Daniel E. Shipton <dshipton@gmail.com> # # Flagpoll is Copyright (C) 2006-2007 by Daniel E. Shipton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to: # Free SoftwareFoundation, Inc. # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # # ----------------------------------------------------------------- import sys, os, glob, os.path, copy, platform pj = os.path.join #################################################################### # SNAGGED FROM PYTHON 2.4 for versions under 2.4 #################################################################### import re as _re class _multimap: """Helper class for combining multiple mappings. Used by .{safe_,}substitute() to combine the mapping and keyword arguments. """ def __init__(self, primary, secondary): self._primary = primary self._secondary = secondary def __getitem__(self, key): try: return self._primary[key] except KeyError: return self._secondary[key] class _TemplateMetaclass(type): pattern = r""" %(delim)s(?: (?P<escaped>%(delim)s) | # Escape sequence of two delimiters (?P<named>%(id)s) | # delimiter and a Python identifier {(?P<braced>%(id)s)} | # delimiter and a braced identifier (?P<invalid>) # Other ill-formed delimiter exprs ) """ def __init__(cls, name, bases, dct): super(_TemplateMetaclass, cls).__init__(name, bases, dct) if 'pattern' in dct: pattern = cls.pattern else: pattern = _TemplateMetaclass.pattern % { 'delim' : _re.escape(cls.delimiter), 'id' : cls.idpattern, } cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE) class Template: """A string class for supporting $-substitutions.""" __metaclass__ = _TemplateMetaclass delimiter = '$' idpattern = r'[_a-z][_a-z0-9]*' def __init__(self, template): self.template = template # Search for $$, $identifier, ${identifier}, and any bare $'s def _invalid(self, mo): i = mo.start('invalid') lines = self.template[:i].splitlines(True) if not lines: colno = 1 lineno = 1 else: colno = i - len(''.join(lines[:-1])) lineno = len(lines) raise ValueError('Invalid placeholder in string: line %d, col %d' % (lineno, colno)) def substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): # Check the most common path first. named = mo.group('named') or mo.group('braced') if named is not None: val = mapping[named] # We use this idiom instead of str() because the latter will # fail if val is a Unicode containing non-ASCII characters. return '%s' % val if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: self._invalid(mo) raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) def safe_substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): named = mo.group('named') if named is not None: try: # We use this idiom instead of str() because the latter # will fail if val is a Unicode containing non-ASCII return '%s' % mapping[named] except KeyError: return self.delimiter + named braced = mo.group('braced') if braced is not None: try: return '%s' % mapping[braced] except KeyError: return self.delimiter + '{' + braced + '}' if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: return self.delimiter raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) #################################################################### # End Snagging #################################################################### def tokenize(val, split_char): val = val.strip() results = [] while len(val) > 0: sn = val.find(split_char) qn = val.find('"') #print " -> val: %s Len: %s" % (val, len(val)) # If we find a quote first, then find the space after the next quote. if qn < sn: #print " -> Found a quote first:", qn # Find next quote. qn2 = val.find('"', qn+1) #print " -> Found second quote:", qn2 sn = val.find(split_char, qn2+1) #print " -> Found next space:", sn if sn < 0: results.append(val[:]) val = "" else: results.append(val[:sn]) val = val[sn:] val = val.strip() return results class Utils: # Holds collection of small utility functions EXTRA_FLAGPOLL_SEARCH_PATHS = "" EXTRA_FLAGPOLL_FILES = "" path_list_cache = None # Cache of found path lists. (only calcuate once) KEEP_DUPS = False FLAGPOLL_LIST_OF_POSSIBLE_ERRORS = [] def addPossibleError(pos_err): Utils.FLAGPOLL_LIST_OF_POSSIBLE_ERRORS.append(pos_err) addPossibleError = staticmethod(addPossibleError) def getPossibleErrors(): return Utils.stripDupInList(Utils.FLAGPOLL_LIST_OF_POSSIBLE_ERRORS) getPossibleErrors = staticmethod(getPossibleErrors) def getFlagpollVersion(): FLAGPOLL_MAJOR_VERSION = 0 FLAGPOLL_MINOR_VERSION = 9 FLAGPOLL_PATCH_VERSION = 1 return ( FLAGPOLL_MAJOR_VERSION, FLAGPOLL_MINOR_VERSION, FLAGPOLL_PATCH_VERSION ) getFlagpollVersion = staticmethod(getFlagpollVersion) def getPathList(): if None != Utils.path_list_cache: return Utils.path_list_cache #TODO: expand LD_LIBRARY_PATH to 64/32/etc??? pkg_cfg_dir = [] flg_cfg_dir = [] ld_path = [] if os.environ.has_key("PKG_CONFIG_PATH"): pkg_cfg_dir = os.environ["PKG_CONFIG_PATH"].split(os.pathsep) if os.environ.has_key("FLAGPOLL_PATH"): flg_cfg_dir = os.environ["FLAGPOLL_PATH"].split(os.pathsep) ld_dirs = ['LD_LIBRARY_PATH', 'DYLD_LIBRARY_PATH', 'PATH'] for d in ld_dirs: if os.environ.has_key(d): cur_path = os.environ[d].split(os.pathsep) ld_path_pkg = [pj(p,'pkgconfig') for p in cur_path] ld_path_flg = [pj(p,'flagpoll') for p in cur_path] ld_path.extend(ld_path_pkg) ld_path.extend(ld_path_flg) extra_paths = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS.split(os.pathsep) path_list = extra_paths path_list.extend(flg_cfg_dir) path_list.extend(pkg_cfg_dir) path_list.extend(ld_path) default_path_list = [pj('/','usr','lib64'), pj('/','usr','lib32'), pj('/','usr','lib'), pj('/','usr','share')] default_path_pkg = [pj(p,'pkgconfig') for p in default_path_list] default_path_flg = [pj(p,'flagpoll') for p in default_path_list] path_list.extend(default_path_pkg) path_list.extend(default_path_flg) flagDBG().out(flagDBG.VERBOSE, "Utils.getPathList", "Potential path list: " + str(path_list)) clean_path_list = [] for p in path_list: if os.path.exists(p) and os.path.isdir(p) and not p in clean_path_list: clean_path_list.append(p) path_list = clean_path_list flagDBG().out(flagDBG.INFO, "Utils.getPathList", "Using path list: " + str(path_list)) Utils.path_list_cache = path_list return path_list getPathList = staticmethod(getPathList) def getFileList(): flist = Utils.EXTRA_FLAGPOLL_FILES.split(":") filelist = [] for f in flist: if os.path.isfile(f): filelist.append(f) return filelist getFileList = staticmethod(getFileList) def setKeepDups(keep_dups): Utils.KEEP_DUPS = keep_dups setKeepDups = staticmethod(setKeepDups) def stripDupInList(gen_list): new_list = [] list_len = len(gen_list) i = 0 while i < list_len: item = gen_list[i].strip() if Utils.KEEP_DUPS: if len(item) > 0: new_list.append(item) continue if item in ('-framework', '-arch', '-isysroot'): item = '%s %s' % (item, gen_list[i + 1]) i += 1 if item not in new_list: if len(item) > 0: new_list.append(item) i += 1 return new_list stripDupInList = staticmethod(stripDupInList) def stripDupLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] dir_list = [] list_len = len(flag_list) i = 0 vc_linker_flag_re = _re.compile(r'^[/-]libpath:', _re.I) other_linker_flag_re = _re.compile(r'^-[LRF]') while i < list_len: flg = flag_list[i].strip() if len(flg) > 0: if (other_linker_flag_re.match(flg) is not None\ or vc_linker_flag_re.match(flg) is not None): dir_list.append(flg) else: if flg in ("-framework", "-arch", "-isysroot"): flg = "%s %s" % (flg, flag_list[i + 1]) i += 1 lib_list.append(flg) i += 1 new_list = dir_list + lib_list return Utils.stripDupInList(new_list) stripDupLinkerFlags = staticmethod(stripDupLinkerFlags) def stripDupIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] extra_list = [] list_len = len(flag_list) i = 0 while i < list_len: flg = flag_list[i].strip() if len(flg) > 0: if flg.startswith("-I") or flg.startswith("/I"): inc_list.append(flg) elif flg in ("-arch", "-isysroot"): extra_list.append("%s %s" % (flg, flag_list[i + 1])) i += 1 else: extra_list.append(flg) i += 1 extra_list.sort() new_list = inc_list + extra_list return Utils.stripDupInList(new_list) stripDupIncludeFlags = staticmethod(stripDupIncludeFlags) def cflagsOnlyDirIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-I") or flg.startswith("/I"): inc_list.append(flg) return Utils.stripDupInList(inc_list) cflagsOnlyDirIncludeFlags = staticmethod(cflagsOnlyDirIncludeFlags) def cflagsOnlyOtherIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though extra_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if not flg.startswith("-I") and not flg.startswith("/I"): extra_list.append(flg) return Utils.stripDupInList(extra_list) cflagsOnlyOtherIncludeFlags = staticmethod(cflagsOnlyOtherIncludeFlags) def libsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-l") or flg.endswith(".lib"): lib_list.append(flg) return Utils.stripDupInList(lib_list) libsOnlyLinkerFlags = staticmethod(libsOnlyLinkerFlags) def libsOnlyOtherLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though other_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: upper_flg = flg.upper() if not flg.startswith("-l") \ and not flg.startswith("-L")\ and not flg.startswith("-R")\ and not upper_flg.startswith("/LIBPATH")\ and not upper_flg.startswith("-LIBPATH")\ and not flg.endswith(".lib"): other_list.append(flg) return Utils.stripDupInList(other_list) libsOnlyOtherLinkerFlags = staticmethod(libsOnlyOtherLinkerFlags) def libDirsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though dir_list = [] vc_linker_flag_re = _re.compile(r'^[/-]libpath:', _re.I) other_linker_flag_re = _re.compile(r'^-[LRF]') for flg in flag_list: flg = flg.strip() if len(flg) > 0: if (other_linker_flag_re.match(flg) is not None or vc_linker_flag_re.match(flg) is not None): dir_list.append(flg) return Utils.stripDupInList(dir_list) libDirsOnlyLinkerFlags = staticmethod(libDirsOnlyLinkerFlags) def printList(gen_list): list_string = "" for item in gen_list: if len(item) > 0: list_string += str(item) list_string += " " print list_string.strip() printList = staticmethod(printList) def parsePcFile(filename): lines = open(filename).readlines() fvars = {} fvars["FlagpollFilename"] = filename lokals = {} lokals["fp_file_cwd"] = str(filename[:- ((len(os.path.basename(filename) ) + 1))]) lines.append("prefix: ${prefix}") append_next = False append_dict = {} append_key = "" for line in lines: line = line.strip() if not line: continue if append_next: tmp = append_dict[append_key] tmp = tmp[:-1] + " " + line append_dict[append_key] = tmp if tmp[-1:] == "\\": append_next = True else: append_next = False continue if line.startswith("#"): continue eq_pos = line.find('=') col_pos = line.find(':') if eq_pos < col_pos and eq_pos != -1 or col_pos == -1 and eq_pos != -1: # local variable name, val = line.split('=', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(lokals) except ValueError: flagDBG().out(flagDBG.WARN, "PkgInfo.parse", "%s has an invalid metadata file" % filename) lokals[name] = val if val[-1:] == "\\": append_next = True append_dict = lokals append_key = name continue if col_pos < eq_pos and col_pos != -1 or eq_pos == -1 and col_pos != -1: # exported variable name, val = line.split(':', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(lokals) except ValueError: flagDBG().out(flagDBG.ERROR, "PkgInfo.parse", "%s has an invalid metadata file" % filename) fvars[name] = val if val[-1:] == "\\": append_next = True append_dict = fvars append_key = name return fvars parsePcFile = staticmethod(parsePcFile) class flagDBG(object): # Logging class is really easy to use # Levels: # 0 - VERBOSE # 1 - INFO # 2 - WARN # 3 - ERROR VERBOSE = 0 INFO = 1 WARN = 2 ERROR = 3 __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if flagDBG.__initialized: return flagDBG.__initialized = True self.mLevel = self.WARN self.mLevelList = ["VERBOSE", "INFO", "WARN", "ERROR"] def setLevel(self, level): if level <= 3: self.mLevel = level def out(self, level, obj, message): if level == self.ERROR: if self.mLevel == self.VERBOSE: print self.mLevelList[level] + ":" + str(obj) + ": " + str(message) else: sys.stderr.write(self.mLevelList[level] + ": " + str(message) + "\n") errs = Utils.getPossibleErrors() if len(errs) > 0: sys.stderr.write("Possible culprits:\n") for pos_err in errs: sys.stderr.write( " " + str(pos_err) + "\n" ) sys.exit(1) if level >= self.mLevel: print self.mLevelList[level] + ":" + str(obj) + ": " + str(message) class DepResolutionSystem(object): """ You add PkgAgents with Filters into system and call resolve() you can check for succes by depsSatisfied() and get the list of packages that work back by calling getPackages() """ __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if DepResolutionSystem.__initialized: return DepResolutionSystem.__initialized = True self.mResolveAgents = [] self.mAgentDict = {} self.mFilters = [] self.mResolveAgentFilters = [] self.mInvalidPackageList = [] self.mSatisfied = False self.mAgentChangeList = [] # list of those responsible for adding Filters # to agents in higher in the chain than them # these are the first agents to ask that they pick # the next best package of them self.mAgentsVisitedList = [] # list of Agents that have been visited self.mResolvedPackageList = [] # list that is generated when deps are satified self.mCheckPrivateRequires = False self.mMadeDependList = False def getFilters(self): return self.mFilters def addFilter(self, filter): self.mFilters.append(filter) def addResolveAgentFilter(self, filter): self.mResolveAgentFilters.append(filter) def makeRequireFilter(self, requires): arch_list = [] arch_list.append("no_arch") arch_list.append("") if platform.system() == "Linux": if requires == "64": arch_list.append("x86_64") arch_list.append("x64") if requires == "32": arch_list.append("i386") arch_list.append("i486") arch_list.append("i586") arch_list.append("i686") if platform.system() == "Darwin": if requires == "64": arch_list.append("ppc64") if requires == "32": arch_list.append("ppc") if platform.system().startswith("IRIX"): arch_list.append(requires) new_filter = Filter("Arch", lambda x,v=arch_list: x in v) self.addFilter(new_filter) def createAgent(self, name): if self.checkAgentExists(name): return self.getAgent(name) else: agent = PkgAgent(name) flagDBG().out(flagDBG.INFO, "DepResSys.createAgent", "Adding %s" % name) self.addNewAgent(agent) return agent def createResolveAgent(self, name): if self.checkAgentExists(name): return self.getAgent(name) else: agent = PkgAgent(name) flagDBG().out(flagDBG.INFO, "DepResSys.createResolveAgent", "Adding %s" % name) self.addResolveAgent(agent) return agent def setPrivateRequires( self, req ): self.mCheckPrivateRequires = req def checkPrivateRequires(self): return self.mCheckPrivateRequires def checkAgentExists(self, name): return self.mAgentDict.has_key(name) def getAgent(self, name): if self.mAgentDict.has_key(name): return self.mAgentDict[name] else: flagDBG().out(flagDBG.ERROR, "DepResSys.getAgent", "Agent %s does not exist" % name) def addNewAgent(self, agent): if not self.checkAgentExists(agent): self.mAgentDict[agent.getName()] = agent def addResolveAgent(self, agent): if agent not in self.mResolveAgents: self.mResolveAgents.append(agent) for filt in self.mResolveAgentFilters: agent.addFilter(filt) def isSatisfied(self): return self.mSatisfied def updateResolvedPackages(self): pkg_list = [] agent_list = [] for agent in self.mResolveAgents: list_of_pkgs = agent.getCurrentPackageList(agent_list) pkg_list.extend(list_of_pkgs) self.mResolvedPackageList = pkg_list def getPackages(self): flagDBG().out(flagDBG.INFO, "DepResSys.getPackages", "Generating list of valid packages ") #str([pkg.getCurrentPackage.getName() for pkg in self.mResolvedPackageList])) # If this comes back empty then there isn't a valid set of packages to use self.updateResolvedPackages() return self.mResolvedPackageList def checkFiltersChanged(self): list_to_use = [] return True in [pkg.filtersChanged(list_to_use) for pkg in self.mResolveAgents] def resolveHelper(self): self.resolveAgentsChanged = True while self.resolveAgentsChanged: for agent in self.mResolveAgents: flagDBG().out(flagDBG.INFO, "DepResSys.resolveHelper", "Updating " + agent.getName()) agent.update(self.mAgentsVisitedList, self.mAgentChangeList) self.resolveAgentsChanged = self.checkFiltersChanged() # Ask mResolveAgents if they are done(they ask sub people) unless they are # really above you in the walk # If there were changes...run update on mResolveAgents again # at the end ask for pkglist..if it comes back empty then we don't # have a usable configuration for those packages def resolveDeps(self): self.resolveHelper() if not self.mMadeDependList: for agent in self.mResolveAgents: agent.makeDependList() self.mMadeDependList = True self.updateResolvedPackages() # Check if the first round through we found something # Otherwise we need to start removing packages that aren't viable # during the loop self.mSatisfied = (len(self.mResolvedPackageList) != 0) # remove top of packages that added Filters. # then move on to resolving again # remove more if neccesary agentChangeNumber = 0 while not self.mResolvedPackageList: if(self.mAgentChangeList[agentChangeNumber]): if self.mAgentChangeList[agentChangeNumber] in self.mInvalidPackageList: agentChangeNumber += 1 else: if(self.mAgentChangeList[agentChangeNumber].getViablePackages()): flagDBG().out(flagDBG.INFO, "DepResSys.resolveDeps", "Removing bad pkg from " + self.mAgentChangeList[agentChangeNumber].getName()) self.mInvalidPackageList.append(self.mAgentChangeList[agentChangeNumber].removeCurrentPackage()) else: flagDBG().out(flagDBG.INFO, "DepResSys.resolveDeps", "No combinations.. Resetting " + self.mAgentChangeList[agentChangeNumber].getName()) self.mAgentChangeList[agentChangeNumber].reset() agentChangeNumber += 1 self.resolveHelper() self.updateResolvedPackages() self.mSatisfied = (len(self.mResolvedPackageList) != 0) return class PkgAgent: """ Agent that keeps track of the versions for a package given some filters and the addition of Filters """ # Makes a PkgAgent that finds its current package with the version reqs def __init__(self, name): if DepResolutionSystem().checkAgentExists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "Package Agent %s already exists" % self.mName) self.mName = name flagDBG().out(flagDBG.INFO, "PkgAgent", "Creating:" + str(self.mName)) if not PkgDB().exists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "No info for package: %s" % self.mName) #XXX Doesn't keep filters added for a redo... DepResolutionSystem().addNewAgent(self) self.mFilterList = [] self.mFilterList.extend(DepResolutionSystem().getFilters()) self.mBasePackageList = PkgDB().getPkgInfos(name) self.mBasePackageList.sort(lambda lhs, rhs: cmp(rhs.getVariable('Version'), lhs.getVariable('Version'))) for filt in self.mFilterList: self.mBasePackageList = filt.filter(self.mBasePackageList) if len(self.mBasePackageList) == 0: flagDBG().out(flagDBG.ERROR, "PkgAgent", "No viable packages for: %s" % self.mName) self.mViablePackageList = copy.deepcopy(self.mBasePackageList) if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mFiltersChanged = True self.mCheckDepends = True self.mAgentDependList = [] def getName(self): return self.mName def setCheckDepends(self, tf): self.mCheckDepends = tf #Filter("Version", lambda x: x == "4.5") def makeDependList(self): if not self.mCheckDepends: self.mAgentDependList = [] return dep_list = [] if self.mCurrentPackage: req_string = self.mCurrentPackage.getVariable("Requires") if DepResolutionSystem().checkPrivateRequires(): req_string = req_string + " " + self.mCurrentPackage.getVariable("Requires.private") req_string = req_string.strip() if req_string == "": return req_string = req_string.replace(',', ' ') req_string = req_string.replace('(', ' ') req_string = req_string.replace(')', ' ') space_req_string_list = req_string.split(' ') req_string_list = [] for entry in space_req_string_list: if len(entry) > 0: req_string_list.append(entry) i = 0 flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList", self.mCurrentPackage.getName() + " requires: " + str(req_string_list)) while len(req_string_list) > i: if PkgDB().exists(req_string_list[i]): new_filter = [] new_agent = DepResolutionSystem().createAgent(req_string_list[i]) if len(req_string_list) > i+1: if req_string_list[i+1] == "=": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x == v) elif req_string_list[i+1] == "<=": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x <= v) elif req_string_list[i+1] == ">=": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x >= v) elif req_string_list[i+1] == ">": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x > v) elif req_string_list[i+1] == "<": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x < v) else: i += 1 else: i += 1 dep_list.append(new_agent) if new_filter: i+=3 new_agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "PkgAgent.makeDependList", "Package %s depends on %s but does not seem to be installed." % (self.mName, str(req_string_list[i]))) flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList", str(self.mName) + " : List is:" + str([pkg.getName() for pkg in dep_list])) self.mAgentDependList = dep_list def filtersChanged(self, packageList): tf_list = [self.mFiltersChanged] if self.mName not in packageList: packageList.append(self.mName) for pkg in self.mAgentDependList: tf_list.append(pkg.filtersChanged(packageList)) return True in tf_list def getCurrentPackageList(self, packageList): pkgs = [] if self.mName not in packageList: flagDBG().out(flagDBG.INFO, "PkgAgent.getCurrentPackageList", "Package: %s" % self.mName) pkgs.append(self.mCurrentPackage) packageList.append(self.mName) # Make depend list if we are supposed to self.updateFilters() self.makeDependList() for pkg in self.mAgentDependList: pkgs.extend(pkg.getCurrentPackageList(packageList)) return pkgs # current pkginfo for me def getCurrentPkgInfo(self): return self.mCurrentPackage # Someone else usually places these on me # I keep track of those separately def addFilter(self, filter): flagDBG().out(flagDBG.INFO, "PkgAgent.addFilter", "Filter %s" % self.mName + " on %s." % filter.getVarName()) self.mFiltersChanged = True self.mFilterList.append(filter) def removeCurrentPackage(self): flagDBG().out(flagDBG.INFO, "PkgAgent.removeCurrentPackage", "Removing current package of %s" % self.mName) if self.mViablePackageList: ret_val = self.mViablePackageList[0] in self.mBasePackageList del self.mViablePackageList[0] if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] return ret_val def update(self, agentVisitedList, agentChangeList): flagDBG().out(flagDBG.INFO, "PkgAgent.update", "%s" % self.mName) if self.mName in agentVisitedList: return agentVisitedList.append(self.mName) if self.mFiltersChanged: self.mFiltersChanged = False self.updateFilters() # TODO: checkFilters and add them # if a pkg is in visitedList then add yourself to agentChangeList for pkg in self.mAgentDependList: pkg.update(agentVisitedList, agentChangeList) return def updateFilters(self): for filt in self.mFilterList: self.mViablePackageList = filt.filter(self.mViablePackageList) flagDBG().out(flagDBG.INFO, "PkgAgent.updateFilters", "%s has " % self.mName + str(len(self.mViablePackageList)) + " left") if len(self.mViablePackageList) > 0: self.mCurrentPackage = self.mViablePackageList[0] else: for f in self.mFilterList: Utils.addPossibleError(str(self.mName) + " -> " + str(f.getVarName())) self.mCurrentPackage = [] def reset(self): flagDBG().out(flagDBG.INFO, "PkgAgent.reset", "Resetting package: %s" % self.mName) self.mViablePackageList = self.mBasePackageList if self.mViablePackageList: self.mCurrentPacakge = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mFilterList = DepResolutionSystem().getFilters() self.mAgentDependList = [] self.mFiltersChanged = True return class Filter: """ A single Filter that knows how to filter the list it recieves Will be inheireted....?..? """ def __init__(self, variableName, testCallable): self.mVarName = variableName self.mTestCallable = testCallable def getVarName(self): return self.mVarName def filter(self, pkg_info_list): ret_pkg_list = [] # Filter first for pkg in pkg_info_list: var = pkg.getVariable(self.mVarName) if self.mTestCallable(var): flagDBG().out(flagDBG.INFO, "Filter", "Passed: %s:" % pkg.getName() + " %s is " % self.mVarName + str(var)) ret_pkg_list.append(pkg) else: flagDBG().out(flagDBG.INFO, "Filter", "Failed: %s:" % pkg.getName() + " %s is " % self.mVarName + str(var)) # Now sort ret_pkg_list.sort(lambda lhs, rhs: cmp(rhs.getVariable(self.mVarName), lhs.getVariable(self.mVarName))) return ret_pkg_list #requires: qt == 4.5 #Filter("Version", lambda x: x <= "4.5") #Filter("Version", lambda x: x <= "4.5") class PkgDB(object): """ Holds all the neccesary information to evaluate itself when needed. Is in charge of holding a list of PkgInfo's that contain info about the package. """ __initialized = False def __init__(self): if self.__initialized: return self.__initialized = True self.mPkgInfos = {} # {pkg_name: List of package infos} self.populatePkgInfoDBPcFiles() self.populatePkgInfoDBFpcFiles() def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def printAllPackages(self): list_of_package_names = [] for pkg in self.mPkgInfos: list_of_package_names.append(pkg) for name in list_of_package_names: print name sys.exit(0) def getVariables(self, name, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariable", "Finding " + str(variable_list) + " in " + str(name)) ret_list = [] for var in variable_list: if self.mPkgInfos.has_key(name): ret_list.extend(self.mPkgInfos[name][0].getVariable(var)) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariable", "Package %s not found." % name) return ret_list def checkPackage(self, name): flagDBG().out(flagDBG.INFO, "PkgDB.checkPackage", "Finding " + str(name)) if self.mPkgInfos.has_key(name): return True else: flagDBG().out(flagDBG.ERROR, "PkgDB.CheckPackage", "Package %s not found." % name) return False def getVariablesAndDeps(self, pkg_list, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariablesAndDeps", "Finding " + str(variable_list) + " in " + str(pkg_list)) if DepResolutionSystem().checkPrivateRequires(): temp_var_list = [] for var in variable_list: temp_var_list.append(var.join(".private")) variable_list = variable_list + temp_var_list for name in pkg_list: if self.mPkgInfos.has_key(name): agent = DepResolutionSystem().createAgent(name) DepResolutionSystem().addResolveAgent(agent) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariablesAndDeps", "Package %s not found." % name) DepResolutionSystem().resolveDeps() pkgs = DepResolutionSystem().getPackages() var_list = [] for pkg in pkgs: if pkg: for var in variable_list: var_list.extend(tokenize(pkg.getVariable(var), pkg.getSplitChar())) return var_list def getPkgInfos(self, name): if self.mPkgInfos.has_key(name): return self.mPkgInfos[name] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getPkgInfos", "Package %s not found." % name) def exists(self, name): return self.mPkgInfos.has_key(name) def getInfo(self, name): if self.mPkgInfos.has_key(name): return [pkg.getInfo() for pkg in self.mPkgInfos[name]] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getInfo", "Package %s not found." % name) def buildPcFileDict(self): """ Builds up a dictionary of {name: list of files for name} """ pc_dict = {} for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.pc")) # List of .pc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these pc files: %s" % str(glob_list)) for g in glob_list: # Get key name and add file to value list in dictionary key = os.path.basename(g)[:-3] # Strip .pc off the filename...rstrip no worky pc_dict.setdefault(key, []).append(g) for f in Utils.getFileList(): if f.endswith(".pc"): key = os.path.basename(f)[:-3] # Strip .pc off the filename...rstrip no worky pc_dict.setdefault(key, []).append(f) return pc_dict # { "key", [ "list", "of", "corresponding", "pc", "files"] } def populatePkgInfoDBPcFiles(self): dict_to_pop_from = self.buildPcFileDict() for (pkg,files) in dict_to_pop_from.iteritems(): for f in files: self.mPkgInfos.setdefault(pkg,[]).append(PkgInfo(pkg, f, "pc")) def buildFpcFileList(self): """ Builds up a dictionary of {name: list of files for name} """ file_list = [] for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.fpc")) # List of .fpc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these fpc files: %s" % str(glob_list)) for g in glob_list: file_list.append(g) for f in Utils.getFileList(): if f.endswith(".fpc"): file_list.append(f) return file_list # [ "list", "of", "fpc", "files"] def populatePkgInfoDBFpcFiles(self): list_to_add = self.buildFpcFileList() for filename in list_to_add: var_dict = Utils.parsePcFile(filename) if not var_dict.has_key("Provides"): flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Provides" % str(filename)) continue if not var_dict.has_key("Arch"): flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Arch" % str(filename)) continue provides_string = var_dict["Provides"] provides_string = provides_string.replace(',', ' ') provides_string = provides_string.replace('(', ' ') provides_string = provides_string.replace(')', ' ') for key in provides_string.split(" "): if len(key) > 0: self.mPkgInfos.setdefault(key, []).append(PkgInfo(key, filename, "fpc", var_dict)) class PkgInfo: """ Holds the information for a package file on the system. These however are evaluated when the need arises. """ def __init__(self, name, file, type, varDict={}): self.mName = name self.mFile = file self.mIsEvaluated = False self.mType = type self.mVariableDict = varDict if self.mType == "fpc": self.mIsEvaluated = True def getVariable(self, variable): self.evaluate() return self.mVariableDict.get(variable,"") def getName(self): return self.mName def evaluate(self): if not self.mIsEvaluated: flagDBG().out(flagDBG.INFO, "PkgInfo.evaluate", "Evaluating %s" % self.mName) self.mVariableDict= Utils.parsePcFile(self.mFile) self.mIsEvaluated = True def getInfo(self): self.evaluate() return self.mVariableDict def getSplitChar(self): self.evaluate() split_char = self.mVariableDict.get("SplitCharacter", ' ') if split_char == "": split_char = ' ' return split_char class OptionsEvaluator: def __init__(self): if len(sys.argv) < 2: self.printHelp() # This is only the args....(first arg is stripped) def evaluateArgs(self, args): # Catch any args that need to be tended to immediately # Process args in the order that they were recieved. Some options are not # shown below because they are sub-options of an option below (--strip-dups) for option in args: if option.startswith("--verbose-debug"): flagDBG().setLevel(flagDBG.VERBOSE) if option.startswith("--debug"): flagDBG().setLevel(flagDBG.INFO) elif option.startswith("--from-file"): val_start = option.find('=') + 1 file = option[val_start:] Utils.EXTRA_FLAGPOLL_FILES = Utils.EXTRA_FLAGPOLL_FILES + ":" + file elif option.startswith("--help"): self.printHelp() sys.exit(0) elif option.startswith("--version"): print "%s.%s.%s" % Utils.getFlagpollVersion() sys.exit(0) elif option.startswith("--list-all"): PkgDB().printAllPackages() continue listedAgentNames = [] agent = None num_args = len(args) curr_arg = 0 output_options = [] # (option, name/"") important_options = [] # ones that need special attention while curr_arg < num_args: if args[curr_arg].startswith("--atleast-version"): val_start = args[curr_arg].find('=') + 1 atleast_version = args[curr_arg][val_start:] atleast_filter = Filter("Version", lambda x,v=atleast_version: x >= v) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(atleast_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --at-least-version") continue if args[curr_arg].startswith("--cflags-only-I"): output_options.append(("cflags-only-I", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--cflags-only-other"): output_options.append(("cflags-only-other", "")) curr_arg = curr_arg + 1 continue #This could be the catch all for the above ones to and then filter based on what is asked... #For clarity of course... if args[curr_arg].startswith("--cflags"): output_options.append(("cflags", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--extra-paths"): val_start = args[curr_arg].find('=') + 1 paths = args[curr_arg][val_start:] Utils.EXTRA_FLAGPOLL_SEARCH_PATHS = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS + ":" + paths curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--exact-version"): val_start = args[curr_arg].find('=') + 1 exact_version = args[curr_arg][val_start:] exact_filter = Filter("Version", lambda x,v=exact_version: x == v) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(exact_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --exact-version") continue if args[curr_arg].startswith("--exists"): important_options.append("exists") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--from-file"): val_start = args[curr_arg].find('=') + 1 file = args[curr_arg][val_start:] file_filter = Filter("FlagpollFilename", lambda x,f=file: x == f) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(file_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --from-file") continue if args[curr_arg].startswith("--info"): important_options.append("info") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--print-pkg-options"): important_options.append("print-pkg-options") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--keep-dups"): Utils.setKeepDups(True) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-l"): output_options.append(("libs-only-l", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-L"): output_options.append(("libs-only-L", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-other"): output_options.append(("libs-only-other", "")) curr_arg = curr_arg + 1 continue #This could be the catch all for the above ones to and then filter based on what is asked... if args[curr_arg].startswith("--libs"): output_options.append(("libs", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--require-all"): rlen = len("--require-all") req_string = args[curr_arg][rlen:] req_string = req_string.replace('-','_') curr_arg = curr_arg + 1 if req_string.find("<=") != -1: op_start = req_string.find("<=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x <= v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find(">=") != -1: op_start = req_string.find(">=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x >= v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find(">") != -1: op_start = req_string.find(">") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x > v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("<") != -1: op_start = req_string.find("<") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x < v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("=") != -1: op_start = req_string.find("=") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x == v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("=") == -1: new_filter = Filter(req_string, lambda x: len(x) > 0) DepResolutionSystem().addFilter(new_filter) continue continue if args[curr_arg].startswith("--require-"): rlen = len("--require-") req_string = args[curr_arg][rlen:] req_string = req_string.replace('-','_') curr_arg = curr_arg + 1 if agent is None: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --require") if req_string.find("<=") != -1: op_start = req_string.find("<=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x <= v) agent.addFilter(new_filter) continue if req_string.find(">=") != -1: op_start = req_string.find(">=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x >= v) agent.addFilter(new_filter) continue if req_string.find(">") != -1: op_start = req_string.find(">") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x > v) agent.addFilter(new_filter) continue if req_string.find("<") != -1: op_start = req_string.find("<") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x < v) agent.addFilter(new_filter) continue if req_string.find("=") != -1: op_start = req_string.find("=") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x == v) agent.addFilter(new_filter) continue if req_string.find("=") == -1: new_filter = Filter(req_string, lambda x: len(x) > 0) agent.addFilter(new_filter) continue continue if args[curr_arg].startswith("--no-deps"): if agent is not None: agent.setCheckDepends(False) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --no-deps") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--require="): val_start = args[curr_arg].find('=') + 1 req_var = args[curr_arg][val_start:] curr_arg = curr_arg + 1 DepResolutionSystem().makeRequireFilter(req_var) continue if args[curr_arg].startswith("--modversion"): if agent is not None: output_options.append(("Version", agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --modversion") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--max-release"): val_start = args[curr_arg].find('=') + 1 max_release = args[curr_arg][val_start:] max_filter = Filter("Version", lambda x,v=max_release: x.startswith(v)) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(max_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --max-release") continue if args[curr_arg].startswith("--static"): DepResolutionSystem().setPrivateRequires(True) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--variable"): val_start = args[curr_arg].find('=') + 1 fetch_var = args[curr_arg][val_start:] if agent is not None: output_options.append((fetch_var, agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --variable") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--get-all"): rlen = len("--get-all-") get_string = args[curr_arg][rlen:] get_string = get_string.replace('-','_') output_options.append((get_string, "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--get"): rlen = len("--get-") get_string = args[curr_arg][rlen:] get_string = get_string.replace('-','_') if agent is not None: output_options.append((get_string, agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --get") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--concat"): important_options.append("concat") curr_arg = curr_arg + 1 continue if not args[curr_arg].startswith("--"): name = args[curr_arg] curr_arg = curr_arg + 1 if PkgDB().checkPackage(name): agent = DepResolutionSystem().createResolveAgent(name) listedAgentNames.append(name) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Package %s" % name) sys.exit(1) continue if args[curr_arg] != "--debug" and args[curr_arg] != "--verbose-debug": flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Option: %s" % args[curr_arg]) curr_arg = curr_arg + 1 if len(listedAgentNames) == 0: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Must specify at least one package") DepResolutionSystem().resolveDeps() pkgs = DepResolutionSystem().getPackages() for p in pkgs: if not p: for option in important_options: if option == "exists": print "no" sys.exit(1) flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found") if len(pkgs) == 0: for option in important_options: if option == "exists": print "no" sys.exit(1) flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found") sys.exit(1) concat = False for option in important_options: if option == "exists": print "yes" return sys.exit(0) # already checked for none above if option == "concat": concat = True if option == "info": pkg_info_list = [] for pkg in pkgs: if pkg.getName() in listedAgentNames: print pkg.getName() pkg_info = pkg.getInfo() for key in pkg_info.keys(): print " %s : %s" % (key, pkg_info[key]) if option == "print-pkg-options": print "" print "All options below would start with (--get-/--get-all-/--require-/--require-all-)" print "NOTE: this list does not include the standard variables that are exported." print "" for pkg in pkgs: if pkg.getName() not in listedAgentNames: continue print "Package: " + pkg.getName() for key in pkg.getInfo().keys(): if key not in [ "Name", "Description", "URL", "Version", "Requires", "Requires.private", "Conflicts", "Libs", "Libs.private", "Cflags", "Provides", "Arch", "FlagpollFilename", "prefix" ]: print " " + key.replace('_','-') #print output_options #output_options = [] #output_single = [] #Process options here.............. concat_list = [] if concat: print_option = lambda x: concat_list.extend(x) else: print_option = lambda x: Utils.printList(x) for option in output_options: if option[0] == "cflags": print_option(Utils.stripDupIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "cflags-only-I": print_option(Utils.cflagsOnlyDirIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "cflags-only-other": print_option(Utils.cflagsOnlyOtherIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "libs-only-l": print_option(Utils.libsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs-only-L": print_option(Utils.libDirsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs-only-other": print_option(Utils.libsOnlyOtherLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs": print_option(Utils.stripDupLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) else: print_option(Utils.stripDupInList(self.getVarFromPkgs(option[0], pkgs, option[1]))) if concat: Utils.printList(Utils.stripDupInList(concat_list)) def getVarFromPkgs(self, var, pkgs, pkg_name=""): var_list = [] ext_vars = [] if var == "Libs": if DepResolutionSystem().checkPrivateRequires: ext_vars.append("Libs.private") if pkg_name == "": for pkg in pkgs: if pkg: var_list.extend(tokenize(pkg.getVariable(var), pkg.getSplitChar())) for extra_var in ext_vars: var_list.extend(tokenize(pkg.getVariable(extra_var), pkg.getSplitChar())) else: for pkg in pkgs: if pkg: if pkg.getName() == pkg_name: var_list.extend(tokenize(pkg.getVariable(var), pkg.getSplitChar())) for extra_var in ext_vars: var_list.extend(tokenize(pkg.getVariable(extra_var), pkg.getSplitChar())) return var_list def printHelp(self): print "usage: flagpoll pkg options [pkg options] [generic options]" print " " print "generic options:" print " --help show this help message and exit" print " --version output version of flagpoll" print " --list-all list all known packages" print " --debug show debug information" print " --verbose-debug show verbose debug information" print " --extra-paths=EXTRA_PATHS" print " extra paths for flagpoll to search for meta-data files" print " --concat concatenate all output and output as one line" print " --keep-dups do not strip out all duplicate info from options" print " --info show information for packages" print " --print-pkg-options show pkg specific options" print " " print "options:" print " --modversion output version for package" print " --require=REQUIRE adds additional requirements for packages ex. 32/64" print " --libs output all linker flags" print " --static output linker flags for static linking" print " --libs-only-l output -l flags" print " --libs-only-other output other libs (e.g. -pthread)" print " --libs-only-L output -L flags" print " --cflags output all pre-processor and compiler flags" print " --cflags-only-I output -I flags" print " --cflags-only-other output cflags not covered by the cflags-only-I option" print " --exists return 0 if the module(s) exist" print " --from-file=FILE use the specified FILE for the package" #print " --print-provides print which packages the package provides" #print " --print-requires print which packages the package requires" print " --no-deps do not lookup dependencies for the package" print " --atleast-version=ATLEAST_VERSION" print " return 0 if the module is at least version" print " ATLEAST_VERSION" print " --exact-version=EXACT_VERSION" print " return 0 if the module is exactly version" print " EXACT_VERSION" print " --max-release=MAX_RELEASE" print " return 0 if the module has a release that has a" print " version of MAX_RELEASE and will return the max" print " --variable=VARIABLE get the value of a variable" print " " print "dynamic options(replace VAR with a variable you want to get/filter on)" print " NOTE: replace underscores with dashes in VAR" print " NOTE: quotes are needed around <,>,= combinations" print " --get-VAR get VAR from package" print " --get-all-VAR get VAR from package and its deps" print " --require-VAR[<,>,=VAL]" print " require that a var is defined for a package" print " or optionally use equality operators against VAL" print " --require-all-VAR[<,>,=VAL]" print " require that a var is defined for all packages" print " or optionally use equality operators against VAL" print "" print "extending search path" print " FLAGPOLL_PATH environment variable that can be set to" print " extend the search path for .fpc/.pc files" print "" print "" print "Send bug reports and/or feedback to flagpoll-users@vrsource.org" sys.exit(0) def main(): # GO! # Initialize singletons and the start evaluating my_dbg = flagDBG() my_dep_system = DepResolutionSystem() opt_evaluator = OptionsEvaluator() opt_evaluator.evaluateArgs(sys.argv[1:]) sys.exit(0) if __name__ == "__main__": main()
Python
#!/usr/bin/env python from distutils.core import setup try: import py2exe except: pass setup( name='flagpoll', version='0.9.1', description='Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software.', author='Daniel E. Shipton', author_email='dshipton@infiscape.com', license='GPL', url='https://realityforge.vrsource.org/view/FlagPoll/WebHome', download_url='https://realityforge.vrsource.org/view/FlagPoll/FlagpollDownloads', console=['flagpoll'], scripts=['flagpoll'], long_description = "Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software. Think of it as the rpm of software development. It enables developers total control over which packages, versions, architectures, etc. that they want to use meta-data from.", data_files=[('share/flagpoll', ['flagpoll.fpc']), ('share/man/man1', ['flagpoll.1']), ('share/aclocal', ['flagpoll.m4']), ('share/html', ['flagpoll-manual.html'])] )
Python
#!/usr/bin/env python # ----------------------------------------------------------------- # # Flagpoll: A tool to extract flags from installed applications # for compiling, settting variables, etc. # # Original Authors: # Daniel E. Shipton <dshipton@gmail.com> # # Flagpoll is Copyright (C) 2006-2007 by Daniel E. Shipton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to: # Free SoftwareFoundation, Inc. # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # # ----------------------------------------------------------------- import sys, os, glob, os.path, copy, platform pj = os.path.join #################################################################### # SNAGGED FROM PYTHON 2.4 for versions under 2.4 #################################################################### import re as _re class _multimap: """Helper class for combining multiple mappings. Used by .{safe_,}substitute() to combine the mapping and keyword arguments. """ def __init__(self, primary, secondary): self._primary = primary self._secondary = secondary def __getitem__(self, key): try: return self._primary[key] except KeyError: return self._secondary[key] class _TemplateMetaclass(type): pattern = r""" %(delim)s(?: (?P<escaped>%(delim)s) | # Escape sequence of two delimiters (?P<named>%(id)s) | # delimiter and a Python identifier {(?P<braced>%(id)s)} | # delimiter and a braced identifier (?P<invalid>) # Other ill-formed delimiter exprs ) """ def __init__(cls, name, bases, dct): super(_TemplateMetaclass, cls).__init__(name, bases, dct) if 'pattern' in dct: pattern = cls.pattern else: pattern = _TemplateMetaclass.pattern % { 'delim' : _re.escape(cls.delimiter), 'id' : cls.idpattern, } cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE) class Template: """A string class for supporting $-substitutions.""" __metaclass__ = _TemplateMetaclass delimiter = '$' idpattern = r'[_a-z][_a-z0-9]*' def __init__(self, template): self.template = template # Search for $$, $identifier, ${identifier}, and any bare $'s def _invalid(self, mo): i = mo.start('invalid') lines = self.template[:i].splitlines(True) if not lines: colno = 1 lineno = 1 else: colno = i - len(''.join(lines[:-1])) lineno = len(lines) raise ValueError('Invalid placeholder in string: line %d, col %d' % (lineno, colno)) def substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): # Check the most common path first. named = mo.group('named') or mo.group('braced') if named is not None: val = mapping[named] # We use this idiom instead of str() because the latter will # fail if val is a Unicode containing non-ASCII characters. return '%s' % val if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: self._invalid(mo) raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) def safe_substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): named = mo.group('named') if named is not None: try: # We use this idiom instead of str() because the latter # will fail if val is a Unicode containing non-ASCII return '%s' % mapping[named] except KeyError: return self.delimiter + named braced = mo.group('braced') if braced is not None: try: return '%s' % mapping[braced] except KeyError: return self.delimiter + '{' + braced + '}' if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: return self.delimiter raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) #################################################################### # End Snagging #################################################################### def tokenize(val, split_char): val = val.strip() results = [] while len(val) > 0: sn = val.find(split_char) qn = val.find('"') #print " -> val: %s Len: %s" % (val, len(val)) # If we find a quote first, then find the space after the next quote. if qn < sn: #print " -> Found a quote first:", qn # Find next quote. qn2 = val.find('"', qn+1) #print " -> Found second quote:", qn2 sn = val.find(split_char, qn2+1) #print " -> Found next space:", sn if sn < 0: results.append(val[:]) val = "" else: results.append(val[:sn]) val = val[sn:] val = val.strip() return results class Utils: # Holds collection of small utility functions EXTRA_FLAGPOLL_SEARCH_PATHS = "" EXTRA_FLAGPOLL_FILES = "" path_list_cache = None # Cache of found path lists. (only calcuate once) KEEP_DUPS = False FLAGPOLL_LIST_OF_POSSIBLE_ERRORS = [] def addPossibleError(pos_err): Utils.FLAGPOLL_LIST_OF_POSSIBLE_ERRORS.append(pos_err) addPossibleError = staticmethod(addPossibleError) def getPossibleErrors(): return Utils.stripDupInList(Utils.FLAGPOLL_LIST_OF_POSSIBLE_ERRORS) getPossibleErrors = staticmethod(getPossibleErrors) def getFlagpollVersion(): FLAGPOLL_MAJOR_VERSION = 0 FLAGPOLL_MINOR_VERSION = 9 FLAGPOLL_PATCH_VERSION = 1 return ( FLAGPOLL_MAJOR_VERSION, FLAGPOLL_MINOR_VERSION, FLAGPOLL_PATCH_VERSION ) getFlagpollVersion = staticmethod(getFlagpollVersion) def getPathList(): if None != Utils.path_list_cache: return Utils.path_list_cache #TODO: expand LD_LIBRARY_PATH to 64/32/etc??? pkg_cfg_dir = [] flg_cfg_dir = [] ld_path = [] if os.environ.has_key("PKG_CONFIG_PATH"): pkg_cfg_dir = os.environ["PKG_CONFIG_PATH"].split(os.pathsep) if os.environ.has_key("FLAGPOLL_PATH"): flg_cfg_dir = os.environ["FLAGPOLL_PATH"].split(os.pathsep) ld_dirs = ['LD_LIBRARY_PATH', 'DYLD_LIBRARY_PATH', 'PATH'] for d in ld_dirs: if os.environ.has_key(d): cur_path = os.environ[d].split(os.pathsep) ld_path_pkg = [pj(p,'pkgconfig') for p in cur_path] ld_path_flg = [pj(p,'flagpoll') for p in cur_path] ld_path.extend(ld_path_pkg) ld_path.extend(ld_path_flg) extra_paths = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS.split(os.pathsep) path_list = extra_paths path_list.extend(flg_cfg_dir) path_list.extend(pkg_cfg_dir) path_list.extend(ld_path) default_path_list = [pj('/','usr','lib64'), pj('/','usr','lib32'), pj('/','usr','lib'), pj('/','usr','share')] default_path_pkg = [pj(p,'pkgconfig') for p in default_path_list] default_path_flg = [pj(p,'flagpoll') for p in default_path_list] path_list.extend(default_path_pkg) path_list.extend(default_path_flg) flagDBG().out(flagDBG.VERBOSE, "Utils.getPathList", "Potential path list: " + str(path_list)) clean_path_list = [] for p in path_list: if os.path.exists(p) and os.path.isdir(p) and not p in clean_path_list: clean_path_list.append(p) path_list = clean_path_list flagDBG().out(flagDBG.INFO, "Utils.getPathList", "Using path list: " + str(path_list)) Utils.path_list_cache = path_list return path_list getPathList = staticmethod(getPathList) def getFileList(): flist = Utils.EXTRA_FLAGPOLL_FILES.split(":") filelist = [] for f in flist: if os.path.isfile(f): filelist.append(f) return filelist getFileList = staticmethod(getFileList) def setKeepDups(keep_dups): Utils.KEEP_DUPS = keep_dups setKeepDups = staticmethod(setKeepDups) def stripDupInList(gen_list): new_list = [] list_len = len(gen_list) i = 0 while i < list_len: item = gen_list[i].strip() if Utils.KEEP_DUPS: if len(item) > 0: new_list.append(item) continue if item in ('-framework', '-arch', '-isysroot'): item = '%s %s' % (item, gen_list[i + 1]) i += 1 if item not in new_list: if len(item) > 0: new_list.append(item) i += 1 return new_list stripDupInList = staticmethod(stripDupInList) def stripDupLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] dir_list = [] list_len = len(flag_list) i = 0 vc_linker_flag_re = _re.compile(r'^[/-]libpath:', _re.I) other_linker_flag_re = _re.compile(r'^-[LRF]') while i < list_len: flg = flag_list[i].strip() if len(flg) > 0: if (other_linker_flag_re.match(flg) is not None\ or vc_linker_flag_re.match(flg) is not None): dir_list.append(flg) else: if flg in ("-framework", "-arch", "-isysroot"): flg = "%s %s" % (flg, flag_list[i + 1]) i += 1 lib_list.append(flg) i += 1 new_list = dir_list + lib_list return Utils.stripDupInList(new_list) stripDupLinkerFlags = staticmethod(stripDupLinkerFlags) def stripDupIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] extra_list = [] list_len = len(flag_list) i = 0 while i < list_len: flg = flag_list[i].strip() if len(flg) > 0: if flg.startswith("-I") or flg.startswith("/I"): inc_list.append(flg) elif flg in ("-arch", "-isysroot"): extra_list.append("%s %s" % (flg, flag_list[i + 1])) i += 1 else: extra_list.append(flg) i += 1 extra_list.sort() new_list = inc_list + extra_list return Utils.stripDupInList(new_list) stripDupIncludeFlags = staticmethod(stripDupIncludeFlags) def cflagsOnlyDirIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-I") or flg.startswith("/I"): inc_list.append(flg) return Utils.stripDupInList(inc_list) cflagsOnlyDirIncludeFlags = staticmethod(cflagsOnlyDirIncludeFlags) def cflagsOnlyOtherIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though extra_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if not flg.startswith("-I") and not flg.startswith("/I"): extra_list.append(flg) return Utils.stripDupInList(extra_list) cflagsOnlyOtherIncludeFlags = staticmethod(cflagsOnlyOtherIncludeFlags) def libsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-l") or flg.endswith(".lib"): lib_list.append(flg) return Utils.stripDupInList(lib_list) libsOnlyLinkerFlags = staticmethod(libsOnlyLinkerFlags) def libsOnlyOtherLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though other_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: upper_flg = flg.upper() if not flg.startswith("-l") \ and not flg.startswith("-L")\ and not flg.startswith("-R")\ and not upper_flg.startswith("/LIBPATH")\ and not upper_flg.startswith("-LIBPATH")\ and not flg.endswith(".lib"): other_list.append(flg) return Utils.stripDupInList(other_list) libsOnlyOtherLinkerFlags = staticmethod(libsOnlyOtherLinkerFlags) def libDirsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though dir_list = [] vc_linker_flag_re = _re.compile(r'^[/-]libpath:', _re.I) other_linker_flag_re = _re.compile(r'^-[LRF]') for flg in flag_list: flg = flg.strip() if len(flg) > 0: if (other_linker_flag_re.match(flg) is not None or vc_linker_flag_re.match(flg) is not None): dir_list.append(flg) return Utils.stripDupInList(dir_list) libDirsOnlyLinkerFlags = staticmethod(libDirsOnlyLinkerFlags) def printList(gen_list): list_string = "" for item in gen_list: if len(item) > 0: list_string += str(item) list_string += " " print list_string.strip() printList = staticmethod(printList) def parsePcFile(filename): lines = open(filename).readlines() fvars = {} fvars["FlagpollFilename"] = filename lokals = {} lokals["fp_file_cwd"] = str(filename[:- ((len(os.path.basename(filename) ) + 1))]) lines.append("prefix: ${prefix}") append_next = False append_dict = {} append_key = "" for line in lines: line = line.strip() if not line: continue if append_next: tmp = append_dict[append_key] tmp = tmp[:-1] + " " + line append_dict[append_key] = tmp if tmp[-1:] == "\\": append_next = True else: append_next = False continue if line.startswith("#"): continue eq_pos = line.find('=') col_pos = line.find(':') if eq_pos < col_pos and eq_pos != -1 or col_pos == -1 and eq_pos != -1: # local variable name, val = line.split('=', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(lokals) except ValueError: flagDBG().out(flagDBG.WARN, "PkgInfo.parse", "%s has an invalid metadata file" % filename) lokals[name] = val if val[-1:] == "\\": append_next = True append_dict = lokals append_key = name continue if col_pos < eq_pos and col_pos != -1 or eq_pos == -1 and col_pos != -1: # exported variable name, val = line.split(':', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(lokals) except ValueError: flagDBG().out(flagDBG.ERROR, "PkgInfo.parse", "%s has an invalid metadata file" % filename) fvars[name] = val if val[-1:] == "\\": append_next = True append_dict = fvars append_key = name return fvars parsePcFile = staticmethod(parsePcFile) class flagDBG(object): # Logging class is really easy to use # Levels: # 0 - VERBOSE # 1 - INFO # 2 - WARN # 3 - ERROR VERBOSE = 0 INFO = 1 WARN = 2 ERROR = 3 __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if flagDBG.__initialized: return flagDBG.__initialized = True self.mLevel = self.WARN self.mLevelList = ["VERBOSE", "INFO", "WARN", "ERROR"] def setLevel(self, level): if level <= 3: self.mLevel = level def out(self, level, obj, message): if level == self.ERROR: if self.mLevel == self.VERBOSE: print self.mLevelList[level] + ":" + str(obj) + ": " + str(message) else: sys.stderr.write(self.mLevelList[level] + ": " + str(message) + "\n") errs = Utils.getPossibleErrors() if len(errs) > 0: sys.stderr.write("Possible culprits:\n") for pos_err in errs: sys.stderr.write( " " + str(pos_err) + "\n" ) sys.exit(1) if level >= self.mLevel: print self.mLevelList[level] + ":" + str(obj) + ": " + str(message) class DepResolutionSystem(object): """ You add PkgAgents with Filters into system and call resolve() you can check for succes by depsSatisfied() and get the list of packages that work back by calling getPackages() """ __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if DepResolutionSystem.__initialized: return DepResolutionSystem.__initialized = True self.mResolveAgents = [] self.mAgentDict = {} self.mFilters = [] self.mResolveAgentFilters = [] self.mInvalidPackageList = [] self.mSatisfied = False self.mAgentChangeList = [] # list of those responsible for adding Filters # to agents in higher in the chain than them # these are the first agents to ask that they pick # the next best package of them self.mAgentsVisitedList = [] # list of Agents that have been visited self.mResolvedPackageList = [] # list that is generated when deps are satified self.mCheckPrivateRequires = False self.mMadeDependList = False def getFilters(self): return self.mFilters def addFilter(self, filter): self.mFilters.append(filter) def addResolveAgentFilter(self, filter): self.mResolveAgentFilters.append(filter) def makeRequireFilter(self, requires): arch_list = [] arch_list.append("no_arch") arch_list.append("") if platform.system() == "Linux": if requires == "64": arch_list.append("x86_64") arch_list.append("x64") if requires == "32": arch_list.append("i386") arch_list.append("i486") arch_list.append("i586") arch_list.append("i686") if platform.system() == "Darwin": if requires == "64": arch_list.append("ppc64") if requires == "32": arch_list.append("ppc") if platform.system().startswith("IRIX"): arch_list.append(requires) new_filter = Filter("Arch", lambda x,v=arch_list: x in v) self.addFilter(new_filter) def createAgent(self, name): if self.checkAgentExists(name): return self.getAgent(name) else: agent = PkgAgent(name) flagDBG().out(flagDBG.INFO, "DepResSys.createAgent", "Adding %s" % name) self.addNewAgent(agent) return agent def createResolveAgent(self, name): if self.checkAgentExists(name): return self.getAgent(name) else: agent = PkgAgent(name) flagDBG().out(flagDBG.INFO, "DepResSys.createResolveAgent", "Adding %s" % name) self.addResolveAgent(agent) return agent def setPrivateRequires( self, req ): self.mCheckPrivateRequires = req def checkPrivateRequires(self): return self.mCheckPrivateRequires def checkAgentExists(self, name): return self.mAgentDict.has_key(name) def getAgent(self, name): if self.mAgentDict.has_key(name): return self.mAgentDict[name] else: flagDBG().out(flagDBG.ERROR, "DepResSys.getAgent", "Agent %s does not exist" % name) def addNewAgent(self, agent): if not self.checkAgentExists(agent): self.mAgentDict[agent.getName()] = agent def addResolveAgent(self, agent): if agent not in self.mResolveAgents: self.mResolveAgents.append(agent) for filt in self.mResolveAgentFilters: agent.addFilter(filt) def isSatisfied(self): return self.mSatisfied def updateResolvedPackages(self): pkg_list = [] agent_list = [] for agent in self.mResolveAgents: list_of_pkgs = agent.getCurrentPackageList(agent_list) pkg_list.extend(list_of_pkgs) self.mResolvedPackageList = pkg_list def getPackages(self): flagDBG().out(flagDBG.INFO, "DepResSys.getPackages", "Generating list of valid packages ") #str([pkg.getCurrentPackage.getName() for pkg in self.mResolvedPackageList])) # If this comes back empty then there isn't a valid set of packages to use self.updateResolvedPackages() return self.mResolvedPackageList def checkFiltersChanged(self): list_to_use = [] return True in [pkg.filtersChanged(list_to_use) for pkg in self.mResolveAgents] def resolveHelper(self): self.resolveAgentsChanged = True while self.resolveAgentsChanged: for agent in self.mResolveAgents: flagDBG().out(flagDBG.INFO, "DepResSys.resolveHelper", "Updating " + agent.getName()) agent.update(self.mAgentsVisitedList, self.mAgentChangeList) self.resolveAgentsChanged = self.checkFiltersChanged() # Ask mResolveAgents if they are done(they ask sub people) unless they are # really above you in the walk # If there were changes...run update on mResolveAgents again # at the end ask for pkglist..if it comes back empty then we don't # have a usable configuration for those packages def resolveDeps(self): self.resolveHelper() if not self.mMadeDependList: for agent in self.mResolveAgents: agent.makeDependList() self.mMadeDependList = True self.updateResolvedPackages() # Check if the first round through we found something # Otherwise we need to start removing packages that aren't viable # during the loop self.mSatisfied = (len(self.mResolvedPackageList) != 0) # remove top of packages that added Filters. # then move on to resolving again # remove more if neccesary agentChangeNumber = 0 while not self.mResolvedPackageList: if(self.mAgentChangeList[agentChangeNumber]): if self.mAgentChangeList[agentChangeNumber] in self.mInvalidPackageList: agentChangeNumber += 1 else: if(self.mAgentChangeList[agentChangeNumber].getViablePackages()): flagDBG().out(flagDBG.INFO, "DepResSys.resolveDeps", "Removing bad pkg from " + self.mAgentChangeList[agentChangeNumber].getName()) self.mInvalidPackageList.append(self.mAgentChangeList[agentChangeNumber].removeCurrentPackage()) else: flagDBG().out(flagDBG.INFO, "DepResSys.resolveDeps", "No combinations.. Resetting " + self.mAgentChangeList[agentChangeNumber].getName()) self.mAgentChangeList[agentChangeNumber].reset() agentChangeNumber += 1 self.resolveHelper() self.updateResolvedPackages() self.mSatisfied = (len(self.mResolvedPackageList) != 0) return class PkgAgent: """ Agent that keeps track of the versions for a package given some filters and the addition of Filters """ # Makes a PkgAgent that finds its current package with the version reqs def __init__(self, name): if DepResolutionSystem().checkAgentExists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "Package Agent %s already exists" % self.mName) self.mName = name flagDBG().out(flagDBG.INFO, "PkgAgent", "Creating:" + str(self.mName)) if not PkgDB().exists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "No info for package: %s" % self.mName) #XXX Doesn't keep filters added for a redo... DepResolutionSystem().addNewAgent(self) self.mFilterList = [] self.mFilterList.extend(DepResolutionSystem().getFilters()) self.mBasePackageList = PkgDB().getPkgInfos(name) self.mBasePackageList.sort(lambda lhs, rhs: cmp(rhs.getVariable('Version'), lhs.getVariable('Version'))) for filt in self.mFilterList: self.mBasePackageList = filt.filter(self.mBasePackageList) if len(self.mBasePackageList) == 0: flagDBG().out(flagDBG.ERROR, "PkgAgent", "No viable packages for: %s" % self.mName) self.mViablePackageList = copy.deepcopy(self.mBasePackageList) if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mFiltersChanged = True self.mCheckDepends = True self.mAgentDependList = [] def getName(self): return self.mName def setCheckDepends(self, tf): self.mCheckDepends = tf #Filter("Version", lambda x: x == "4.5") def makeDependList(self): if not self.mCheckDepends: self.mAgentDependList = [] return dep_list = [] if self.mCurrentPackage: req_string = self.mCurrentPackage.getVariable("Requires") if DepResolutionSystem().checkPrivateRequires(): req_string = req_string + " " + self.mCurrentPackage.getVariable("Requires.private") req_string = req_string.strip() if req_string == "": return req_string = req_string.replace(',', ' ') req_string = req_string.replace('(', ' ') req_string = req_string.replace(')', ' ') space_req_string_list = req_string.split(' ') req_string_list = [] for entry in space_req_string_list: if len(entry) > 0: req_string_list.append(entry) i = 0 flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList", self.mCurrentPackage.getName() + " requires: " + str(req_string_list)) while len(req_string_list) > i: if PkgDB().exists(req_string_list[i]): new_filter = [] new_agent = DepResolutionSystem().createAgent(req_string_list[i]) if len(req_string_list) > i+1: if req_string_list[i+1] == "=": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x == v) elif req_string_list[i+1] == "<=": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x <= v) elif req_string_list[i+1] == ">=": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x >= v) elif req_string_list[i+1] == ">": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x > v) elif req_string_list[i+1] == "<": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x < v) else: i += 1 else: i += 1 dep_list.append(new_agent) if new_filter: i+=3 new_agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "PkgAgent.makeDependList", "Package %s depends on %s but does not seem to be installed." % (self.mName, str(req_string_list[i]))) flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList", str(self.mName) + " : List is:" + str([pkg.getName() for pkg in dep_list])) self.mAgentDependList = dep_list def filtersChanged(self, packageList): tf_list = [self.mFiltersChanged] if self.mName not in packageList: packageList.append(self.mName) for pkg in self.mAgentDependList: tf_list.append(pkg.filtersChanged(packageList)) return True in tf_list def getCurrentPackageList(self, packageList): pkgs = [] if self.mName not in packageList: flagDBG().out(flagDBG.INFO, "PkgAgent.getCurrentPackageList", "Package: %s" % self.mName) pkgs.append(self.mCurrentPackage) packageList.append(self.mName) # Make depend list if we are supposed to self.updateFilters() self.makeDependList() for pkg in self.mAgentDependList: pkgs.extend(pkg.getCurrentPackageList(packageList)) return pkgs # current pkginfo for me def getCurrentPkgInfo(self): return self.mCurrentPackage # Someone else usually places these on me # I keep track of those separately def addFilter(self, filter): flagDBG().out(flagDBG.INFO, "PkgAgent.addFilter", "Filter %s" % self.mName + " on %s." % filter.getVarName()) self.mFiltersChanged = True self.mFilterList.append(filter) def removeCurrentPackage(self): flagDBG().out(flagDBG.INFO, "PkgAgent.removeCurrentPackage", "Removing current package of %s" % self.mName) if self.mViablePackageList: ret_val = self.mViablePackageList[0] in self.mBasePackageList del self.mViablePackageList[0] if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] return ret_val def update(self, agentVisitedList, agentChangeList): flagDBG().out(flagDBG.INFO, "PkgAgent.update", "%s" % self.mName) if self.mName in agentVisitedList: return agentVisitedList.append(self.mName) if self.mFiltersChanged: self.mFiltersChanged = False self.updateFilters() # TODO: checkFilters and add them # if a pkg is in visitedList then add yourself to agentChangeList for pkg in self.mAgentDependList: pkg.update(agentVisitedList, agentChangeList) return def updateFilters(self): for filt in self.mFilterList: self.mViablePackageList = filt.filter(self.mViablePackageList) flagDBG().out(flagDBG.INFO, "PkgAgent.updateFilters", "%s has " % self.mName + str(len(self.mViablePackageList)) + " left") if len(self.mViablePackageList) > 0: self.mCurrentPackage = self.mViablePackageList[0] else: for f in self.mFilterList: Utils.addPossibleError(str(self.mName) + " -> " + str(f.getVarName())) self.mCurrentPackage = [] def reset(self): flagDBG().out(flagDBG.INFO, "PkgAgent.reset", "Resetting package: %s" % self.mName) self.mViablePackageList = self.mBasePackageList if self.mViablePackageList: self.mCurrentPacakge = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mFilterList = DepResolutionSystem().getFilters() self.mAgentDependList = [] self.mFiltersChanged = True return class Filter: """ A single Filter that knows how to filter the list it recieves Will be inheireted....?..? """ def __init__(self, variableName, testCallable): self.mVarName = variableName self.mTestCallable = testCallable def getVarName(self): return self.mVarName def filter(self, pkg_info_list): ret_pkg_list = [] # Filter first for pkg in pkg_info_list: var = pkg.getVariable(self.mVarName) if self.mTestCallable(var): flagDBG().out(flagDBG.INFO, "Filter", "Passed: %s:" % pkg.getName() + " %s is " % self.mVarName + str(var)) ret_pkg_list.append(pkg) else: flagDBG().out(flagDBG.INFO, "Filter", "Failed: %s:" % pkg.getName() + " %s is " % self.mVarName + str(var)) # Now sort ret_pkg_list.sort(lambda lhs, rhs: cmp(rhs.getVariable(self.mVarName), lhs.getVariable(self.mVarName))) return ret_pkg_list #requires: qt == 4.5 #Filter("Version", lambda x: x <= "4.5") #Filter("Version", lambda x: x <= "4.5") class PkgDB(object): """ Holds all the neccesary information to evaluate itself when needed. Is in charge of holding a list of PkgInfo's that contain info about the package. """ __initialized = False def __init__(self): if self.__initialized: return self.__initialized = True self.mPkgInfos = {} # {pkg_name: List of package infos} self.populatePkgInfoDBPcFiles() self.populatePkgInfoDBFpcFiles() def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def printAllPackages(self): list_of_package_names = [] for pkg in self.mPkgInfos: list_of_package_names.append(pkg) for name in list_of_package_names: print name sys.exit(0) def getVariables(self, name, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariable", "Finding " + str(variable_list) + " in " + str(name)) ret_list = [] for var in variable_list: if self.mPkgInfos.has_key(name): ret_list.extend(self.mPkgInfos[name][0].getVariable(var)) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariable", "Package %s not found." % name) return ret_list def checkPackage(self, name): flagDBG().out(flagDBG.INFO, "PkgDB.checkPackage", "Finding " + str(name)) if self.mPkgInfos.has_key(name): return True else: flagDBG().out(flagDBG.ERROR, "PkgDB.CheckPackage", "Package %s not found." % name) return False def getVariablesAndDeps(self, pkg_list, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariablesAndDeps", "Finding " + str(variable_list) + " in " + str(pkg_list)) if DepResolutionSystem().checkPrivateRequires(): temp_var_list = [] for var in variable_list: temp_var_list.append(var.join(".private")) variable_list = variable_list + temp_var_list for name in pkg_list: if self.mPkgInfos.has_key(name): agent = DepResolutionSystem().createAgent(name) DepResolutionSystem().addResolveAgent(agent) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariablesAndDeps", "Package %s not found." % name) DepResolutionSystem().resolveDeps() pkgs = DepResolutionSystem().getPackages() var_list = [] for pkg in pkgs: if pkg: for var in variable_list: var_list.extend(tokenize(pkg.getVariable(var), pkg.getSplitChar())) return var_list def getPkgInfos(self, name): if self.mPkgInfos.has_key(name): return self.mPkgInfos[name] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getPkgInfos", "Package %s not found." % name) def exists(self, name): return self.mPkgInfos.has_key(name) def getInfo(self, name): if self.mPkgInfos.has_key(name): return [pkg.getInfo() for pkg in self.mPkgInfos[name]] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getInfo", "Package %s not found." % name) def buildPcFileDict(self): """ Builds up a dictionary of {name: list of files for name} """ pc_dict = {} for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.pc")) # List of .pc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these pc files: %s" % str(glob_list)) for g in glob_list: # Get key name and add file to value list in dictionary key = os.path.basename(g)[:-3] # Strip .pc off the filename...rstrip no worky pc_dict.setdefault(key, []).append(g) for f in Utils.getFileList(): if f.endswith(".pc"): key = os.path.basename(f)[:-3] # Strip .pc off the filename...rstrip no worky pc_dict.setdefault(key, []).append(f) return pc_dict # { "key", [ "list", "of", "corresponding", "pc", "files"] } def populatePkgInfoDBPcFiles(self): dict_to_pop_from = self.buildPcFileDict() for (pkg,files) in dict_to_pop_from.iteritems(): for f in files: self.mPkgInfos.setdefault(pkg,[]).append(PkgInfo(pkg, f, "pc")) def buildFpcFileList(self): """ Builds up a dictionary of {name: list of files for name} """ file_list = [] for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.fpc")) # List of .fpc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these fpc files: %s" % str(glob_list)) for g in glob_list: file_list.append(g) for f in Utils.getFileList(): if f.endswith(".fpc"): file_list.append(f) return file_list # [ "list", "of", "fpc", "files"] def populatePkgInfoDBFpcFiles(self): list_to_add = self.buildFpcFileList() for filename in list_to_add: var_dict = Utils.parsePcFile(filename) if not var_dict.has_key("Provides"): flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Provides" % str(filename)) continue if not var_dict.has_key("Arch"): flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Arch" % str(filename)) continue provides_string = var_dict["Provides"] provides_string = provides_string.replace(',', ' ') provides_string = provides_string.replace('(', ' ') provides_string = provides_string.replace(')', ' ') for key in provides_string.split(" "): if len(key) > 0: self.mPkgInfos.setdefault(key, []).append(PkgInfo(key, filename, "fpc", var_dict)) class PkgInfo: """ Holds the information for a package file on the system. These however are evaluated when the need arises. """ def __init__(self, name, file, type, varDict={}): self.mName = name self.mFile = file self.mIsEvaluated = False self.mType = type self.mVariableDict = varDict if self.mType == "fpc": self.mIsEvaluated = True def getVariable(self, variable): self.evaluate() return self.mVariableDict.get(variable,"") def getName(self): return self.mName def evaluate(self): if not self.mIsEvaluated: flagDBG().out(flagDBG.INFO, "PkgInfo.evaluate", "Evaluating %s" % self.mName) self.mVariableDict= Utils.parsePcFile(self.mFile) self.mIsEvaluated = True def getInfo(self): self.evaluate() return self.mVariableDict def getSplitChar(self): self.evaluate() split_char = self.mVariableDict.get("SplitCharacter", ' ') if split_char == "": split_char = ' ' return split_char class OptionsEvaluator: def __init__(self): if len(sys.argv) < 2: self.printHelp() # This is only the args....(first arg is stripped) def evaluateArgs(self, args): # Catch any args that need to be tended to immediately # Process args in the order that they were recieved. Some options are not # shown below because they are sub-options of an option below (--strip-dups) for option in args: if option.startswith("--verbose-debug"): flagDBG().setLevel(flagDBG.VERBOSE) if option.startswith("--debug"): flagDBG().setLevel(flagDBG.INFO) elif option.startswith("--from-file"): val_start = option.find('=') + 1 file = option[val_start:] Utils.EXTRA_FLAGPOLL_FILES = Utils.EXTRA_FLAGPOLL_FILES + ":" + file elif option.startswith("--help"): self.printHelp() sys.exit(0) elif option.startswith("--version"): print "%s.%s.%s" % Utils.getFlagpollVersion() sys.exit(0) elif option.startswith("--list-all"): PkgDB().printAllPackages() continue listedAgentNames = [] agent = None num_args = len(args) curr_arg = 0 output_options = [] # (option, name/"") important_options = [] # ones that need special attention while curr_arg < num_args: if args[curr_arg].startswith("--atleast-version"): val_start = args[curr_arg].find('=') + 1 atleast_version = args[curr_arg][val_start:] atleast_filter = Filter("Version", lambda x,v=atleast_version: x >= v) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(atleast_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --at-least-version") continue if args[curr_arg].startswith("--cflags-only-I"): output_options.append(("cflags-only-I", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--cflags-only-other"): output_options.append(("cflags-only-other", "")) curr_arg = curr_arg + 1 continue #This could be the catch all for the above ones to and then filter based on what is asked... #For clarity of course... if args[curr_arg].startswith("--cflags"): output_options.append(("cflags", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--extra-paths"): val_start = args[curr_arg].find('=') + 1 paths = args[curr_arg][val_start:] Utils.EXTRA_FLAGPOLL_SEARCH_PATHS = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS + ":" + paths curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--exact-version"): val_start = args[curr_arg].find('=') + 1 exact_version = args[curr_arg][val_start:] exact_filter = Filter("Version", lambda x,v=exact_version: x == v) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(exact_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --exact-version") continue if args[curr_arg].startswith("--exists"): important_options.append("exists") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--from-file"): val_start = args[curr_arg].find('=') + 1 file = args[curr_arg][val_start:] file_filter = Filter("FlagpollFilename", lambda x,f=file: x == f) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(file_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --from-file") continue if args[curr_arg].startswith("--info"): important_options.append("info") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--print-pkg-options"): important_options.append("print-pkg-options") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--keep-dups"): Utils.setKeepDups(True) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-l"): output_options.append(("libs-only-l", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-L"): output_options.append(("libs-only-L", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-other"): output_options.append(("libs-only-other", "")) curr_arg = curr_arg + 1 continue #This could be the catch all for the above ones to and then filter based on what is asked... if args[curr_arg].startswith("--libs"): output_options.append(("libs", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--require-all"): rlen = len("--require-all") req_string = args[curr_arg][rlen:] req_string = req_string.replace('-','_') curr_arg = curr_arg + 1 if req_string.find("<=") != -1: op_start = req_string.find("<=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x <= v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find(">=") != -1: op_start = req_string.find(">=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x >= v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find(">") != -1: op_start = req_string.find(">") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x > v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("<") != -1: op_start = req_string.find("<") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x < v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("=") != -1: op_start = req_string.find("=") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x == v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("=") == -1: new_filter = Filter(req_string, lambda x: len(x) > 0) DepResolutionSystem().addFilter(new_filter) continue continue if args[curr_arg].startswith("--require-"): rlen = len("--require-") req_string = args[curr_arg][rlen:] req_string = req_string.replace('-','_') curr_arg = curr_arg + 1 if agent is None: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --require") if req_string.find("<=") != -1: op_start = req_string.find("<=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x <= v) agent.addFilter(new_filter) continue if req_string.find(">=") != -1: op_start = req_string.find(">=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x >= v) agent.addFilter(new_filter) continue if req_string.find(">") != -1: op_start = req_string.find(">") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x > v) agent.addFilter(new_filter) continue if req_string.find("<") != -1: op_start = req_string.find("<") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x < v) agent.addFilter(new_filter) continue if req_string.find("=") != -1: op_start = req_string.find("=") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x == v) agent.addFilter(new_filter) continue if req_string.find("=") == -1: new_filter = Filter(req_string, lambda x: len(x) > 0) agent.addFilter(new_filter) continue continue if args[curr_arg].startswith("--no-deps"): if agent is not None: agent.setCheckDepends(False) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --no-deps") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--require="): val_start = args[curr_arg].find('=') + 1 req_var = args[curr_arg][val_start:] curr_arg = curr_arg + 1 DepResolutionSystem().makeRequireFilter(req_var) continue if args[curr_arg].startswith("--modversion"): if agent is not None: output_options.append(("Version", agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --modversion") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--max-release"): val_start = args[curr_arg].find('=') + 1 max_release = args[curr_arg][val_start:] max_filter = Filter("Version", lambda x,v=max_release: x.startswith(v)) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(max_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --max-release") continue if args[curr_arg].startswith("--static"): DepResolutionSystem().setPrivateRequires(True) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--variable"): val_start = args[curr_arg].find('=') + 1 fetch_var = args[curr_arg][val_start:] if agent is not None: output_options.append((fetch_var, agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --variable") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--get-all"): rlen = len("--get-all-") get_string = args[curr_arg][rlen:] get_string = get_string.replace('-','_') output_options.append((get_string, "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--get"): rlen = len("--get-") get_string = args[curr_arg][rlen:] get_string = get_string.replace('-','_') if agent is not None: output_options.append((get_string, agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --get") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--concat"): important_options.append("concat") curr_arg = curr_arg + 1 continue if not args[curr_arg].startswith("--"): name = args[curr_arg] curr_arg = curr_arg + 1 if PkgDB().checkPackage(name): agent = DepResolutionSystem().createResolveAgent(name) listedAgentNames.append(name) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Package %s" % name) sys.exit(1) continue if args[curr_arg] != "--debug" and args[curr_arg] != "--verbose-debug": flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Option: %s" % args[curr_arg]) curr_arg = curr_arg + 1 if len(listedAgentNames) == 0: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Must specify at least one package") DepResolutionSystem().resolveDeps() pkgs = DepResolutionSystem().getPackages() for p in pkgs: if not p: for option in important_options: if option == "exists": print "no" sys.exit(1) flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found") if len(pkgs) == 0: for option in important_options: if option == "exists": print "no" sys.exit(1) flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found") sys.exit(1) concat = False for option in important_options: if option == "exists": print "yes" return sys.exit(0) # already checked for none above if option == "concat": concat = True if option == "info": pkg_info_list = [] for pkg in pkgs: if pkg.getName() in listedAgentNames: print pkg.getName() pkg_info = pkg.getInfo() for key in pkg_info.keys(): print " %s : %s" % (key, pkg_info[key]) if option == "print-pkg-options": print "" print "All options below would start with (--get-/--get-all-/--require-/--require-all-)" print "NOTE: this list does not include the standard variables that are exported." print "" for pkg in pkgs: if pkg.getName() not in listedAgentNames: continue print "Package: " + pkg.getName() for key in pkg.getInfo().keys(): if key not in [ "Name", "Description", "URL", "Version", "Requires", "Requires.private", "Conflicts", "Libs", "Libs.private", "Cflags", "Provides", "Arch", "FlagpollFilename", "prefix" ]: print " " + key.replace('_','-') #print output_options #output_options = [] #output_single = [] #Process options here.............. concat_list = [] if concat: print_option = lambda x: concat_list.extend(x) else: print_option = lambda x: Utils.printList(x) for option in output_options: if option[0] == "cflags": print_option(Utils.stripDupIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "cflags-only-I": print_option(Utils.cflagsOnlyDirIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "cflags-only-other": print_option(Utils.cflagsOnlyOtherIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "libs-only-l": print_option(Utils.libsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs-only-L": print_option(Utils.libDirsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs-only-other": print_option(Utils.libsOnlyOtherLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs": print_option(Utils.stripDupLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) else: print_option(Utils.stripDupInList(self.getVarFromPkgs(option[0], pkgs, option[1]))) if concat: Utils.printList(Utils.stripDupInList(concat_list)) def getVarFromPkgs(self, var, pkgs, pkg_name=""): var_list = [] ext_vars = [] if var == "Libs": if DepResolutionSystem().checkPrivateRequires: ext_vars.append("Libs.private") if pkg_name == "": for pkg in pkgs: if pkg: var_list.extend(tokenize(pkg.getVariable(var), pkg.getSplitChar())) for extra_var in ext_vars: var_list.extend(tokenize(pkg.getVariable(extra_var), pkg.getSplitChar())) else: for pkg in pkgs: if pkg: if pkg.getName() == pkg_name: var_list.extend(tokenize(pkg.getVariable(var), pkg.getSplitChar())) for extra_var in ext_vars: var_list.extend(tokenize(pkg.getVariable(extra_var), pkg.getSplitChar())) return var_list def printHelp(self): print "usage: flagpoll pkg options [pkg options] [generic options]" print " " print "generic options:" print " --help show this help message and exit" print " --version output version of flagpoll" print " --list-all list all known packages" print " --debug show debug information" print " --verbose-debug show verbose debug information" print " --extra-paths=EXTRA_PATHS" print " extra paths for flagpoll to search for meta-data files" print " --concat concatenate all output and output as one line" print " --keep-dups do not strip out all duplicate info from options" print " --info show information for packages" print " --print-pkg-options show pkg specific options" print " " print "options:" print " --modversion output version for package" print " --require=REQUIRE adds additional requirements for packages ex. 32/64" print " --libs output all linker flags" print " --static output linker flags for static linking" print " --libs-only-l output -l flags" print " --libs-only-other output other libs (e.g. -pthread)" print " --libs-only-L output -L flags" print " --cflags output all pre-processor and compiler flags" print " --cflags-only-I output -I flags" print " --cflags-only-other output cflags not covered by the cflags-only-I option" print " --exists return 0 if the module(s) exist" print " --from-file=FILE use the specified FILE for the package" #print " --print-provides print which packages the package provides" #print " --print-requires print which packages the package requires" print " --no-deps do not lookup dependencies for the package" print " --atleast-version=ATLEAST_VERSION" print " return 0 if the module is at least version" print " ATLEAST_VERSION" print " --exact-version=EXACT_VERSION" print " return 0 if the module is exactly version" print " EXACT_VERSION" print " --max-release=MAX_RELEASE" print " return 0 if the module has a release that has a" print " version of MAX_RELEASE and will return the max" print " --variable=VARIABLE get the value of a variable" print " " print "dynamic options(replace VAR with a variable you want to get/filter on)" print " NOTE: replace underscores with dashes in VAR" print " NOTE: quotes are needed around <,>,= combinations" print " --get-VAR get VAR from package" print " --get-all-VAR get VAR from package and its deps" print " --require-VAR[<,>,=VAL]" print " require that a var is defined for a package" print " or optionally use equality operators against VAL" print " --require-all-VAR[<,>,=VAL]" print " require that a var is defined for all packages" print " or optionally use equality operators against VAL" print "" print "extending search path" print " FLAGPOLL_PATH environment variable that can be set to" print " extend the search path for .fpc/.pc files" print "" print "" print "Send bug reports and/or feedback to flagpoll-users@vrsource.org" sys.exit(0) def main(): # GO! # Initialize singletons and the start evaluating my_dbg = flagDBG() my_dep_system = DepResolutionSystem() opt_evaluator = OptionsEvaluator() opt_evaluator.evaluateArgs(sys.argv[1:]) sys.exit(0) if __name__ == "__main__": main()
Python
#!/usr/bin/env python # ----------------------------------------------------------------- # # Flag Poll: A tool to extract flags from installed applications # for compiling, settting variables, etc. # # Original Authors: # Daniel E. Shipton <dshipton@gmail.com> # # Flag Poll is Copyright (C) 2006 by Daniel E. Shipton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to: # Free SoftwareFoundation, Inc. # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # # ----------------------------------------------------------------- """Makes a flagpole .fpc file from user input. v0.9 coded by Jeff Groves""" import os import sys import getopt ##String prompts for the input varPrompt = """Convience variables (one 'var_name= var_definition' per line,""" + \ """ empty line when done)""" namePrompt = "Formal Name" descriptionPrompt = "Description" urlPrompt = "URL" providesPrompt = "One or more names to look package up by: (Provides)" versionPrompt = "Version (x.y.z)" architecturePrompt = "Architecture" requirePrompt = "Requires" libPrompt = "Linker Flags (-lfoo -L/usr/lib)" staticLibPrompt = "Static Linking Flags/Libs (extra private libs)" compileFlagsPrompt = "Compile/Include Flags (-I/usr -fpge -O2)" fileNamePrompt = "FPC File's Name" def usage(): """Prints a list of acceptable arguments for fpcmaker.py.""" print """ Fpcmaker.py Options: -n, --name= : Sets %s -d, --description= : Sets %s -u, --url= : Sets %s -p, --provides= : Sets %s -v, --version= : Sets %s -a, --architecture= : Sets %s -r, --requires= : Sets %s -l, --libs= : Sets %s -c, --cflags= : Sets %s -s, --static= : Sets %s -f, --file= : Sets %s """ %(namePrompt, descriptionPrompt, urlPrompt, providesPrompt, versionPrompt, architecturePrompt, requirePrompt, libPrompt, compileFlagsPrompt, staticLibPrompt, fileNamePrompt) return def checkFileName(fileName): """Checks if the fpc file name's blank, contains slashes, or exists.""" nameCleared = False writeFile = True confirms = ['y', 'Y', 'yes', 'Yes'] ##Loops until the name clears or writing the file's aborted. while(not nameCleared and writeFile): ##If it's blank, give the option of aborting the program. if fileName == "": choice = raw_input("Do you want to abort writing the" + " .fpc file? (Y/N): ") if choice not in confirms: fileName = raw_input("Please enter a different name for the" + " .fpc file: ") else: writeFile = False ##If it contains slashes, ask for another name. elif '/' in fileName or '\\' in fileName: print "I can't write to %s because it contains slashes."%(fileName) fileName = raw_input("Please enter a different name for the" + " .fpc file: ") ##If it already exists, ask if they want to overwrite. ##If not, ask for another name. elif os.path.exists(fileName): choice = raw_input("The file %s already exists." %(fileName) + " Do you want to overwrite it? (Y/N): ") if choice not in confirms: fileName = raw_input("Please enter a different name for the" + " .fpc file: ") else: nameCleared = True else: nameCleared = True return [fileName, writeFile] ##Booleans for whether that argument was sent in the command line varSet = False providesSet = False nameSet = False descriptionSet = False urlSet = False architectureSet = False versionSet = False requiresSet = False libsSet = False compileFlagsSet = False staticLibSet = False fileNameSet = False ##Get the options & arguments sent. arguments = sys.argv[1:] try: opts, args = getopt.getopt(arguments, "p:n:u:d:a:r:v:l:c:s:f:", ["provides=", "name=", "url=", "description=", "architecture=", "requires=", "version=", "libs=", "cflags=", "static=", "file="]) ##Send them usage info if they enter a wrong argument except getopt.GetoptError: usage() sys.exit(2) for opt, arg in opts: if opt in ('-p', '--provides'): providesSet = True provides = arg elif opt in ('-n', '--name'): nameSet = True name = arg elif opt in ('-v', '--version'): versionSet = True version = arg elif opt in ('-u', '--url'): urlSet = True url = arg elif opt in ('-d', '--description'): descriptionSet = True description = arg elif opt in ('-a', '--architecture'): architectureSet = True architecture = arg elif opt in ('-r', '--requires'): requiresSet = True requires = arg elif opt in ('-l', '--libs'): libsSet = True libs = arg elif opt in ('-c', '--cflags'): compileFlagsSet = True compileFlags = arg elif opt in ('-s', '--static'): staticLibSet = True staticLib = arg elif opt in ('-f', '--file'): fileNameSet = True fileName = arg ##Grab any input not passed in the arguments from the user. if not varSet: varLine = None variables = "" print "%s:" %(varPrompt) while(varLine != ""): varLine = raw_input("") variables = variables + "%s\n" %(varLine) if not nameSet: name = raw_input("%s: " %(namePrompt)) if not descriptionSet: description = raw_input("%s: " %(descriptionPrompt)) if not urlSet: url = raw_input("%s: " %(urlPrompt)) if not versionSet: version = raw_input("%s: " %(versionPrompt)) if not providesSet: provides = raw_input("%s: " %(providesPrompt)) if not requiresSet: requires = raw_input("%s: " %(requirePrompt)) if not architectureSet: architecture = raw_input("%s: " %(architecturePrompt)) if not libsSet: libs = raw_input("%s: " %(libPrompt)) if not staticLibSet: staticLib = raw_input("%s: " %(staticLibPrompt)) if not compileFlagsSet: compileFlags = raw_input("%s: " %(compileFlagsPrompt)) if not fileNameSet: fileName = raw_input("%s: " %(fileNamePrompt)) ##Check the file's name. fileName, writeFile = checkFileName(fileName) ##If they chose not to overwrite, write the file. if writeFile: fpc = open(fileName, 'w') fpc.write("%s" %(variables)) fpc.write("Name: %s\n" %(name)) fpc.write("Description: %s\n" %(description)) fpc.write("URL: %s\n" %(url)) fpc.write("Version: %s\n" %(version)) fpc.write("Provides: %s\n" %(provides)) fpc.write("Requires: %s\n" %(requires)) fpc.write("Arch: %s\n" %(architecture)) fpc.write("Libs: %s\n" %(libs)) fpc.write("Libs.private: %s\n" %(staticLib)) fpc.write("Cflags: %s\n" %(compileFlags)) fpc.close() ##TESTER: Print the file out. fpc = open(fileName, 'r') ##TESTER print fpc.read() ##TESTER fpc.close ##TESTER
Python
#!/usr/bin/env python from distutils.core import setup setup( name='flagpoll', version='0.6.0', description='Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software.', author='Daniel E. Shipton', author_email='dshipton@infiscape.com', license='GPL', url='https://realityforge.vrsource.org/view/FlagPoll/WebHome', download_url='https://realityforge.vrsource.org/view/FlagPoll/FlagpollDownloads', scripts=['flagpoll'], long_description = "Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software. Think of it as the rpm of software development. It enables developers total control over which packages, versions, architectures, etc. that they want to use meta-data from.", data_files=[('share/flagpoll', ['flagpoll.fpc']), ('share/man/man1', ['flagpoll.1']), ('share/aclocal', ['flagpoll.m4'])] )
Python
#!/usr/bin/env python # ----------------------------------------------------------------- # # Flag Poll: A tool to extract flags from installed applications # for compiling, settting variables, etc. # # Original Authors: # Daniel E. Shipton <dshipton@gmail.com> # # Flag Poll is Copyright (C) 2006 by Daniel E. Shipton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to: # Free SoftwareFoundation, Inc. # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # # ----------------------------------------------------------------- """Makes a flagpole .fpc file from user input. v0.9 coded by Jeff Groves""" import os import sys import getopt ##String prompts for the input varPrompt = """Convience variables (one 'var_name= var_definition' per line,""" + \ """ empty line when done)""" namePrompt = "Formal Name" descriptionPrompt = "Description" urlPrompt = "URL" providesPrompt = "One or more names to look package up by: (Provides)" versionPrompt = "Version (x.y.z)" architecturePrompt = "Architecture" requirePrompt = "Requires" libPrompt = "Linker Flags (-lfoo -L/usr/lib)" staticLibPrompt = "Static Linking Flags/Libs (extra private libs)" compileFlagsPrompt = "Compile/Include Flags (-I/usr -fpge -O2)" fileNamePrompt = "FPC File's Name" def usage(): """Prints a list of acceptable arguments for fpcmaker.py.""" print """ Fpcmaker.py Options: -n, --name= : Sets %s -d, --description= : Sets %s -u, --url= : Sets %s -p, --provides= : Sets %s -v, --version= : Sets %s -a, --architecture= : Sets %s -r, --requires= : Sets %s -l, --libs= : Sets %s -c, --cflags= : Sets %s -s, --static= : Sets %s -f, --file= : Sets %s """ %(namePrompt, descriptionPrompt, urlPrompt, providesPrompt, versionPrompt, architecturePrompt, requirePrompt, libPrompt, compileFlagsPrompt, staticLibPrompt, fileNamePrompt) return def checkFileName(fileName): """Checks if the fpc file name's blank, contains slashes, or exists.""" nameCleared = False writeFile = True confirms = ['y', 'Y', 'yes', 'Yes'] ##Loops until the name clears or writing the file's aborted. while(not nameCleared and writeFile): ##If it's blank, give the option of aborting the program. if fileName == "": choice = raw_input("Do you want to abort writing the" + " .fpc file? (Y/N): ") if choice not in confirms: fileName = raw_input("Please enter a different name for the" + " .fpc file: ") else: writeFile = False ##If it contains slashes, ask for another name. elif '/' in fileName or '\\' in fileName: print "I can't write to %s because it contains slashes."%(fileName) fileName = raw_input("Please enter a different name for the" + " .fpc file: ") ##If it already exists, ask if they want to overwrite. ##If not, ask for another name. elif os.path.exists(fileName): choice = raw_input("The file %s already exists." %(fileName) + " Do you want to overwrite it? (Y/N): ") if choice not in confirms: fileName = raw_input("Please enter a different name for the" + " .fpc file: ") else: nameCleared = True else: nameCleared = True return [fileName, writeFile] ##Booleans for whether that argument was sent in the command line varSet = False providesSet = False nameSet = False descriptionSet = False urlSet = False architectureSet = False versionSet = False requiresSet = False libsSet = False compileFlagsSet = False staticLibSet = False fileNameSet = False ##Get the options & arguments sent. arguments = sys.argv[1:] try: opts, args = getopt.getopt(arguments, "p:n:u:d:a:r:v:l:c:s:f:", ["provides=", "name=", "url=", "description=", "architecture=", "requires=", "version=", "libs=", "cflags=", "static=", "file="]) ##Send them usage info if they enter a wrong argument except getopt.GetoptError: usage() sys.exit(2) for opt, arg in opts: if opt in ('-p', '--provides'): providesSet = True provides = arg elif opt in ('-n', '--name'): nameSet = True name = arg elif opt in ('-v', '--version'): versionSet = True version = arg elif opt in ('-u', '--url'): urlSet = True url = arg elif opt in ('-d', '--description'): descriptionSet = True description = arg elif opt in ('-a', '--architecture'): architectureSet = True architecture = arg elif opt in ('-r', '--requires'): requiresSet = True requires = arg elif opt in ('-l', '--libs'): libsSet = True libs = arg elif opt in ('-c', '--cflags'): compileFlagsSet = True compileFlags = arg elif opt in ('-s', '--static'): staticLibSet = True staticLib = arg elif opt in ('-f', '--file'): fileNameSet = True fileName = arg ##Grab any input not passed in the arguments from the user. if not varSet: varLine = None variables = "" print "%s:" %(varPrompt) while(varLine != ""): varLine = raw_input("") variables = variables + "%s\n" %(varLine) if not nameSet: name = raw_input("%s: " %(namePrompt)) if not descriptionSet: description = raw_input("%s: " %(descriptionPrompt)) if not urlSet: url = raw_input("%s: " %(urlPrompt)) if not versionSet: version = raw_input("%s: " %(versionPrompt)) if not providesSet: provides = raw_input("%s: " %(providesPrompt)) if not requiresSet: requires = raw_input("%s: " %(requirePrompt)) if not architectureSet: architecture = raw_input("%s: " %(architecturePrompt)) if not libsSet: libs = raw_input("%s: " %(libPrompt)) if not staticLibSet: staticLib = raw_input("%s: " %(staticLibPrompt)) if not compileFlagsSet: compileFlags = raw_input("%s: " %(compileFlagsPrompt)) if not fileNameSet: fileName = raw_input("%s: " %(fileNamePrompt)) ##Check the file's name. fileName, writeFile = checkFileName(fileName) ##If they chose not to overwrite, write the file. if writeFile: fpc = open(fileName, 'w') fpc.write("%s" %(variables)) fpc.write("Name: %s\n" %(name)) fpc.write("Description: %s\n" %(description)) fpc.write("URL: %s\n" %(url)) fpc.write("Version: %s\n" %(version)) fpc.write("Provides: %s\n" %(provides)) fpc.write("Requires: %s\n" %(requires)) fpc.write("Arch: %s\n" %(architecture)) fpc.write("Libs: %s\n" %(libs)) fpc.write("Libs.private: %s\n" %(staticLib)) fpc.write("Cflags: %s\n" %(compileFlags)) fpc.close() ##TESTER: Print the file out. fpc = open(fileName, 'r') ##TESTER print fpc.read() ##TESTER fpc.close ##TESTER
Python
#!/usr/bin/env python # ----------------------------------------------------------------- # # Flagpoll: A tool to extract flags from installed applications # for compiling, settting variables, etc. # # Original Authors: # Daniel E. Shipton <dshipton@gmail.com> # # Flagpoll is Copyright (C) 2006 by Daniel E. Shipton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to: # Free SoftwareFoundation, Inc. # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # # ----------------------------------------------------------------- from optparse import OptionParser import sys, os, glob, os.path, copy, platform pj = os.path.join #################################################################### # SNAGGED FROM PYTHON 2.4 for versions under 2.4 #################################################################### import re as _re class _multimap: """Helper class for combining multiple mappings. Used by .{safe_,}substitute() to combine the mapping and keyword arguments. """ def __init__(self, primary, secondary): self._primary = primary self._secondary = secondary def __getitem__(self, key): try: return self._primary[key] except KeyError: return self._secondary[key] class _TemplateMetaclass(type): pattern = r""" %(delim)s(?: (?P<escaped>%(delim)s) | # Escape sequence of two delimiters (?P<named>%(id)s) | # delimiter and a Python identifier {(?P<braced>%(id)s)} | # delimiter and a braced identifier (?P<invalid>) # Other ill-formed delimiter exprs ) """ def __init__(cls, name, bases, dct): super(_TemplateMetaclass, cls).__init__(name, bases, dct) if 'pattern' in dct: pattern = cls.pattern else: pattern = _TemplateMetaclass.pattern % { 'delim' : _re.escape(cls.delimiter), 'id' : cls.idpattern, } cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE) class Template: """A string class for supporting $-substitutions.""" __metaclass__ = _TemplateMetaclass delimiter = '$' idpattern = r'[_a-z][_a-z0-9]*' def __init__(self, template): self.template = template # Search for $$, $identifier, ${identifier}, and any bare $'s def _invalid(self, mo): i = mo.start('invalid') lines = self.template[:i].splitlines(True) if not lines: colno = 1 lineno = 1 else: colno = i - len(''.join(lines[:-1])) lineno = len(lines) raise ValueError('Invalid placeholder in string: line %d, col %d' % (lineno, colno)) def substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): # Check the most common path first. named = mo.group('named') or mo.group('braced') if named is not None: val = mapping[named] # We use this idiom instead of str() because the latter will # fail if val is a Unicode containing non-ASCII characters. return '%s' % val if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: self._invalid(mo) raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) def safe_substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): named = mo.group('named') if named is not None: try: # We use this idiom instead of str() because the latter # will fail if val is a Unicode containing non-ASCII return '%s' % mapping[named] except KeyError: return self.delimiter + named braced = mo.group('braced') if braced is not None: try: return '%s' % mapping[braced] except KeyError: return self.delimiter + '{' + braced + '}' if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: return self.delimiter raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) #################################################################### # End Snagging #################################################################### class Utils: # Holds collection of small utility functions EXTRA_FLAGPOLL_SEARCH_PATHS = "" EXTRA_FLAGPOLL_FILES = "" path_list_cache = None # Cache of found path lists. (only calcuate once) KEEP_DUPS = False def getFlagpollVersion(): FLAGPOLL_MAJOR_VERSION = 0 FLAGPOLL_MINOR_VERSION = 6 FLAGPOLL_PATCH_VERSION = 0 return ( FLAGPOLL_MAJOR_VERSION, FLAGPOLL_MINOR_VERSION, FLAGPOLL_PATCH_VERSION ) getFlagpollVersion = staticmethod(getFlagpollVersion) def getPathList(): if None != Utils.path_list_cache: return Utils.path_list_cache #TODO: expand LD_LIBRARY_PATH to 64/32/etc??? pkg_cfg_dir = [] flg_cfg_dir = [] ld_path = [] if os.environ.has_key("PKG_CONFIG_PATH"): pkg_cfg_dir = os.environ["PKG_CONFIG_PATH"].split(os.pathsep) if os.environ.has_key("FLAGPOLL_PATH"): flg_cfg_dir = os.environ["FLAGPOLL_PATH"].split(os.pathsep) if os.environ.has_key("LD_LIBRARY_PATH"): ld_path = os.environ["LD_LIBRARY_PATH"].split(os.pathsep) ld_path_pkg = [pj(p,'pkgconfig') for p in ld_path] ld_path_flg = [pj(p,'flagpoll') for p in ld_path] ld_path = [] ld_path.extend(ld_path_pkg) ld_path.extend(ld_path_flg) extra_paths = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS.split(os.pathsep) path_list = ["/usr/lib64/pkgconfig", "/usr/lib/pkgconfig", "/usr/share/pkgconfig", "/usr/lib64/flagpoll", "/usr/lib/flagpoll", "/usr/share/flagpoll"] path_list.extend(pkg_cfg_dir) path_list.extend(flg_cfg_dir) path_list.extend(extra_paths) path_list.extend(ld_path) flagDBG().out(flagDBG.VERBOSE, "Utils.getPathList", "Potential path list: " + str(path_list)) path_list = [p for p in path_list if os.path.exists(p)] flagDBG().out(flagDBG.INFO, "Utils.getPathList", "Using path list: " + str(path_list)) Utils.path_list_cache = path_list return path_list getPathList = staticmethod(getPathList) def getFileList(): flist = Utils.EXTRA_FLAGPOLL_FILES.split(":") filelist = [] for f in flist: if os.path.isfile(f): filelist.append(f) return filelist getFileList = staticmethod(getFileList) def setKeepDups(keep_dups): Utils.KEEP_DUPS = keep_dups setKeepDups = staticmethod(setKeepDups) def stripDupInList(gen_list): new_list = [] for item in gen_list: item = item.strip() if Utils.KEEP_DUPS: if len(item) > 0: new_list.append(item) continue if item not in new_list: if len(item) > 0: new_list.append(item) return new_list stripDupInList = staticmethod(stripDupInList) def stripDupLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] dir_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-L") or flg.startswith("-R"): dir_list.append(flg) else: lib_list.append(flg) new_list = dir_list + lib_list return Utils.stripDupInList(new_list) stripDupLinkerFlags = staticmethod(stripDupLinkerFlags) def stripDupIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] extra_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-I"): inc_list.append(flg) else: extra_list.append(flg) extra_list.sort() new_list = inc_list + extra_list return Utils.stripDupInList(new_list) stripDupIncludeFlags = staticmethod(stripDupIncludeFlags) def cflagsOnlyDirIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-I"): inc_list.append(flg) return Utils.stripDupInList(inc_list) cflagsOnlyDirIncludeFlags = staticmethod(cflagsOnlyDirIncludeFlags) def cflagsOnlyOtherIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though extra_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if not flg.startswith("-I"): extra_list.append(flg) return Utils.stripDupInList(extra_list) cflagsOnlyOtherIncludeFlags = staticmethod(cflagsOnlyOtherIncludeFlags) def libsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-l"): lib_list.append(flg) return Utils.stripDupInList(lib_list) libsOnlyLinkerFlags = staticmethod(libsOnlyLinkerFlags) def libsOnlyOtherLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though other_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if not flg.startswith("-l") and not flg.startswith("-L") and not flg.startswith("-R"): other_list.append(flg) return Utils.stripDupInList(other_list) libsOnlyOtherLinkerFlags = staticmethod(libsOnlyOtherLinkerFlags) def libDirsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though dir_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-L") or flg.startswith("-R"): dir_list.append(flg) return Utils.stripDupInList(dir_list) libDirsOnlyLinkerFlags = staticmethod(libDirsOnlyLinkerFlags) def printList(gen_list): list_string = "" for item in gen_list: if len(item) > 0: list_string+=str(item) list_string+=" " print list_string.strip() printList = staticmethod(printList) def parsePcFile(filename): lines = open(filename).readlines() fvars = {} fvars["XXFlagpollFilenameXX"] = filename lokals = {} lokals["fp_file_cwd"] = str(filename[:- ((len(os.path.basename(filename) ) + 1))]) lines.append("prefix: ${prefix}") for line in lines: line = line.strip() if not line: continue if line.startswith("#"): continue eq_pos = line.find('=') col_pos = line.find(':') if eq_pos < col_pos and eq_pos != -1 or col_pos == -1 and eq_pos !=-1: # local variable name, val = line.split('=', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(lokals) except ValueError: flagDBG().out(flagDBG.WARN, "PkgInfo.parse", "%s has an invalid metadata file" % filename) lokals[name] = val if col_pos < eq_pos and col_pos != -1 or eq_pos == -1 and col_pos !=-1: # exported variable name, val = line.split(':', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(lokals) except ValueError: flagDBG().out(flagDBG.ERROR, "PkgInfo.parse", "%s has an invalid metadata file" % filename) fvars[name] = val return fvars parsePcFile = staticmethod(parsePcFile) class flagDBG(object): # Logging class is really easy to use # Levels: # 0 - VERBOSE # 1 - INFO # 2 - WARN # 3 - ERROR VERBOSE=0 INFO=1 WARN=2 ERROR=3 __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if flagDBG.__initialized: return flagDBG.__initialized = True self.mLevel = self.WARN self.mLevelList = ["VERBOSE","INFO","WARN","ERROR"] def setLevel(self, level): if level <= 3: self.mLevel = level def out(self, level, obj, message): if level == self.ERROR: if self.mLevel == self.VERBOSE: print self.mLevelList[level] + ":" + str(obj) + ": " + str(message) else: print self.mLevelList[level] + ": " + str(message) sys.exit(1) if level >= self.mLevel: print self.mLevelList[level] + ":" + str(obj) + ": " + str(message) class DepResolutionSystem(object): """ You add PkgAgents with Filters into system and call resolve() you can check for succes by depsSatisfied() and get the list of packages that work back by calling getPackages() """ __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if DepResolutionSystem.__initialized: return DepResolutionSystem.__initialized = True self.mResolveAgents = [] self.mAgentDict = {} self.mFilters = [] self.mResolveAgentFilters = [] self.mInvalidPackageList = [] self.mSatisfied = False self.mAgentChangeList = [] # list of those responsible for adding Filters # to agents in higher in the chain than them # these are the first agents to ask that they pick # the next best package of them self.mAgentsVisitedList = [] # list of Agents that have been visited self.mResolvedPackageList = [] # list that is generated when deps are satified self.mCheckPrivateRequires = False self.mMadeDependList = False def getFilters(self): return self.mFilters def addFilter(self, filter): self.mFilters.append(filter) def addResolveAgentFilter(self, filter): self.mResolveAgentFilters.append(filter) def makeRequireFilter(self, requires): arch_list = [] arch_list.append("no_arch") arch_list.append("") if platform.system() == "Linux": if requires == "64": arch_list.append("x86_64") if requires == "32": arch_list.append("i386") arch_list.append("i586") arch_list.append("i686") if platform.system() == "Darwin": if requires == "64": arch_list.append("ppc64") if requires == "32": arch_list.append("ppc") new_filter = Filter("Arch", lambda x: x in arch_list) self.addFilter(new_filter) def createAgent(self, name): if self.checkAgentExists(name): return self.getAgent(name) else: agent = PkgAgent(name) flagDBG().out(flagDBG.INFO, "DepResSys.createAgent", "Adding %s" % name) self.addNewAgent(agent) return agent def createResolveAgent(self, name): if self.checkAgentExists(name): return self.getAgent(name) else: agent = PkgAgent(name) flagDBG().out(flagDBG.INFO, "DepResSys.createResloveAgent", "Adding %s" % name) self.addResolveAgent(agent) return agent def setPrivateRequires( self, req ): self.mCheckPrivateRequires = req def checkPrivateRequires(self): return self.mCheckPrivateRequires def checkAgentExists(self, name): return self.mAgentDict.has_key(name) def getAgent(self, name): if self.mAgentDict.has_key(name): return self.mAgentDict[name] else: flagDBG().out(flagDBG.ERROR, "DepResSys.getAgent", "Agent %s does not exist" % name) def addNewAgent(self, agent): if not self.checkAgentExists(agent): self.mAgentDict[agent.getName()] = agent def addResolveAgent(self, agent): if agent not in self.mResolveAgents: self.mResolveAgents.append(agent) for filt in self.mResolveAgentFilters: agent.addFilter(filt) def isSatisfied(self): return self.mSatisfied def updateResolvedPackages(self): pkg_list = [] agent_list = [] for agent in self.mResolveAgents: list_of_pkgs = agent.getCurrentPackageList(agent_list) pkg_list.extend(list_of_pkgs) self.mResolvedPackageList = pkg_list def getPackages(self): flagDBG().out(flagDBG.VERBOSE, "DepResSys.getPackages", "Generating list of valid packages ") #str([pkg.getCurrentPa.getName() for pkg in self.mResolvedPackageList])) # If this comes back empty then there isn't a valid set of packages to use self.updateResolvedPackages() return self.mResolvedPackageList def checkFiltersChanged(self): list_to_use = [] return True in [pkg.filtersChanged(list_to_use) for pkg in self.mResolveAgents] def resolveHelper(self): self.resolveAgentsChanged = True while self.resolveAgentsChanged: for agent in self.mResolveAgents: flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveHelper", "Updating " + agent.getName()) agent.update(self.mAgentsVisitedList, self.mAgentChangeList) self.resolveAgentsChanged = self.checkFiltersChanged() # Ask mResolveAgents if they are done(they ask sub people) unless they are # really above you in the walk # If there were changes...run update on mResolveAgents again # at the end ask for pkglist..if it comes back empty then we don't # have a usable configuration for those packages def resolveDeps(self): if not self.mMadeDependList: for agent in self.mResolveAgents: agent.makeDependList() self.mMadeDependList = True self.resolveHelper() self.updateResolvedPackages() # Check if the first round through we found something # Otherwise we need to start removing packages that aren't viable # during the loop self.mSatisfied = (len(self.mResolvedPackageList) != 0) # remove top of packages that added Filters. # then move on to resolving again # remove more if neccesary agentChangeNumber = 0 while not self.mResolvedPackageList: if(self.mAgentChangeList[agentChangeNumber]): if self.mAgentChangeList[agentChangeNumber] in self.mInvalidPackageList: agentChangeNumber+=1 else: if(self.mAgentChangeList[agentChangeNumber].getViablePackages()): flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveDeps", "Removing bad pkg from " + self.mAgentChangeList[agentChangeNumber].getName()) self.mInvalidPackageList.append(self.mAgentChangeList[agentChangeNumber].removeCurrentPackage()) else: flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveDeps", "No combinations.. Resetting " + self.mAgentChangeList[agentChangeNumber].getName()) self.mAgentChangeList[agentChangeNumber].reset() agentChangeNumber+=1 self.resolveHelper() self.updateResolvedPackages() self.mSatisfied = (len(self.mResolvedPackageList) != 0) return class PkgAgent: """ Agent that keeps track of the versions for a package given some filters and the addition of Filters """ # Makes a PkgAgent that finds its current package with the version reqs def __init__(self, name): if DepResolutionSystem().checkAgentExists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "Package Agent %s already exists" % self.mName) self.mName = name flagDBG().out(flagDBG.VERBOSE, "PkgAgent", "Creating:" + str(self.mName)) if not PkgDB().exists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "No info for package: %s" % self.mName) #XXX Doesn't keep filters added for a redo... DepResolutionSystem().addNewAgent(self) self.mFilterList = [] self.mFilterList.extend(DepResolutionSystem().getFilters()) self.mBasePackageList = PkgDB().getPkgInfos(name) for filt in self.mFilterList: self.mBasePackageList = filt.filter(self.mBasePackageList) if len(self.mBasePackageList) == 0: flagDBG().out(flagDBG.ERROR, "PkgAgent", "No viable packages for: %s" % self.mName) self.mViablePackageList = copy.deepcopy(self.mBasePackageList) if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mAgentDependList = [] # Agents that it depends on/needs to update #self.makeDependList() self.mFiltersChanged = True self.mCheckDepends = True def getName(self): return self.mName def setCheckDepends(self, tf): self.mCheckDepends = tf #Filter("Version", lambda x: x == "4.5") def makeDependList(self): if not self.mCheckDepends: self.mAgentDependList = [] return dep_list = [] if self.mCurrentPackage: req_string = self.mCurrentPackage.getVariable("Requires") if DepResolutionSystem().checkPrivateRequires(): req_string = req_string + " " + self.mCurrentPackage.getVariable("Requires.private") req_string = req_string.strip() if req_string == "": return req_string = req_string.replace(',', ' ') req_string = req_string.replace('(', ' ') req_string = req_string.replace(')', ' ') space_req_string_list = req_string.split(' ') req_string_list = [] for entry in space_req_string_list: if len(entry) > 0: req_string_list.append(entry) i = 0 flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList", self.mCurrentPackage.getName() + " requires: " + str(req_string_list)) while len(req_string_list) > i: if PkgDB().exists(req_string_list[i]): new_filter = [] new_agent = DepResolutionSystem().createAgent(req_string_list[i]) if len(req_string_list) > i+1: if req_string_list[i+1] == "=": ver_to_filt = req_string_list[i+2] new_filter = Filter("Version", lambda x: x == ver_to_filt) elif req_string_list[i+1] == "<=": ver_to_filt = req_string_list[i+2] new_filter = Filter("Version", lambda x: x <= ver_to_filt) elif req_string_list[i+1] == ">=": ver_to_filt = req_string_list[i+2] new_filter = Filter("Version", lambda x: x >= ver_to_filt) else: i+=1 else: i+=1 dep_list.append(new_agent) if new_filter: i+=3 new_agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "PkgAgent.makeDependList", "Package %s depends on %s but does not seem to be installed." % (self.mName, str(req_string_list[i]))) flagDBG().out(flagDBG.VERBOSE, "PkgAgent.makeDependList", "List is:" + str([pkg.getName() for pkg in dep_list])) self.mAgentDependList = dep_list def filtersChanged(self,packageList): tf_list = [self.mFiltersChanged] if self.mName not in packageList: packageList.append(self.mName) for pkg in self.mAgentDependList: tf_list.append(pkg.filtersChanged(packageList)) return True in tf_list def getCurrentPackageList(self, packageList): pkgs = [] if self.mName not in packageList: flagDBG().out(flagDBG.VERBOSE, "PkgAgent.getCurrentPackageList", "Package: %s" % self.mName) pkgs.append(self.mCurrentPackage) packageList.append(self.mName) for pkg in self.mAgentDependList: pkgs.extend(pkg.getCurrentPackageList(packageList)) return pkgs # current pkginfo for me def getCurrentPkgInfo(self): return self.mCurrentPackage # Someone else usually places these on me # I keep track of those separately def addFilter(self, filter): flagDBG().out(flagDBG.VERBOSE, "PkgAgent.addFilter", "Adding a Filter to %s" % self.mName) self.mFiltersChanged = True self.mFilterList.append(filter) def removeCurrentPackage(self): flagDBG().out(flagDBG.VERBOSE, "PkgAgent.removeCurrentPackage", "Removing current package of %s" % self.mName) if self.mViablePackageList: ret_val = self.mViablePackageList[0] in self.mBasePackageList del self.mViablePackageList[0] if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] return ret_val def update(self, agentVisitedList, agentChangeList): if self.mName in agentVisitedList: return agentVisitedList.append(self.mName) if self.mFiltersChanged: self.mFiltersChanged = False self.updateFilters() # TODO: checkFilters and add them # if a pkg is in visitedList then add yourself to agentChangeList for pkg in self.mAgentDependList: pkg.update(agentVisitedList, agentChangeList) return def updateFilters(self): for filt in self.mFilterList: self.mViablePackageList = filt.filter(self.mViablePackageList) if len(self.mViablePackageList) > 0: self.mCurrentPackage = self.mViablePackageList[0] else: self.mCurrentPackage = [] def reset(self): flagDBG().out(flagDBG.VERBOSE, "PkgAgent.reset", "Resetting package: %s" % self.mName) self.mViablePackageList = self.mBasePackageList if self.mViablePackageList: self.mCurrentPacakge = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mFilterList = DepResolutionSystem().getFilters() self.mAgentDependList = [] self.mFiltersChanged = True return class Filter: """ A single Filter that knows how to filter the list it recieves Will be inheireted....?..? """ def __init__(self, variableName, testCallable): self.mVarName = variableName self.mTestCallable = testCallable def filter(self, pkg_info_list): ret_pkg_list = [] # Filter first for pkg in pkg_info_list: var = pkg.getVariable(self.mVarName) if self.mTestCallable(var): ret_pkg_list.append(pkg) # Now sort ret_pkg_list.sort(lambda lhs,rhs: cmp(lhs.getVariable(self.mVarName), rhs.getVariable(self.mVarName))) return ret_pkg_list #requires: qt == 4.5 #Filter("Version", lambda x: x <= "4.5") #Filter("Version", lambda x: x <= "4.5") class PkgDB(object): """ Holds all the neccesary information to evaluate itself when needed. Is in charge of holding a list of PkgInfo's that contain info about the package. """ __initialized = False def __init__(self): if self.__initialized: return self.__initialized = True self.mPkgInfos = {} # {pkg_name: List of package infos} self.populatePkgInfoDBPcFiles() self.populatePkgInfoDBFpcFiles() def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def printAllPackages(self): list_of_package_names = [] for pkg in self.mPkgInfos: list_of_package_names.append(pkg) for name in list_of_package_names: print name sys.exit(0) def getVariables(self, name, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariable", "Finding " + str(variable_list) + " in " + str(name)) ret_list = [] for var in variable_list: if self.mPkgInfos.has_key(name): ret_list.extend(self.mPkgInfos[name][0].getVariable(var)) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariable", "Package %s not found." % name) return ret_list def checkPackage(self, name): flagDBG().out(flagDBG.INFO, "PkgDB.checkPackage", "Finding " + str(name)) if self.mPkgInfos.has_key(name): return True else: flagDBG().out(flagDBG.ERROR, "PkgDB.CheckPackage", "Package %s not found." % name) return False def getVariablesAndDeps(self, pkg_list, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariablesAndDeps", "Finding " + str(variable_list) + " in " + str(pkg_list)) if DepResolutionSystem().checkPrivateRequires(): temp_var_list = [] for var in variable_list: temp_var_list.append(var.join(".private")) variable_list = variable_list + temp_var_list for name in pkg_list: if self.mPkgInfos.has_key(name): agent = DepResolutionSystem().createAgent(name) DepResolutionSystem().addResolveAgent(agent) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariablesAndDeps", "Package %s not found." % name) DepResolutionSystem().resolveDeps() pkgs = DepResolutionSystem().getPackages() var_list = [] for pkg in pkgs: if pkg: for var in variable_list: var_list.extend(pkg.getVariable(var).split(' ')) return var_list def getPkgInfos(self, name): if self.mPkgInfos.has_key(name): return self.mPkgInfos[name] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getPkgInfos", "Package %s not found." % name) def exists(self, name): return self.mPkgInfos.has_key(name) def getInfo(self, name): if self.mPkgInfos.has_key(name): return [pkg.getInfo() for pkg in self.mPkgInfos[name]] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getInfo", "Package %s not found." % name) def buildPcFileDict(self): """ Builds up a dictionary of {name: list of files for name} """ pc_dict = {} for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.pc")) # List of .pc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these pc files: %s" % str(glob_list)) for g in glob_list: # Get key name and add file to value list in dictionary key = os.path.basename(g)[:-3] # Strip .pc off the filename...rstrip no worky pc_dict.setdefault(key,[]).append(g) for f in Utils.getFileList(): if f.endswith(".pc"): key = os.path.basename(f)[:-3] # Strip .pc off the filename...rstrip no worky pc_dict.setdefault(key,[]).append(f) return pc_dict # { "key", [ "list", "of", "corresponding", "pc", "files"] } def populatePkgInfoDBPcFiles(self): dict_to_pop_from = self.buildPcFileDict() for (pkg,files) in dict_to_pop_from.iteritems(): for f in files: self.mPkgInfos.setdefault(pkg,[]).append(PkgInfo(pkg, f, "pc")) def buildFpcFileList(self): """ Builds up a dictionary of {name: list of files for name} """ file_list = [] for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.fpc")) # List of .fpc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these fpc files: %s" % str(glob_list)) for g in glob_list: file_list.append(g) for f in Utils.getFileList(): if f.endswith(".fpc"): file_list.append(f) return file_list # [ "list", "of", "fpc", "files"] def populatePkgInfoDBFpcFiles(self): list_to_add = self.buildFpcFileList() for filename in list_to_add: var_dict = Utils.parsePcFile(filename) if not var_dict.has_key("Provides"): flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Provides" % str(filename)) continue if not var_dict.has_key("Arch"): flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Arch" % str(filename)) continue provides_string = var_dict["Provides"] provides_string = provides_string.replace(',', ' ') provides_string = provides_string.replace('(', ' ') provides_string = provides_string.replace(')', ' ') for key in provides_string.split(" "): if len(key) > 0: self.mPkgInfos.setdefault(key,[]).append(PkgInfo(key, filename, "fpc", var_dict)) class PkgInfo: """ Holds the information for a package file on the system. These however are evaluated when the need arises. """ def __init__(self, name, file, type, varDict={}): self.mName = name self.mFile = file self.mIsEvaluated = False self.mType = type self.mVariableDict = varDict if self.mType == "fpc": self.mIsEvaluated = True def getVariable(self, variable): self.evaluate() return self.mVariableDict.get(variable,"") def getName(self): return self.mName def evaluate(self): if not self.mIsEvaluated: flagDBG().out(flagDBG.INFO, "PkgInfo.evaluate", "Evaluating %s" % self.mName) self.mVariableDict= Utils.parsePcFile(self.mFile) self.mIsEvaluated = True def getInfo(self): self.evaluate() return self.mVariableDict class OptionsEvaluator: def __init__(self): #self.mOptParser = self.GetOptionParser() #self.mOptParser.print_help() if len(sys.argv) < 2: self.printHelp() #(self.mOptions, self.mArgs) = self.mOptParser.parse_args() #if self.mOptions.version: # print "%s.%s.%s" % Utils.getFlagpollVersion() # sys.exit(0) #if len(self.mArgs) < 1: # self.mOptParser.print_help() # sys.exit(1) # This is only the args....(first arg is stripped) def evaluateArgs(self, args): # Catch any args that need to be tended to immediately # Process args in the order that they were recieved. Some options are not # shown below because they are sub-options of an option below (--strip-dups) for option in args: if option.startswith("--debug"): flagDBG().setLevel(flagDBG.VERBOSE) elif option.startswith("--from-file"): val_start = option.find('=') + 1 file = option[val_start:] Utils.EXTRA_FLAGPOLL_FILES = Utils.EXTRA_FLAGPOLL_FILES + ":" + file elif option.startswith("--help"): self.printHelp() sys.exit(0) elif option.startswith("--version"): print "%s.%s.%s" % Utils.getFlagpollVersion() sys.exit(0) elif option.startswith("--list-all"): PkgDB().printAllPackages() continue agent = None num_args = len(args) curr_arg = 0 output_options = [] # (option, name/"") important_options = [] # ones that need special attention while curr_arg < num_args: if args[curr_arg].startswith("--atleast-version"): val_start = args[curr_arg].find('=') + 1 atleast_version = args[curr_arg][val_start:] atleast_filter = Filter("Version", lambda x: x >= atleast_version) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(atleast_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --at-least-version") continue if args[curr_arg].startswith("--cflags-only-I"): output_options.append(("cflags-only-I", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--cflags-only-other"): output_options.append(("cflags-only-other", "")) curr_arg = curr_arg + 1 continue #This could be the catch all for the above ones to and then filter based on what is asked... #For clarity of course... if args[curr_arg].startswith("--cflags"): output_options.append(("cflags", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--extra-paths"): val_start = args[curr_arg].find('=') + 1 paths = args[curr_arg][val_start:] Utils.EXTRA_FLAGPOLL_SEARCH_PATHS = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS + ":" + paths curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--exact-version"): val_start = args[curr_arg].find('=') + 1 exact_version = args[curr_arg][val_start:] exact_filter = Filter("Version", lambda x: x == exact_version) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(exact_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --exact-version") continue if args[curr_arg].startswith("--exists"): important_options.append("exists") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--from-file"): val_start = args[curr_arg].find('=') + 1 file = args[curr_arg][val_start:] file_filter = Filter("XXFlagpollFilenameXX", lambda x: x == file) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(file_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --from-file") continue if args[curr_arg].startswith("--info"): important_options.append("info") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--keep-dups"): Utils.setKeepDups(True) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-l"): output_options.append(("libs-only-l", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-L"): output_options.append(("libs-only-L", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-other"): output_options.append(("libs-only-other", "")) curr_arg = curr_arg + 1 continue #This could be the catch all for the above ones to and then filter based on what is asked... if args[curr_arg].startswith("--libs"): output_options.append(("libs", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--require-all"): rlen = len("--require-all") req_string = args[curr_arg][rlen:] req_string = req_string.replace('-','_') curr_arg = curr_arg + 1 if req_string.find("<=") != -1: op_start = req_string.find("<=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x: x <= req_val) DepResolutionSystem().addFilter(new_filter) continue if req_string.find(">=") != -1: op_start = req_string.find(">=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x: x >= req_val) DepResolutionSystem().addFilter(new_filter) continue if req_string.find(">") != -1: op_start = req_string.find(">") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x > req_val) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("<") != -1: op_start = req_string.find("<") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x < req_val) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("=") != -1: op_start = req_string.find("=") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x == req_val) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("=") == -1: new_filter = Filter(req_string, lambda x: len(x) > 0) DepResolutionSystem().addFilter(new_filter) continue continue if args[curr_arg].startswith("--require-"): rlen = len("--require-") req_string = args[curr_arg][rlen:] req_string = req_string.replace('-','_') curr_arg = curr_arg + 1 if agent is None: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --require") if req_string.find("<=") != -1: op_start = req_string.find("<=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x: x <= req_val) agent.addFilter(new_filter) continue if req_string.find(">=") != -1: op_start = req_string.find(">=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x: x >= req_val) agent.addFilter(new_filter) continue if req_string.find(">") != -1: op_start = req_string.find(">") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x > req_val) agent.addFilter(new_filter) continue if req_string.find("<") != -1: op_start = req_string.find("<") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x < req_val) agent.addFilter(new_filter) continue if req_string.find("=") != -1: op_start = req_string.find("=") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x == req_val) agent.addFilter(new_filter) continue if req_string.find("=") == -1: new_filter = Filter(req_string, lambda x: len(x) > 0) agent.addFilter(new_filter) continue continue if args[curr_arg].startswith("--no-deps"): if agent is not None: agent.setCheckDepends(False) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --no-deps") if args[curr_arg].startswith("--require="): val_start = args[curr_arg].find('=') + 1 req_var = args[curr_arg][val_start:] curr_arg = curr_arg + 1 DepResolutionSystem().makeRequireFilter(req_var) continue if args[curr_arg].startswith("--modversion"): if agent is not None: output_options.append(("Version", agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --modversion") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--max-release"): val_start = args[curr_arg].find('=') + 1 max_release = args[curr_arg][val_start:] max_filter = Filter("Version", lambda x: x.startswith(max_release)) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(max_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --max-release") continue if args[curr_arg].startswith("--static"): DepResolutionSystem().setPrivateRequires(True) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--variable"): val_start = args[curr_arg].find('=') + 1 fetch_var = args[curr_arg][val_start:] if agent is not None: output_options.append((fetch_var, agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --variable") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--get-all"): rlen = len("--get-all-") get_string = args[curr_arg][rlen:] get_string = get_string.replace('-','_') output_options.append((get_string, "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--get"): rlen = len("--get-") get_string = args[curr_arg][rlen:] get_string = get_string.replace('-','_') if agent is not None: output_options.append((get_string, agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --get") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--concat"): important_options.append("concat") curr_arg = curr_arg + 1 continue if not args[curr_arg].startswith("--"): name = args[curr_arg] curr_arg = curr_arg + 1 if PkgDB().checkPackage(name): agent = DepResolutionSystem().createResolveAgent(name) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Package %s" % name) sys.exit(1) continue if args[curr_arg] != "--debug": flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Option: %s" % args[curr_arg]) curr_arg = curr_arg + 1 DepResolutionSystem().resolveDeps() pkgs = DepResolutionSystem().getPackages() for p in pkgs: if not p: for option in important_options: if option == "exists": print "no" sys.exit(1) flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found") if len(pkgs) == 0: for option in important_options: if option == "exists": print "no" sys.exit(1) flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found") sys.exit(1) concat = False for option in important_options: if option == "exists": print "yes" return sys.exit(0) # already checked for none above if option == "concat": concat = True if option == "info": pkg_info_list = [] for pkg in pkgs: #MAKE PRETTY print pkg.getInfo() #print output_options #output_options = [] #output_single = [] #Process options here.............. concat_list = [] if concat: print_option = lambda x: concat_list.extend(x) else: print_option = lambda x: Utils.printList(x) for option in output_options: if option[0] == "cflags": print_option(Utils.stripDupIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "cflags-only-I": print_option(Utils.cflagsOnlyDirIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "cflags-only-other": print_option(Utils.cflagsOnlyOtherIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "libs-only-l": print_option(Utils.libsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs-only-L": print_option(Utils.libDirsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs-only-other": print_option(Utils.libsOnlyOtherLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs": print_option(Utils.stripDupLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) else: print_option(Utils.stripDupInList(self.getVarFromPkgs(option[0], pkgs, option[1]))) if concat: Utils.printList(Utils.stripDupInList(concat_list)) def getVarFromPkgs(self, var, pkgs, pkg_name=""): var_list = [] ext_vars = [] if var == "Libs": if DepResolutionSystem().checkPrivateRequires: ext_vars.append("Libs.private") if pkg_name == "": for pkg in pkgs: if pkg: var_list.extend(pkg.getVariable(var).split(' ')) for extra_var in ext_vars: var_list.extend(pkg.getVariable(extra_var).split(' ')) else: for pkg in pkgs: if pkg: if pkg.getName() == pkg_name: var_list.extend(pkg.getVariable(var).split(' ')) for extra_var in ext_vars: var_list.extend(pkg.getVariable(extra_var).split(' ')) return var_list def printHelp(self): print "usage: flagpoll pkg options [pkg options] [generic options]" print " " print "generic options:" print " --help show this help message and exit" print " --version output version of flagpoll" print " --list-all list all known packages" print " --debug show verbose debug information" print " --extra-paths=EXTRA_PATHS" print " extra paths for flagpoll to search for meta-data files" print " --concat concatenate all output and output as one line" print " --keep-dups do not strip out all duplicate info from options" print " --info show information for packages" print " " print "options:" print " --modversion output version for package" print " --require=REQUIRE adds additional requirements for packages ex. 32/64" print " --libs output all linker flags" print " --static output linker flags for static linking" print " --libs-only-l output -l flags" print " --libs-only-other output other libs (e.g. -pthread)" print " --libs-only-L output -L flags" print " --cflags output all pre-processor and compiler flags" print " --cflags-only-I output -I flags" print " --cflags-only-other output cflags not covered by the cflags-only-I option" print " --exists return 0 if the module(s) exist" print " --from-file=FILE use the specified FILE for the package" #print " --print-provides print which packages the package provides" #print " --print-requires print which packages the package requires" print " --no-deps do not lookup dependencies for the package" print " --atleast-version=ATLEAST_VERSION" print " return 0 if the module is at least version" print " ATLEAST_VERSION" print " --exact-version=EXACT_VERSION" print " return 0 if the module is exactly version" print " EXACT_VERSION" print " --max-release=MAX_RELEASE" print " return 0 if the module has a release that has a" print " version of MAX_RELEASE and will return the max" print " --variable=VARIABLE get the value of a variable" print " " print "dynamic options(replace VAR with a variable you want to get/filter on)" print " NOTE: replace underscores with dashes in VAR" print " NOTE: quotes are needed around <,>,= combinations" print " --get-VAR get VAR from package" print " --get-all-VAR get VAR from package and its deps" print " --require-VAR[<,>,=VAL]" print " require that a var is defined for a package" print " or optionally use equality operators against VAL" print " --require-all-VAR[<,>,=VAL]" print " require that a var is defined for all packages" print " or optionally use equality operators against VAL" sys.exit(0) def main(): # GO! # Initialize singletons and the start evaluating #print sys.argv[1:] my_dbg = flagDBG() my_dep_system = DepResolutionSystem() opt_evaluator = OptionsEvaluator() opt_evaluator.evaluateArgs(sys.argv[1:]) sys.exit(0) if __name__ == "__main__": main()
Python
#!/usr/bin/env python from distutils.core import setup setup( name='flagpoll', version='0.6.0', description='Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software.', author='Daniel E. Shipton', author_email='dshipton@infiscape.com', license='GPL', url='https://realityforge.vrsource.org/view/FlagPoll/WebHome', download_url='https://realityforge.vrsource.org/view/FlagPoll/FlagpollDownloads', scripts=['flagpoll'], long_description = "Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software. Think of it as the rpm of software development. It enables developers total control over which packages, versions, architectures, etc. that they want to use meta-data from.", data_files=[('share/flagpoll', ['flagpoll.fpc']), ('share/man/man1', ['flagpoll.1']), ('share/aclocal', ['flagpoll.m4'])] )
Python
#!/usr/bin/env python # ----------------------------------------------------------------- # # Flagpoll: A tool to extract flags from installed applications # for compiling, settting variables, etc. # # Original Authors: # Daniel E. Shipton <dshipton@gmail.com> # # Flagpoll is Copyright (C) 2006 by Daniel E. Shipton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to: # Free SoftwareFoundation, Inc. # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # # ----------------------------------------------------------------- from optparse import OptionParser import sys, os, glob, os.path, copy, platform pj = os.path.join #################################################################### # SNAGGED FROM PYTHON 2.4 for versions under 2.4 #################################################################### import re as _re class _multimap: """Helper class for combining multiple mappings. Used by .{safe_,}substitute() to combine the mapping and keyword arguments. """ def __init__(self, primary, secondary): self._primary = primary self._secondary = secondary def __getitem__(self, key): try: return self._primary[key] except KeyError: return self._secondary[key] class _TemplateMetaclass(type): pattern = r""" %(delim)s(?: (?P<escaped>%(delim)s) | # Escape sequence of two delimiters (?P<named>%(id)s) | # delimiter and a Python identifier {(?P<braced>%(id)s)} | # delimiter and a braced identifier (?P<invalid>) # Other ill-formed delimiter exprs ) """ def __init__(cls, name, bases, dct): super(_TemplateMetaclass, cls).__init__(name, bases, dct) if 'pattern' in dct: pattern = cls.pattern else: pattern = _TemplateMetaclass.pattern % { 'delim' : _re.escape(cls.delimiter), 'id' : cls.idpattern, } cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE) class Template: """A string class for supporting $-substitutions.""" __metaclass__ = _TemplateMetaclass delimiter = '$' idpattern = r'[_a-z][_a-z0-9]*' def __init__(self, template): self.template = template # Search for $$, $identifier, ${identifier}, and any bare $'s def _invalid(self, mo): i = mo.start('invalid') lines = self.template[:i].splitlines(True) if not lines: colno = 1 lineno = 1 else: colno = i - len(''.join(lines[:-1])) lineno = len(lines) raise ValueError('Invalid placeholder in string: line %d, col %d' % (lineno, colno)) def substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): # Check the most common path first. named = mo.group('named') or mo.group('braced') if named is not None: val = mapping[named] # We use this idiom instead of str() because the latter will # fail if val is a Unicode containing non-ASCII characters. return '%s' % val if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: self._invalid(mo) raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) def safe_substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): named = mo.group('named') if named is not None: try: # We use this idiom instead of str() because the latter # will fail if val is a Unicode containing non-ASCII return '%s' % mapping[named] except KeyError: return self.delimiter + named braced = mo.group('braced') if braced is not None: try: return '%s' % mapping[braced] except KeyError: return self.delimiter + '{' + braced + '}' if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: return self.delimiter raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) #################################################################### # End Snagging #################################################################### class Utils: # Holds collection of small utility functions EXTRA_FLAGPOLL_SEARCH_PATHS = "" EXTRA_FLAGPOLL_FILES = "" path_list_cache = None # Cache of found path lists. (only calcuate once) KEEP_DUPS = False def getFlagpollVersion(): FLAGPOLL_MAJOR_VERSION = 0 FLAGPOLL_MINOR_VERSION = 6 FLAGPOLL_PATCH_VERSION = 0 return ( FLAGPOLL_MAJOR_VERSION, FLAGPOLL_MINOR_VERSION, FLAGPOLL_PATCH_VERSION ) getFlagpollVersion = staticmethod(getFlagpollVersion) def getPathList(): if None != Utils.path_list_cache: return Utils.path_list_cache #TODO: expand LD_LIBRARY_PATH to 64/32/etc??? pkg_cfg_dir = [] flg_cfg_dir = [] ld_path = [] if os.environ.has_key("PKG_CONFIG_PATH"): pkg_cfg_dir = os.environ["PKG_CONFIG_PATH"].split(os.pathsep) if os.environ.has_key("FLAGPOLL_PATH"): flg_cfg_dir = os.environ["FLAGPOLL_PATH"].split(os.pathsep) if os.environ.has_key("LD_LIBRARY_PATH"): ld_path = os.environ["LD_LIBRARY_PATH"].split(os.pathsep) ld_path_pkg = [pj(p,'pkgconfig') for p in ld_path] ld_path_flg = [pj(p,'flagpoll') for p in ld_path] ld_path = [] ld_path.extend(ld_path_pkg) ld_path.extend(ld_path_flg) extra_paths = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS.split(os.pathsep) path_list = ["/usr/lib64/pkgconfig", "/usr/lib/pkgconfig", "/usr/share/pkgconfig", "/usr/lib64/flagpoll", "/usr/lib/flagpoll", "/usr/share/flagpoll"] path_list.extend(pkg_cfg_dir) path_list.extend(flg_cfg_dir) path_list.extend(extra_paths) path_list.extend(ld_path) flagDBG().out(flagDBG.VERBOSE, "Utils.getPathList", "Potential path list: " + str(path_list)) path_list = [p for p in path_list if os.path.exists(p)] flagDBG().out(flagDBG.INFO, "Utils.getPathList", "Using path list: " + str(path_list)) Utils.path_list_cache = path_list return path_list getPathList = staticmethod(getPathList) def getFileList(): flist = Utils.EXTRA_FLAGPOLL_FILES.split(":") filelist = [] for f in flist: if os.path.isfile(f): filelist.append(f) return filelist getFileList = staticmethod(getFileList) def setKeepDups(keep_dups): Utils.KEEP_DUPS = keep_dups setKeepDups = staticmethod(setKeepDups) def stripDupInList(gen_list): new_list = [] for item in gen_list: item = item.strip() if Utils.KEEP_DUPS: if len(item) > 0: new_list.append(item) continue if item not in new_list: if len(item) > 0: new_list.append(item) return new_list stripDupInList = staticmethod(stripDupInList) def stripDupLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] dir_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-L") or flg.startswith("-R"): dir_list.append(flg) else: lib_list.append(flg) new_list = dir_list + lib_list return Utils.stripDupInList(new_list) stripDupLinkerFlags = staticmethod(stripDupLinkerFlags) def stripDupIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] extra_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-I"): inc_list.append(flg) else: extra_list.append(flg) extra_list.sort() new_list = inc_list + extra_list return Utils.stripDupInList(new_list) stripDupIncludeFlags = staticmethod(stripDupIncludeFlags) def cflagsOnlyDirIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-I"): inc_list.append(flg) return Utils.stripDupInList(inc_list) cflagsOnlyDirIncludeFlags = staticmethod(cflagsOnlyDirIncludeFlags) def cflagsOnlyOtherIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though extra_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if not flg.startswith("-I"): extra_list.append(flg) return Utils.stripDupInList(extra_list) cflagsOnlyOtherIncludeFlags = staticmethod(cflagsOnlyOtherIncludeFlags) def libsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-l"): lib_list.append(flg) return Utils.stripDupInList(lib_list) libsOnlyLinkerFlags = staticmethod(libsOnlyLinkerFlags) def libsOnlyOtherLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though other_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if not flg.startswith("-l") and not flg.startswith("-L") and not flg.startswith("-R"): other_list.append(flg) return Utils.stripDupInList(other_list) libsOnlyOtherLinkerFlags = staticmethod(libsOnlyOtherLinkerFlags) def libDirsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though dir_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-L") or flg.startswith("-R"): dir_list.append(flg) return Utils.stripDupInList(dir_list) libDirsOnlyLinkerFlags = staticmethod(libDirsOnlyLinkerFlags) def printList(gen_list): list_string = "" for item in gen_list: if len(item) > 0: list_string+=str(item) list_string+=" " print list_string.strip() printList = staticmethod(printList) def parsePcFile(filename): lines = open(filename).readlines() fvars = {} fvars["XXFlagpollFilenameXX"] = filename lokals = {} lokals["fp_file_cwd"] = str(filename[:- ((len(os.path.basename(filename) ) + 1))]) lines.append("prefix: ${prefix}") for line in lines: line = line.strip() if not line: continue if line.startswith("#"): continue eq_pos = line.find('=') col_pos = line.find(':') if eq_pos < col_pos and eq_pos != -1 or col_pos == -1 and eq_pos !=-1: # local variable name, val = line.split('=', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(lokals) except ValueError: flagDBG().out(flagDBG.WARN, "PkgInfo.parse", "%s has an invalid metadata file" % filename) lokals[name] = val if col_pos < eq_pos and col_pos != -1 or eq_pos == -1 and col_pos !=-1: # exported variable name, val = line.split(':', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(lokals) except ValueError: flagDBG().out(flagDBG.ERROR, "PkgInfo.parse", "%s has an invalid metadata file" % filename) fvars[name] = val return fvars parsePcFile = staticmethod(parsePcFile) class flagDBG(object): # Logging class is really easy to use # Levels: # 0 - VERBOSE # 1 - INFO # 2 - WARN # 3 - ERROR VERBOSE=0 INFO=1 WARN=2 ERROR=3 __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if flagDBG.__initialized: return flagDBG.__initialized = True self.mLevel = self.WARN self.mLevelList = ["VERBOSE","INFO","WARN","ERROR"] def setLevel(self, level): if level <= 3: self.mLevel = level def out(self, level, obj, message): if level == self.ERROR: if self.mLevel == self.VERBOSE: print self.mLevelList[level] + ":" + str(obj) + ": " + str(message) else: print self.mLevelList[level] + ": " + str(message) sys.exit(1) if level >= self.mLevel: print self.mLevelList[level] + ":" + str(obj) + ": " + str(message) class DepResolutionSystem(object): """ You add PkgAgents with Filters into system and call resolve() you can check for succes by depsSatisfied() and get the list of packages that work back by calling getPackages() """ __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if DepResolutionSystem.__initialized: return DepResolutionSystem.__initialized = True self.mResolveAgents = [] self.mAgentDict = {} self.mFilters = [] self.mResolveAgentFilters = [] self.mInvalidPackageList = [] self.mSatisfied = False self.mAgentChangeList = [] # list of those responsible for adding Filters # to agents in higher in the chain than them # these are the first agents to ask that they pick # the next best package of them self.mAgentsVisitedList = [] # list of Agents that have been visited self.mResolvedPackageList = [] # list that is generated when deps are satified self.mCheckPrivateRequires = False self.mMadeDependList = False def getFilters(self): return self.mFilters def addFilter(self, filter): self.mFilters.append(filter) def addResolveAgentFilter(self, filter): self.mResolveAgentFilters.append(filter) def makeRequireFilter(self, requires): arch_list = [] arch_list.append("no_arch") arch_list.append("") if platform.system() == "Linux": if requires == "64": arch_list.append("x86_64") if requires == "32": arch_list.append("i386") arch_list.append("i586") arch_list.append("i686") if platform.system() == "Darwin": if requires == "64": arch_list.append("ppc64") if requires == "32": arch_list.append("ppc") new_filter = Filter("Arch", lambda x: x in arch_list) self.addFilter(new_filter) def createAgent(self, name): if self.checkAgentExists(name): return self.getAgent(name) else: agent = PkgAgent(name) flagDBG().out(flagDBG.INFO, "DepResSys.createAgent", "Adding %s" % name) self.addNewAgent(agent) return agent def createResolveAgent(self, name): if self.checkAgentExists(name): return self.getAgent(name) else: agent = PkgAgent(name) flagDBG().out(flagDBG.INFO, "DepResSys.createResloveAgent", "Adding %s" % name) self.addResolveAgent(agent) return agent def setPrivateRequires( self, req ): self.mCheckPrivateRequires = req def checkPrivateRequires(self): return self.mCheckPrivateRequires def checkAgentExists(self, name): return self.mAgentDict.has_key(name) def getAgent(self, name): if self.mAgentDict.has_key(name): return self.mAgentDict[name] else: flagDBG().out(flagDBG.ERROR, "DepResSys.getAgent", "Agent %s does not exist" % name) def addNewAgent(self, agent): if not self.checkAgentExists(agent): self.mAgentDict[agent.getName()] = agent def addResolveAgent(self, agent): if agent not in self.mResolveAgents: self.mResolveAgents.append(agent) for filt in self.mResolveAgentFilters: agent.addFilter(filt) def isSatisfied(self): return self.mSatisfied def updateResolvedPackages(self): pkg_list = [] agent_list = [] for agent in self.mResolveAgents: list_of_pkgs = agent.getCurrentPackageList(agent_list) pkg_list.extend(list_of_pkgs) self.mResolvedPackageList = pkg_list def getPackages(self): flagDBG().out(flagDBG.VERBOSE, "DepResSys.getPackages", "Generating list of valid packages ") #str([pkg.getCurrentPa.getName() for pkg in self.mResolvedPackageList])) # If this comes back empty then there isn't a valid set of packages to use self.updateResolvedPackages() return self.mResolvedPackageList def checkFiltersChanged(self): list_to_use = [] return True in [pkg.filtersChanged(list_to_use) for pkg in self.mResolveAgents] def resolveHelper(self): self.resolveAgentsChanged = True while self.resolveAgentsChanged: for agent in self.mResolveAgents: flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveHelper", "Updating " + agent.getName()) agent.update(self.mAgentsVisitedList, self.mAgentChangeList) self.resolveAgentsChanged = self.checkFiltersChanged() # Ask mResolveAgents if they are done(they ask sub people) unless they are # really above you in the walk # If there were changes...run update on mResolveAgents again # at the end ask for pkglist..if it comes back empty then we don't # have a usable configuration for those packages def resolveDeps(self): if not self.mMadeDependList: for agent in self.mResolveAgents: agent.makeDependList() self.mMadeDependList = True self.resolveHelper() self.updateResolvedPackages() # Check if the first round through we found something # Otherwise we need to start removing packages that aren't viable # during the loop self.mSatisfied = (len(self.mResolvedPackageList) != 0) # remove top of packages that added Filters. # then move on to resolving again # remove more if neccesary agentChangeNumber = 0 while not self.mResolvedPackageList: if(self.mAgentChangeList[agentChangeNumber]): if self.mAgentChangeList[agentChangeNumber] in self.mInvalidPackageList: agentChangeNumber+=1 else: if(self.mAgentChangeList[agentChangeNumber].getViablePackages()): flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveDeps", "Removing bad pkg from " + self.mAgentChangeList[agentChangeNumber].getName()) self.mInvalidPackageList.append(self.mAgentChangeList[agentChangeNumber].removeCurrentPackage()) else: flagDBG().out(flagDBG.VERBOSE, "DepResSys.resolveDeps", "No combinations.. Resetting " + self.mAgentChangeList[agentChangeNumber].getName()) self.mAgentChangeList[agentChangeNumber].reset() agentChangeNumber+=1 self.resolveHelper() self.updateResolvedPackages() self.mSatisfied = (len(self.mResolvedPackageList) != 0) return class PkgAgent: """ Agent that keeps track of the versions for a package given some filters and the addition of Filters """ # Makes a PkgAgent that finds its current package with the version reqs def __init__(self, name): if DepResolutionSystem().checkAgentExists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "Package Agent %s already exists" % self.mName) self.mName = name flagDBG().out(flagDBG.VERBOSE, "PkgAgent", "Creating:" + str(self.mName)) if not PkgDB().exists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "No info for package: %s" % self.mName) #XXX Doesn't keep filters added for a redo... DepResolutionSystem().addNewAgent(self) self.mFilterList = [] self.mFilterList.extend(DepResolutionSystem().getFilters()) self.mBasePackageList = PkgDB().getPkgInfos(name) for filt in self.mFilterList: self.mBasePackageList = filt.filter(self.mBasePackageList) if len(self.mBasePackageList) == 0: flagDBG().out(flagDBG.ERROR, "PkgAgent", "No viable packages for: %s" % self.mName) self.mViablePackageList = copy.deepcopy(self.mBasePackageList) if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mAgentDependList = [] # Agents that it depends on/needs to update #self.makeDependList() self.mFiltersChanged = True self.mCheckDepends = True def getName(self): return self.mName def setCheckDepends(self, tf): self.mCheckDepends = tf #Filter("Version", lambda x: x == "4.5") def makeDependList(self): if not self.mCheckDepends: self.mAgentDependList = [] return dep_list = [] if self.mCurrentPackage: req_string = self.mCurrentPackage.getVariable("Requires") if DepResolutionSystem().checkPrivateRequires(): req_string = req_string + " " + self.mCurrentPackage.getVariable("Requires.private") req_string = req_string.strip() if req_string == "": return req_string = req_string.replace(',', ' ') req_string = req_string.replace('(', ' ') req_string = req_string.replace(')', ' ') space_req_string_list = req_string.split(' ') req_string_list = [] for entry in space_req_string_list: if len(entry) > 0: req_string_list.append(entry) i = 0 flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList", self.mCurrentPackage.getName() + " requires: " + str(req_string_list)) while len(req_string_list) > i: if PkgDB().exists(req_string_list[i]): new_filter = [] new_agent = DepResolutionSystem().createAgent(req_string_list[i]) if len(req_string_list) > i+1: if req_string_list[i+1] == "=": ver_to_filt = req_string_list[i+2] new_filter = Filter("Version", lambda x: x == ver_to_filt) elif req_string_list[i+1] == "<=": ver_to_filt = req_string_list[i+2] new_filter = Filter("Version", lambda x: x <= ver_to_filt) elif req_string_list[i+1] == ">=": ver_to_filt = req_string_list[i+2] new_filter = Filter("Version", lambda x: x >= ver_to_filt) else: i+=1 else: i+=1 dep_list.append(new_agent) if new_filter: i+=3 new_agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "PkgAgent.makeDependList", "Package %s depends on %s but does not seem to be installed." % (self.mName, str(req_string_list[i]))) flagDBG().out(flagDBG.VERBOSE, "PkgAgent.makeDependList", "List is:" + str([pkg.getName() for pkg in dep_list])) self.mAgentDependList = dep_list def filtersChanged(self,packageList): tf_list = [self.mFiltersChanged] if self.mName not in packageList: packageList.append(self.mName) for pkg in self.mAgentDependList: tf_list.append(pkg.filtersChanged(packageList)) return True in tf_list def getCurrentPackageList(self, packageList): pkgs = [] if self.mName not in packageList: flagDBG().out(flagDBG.VERBOSE, "PkgAgent.getCurrentPackageList", "Package: %s" % self.mName) pkgs.append(self.mCurrentPackage) packageList.append(self.mName) for pkg in self.mAgentDependList: pkgs.extend(pkg.getCurrentPackageList(packageList)) return pkgs # current pkginfo for me def getCurrentPkgInfo(self): return self.mCurrentPackage # Someone else usually places these on me # I keep track of those separately def addFilter(self, filter): flagDBG().out(flagDBG.VERBOSE, "PkgAgent.addFilter", "Adding a Filter to %s" % self.mName) self.mFiltersChanged = True self.mFilterList.append(filter) def removeCurrentPackage(self): flagDBG().out(flagDBG.VERBOSE, "PkgAgent.removeCurrentPackage", "Removing current package of %s" % self.mName) if self.mViablePackageList: ret_val = self.mViablePackageList[0] in self.mBasePackageList del self.mViablePackageList[0] if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] return ret_val def update(self, agentVisitedList, agentChangeList): if self.mName in agentVisitedList: return agentVisitedList.append(self.mName) if self.mFiltersChanged: self.mFiltersChanged = False self.updateFilters() # TODO: checkFilters and add them # if a pkg is in visitedList then add yourself to agentChangeList for pkg in self.mAgentDependList: pkg.update(agentVisitedList, agentChangeList) return def updateFilters(self): for filt in self.mFilterList: self.mViablePackageList = filt.filter(self.mViablePackageList) if len(self.mViablePackageList) > 0: self.mCurrentPackage = self.mViablePackageList[0] else: self.mCurrentPackage = [] def reset(self): flagDBG().out(flagDBG.VERBOSE, "PkgAgent.reset", "Resetting package: %s" % self.mName) self.mViablePackageList = self.mBasePackageList if self.mViablePackageList: self.mCurrentPacakge = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mFilterList = DepResolutionSystem().getFilters() self.mAgentDependList = [] self.mFiltersChanged = True return class Filter: """ A single Filter that knows how to filter the list it recieves Will be inheireted....?..? """ def __init__(self, variableName, testCallable): self.mVarName = variableName self.mTestCallable = testCallable def filter(self, pkg_info_list): ret_pkg_list = [] # Filter first for pkg in pkg_info_list: var = pkg.getVariable(self.mVarName) if self.mTestCallable(var): ret_pkg_list.append(pkg) # Now sort ret_pkg_list.sort(lambda lhs,rhs: cmp(lhs.getVariable(self.mVarName), rhs.getVariable(self.mVarName))) return ret_pkg_list #requires: qt == 4.5 #Filter("Version", lambda x: x <= "4.5") #Filter("Version", lambda x: x <= "4.5") class PkgDB(object): """ Holds all the neccesary information to evaluate itself when needed. Is in charge of holding a list of PkgInfo's that contain info about the package. """ __initialized = False def __init__(self): if self.__initialized: return self.__initialized = True self.mPkgInfos = {} # {pkg_name: List of package infos} self.populatePkgInfoDBPcFiles() self.populatePkgInfoDBFpcFiles() def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def printAllPackages(self): list_of_package_names = [] for pkg in self.mPkgInfos: list_of_package_names.append(pkg) for name in list_of_package_names: print name sys.exit(0) def getVariables(self, name, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariable", "Finding " + str(variable_list) + " in " + str(name)) ret_list = [] for var in variable_list: if self.mPkgInfos.has_key(name): ret_list.extend(self.mPkgInfos[name][0].getVariable(var)) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariable", "Package %s not found." % name) return ret_list def checkPackage(self, name): flagDBG().out(flagDBG.INFO, "PkgDB.checkPackage", "Finding " + str(name)) if self.mPkgInfos.has_key(name): return True else: flagDBG().out(flagDBG.ERROR, "PkgDB.CheckPackage", "Package %s not found." % name) return False def getVariablesAndDeps(self, pkg_list, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariablesAndDeps", "Finding " + str(variable_list) + " in " + str(pkg_list)) if DepResolutionSystem().checkPrivateRequires(): temp_var_list = [] for var in variable_list: temp_var_list.append(var.join(".private")) variable_list = variable_list + temp_var_list for name in pkg_list: if self.mPkgInfos.has_key(name): agent = DepResolutionSystem().createAgent(name) DepResolutionSystem().addResolveAgent(agent) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariablesAndDeps", "Package %s not found." % name) DepResolutionSystem().resolveDeps() pkgs = DepResolutionSystem().getPackages() var_list = [] for pkg in pkgs: if pkg: for var in variable_list: var_list.extend(pkg.getVariable(var).split(' ')) return var_list def getPkgInfos(self, name): if self.mPkgInfos.has_key(name): return self.mPkgInfos[name] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getPkgInfos", "Package %s not found." % name) def exists(self, name): return self.mPkgInfos.has_key(name) def getInfo(self, name): if self.mPkgInfos.has_key(name): return [pkg.getInfo() for pkg in self.mPkgInfos[name]] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getInfo", "Package %s not found." % name) def buildPcFileDict(self): """ Builds up a dictionary of {name: list of files for name} """ pc_dict = {} for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.pc")) # List of .pc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these pc files: %s" % str(glob_list)) for g in glob_list: # Get key name and add file to value list in dictionary key = os.path.basename(g)[:-3] # Strip .pc off the filename...rstrip no worky pc_dict.setdefault(key,[]).append(g) for f in Utils.getFileList(): if f.endswith(".pc"): key = os.path.basename(f)[:-3] # Strip .pc off the filename...rstrip no worky pc_dict.setdefault(key,[]).append(f) return pc_dict # { "key", [ "list", "of", "corresponding", "pc", "files"] } def populatePkgInfoDBPcFiles(self): dict_to_pop_from = self.buildPcFileDict() for (pkg,files) in dict_to_pop_from.iteritems(): for f in files: self.mPkgInfos.setdefault(pkg,[]).append(PkgInfo(pkg, f, "pc")) def buildFpcFileList(self): """ Builds up a dictionary of {name: list of files for name} """ file_list = [] for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.fpc")) # List of .fpc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these fpc files: %s" % str(glob_list)) for g in glob_list: file_list.append(g) for f in Utils.getFileList(): if f.endswith(".fpc"): file_list.append(f) return file_list # [ "list", "of", "fpc", "files"] def populatePkgInfoDBFpcFiles(self): list_to_add = self.buildFpcFileList() for filename in list_to_add: var_dict = Utils.parsePcFile(filename) if not var_dict.has_key("Provides"): flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Provides" % str(filename)) continue if not var_dict.has_key("Arch"): flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Arch" % str(filename)) continue provides_string = var_dict["Provides"] provides_string = provides_string.replace(',', ' ') provides_string = provides_string.replace('(', ' ') provides_string = provides_string.replace(')', ' ') for key in provides_string.split(" "): if len(key) > 0: self.mPkgInfos.setdefault(key,[]).append(PkgInfo(key, filename, "fpc", var_dict)) class PkgInfo: """ Holds the information for a package file on the system. These however are evaluated when the need arises. """ def __init__(self, name, file, type, varDict={}): self.mName = name self.mFile = file self.mIsEvaluated = False self.mType = type self.mVariableDict = varDict if self.mType == "fpc": self.mIsEvaluated = True def getVariable(self, variable): self.evaluate() return self.mVariableDict.get(variable,"") def getName(self): return self.mName def evaluate(self): if not self.mIsEvaluated: flagDBG().out(flagDBG.INFO, "PkgInfo.evaluate", "Evaluating %s" % self.mName) self.mVariableDict= Utils.parsePcFile(self.mFile) self.mIsEvaluated = True def getInfo(self): self.evaluate() return self.mVariableDict class OptionsEvaluator: def __init__(self): #self.mOptParser = self.GetOptionParser() #self.mOptParser.print_help() if len(sys.argv) < 2: self.printHelp() #(self.mOptions, self.mArgs) = self.mOptParser.parse_args() #if self.mOptions.version: # print "%s.%s.%s" % Utils.getFlagpollVersion() # sys.exit(0) #if len(self.mArgs) < 1: # self.mOptParser.print_help() # sys.exit(1) # This is only the args....(first arg is stripped) def evaluateArgs(self, args): # Catch any args that need to be tended to immediately # Process args in the order that they were recieved. Some options are not # shown below because they are sub-options of an option below (--strip-dups) for option in args: if option.startswith("--debug"): flagDBG().setLevel(flagDBG.VERBOSE) elif option.startswith("--from-file"): val_start = option.find('=') + 1 file = option[val_start:] Utils.EXTRA_FLAGPOLL_FILES = Utils.EXTRA_FLAGPOLL_FILES + ":" + file elif option.startswith("--help"): self.printHelp() sys.exit(0) elif option.startswith("--version"): print "%s.%s.%s" % Utils.getFlagpollVersion() sys.exit(0) elif option.startswith("--list-all"): PkgDB().printAllPackages() continue agent = None num_args = len(args) curr_arg = 0 output_options = [] # (option, name/"") important_options = [] # ones that need special attention while curr_arg < num_args: if args[curr_arg].startswith("--atleast-version"): val_start = args[curr_arg].find('=') + 1 atleast_version = args[curr_arg][val_start:] atleast_filter = Filter("Version", lambda x: x >= atleast_version) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(atleast_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --at-least-version") continue if args[curr_arg].startswith("--cflags-only-I"): output_options.append(("cflags-only-I", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--cflags-only-other"): output_options.append(("cflags-only-other", "")) curr_arg = curr_arg + 1 continue #This could be the catch all for the above ones to and then filter based on what is asked... #For clarity of course... if args[curr_arg].startswith("--cflags"): output_options.append(("cflags", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--extra-paths"): val_start = args[curr_arg].find('=') + 1 paths = args[curr_arg][val_start:] Utils.EXTRA_FLAGPOLL_SEARCH_PATHS = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS + ":" + paths curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--exact-version"): val_start = args[curr_arg].find('=') + 1 exact_version = args[curr_arg][val_start:] exact_filter = Filter("Version", lambda x: x == exact_version) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(exact_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --exact-version") continue if args[curr_arg].startswith("--exists"): important_options.append("exists") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--from-file"): val_start = args[curr_arg].find('=') + 1 file = args[curr_arg][val_start:] file_filter = Filter("XXFlagpollFilenameXX", lambda x: x == file) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(file_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --from-file") continue if args[curr_arg].startswith("--info"): important_options.append("info") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--keep-dups"): Utils.setKeepDups(True) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-l"): output_options.append(("libs-only-l", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-L"): output_options.append(("libs-only-L", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-other"): output_options.append(("libs-only-other", "")) curr_arg = curr_arg + 1 continue #This could be the catch all for the above ones to and then filter based on what is asked... if args[curr_arg].startswith("--libs"): output_options.append(("libs", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--require-all"): rlen = len("--require-all") req_string = args[curr_arg][rlen:] req_string = req_string.replace('-','_') curr_arg = curr_arg + 1 if req_string.find("<=") != -1: op_start = req_string.find("<=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x: x <= req_val) DepResolutionSystem().addFilter(new_filter) continue if req_string.find(">=") != -1: op_start = req_string.find(">=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x: x >= req_val) DepResolutionSystem().addFilter(new_filter) continue if req_string.find(">") != -1: op_start = req_string.find(">") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x > req_val) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("<") != -1: op_start = req_string.find("<") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x < req_val) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("=") != -1: op_start = req_string.find("=") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x == req_val) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("=") == -1: new_filter = Filter(req_string, lambda x: len(x) > 0) DepResolutionSystem().addFilter(new_filter) continue continue if args[curr_arg].startswith("--require-"): rlen = len("--require-") req_string = args[curr_arg][rlen:] req_string = req_string.replace('-','_') curr_arg = curr_arg + 1 if agent is None: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --require") if req_string.find("<=") != -1: op_start = req_string.find("<=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x: x <= req_val) agent.addFilter(new_filter) continue if req_string.find(">=") != -1: op_start = req_string.find(">=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x: x >= req_val) agent.addFilter(new_filter) continue if req_string.find(">") != -1: op_start = req_string.find(">") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x > req_val) agent.addFilter(new_filter) continue if req_string.find("<") != -1: op_start = req_string.find("<") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x < req_val) agent.addFilter(new_filter) continue if req_string.find("=") != -1: op_start = req_string.find("=") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x: x == req_val) agent.addFilter(new_filter) continue if req_string.find("=") == -1: new_filter = Filter(req_string, lambda x: len(x) > 0) agent.addFilter(new_filter) continue continue if args[curr_arg].startswith("--no-deps"): if agent is not None: agent.setCheckDepends(False) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --no-deps") if args[curr_arg].startswith("--require="): val_start = args[curr_arg].find('=') + 1 req_var = args[curr_arg][val_start:] curr_arg = curr_arg + 1 DepResolutionSystem().makeRequireFilter(req_var) continue if args[curr_arg].startswith("--modversion"): if agent is not None: output_options.append(("Version", agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --modversion") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--max-release"): val_start = args[curr_arg].find('=') + 1 max_release = args[curr_arg][val_start:] max_filter = Filter("Version", lambda x: x.startswith(max_release)) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(max_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --max-release") continue if args[curr_arg].startswith("--static"): DepResolutionSystem().setPrivateRequires(True) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--variable"): val_start = args[curr_arg].find('=') + 1 fetch_var = args[curr_arg][val_start:] if agent is not None: output_options.append((fetch_var, agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --variable") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--get-all"): rlen = len("--get-all-") get_string = args[curr_arg][rlen:] get_string = get_string.replace('-','_') output_options.append((get_string, "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--get"): rlen = len("--get-") get_string = args[curr_arg][rlen:] get_string = get_string.replace('-','_') if agent is not None: output_options.append((get_string, agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --get") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--concat"): important_options.append("concat") curr_arg = curr_arg + 1 continue if not args[curr_arg].startswith("--"): name = args[curr_arg] curr_arg = curr_arg + 1 if PkgDB().checkPackage(name): agent = DepResolutionSystem().createResolveAgent(name) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Package %s" % name) sys.exit(1) continue if args[curr_arg] != "--debug": flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Option: %s" % args[curr_arg]) curr_arg = curr_arg + 1 DepResolutionSystem().resolveDeps() pkgs = DepResolutionSystem().getPackages() for p in pkgs: if not p: for option in important_options: if option == "exists": print "no" sys.exit(1) flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found") if len(pkgs) == 0: for option in important_options: if option == "exists": print "no" sys.exit(1) flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found") sys.exit(1) concat = False for option in important_options: if option == "exists": print "yes" return sys.exit(0) # already checked for none above if option == "concat": concat = True if option == "info": pkg_info_list = [] for pkg in pkgs: #MAKE PRETTY print pkg.getInfo() #print output_options #output_options = [] #output_single = [] #Process options here.............. concat_list = [] if concat: print_option = lambda x: concat_list.extend(x) else: print_option = lambda x: Utils.printList(x) for option in output_options: if option[0] == "cflags": print_option(Utils.stripDupIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "cflags-only-I": print_option(Utils.cflagsOnlyDirIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "cflags-only-other": print_option(Utils.cflagsOnlyOtherIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "libs-only-l": print_option(Utils.libsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs-only-L": print_option(Utils.libDirsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs-only-other": print_option(Utils.libsOnlyOtherLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs": print_option(Utils.stripDupLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) else: print_option(Utils.stripDupInList(self.getVarFromPkgs(option[0], pkgs, option[1]))) if concat: Utils.printList(Utils.stripDupInList(concat_list)) def getVarFromPkgs(self, var, pkgs, pkg_name=""): var_list = [] ext_vars = [] if var == "Libs": if DepResolutionSystem().checkPrivateRequires: ext_vars.append("Libs.private") if pkg_name == "": for pkg in pkgs: if pkg: var_list.extend(pkg.getVariable(var).split(' ')) for extra_var in ext_vars: var_list.extend(pkg.getVariable(extra_var).split(' ')) else: for pkg in pkgs: if pkg: if pkg.getName() == pkg_name: var_list.extend(pkg.getVariable(var).split(' ')) for extra_var in ext_vars: var_list.extend(pkg.getVariable(extra_var).split(' ')) return var_list def printHelp(self): print "usage: flagpoll pkg options [pkg options] [generic options]" print " " print "generic options:" print " --help show this help message and exit" print " --version output version of flagpoll" print " --list-all list all known packages" print " --debug show verbose debug information" print " --extra-paths=EXTRA_PATHS" print " extra paths for flagpoll to search for meta-data files" print " --concat concatenate all output and output as one line" print " --keep-dups do not strip out all duplicate info from options" print " --info show information for packages" print " " print "options:" print " --modversion output version for package" print " --require=REQUIRE adds additional requirements for packages ex. 32/64" print " --libs output all linker flags" print " --static output linker flags for static linking" print " --libs-only-l output -l flags" print " --libs-only-other output other libs (e.g. -pthread)" print " --libs-only-L output -L flags" print " --cflags output all pre-processor and compiler flags" print " --cflags-only-I output -I flags" print " --cflags-only-other output cflags not covered by the cflags-only-I option" print " --exists return 0 if the module(s) exist" print " --from-file=FILE use the specified FILE for the package" #print " --print-provides print which packages the package provides" #print " --print-requires print which packages the package requires" print " --no-deps do not lookup dependencies for the package" print " --atleast-version=ATLEAST_VERSION" print " return 0 if the module is at least version" print " ATLEAST_VERSION" print " --exact-version=EXACT_VERSION" print " return 0 if the module is exactly version" print " EXACT_VERSION" print " --max-release=MAX_RELEASE" print " return 0 if the module has a release that has a" print " version of MAX_RELEASE and will return the max" print " --variable=VARIABLE get the value of a variable" print " " print "dynamic options(replace VAR with a variable you want to get/filter on)" print " NOTE: replace underscores with dashes in VAR" print " NOTE: quotes are needed around <,>,= combinations" print " --get-VAR get VAR from package" print " --get-all-VAR get VAR from package and its deps" print " --require-VAR[<,>,=VAL]" print " require that a var is defined for a package" print " or optionally use equality operators against VAL" print " --require-all-VAR[<,>,=VAL]" print " require that a var is defined for all packages" print " or optionally use equality operators against VAL" sys.exit(0) def main(): # GO! # Initialize singletons and the start evaluating #print sys.argv[1:] my_dbg = flagDBG() my_dep_system = DepResolutionSystem() opt_evaluator = OptionsEvaluator() opt_evaluator.evaluateArgs(sys.argv[1:]) sys.exit(0) if __name__ == "__main__": main()
Python
#!/usr/bin/env python # ----------------------------------------------------------------- # # Flag Poll: A tool to extract flags from installed applications # for compiling, settting variables, etc. # # Original Authors: # Daniel E. Shipton <dshipton@gmail.com> # # Flag Poll is Copyright (C) 2006 by Daniel E. Shipton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to: # Free SoftwareFoundation, Inc. # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # # ----------------------------------------------------------------- """Makes a flagpole .fpc file from user input. v0.9 coded by Jeff Groves""" import os import sys import getopt ##String prompts for the input varPrompt = """Convience variables (one 'var_name= var_definition' per line,""" + \ """ empty line when done)""" namePrompt = "Formal Name" descriptionPrompt = "Description" urlPrompt = "URL" providesPrompt = "One or more names to look package up by: (Provides)" versionPrompt = "Version (x.y.z)" architecturePrompt = "Architecture" requirePrompt = "Requires" libPrompt = "Linker Flags (-lfoo -L/usr/lib)" staticLibPrompt = "Static Linking Flags/Libs (extra private libs)" compileFlagsPrompt = "Compile/Include Flags (-I/usr -fpge -O2)" fileNamePrompt = "FPC File's Name" def usage(): """Prints a list of acceptable arguments for fpcmaker.py.""" print """ Fpcmaker.py Options: -n, --name= : Sets %s -d, --description= : Sets %s -u, --url= : Sets %s -p, --provides= : Sets %s -v, --version= : Sets %s -a, --architecture= : Sets %s -r, --requires= : Sets %s -l, --libs= : Sets %s -c, --cflags= : Sets %s -s, --static= : Sets %s -f, --file= : Sets %s """ %(namePrompt, descriptionPrompt, urlPrompt, providesPrompt, versionPrompt, architecturePrompt, requirePrompt, libPrompt, compileFlagsPrompt, staticLibPrompt, fileNamePrompt) return def checkFileName(fileName): """Checks if the fpc file name's blank, contains slashes, or exists.""" nameCleared = False writeFile = True confirms = ['y', 'Y', 'yes', 'Yes'] ##Loops until the name clears or writing the file's aborted. while(not nameCleared and writeFile): ##If it's blank, give the option of aborting the program. if fileName == "": choice = raw_input("Do you want to abort writing the" + " .fpc file? (Y/N): ") if choice not in confirms: fileName = raw_input("Please enter a different name for the" + " .fpc file: ") else: writeFile = False ##If it contains slashes, ask for another name. elif '/' in fileName or '\\' in fileName: print "I can't write to %s because it contains slashes."%(fileName) fileName = raw_input("Please enter a different name for the" + " .fpc file: ") ##If it already exists, ask if they want to overwrite. ##If not, ask for another name. elif os.path.exists(fileName): choice = raw_input("The file %s already exists." %(fileName) + " Do you want to overwrite it? (Y/N): ") if choice not in confirms: fileName = raw_input("Please enter a different name for the" + " .fpc file: ") else: nameCleared = True else: nameCleared = True return [fileName, writeFile] ##Booleans for whether that argument was sent in the command line varSet = False providesSet = False nameSet = False descriptionSet = False urlSet = False architectureSet = False versionSet = False requiresSet = False libsSet = False compileFlagsSet = False staticLibSet = False fileNameSet = False ##Get the options & arguments sent. arguments = sys.argv[1:] try: opts, args = getopt.getopt(arguments, "p:n:u:d:a:r:v:l:c:s:f:", ["provides=", "name=", "url=", "description=", "architecture=", "requires=", "version=", "libs=", "cflags=", "static=", "file="]) ##Send them usage info if they enter a wrong argument except getopt.GetoptError: usage() sys.exit(2) for opt, arg in opts: if opt in ('-p', '--provides'): providesSet = True provides = arg elif opt in ('-n', '--name'): nameSet = True name = arg elif opt in ('-v', '--version'): versionSet = True version = arg elif opt in ('-u', '--url'): urlSet = True url = arg elif opt in ('-d', '--description'): descriptionSet = True description = arg elif opt in ('-a', '--architecture'): architectureSet = True architecture = arg elif opt in ('-r', '--requires'): requiresSet = True requires = arg elif opt in ('-l', '--libs'): libsSet = True libs = arg elif opt in ('-c', '--cflags'): compileFlagsSet = True compileFlags = arg elif opt in ('-s', '--static'): staticLibSet = True staticLib = arg elif opt in ('-f', '--file'): fileNameSet = True fileName = arg ##Grab any input not passed in the arguments from the user. if not varSet: varLine = None variables = "" print "%s:" %(varPrompt) while(varLine != ""): varLine = raw_input("") variables = variables + "%s\n" %(varLine) if not nameSet: name = raw_input("%s: " %(namePrompt)) if not descriptionSet: description = raw_input("%s: " %(descriptionPrompt)) if not urlSet: url = raw_input("%s: " %(urlPrompt)) if not versionSet: version = raw_input("%s: " %(versionPrompt)) if not providesSet: provides = raw_input("%s: " %(providesPrompt)) if not requiresSet: requires = raw_input("%s: " %(requirePrompt)) if not architectureSet: architecture = raw_input("%s: " %(architecturePrompt)) if not libsSet: libs = raw_input("%s: " %(libPrompt)) if not staticLibSet: staticLib = raw_input("%s: " %(staticLibPrompt)) if not compileFlagsSet: compileFlags = raw_input("%s: " %(compileFlagsPrompt)) if not fileNameSet: fileName = raw_input("%s: " %(fileNamePrompt)) ##Check the file's name. fileName, writeFile = checkFileName(fileName) ##If they chose not to overwrite, write the file. if writeFile: fpc = open(fileName, 'w') fpc.write("%s" %(variables)) fpc.write("Name: %s\n" %(name)) fpc.write("Description: %s\n" %(description)) fpc.write("URL: %s\n" %(url)) fpc.write("Version: %s\n" %(version)) fpc.write("Provides: %s\n" %(provides)) fpc.write("Requires: %s\n" %(requires)) fpc.write("Arch: %s\n" %(architecture)) fpc.write("Libs: %s\n" %(libs)) fpc.write("Libs.private: %s\n" %(staticLib)) fpc.write("Cflags: %s\n" %(compileFlags)) fpc.close() ##TESTER: Print the file out. fpc = open(fileName, 'r') ##TESTER print fpc.read() ##TESTER fpc.close ##TESTER
Python
#!/usr/bin/env python from distutils.core import setup try: import py2exe except: pass setup( name='flagpoll', version='0.9.4', description='Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software.', author='Daniel E. Shipton', author_email='dshipton@infiscape.com', license='GPL', url='http://code.google.com/p/flagpoll/', download_url='http://code.google.com/p/flagpoll/downloads/list', console=['flagpoll'], scripts=['flagpoll'], long_description = "Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software. Think of it as the rpm of software development. It enables developers total control over which packages, versions, architectures, etc. that they want to use meta-data from.", data_files=[('share/flagpoll', ['flagpoll.fpc']), ('share/man/man1', ['flagpoll.1']), ('share/aclocal', ['flagpoll.m4']), ('share/html', ['flagpoll-manual.html'])] )
Python
#!/usr/bin/env python # ----------------------------------------------------------------- # # Flag Poll: A tool to extract flags from installed applications # for compiling, settting variables, etc. # # Original Authors: # Daniel E. Shipton <dshipton@gmail.com> # # Flag Poll is Copyright (C) 2006 by Daniel E. Shipton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to: # Free SoftwareFoundation, Inc. # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # # ----------------------------------------------------------------- """Makes a flagpole .fpc file from user input. v0.9 coded by Jeff Groves""" import os import sys import getopt ##String prompts for the input varPrompt = """Convience variables (one 'var_name= var_definition' per line,""" + \ """ empty line when done)""" namePrompt = "Formal Name" descriptionPrompt = "Description" urlPrompt = "URL" providesPrompt = "One or more names to look package up by: (Provides)" versionPrompt = "Version (x.y.z)" architecturePrompt = "Architecture" requirePrompt = "Requires" libPrompt = "Linker Flags (-lfoo -L/usr/lib)" staticLibPrompt = "Static Linking Flags/Libs (extra private libs)" compileFlagsPrompt = "Compile/Include Flags (-I/usr -fpge -O2)" fileNamePrompt = "FPC File's Name" def usage(): """Prints a list of acceptable arguments for fpcmaker.py.""" print """ Fpcmaker.py Options: -n, --name= : Sets %s -d, --description= : Sets %s -u, --url= : Sets %s -p, --provides= : Sets %s -v, --version= : Sets %s -a, --architecture= : Sets %s -r, --requires= : Sets %s -l, --libs= : Sets %s -c, --cflags= : Sets %s -s, --static= : Sets %s -f, --file= : Sets %s """ %(namePrompt, descriptionPrompt, urlPrompt, providesPrompt, versionPrompt, architecturePrompt, requirePrompt, libPrompt, compileFlagsPrompt, staticLibPrompt, fileNamePrompt) return def checkFileName(fileName): """Checks if the fpc file name's blank, contains slashes, or exists.""" nameCleared = False writeFile = True confirms = ['y', 'Y', 'yes', 'Yes'] ##Loops until the name clears or writing the file's aborted. while(not nameCleared and writeFile): ##If it's blank, give the option of aborting the program. if fileName == "": choice = raw_input("Do you want to abort writing the" + " .fpc file? (Y/N): ") if choice not in confirms: fileName = raw_input("Please enter a different name for the" + " .fpc file: ") else: writeFile = False ##If it contains slashes, ask for another name. elif '/' in fileName or '\\' in fileName: print "I can't write to %s because it contains slashes."%(fileName) fileName = raw_input("Please enter a different name for the" + " .fpc file: ") ##If it already exists, ask if they want to overwrite. ##If not, ask for another name. elif os.path.exists(fileName): choice = raw_input("The file %s already exists." %(fileName) + " Do you want to overwrite it? (Y/N): ") if choice not in confirms: fileName = raw_input("Please enter a different name for the" + " .fpc file: ") else: nameCleared = True else: nameCleared = True return [fileName, writeFile] ##Booleans for whether that argument was sent in the command line varSet = False providesSet = False nameSet = False descriptionSet = False urlSet = False architectureSet = False versionSet = False requiresSet = False libsSet = False compileFlagsSet = False staticLibSet = False fileNameSet = False ##Get the options & arguments sent. arguments = sys.argv[1:] try: opts, args = getopt.getopt(arguments, "p:n:u:d:a:r:v:l:c:s:f:", ["provides=", "name=", "url=", "description=", "architecture=", "requires=", "version=", "libs=", "cflags=", "static=", "file="]) ##Send them usage info if they enter a wrong argument except getopt.GetoptError: usage() sys.exit(2) for opt, arg in opts: if opt in ('-p', '--provides'): providesSet = True provides = arg elif opt in ('-n', '--name'): nameSet = True name = arg elif opt in ('-v', '--version'): versionSet = True version = arg elif opt in ('-u', '--url'): urlSet = True url = arg elif opt in ('-d', '--description'): descriptionSet = True description = arg elif opt in ('-a', '--architecture'): architectureSet = True architecture = arg elif opt in ('-r', '--requires'): requiresSet = True requires = arg elif opt in ('-l', '--libs'): libsSet = True libs = arg elif opt in ('-c', '--cflags'): compileFlagsSet = True compileFlags = arg elif opt in ('-s', '--static'): staticLibSet = True staticLib = arg elif opt in ('-f', '--file'): fileNameSet = True fileName = arg ##Grab any input not passed in the arguments from the user. if not varSet: varLine = None variables = "" print "%s:" %(varPrompt) while(varLine != ""): varLine = raw_input("") variables = variables + "%s\n" %(varLine) if not nameSet: name = raw_input("%s: " %(namePrompt)) if not descriptionSet: description = raw_input("%s: " %(descriptionPrompt)) if not urlSet: url = raw_input("%s: " %(urlPrompt)) if not versionSet: version = raw_input("%s: " %(versionPrompt)) if not providesSet: provides = raw_input("%s: " %(providesPrompt)) if not requiresSet: requires = raw_input("%s: " %(requirePrompt)) if not architectureSet: architecture = raw_input("%s: " %(architecturePrompt)) if not libsSet: libs = raw_input("%s: " %(libPrompt)) if not staticLibSet: staticLib = raw_input("%s: " %(staticLibPrompt)) if not compileFlagsSet: compileFlags = raw_input("%s: " %(compileFlagsPrompt)) if not fileNameSet: fileName = raw_input("%s: " %(fileNamePrompt)) ##Check the file's name. fileName, writeFile = checkFileName(fileName) ##If they chose not to overwrite, write the file. if writeFile: fpc = open(fileName, 'w') fpc.write("%s" %(variables)) fpc.write("Name: %s\n" %(name)) fpc.write("Description: %s\n" %(description)) fpc.write("URL: %s\n" %(url)) fpc.write("Version: %s\n" %(version)) fpc.write("Provides: %s\n" %(provides)) fpc.write("Requires: %s\n" %(requires)) fpc.write("Arch: %s\n" %(architecture)) fpc.write("Libs: %s\n" %(libs)) fpc.write("Libs.private: %s\n" %(staticLib)) fpc.write("Cflags: %s\n" %(compileFlags)) fpc.close() ##TESTER: Print the file out. fpc = open(fileName, 'r') ##TESTER print fpc.read() ##TESTER fpc.close ##TESTER
Python
#!/usr/bin/env python # ----------------------------------------------------------------- # # Flagpoll: A tool to extract flags from installed applications # for compiling, settting variables, etc. # # Original Authors: # Daniel E. Shipton <dshipton@gmail.com> # # Flagpoll is Copyright (C) 2006-2007 by Daniel E. Shipton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to: # Free SoftwareFoundation, Inc. # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # # ----------------------------------------------------------------- import sys, os, glob, os.path, copy, platform pj = os.path.join #################################################################### # SNAGGED FROM PYTHON 2.4 for versions under 2.4 #################################################################### import re as _re class _multimap: """Helper class for combining multiple mappings. Used by .{safe_,}substitute() to combine the mapping and keyword arguments. """ def __init__(self, primary, secondary): self._primary = primary self._secondary = secondary def __getitem__(self, key): try: return self._primary[key] except KeyError: return self._secondary[key] class _TemplateMetaclass(type): pattern = r""" %(delim)s(?: (?P<escaped>%(delim)s) | # Escape sequence of two delimiters (?P<named>%(id)s) | # delimiter and a Python identifier {(?P<braced>%(id)s)} | # delimiter and a braced identifier (?P<invalid>) # Other ill-formed delimiter exprs ) """ def __init__(cls, name, bases, dct): super(_TemplateMetaclass, cls).__init__(name, bases, dct) if 'pattern' in dct: pattern = cls.pattern else: pattern = _TemplateMetaclass.pattern % { 'delim' : _re.escape(cls.delimiter), 'id' : cls.idpattern, } cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE) class Template: """A string class for supporting $-substitutions.""" __metaclass__ = _TemplateMetaclass delimiter = '$' idpattern = r'[_a-z][_a-z0-9]*' def __init__(self, template): self.template = template # Search for $$, $identifier, ${identifier}, and any bare $'s def _invalid(self, mo): i = mo.start('invalid') lines = self.template[:i].splitlines(True) if not lines: colno = 1 lineno = 1 else: colno = i - len(''.join(lines[:-1])) lineno = len(lines) raise ValueError('Invalid placeholder in string: line %d, col %d' % (lineno, colno)) def substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): # Check the most common path first. named = mo.group('named') or mo.group('braced') if named is not None: val = mapping[named] # We use this idiom instead of str() because the latter will # fail if val is a Unicode containing non-ASCII characters. return '%s' % val if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: self._invalid(mo) raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) def safe_substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): named = mo.group('named') if named is not None: try: # We use this idiom instead of str() because the latter # will fail if val is a Unicode containing non-ASCII return '%s' % mapping[named] except KeyError: return self.delimiter + named braced = mo.group('braced') if braced is not None: try: return '%s' % mapping[braced] except KeyError: return self.delimiter + '{' + braced + '}' if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: return self.delimiter raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) #################################################################### # End Snagging #################################################################### def tokenize(val, split_char): val = val.strip() results = [] while len(val) > 0: sn = val.find(split_char) qn = val.find('"') #print " -> val: %s Len: %s" % (val, len(val)) # If we find a quote first, then find the space after the next quote. if qn < sn: #print " -> Found a quote first:", qn # Find next quote. qn2 = val.find('"', qn+1) #print " -> Found second quote:", qn2 sn = val.find(split_char, qn2+1) #print " -> Found next space:", sn if sn < 0: results.append(val[:]) val = "" else: results.append(val[:sn]) val = val[sn:] val = val.strip() return results class Utils: # Holds collection of small utility functions EXTRA_FLAGPOLL_SEARCH_PATHS = "" EXTRA_FLAGPOLL_FILES = "" path_list_cache = None # Cache of found path lists. (only calcuate once) KEEP_DUPS = False FLAGPOLL_LIST_OF_POSSIBLE_ERRORS = [] def addPossibleError(pos_err): Utils.FLAGPOLL_LIST_OF_POSSIBLE_ERRORS.append(pos_err) addPossibleError = staticmethod(addPossibleError) def getPossibleErrors(): return Utils.stripDupInList(Utils.FLAGPOLL_LIST_OF_POSSIBLE_ERRORS) getPossibleErrors = staticmethod(getPossibleErrors) def getFlagpollVersion(): FLAGPOLL_MAJOR_VERSION = 0 FLAGPOLL_MINOR_VERSION = 9 FLAGPOLL_PATCH_VERSION = 4 return ( FLAGPOLL_MAJOR_VERSION, FLAGPOLL_MINOR_VERSION, FLAGPOLL_PATCH_VERSION ) getFlagpollVersion = staticmethod(getFlagpollVersion) def getPathList(): if None != Utils.path_list_cache: return Utils.path_list_cache #TODO: expand LD_LIBRARY_PATH to 64/32/etc??? pkg_cfg_dir = [] flg_cfg_dir = [] ld_path = [] if os.environ.has_key("PKG_CONFIG_PATH"): pkg_cfg_dir = os.environ["PKG_CONFIG_PATH"].split(os.pathsep) if os.environ.has_key("FLAGPOLL_PATH"): flg_cfg_dir = os.environ["FLAGPOLL_PATH"].split(os.pathsep) ld_dirs = ['LD_LIBRARY_PATH', 'DYLD_LIBRARY_PATH', 'PATH'] for d in ld_dirs: if os.environ.has_key(d): cur_path = os.environ[d].split(os.pathsep) ld_path_pkg = [pj(p,'pkgconfig') for p in cur_path] ld_path_flg = [pj(p,'flagpoll') for p in cur_path] ld_path.extend(ld_path_pkg) ld_path.extend(ld_path_flg) extra_paths = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS.split(os.pathsep) path_list = extra_paths path_list.extend(flg_cfg_dir) path_list.extend(pkg_cfg_dir) path_list.extend(ld_path) default_path_list = [pj('/','usr','lib64'), pj('/','usr','lib32'), pj('/','usr','lib'), pj('/','usr','share')] default_path_pkg = [pj(p,'pkgconfig') for p in default_path_list] default_path_flg = [pj(p,'flagpoll') for p in default_path_list] path_list.extend(default_path_pkg) path_list.extend(default_path_flg) flagDBG().out(flagDBG.VERBOSE, "Utils.getPathList", "Potential path list: " + str(path_list)) clean_path_list = [] for p in path_list: if os.path.exists(p) and os.path.isdir(p) and not p in clean_path_list: clean_path_list.append(p) path_list = clean_path_list flagDBG().out(flagDBG.INFO, "Utils.getPathList", "Using path list: " + str(path_list)) Utils.path_list_cache = path_list return path_list getPathList = staticmethod(getPathList) def getFileList(): flist = Utils.EXTRA_FLAGPOLL_FILES.split(":") filelist = [] for f in flist: if os.path.isfile(f): filelist.append(f) return filelist getFileList = staticmethod(getFileList) def setKeepDups(keep_dups): Utils.KEEP_DUPS = keep_dups setKeepDups = staticmethod(setKeepDups) def stripDupInList(gen_list): new_list = [] list_len = len(gen_list) i = 0 while i < list_len: item = gen_list[i].strip() if Utils.KEEP_DUPS: if len(item) > 0: new_list.append(item) continue if item in ('-framework', '-arch', '-isysroot'): item = '%s %s' % (item, gen_list[i + 1]) i += 1 if item not in new_list: if len(item) > 0: new_list.append(item) i += 1 return new_list stripDupInList = staticmethod(stripDupInList) def stripDupLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] dir_list = [] list_len = len(flag_list) i = 0 vc_linker_flag_re = _re.compile(r'^[/-]libpath:', _re.I) other_linker_flag_re = _re.compile(r'^-[LRF]') while i < list_len: flg = flag_list[i].strip() if len(flg) > 0: if (other_linker_flag_re.match(flg) is not None\ or vc_linker_flag_re.match(flg) is not None): dir_list.append(flg) else: if flg in ("-framework", "-arch", "-isysroot"): flg = "%s %s" % (flg, flag_list[i + 1]) i += 1 lib_list.append(flg) i += 1 new_list = dir_list + lib_list return Utils.stripDupInList(new_list) stripDupLinkerFlags = staticmethod(stripDupLinkerFlags) def stripDupIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] extra_list = [] list_len = len(flag_list) i = 0 while i < list_len: flg = flag_list[i].strip() if len(flg) > 0: if flg.startswith("-I") or flg.startswith("/I"): inc_list.append(flg) elif flg in ("-arch", "-isysroot"): extra_list.append("%s %s" % (flg, flag_list[i + 1])) i += 1 else: extra_list.append(flg) i += 1 extra_list.sort() new_list = inc_list + extra_list return Utils.stripDupInList(new_list) stripDupIncludeFlags = staticmethod(stripDupIncludeFlags) def cflagsOnlyDirIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-I") or flg.startswith("/I"): inc_list.append(flg) return Utils.stripDupInList(inc_list) cflagsOnlyDirIncludeFlags = staticmethod(cflagsOnlyDirIncludeFlags) def cflagsOnlyOtherIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though extra_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if not flg.startswith("-I") and not flg.startswith("/I"): extra_list.append(flg) return Utils.stripDupInList(extra_list) cflagsOnlyOtherIncludeFlags = staticmethod(cflagsOnlyOtherIncludeFlags) def libsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-l") or flg.endswith(".lib"): lib_list.append(flg) return Utils.stripDupInList(lib_list) libsOnlyLinkerFlags = staticmethod(libsOnlyLinkerFlags) def libsOnlyOtherLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though other_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: upper_flg = flg.upper() if not flg.startswith("-l") \ and not flg.startswith("-L")\ and not flg.startswith("-R")\ and not upper_flg.startswith("/LIBPATH")\ and not upper_flg.startswith("-LIBPATH")\ and not flg.endswith(".lib"): other_list.append(flg) return Utils.stripDupInList(other_list) libsOnlyOtherLinkerFlags = staticmethod(libsOnlyOtherLinkerFlags) def libDirsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though dir_list = [] vc_linker_flag_re = _re.compile(r'^[/-]libpath:', _re.I) other_linker_flag_re = _re.compile(r'^-[LRF]') for flg in flag_list: flg = flg.strip() if len(flg) > 0: if (other_linker_flag_re.match(flg) is not None or vc_linker_flag_re.match(flg) is not None): dir_list.append(flg) return Utils.stripDupInList(dir_list) libDirsOnlyLinkerFlags = staticmethod(libDirsOnlyLinkerFlags) def printList(gen_list): list_string = "" for item in gen_list: if len(item) > 0: list_string += str(item) list_string += " " print list_string.strip() printList = staticmethod(printList) def parsePcFile(filename): lines = open(filename).readlines() fvars = {} fvars["FlagpollFilename"] = filename lokals = {} lokals["fp_file_cwd"] = str(filename[:- ((len(os.path.basename(filename) ) + 1))]) lines.append("prefix: ${prefix}") append_next = False append_dict = {} append_key = "" for line in lines: line = line.strip() if not line: continue if append_next: tmp = append_dict[append_key] tmp = tmp[:-1] + " " + line append_dict[append_key] = tmp if tmp[-1:] == "\\": append_next = True else: append_next = False continue if line.startswith("#"): continue eq_pos = line.find('=') col_pos = line.find(':') if eq_pos < col_pos and eq_pos != -1 or col_pos == -1 and eq_pos != -1: # local variable name, val = line.split('=', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(lokals) except ValueError: flagDBG().out(flagDBG.WARN, "PkgInfo.parse", "%s has an invalid metadata file" % filename) lokals[name] = val if val[-1:] == "\\": append_next = True append_dict = lokals append_key = name continue if col_pos < eq_pos and col_pos != -1 or eq_pos == -1 and col_pos != -1: # exported variable name, val = line.split(':', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(lokals) except ValueError: flagDBG().out(flagDBG.ERROR, "PkgInfo.parse", "%s has an invalid metadata file" % filename) fvars[name] = val if val[-1:] == "\\": append_next = True append_dict = fvars append_key = name return fvars parsePcFile = staticmethod(parsePcFile) class flagDBG(object): # Logging class is really easy to use # Levels: # 0 - VERBOSE # 1 - INFO # 2 - WARN # 3 - ERROR VERBOSE = 0 INFO = 1 WARN = 2 ERROR = 3 __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if flagDBG.__initialized: return flagDBG.__initialized = True self.mLevel = self.WARN self.mLevelList = ["VERBOSE", "INFO", "WARN", "ERROR"] def setLevel(self, level): if level <= 3: self.mLevel = level def out(self, level, obj, message): if level == self.ERROR: if self.mLevel == self.VERBOSE: print self.mLevelList[level] + ":" + str(obj) + ": " + str(message) else: sys.stderr.write(self.mLevelList[level] + ": " + str(message) + "\n") errs = Utils.getPossibleErrors() if len(errs) > 0: sys.stderr.write("Possible culprits:\n") for pos_err in errs: sys.stderr.write( " " + str(pos_err) + "\n" ) sys.exit(1) if level >= self.mLevel: print self.mLevelList[level] + ":" + str(obj) + ": " + str(message) class DepResolutionSystem(object): """ You add PkgAgents with Filters into system and call resolve() you can check for succes by depsSatisfied() and get the list of packages that work back by calling getPackages() """ __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if DepResolutionSystem.__initialized: return DepResolutionSystem.__initialized = True self.mResolveAgents = [] self.mAgentDict = {} self.mFilters = [] self.mResolveAgentFilters = [] self.mInvalidPackageList = [] self.mSatisfied = False self.mAgentChangeList = [] # list of those responsible for adding Filters # to agents in higher in the chain than them # these are the first agents to ask that they pick # the next best package of them self.mAgentsVisitedList = [] # list of Agents that have been visited self.mResolvedPackageList = [] # list that is generated when deps are satified self.mCheckPrivateRequires = False self.mMadeDependList = False def getFilters(self): return self.mFilters def addFilter(self, filter): self.mFilters.append(filter) def addResolveAgentFilter(self, filter): self.mResolveAgentFilters.append(filter) def makeRequireFilter(self, requires): arch_list = [] arch_list.append("no_arch") arch_list.append("") if platform.system() == "Linux": if requires == "64": arch_list.append("x86_64") arch_list.append("x64") if requires == "32": arch_list.append("i386") arch_list.append("i486") arch_list.append("i586") arch_list.append("i686") if platform.system() == "Darwin": if requires == "64": arch_list.append("ppc64") if requires == "32": arch_list.append("ppc") if platform.system().startswith("IRIX"): arch_list.append(requires) new_filter = Filter("Arch", lambda x,v=arch_list: x in v) self.addFilter(new_filter) def createAgent(self, name): if self.checkAgentExists(name): return self.getAgent(name) else: agent = PkgAgent(name) flagDBG().out(flagDBG.INFO, "DepResSys.createAgent", "Adding %s" % name) self.addNewAgent(agent) return agent def createResolveAgent(self, name): if self.checkAgentExists(name): return self.getAgent(name) else: agent = PkgAgent(name) flagDBG().out(flagDBG.INFO, "DepResSys.createResolveAgent", "Adding %s" % name) self.addResolveAgent(agent) return agent def setPrivateRequires( self, req ): self.mCheckPrivateRequires = req def checkPrivateRequires(self): return self.mCheckPrivateRequires def checkAgentExists(self, name): return self.mAgentDict.has_key(name) def getAgent(self, name): if self.mAgentDict.has_key(name): return self.mAgentDict[name] else: flagDBG().out(flagDBG.ERROR, "DepResSys.getAgent", "Agent %s does not exist" % name) def addNewAgent(self, agent): if not self.checkAgentExists(agent): self.mAgentDict[agent.getName()] = agent def addResolveAgent(self, agent): if agent not in self.mResolveAgents: self.mResolveAgents.append(agent) for filt in self.mResolveAgentFilters: agent.addFilter(filt) def isSatisfied(self): return self.mSatisfied def updateResolvedPackages(self): pkg_list = [] agent_list = [] for agent in self.mResolveAgents: list_of_pkgs = agent.getCurrentPackageList(agent_list) pkg_list.extend(list_of_pkgs) self.mResolvedPackageList = pkg_list def getPackages(self): flagDBG().out(flagDBG.INFO, "DepResSys.getPackages", "Generating list of valid packages ") #str([pkg.getCurrentPackage.getName() for pkg in self.mResolvedPackageList])) # If this comes back empty then there isn't a valid set of packages to use self.updateResolvedPackages() return self.mResolvedPackageList def checkFiltersChanged(self): list_to_use = [] return True in [pkg.filtersChanged(list_to_use) for pkg in self.mResolveAgents] def resolveHelper(self): self.resolveAgentsChanged = True while self.resolveAgentsChanged: for agent in self.mResolveAgents: flagDBG().out(flagDBG.INFO, "DepResSys.resolveHelper", "Updating " + agent.getName()) agent.update(self.mAgentsVisitedList, self.mAgentChangeList) self.resolveAgentsChanged = self.checkFiltersChanged() # Ask mResolveAgents if they are done(they ask sub people) unless they are # really above you in the walk # If there were changes...run update on mResolveAgents again # at the end ask for pkglist..if it comes back empty then we don't # have a usable configuration for those packages def resolveDeps(self): self.resolveHelper() if not self.mMadeDependList: for agent in self.mResolveAgents: agent.makeDependList() self.mMadeDependList = True self.updateResolvedPackages() # Check if the first round through we found something # Otherwise we need to start removing packages that aren't viable # during the loop self.mSatisfied = (len(self.mResolvedPackageList) != 0) # remove top of packages that added Filters. # then move on to resolving again # remove more if neccesary agentChangeNumber = 0 while not self.mResolvedPackageList: if(self.mAgentChangeList[agentChangeNumber]): if self.mAgentChangeList[agentChangeNumber] in self.mInvalidPackageList: agentChangeNumber += 1 else: if(self.mAgentChangeList[agentChangeNumber].getViablePackages()): flagDBG().out(flagDBG.INFO, "DepResSys.resolveDeps", "Removing bad pkg from " + self.mAgentChangeList[agentChangeNumber].getName()) self.mInvalidPackageList.append(self.mAgentChangeList[agentChangeNumber].removeCurrentPackage()) else: flagDBG().out(flagDBG.INFO, "DepResSys.resolveDeps", "No combinations.. Resetting " + self.mAgentChangeList[agentChangeNumber].getName()) self.mAgentChangeList[agentChangeNumber].reset() agentChangeNumber += 1 self.resolveHelper() self.updateResolvedPackages() self.mSatisfied = (len(self.mResolvedPackageList) != 0) return class PkgAgent: """ Agent that keeps track of the versions for a package given some filters and the addition of Filters """ # Makes a PkgAgent that finds its current package with the version reqs def __init__(self, name): if DepResolutionSystem().checkAgentExists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "Package Agent %s already exists" % self.mName) self.mName = name flagDBG().out(flagDBG.INFO, "PkgAgent", "Creating:" + str(self.mName)) if not PkgDB().exists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "No info for package: %s" % self.mName) #XXX Doesn't keep filters added for a redo... DepResolutionSystem().addNewAgent(self) self.mFilterList = [] self.mFilterList.extend(DepResolutionSystem().getFilters()) self.mBasePackageList = PkgDB().getPkgInfos(name) self.mBasePackageList.sort(lambda lhs, rhs: cmp(rhs.getVariable('Version'), lhs.getVariable('Version'))) for filt in self.mFilterList: self.mBasePackageList = filt.filter(self.mBasePackageList) if len(self.mBasePackageList) == 0: flagDBG().out(flagDBG.ERROR, "PkgAgent", "No viable packages for: %s" % self.mName) self.mViablePackageList = copy.deepcopy(self.mBasePackageList) if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mFiltersChanged = True self.mCheckDepends = True self.mAgentDependList = [] def getName(self): return self.mName def setCheckDepends(self, tf): self.mCheckDepends = tf #Filter("Version", lambda x: x == "4.5") def makeDependList(self): if not self.mCheckDepends: self.mAgentDependList = [] return dep_list = [] if self.mCurrentPackage: req_string = self.mCurrentPackage.getVariable("Requires") if DepResolutionSystem().checkPrivateRequires(): req_string = req_string + " " + self.mCurrentPackage.getVariable("Requires.private") req_string = req_string.strip() if req_string == "": return req_string = req_string.replace(',', ' ') req_string = req_string.replace('(', ' ') req_string = req_string.replace(')', ' ') space_req_string_list = req_string.split(' ') req_string_list = [] for entry in space_req_string_list: if len(entry) > 0: req_string_list.append(entry) i = 0 flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList", self.mCurrentPackage.getName() + " requires: " + str(req_string_list)) while len(req_string_list) > i: if PkgDB().exists(req_string_list[i]): new_filter = [] new_agent = DepResolutionSystem().createAgent(req_string_list[i]) if len(req_string_list) > i+1: if req_string_list[i+1] == "=": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x == v) elif req_string_list[i+1] == "<=": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x <= v) elif req_string_list[i+1] == ">=": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x >= v) elif req_string_list[i+1] == ">": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x > v) elif req_string_list[i+1] == "<": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x < v) else: i += 1 else: i += 1 dep_list.append(new_agent) if new_filter: i+=3 new_agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "PkgAgent.makeDependList", "Package %s depends on %s but does not seem to be installed." % (self.mName, str(req_string_list[i]))) flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList", str(self.mName) + " : List is:" + str([pkg.getName() for pkg in dep_list])) self.mAgentDependList = dep_list def filtersChanged(self, packageList): tf_list = [self.mFiltersChanged] if self.mName not in packageList: packageList.append(self.mName) for pkg in self.mAgentDependList: tf_list.append(pkg.filtersChanged(packageList)) return True in tf_list def getCurrentPackageList(self, packageList): pkgs = [] if self.mName not in packageList: flagDBG().out(flagDBG.INFO, "PkgAgent.getCurrentPackageList", "Package: %s" % self.mName) pkgs.append(self.mCurrentPackage) packageList.append(self.mName) # Make depend list if we are supposed to self.updateFilters() self.makeDependList() for pkg in self.mAgentDependList: pkgs.extend(pkg.getCurrentPackageList(packageList)) return pkgs # current pkginfo for me def getCurrentPkgInfo(self): return self.mCurrentPackage # Someone else usually places these on me # I keep track of those separately def addFilter(self, filter): flagDBG().out(flagDBG.INFO, "PkgAgent.addFilter", "Filter %s" % self.mName + " on %s." % filter.getVarName()) self.mFiltersChanged = True self.mFilterList.append(filter) def removeCurrentPackage(self): flagDBG().out(flagDBG.INFO, "PkgAgent.removeCurrentPackage", "Removing current package of %s" % self.mName) if self.mViablePackageList: ret_val = self.mViablePackageList[0] in self.mBasePackageList del self.mViablePackageList[0] if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] return ret_val def update(self, agentVisitedList, agentChangeList): flagDBG().out(flagDBG.INFO, "PkgAgent.update", "%s" % self.mName) if self.mName in agentVisitedList: return agentVisitedList.append(self.mName) if self.mFiltersChanged: self.mFiltersChanged = False self.updateFilters() # TODO: checkFilters and add them # if a pkg is in visitedList then add yourself to agentChangeList for pkg in self.mAgentDependList: pkg.update(agentVisitedList, agentChangeList) return def updateFilters(self): for filt in self.mFilterList: self.mViablePackageList = filt.filter(self.mViablePackageList) flagDBG().out(flagDBG.INFO, "PkgAgent.updateFilters", "%s has " % self.mName + str(len(self.mViablePackageList)) + " left") if len(self.mViablePackageList) > 0: self.mCurrentPackage = self.mViablePackageList[0] else: for f in self.mFilterList: Utils.addPossibleError(str(self.mName) + " -> " + str(f.getVarName())) self.mCurrentPackage = [] def reset(self): flagDBG().out(flagDBG.INFO, "PkgAgent.reset", "Resetting package: %s" % self.mName) self.mViablePackageList = self.mBasePackageList if self.mViablePackageList: self.mCurrentPacakge = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mFilterList = DepResolutionSystem().getFilters() self.mAgentDependList = [] self.mFiltersChanged = True return class Filter: """ A single Filter that knows how to filter the list it recieves Will be inheireted....?..? """ def __init__(self, variableName, testCallable): self.mVarName = variableName self.mTestCallable = testCallable def getVarName(self): return self.mVarName def filter(self, pkg_info_list): ret_pkg_list = [] # Filter first for pkg in pkg_info_list: var = pkg.getVariable(self.mVarName) if self.mTestCallable(var): flagDBG().out(flagDBG.INFO, "Filter", "Passed: %s:" % pkg.getName() + " %s is " % self.mVarName + str(var)) ret_pkg_list.append(pkg) else: flagDBG().out(flagDBG.INFO, "Filter", "Failed: %s:" % pkg.getName() + " %s is " % self.mVarName + str(var)) # Now sort ret_pkg_list.sort(lambda lhs, rhs: cmp(rhs.getVariable(self.mVarName), lhs.getVariable(self.mVarName))) return ret_pkg_list #requires: qt == 4.5 #Filter("Version", lambda x: x <= "4.5") #Filter("Version", lambda x: x <= "4.5") class PkgDB(object): """ Holds all the neccesary information to evaluate itself when needed. Is in charge of holding a list of PkgInfo's that contain info about the package. """ __initialized = False def __init__(self): if self.__initialized: return self.__initialized = True self.mPkgInfos = {} # {pkg_name: List of package infos} self.populatePkgInfoDBPcFiles() self.populatePkgInfoDBFpcFiles() def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def printAllPackages(self): list_of_package_names = [] for pkg in self.mPkgInfos: list_of_package_names.append(pkg) for name in list_of_package_names: print name sys.exit(0) def getVariables(self, name, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariable", "Finding " + str(variable_list) + " in " + str(name)) ret_list = [] for var in variable_list: if self.mPkgInfos.has_key(name): ret_list.extend(self.mPkgInfos[name][0].getVariable(var)) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariable", "Package %s not found." % name) return ret_list def checkPackage(self, name): flagDBG().out(flagDBG.INFO, "PkgDB.checkPackage", "Finding " + str(name)) if self.mPkgInfos.has_key(name): return True else: flagDBG().out(flagDBG.ERROR, "PkgDB.CheckPackage", "Package %s not found." % name) return False def getVariablesAndDeps(self, pkg_list, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariablesAndDeps", "Finding " + str(variable_list) + " in " + str(pkg_list)) if DepResolutionSystem().checkPrivateRequires(): temp_var_list = [] for var in variable_list: temp_var_list.append(var.join(".private")) variable_list = variable_list + temp_var_list for name in pkg_list: if self.mPkgInfos.has_key(name): agent = DepResolutionSystem().createAgent(name) DepResolutionSystem().addResolveAgent(agent) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariablesAndDeps", "Package %s not found." % name) DepResolutionSystem().resolveDeps() pkgs = DepResolutionSystem().getPackages() var_list = [] for pkg in pkgs: if pkg: for var in variable_list: var_list.extend(tokenize(pkg.getVariable(var), pkg.getSplitChar())) return var_list def getPkgInfos(self, name): if self.mPkgInfos.has_key(name): return self.mPkgInfos[name] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getPkgInfos", "Package %s not found." % name) def exists(self, name): return self.mPkgInfos.has_key(name) def getInfo(self, name): if self.mPkgInfos.has_key(name): return [pkg.getInfo() for pkg in self.mPkgInfos[name]] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getInfo", "Package %s not found." % name) def buildPcFileDict(self): """ Builds up a dictionary of {name: list of files for name} """ pc_dict = {} for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.pc")) # List of .pc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these pc files: %s" % str(glob_list)) for g in glob_list: # Get key name and add file to value list in dictionary key = os.path.basename(g)[:-3] # Strip .pc off the filename...rstrip no worky pc_dict.setdefault(key, []).append(g) for f in Utils.getFileList(): if f.endswith(".pc"): key = os.path.basename(f)[:-3] # Strip .pc off the filename...rstrip no worky pc_dict.setdefault(key, []).append(f) return pc_dict # { "key", [ "list", "of", "corresponding", "pc", "files"] } def populatePkgInfoDBPcFiles(self): dict_to_pop_from = self.buildPcFileDict() for (pkg,files) in dict_to_pop_from.iteritems(): for f in files: self.mPkgInfos.setdefault(pkg,[]).append(PkgInfo(pkg, f, "pc")) def buildFpcFileList(self): """ Builds up a dictionary of {name: list of files for name} """ file_list = [] for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.fpc")) # List of .fpc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these fpc files: %s" % str(glob_list)) for g in glob_list: file_list.append(g) for f in Utils.getFileList(): if f.endswith(".fpc"): file_list.append(f) return file_list # [ "list", "of", "fpc", "files"] def populatePkgInfoDBFpcFiles(self): list_to_add = self.buildFpcFileList() for filename in list_to_add: var_dict = Utils.parsePcFile(filename) if not var_dict.has_key("Provides"): flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Provides" % str(filename)) continue if not var_dict.has_key("Arch"): flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Arch" % str(filename)) continue provides_string = var_dict["Provides"] provides_string = provides_string.replace(',', ' ') provides_string = provides_string.replace('(', ' ') provides_string = provides_string.replace(')', ' ') for key in provides_string.split(" "): if len(key) > 0: self.mPkgInfos.setdefault(key, []).append(PkgInfo(key, filename, "fpc", var_dict)) class PkgInfo: """ Holds the information for a package file on the system. These however are evaluated when the need arises. """ def __init__(self, name, file, type, varDict={}): self.mName = name self.mFile = file self.mIsEvaluated = False self.mType = type self.mVariableDict = varDict if self.mType == "fpc": self.mIsEvaluated = True def getVariable(self, variable): self.evaluate() return self.mVariableDict.get(variable,"") def getName(self): return self.mName def evaluate(self): if not self.mIsEvaluated: flagDBG().out(flagDBG.INFO, "PkgInfo.evaluate", "Evaluating %s" % self.mName) self.mVariableDict= Utils.parsePcFile(self.mFile) self.mIsEvaluated = True def getInfo(self): self.evaluate() return self.mVariableDict def getSplitChar(self): self.evaluate() split_char = self.mVariableDict.get("SplitCharacter", ' ') if split_char == "": split_char = ' ' return split_char class OptionsEvaluator: def __init__(self): if len(sys.argv) < 2: self.printHelp() # This is only the args....(first arg is stripped) def evaluateArgs(self, args): # Catch any args that need to be tended to immediately # Process args in the order that they were recieved. Some options are not # shown below because they are sub-options of an option below (--strip-dups) for option in args: if option.startswith("--verbose-debug"): flagDBG().setLevel(flagDBG.VERBOSE) if option.startswith("--debug"): flagDBG().setLevel(flagDBG.INFO) elif option.startswith("--from-file"): val_start = option.find('=') + 1 file = option[val_start:] Utils.EXTRA_FLAGPOLL_FILES = Utils.EXTRA_FLAGPOLL_FILES + ":" + file elif option.startswith("--help"): self.printHelp() sys.exit(0) elif option.startswith("--version"): print "%s.%s.%s" % Utils.getFlagpollVersion() sys.exit(0) elif option.startswith("--list-all"): PkgDB().printAllPackages() continue listedAgentNames = [] agent = None num_args = len(args) curr_arg = 0 output_options = [] # (option, name/"") important_options = [] # ones that need special attention while curr_arg < num_args: if args[curr_arg].startswith("--atleast-version"): val_start = args[curr_arg].find('=') + 1 atleast_version = args[curr_arg][val_start:] atleast_filter = Filter("Version", lambda x,v=atleast_version: x >= v) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(atleast_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --at-least-version") continue if args[curr_arg].startswith("--cflags-only-I"): output_options.append(("cflags-only-I", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--cflags-only-other"): output_options.append(("cflags-only-other", "")) curr_arg = curr_arg + 1 continue #This could be the catch all for the above ones to and then filter based on what is asked... #For clarity of course... if args[curr_arg].startswith("--cflags"): output_options.append(("cflags", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--extra-paths"): val_start = args[curr_arg].find('=') + 1 paths = args[curr_arg][val_start:] Utils.EXTRA_FLAGPOLL_SEARCH_PATHS = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS + ":" + paths curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--exact-version"): val_start = args[curr_arg].find('=') + 1 exact_version = args[curr_arg][val_start:] exact_filter = Filter("Version", lambda x,v=exact_version: x == v) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(exact_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --exact-version") continue if args[curr_arg].startswith("--exists"): important_options.append("exists") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--from-file"): val_start = args[curr_arg].find('=') + 1 file = args[curr_arg][val_start:] file_filter = Filter("FlagpollFilename", lambda x,f=file: x == f) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(file_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --from-file") continue if args[curr_arg].startswith("--info"): important_options.append("info") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--print-pkg-options"): important_options.append("print-pkg-options") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--keep-dups"): Utils.setKeepDups(True) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-l"): output_options.append(("libs-only-l", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-L"): output_options.append(("libs-only-L", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-other"): output_options.append(("libs-only-other", "")) curr_arg = curr_arg + 1 continue #This could be the catch all for the above ones to and then filter based on what is asked... if args[curr_arg].startswith("--libs"): output_options.append(("libs", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--require-all"): rlen = len("--require-all") req_string = args[curr_arg][rlen:] req_string = req_string.replace('-','_') curr_arg = curr_arg + 1 if req_string.find("<=") != -1: op_start = req_string.find("<=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x <= v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find(">=") != -1: op_start = req_string.find(">=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x >= v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find(">") != -1: op_start = req_string.find(">") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x > v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("<") != -1: op_start = req_string.find("<") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x < v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("=") != -1: op_start = req_string.find("=") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x == v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("=") == -1: new_filter = Filter(req_string, lambda x: len(x) > 0) DepResolutionSystem().addFilter(new_filter) continue continue if args[curr_arg].startswith("--require-"): rlen = len("--require-") req_string = args[curr_arg][rlen:] req_string = req_string.replace('-','_') curr_arg = curr_arg + 1 if agent is None: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --require") if req_string.find("<=") != -1: op_start = req_string.find("<=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x <= v) agent.addFilter(new_filter) continue if req_string.find(">=") != -1: op_start = req_string.find(">=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x >= v) agent.addFilter(new_filter) continue if req_string.find(">") != -1: op_start = req_string.find(">") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x > v) agent.addFilter(new_filter) continue if req_string.find("<") != -1: op_start = req_string.find("<") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x < v) agent.addFilter(new_filter) continue if req_string.find("=") != -1: op_start = req_string.find("=") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x == v) agent.addFilter(new_filter) continue if req_string.find("=") == -1: new_filter = Filter(req_string, lambda x: len(x) > 0) agent.addFilter(new_filter) continue continue if args[curr_arg].startswith("--no-deps"): if agent is not None: agent.setCheckDepends(False) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --no-deps") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--require="): val_start = args[curr_arg].find('=') + 1 req_var = args[curr_arg][val_start:] curr_arg = curr_arg + 1 DepResolutionSystem().makeRequireFilter(req_var) continue if args[curr_arg].startswith("--modversion"): if agent is not None: output_options.append(("Version", agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --modversion") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--max-release"): val_start = args[curr_arg].find('=') + 1 max_release = args[curr_arg][val_start:] max_filter = Filter("Version", lambda x,v=max_release: x.startswith(v)) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(max_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --max-release") continue if args[curr_arg].startswith("--static"): DepResolutionSystem().setPrivateRequires(True) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--variable"): val_start = args[curr_arg].find('=') + 1 fetch_var = args[curr_arg][val_start:] if agent is not None: output_options.append((fetch_var, agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --variable") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--get-all"): rlen = len("--get-all-") get_string = args[curr_arg][rlen:] get_string = get_string.replace('-','_') output_options.append((get_string, "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--get"): rlen = len("--get-") get_string = args[curr_arg][rlen:] get_string = get_string.replace('-','_') if agent is not None: output_options.append((get_string, agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --get") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--concat"): important_options.append("concat") curr_arg = curr_arg + 1 continue if not args[curr_arg].startswith("--"): name = args[curr_arg] curr_arg = curr_arg + 1 if PkgDB().checkPackage(name): agent = DepResolutionSystem().createResolveAgent(name) listedAgentNames.append(name) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Package %s" % name) sys.exit(1) continue if args[curr_arg] != "--debug" and args[curr_arg] != "--verbose-debug": flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Option: %s" % args[curr_arg]) curr_arg = curr_arg + 1 if len(listedAgentNames) == 0: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Must specify at least one package") DepResolutionSystem().resolveDeps() pkgs = DepResolutionSystem().getPackages() for p in pkgs: if not p: for option in important_options: if option == "exists": print "no" sys.exit(1) flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found") if len(pkgs) == 0: for option in important_options: if option == "exists": print "no" sys.exit(1) flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found") sys.exit(1) concat = False for option in important_options: if option == "exists": print "yes" return sys.exit(0) # already checked for none above if option == "concat": concat = True if option == "info": pkg_info_list = [] for pkg in pkgs: if pkg.getName() in listedAgentNames: print pkg.getName() pkg_info = pkg.getInfo() for key in pkg_info.keys(): print " %s : %s" % (key, pkg_info[key]) if option == "print-pkg-options": print "" print "All options below would start with (--get-/--get-all-/--require-/--require-all-)" print "NOTE: this list does not include the standard variables that are exported." print "" for pkg in pkgs: if pkg.getName() not in listedAgentNames: continue print "Package: " + pkg.getName() for key in pkg.getInfo().keys(): if key not in [ "Name", "Description", "URL", "Version", "Requires", "Requires.private", "Conflicts", "Libs", "Libs.private", "Cflags", "Provides", "Arch", "FlagpollFilename", "prefix" ]: print " " + key.replace('_','-') #print output_options #output_options = [] #output_single = [] #Process options here.............. concat_list = [] if concat: print_option = lambda x: concat_list.extend(x) else: print_option = lambda x: Utils.printList(x) for option in output_options: if option[0] == "cflags": print_option(Utils.stripDupIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "cflags-only-I": print_option(Utils.cflagsOnlyDirIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "cflags-only-other": print_option(Utils.cflagsOnlyOtherIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "libs-only-l": print_option(Utils.libsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs-only-L": print_option(Utils.libDirsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs-only-other": print_option(Utils.libsOnlyOtherLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs": print_option(Utils.stripDupLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) else: print_option(Utils.stripDupInList(self.getVarFromPkgs(option[0], pkgs, option[1]))) if concat: Utils.printList(Utils.stripDupInList(concat_list)) def getVarFromPkgs(self, var, pkgs, pkg_name=""): var_list = [] ext_vars = [] if var == "Libs": if DepResolutionSystem().checkPrivateRequires: ext_vars.append("Libs.private") if pkg_name == "": for pkg in pkgs: if pkg: var_list.extend(tokenize(pkg.getVariable(var), pkg.getSplitChar())) for extra_var in ext_vars: var_list.extend(tokenize(pkg.getVariable(extra_var), pkg.getSplitChar())) else: for pkg in pkgs: if pkg: if pkg.getName() == pkg_name: var_list.extend(tokenize(pkg.getVariable(var), pkg.getSplitChar())) for extra_var in ext_vars: var_list.extend(tokenize(pkg.getVariable(extra_var), pkg.getSplitChar())) return var_list def printHelp(self): print "usage: flagpoll pkg options [pkg options] [generic options]" print " " print "generic options:" print " --help show this help message and exit" print " --version output version of flagpoll" print " --list-all list all known packages" print " --debug show debug information" print " --verbose-debug show verbose debug information" print " --extra-paths=EXTRA_PATHS" print " extra paths for flagpoll to search for meta-data files" print " --concat concatenate all output and output as one line" print " --keep-dups do not strip out all duplicate info from options" print " --info show information for packages" print " --print-pkg-options show pkg specific options" print " " print "options:" print " --modversion output version for package" print " --require=REQUIRE adds additional requirements for packages ex. 32/64" print " --libs output all linker flags" print " --static output linker flags for static linking" print " --libs-only-l output -l flags" print " --libs-only-other output other libs (e.g. -pthread)" print " --libs-only-L output -L flags" print " --cflags output all pre-processor and compiler flags" print " --cflags-only-I output -I flags" print " --cflags-only-other output cflags not covered by the cflags-only-I option" print " --exists return 0 if the module(s) exist" print " --from-file=FILE use the specified FILE for the package" #print " --print-provides print which packages the package provides" #print " --print-requires print which packages the package requires" print " --no-deps do not lookup dependencies for the package" print " --atleast-version=ATLEAST_VERSION" print " return 0 if the module is at least version" print " ATLEAST_VERSION" print " --exact-version=EXACT_VERSION" print " return 0 if the module is exactly version" print " EXACT_VERSION" print " --max-release=MAX_RELEASE" print " return 0 if the module has a release that has a" print " version of MAX_RELEASE and will return the max" print " --variable=VARIABLE get the value of a variable" print " " print "dynamic options(replace VAR with a variable you want to get/filter on)" print " NOTE: replace underscores with dashes in VAR" print " NOTE: quotes are needed around <,>,= combinations" print " --get-VAR get VAR from package" print " --get-all-VAR get VAR from package and its deps" print " --require-VAR[<,>,=VAL]" print " require that a var is defined for a package" print " or optionally use equality operators against VAL" print " --require-all-VAR[<,>,=VAL]" print " require that a var is defined for all packages" print " or optionally use equality operators against VAL" print "" print "extending search path" print " FLAGPOLL_PATH environment variable that can be set to" print " extend the search path for .fpc/.pc files" print "" print "" print "Send bug reports and/or feedback to flagpoll-users@vrsource.org" sys.exit(0) def main(): # GO! # Initialize singletons and the start evaluating my_dbg = flagDBG() my_dep_system = DepResolutionSystem() opt_evaluator = OptionsEvaluator() opt_evaluator.evaluateArgs(sys.argv[1:]) sys.exit(0) if __name__ == "__main__": main()
Python
#!/usr/bin/env python from distutils.core import setup try: import py2exe except: pass setup( name='flagpoll', version='0.9.4', description='Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software.', author='Daniel E. Shipton', author_email='dshipton@infiscape.com', license='GPL', url='http://code.google.com/p/flagpoll/', download_url='http://code.google.com/p/flagpoll/downloads/list', console=['flagpoll'], scripts=['flagpoll'], long_description = "Flagpoll is a tool for developers to use meta-data files for storing information on what is needed to compile their software. Think of it as the rpm of software development. It enables developers total control over which packages, versions, architectures, etc. that they want to use meta-data from.", data_files=[('share/flagpoll', ['flagpoll.fpc']), ('share/man/man1', ['flagpoll.1']), ('share/aclocal', ['flagpoll.m4']), ('share/html', ['flagpoll-manual.html'])] )
Python
#!/usr/bin/env python # ----------------------------------------------------------------- # # Flagpoll: A tool to extract flags from installed applications # for compiling, settting variables, etc. # # Original Authors: # Daniel E. Shipton <dshipton@gmail.com> # # Flagpoll is Copyright (C) 2006-2007 by Daniel E. Shipton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to: # Free SoftwareFoundation, Inc. # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # # ----------------------------------------------------------------- import sys, os, glob, os.path, copy, platform pj = os.path.join #################################################################### # SNAGGED FROM PYTHON 2.4 for versions under 2.4 #################################################################### import re as _re class _multimap: """Helper class for combining multiple mappings. Used by .{safe_,}substitute() to combine the mapping and keyword arguments. """ def __init__(self, primary, secondary): self._primary = primary self._secondary = secondary def __getitem__(self, key): try: return self._primary[key] except KeyError: return self._secondary[key] class _TemplateMetaclass(type): pattern = r""" %(delim)s(?: (?P<escaped>%(delim)s) | # Escape sequence of two delimiters (?P<named>%(id)s) | # delimiter and a Python identifier {(?P<braced>%(id)s)} | # delimiter and a braced identifier (?P<invalid>) # Other ill-formed delimiter exprs ) """ def __init__(cls, name, bases, dct): super(_TemplateMetaclass, cls).__init__(name, bases, dct) if 'pattern' in dct: pattern = cls.pattern else: pattern = _TemplateMetaclass.pattern % { 'delim' : _re.escape(cls.delimiter), 'id' : cls.idpattern, } cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE) class Template: """A string class for supporting $-substitutions.""" __metaclass__ = _TemplateMetaclass delimiter = '$' idpattern = r'[_a-z][_a-z0-9]*' def __init__(self, template): self.template = template # Search for $$, $identifier, ${identifier}, and any bare $'s def _invalid(self, mo): i = mo.start('invalid') lines = self.template[:i].splitlines(True) if not lines: colno = 1 lineno = 1 else: colno = i - len(''.join(lines[:-1])) lineno = len(lines) raise ValueError('Invalid placeholder in string: line %d, col %d' % (lineno, colno)) def substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): # Check the most common path first. named = mo.group('named') or mo.group('braced') if named is not None: val = mapping[named] # We use this idiom instead of str() because the latter will # fail if val is a Unicode containing non-ASCII characters. return '%s' % val if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: self._invalid(mo) raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) def safe_substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _multimap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): named = mo.group('named') if named is not None: try: # We use this idiom instead of str() because the latter # will fail if val is a Unicode containing non-ASCII return '%s' % mapping[named] except KeyError: return self.delimiter + named braced = mo.group('braced') if braced is not None: try: return '%s' % mapping[braced] except KeyError: return self.delimiter + '{' + braced + '}' if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: return self.delimiter raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) #################################################################### # End Snagging #################################################################### def tokenize(val, split_char): val = val.strip() results = [] while len(val) > 0: sn = val.find(split_char) qn = val.find('"') #print " -> val: %s Len: %s" % (val, len(val)) # If we find a quote first, then find the space after the next quote. if qn < sn: #print " -> Found a quote first:", qn # Find next quote. qn2 = val.find('"', qn+1) #print " -> Found second quote:", qn2 sn = val.find(split_char, qn2+1) #print " -> Found next space:", sn if sn < 0: results.append(val[:]) val = "" else: results.append(val[:sn]) val = val[sn:] val = val.strip() return results class Utils: # Holds collection of small utility functions EXTRA_FLAGPOLL_SEARCH_PATHS = "" EXTRA_FLAGPOLL_FILES = "" path_list_cache = None # Cache of found path lists. (only calcuate once) KEEP_DUPS = False FLAGPOLL_LIST_OF_POSSIBLE_ERRORS = [] def addPossibleError(pos_err): Utils.FLAGPOLL_LIST_OF_POSSIBLE_ERRORS.append(pos_err) addPossibleError = staticmethod(addPossibleError) def getPossibleErrors(): return Utils.stripDupInList(Utils.FLAGPOLL_LIST_OF_POSSIBLE_ERRORS) getPossibleErrors = staticmethod(getPossibleErrors) def getFlagpollVersion(): FLAGPOLL_MAJOR_VERSION = 0 FLAGPOLL_MINOR_VERSION = 9 FLAGPOLL_PATCH_VERSION = 4 return ( FLAGPOLL_MAJOR_VERSION, FLAGPOLL_MINOR_VERSION, FLAGPOLL_PATCH_VERSION ) getFlagpollVersion = staticmethod(getFlagpollVersion) def getPathList(): if None != Utils.path_list_cache: return Utils.path_list_cache #TODO: expand LD_LIBRARY_PATH to 64/32/etc??? pkg_cfg_dir = [] flg_cfg_dir = [] ld_path = [] if os.environ.has_key("PKG_CONFIG_PATH"): pkg_cfg_dir = os.environ["PKG_CONFIG_PATH"].split(os.pathsep) if os.environ.has_key("FLAGPOLL_PATH"): flg_cfg_dir = os.environ["FLAGPOLL_PATH"].split(os.pathsep) ld_dirs = ['LD_LIBRARY_PATH', 'DYLD_LIBRARY_PATH', 'PATH'] for d in ld_dirs: if os.environ.has_key(d): cur_path = os.environ[d].split(os.pathsep) ld_path_pkg = [pj(p,'pkgconfig') for p in cur_path] ld_path_flg = [pj(p,'flagpoll') for p in cur_path] ld_path.extend(ld_path_pkg) ld_path.extend(ld_path_flg) extra_paths = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS.split(os.pathsep) path_list = extra_paths path_list.extend(flg_cfg_dir) path_list.extend(pkg_cfg_dir) path_list.extend(ld_path) default_path_list = [pj('/','usr','lib64'), pj('/','usr','lib32'), pj('/','usr','lib'), pj('/','usr','share')] default_path_pkg = [pj(p,'pkgconfig') for p in default_path_list] default_path_flg = [pj(p,'flagpoll') for p in default_path_list] path_list.extend(default_path_pkg) path_list.extend(default_path_flg) flagDBG().out(flagDBG.VERBOSE, "Utils.getPathList", "Potential path list: " + str(path_list)) clean_path_list = [] for p in path_list: if os.path.exists(p) and os.path.isdir(p) and not p in clean_path_list: clean_path_list.append(p) path_list = clean_path_list flagDBG().out(flagDBG.INFO, "Utils.getPathList", "Using path list: " + str(path_list)) Utils.path_list_cache = path_list return path_list getPathList = staticmethod(getPathList) def getFileList(): flist = Utils.EXTRA_FLAGPOLL_FILES.split(":") filelist = [] for f in flist: if os.path.isfile(f): filelist.append(f) return filelist getFileList = staticmethod(getFileList) def setKeepDups(keep_dups): Utils.KEEP_DUPS = keep_dups setKeepDups = staticmethod(setKeepDups) def stripDupInList(gen_list): new_list = [] list_len = len(gen_list) i = 0 while i < list_len: item = gen_list[i].strip() if Utils.KEEP_DUPS: if len(item) > 0: new_list.append(item) continue if item in ('-framework', '-arch', '-isysroot'): item = '%s %s' % (item, gen_list[i + 1]) i += 1 if item not in new_list: if len(item) > 0: new_list.append(item) i += 1 return new_list stripDupInList = staticmethod(stripDupInList) def stripDupLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] dir_list = [] list_len = len(flag_list) i = 0 vc_linker_flag_re = _re.compile(r'^[/-]libpath:', _re.I) other_linker_flag_re = _re.compile(r'^-[LRF]') while i < list_len: flg = flag_list[i].strip() if len(flg) > 0: if (other_linker_flag_re.match(flg) is not None\ or vc_linker_flag_re.match(flg) is not None): dir_list.append(flg) else: if flg in ("-framework", "-arch", "-isysroot"): flg = "%s %s" % (flg, flag_list[i + 1]) i += 1 lib_list.append(flg) i += 1 new_list = dir_list + lib_list return Utils.stripDupInList(new_list) stripDupLinkerFlags = staticmethod(stripDupLinkerFlags) def stripDupIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] extra_list = [] list_len = len(flag_list) i = 0 while i < list_len: flg = flag_list[i].strip() if len(flg) > 0: if flg.startswith("-I") or flg.startswith("/I"): inc_list.append(flg) elif flg in ("-arch", "-isysroot"): extra_list.append("%s %s" % (flg, flag_list[i + 1])) i += 1 else: extra_list.append(flg) i += 1 extra_list.sort() new_list = inc_list + extra_list return Utils.stripDupInList(new_list) stripDupIncludeFlags = staticmethod(stripDupIncludeFlags) def cflagsOnlyDirIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though inc_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-I") or flg.startswith("/I"): inc_list.append(flg) return Utils.stripDupInList(inc_list) cflagsOnlyDirIncludeFlags = staticmethod(cflagsOnlyDirIncludeFlags) def cflagsOnlyOtherIncludeFlags(flag_list): # List is constructed as such ("-I/inc", "-fno-static-blah") # We do slightly dumb stripping though extra_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if not flg.startswith("-I") and not flg.startswith("/I"): extra_list.append(flg) return Utils.stripDupInList(extra_list) cflagsOnlyOtherIncludeFlags = staticmethod(cflagsOnlyOtherIncludeFlags) def libsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though lib_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: if flg.startswith("-l") or flg.endswith(".lib"): lib_list.append(flg) return Utils.stripDupInList(lib_list) libsOnlyLinkerFlags = staticmethod(libsOnlyLinkerFlags) def libsOnlyOtherLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though other_list = [] for flg in flag_list: flg = flg.strip() if len(flg) > 0: upper_flg = flg.upper() if not flg.startswith("-l") \ and not flg.startswith("-L")\ and not flg.startswith("-R")\ and not upper_flg.startswith("/LIBPATH")\ and not upper_flg.startswith("-LIBPATH")\ and not flg.endswith(".lib"): other_list.append(flg) return Utils.stripDupInList(other_list) libsOnlyOtherLinkerFlags = staticmethod(libsOnlyOtherLinkerFlags) def libDirsOnlyLinkerFlags(flag_list): # List is constructed as such ("-L /path", "-L/sfad", "-fpge", "-l pg", "-lpg") # We do slightly dumb stripping though dir_list = [] vc_linker_flag_re = _re.compile(r'^[/-]libpath:', _re.I) other_linker_flag_re = _re.compile(r'^-[LRF]') for flg in flag_list: flg = flg.strip() if len(flg) > 0: if (other_linker_flag_re.match(flg) is not None or vc_linker_flag_re.match(flg) is not None): dir_list.append(flg) return Utils.stripDupInList(dir_list) libDirsOnlyLinkerFlags = staticmethod(libDirsOnlyLinkerFlags) def printList(gen_list): list_string = "" for item in gen_list: if len(item) > 0: list_string += str(item) list_string += " " print list_string.strip() printList = staticmethod(printList) def parsePcFile(filename): lines = open(filename).readlines() fvars = {} fvars["FlagpollFilename"] = filename lokals = {} lokals["fp_file_cwd"] = str(filename[:- ((len(os.path.basename(filename) ) + 1))]) lines.append("prefix: ${prefix}") append_next = False append_dict = {} append_key = "" for line in lines: line = line.strip() if not line: continue if append_next: tmp = append_dict[append_key] tmp = tmp[:-1] + " " + line append_dict[append_key] = tmp if tmp[-1:] == "\\": append_next = True else: append_next = False continue if line.startswith("#"): continue eq_pos = line.find('=') col_pos = line.find(':') if eq_pos < col_pos and eq_pos != -1 or col_pos == -1 and eq_pos != -1: # local variable name, val = line.split('=', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(lokals) except ValueError: flagDBG().out(flagDBG.WARN, "PkgInfo.parse", "%s has an invalid metadata file" % filename) lokals[name] = val if val[-1:] == "\\": append_next = True append_dict = lokals append_key = name continue if col_pos < eq_pos and col_pos != -1 or eq_pos == -1 and col_pos != -1: # exported variable name, val = line.split(':', 1) name = name.strip() val = val.strip() if '$' in val: try: val = Template(val).safe_substitute(lokals) except ValueError: flagDBG().out(flagDBG.ERROR, "PkgInfo.parse", "%s has an invalid metadata file" % filename) fvars[name] = val if val[-1:] == "\\": append_next = True append_dict = fvars append_key = name return fvars parsePcFile = staticmethod(parsePcFile) class flagDBG(object): # Logging class is really easy to use # Levels: # 0 - VERBOSE # 1 - INFO # 2 - WARN # 3 - ERROR VERBOSE = 0 INFO = 1 WARN = 2 ERROR = 3 __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if flagDBG.__initialized: return flagDBG.__initialized = True self.mLevel = self.WARN self.mLevelList = ["VERBOSE", "INFO", "WARN", "ERROR"] def setLevel(self, level): if level <= 3: self.mLevel = level def out(self, level, obj, message): if level == self.ERROR: if self.mLevel == self.VERBOSE: print self.mLevelList[level] + ":" + str(obj) + ": " + str(message) else: sys.stderr.write(self.mLevelList[level] + ": " + str(message) + "\n") errs = Utils.getPossibleErrors() if len(errs) > 0: sys.stderr.write("Possible culprits:\n") for pos_err in errs: sys.stderr.write( " " + str(pos_err) + "\n" ) sys.exit(1) if level >= self.mLevel: print self.mLevelList[level] + ":" + str(obj) + ": " + str(message) class DepResolutionSystem(object): """ You add PkgAgents with Filters into system and call resolve() you can check for succes by depsSatisfied() and get the list of packages that work back by calling getPackages() """ __initialized = False def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def __init__(self): if DepResolutionSystem.__initialized: return DepResolutionSystem.__initialized = True self.mResolveAgents = [] self.mAgentDict = {} self.mFilters = [] self.mResolveAgentFilters = [] self.mInvalidPackageList = [] self.mSatisfied = False self.mAgentChangeList = [] # list of those responsible for adding Filters # to agents in higher in the chain than them # these are the first agents to ask that they pick # the next best package of them self.mAgentsVisitedList = [] # list of Agents that have been visited self.mResolvedPackageList = [] # list that is generated when deps are satified self.mCheckPrivateRequires = False self.mMadeDependList = False def getFilters(self): return self.mFilters def addFilter(self, filter): self.mFilters.append(filter) def addResolveAgentFilter(self, filter): self.mResolveAgentFilters.append(filter) def makeRequireFilter(self, requires): arch_list = [] arch_list.append("no_arch") arch_list.append("") if platform.system() == "Linux": if requires == "64": arch_list.append("x86_64") arch_list.append("x64") if requires == "32": arch_list.append("i386") arch_list.append("i486") arch_list.append("i586") arch_list.append("i686") if platform.system() == "Darwin": if requires == "64": arch_list.append("ppc64") if requires == "32": arch_list.append("ppc") if platform.system().startswith("IRIX"): arch_list.append(requires) new_filter = Filter("Arch", lambda x,v=arch_list: x in v) self.addFilter(new_filter) def createAgent(self, name): if self.checkAgentExists(name): return self.getAgent(name) else: agent = PkgAgent(name) flagDBG().out(flagDBG.INFO, "DepResSys.createAgent", "Adding %s" % name) self.addNewAgent(agent) return agent def createResolveAgent(self, name): if self.checkAgentExists(name): return self.getAgent(name) else: agent = PkgAgent(name) flagDBG().out(flagDBG.INFO, "DepResSys.createResolveAgent", "Adding %s" % name) self.addResolveAgent(agent) return agent def setPrivateRequires( self, req ): self.mCheckPrivateRequires = req def checkPrivateRequires(self): return self.mCheckPrivateRequires def checkAgentExists(self, name): return self.mAgentDict.has_key(name) def getAgent(self, name): if self.mAgentDict.has_key(name): return self.mAgentDict[name] else: flagDBG().out(flagDBG.ERROR, "DepResSys.getAgent", "Agent %s does not exist" % name) def addNewAgent(self, agent): if not self.checkAgentExists(agent): self.mAgentDict[agent.getName()] = agent def addResolveAgent(self, agent): if agent not in self.mResolveAgents: self.mResolveAgents.append(agent) for filt in self.mResolveAgentFilters: agent.addFilter(filt) def isSatisfied(self): return self.mSatisfied def updateResolvedPackages(self): pkg_list = [] agent_list = [] for agent in self.mResolveAgents: list_of_pkgs = agent.getCurrentPackageList(agent_list) pkg_list.extend(list_of_pkgs) self.mResolvedPackageList = pkg_list def getPackages(self): flagDBG().out(flagDBG.INFO, "DepResSys.getPackages", "Generating list of valid packages ") #str([pkg.getCurrentPackage.getName() for pkg in self.mResolvedPackageList])) # If this comes back empty then there isn't a valid set of packages to use self.updateResolvedPackages() return self.mResolvedPackageList def checkFiltersChanged(self): list_to_use = [] return True in [pkg.filtersChanged(list_to_use) for pkg in self.mResolveAgents] def resolveHelper(self): self.resolveAgentsChanged = True while self.resolveAgentsChanged: for agent in self.mResolveAgents: flagDBG().out(flagDBG.INFO, "DepResSys.resolveHelper", "Updating " + agent.getName()) agent.update(self.mAgentsVisitedList, self.mAgentChangeList) self.resolveAgentsChanged = self.checkFiltersChanged() # Ask mResolveAgents if they are done(they ask sub people) unless they are # really above you in the walk # If there were changes...run update on mResolveAgents again # at the end ask for pkglist..if it comes back empty then we don't # have a usable configuration for those packages def resolveDeps(self): self.resolveHelper() if not self.mMadeDependList: for agent in self.mResolveAgents: agent.makeDependList() self.mMadeDependList = True self.updateResolvedPackages() # Check if the first round through we found something # Otherwise we need to start removing packages that aren't viable # during the loop self.mSatisfied = (len(self.mResolvedPackageList) != 0) # remove top of packages that added Filters. # then move on to resolving again # remove more if neccesary agentChangeNumber = 0 while not self.mResolvedPackageList: if(self.mAgentChangeList[agentChangeNumber]): if self.mAgentChangeList[agentChangeNumber] in self.mInvalidPackageList: agentChangeNumber += 1 else: if(self.mAgentChangeList[agentChangeNumber].getViablePackages()): flagDBG().out(flagDBG.INFO, "DepResSys.resolveDeps", "Removing bad pkg from " + self.mAgentChangeList[agentChangeNumber].getName()) self.mInvalidPackageList.append(self.mAgentChangeList[agentChangeNumber].removeCurrentPackage()) else: flagDBG().out(flagDBG.INFO, "DepResSys.resolveDeps", "No combinations.. Resetting " + self.mAgentChangeList[agentChangeNumber].getName()) self.mAgentChangeList[agentChangeNumber].reset() agentChangeNumber += 1 self.resolveHelper() self.updateResolvedPackages() self.mSatisfied = (len(self.mResolvedPackageList) != 0) return class PkgAgent: """ Agent that keeps track of the versions for a package given some filters and the addition of Filters """ # Makes a PkgAgent that finds its current package with the version reqs def __init__(self, name): if DepResolutionSystem().checkAgentExists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "Package Agent %s already exists" % self.mName) self.mName = name flagDBG().out(flagDBG.INFO, "PkgAgent", "Creating:" + str(self.mName)) if not PkgDB().exists(name): flagDBG().out(flagDBG.ERROR, "PkgAgent", "No info for package: %s" % self.mName) #XXX Doesn't keep filters added for a redo... DepResolutionSystem().addNewAgent(self) self.mFilterList = [] self.mFilterList.extend(DepResolutionSystem().getFilters()) self.mBasePackageList = PkgDB().getPkgInfos(name) self.mBasePackageList.sort(lambda lhs, rhs: cmp(rhs.getVariable('Version'), lhs.getVariable('Version'))) for filt in self.mFilterList: self.mBasePackageList = filt.filter(self.mBasePackageList) if len(self.mBasePackageList) == 0: flagDBG().out(flagDBG.ERROR, "PkgAgent", "No viable packages for: %s" % self.mName) self.mViablePackageList = copy.deepcopy(self.mBasePackageList) if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mFiltersChanged = True self.mCheckDepends = True self.mAgentDependList = [] def getName(self): return self.mName def setCheckDepends(self, tf): self.mCheckDepends = tf #Filter("Version", lambda x: x == "4.5") def makeDependList(self): if not self.mCheckDepends: self.mAgentDependList = [] return dep_list = [] if self.mCurrentPackage: req_string = self.mCurrentPackage.getVariable("Requires") if DepResolutionSystem().checkPrivateRequires(): req_string = req_string + " " + self.mCurrentPackage.getVariable("Requires.private") req_string = req_string.strip() if req_string == "": return req_string = req_string.replace(',', ' ') req_string = req_string.replace('(', ' ') req_string = req_string.replace(')', ' ') space_req_string_list = req_string.split(' ') req_string_list = [] for entry in space_req_string_list: if len(entry) > 0: req_string_list.append(entry) i = 0 flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList", self.mCurrentPackage.getName() + " requires: " + str(req_string_list)) while len(req_string_list) > i: if PkgDB().exists(req_string_list[i]): new_filter = [] new_agent = DepResolutionSystem().createAgent(req_string_list[i]) if len(req_string_list) > i+1: if req_string_list[i+1] == "=": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x == v) elif req_string_list[i+1] == "<=": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x <= v) elif req_string_list[i+1] == ">=": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x >= v) elif req_string_list[i+1] == ">": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x > v) elif req_string_list[i+1] == "<": ver_to_filt = req_string_list[i+2].strip() new_filter = Filter("Version", lambda x,v=ver_to_filt: x < v) else: i += 1 else: i += 1 dep_list.append(new_agent) if new_filter: i+=3 new_agent.addFilter(new_filter) else: flagDBG().out(flagDBG.ERROR, "PkgAgent.makeDependList", "Package %s depends on %s but does not seem to be installed." % (self.mName, str(req_string_list[i]))) flagDBG().out(flagDBG.INFO, "PkgAgent.makeDependList", str(self.mName) + " : List is:" + str([pkg.getName() for pkg in dep_list])) self.mAgentDependList = dep_list def filtersChanged(self, packageList): tf_list = [self.mFiltersChanged] if self.mName not in packageList: packageList.append(self.mName) for pkg in self.mAgentDependList: tf_list.append(pkg.filtersChanged(packageList)) return True in tf_list def getCurrentPackageList(self, packageList): pkgs = [] if self.mName not in packageList: flagDBG().out(flagDBG.INFO, "PkgAgent.getCurrentPackageList", "Package: %s" % self.mName) pkgs.append(self.mCurrentPackage) packageList.append(self.mName) # Make depend list if we are supposed to self.updateFilters() self.makeDependList() for pkg in self.mAgentDependList: pkgs.extend(pkg.getCurrentPackageList(packageList)) return pkgs # current pkginfo for me def getCurrentPkgInfo(self): return self.mCurrentPackage # Someone else usually places these on me # I keep track of those separately def addFilter(self, filter): flagDBG().out(flagDBG.INFO, "PkgAgent.addFilter", "Filter %s" % self.mName + " on %s." % filter.getVarName()) self.mFiltersChanged = True self.mFilterList.append(filter) def removeCurrentPackage(self): flagDBG().out(flagDBG.INFO, "PkgAgent.removeCurrentPackage", "Removing current package of %s" % self.mName) if self.mViablePackageList: ret_val = self.mViablePackageList[0] in self.mBasePackageList del self.mViablePackageList[0] if self.mViablePackageList: self.mCurrentPackage = self.mViablePackageList[0] return ret_val def update(self, agentVisitedList, agentChangeList): flagDBG().out(flagDBG.INFO, "PkgAgent.update", "%s" % self.mName) if self.mName in agentVisitedList: return agentVisitedList.append(self.mName) if self.mFiltersChanged: self.mFiltersChanged = False self.updateFilters() # TODO: checkFilters and add them # if a pkg is in visitedList then add yourself to agentChangeList for pkg in self.mAgentDependList: pkg.update(agentVisitedList, agentChangeList) return def updateFilters(self): for filt in self.mFilterList: self.mViablePackageList = filt.filter(self.mViablePackageList) flagDBG().out(flagDBG.INFO, "PkgAgent.updateFilters", "%s has " % self.mName + str(len(self.mViablePackageList)) + " left") if len(self.mViablePackageList) > 0: self.mCurrentPackage = self.mViablePackageList[0] else: for f in self.mFilterList: Utils.addPossibleError(str(self.mName) + " -> " + str(f.getVarName())) self.mCurrentPackage = [] def reset(self): flagDBG().out(flagDBG.INFO, "PkgAgent.reset", "Resetting package: %s" % self.mName) self.mViablePackageList = self.mBasePackageList if self.mViablePackageList: self.mCurrentPacakge = self.mViablePackageList[0] else: self.mCurrentPackage = [] self.mFilterList = DepResolutionSystem().getFilters() self.mAgentDependList = [] self.mFiltersChanged = True return class Filter: """ A single Filter that knows how to filter the list it recieves Will be inheireted....?..? """ def __init__(self, variableName, testCallable): self.mVarName = variableName self.mTestCallable = testCallable def getVarName(self): return self.mVarName def filter(self, pkg_info_list): ret_pkg_list = [] # Filter first for pkg in pkg_info_list: var = pkg.getVariable(self.mVarName) if self.mTestCallable(var): flagDBG().out(flagDBG.INFO, "Filter", "Passed: %s:" % pkg.getName() + " %s is " % self.mVarName + str(var)) ret_pkg_list.append(pkg) else: flagDBG().out(flagDBG.INFO, "Filter", "Failed: %s:" % pkg.getName() + " %s is " % self.mVarName + str(var)) # Now sort ret_pkg_list.sort(lambda lhs, rhs: cmp(rhs.getVariable(self.mVarName), lhs.getVariable(self.mVarName))) return ret_pkg_list #requires: qt == 4.5 #Filter("Version", lambda x: x <= "4.5") #Filter("Version", lambda x: x <= "4.5") class PkgDB(object): """ Holds all the neccesary information to evaluate itself when needed. Is in charge of holding a list of PkgInfo's that contain info about the package. """ __initialized = False def __init__(self): if self.__initialized: return self.__initialized = True self.mPkgInfos = {} # {pkg_name: List of package infos} self.populatePkgInfoDBPcFiles() self.populatePkgInfoDBFpcFiles() def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance def printAllPackages(self): list_of_package_names = [] for pkg in self.mPkgInfos: list_of_package_names.append(pkg) for name in list_of_package_names: print name sys.exit(0) def getVariables(self, name, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariable", "Finding " + str(variable_list) + " in " + str(name)) ret_list = [] for var in variable_list: if self.mPkgInfos.has_key(name): ret_list.extend(self.mPkgInfos[name][0].getVariable(var)) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariable", "Package %s not found." % name) return ret_list def checkPackage(self, name): flagDBG().out(flagDBG.INFO, "PkgDB.checkPackage", "Finding " + str(name)) if self.mPkgInfos.has_key(name): return True else: flagDBG().out(flagDBG.ERROR, "PkgDB.CheckPackage", "Package %s not found." % name) return False def getVariablesAndDeps(self, pkg_list, variable_list): flagDBG().out(flagDBG.INFO, "PkgDB.getVariablesAndDeps", "Finding " + str(variable_list) + " in " + str(pkg_list)) if DepResolutionSystem().checkPrivateRequires(): temp_var_list = [] for var in variable_list: temp_var_list.append(var.join(".private")) variable_list = variable_list + temp_var_list for name in pkg_list: if self.mPkgInfos.has_key(name): agent = DepResolutionSystem().createAgent(name) DepResolutionSystem().addResolveAgent(agent) else: flagDBG().out(flagDBG.ERROR, "PkgDB.getVariablesAndDeps", "Package %s not found." % name) DepResolutionSystem().resolveDeps() pkgs = DepResolutionSystem().getPackages() var_list = [] for pkg in pkgs: if pkg: for var in variable_list: var_list.extend(tokenize(pkg.getVariable(var), pkg.getSplitChar())) return var_list def getPkgInfos(self, name): if self.mPkgInfos.has_key(name): return self.mPkgInfos[name] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getPkgInfos", "Package %s not found." % name) def exists(self, name): return self.mPkgInfos.has_key(name) def getInfo(self, name): if self.mPkgInfos.has_key(name): return [pkg.getInfo() for pkg in self.mPkgInfos[name]] else: flagDBG().out(flagDBG.ERROR, "PkgDB.getInfo", "Package %s not found." % name) def buildPcFileDict(self): """ Builds up a dictionary of {name: list of files for name} """ pc_dict = {} for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.pc")) # List of .pc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these pc files: %s" % str(glob_list)) for g in glob_list: # Get key name and add file to value list in dictionary key = os.path.basename(g)[:-3] # Strip .pc off the filename...rstrip no worky pc_dict.setdefault(key, []).append(g) for f in Utils.getFileList(): if f.endswith(".pc"): key = os.path.basename(f)[:-3] # Strip .pc off the filename...rstrip no worky pc_dict.setdefault(key, []).append(f) return pc_dict # { "key", [ "list", "of", "corresponding", "pc", "files"] } def populatePkgInfoDBPcFiles(self): dict_to_pop_from = self.buildPcFileDict() for (pkg,files) in dict_to_pop_from.iteritems(): for f in files: self.mPkgInfos.setdefault(pkg,[]).append(PkgInfo(pkg, f, "pc")) def buildFpcFileList(self): """ Builds up a dictionary of {name: list of files for name} """ file_list = [] for p in Utils.getPathList(): glob_list = glob.glob(os.path.join(p, "*.fpc")) # List of .fpc files in that directory flagDBG().out(flagDBG.VERBOSE, "PkgDB.buildPcFileDict", "Process these fpc files: %s" % str(glob_list)) for g in glob_list: file_list.append(g) for f in Utils.getFileList(): if f.endswith(".fpc"): file_list.append(f) return file_list # [ "list", "of", "fpc", "files"] def populatePkgInfoDBFpcFiles(self): list_to_add = self.buildFpcFileList() for filename in list_to_add: var_dict = Utils.parsePcFile(filename) if not var_dict.has_key("Provides"): flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Provides" % str(filename)) continue if not var_dict.has_key("Arch"): flagDBG().out(flagDBG.WARN, "PkgDB.populate", "%s missing Arch" % str(filename)) continue provides_string = var_dict["Provides"] provides_string = provides_string.replace(',', ' ') provides_string = provides_string.replace('(', ' ') provides_string = provides_string.replace(')', ' ') for key in provides_string.split(" "): if len(key) > 0: self.mPkgInfos.setdefault(key, []).append(PkgInfo(key, filename, "fpc", var_dict)) class PkgInfo: """ Holds the information for a package file on the system. These however are evaluated when the need arises. """ def __init__(self, name, file, type, varDict={}): self.mName = name self.mFile = file self.mIsEvaluated = False self.mType = type self.mVariableDict = varDict if self.mType == "fpc": self.mIsEvaluated = True def getVariable(self, variable): self.evaluate() return self.mVariableDict.get(variable,"") def getName(self): return self.mName def evaluate(self): if not self.mIsEvaluated: flagDBG().out(flagDBG.INFO, "PkgInfo.evaluate", "Evaluating %s" % self.mName) self.mVariableDict= Utils.parsePcFile(self.mFile) self.mIsEvaluated = True def getInfo(self): self.evaluate() return self.mVariableDict def getSplitChar(self): self.evaluate() split_char = self.mVariableDict.get("SplitCharacter", ' ') if split_char == "": split_char = ' ' return split_char class OptionsEvaluator: def __init__(self): if len(sys.argv) < 2: self.printHelp() # This is only the args....(first arg is stripped) def evaluateArgs(self, args): # Catch any args that need to be tended to immediately # Process args in the order that they were recieved. Some options are not # shown below because they are sub-options of an option below (--strip-dups) for option in args: if option.startswith("--verbose-debug"): flagDBG().setLevel(flagDBG.VERBOSE) if option.startswith("--debug"): flagDBG().setLevel(flagDBG.INFO) elif option.startswith("--from-file"): val_start = option.find('=') + 1 file = option[val_start:] Utils.EXTRA_FLAGPOLL_FILES = Utils.EXTRA_FLAGPOLL_FILES + ":" + file elif option.startswith("--help"): self.printHelp() sys.exit(0) elif option.startswith("--version"): print "%s.%s.%s" % Utils.getFlagpollVersion() sys.exit(0) elif option.startswith("--list-all"): PkgDB().printAllPackages() continue listedAgentNames = [] agent = None num_args = len(args) curr_arg = 0 output_options = [] # (option, name/"") important_options = [] # ones that need special attention while curr_arg < num_args: if args[curr_arg].startswith("--atleast-version"): val_start = args[curr_arg].find('=') + 1 atleast_version = args[curr_arg][val_start:] atleast_filter = Filter("Version", lambda x,v=atleast_version: x >= v) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(atleast_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --at-least-version") continue if args[curr_arg].startswith("--cflags-only-I"): output_options.append(("cflags-only-I", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--cflags-only-other"): output_options.append(("cflags-only-other", "")) curr_arg = curr_arg + 1 continue #This could be the catch all for the above ones to and then filter based on what is asked... #For clarity of course... if args[curr_arg].startswith("--cflags"): output_options.append(("cflags", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--extra-paths"): val_start = args[curr_arg].find('=') + 1 paths = args[curr_arg][val_start:] Utils.EXTRA_FLAGPOLL_SEARCH_PATHS = Utils.EXTRA_FLAGPOLL_SEARCH_PATHS + ":" + paths curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--exact-version"): val_start = args[curr_arg].find('=') + 1 exact_version = args[curr_arg][val_start:] exact_filter = Filter("Version", lambda x,v=exact_version: x == v) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(exact_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --exact-version") continue if args[curr_arg].startswith("--exists"): important_options.append("exists") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--from-file"): val_start = args[curr_arg].find('=') + 1 file = args[curr_arg][val_start:] file_filter = Filter("FlagpollFilename", lambda x,f=file: x == f) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(file_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --from-file") continue if args[curr_arg].startswith("--info"): important_options.append("info") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--print-pkg-options"): important_options.append("print-pkg-options") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--keep-dups"): Utils.setKeepDups(True) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-l"): output_options.append(("libs-only-l", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-L"): output_options.append(("libs-only-L", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--libs-only-other"): output_options.append(("libs-only-other", "")) curr_arg = curr_arg + 1 continue #This could be the catch all for the above ones to and then filter based on what is asked... if args[curr_arg].startswith("--libs"): output_options.append(("libs", "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--require-all"): rlen = len("--require-all") req_string = args[curr_arg][rlen:] req_string = req_string.replace('-','_') curr_arg = curr_arg + 1 if req_string.find("<=") != -1: op_start = req_string.find("<=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x <= v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find(">=") != -1: op_start = req_string.find(">=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x >= v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find(">") != -1: op_start = req_string.find(">") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x > v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("<") != -1: op_start = req_string.find("<") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x < v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("=") != -1: op_start = req_string.find("=") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x == v) DepResolutionSystem().addFilter(new_filter) continue if req_string.find("=") == -1: new_filter = Filter(req_string, lambda x: len(x) > 0) DepResolutionSystem().addFilter(new_filter) continue continue if args[curr_arg].startswith("--require-"): rlen = len("--require-") req_string = args[curr_arg][rlen:] req_string = req_string.replace('-','_') curr_arg = curr_arg + 1 if agent is None: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --require") if req_string.find("<=") != -1: op_start = req_string.find("<=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x <= v) agent.addFilter(new_filter) continue if req_string.find(">=") != -1: op_start = req_string.find(">=") req_var = req_string[:op_start] req_val = req_string[op_start + 2:] new_filter = Filter(req_var, lambda x,v=req_val: x >= v) agent.addFilter(new_filter) continue if req_string.find(">") != -1: op_start = req_string.find(">") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x > v) agent.addFilter(new_filter) continue if req_string.find("<") != -1: op_start = req_string.find("<") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x < v) agent.addFilter(new_filter) continue if req_string.find("=") != -1: op_start = req_string.find("=") req_var = req_string[:op_start] req_val = req_string[op_start + 1:] new_filter = Filter(req_var, lambda x,v=req_val: x == v) agent.addFilter(new_filter) continue if req_string.find("=") == -1: new_filter = Filter(req_string, lambda x: len(x) > 0) agent.addFilter(new_filter) continue continue if args[curr_arg].startswith("--no-deps"): if agent is not None: agent.setCheckDepends(False) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --no-deps") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--require="): val_start = args[curr_arg].find('=') + 1 req_var = args[curr_arg][val_start:] curr_arg = curr_arg + 1 DepResolutionSystem().makeRequireFilter(req_var) continue if args[curr_arg].startswith("--modversion"): if agent is not None: output_options.append(("Version", agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --modversion") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--max-release"): val_start = args[curr_arg].find('=') + 1 max_release = args[curr_arg][val_start:] max_filter = Filter("Version", lambda x,v=max_release: x.startswith(v)) curr_arg = curr_arg + 1 if agent is not None: agent.addFilter(max_filter) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --max-release") continue if args[curr_arg].startswith("--static"): DepResolutionSystem().setPrivateRequires(True) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--variable"): val_start = args[curr_arg].find('=') + 1 fetch_var = args[curr_arg][val_start:] if agent is not None: output_options.append((fetch_var, agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --variable") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--get-all"): rlen = len("--get-all-") get_string = args[curr_arg][rlen:] get_string = get_string.replace('-','_') output_options.append((get_string, "")) curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--get"): rlen = len("--get-") get_string = args[curr_arg][rlen:] get_string = get_string.replace('-','_') if agent is not None: output_options.append((get_string, agent.getName())) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No package specified for option: --get") curr_arg = curr_arg + 1 continue if args[curr_arg].startswith("--concat"): important_options.append("concat") curr_arg = curr_arg + 1 continue if not args[curr_arg].startswith("--"): name = args[curr_arg] curr_arg = curr_arg + 1 if PkgDB().checkPackage(name): agent = DepResolutionSystem().createResolveAgent(name) listedAgentNames.append(name) else: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Package %s" % name) sys.exit(1) continue if args[curr_arg] != "--debug" and args[curr_arg] != "--verbose-debug": flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Invalid Option: %s" % args[curr_arg]) curr_arg = curr_arg + 1 if len(listedAgentNames) == 0: flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "Must specify at least one package") DepResolutionSystem().resolveDeps() pkgs = DepResolutionSystem().getPackages() for p in pkgs: if not p: for option in important_options: if option == "exists": print "no" sys.exit(1) flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found") if len(pkgs) == 0: for option in important_options: if option == "exists": print "no" sys.exit(1) flagDBG().out(flagDBG.ERROR, "OptionsEvaluator", "No valid configurations found") sys.exit(1) concat = False for option in important_options: if option == "exists": print "yes" return sys.exit(0) # already checked for none above if option == "concat": concat = True if option == "info": pkg_info_list = [] for pkg in pkgs: if pkg.getName() in listedAgentNames: print pkg.getName() pkg_info = pkg.getInfo() for key in pkg_info.keys(): print " %s : %s" % (key, pkg_info[key]) if option == "print-pkg-options": print "" print "All options below would start with (--get-/--get-all-/--require-/--require-all-)" print "NOTE: this list does not include the standard variables that are exported." print "" for pkg in pkgs: if pkg.getName() not in listedAgentNames: continue print "Package: " + pkg.getName() for key in pkg.getInfo().keys(): if key not in [ "Name", "Description", "URL", "Version", "Requires", "Requires.private", "Conflicts", "Libs", "Libs.private", "Cflags", "Provides", "Arch", "FlagpollFilename", "prefix" ]: print " " + key.replace('_','-') #print output_options #output_options = [] #output_single = [] #Process options here.............. concat_list = [] if concat: print_option = lambda x: concat_list.extend(x) else: print_option = lambda x: Utils.printList(x) for option in output_options: if option[0] == "cflags": print_option(Utils.stripDupIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "cflags-only-I": print_option(Utils.cflagsOnlyDirIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "cflags-only-other": print_option(Utils.cflagsOnlyOtherIncludeFlags(self.getVarFromPkgs("Cflags", pkgs, option[1]))) elif option[0] == "libs-only-l": print_option(Utils.libsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs-only-L": print_option(Utils.libDirsOnlyLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs-only-other": print_option(Utils.libsOnlyOtherLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) elif option[0] == "libs": print_option(Utils.stripDupLinkerFlags(self.getVarFromPkgs("Libs", pkgs, option[1]))) else: print_option(Utils.stripDupInList(self.getVarFromPkgs(option[0], pkgs, option[1]))) if concat: Utils.printList(Utils.stripDupInList(concat_list)) def getVarFromPkgs(self, var, pkgs, pkg_name=""): var_list = [] ext_vars = [] if var == "Libs": if DepResolutionSystem().checkPrivateRequires: ext_vars.append("Libs.private") if pkg_name == "": for pkg in pkgs: if pkg: var_list.extend(tokenize(pkg.getVariable(var), pkg.getSplitChar())) for extra_var in ext_vars: var_list.extend(tokenize(pkg.getVariable(extra_var), pkg.getSplitChar())) else: for pkg in pkgs: if pkg: if pkg.getName() == pkg_name: var_list.extend(tokenize(pkg.getVariable(var), pkg.getSplitChar())) for extra_var in ext_vars: var_list.extend(tokenize(pkg.getVariable(extra_var), pkg.getSplitChar())) return var_list def printHelp(self): print "usage: flagpoll pkg options [pkg options] [generic options]" print " " print "generic options:" print " --help show this help message and exit" print " --version output version of flagpoll" print " --list-all list all known packages" print " --debug show debug information" print " --verbose-debug show verbose debug information" print " --extra-paths=EXTRA_PATHS" print " extra paths for flagpoll to search for meta-data files" print " --concat concatenate all output and output as one line" print " --keep-dups do not strip out all duplicate info from options" print " --info show information for packages" print " --print-pkg-options show pkg specific options" print " " print "options:" print " --modversion output version for package" print " --require=REQUIRE adds additional requirements for packages ex. 32/64" print " --libs output all linker flags" print " --static output linker flags for static linking" print " --libs-only-l output -l flags" print " --libs-only-other output other libs (e.g. -pthread)" print " --libs-only-L output -L flags" print " --cflags output all pre-processor and compiler flags" print " --cflags-only-I output -I flags" print " --cflags-only-other output cflags not covered by the cflags-only-I option" print " --exists return 0 if the module(s) exist" print " --from-file=FILE use the specified FILE for the package" #print " --print-provides print which packages the package provides" #print " --print-requires print which packages the package requires" print " --no-deps do not lookup dependencies for the package" print " --atleast-version=ATLEAST_VERSION" print " return 0 if the module is at least version" print " ATLEAST_VERSION" print " --exact-version=EXACT_VERSION" print " return 0 if the module is exactly version" print " EXACT_VERSION" print " --max-release=MAX_RELEASE" print " return 0 if the module has a release that has a" print " version of MAX_RELEASE and will return the max" print " --variable=VARIABLE get the value of a variable" print " " print "dynamic options(replace VAR with a variable you want to get/filter on)" print " NOTE: replace underscores with dashes in VAR" print " NOTE: quotes are needed around <,>,= combinations" print " --get-VAR get VAR from package" print " --get-all-VAR get VAR from package and its deps" print " --require-VAR[<,>,=VAL]" print " require that a var is defined for a package" print " or optionally use equality operators against VAL" print " --require-all-VAR[<,>,=VAL]" print " require that a var is defined for all packages" print " or optionally use equality operators against VAL" print "" print "extending search path" print " FLAGPOLL_PATH environment variable that can be set to" print " extend the search path for .fpc/.pc files" print "" print "" print "Send bug reports and/or feedback to flagpoll-users@vrsource.org" sys.exit(0) def main(): # GO! # Initialize singletons and the start evaluating my_dbg = flagDBG() my_dep_system = DepResolutionSystem() opt_evaluator = OptionsEvaluator() opt_evaluator.evaluateArgs(sys.argv[1:]) sys.exit(0) if __name__ == "__main__": main()
Python
#!/usr/bin/env python # ----------------------------------------------------------------- # # Flag Poll: A tool to extract flags from installed applications # for compiling, settting variables, etc. # # Original Authors: # Daniel E. Shipton <dshipton@gmail.com> # # Flag Poll is Copyright (C) 2006 by Daniel E. Shipton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to: # Free SoftwareFoundation, Inc. # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # # ----------------------------------------------------------------- """Makes a flagpole .fpc file from user input. v0.9 coded by Jeff Groves""" import os import sys import getopt ##String prompts for the input varPrompt = """Convience variables (one 'var_name= var_definition' per line,""" + \ """ empty line when done)""" namePrompt = "Formal Name" descriptionPrompt = "Description" urlPrompt = "URL" providesPrompt = "One or more names to look package up by: (Provides)" versionPrompt = "Version (x.y.z)" architecturePrompt = "Architecture" requirePrompt = "Requires" libPrompt = "Linker Flags (-lfoo -L/usr/lib)" staticLibPrompt = "Static Linking Flags/Libs (extra private libs)" compileFlagsPrompt = "Compile/Include Flags (-I/usr -fpge -O2)" fileNamePrompt = "FPC File's Name" def usage(): """Prints a list of acceptable arguments for fpcmaker.py.""" print """ Fpcmaker.py Options: -n, --name= : Sets %s -d, --description= : Sets %s -u, --url= : Sets %s -p, --provides= : Sets %s -v, --version= : Sets %s -a, --architecture= : Sets %s -r, --requires= : Sets %s -l, --libs= : Sets %s -c, --cflags= : Sets %s -s, --static= : Sets %s -f, --file= : Sets %s """ %(namePrompt, descriptionPrompt, urlPrompt, providesPrompt, versionPrompt, architecturePrompt, requirePrompt, libPrompt, compileFlagsPrompt, staticLibPrompt, fileNamePrompt) return def checkFileName(fileName): """Checks if the fpc file name's blank, contains slashes, or exists.""" nameCleared = False writeFile = True confirms = ['y', 'Y', 'yes', 'Yes'] ##Loops until the name clears or writing the file's aborted. while(not nameCleared and writeFile): ##If it's blank, give the option of aborting the program. if fileName == "": choice = raw_input("Do you want to abort writing the" + " .fpc file? (Y/N): ") if choice not in confirms: fileName = raw_input("Please enter a different name for the" + " .fpc file: ") else: writeFile = False ##If it contains slashes, ask for another name. elif '/' in fileName or '\\' in fileName: print "I can't write to %s because it contains slashes."%(fileName) fileName = raw_input("Please enter a different name for the" + " .fpc file: ") ##If it already exists, ask if they want to overwrite. ##If not, ask for another name. elif os.path.exists(fileName): choice = raw_input("The file %s already exists." %(fileName) + " Do you want to overwrite it? (Y/N): ") if choice not in confirms: fileName = raw_input("Please enter a different name for the" + " .fpc file: ") else: nameCleared = True else: nameCleared = True return [fileName, writeFile] ##Booleans for whether that argument was sent in the command line varSet = False providesSet = False nameSet = False descriptionSet = False urlSet = False architectureSet = False versionSet = False requiresSet = False libsSet = False compileFlagsSet = False staticLibSet = False fileNameSet = False ##Get the options & arguments sent. arguments = sys.argv[1:] try: opts, args = getopt.getopt(arguments, "p:n:u:d:a:r:v:l:c:s:f:", ["provides=", "name=", "url=", "description=", "architecture=", "requires=", "version=", "libs=", "cflags=", "static=", "file="]) ##Send them usage info if they enter a wrong argument except getopt.GetoptError: usage() sys.exit(2) for opt, arg in opts: if opt in ('-p', '--provides'): providesSet = True provides = arg elif opt in ('-n', '--name'): nameSet = True name = arg elif opt in ('-v', '--version'): versionSet = True version = arg elif opt in ('-u', '--url'): urlSet = True url = arg elif opt in ('-d', '--description'): descriptionSet = True description = arg elif opt in ('-a', '--architecture'): architectureSet = True architecture = arg elif opt in ('-r', '--requires'): requiresSet = True requires = arg elif opt in ('-l', '--libs'): libsSet = True libs = arg elif opt in ('-c', '--cflags'): compileFlagsSet = True compileFlags = arg elif opt in ('-s', '--static'): staticLibSet = True staticLib = arg elif opt in ('-f', '--file'): fileNameSet = True fileName = arg ##Grab any input not passed in the arguments from the user. if not varSet: varLine = None variables = "" print "%s:" %(varPrompt) while(varLine != ""): varLine = raw_input("") variables = variables + "%s\n" %(varLine) if not nameSet: name = raw_input("%s: " %(namePrompt)) if not descriptionSet: description = raw_input("%s: " %(descriptionPrompt)) if not urlSet: url = raw_input("%s: " %(urlPrompt)) if not versionSet: version = raw_input("%s: " %(versionPrompt)) if not providesSet: provides = raw_input("%s: " %(providesPrompt)) if not requiresSet: requires = raw_input("%s: " %(requirePrompt)) if not architectureSet: architecture = raw_input("%s: " %(architecturePrompt)) if not libsSet: libs = raw_input("%s: " %(libPrompt)) if not staticLibSet: staticLib = raw_input("%s: " %(staticLibPrompt)) if not compileFlagsSet: compileFlags = raw_input("%s: " %(compileFlagsPrompt)) if not fileNameSet: fileName = raw_input("%s: " %(fileNamePrompt)) ##Check the file's name. fileName, writeFile = checkFileName(fileName) ##If they chose not to overwrite, write the file. if writeFile: fpc = open(fileName, 'w') fpc.write("%s" %(variables)) fpc.write("Name: %s\n" %(name)) fpc.write("Description: %s\n" %(description)) fpc.write("URL: %s\n" %(url)) fpc.write("Version: %s\n" %(version)) fpc.write("Provides: %s\n" %(provides)) fpc.write("Requires: %s\n" %(requires)) fpc.write("Arch: %s\n" %(architecture)) fpc.write("Libs: %s\n" %(libs)) fpc.write("Libs.private: %s\n" %(staticLib)) fpc.write("Cflags: %s\n" %(compileFlags)) fpc.close() ##TESTER: Print the file out. fpc = open(fileName, 'r') ##TESTER print fpc.read() ##TESTER fpc.close ##TESTER
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- # # untitled.py # # Copyright 2012 Aleksi Joakim Palomäki <aleksi@ajp.dy.fi> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. # # class numfind: def numfinder(self, text, string, length): import re if '<span class="parameter-value">(' != string: loc1 = text.find(string) unparsed = text[loc1:loc1+length] almostparsed = re.findall("[-]?[0-9]*", unparsed) parsed = [i for i in almostparsed if i] while parsed.count("-") > 0: if parsed.count("-") > 0: #This had extra "-" marks and this is removing the ones we don't need #print parsed.count("-") parsed.remove("-") if parsed.count("-") >= 1: #if we have more then 1 then the - is [0] and bug, remove it. parsed.pop(0) #for i in parsed: # if parsed[0] == "-": # parsed.remove() try: #This is something ugly to define if we have desimals or not :P ready = parsed[0] + ',' + parsed[1] return ready except: #if parsed is invalid for above statement we need to set it to something else if parsed == []: parsed = [-1] return parsed[0] else: #and in case its not empty [] we still need to set it to something else since it failed above.. return parsed[0] #lets expect its about clouds #TODO: If we ever want to have fiweather work with "All" weather sites, # we need smarter system to specify weather we are searching clouds or not.. else: loc1 = text.find(string) unparsed = text[loc1:loc1+length] almostparsed = re.findall("[-]?[0-9]*", unparsed) parsed = [i for i in almostparsed if i] #print unparsed while "-" in parsed: if "-" in parsed: parsed.remove("-") if parsed == []: parsed = [-1] return parsed[0] else: ready = parsed[0] + '/' + parsed[1] return ready #print numfinder("moi","kaikenlaistamoimoi teksit ja sit pari numero 349 astetta", "numero", 2000)
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- # # FiWeathersrc.py # # Copyright 2010-2011 Aleksi Joakim Palomäki <aleksi@ajp.dy.fi>, Tuukka Ojala <tuukka.ojala@gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. ''' This is function to find the informations Today ''' def cityString (title, doc): start = int (title) +7 end = doc.find (" - Pai") return doc [start:end] def finds(location): import config_parser cfg = "ITL.txt" c = config_parser.config_pars(cfg) baseurl = c["baseurl"] tempera_num = int(c["temperature_num"]) tempera_base = c["temperature_start"] dew_num = int(c["dewpoint_num"]) dew_base = c["dewpoint_start"] hum_num = int(c["humidity_num"]) hum_base = c["humidity_start"] win_num = int(c["wind_speed_num"]) win_base = c["wind_speed_start"] wing_num = int(c["wind_gust_num"]) wing_base = c["wind_gust_start"] import string_num_finder x = string_num_finder.numfind() ''''List for conditions that this function returns''' Conditions=[] '''Imports''' import urllib2 '''Open the weatherinstitute webpage and fetch the source html''' try: site = baseurl + location url = urllib2.urlopen(urllib2.quote(site).replace('%3A', ':')) except : print "Unable to fetch weather data. Please check your internet connection. If your connection is working fine then please file a bug at http://code.google.com/p/fiweather/issues/list" exit() doc=url.read() '''City name''' title = doc.find ("<title>") if title > 0: Conditions.append (cityString (title, doc)) else: Conditions.append ("Unknown city") '''Temperature value''' temper = x.numfinder(doc, tempera_base, tempera_num) if temper > 0: Conditions.append(temper) else: Conditions.append("No information.") '''Dew Point value''' dew = x.numfinder(doc, dew_base, dew_num) if dew > 0: #print dew Conditions.append(dew) else: Conditions.append("No information.") '''Humidity value''' humidit =x.numfinder(doc, hum_base, hum_num) if humidit > 0: Conditions.append(humidit) '''Windspeed value''' windit =x.numfinder(doc, win_base, win_num) clear = doc.find('''Tyynt&auml;</span>''') #dependant on working with ITL fix it. if windit > 0: Conditions.append(windit) elif clear > 0: Conditions.append('Calm') else: Conditions.append("No information.") '''Wind gust value''' gust =x.numfinder(doc, wing_base, wing_num) if gust > 0: Conditions.append(gust) else: Conditions.append("No information.") '''Cloudness''' clouds =x.numfinder(doc, '''<span class="parameter-value">(''', 50) if clouds > 0: Conditions.append(clouds) else: Conditions.append("No information.") '''Visibility''' visibility =x.numfinder(doc, '''<span class="parameter-name">N&auml;kyvyys</span>''', 100) if visibility > 0: Conditions.append(visibility) else: Conditions.append("No information.") '''pressure''' pr = x.numfinder(doc, '''<span class="parameter-name">Paine</span> <span class="parameter-value">''', 80) if pr > 0: Conditions.append (pr) else: Conditions.append ("No information.") '''Water for hour''' wh = x.numfinder(doc, '''sadekertym&auml;</span> <span class="parameter-value">''', 90) #print wh if wh > 0: Conditions.append (wh) else: Conditions.append ("No information.") return Conditions ###The Ugliest thing i ever wrote.. well not quite.. but close!### def forec(location): '''Imports''' import urllib2 import datetime '''Open the weatherinstitute webpage and fetch the source html''' try: site = 'http://ilmatieteenlaitos.fi/saa/' + location url = urllib2.urlopen(urllib2.quote(site).replace('%3A', ':')) except : print "Unable to fetch weather data. Please check your internet connection. If your connection is working fine then please file a bug at http://code.google.com/p/fiweather/issues/list" exit() doc=url.read() begin = doc.find('<tr class="meteogram-temperatures">') times = doc.find('<colgroup>') #return begin if begin > 0: loppu = doc.find('</td></tr><tr class="meteogram-wind-symbols"') #print doc[begin:loppu] parse1 = doc[begin:loppu].replace('<tr class="meteogram-temperatures">', '').replace('\n <td class="positive">','').replace('</td><td class="positive">', '').replace(' ', '').replace('<span title="lämpötila ', '').replace('</span>', '') parse2 = parse1.split('\n') lista = [] for f in parse2: luku = f.find('"') parsettu = f[0:luku].replace('°C', '') lista.append(parsettu) #lista= list(set(lista)) lista.remove("") for x in lista: if x == ' ': lista.remove(x) else: pass if times > 0: begin = doc.find('<colgroup>') end = doc.find('</colgroup>') parse1 = doc[begin:end] parse2 = parse1.replace(' <col class="', '').replace(' <col class="', '').replace(' first-daily-step" />', '').replace(' last-daily-step" />', '').replace('" /', '').replace('>', '') parse3 = parse2.split('\n') parse3.remove("<colgroup") parse3.remove(' ') fir = 0 o = parse3.count('first-day odd-day ') luku = 0 i = 0 import forec o = forec.forec(lista, parse3) return o else: return 'Something went wrong in FiWeathersrc.py '
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- # # fiweather # # Copyright 2010-2011 Aleksi Joakim Palomäki <aleksi@ajp.dy.fi>, Tuukka Ojala <tuukka.ojala@gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. import urllib2 import sys import FiWeathersrc def help (): print 'Usage: fiweather city' print "Options:" print "-nofilt\t\t Don't filter output based on available information." print "-forec\t\t Show forecast.(incomplete!)" sys.exit (0) try: location = sys.argv[1] '''Uncomment under for testing''' #location = "Helsinki" except IndexError: help () #if sys.argv [1] == '-h' or sys.argv [1] == '--help': # help () '''Metrics''' celsius = ' °C' dewpoint = ' °C' prosents = ' %' windspeed = ' m/s' windgust = ' m/s' kilometers = ' km' airpressure = ' hPa' wateramount= ' mm' #Do we filter? filt = True ###Features in developement try: if sys.argv[2]>0: if sys.argv[2] == '-forec': Y = FiWeathersrc.forec(location) print Y quit() elif sys.argv[2] == "-nofilt": #We dont' want to filter :( filt = False except IndexError, e: pass X = FiWeathersrc.finds(location) #print X '''Remove metrics from no info values''' if X[0] == "Unknown city": city = none else: city = X[0] if X[1] == "No information.": celsius = '' if X[2] == "No information.": dewpoint = '' if X[3] == "No information.": pressure = '' if X[4] == "No information." or X[4] == "Calm": windspeed = '' if X[5] == "No information.": windgust = '' if X[7] == "No information.": kilometers = '' if X[8] == "No information.": airpressure = '' if X[9] == "No information.": wateramount = '' try:#This is quickly made fix allowing us to use city search like "Helsinki/kumpula" or "Kouvola/anjala" if location.capitalize () <> city and city.split(",")[1].strip(" ") not in location.capitalize () : print "Invalid city." sys.exit (1) except:#Fallback to old way if the new one fails(gives index error) if location.capitalize () <> city: print "Invalid city." sys.exit (1) Temperature = X[1] + celsius Dew_Point = X[2] + dewpoint Air_Humidity = X[3] + prosents Wind_speed = X[4] + windspeed Wind_gust = X[5] + windgust Cloud_level = X[6] Visibility = X[7] + kilometers Air_Pressure = X[8] + airpressure Last_1h_Rain = X[9] + wateramount #Ugly filtering "No information" away if wanted. if filt == True: #print "filter true" if X[0].find("No information."): print 'Weather in %(city)s'% locals() if X[1].find("No information."): print 'Temperature:\t %(Temperature)s'% locals() if X[2].find("No information."): print 'Dew Point:\t %(Dew_Point)s'% locals() if X[3].find("No information."): print 'Air Humidity:\t %(Air_Humidity)s'% locals() if X[4].find("No information."): print 'Wind speed:\t %(Wind_speed)s'% locals() if X[5].find("No information."): print 'Wind gust:\t %(Wind_gust)s'% locals() if X[6].find("No information."): print 'Cloudness:\t %(Cloud_level)s'% locals() if X[7].find("No information."): print 'Visibility:\t %(Visibility)s'% locals() if X[8].find("No information."): print 'Air Pressure:\t %(Air_Pressure)s'% locals() if X[9].find("No information."): print 'Last 1h Rain:\t %(Last_1h_Rain)s'% locals() sys.exit(0) ########################### Weather_All = '''Weather in %(city)s Temperature:\t %(Temperature)s Dew Point:\t %(Dew_Point)s Air Humidity:\t %(Air_Humidity)s Wind speed:\t %(Wind_speed)s Wind gust:\t %(Wind_gust)s Cloudness:\t %(Cloud_level)s Visibility:\t %(Visibility)s Air Pressure:\t %(Air_Pressure)s Last 1h Rain:\t %(Last_1h_Rain)s ''' % locals() print Weather_All
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- # # FiWeathersrc.py # # Copyright 2010-2011 Aleksi Joakim Palomäki <aleksi@ajp.dy.fi>, Tuukka Ojala <tuukka.ojala@gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. ''' This is function to find the informations Today ''' def cityString (title, doc): start = int (title) +7 end = doc.find (" - Pai") return doc [start:end] def finds(location): import config_parser cfg = "ITL.txt" c = config_parser.config_pars(cfg) baseurl = c["baseurl"] tempera_num = int(c["temperature_num"]) tempera_base = c["temperature_start"] dew_num = int(c["dewpoint_num"]) dew_base = c["dewpoint_start"] hum_num = int(c["humidity_num"]) hum_base = c["humidity_start"] win_num = int(c["wind_speed_num"]) win_base = c["wind_speed_start"] wing_num = int(c["wind_gust_num"]) wing_base = c["wind_gust_start"] import string_num_finder x = string_num_finder.numfind() ''''List for conditions that this function returns''' Conditions=[] '''Imports''' import urllib2 '''Open the weatherinstitute webpage and fetch the source html''' try: site = baseurl + location url = urllib2.urlopen(urllib2.quote(site).replace('%3A', ':')) except : print "Unable to fetch weather data. Please check your internet connection. If your connection is working fine then please file a bug at http://code.google.com/p/fiweather/issues/list" exit() doc=url.read() '''City name''' title = doc.find ("<title>") if title > 0: Conditions.append (cityString (title, doc)) else: Conditions.append ("Unknown city") '''Temperature value''' temper = x.numfinder(doc, tempera_base, tempera_num) if temper > 0: Conditions.append(temper) else: Conditions.append("No information.") '''Dew Point value''' dew = x.numfinder(doc, dew_base, dew_num) if dew > 0: #print dew Conditions.append(dew) else: Conditions.append("No information.") '''Humidity value''' humidit =x.numfinder(doc, hum_base, hum_num) if humidit > 0: Conditions.append(humidit) '''Windspeed value''' windit =x.numfinder(doc, win_base, win_num) clear = doc.find('''Tyynt&auml;</span>''') #dependant on working with ITL fix it. if windit > 0: Conditions.append(windit) elif clear > 0: Conditions.append('Calm') else: Conditions.append("No information.") '''Wind gust value''' gust =x.numfinder(doc, wing_base, wing_num) if gust > 0: Conditions.append(gust) else: Conditions.append("No information.") '''Cloudness''' clouds =x.numfinder(doc, '''<span class="parameter-value">(''', 50) if clouds > 0: Conditions.append(clouds) else: Conditions.append("No information.") '''Visibility''' visibility =x.numfinder(doc, '''<span class="parameter-name">N&auml;kyvyys</span>''', 100) if visibility > 0: Conditions.append(visibility) else: Conditions.append("No information.") '''pressure''' pr = x.numfinder(doc, '''<span class="parameter-name">Paine</span> <span class="parameter-value">''', 80) if pr > 0: Conditions.append (pr) else: Conditions.append ("No information.") '''Water for hour''' wh = x.numfinder(doc, '''sadekertym&auml;</span> <span class="parameter-value">''', 90) #print wh if wh > 0: Conditions.append (wh) else: Conditions.append ("No information.") return Conditions ###The Ugliest thing i ever wrote.. well not quite.. but close!### def forec(location): '''Imports''' import urllib2 import datetime '''Open the weatherinstitute webpage and fetch the source html''' try: site = 'http://ilmatieteenlaitos.fi/saa/' + location url = urllib2.urlopen(urllib2.quote(site).replace('%3A', ':')) except : print "Unable to fetch weather data. Please check your internet connection. If your connection is working fine then please file a bug at http://code.google.com/p/fiweather/issues/list" exit() doc=url.read() begin = doc.find('<tr class="meteogram-temperatures">') times = doc.find('<colgroup>') #return begin if begin > 0: loppu = doc.find('</td></tr><tr class="meteogram-wind-symbols"') #print doc[begin:loppu] parse1 = doc[begin:loppu].replace('<tr class="meteogram-temperatures">', '').replace('\n <td class="positive">','').replace('</td><td class="positive">', '').replace(' ', '').replace('<span title="lämpötila ', '').replace('</span>', '') parse2 = parse1.split('\n') lista = [] for f in parse2: luku = f.find('"') parsettu = f[0:luku].replace('°C', '') lista.append(parsettu) #lista= list(set(lista)) lista.remove("") for x in lista: if x == ' ': lista.remove(x) else: pass if times > 0: begin = doc.find('<colgroup>') end = doc.find('</colgroup>') parse1 = doc[begin:end] parse2 = parse1.replace(' <col class="', '').replace(' <col class="', '').replace(' first-daily-step" />', '').replace(' last-daily-step" />', '').replace('" /', '').replace('>', '') parse3 = parse2.split('\n') parse3.remove("<colgroup") parse3.remove(' ') fir = 0 o = parse3.count('first-day odd-day ') luku = 0 i = 0 import forec o = forec.forec(lista, parse3) return o else: return 'Something went wrong in FiWeathersrc.py '
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- # # fiweather # # Copyright 2010-2011 Aleksi Joakim Palomäki <aleksi@ajp.dy.fi>, Tuukka Ojala <tuukka.ojala@gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. import urllib2 import sys import FiWeathersrc def help (): print 'Usage: fiweather city' print "Options:" print "-nofilt\t\t Don't filter output based on available information." print "-forec\t\t Show forecast.(incomplete!)" sys.exit (0) try: location = sys.argv[1] '''Uncomment under for testing''' #location = "Helsinki" except IndexError: help () #if sys.argv [1] == '-h' or sys.argv [1] == '--help': # help () '''Metrics''' celsius = ' °C' dewpoint = ' °C' prosents = ' %' windspeed = ' m/s' windgust = ' m/s' kilometers = ' km' airpressure = ' hPa' wateramount= ' mm' #Do we filter? filt = True ###Features in developement try: if sys.argv[2]>0: if sys.argv[2] == '-forec': Y = FiWeathersrc.forec(location) print Y quit() elif sys.argv[2] == "-nofilt": #We dont' want to filter :( filt = False except IndexError, e: pass X = FiWeathersrc.finds(location) #print X '''Remove metrics from no info values''' if X[0] == "Unknown city": city = none else: city = X[0] if X[1] == "No information.": celsius = '' if X[2] == "No information.": dewpoint = '' if X[3] == "No information.": pressure = '' if X[4] == "No information." or X[4] == "Calm": windspeed = '' if X[5] == "No information.": windgust = '' if X[7] == "No information.": kilometers = '' if X[8] == "No information.": airpressure = '' if X[9] == "No information.": wateramount = '' try:#This is quickly made fix allowing us to use city search like "Helsinki/kumpula" or "Kouvola/anjala" if location.capitalize () <> city and city.split(",")[1].strip(" ") not in location.capitalize () : print "Invalid city." sys.exit (1) except:#Fallback to old way if the new one fails(gives index error) if location.capitalize () <> city: print "Invalid city." sys.exit (1) Temperature = X[1] + celsius Dew_Point = X[2] + dewpoint Air_Humidity = X[3] + prosents Wind_speed = X[4] + windspeed Wind_gust = X[5] + windgust Cloud_level = X[6] Visibility = X[7] + kilometers Air_Pressure = X[8] + airpressure Last_1h_Rain = X[9] + wateramount #Ugly filtering "No information" away if wanted. if filt == True: #print "filter true" if X[0].find("No information."): print 'Weather in %(city)s'% locals() if X[1].find("No information."): print 'Temperature:\t %(Temperature)s'% locals() if X[2].find("No information."): print 'Dew Point:\t %(Dew_Point)s'% locals() if X[3].find("No information."): print 'Air Humidity:\t %(Air_Humidity)s'% locals() if X[4].find("No information."): print 'Wind speed:\t %(Wind_speed)s'% locals() if X[5].find("No information."): print 'Wind gust:\t %(Wind_gust)s'% locals() if X[6].find("No information."): print 'Cloudness:\t %(Cloud_level)s'% locals() if X[7].find("No information."): print 'Visibility:\t %(Visibility)s'% locals() if X[8].find("No information."): print 'Air Pressure:\t %(Air_Pressure)s'% locals() if X[9].find("No information."): print 'Last 1h Rain:\t %(Last_1h_Rain)s'% locals() sys.exit(0) ########################### Weather_All = '''Weather in %(city)s Temperature:\t %(Temperature)s Dew Point:\t %(Dew_Point)s Air Humidity:\t %(Air_Humidity)s Wind speed:\t %(Wind_speed)s Wind gust:\t %(Wind_gust)s Cloudness:\t %(Cloud_level)s Visibility:\t %(Visibility)s Air Pressure:\t %(Air_Pressure)s Last 1h Rain:\t %(Last_1h_Rain)s ''' % locals() print Weather_All
Python
from distutils.core import setup import py2exe import sys sys.argv.append ("py2exe") options = { 'ascii':True, 'excludes':['_ssl', 'difflib', 'doctest', 'locale', 'optparse', 'pickle', 'calendar'], 'compressed':True} name = "Fiweather" version = "1.0" setup (name=name, version=version, console=['../fiweather'], options={'py2exe':options}) #setup (name=name, version=version, windows=['../fiweatherGUI.pyw'], options={'py2exe':options})
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- # # untitled.py # # Copyright 2011 Aleksi Palomäki <aleksi@gami> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. # # #ennusteet = ['19 ', '20 ', '16 ', '14 ', '13 ', '13 ', '16 ', '20 ', '19 ', '14 ', '18 ', '21 ', '15 ', '20 ', '14 ', '21 ', '17 ', '31 '] #ajat = ['first-day odd-day', 'first-day odd-day', 'first-day odd-day', 'even-day', 'even-day', 'even-day', 'even-day', 'even-day', 'even-day', 'odd-day', 'odd-day', 'odd-day', 'even-day', 'even-day', 'odd-day', 'odd-day', 'last-day even-day', 'last-day even-day'] def forec(ennusteet, ajat): firstdays = 0 secondday = 0 today = [] check = 1 ennuste = [] time = 21 for x in ajat[:]: if x == "first-day odd-day": ennuste.append("Today: " + ennusteet[0] + "C") firstdays = firstdays+1 del ennusteet[0] del ajat[0] for x in ajat[:]: if x == "even-day" and check == 1: ennuste.append("Tomorrow: " + ennusteet[0] + "C") secondday = secondday+1 del ennusteet[0] del ajat[0] if x == "odd-day": break for i in range(firstdays): if firstdays < 2: ennuste[i] = "Today: " + ennusteet[0] + "C" for x in ennuste[:]: print x print firstdays
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- # # untitled.py # # Copyright 2012 Aleksi Joakim Palomäki <aleksi@ajp.dy.fi> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. # # class numfind: def numfinder(self, text, string, length): import re if '<span class="parameter-value">(' != string: loc1 = text.find(string) unparsed = text[loc1:loc1+length] almostparsed = re.findall("[-]?[0-9]*", unparsed) parsed = [i for i in almostparsed if i] while parsed.count("-") > 0: if parsed.count("-") > 0: #This had extra "-" marks and this is removing the ones we don't need #print parsed.count("-") parsed.remove("-") if parsed.count("-") >= 1: #if we have more then 1 then the - is [0] and bug, remove it. parsed.pop(0) #for i in parsed: # if parsed[0] == "-": # parsed.remove() try: #This is something ugly to define if we have desimals or not :P ready = parsed[0] + ',' + parsed[1] return ready except: #if parsed is invalid for above statement we need to set it to something else if parsed == []: parsed = [-1] return parsed[0] else: #and in case its not empty [] we still need to set it to something else since it failed above.. return parsed[0] #lets expect its about clouds #TODO: If we ever want to have fiweather work with "All" weather sites, # we need smarter system to specify weather we are searching clouds or not.. else: loc1 = text.find(string) unparsed = text[loc1:loc1+length] almostparsed = re.findall("[-]?[0-9]*", unparsed) parsed = [i for i in almostparsed if i] #print unparsed while "-" in parsed: if "-" in parsed: parsed.remove("-") if parsed == []: parsed = [-1] return parsed[0] else: ready = parsed[0] + '/' + parsed[1] return ready #print numfinder("moi","kaikenlaistamoimoi teksit ja sit pari numero 349 astetta", "numero", 2000)
Python
import ConfigParser def config_pars(cfg): values = {} config = ConfigParser.ConfigParser() config.readfp(open(cfg)) url = config.get("baseurl", "url") tmp_start = config.get("temperature", "start") tmp_num = config.get("temperature", "num") dew_start = config.get("dewpoint", "start") dew_num = config.get("dewpoint", "num") hum_start = config.get("humidity", "start") hum_num = config.get("dewpoint", "num") win_start = config.get("wind_speed", "start") win_num = config.get("dewpoint", "num") wing_start = config.get("wind_gust", "start") wing_num = config.get("dewpoint", "num") cloud_start = config.get("cloudness", "start") cloud_num = config.get("dewpoint", "num") values["baseurl"] = url values["temperature_start"] = tmp_start values["temperature_num"] = tmp_num values["dewpoint_start"] = dew_start values["dewpoint_num"] = dew_num values["humidity_start"] = hum_start values["humidity_num"] = hum_num values["wind_speed_start"] = win_start values["wind_speed_num"] = win_num values["wind_gust_start"] = wing_start values["wind_gust_num"] = wing_num return values
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- # # FiWeathersrc.py # # Copyright 2010-2011 Aleksi Joakim Palomäki <aleksi@ajp.dy.fi>, Tuukka Ojala <tuukka.ojala@gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. ''' This is function to find the informations Today ''' def cityString (title, doc): start = int (title) +7 end = doc.find (" - Pai") return doc [start:end] def finds(location): import config_parser cfg = "ITL.txt" c = config_parser.config_pars(cfg) baseurl = c["baseurl"] tempera_num = int(c["temperature_num"]) tempera_base = c["temperature_start"] dew_num = int(c["dewpoint_num"]) dew_base = c["dewpoint_start"] hum_num = int(c["humidity_num"]) hum_base = c["humidity_start"] win_num = int(c["wind_speed_num"]) win_base = c["wind_speed_start"] wing_num = int(c["wind_gust_num"]) wing_base = c["wind_gust_start"] import string_num_finder x = string_num_finder.numfind() ''''List for conditions that this function returns''' Conditions=[] '''Imports''' import urllib2 '''Open the weatherinstitute webpage and fetch the source html''' try: site = baseurl + location url = urllib2.urlopen(urllib2.quote(site).replace('%3A', ':')) except : print "Unable to fetch weather data. Please check your internet connection. If your connection is working fine then please file a bug at http://code.google.com/p/fiweather/issues/list" exit() doc=url.read() '''City name''' title = doc.find ("<title>") if title > 0: Conditions.append (cityString (title, doc)) else: Conditions.append ("Unknown city") '''Temperature value''' temper = x.numfinder(doc, tempera_base, tempera_num) if temper > 0: Conditions.append(temper) else: Conditions.append("No information.") '''Dew Point value''' dew = x.numfinder(doc, dew_base, dew_num) if dew > 0: #print dew Conditions.append(dew) else: Conditions.append("No information.") '''Humidity value''' humidit =x.numfinder(doc, hum_base, hum_num) if humidit > 0: Conditions.append(humidit) '''Windspeed value''' windit =x.numfinder(doc, win_base, win_num) clear = doc.find('''Tyynt&auml;</span>''') #dependant on working with ITL fix it. if windit > 0: Conditions.append(windit) elif clear > 0: Conditions.append('Calm') else: Conditions.append("No information.") '''Wind gust value''' gust =x.numfinder(doc, wing_base, wing_num) if gust > 0: Conditions.append(gust) else: Conditions.append("No information.") '''Cloudness''' clouds =x.numfinder(doc, '''<span class="parameter-value">(''', 50) if clouds > 0: Conditions.append(clouds) else: Conditions.append("No information.") '''Visibility''' visibility =x.numfinder(doc, '''<span class="parameter-name">N&auml;kyvyys</span>''', 100) if visibility > 0: Conditions.append(visibility) else: Conditions.append("No information.") '''pressure''' pr = x.numfinder(doc, '''<span class="parameter-name">Paine</span> <span class="parameter-value">''', 80) if pr > 0: Conditions.append (pr) else: Conditions.append ("No information.") '''Water for hour''' wh = x.numfinder(doc, '''sadekertym&auml;</span> <span class="parameter-value">''', 90) #print wh if wh > 0: Conditions.append (wh) else: Conditions.append ("No information.") return Conditions ###The Ugliest thing i ever wrote.. well not quite.. but close!### def forec(location): '''Imports''' import urllib2 import datetime '''Open the weatherinstitute webpage and fetch the source html''' try: site = 'http://ilmatieteenlaitos.fi/saa/' + location url = urllib2.urlopen(urllib2.quote(site).replace('%3A', ':')) except : print "Unable to fetch weather data. Please check your internet connection. If your connection is working fine then please file a bug at http://code.google.com/p/fiweather/issues/list" exit() doc=url.read() begin = doc.find('<tr class="meteogram-temperatures">') times = doc.find('<colgroup>') #return begin if begin > 0: loppu = doc.find('</td></tr><tr class="meteogram-wind-symbols"') #print doc[begin:loppu] parse1 = doc[begin:loppu].replace('<tr class="meteogram-temperatures">', '').replace('\n <td class="positive">','').replace('</td><td class="positive">', '').replace(' ', '').replace('<span title="lämpötila ', '').replace('</span>', '') parse2 = parse1.split('\n') lista = [] for f in parse2: luku = f.find('"') parsettu = f[0:luku].replace('°C', '') lista.append(parsettu) #lista= list(set(lista)) lista.remove("") for x in lista: if x == ' ': lista.remove(x) else: pass if times > 0: begin = doc.find('<colgroup>') end = doc.find('</colgroup>') parse1 = doc[begin:end] parse2 = parse1.replace(' <col class="', '').replace(' <col class="', '').replace(' first-daily-step" />', '').replace(' last-daily-step" />', '').replace('" /', '').replace('>', '') parse3 = parse2.split('\n') parse3.remove("<colgroup") parse3.remove(' ') fir = 0 o = parse3.count('first-day odd-day ') luku = 0 i = 0 import forec o = forec.forec(lista, parse3) return o else: return 'Something went wrong in FiWeathersrc.py '
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- # # fiweather # # Copyright 2010-2011 Aleksi Joakim Palomäki <aleksi@ajp.dy.fi>, Tuukka Ojala <tuukka.ojala@gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. import urllib2 import sys import FiWeathersrc def help (): print 'Usage: fiweather city' print "Options:" print "-nofilt\t\t Don't filter output based on available information." print "-forec\t\t Show forecast.(incomplete!)" sys.exit (0) try: location = sys.argv[1] '''Uncomment under for testing''' #location = "Helsinki" except IndexError: help () #if sys.argv [1] == '-h' or sys.argv [1] == '--help': # help () '''Metrics''' celsius = ' °C' dewpoint = ' °C' prosents = ' %' windspeed = ' m/s' windgust = ' m/s' kilometers = ' km' airpressure = ' hPa' wateramount= ' mm' #Do we filter? filt = True ###Features in developement try: if sys.argv[2]>0: if sys.argv[2] == '-forec': Y = FiWeathersrc.forec(location) print Y quit() elif sys.argv[2] == "-nofilt": #We dont' want to filter :( filt = False except IndexError, e: pass X = FiWeathersrc.finds(location) #print X '''Remove metrics from no info values''' if X[0] == "Unknown city": city = none else: city = X[0] if X[1] == "No information.": celsius = '' if X[2] == "No information.": dewpoint = '' if X[3] == "No information.": pressure = '' if X[4] == "No information." or X[4] == "Calm": windspeed = '' if X[5] == "No information.": windgust = '' if X[7] == "No information.": kilometers = '' if X[8] == "No information.": airpressure = '' if X[9] == "No information.": wateramount = '' if location.capitalize () <> city: print "Invalid city." sys.exit (1) Temperature = X[1] + celsius Dew_Point = X[2] + dewpoint Air_Humidity = X[3] + prosents Wind_speed = X[4] + windspeed Wind_gust = X[5] + windgust Cloud_level = X[6] Visibility = X[7] + kilometers Air_Pressure = X[8] + airpressure Last_1h_Rain = X[9] + wateramount #Ugly filtering "No information" away if wanted. if filt == True: #print "filter true" if X[0].find("No information."): print 'Weather in %(city)s'% locals() if X[1].find("No information."): print 'Temperature:\t %(Temperature)s'% locals() if X[2].find("No information."): print 'Dew Point:\t %(Dew_Point)s'% locals() if X[3].find("No information."): print 'Air Humidity:\t %(Air_Humidity)s'% locals() if X[4].find("No information."): print 'Wind speed:\t %(Wind_speed)s'% locals() if X[5].find("No information."): print 'Wind gust:\t %(Wind_gust)s'% locals() if X[6].find("No information."): print 'Cloudness:\t %(Cloud_level)s'% locals() if X[7].find("No information."): print 'Visibility:\t %(Visibility)s'% locals() if X[8].find("No information."): print 'Air Pressure:\t %(Air_Pressure)s'% locals() if X[9].find("No information."): print 'Last 1h Rain:\t %(Last_1h_Rain)s'% locals() sys.exit(0) ########################### Weather_All = '''Weather in %(city)s Temperature:\t %(Temperature)s Dew Point:\t %(Dew_Point)s Air Humidity:\t %(Air_Humidity)s Wind speed:\t %(Wind_speed)s Wind gust:\t %(Wind_gust)s Cloudness:\t %(Cloud_level)s Visibility:\t %(Visibility)s Air Pressure:\t %(Air_Pressure)s Last 1h Rain:\t %(Last_1h_Rain)s ''' % locals() print Weather_All
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- # # untitled.py # # Copyright 2011 Aleksi Palomäki <aleksi@gami> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. # # #ennusteet = ['19 ', '20 ', '16 ', '14 ', '13 ', '13 ', '16 ', '20 ', '19 ', '14 ', '18 ', '21 ', '15 ', '20 ', '14 ', '21 ', '17 ', '31 '] #ajat = ['first-day odd-day', 'first-day odd-day', 'first-day odd-day', 'even-day', 'even-day', 'even-day', 'even-day', 'even-day', 'even-day', 'odd-day', 'odd-day', 'odd-day', 'even-day', 'even-day', 'odd-day', 'odd-day', 'last-day even-day', 'last-day even-day'] def forec(ennusteet, ajat): firstdays = 0 secondday = 0 today = [] check = 1 ennuste = [] time = 21 for x in ajat[:]: if x == "first-day odd-day": ennuste.append("Today: " + ennusteet[0] + "C") firstdays = firstdays+1 del ennusteet[0] del ajat[0] for x in ajat[:]: if x == "even-day" and check == 1: ennuste.append("Tomorrow: " + ennusteet[0] + "C") secondday = secondday+1 del ennusteet[0] del ajat[0] if x == "odd-day": break for i in range(firstdays): if firstdays < 2: ennuste[i] = "Today: " + ennusteet[0] + "C" for x in ennuste[:]: print x print firstdays
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- # # FiWeathersrc.py # # Copyright 2010-2011 Aleksi Joakim Palomäki <aleksi@ajp.dy.fi>, Tuukka Ojala <tuukka.ojala@gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. ''' This is function to find the informations Today ''' def cityString (title, doc): start = int (title) +7 end = doc.find (" - Pai") return doc [start:end] def finds(location): import config_parser cfg = "ITL.txt" c = config_parser.config_pars(cfg) baseurl = c["baseurl"] tempera_num = int(c["temperature_num"]) tempera_base = c["temperature_start"] dew_num = int(c["dewpoint_num"]) dew_base = c["dewpoint_start"] hum_num = int(c["humidity_num"]) hum_base = c["humidity_start"] win_num = int(c["wind_speed_num"]) win_base = c["wind_speed_start"] wing_num = int(c["wind_gust_num"]) wing_base = c["wind_gust_start"] import string_num_finder x = string_num_finder.numfind() ''''List for conditions that this function returns''' Conditions=[] '''Imports''' import urllib2 '''Open the weatherinstitute webpage and fetch the source html''' try: site = baseurl + location url = urllib2.urlopen(urllib2.quote(site).replace('%3A', ':')) except : print "Unable to fetch weather data. Please check your internet connection. If your connection is working fine then please file a bug at http://code.google.com/p/fiweather/issues/list" exit() doc=url.read() '''City name''' title = doc.find ("<title>") if title > 0: Conditions.append (cityString (title, doc)) else: Conditions.append ("Unknown city") '''Temperature value''' temper = x.numfinder(doc, tempera_base, tempera_num) if temper > 0: Conditions.append(temper) else: Conditions.append("No information.") '''Dew Point value''' dew = x.numfinder(doc, dew_base, dew_num) if dew > 0: #print dew Conditions.append(dew) else: Conditions.append("No information.") '''Humidity value''' humidit =x.numfinder(doc, hum_base, hum_num) if humidit > 0: Conditions.append(humidit) '''Windspeed value''' windit =x.numfinder(doc, win_base, win_num) clear = doc.find('''Tyynt&auml;</span>''') #dependant on working with ITL fix it. if windit > 0: Conditions.append(windit) elif clear > 0: Conditions.append('Calm') else: Conditions.append("No information.") '''Wind gust value''' gust =x.numfinder(doc, wing_base, wing_num) if gust > 0: Conditions.append(gust) else: Conditions.append("No information.") '''Cloudness''' clouds =x.numfinder(doc, '''<span class="parameter-value">(''', 50) if clouds > 0: Conditions.append(clouds) else: Conditions.append("No information.") '''Visibility''' visibility =x.numfinder(doc, '''<span class="parameter-name">N&auml;kyvyys</span>''', 100) if visibility > 0: Conditions.append(visibility) else: Conditions.append("No information.") '''pressure''' pr = x.numfinder(doc, '''<span class="parameter-name">Paine</span> <span class="parameter-value">''', 80) if pr > 0: Conditions.append (pr) else: Conditions.append ("No information.") '''Water for hour''' wh = x.numfinder(doc, '''sadekertym&auml;</span> <span class="parameter-value">''', 90) #print wh if wh > 0: Conditions.append (wh) else: Conditions.append ("No information.") return Conditions ###The Ugliest thing i ever wrote.. well not quite.. but close!### def forec(location): '''Imports''' import urllib2 import datetime '''Open the weatherinstitute webpage and fetch the source html''' try: site = 'http://ilmatieteenlaitos.fi/saa/' + location url = urllib2.urlopen(urllib2.quote(site).replace('%3A', ':')) except : print "Unable to fetch weather data. Please check your internet connection. If your connection is working fine then please file a bug at http://code.google.com/p/fiweather/issues/list" exit() doc=url.read() begin = doc.find('<tr class="meteogram-temperatures">') times = doc.find('<colgroup>') #return begin if begin > 0: loppu = doc.find('</td></tr><tr class="meteogram-wind-symbols"') #print doc[begin:loppu] parse1 = doc[begin:loppu].replace('<tr class="meteogram-temperatures">', '').replace('\n <td class="positive">','').replace('</td><td class="positive">', '').replace(' ', '').replace('<span title="lämpötila ', '').replace('</span>', '') parse2 = parse1.split('\n') lista = [] for f in parse2: luku = f.find('"') parsettu = f[0:luku].replace('°C', '') lista.append(parsettu) #lista= list(set(lista)) lista.remove("") for x in lista: if x == ' ': lista.remove(x) else: pass if times > 0: begin = doc.find('<colgroup>') end = doc.find('</colgroup>') parse1 = doc[begin:end] parse2 = parse1.replace(' <col class="', '').replace(' <col class="', '').replace(' first-daily-step" />', '').replace(' last-daily-step" />', '').replace('" /', '').replace('>', '') parse3 = parse2.split('\n') parse3.remove("<colgroup") parse3.remove(' ') fir = 0 o = parse3.count('first-day odd-day ') luku = 0 i = 0 import forec o = forec.forec(lista, parse3) return o else: return 'Something went wrong in FiWeathersrc.py '
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- # # fiweather # # Copyright 2010-2011 Aleksi Joakim Palomäki <aleksi@ajp.dy.fi>, Tuukka Ojala <tuukka.ojala@gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. import urllib2 import sys import FiWeathersrc def help (): print 'Usage: fiweather city' print "Options:" print "-nofilt\t\t Don't filter output based on available information." print "-forec\t\t Show forecast.(incomplete!)" sys.exit (0) try: location = sys.argv[1] '''Uncomment under for testing''' #location = "Helsinki" except IndexError: help () #if sys.argv [1] == '-h' or sys.argv [1] == '--help': # help () '''Metrics''' celsius = ' °C' dewpoint = ' °C' prosents = ' %' windspeed = ' m/s' windgust = ' m/s' kilometers = ' km' airpressure = ' hPa' wateramount= ' mm' #Do we filter? filt = True ###Features in developement try: if sys.argv[2]>0: if sys.argv[2] == '-forec': Y = FiWeathersrc.forec(location) print Y quit() elif sys.argv[2] == "-nofilt": #We dont' want to filter :( filt = False except IndexError, e: pass X = FiWeathersrc.finds(location) #print X '''Remove metrics from no info values''' if X[0] == "Unknown city": city = none else: city = X[0] if X[1] == "No information.": celsius = '' if X[2] == "No information.": dewpoint = '' if X[3] == "No information.": pressure = '' if X[4] == "No information." or X[4] == "Calm": windspeed = '' if X[5] == "No information.": windgust = '' if X[7] == "No information.": kilometers = '' if X[8] == "No information.": airpressure = '' if X[9] == "No information.": wateramount = '' if location.capitalize () <> city: print "Invalid city." sys.exit (1) Temperature = X[1] + celsius Dew_Point = X[2] + dewpoint Air_Humidity = X[3] + prosents Wind_speed = X[4] + windspeed Wind_gust = X[5] + windgust Cloud_level = X[6] Visibility = X[7] + kilometers Air_Pressure = X[8] + airpressure Last_1h_Rain = X[9] + wateramount #Ugly filtering "No information" away if wanted. if filt == True: #print "filter true" if X[0].find("No information."): print 'Weather in %(city)s'% locals() if X[1].find("No information."): print 'Temperature:\t %(Temperature)s'% locals() if X[2].find("No information."): print 'Dew Point:\t %(Dew_Point)s'% locals() if X[3].find("No information."): print 'Air Humidity:\t %(Air_Humidity)s'% locals() if X[4].find("No information."): print 'Wind speed:\t %(Wind_speed)s'% locals() if X[5].find("No information."): print 'Wind gust:\t %(Wind_gust)s'% locals() if X[6].find("No information."): print 'Cloudness:\t %(Cloud_level)s'% locals() if X[7].find("No information."): print 'Visibility:\t %(Visibility)s'% locals() if X[8].find("No information."): print 'Air Pressure:\t %(Air_Pressure)s'% locals() if X[9].find("No information."): print 'Last 1h Rain:\t %(Last_1h_Rain)s'% locals() sys.exit(0) ########################### Weather_All = '''Weather in %(city)s Temperature:\t %(Temperature)s Dew Point:\t %(Dew_Point)s Air Humidity:\t %(Air_Humidity)s Wind speed:\t %(Wind_speed)s Wind gust:\t %(Wind_gust)s Cloudness:\t %(Cloud_level)s Visibility:\t %(Visibility)s Air Pressure:\t %(Air_Pressure)s Last 1h Rain:\t %(Last_1h_Rain)s ''' % locals() print Weather_All
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- # # untitled.py # # Copyright 2012 Aleksi Joakim Palomäki <aleksi@Oblivion> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. # # import sys, commands #try: # import pygtk # pygtk.require("2.0") #except: # pass try: import gtk import gtk.glade except: sys.exit(1) print "Imported stuff successfully." class FiWeatherGUI: def __init__(self): self.gladefile = "gui_simple1.glade" self.builder = gtk.Builder() self.builder.add_from_file(self.gladefile) self.builder.connect_signals(self) #self.builder.get_object("window1") self.window = self.builder.get_object("window1") self.button1 = self.builder.get_object("button1") self.entry = self.builder.get_object("entry1") self.text = self.builder.get_object("textview1") if (self.window): self.window.connect("destroy", gtk.main_quit) self.button1.connect("clicked", self.btnclicked) def btnclicked(self, widget): #print "You clicked the button1" city = self.entry.get_text() weatherinfo = commands.getoutput("python fiweather " + city) #help(self.text) # print self.text.get_buffer().insert(self.text.get_buffer().get_end_iter(), "\n" + str(weatherinfo)) print self.text.get_buffer().set_text(str(weatherinfo)) app = FiWeatherGUI() gtk.main()
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- # # untitled.py # # Copyright 2012 Aleksi Joakim Palomäki <aleksi@Oblivion> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. # # import sys, commands #try: # import pygtk # pygtk.require("2.0") #except: # pass try: import gtk import gtk.glade except: sys.exit(1) print "Imported stuff successfully." class FiWeatherGUI: def __init__(self): self.gladefile = "gui_simple1.glade" self.builder = gtk.Builder() self.builder.add_from_file(self.gladefile) self.builder.connect_signals(self) #self.builder.get_object("window1") self.window = self.builder.get_object("window1") self.button1 = self.builder.get_object("button1") self.entry = self.builder.get_object("entry1") self.text = self.builder.get_object("textview1") if (self.window): self.window.connect("destroy", gtk.main_quit) self.button1.connect("clicked", self.btnclicked) def btnclicked(self, widget): #print "You clicked the button1" city = self.entry.get_text() weatherinfo = commands.getoutput("python fiweather " + city) #help(self.text) # print self.text.get_buffer().insert(self.text.get_buffer().get_end_iter(), "\n" + str(weatherinfo)) print self.text.get_buffer().set_text(str(weatherinfo)) app = FiWeatherGUI() gtk.main()
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import maya.OpenMaya as OpenMaya import os import unittest import util class AnimMeshTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] self.__abcStitcherExe = os.environ['AbcStitcher'] + ' ' def tearDown(self): for f in self.__files : os.remove(f) def testAnimPolyReadWrite(self): numFaces = 6 numVertices = 8 numFaceConnects = 24 vtx_1 = OpenMaya.MFloatPoint(-0.5, -0.5, -0.5) vtx_2 = OpenMaya.MFloatPoint( 0.5, -0.5, -0.5) vtx_3 = OpenMaya.MFloatPoint( 0.5, -0.5, 0.5) vtx_4 = OpenMaya.MFloatPoint(-0.5, -0.5, 0.5) vtx_5 = OpenMaya.MFloatPoint(-0.5, 0.5, -0.5) vtx_6 = OpenMaya.MFloatPoint(-0.5, 0.5, 0.5) vtx_7 = OpenMaya.MFloatPoint( 0.5, 0.5, 0.5) vtx_8 = OpenMaya.MFloatPoint( 0.5, 0.5, -0.5) points = OpenMaya.MFloatPointArray() points.setLength(8) points.set(vtx_1, 0) points.set(vtx_2, 1) points.set(vtx_3, 2) points.set(vtx_4, 3) points.set(vtx_5, 4) points.set(vtx_6, 5) points.set(vtx_7, 6) points.set(vtx_8, 7) faceConnects = OpenMaya.MIntArray() faceConnects.setLength(numFaceConnects) faceConnects.set(0, 0) faceConnects.set(1, 1) faceConnects.set(2, 2) faceConnects.set(3, 3) faceConnects.set(4, 4) faceConnects.set(5, 5) faceConnects.set(6, 6) faceConnects.set(7, 7) faceConnects.set(3, 8) faceConnects.set(2, 9) faceConnects.set(6, 10) faceConnects.set(5, 11) faceConnects.set(0, 12) faceConnects.set(3, 13) faceConnects.set(5, 14) faceConnects.set(4, 15) faceConnects.set(0, 16) faceConnects.set(4, 17) faceConnects.set(7, 18) faceConnects.set(1, 19) faceConnects.set(1, 20) faceConnects.set(7, 21) faceConnects.set(6, 22) faceConnects.set(2, 23) faceCounts = OpenMaya.MIntArray() faceCounts.setLength(6) faceCounts.set(4, 0) faceCounts.set(4, 1) faceCounts.set(4, 2) faceCounts.set(4, 3) faceCounts.set(4, 4) faceCounts.set(4, 5) transFn = OpenMaya.MFnTransform() parent = transFn.create() transFn.setName('poly') meshFn = OpenMaya.MFnMesh() meshFn.create(numVertices, numFaces, points, faceCounts, faceConnects, parent) meshFn.setName("polyShape"); MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe('polyShape.vtx[0:7]') MayaCmds.currentTime(24, update=True) MayaCmds.setKeyframe('polyShape.vtx[0:7]') MayaCmds.currentTime(12, update=True) vtx_11 = OpenMaya.MFloatPoint(-1, -1, -1) vtx_22 = OpenMaya.MFloatPoint( 1, -1, -1) vtx_33 = OpenMaya.MFloatPoint( 1, -1, 1) vtx_44 = OpenMaya.MFloatPoint(-1, -1, 1) vtx_55 = OpenMaya.MFloatPoint(-1, 1, -1) vtx_66 = OpenMaya.MFloatPoint(-1, 1, 1) vtx_77 = OpenMaya.MFloatPoint( 1, 1, 1) vtx_88 = OpenMaya.MFloatPoint( 1, 1, -1) points.set(vtx_11, 0) points.set(vtx_22, 1) points.set(vtx_33, 2) points.set(vtx_44, 3) points.set(vtx_55, 4) points.set(vtx_66, 5) points.set(vtx_77, 6) points.set(vtx_88, 7) meshFn.setPoints(points) MayaCmds.setKeyframe('polyShape.vtx[0:7]') self.__files.append(util.expandFileName('animPoly.abc')) self.__files.append(util.expandFileName('animPoly01_14.abc')) MayaCmds.AbcExport(j='-fr 1 14 -root poly -file ' + self.__files[-1]) self.__files.append(util.expandFileName('animPoly15_24.abc')) MayaCmds.AbcExport(j='-fr 15 24 -root poly -file ' + self.__files[-1]) # use AbcStitcher to combine two files into one os.system(self.__abcStitcherExe + ' '.join(self.__files[-3:])) # reading test MayaCmds.AbcImport(self.__files[-3], mode='open') MayaCmds.currentTime(1, update=True) sList = OpenMaya.MSelectionList(); sList.add('polyShape'); meshObj = OpenMaya.MObject(); sList.getDependNode(0, meshObj); meshFn = OpenMaya.MFnMesh(meshObj) # check the point list meshPoints = OpenMaya.MFloatPointArray() meshFn.getPoints(meshPoints) self.failUnlessEqual(vtx_1, meshPoints[0]) self.failUnlessEqual(vtx_2, meshPoints[1]) self.failUnlessEqual(vtx_3, meshPoints[2]) self.failUnlessEqual(vtx_4, meshPoints[3]) self.failUnlessEqual(vtx_5, meshPoints[4]) self.failUnlessEqual(vtx_6, meshPoints[5]) self.failUnlessEqual(vtx_7, meshPoints[6]) self.failUnlessEqual(vtx_8, meshPoints[7]) # check the polygonvertices list vertexList = OpenMaya.MIntArray() faceConnects = OpenMaya.MIntArray() faceConnects.setLength(4) faceConnects.set(0, 0) faceConnects.set(1, 1) faceConnects.set(2, 2) faceConnects.set(3, 3) meshFn.getPolygonVertices(0, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(4, 0) faceConnects.set(5, 1) faceConnects.set(6, 2) faceConnects.set(7, 3) meshFn.getPolygonVertices(1, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(3, 0) faceConnects.set(2, 1) faceConnects.set(6, 2) faceConnects.set(5, 3) meshFn.getPolygonVertices(2, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(0, 0) faceConnects.set(3, 1) faceConnects.set(5, 2) faceConnects.set(4, 3) meshFn.getPolygonVertices(3, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(0, 0) faceConnects.set(4, 1) faceConnects.set(7, 2) faceConnects.set(1, 3) meshFn.getPolygonVertices(4, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(1, 0) faceConnects.set(7, 1) faceConnects.set(6, 2) faceConnects.set(2, 3) meshFn.getPolygonVertices(5, vertexList) self.failUnlessEqual(faceConnects, vertexList) MayaCmds.currentTime(12, update=True) meshPoints = OpenMaya.MFloatPointArray() meshFn.getPoints(meshPoints) self.failUnlessEqual(vtx_11, meshPoints[0]) self.failUnlessEqual(vtx_22, meshPoints[1]) self.failUnlessEqual(vtx_33, meshPoints[2]) self.failUnlessEqual(vtx_44, meshPoints[3]) self.failUnlessEqual(vtx_55, meshPoints[4]) self.failUnlessEqual(vtx_66, meshPoints[5]) self.failUnlessEqual(vtx_77, meshPoints[6]) self.failUnlessEqual(vtx_88, meshPoints[7]) MayaCmds.currentTime(24, update=True) meshPoints = OpenMaya.MFloatPointArray() meshFn.getPoints(meshPoints) self.failUnlessEqual(vtx_1, meshPoints[0]) self.failUnlessEqual(vtx_2, meshPoints[1]) self.failUnlessEqual(vtx_3, meshPoints[2]) self.failUnlessEqual(vtx_4, meshPoints[3]) self.failUnlessEqual(vtx_5, meshPoints[4]) self.failUnlessEqual(vtx_6, meshPoints[5]) self.failUnlessEqual(vtx_7, meshPoints[6]) self.failUnlessEqual(vtx_8, meshPoints[7]) def testAnimSubDReadWrite(self): numFaces = 6 numVertices = 8 numFaceConnects = 24 vtx_1 = OpenMaya.MFloatPoint(-0.5, -0.5, -0.5) vtx_2 = OpenMaya.MFloatPoint( 0.5, -0.5, -0.5) vtx_3 = OpenMaya.MFloatPoint( 0.5, -0.5, 0.5) vtx_4 = OpenMaya.MFloatPoint(-0.5, -0.5, 0.5) vtx_5 = OpenMaya.MFloatPoint(-0.5, 0.5, -0.5) vtx_6 = OpenMaya.MFloatPoint(-0.5, 0.5, 0.5) vtx_7 = OpenMaya.MFloatPoint( 0.5, 0.5, 0.5) vtx_8 = OpenMaya.MFloatPoint( 0.5, 0.5, -0.5) points = OpenMaya.MFloatPointArray() points.setLength(8) points.set(vtx_1, 0) points.set(vtx_2, 1) points.set(vtx_3, 2) points.set(vtx_4, 3) points.set(vtx_5, 4) points.set(vtx_6, 5) points.set(vtx_7, 6) points.set(vtx_8, 7) faceConnects = OpenMaya.MIntArray() faceConnects.setLength(numFaceConnects) faceConnects.set(0, 0) faceConnects.set(1, 1) faceConnects.set(2, 2) faceConnects.set(3, 3) faceConnects.set(4, 4) faceConnects.set(5, 5) faceConnects.set(6, 6) faceConnects.set(7, 7) faceConnects.set(3, 8) faceConnects.set(2, 9) faceConnects.set(6, 10) faceConnects.set(5, 11) faceConnects.set(0, 12) faceConnects.set(3, 13) faceConnects.set(5, 14) faceConnects.set(4, 15) faceConnects.set(0, 16) faceConnects.set(4, 17) faceConnects.set(7, 18) faceConnects.set(1, 19) faceConnects.set(1, 20) faceConnects.set(7, 21) faceConnects.set(6, 22) faceConnects.set(2, 23) faceCounts = OpenMaya.MIntArray() faceCounts.setLength(6) faceCounts.set(4, 0) faceCounts.set(4, 1) faceCounts.set(4, 2) faceCounts.set(4, 3) faceCounts.set(4, 4) faceCounts.set(4, 5) transFn = OpenMaya.MFnTransform() parent = transFn.create() transFn.setName('subD') meshFn = OpenMaya.MFnMesh() meshFn.create(numVertices, numFaces, points, faceCounts, faceConnects, parent) meshFn.setName("subDShape"); MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe('subDShape.vtx[0:7]') MayaCmds.currentTime(24, update=True) MayaCmds.setKeyframe('subDShape.vtx[0:7]') MayaCmds.currentTime(12, update=True) vtx_11 = OpenMaya.MFloatPoint(-1, -1, -1) vtx_22 = OpenMaya.MFloatPoint( 1, -1, -1) vtx_33 = OpenMaya.MFloatPoint( 1, -1, 1) vtx_44 = OpenMaya.MFloatPoint(-1, -1, 1) vtx_55 = OpenMaya.MFloatPoint(-1, 1, -1) vtx_66 = OpenMaya.MFloatPoint(-1, 1, 1) vtx_77 = OpenMaya.MFloatPoint( 1, 1, 1) vtx_88 = OpenMaya.MFloatPoint( 1, 1, -1) points.set(vtx_11, 0) points.set(vtx_22, 1) points.set(vtx_33, 2) points.set(vtx_44, 3) points.set(vtx_55, 4) points.set(vtx_66, 5) points.set(vtx_77, 6) points.set(vtx_88, 7) meshFn.setPoints(points) MayaCmds.setKeyframe('subDShape.vtx[0:7]') # mark the mesh as a subD MayaCmds.select('subDShape') MayaCmds.addAttr(attributeType='bool', defaultValue=1, keyable=True, longName='SubDivisionMesh') self.__files.append(util.expandFileName('animSubD.abc')) self.__files.append(util.expandFileName('animSubD01_14.abc')) MayaCmds.AbcExport(j='-fr 1 14 -root subD -file ' + self.__files[-1]) self.__files.append(util.expandFileName('animSubD15_24.abc')) MayaCmds.AbcExport(j='-fr 15 24 -root subD -file ' + self.__files[-1]) # use AbcStitcher to combine two files into one os.system(self.__abcStitcherExe + ' '.join(self.__files[-3:])) # reading test MayaCmds.AbcImport(self.__files[-3], mode='open') MayaCmds.currentTime(1, update=True) sList = OpenMaya.MSelectionList() sList.add('subDShape') meshObj = OpenMaya.MObject() sList.getDependNode(0, meshObj) meshFn = OpenMaya.MFnMesh(meshObj) # check the point list meshPoints = OpenMaya.MFloatPointArray() meshFn.getPoints(meshPoints) self.failUnlessEqual(vtx_1, meshPoints[0]) self.failUnlessEqual(vtx_2, meshPoints[1]) self.failUnlessEqual(vtx_3, meshPoints[2]) self.failUnlessEqual(vtx_4, meshPoints[3]) self.failUnlessEqual(vtx_5, meshPoints[4]) self.failUnlessEqual(vtx_6, meshPoints[5]) self.failUnlessEqual(vtx_7, meshPoints[6]) self.failUnlessEqual(vtx_8, meshPoints[7]) # check the polygonvertices list vertexList = OpenMaya.MIntArray() faceConnects = OpenMaya.MIntArray() faceConnects.setLength(4) faceConnects.set(0, 0) faceConnects.set(1, 1) faceConnects.set(2, 2) faceConnects.set(3, 3) meshFn.getPolygonVertices(0, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(4, 0) faceConnects.set(5, 1) faceConnects.set(6, 2) faceConnects.set(7, 3) meshFn.getPolygonVertices(1, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(3, 0) faceConnects.set(2, 1) faceConnects.set(6, 2) faceConnects.set(5, 3) meshFn.getPolygonVertices(2, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(0, 0) faceConnects.set(3, 1) faceConnects.set(5, 2) faceConnects.set(4, 3) meshFn.getPolygonVertices(3, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(0, 0) faceConnects.set(4, 1) faceConnects.set(7, 2) faceConnects.set(1, 3) meshFn.getPolygonVertices(4, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(1, 0) faceConnects.set(7, 1) faceConnects.set(6, 2) faceConnects.set(2, 3) meshFn.getPolygonVertices(5, vertexList) self.failUnlessEqual(faceConnects, vertexList) MayaCmds.currentTime(12, update=True) meshPoints = OpenMaya.MFloatPointArray() meshFn.getPoints(meshPoints) self.failUnlessEqual(vtx_11, meshPoints[0]) self.failUnlessEqual(vtx_22, meshPoints[1]) self.failUnlessEqual(vtx_33, meshPoints[2]) self.failUnlessEqual(vtx_44, meshPoints[3]) self.failUnlessEqual(vtx_55, meshPoints[4]) self.failUnlessEqual(vtx_66, meshPoints[5]) self.failUnlessEqual(vtx_77, meshPoints[6]) self.failUnlessEqual(vtx_88, meshPoints[7]) MayaCmds.currentTime(24, update=True) meshPoints = OpenMaya.MFloatPointArray() meshFn.getPoints(meshPoints) self.failUnlessEqual(vtx_1, meshPoints[0]) self.failUnlessEqual(vtx_2, meshPoints[1]) self.failUnlessEqual(vtx_3, meshPoints[2]) self.failUnlessEqual(vtx_4, meshPoints[3]) self.failUnlessEqual(vtx_5, meshPoints[4]) self.failUnlessEqual(vtx_6, meshPoints[5]) self.failUnlessEqual(vtx_7, meshPoints[6]) self.failUnlessEqual(vtx_8, meshPoints[7])
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import maya.OpenMaya as OpenMaya import os import unittest import util def getObjFromName( nodeName ): selectionList = OpenMaya.MSelectionList() selectionList.add( nodeName ) obj = OpenMaya.MObject() selectionList.getDependNode(0, obj) return obj class MeshUVsTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files: os.remove(f) # we only support writing out the most basic uv sets (and static only) def testPolyUVs(self): MayaCmds.polyCube(name = 'cube') cubeObj = getObjFromName('cubeShape') fnMesh = OpenMaya.MFnMesh(cubeObj) # get the name of the current UV set uvSetName = fnMesh.currentUVSetName() uArray = OpenMaya.MFloatArray() vArray = OpenMaya.MFloatArray() fnMesh.getUVs(uArray, vArray, uvSetName) newUArray = [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 2, -1, -1] newVArray = [0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 0, 1 , 0, 1] for i in range(0, 14): uArray[i] = newUArray[i] vArray[i] = newVArray[i] fnMesh.setUVs(uArray, vArray, uvSetName) self.__files.append(util.expandFileName('polyUvsTest.abc')) MayaCmds.AbcExport(j='-uv -root cube -file ' + self.__files[-1]) # reading test MayaCmds.AbcImport(self.__files[-1], mode='open') MayaCmds.select('cube.map[0:13]', replace=True) uvs = MayaCmds.polyEditUV(query=True) for i in range(0, 14): self.failUnlessAlmostEqual(newUArray[i], uvs[2*i], 4, 'map[%d].u is not the same' % i) self.failUnlessAlmostEqual(newVArray[i], uvs[2*i+1], 4, 'map[%d].v is not the same' % i)
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import maya.OpenMaya as OpenMaya import unittest import util import os class interpolationTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files: os.remove(f) def testSubD(self): trans = MayaCmds.polyPlane(n='plane', sx=1, sy=1, ch=False)[0] shape = MayaCmds.pickWalk(d='down')[0] MayaCmds.addAttr(attributeType='bool', defaultValue=1, keyable=True, longName='SubDivisionMesh') MayaCmds.select(trans+'.vtx[0:3]', r=True) MayaCmds.move(0, 1, 0, r=True) MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe() MayaCmds.currentTime(2, update=True) MayaCmds.move(0, 5, 0, r=True) MayaCmds.setKeyframe() self.__files.append(util.expandFileName('testSubDInterpolation.abc')) MayaCmds.AbcExport(j='-fr 1 2 -root %s -file %s' % (trans, self.__files[-1])) MayaCmds.AbcImport(self.__files[-1], mode='open') MayaCmds.currentTime(1.004, update=True) ty = MayaCmds.getAttr(shape+'.vt[0]')[0][1] self.failUnlessAlmostEqual(1.02, ty) setTime = MayaCmds.currentTime(1.422, update=True) alpha = (setTime - 1) / (2 - 1) ty = MayaCmds.getAttr(shape+'.vt[0]')[0][1] self.failUnlessAlmostEqual(ty, (1-alpha)*1.0+alpha*6.0, 3) def testPoly(self): trans = MayaCmds.polyPlane(n='plane', sx=1, sy=1, ch=False)[0] shape = MayaCmds.pickWalk(d='down')[0] MayaCmds.select(trans+'.vtx[0:3]', r=True) MayaCmds.move(0, 1, 0, r=True) MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe() MayaCmds.currentTime(2, update=True) MayaCmds.move(0, 5, 0, r=True) MayaCmds.setKeyframe() self.__files.append(util.expandFileName('testPolyInterpolation.abc')) MayaCmds.AbcExport(j='-fr 1 2 -root %s -file %s' % (trans, self.__files[-1])) MayaCmds.AbcImport(self.__files[-1], mode='open') MayaCmds.currentTime(1.004, update=True) ty = MayaCmds.getAttr(shape+'.vt[0]')[0][1] self.failUnlessAlmostEqual(1.02, ty) setTime = MayaCmds.currentTime(1.422, update=True) alpha = (setTime - 1) / (2 - 1) ty = MayaCmds.getAttr(shape+'.vt[0]')[0][1] self.failUnlessAlmostEqual(ty, (1-alpha)*1.0+alpha*6.0, 3) def testTransOp(self): nodeName = MayaCmds.createNode('transform', n='test') # shear MayaCmds.setKeyframe(nodeName, value=0, attribute='shearXY', t=1) MayaCmds.setKeyframe(nodeName, value=0, attribute='shearYZ', t=1) MayaCmds.setKeyframe(nodeName, value=0, attribute='shearXZ', t=1) MayaCmds.setKeyframe(nodeName, value=1.5, attribute='shearXY', t=2) MayaCmds.setKeyframe(nodeName, value=5, attribute='shearYZ', t=2) MayaCmds.setKeyframe(nodeName, value=2.5, attribute='shearXZ', t=2) # translate MayaCmds.setKeyframe('test', value=0, attribute='translateX', t=1) MayaCmds.setKeyframe('test', value=0, attribute='translateY', t=1) MayaCmds.setKeyframe('test', value=0, attribute='translateZ', t=1) MayaCmds.setKeyframe('test', value=1.5, attribute='translateX', t=2) MayaCmds.setKeyframe('test', value=5, attribute='translateY', t=2) MayaCmds.setKeyframe('test', value=2.5, attribute='translateZ', t=2) # rotate MayaCmds.setKeyframe('test', value=0, attribute='rotateX', t=1) MayaCmds.setKeyframe('test', value=0, attribute='rotateY', t=1) MayaCmds.setKeyframe('test', value=0, attribute='rotateZ', t=1) MayaCmds.setKeyframe('test', value=24, attribute='rotateX', t=2) MayaCmds.setKeyframe('test', value=53, attribute='rotateY', t=2) MayaCmds.setKeyframe('test', value=90, attribute='rotateZ', t=2) # scale MayaCmds.setKeyframe('test', value=1, attribute='scaleX', t=1) MayaCmds.setKeyframe('test', value=1, attribute='scaleY', t=1) MayaCmds.setKeyframe('test', value=1, attribute='scaleZ', t=1) MayaCmds.setKeyframe('test', value=1.2, attribute='scaleX', t=2) MayaCmds.setKeyframe('test', value=1.5, attribute='scaleY', t=2) MayaCmds.setKeyframe('test', value=1.5, attribute='scaleZ', t=2) # rotate pivot MayaCmds.setKeyframe('test', value=0.5, attribute='rotatePivotX', t=1) MayaCmds.setKeyframe('test', value=-0.1, attribute='rotatePivotY', t=1) MayaCmds.setKeyframe('test', value=1, attribute='rotatePivotZ', t=1) MayaCmds.setKeyframe('test', value=0.8, attribute='rotatePivotX', t=2) MayaCmds.setKeyframe('test', value=1.5, attribute='rotatePivotY', t=2) MayaCmds.setKeyframe('test', value=-1, attribute='rotatePivotZ', t=2) # scale pivot MayaCmds.setKeyframe('test', value=1.2, attribute='scalePivotX', t=1) MayaCmds.setKeyframe('test', value=1.0, attribute='scalePivotY', t=1) MayaCmds.setKeyframe('test', value=1.2, attribute='scalePivotZ', t=1) MayaCmds.setKeyframe('test', value=1.4, attribute='scalePivotX', t=2) MayaCmds.setKeyframe('test', value=1.5, attribute='scalePivotY', t=2) MayaCmds.setKeyframe('test', value=1.5, attribute='scalePivotZ', t=2) self.__files.append(util.expandFileName('testTransOpInterpolation.abc')) MayaCmds.AbcExport(j='-fr 1 2 -root %s -f %s' % (nodeName, self.__files[-1])) MayaCmds.AbcImport(self.__files[-1], mode='open') MayaCmds.currentTime(1.004, update=True) # should read the content of frame #1 self.failUnlessAlmostEqual(0.006, MayaCmds.getAttr('test.shearXY')) self.failUnlessAlmostEqual(0.02, MayaCmds.getAttr('test.shearYZ')) self.failUnlessAlmostEqual(0.01, MayaCmds.getAttr('test.shearXZ')) self.failUnlessAlmostEqual(0.006, MayaCmds.getAttr('test.translateX')) self.failUnlessAlmostEqual(0.02, MayaCmds.getAttr('test.translateY')) self.failUnlessAlmostEqual(0.01, MayaCmds.getAttr('test.translateZ')) self.failUnlessAlmostEqual(0.096, MayaCmds.getAttr('test.rotateX')) self.failUnlessAlmostEqual(0.212, MayaCmds.getAttr('test.rotateY')) self.failUnlessAlmostEqual(0.36, MayaCmds.getAttr('test.rotateZ')) self.failUnlessAlmostEqual(1.0008, MayaCmds.getAttr('test.scaleX')) self.failUnlessAlmostEqual(1.002, MayaCmds.getAttr('test.scaleY')) self.failUnlessAlmostEqual(1.002, MayaCmds.getAttr('test.scaleZ')) self.failUnlessAlmostEqual(0.5012, MayaCmds.getAttr('test.rotatePivotX')) self.failUnlessAlmostEqual(-0.0936, MayaCmds.getAttr('test.rotatePivotY')) self.failUnlessAlmostEqual(0.992, MayaCmds.getAttr('test.rotatePivotZ')) self.failUnlessAlmostEqual(1.2008, MayaCmds.getAttr('test.scalePivotX')) self.failUnlessAlmostEqual(1.002, MayaCmds.getAttr('test.scalePivotY')) self.failUnlessAlmostEqual(1.2012, MayaCmds.getAttr('test.scalePivotZ')) setTime = MayaCmds.currentTime(1.422, update=True) alpha = (setTime - 1) / (2 - 1) # should interpolate the content of frame #3 and frame #4 self.failUnlessAlmostEqual(MayaCmds.getAttr('test.shearXY'), (1-alpha)*0+alpha*1.5) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.shearYZ'), (1-alpha)*0+alpha*5.0) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.shearXZ'), (1-alpha)*0+alpha*2.5) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.translateX'), (1-alpha)*0+alpha*1.5) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.translateY'), (1-alpha)*0+alpha*5.0) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.translateZ'), (1-alpha)*0+alpha*2.5) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.rotateX'), (1-alpha)*0+alpha*24) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.rotateY'), (1-alpha)*0+alpha*53) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.rotateZ'), (1-alpha)*0+alpha*90) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.scaleX'), (1-alpha)*1+alpha*1.2) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.scaleY'), (1-alpha)*1+alpha*1.5) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.scaleZ'), (1-alpha)*1+alpha*1.5) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.rotatePivotX'), (1-alpha)*0.5+alpha*0.8) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.rotatePivotY'), (1-alpha)*(-0.1)+alpha*1.5) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.rotatePivotZ'), (1-alpha)*1.0+alpha*(-1.0)) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.scalePivotX'), (1-alpha)*1.2+alpha*1.4) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.scalePivotY'), (1-alpha)*1.0+alpha*1.5) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.scalePivotZ'), (1-alpha)*1.2+alpha*1.5) def testCamera(self): # create an animated camera and write out name = MayaCmds.camera() MayaCmds.setAttr(name[1]+'.horizontalFilmAperture', 0.962) MayaCmds.setAttr(name[1]+'.verticalFilmAperture', 0.731) MayaCmds.setAttr(name[1]+'.focalLength', 50) MayaCmds.setAttr(name[1]+'.focusDistance', 5) MayaCmds.setAttr(name[1]+'.shutterAngle', 144) # animate the camera MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe(name[1], attribute='horizontalFilmAperture') MayaCmds.setKeyframe(name[1], attribute='focalLength') MayaCmds.setKeyframe(name[1], attribute='focusDistance') MayaCmds.setKeyframe(name[1], attribute='shutterAngle') MayaCmds.currentTime(6, update=True) MayaCmds.setKeyframe(name[1], attribute='horizontalFilmAperture', value=0.95) MayaCmds.setKeyframe(name[1], attribute='focalLength', value=40) MayaCmds.setKeyframe(name[1], attribute='focusDistance', value=5.4) MayaCmds.setKeyframe(name[1], attribute='shutterAngle', value=174.94) self.__files.append(util.expandFileName('testCameraInterpolation.abc')) MayaCmds.AbcExport(j='-fr 1 6 -root %s -f %s' % (name[0], self.__files[-1])) MayaCmds.AbcImport(self.__files[-1], mode='import') camList = MayaCmds.ls(type='camera') t = 1.004 MayaCmds.currentTime(t, update=True) self.failUnlessAlmostEqual(MayaCmds.getAttr(camList[0]+'.horizontalFilmAperture'), 0.962, 3) setTime = MayaCmds.currentTime(1.422, update=True) alpha = (setTime - 1) / (2 - 1) if not util.compareCamera(camList[0], camList[1]): self.fail('%s and %s are not the same at frame %d' % (camList[0], camList[1], t)) def testProp(self): trans = MayaCmds.createNode("transform") # create animated props MayaCmds.select(trans) MayaCmds.addAttr(longName='SPT_int8', dv=0, attributeType='byte', keyable=True) MayaCmds.addAttr(longName='SPT_int16', dv=0, attributeType='short', keyable=True) MayaCmds.addAttr(longName='SPT_int32', dv=0, attributeType='long', keyable=True) MayaCmds.addAttr(longName='SPT_float', dv=0, attributeType='float', keyable=True) MayaCmds.addAttr(longName='SPT_double', dv=0, attributeType='double', keyable=True) MayaCmds.setKeyframe(trans, value=0, attribute='SPT_int8', t=1) MayaCmds.setKeyframe(trans, value=100, attribute='SPT_int16', t=1) MayaCmds.setKeyframe(trans, value=1000, attribute='SPT_int32', t=1) MayaCmds.setKeyframe(trans, value=0.57777777, attribute='SPT_float', t=1) MayaCmds.setKeyframe(trans, value=5.045643545457, attribute='SPT_double', t=1) MayaCmds.setKeyframe(trans, value=8, attribute='SPT_int8', t=2) MayaCmds.setKeyframe(trans, value=16, attribute='SPT_int16', t=2) MayaCmds.setKeyframe(trans, value=32, attribute='SPT_int32', t=2) MayaCmds.setKeyframe(trans, value=3.141592654, attribute='SPT_float', t=2) MayaCmds.setKeyframe(trans, value=3.141592654, attribute='SPT_double', t=2) self.__files.append(util.expandFileName('testPropInterpolation.abc')) MayaCmds.AbcExport(j='-fr 1 2 -atp SPT_ -root %s -f %s' % (trans, self.__files[-1])) MayaCmds.AbcImport(self.__files[-1], mode='open') t = 1.004 MayaCmds.currentTime(t, update=True) self.failUnlessEqual(MayaCmds.getAttr(trans+'.SPT_int8'), 0) self.failUnlessEqual(MayaCmds.getAttr(trans+'.SPT_int16'), 99) self.failUnlessEqual(MayaCmds.getAttr(trans+'.SPT_int32'), 996) self.failUnlessAlmostEqual(MayaCmds.getAttr(trans+'.SPT_float'), 0.5880330295359999, 7) self.failUnlessAlmostEqual(MayaCmds.getAttr(trans+'.SPT_double'), 5.038027341891171, 7) setTime = MayaCmds.currentTime(1.422, update=True) alpha = (setTime - 1) / (2 - 1) self.failUnlessAlmostEqual(MayaCmds.getAttr(trans+'.SPT_int8'), (1-alpha)*0+alpha*8, -1) self.failUnlessAlmostEqual(MayaCmds.getAttr(trans+'.SPT_int16'), (1-alpha)*100+alpha*16, -1) self.failUnlessAlmostEqual(MayaCmds.getAttr(trans+'.SPT_int32'), (1-alpha)*1000+alpha*32, -1) self.failUnlessAlmostEqual(MayaCmds.getAttr(trans+'.SPT_float'), (1-alpha)*0.57777777+alpha*3.141592654, 6) self.failUnlessAlmostEqual(MayaCmds.getAttr(trans+'.SPT_double'), (1-alpha)* 5.045643545457+alpha*3.141592654, 6)
Python
#!/usr/bin/env mayapy ##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** # run this via mayapy # runs the test suite import glob import os import sys import time import unittest import maya.standalone maya.standalone.initialize(name='python') from maya import cmds as MayaCmds from maya.mel import eval as MelEval usage = """ Usage: mayapy RunTests.py AbcExport AbcImport AbcStitcher [tests.py] Where: AbcExport is the location of the AbcExport Maya plugin to load. AbcImport is the location of the AbcImport Maya plugin to load. AbcStitcher is the location of the AbcStitcher command to use. If no specific python tests are specified, all python files named *_test.py in the same directory as this file are used. """ if len(sys.argv) < 4: raise RuntimeError(usage) MayaCmds.loadPlugin(sys.argv[1]) print 'LOADED', sys.argv[1] MayaCmds.loadPlugin(sys.argv[2]) print 'LOADED', sys.argv[2] if not os.path.exists(sys.argv[3]): raise RuntimeError (sys.argv[3] + ' does not exist') else: os.environ['AbcStitcher'] = sys.argv[3] suite = unittest.TestSuite() main_dir = os.path.dirname(os.path.abspath(__file__)) os.chdir( main_dir ) MelEval('chdir "%s"' % main_dir ) # For now, hack the path (so the import below works) sys.path.append("..") # Load all the tests specified by the command line or *_test.py testFiles = sys.argv[4:] if not testFiles: testFiles = glob.glob('*_test.py') for file in testFiles: name = os.path.splitext(file)[0] __import__(name) test = unittest.defaultTestLoader.loadTestsFromName(name) suite.addTest(test) # Run the tests runner = unittest.TextTestRunner(verbosity=2) runner.run(suite)
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import unittest import util class TransformTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files : os.remove(f) def testStaticTransformReadWrite(self): nodeName = MayaCmds.polyCube(n='cube') MayaCmds.setAttr('cube.translate', 2.456, -3.95443, 0, type="double3") MayaCmds.setAttr('cube.rotate', 45, 15, -90, type="double3") MayaCmds.setAttr('cube.rotateOrder', 4) MayaCmds.setAttr('cube.scale', 1.5, 5, 1, type="double3") MayaCmds.setAttr('cube.shearXY',1) MayaCmds.setAttr('cube.rotatePivot', 13.52, 0.0, 20.25, type="double3") MayaCmds.setAttr('cube.rotatePivotTranslate', 0.5, 0.0, 0.25, type="double3") MayaCmds.setAttr('cube.scalePivot', 10.7, 2.612, 0.2, type="double3") MayaCmds.setAttr('cube.scalePivotTranslate', 0.0, 0.0, 0.25, type="double3") MayaCmds.setAttr('cube.inheritsTransform', 0) self.__files.append(util.expandFileName('testStaticTransformReadWrite.abc')) MayaCmds.AbcExport(j='-root %s -file %s' % (nodeName[0], self.__files[-1])) # reading test MayaCmds.AbcImport(self.__files[-1], mode='open') self.failUnlessAlmostEqual(2.456, MayaCmds.getAttr('cube.translateX'), 4) self.failUnlessAlmostEqual(-3.95443, MayaCmds.getAttr('cube.translateY'), 4) self.failUnlessAlmostEqual(0.0, MayaCmds.getAttr('cube.translateZ'), 4) self.failUnlessAlmostEqual(45, MayaCmds.getAttr('cube.rotateX'), 4) self.failUnlessAlmostEqual(15, MayaCmds.getAttr('cube.rotateY'), 4) self.failUnlessAlmostEqual(-90, MayaCmds.getAttr('cube.rotateZ'), 4) self.failUnlessEqual(4, MayaCmds.getAttr('cube.rotateOrder')) self.failUnlessAlmostEqual(1.5, MayaCmds.getAttr('cube.scaleX'), 4) self.failUnlessAlmostEqual(5, MayaCmds.getAttr('cube.scaleY'), 4) self.failUnlessAlmostEqual(1, MayaCmds.getAttr('cube.scaleZ'), 4) self.failUnlessAlmostEqual(1, MayaCmds.getAttr('cube.shearXY'), 4) self.failUnlessAlmostEqual(13.52, MayaCmds.getAttr('cube.rotatePivotX'), 4) self.failUnlessAlmostEqual(0.0, MayaCmds.getAttr('cube.rotatePivotY'), 4) self.failUnlessAlmostEqual(20.25, MayaCmds.getAttr('cube.rotatePivotZ'), 4) self.failUnlessAlmostEqual(0.5, MayaCmds.getAttr('cube.rotatePivotTranslateX'), 4) self.failUnlessAlmostEqual(0.0, MayaCmds.getAttr('cube.rotatePivotTranslateY'), 4) self.failUnlessAlmostEqual(0.25, MayaCmds.getAttr('cube.rotatePivotTranslateZ'), 4) self.failUnlessAlmostEqual(10.7, MayaCmds.getAttr('cube.scalePivotX'), 4) self.failUnlessAlmostEqual(2.612, MayaCmds.getAttr('cube.scalePivotY'), 4) self.failUnlessAlmostEqual(0.2, MayaCmds.getAttr('cube.scalePivotZ'), 4) self.failUnlessAlmostEqual(0.0, MayaCmds.getAttr('cube.scalePivotTranslateX'), 4) self.failUnlessAlmostEqual(0.0, MayaCmds.getAttr('cube.scalePivotTranslateY'), 4) self.failUnlessAlmostEqual(0.25, MayaCmds.getAttr('cube.scalePivotTranslateZ'), 4) self.failUnlessEqual(0, MayaCmds.getAttr('cube.inheritsTransform')) def testStaticTransformRotateOrder(self): nodeName = MayaCmds.polyCube(n='cube') MayaCmds.setAttr('cube.rotate', 45, 1, -90, type="double3") MayaCmds.setAttr('cube.rotateOrder', 5) self.__files.append(util.expandFileName('testStaticTransformRotateOrder.abc')) MayaCmds.AbcExport(j='-root %s -file %s' % (nodeName[0], self.__files[-1])) MayaCmds.AbcImport(self.__files[-1], mode='open') self.failUnlessEqual(5, MayaCmds.getAttr('cube.rotateOrder')) self.failUnlessAlmostEqual(45, MayaCmds.getAttr('cube.rotateX'), 4) self.failUnlessAlmostEqual(1, MayaCmds.getAttr('cube.rotateY'), 4) self.failUnlessAlmostEqual(-90, MayaCmds.getAttr('cube.rotateZ'), 4) def testStaticTransformRotateOrder2(self): nodeName = MayaCmds.polyCube(n='cube') MayaCmds.setAttr('cube.rotate', 45, 0, -90, type="double3") MayaCmds.setAttr('cube.rotateOrder', 5) self.__files.append(util.expandFileName('testStaticTransformRotateOrder2.abc')) MayaCmds.AbcExport(j='-root %s -file %s' % (nodeName[0], self.__files[-1])) MayaCmds.AbcImport(self.__files[-1], mode='open') self.failUnlessEqual(5, MayaCmds.getAttr('cube.rotateOrder')) self.failUnlessAlmostEqual(45, MayaCmds.getAttr('cube.rotateX'), 4) self.failUnlessAlmostEqual(0, MayaCmds.getAttr('cube.rotateY'), 4) self.failUnlessAlmostEqual(-90, MayaCmds.getAttr('cube.rotateZ'), 4)
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import subprocess import unittest import util class AnimNurbsCurveTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__abcStitcher = [os.environ['AbcStitcher']] self.__files = [] def tearDown(self): for f in self.__files: os.remove(f) # a test for animated non-curve group Nurbs Curve def testAnimSimpleNurbsCurveRW(self): # create the Nurbs Curve name = MayaCmds.curve( d=3, p=[(0, 0, 0), (3, 5, 6), (5, 6, 7), (9, 9, 9), (12, 10, 2)], k=[0,0,0,1,2,2,2] ) MayaCmds.select(name+'.cv[0:4]') # frame 1 MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe() # frame 24 MayaCmds.currentTime(24, update=True) MayaCmds.setKeyframe() # frame 12 MayaCmds.currentTime(12, update=True) MayaCmds.move(3, 0, 0, r=True) MayaCmds.setKeyframe() self.__files.append(util.expandFileName('testAnimNurbsSingleCurve.abc')) self.__files.append(util.expandFileName('testAnimNurbsSingleCurve01_14.abc')) self.__files.append(util.expandFileName('testAnimNurbsSingleCurve15_24.abc')) MayaCmds.AbcExport(j='-fr 1 14 -root %s -file %s' % (name, self.__files[-2])) MayaCmds.AbcExport(j='-fr 15 24 -root %s -file %s' % (name, self.__files[-1])) # use AbcStitcher to combine two files into one subprocess.call(self.__abcStitcher + self.__files[-3:]) MayaCmds.AbcImport(self.__files[-3], mode='import') shapeNames = MayaCmds.ls(exactType='nurbsCurve') MayaCmds.currentTime(1, update=True) util.compareNurbsCurve(shapeNames[0], shapeNames[1]) MayaCmds.currentTime(12, update=True) util.compareNurbsCurve(shapeNames[0], shapeNames[1]) MayaCmds.currentTime(24, update=True) util.compareNurbsCurve(shapeNames[0], shapeNames[1]) def testAnimNurbsCurveGrpRW(self): # create Nurbs Curve group knotVec = [0,0,0,1,2,2,2] curve1CV = [(0, 0, 0), (3, 5, 0), (5, 6, 0), (9, 9, 0), (12, 10, 0)] curve2CV = [(0, 0, 3), (3, 5, 3), (5, 6, 3), (9, 9, 3), (12, 10, 3)] curve3CV = [(0, 0, 6), (3, 5, 6), (5, 6, 6), (9, 9, 6), (12, 10, 6)] MayaCmds.curve(d=3, p=curve1CV, k=knotVec, name='curve1') MayaCmds.curve(d=3, p=curve2CV, k=knotVec, name='curve2') MayaCmds.curve(d=3, p=curve3CV, k=knotVec, name='curve3') MayaCmds.group('curve1', 'curve2', 'curve3', name='group') MayaCmds.addAttr('group', longName='riCurves', at='bool', dv=True) # frame 1 MayaCmds.currentTime(1, update=True) MayaCmds.select('curve1.cv[0:4]', 'curve2.cv[0:4]', 'curve3.cv[0:4]', replace=True) MayaCmds.setKeyframe() # frame 24 MayaCmds.currentTime(24, update=True) MayaCmds.select('curve1.cv[0:4]') MayaCmds.rotate(0.0, '90deg', 0.0, relative=True ) MayaCmds.select('curve2.cv[0:4]') MayaCmds.move(0.0, 0.5, 0.0, relative=True ) MayaCmds.select('curve3.cv[0:4]') MayaCmds.scale(1.0, 0.5, 1.0, relative=True ) MayaCmds.select('curve1.cv[0:4]', 'curve2.cv[0:4]', 'curve3.cv[0:4]', replace=True) MayaCmds.setKeyframe() self.__files.append(util.expandFileName('testAnimNCGrp.abc')) self.__files.append(util.expandFileName('testAnimNCGrp01_14.abc')) self.__files.append(util.expandFileName('testAnimNCGrp15_24.abc')) MayaCmds.AbcExport(j='-fr 1 14 -root %s -file %s' % ('group', self.__files[-2])) MayaCmds.AbcExport(j='-fr 15 24 -root %s -file %s' % ('group', self.__files[-1])) # use AbcStitcher to combine two files into one subprocess.call(self.__abcStitcher + self.__files[-3:]) # reading test MayaCmds.AbcImport(self.__files[-3], mode='import') shapeNames = MayaCmds.ls(exactType='nurbsCurve') MayaCmds.currentTime(1, update=True) for i in range(0, 3): util.compareNurbsCurve(shapeNames[i], shapeNames[i+3]) MayaCmds.currentTime(12, update=True) for i in range(0, 3): util.compareNurbsCurve(shapeNames[i], shapeNames[i+3]) MayaCmds.currentTime(24, update=True) for i in range(0, 3): util.compareNurbsCurve(shapeNames[i], shapeNames[i+3])
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds from maya.mel import eval as MelEval import os import maya.OpenMaya as OpenMaya import unittest import util class StaticMeshTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files : os.remove(f) def testStaticMeshReadWrite(self): numFaces = 6 numVertices = 8 numFaceConnects = 24 vtx_1 = OpenMaya.MFloatPoint(-0.5, -0.5, -0.5) vtx_2 = OpenMaya.MFloatPoint( 0.5, -0.5, -0.5) vtx_3 = OpenMaya.MFloatPoint( 0.5, -0.5, 0.5) vtx_4 = OpenMaya.MFloatPoint(-0.5, -0.5, 0.5) vtx_5 = OpenMaya.MFloatPoint(-0.5, 0.5, -0.5) vtx_6 = OpenMaya.MFloatPoint(-0.5, 0.5, 0.5) vtx_7 = OpenMaya.MFloatPoint( 0.5, 0.5, 0.5) vtx_8 = OpenMaya.MFloatPoint( 0.5, 0.5, -0.5) points = OpenMaya.MFloatPointArray() points.setLength(8) points.set(vtx_1, 0) points.set(vtx_2, 1) points.set(vtx_3, 2) points.set(vtx_4, 3) points.set(vtx_5, 4) points.set(vtx_6, 5) points.set(vtx_7, 6) points.set(vtx_8, 7) faceConnects = OpenMaya.MIntArray() faceConnects.setLength(numFaceConnects) faceConnects.set(0, 0) faceConnects.set(1, 1) faceConnects.set(2, 2) faceConnects.set(3, 3) faceConnects.set(4, 4) faceConnects.set(5, 5) faceConnects.set(6, 6) faceConnects.set(7, 7) faceConnects.set(3, 8) faceConnects.set(2, 9) faceConnects.set(6, 10) faceConnects.set(5, 11) faceConnects.set(0, 12) faceConnects.set(3, 13) faceConnects.set(5, 14) faceConnects.set(4, 15) faceConnects.set(0, 16) faceConnects.set(4, 17) faceConnects.set(7, 18) faceConnects.set(1, 19) faceConnects.set(1, 20) faceConnects.set(7, 21) faceConnects.set(6, 22) faceConnects.set(2, 23) faceCounts = OpenMaya.MIntArray() faceCounts.setLength(6) faceCounts.set(4, 0) faceCounts.set(4, 1) faceCounts.set(4, 2) faceCounts.set(4, 3) faceCounts.set(4, 4) faceCounts.set(4, 5) transFn = OpenMaya.MFnTransform() parent = transFn.create() transFn.setName('mesh') meshFn = OpenMaya.MFnMesh() meshFn.create(numVertices, numFaces, points, faceCounts, faceConnects, parent) meshFn.setName("meshShape"); self.__files.append(util.expandFileName('testStaticMeshReadWrite.abc')) MayaCmds.AbcExport(j='-root mesh -file ' + self.__files[-1]) MayaCmds.AbcImport(self.__files[-1], mode='open') sList = OpenMaya.MSelectionList() sList.add('meshShape') meshObj = OpenMaya.MObject() sList.getDependNode(0, meshObj) meshFn = OpenMaya.MFnMesh(meshObj) # check the point list meshPoints = OpenMaya.MFloatPointArray() meshFn.getPoints(meshPoints); self.failUnlessEqual(vtx_1, meshPoints[0]) self.failUnlessEqual(vtx_2, meshPoints[1]) self.failUnlessEqual(vtx_3, meshPoints[2]) self.failUnlessEqual(vtx_4, meshPoints[3]) self.failUnlessEqual(vtx_5, meshPoints[4]) self.failUnlessEqual(vtx_6, meshPoints[5]) self.failUnlessEqual(vtx_7, meshPoints[6]) self.failUnlessEqual(vtx_8, meshPoints[7]) # check the polygonvertices list vertexList = OpenMaya.MIntArray() faceConnects = OpenMaya.MIntArray() faceConnects.setLength(4) faceConnects.set(0, 0) faceConnects.set(1, 1) faceConnects.set(2, 2) faceConnects.set(3, 3) meshFn.getPolygonVertices(0, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(4, 0) faceConnects.set(5, 1) faceConnects.set(6, 2) faceConnects.set(7, 3) meshFn.getPolygonVertices(1, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(3, 0) faceConnects.set(2, 1) faceConnects.set(6, 2) faceConnects.set(5, 3) meshFn.getPolygonVertices(2, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(0, 0) faceConnects.set(3, 1) faceConnects.set(5, 2) faceConnects.set(4, 3) meshFn.getPolygonVertices(3, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(0, 0) faceConnects.set(4, 1) faceConnects.set(7, 2) faceConnects.set(1, 3) meshFn.getPolygonVertices(4, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(1, 0) faceConnects.set(7, 1) faceConnects.set(6, 2) faceConnects.set(2, 3) meshFn.getPolygonVertices(5, vertexList) self.failUnlessEqual(faceConnects, vertexList)
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import unittest import util class VisibilityTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files : os.remove(f) def testStaticVisibility(self): poly1 = MayaCmds.polyPlane(sx=2, sy=2, w=1, h=1, ch=0)[0] group1 = MayaCmds.group() group2 = MayaCmds.createNode("transform") MayaCmds.select(group1, group2) group3 = MayaCmds.group() group4 = (MayaCmds.duplicate(group1, rr=1))[0] group5 = MayaCmds.group() MayaCmds.select(group3, group5) root = MayaCmds.group(name='root') MayaCmds.setAttr(group1 + '.visibility', 0) MayaCmds.setAttr(group2 + '.visibility', 0) MayaCmds.setAttr(group5 + '.visibility', 0) self.__files.append(util.expandFileName('staticVisibilityTest.abc')) MayaCmds.AbcExport(j='-wv -root %s -file %s' % (root, self.__files[-1])) MayaCmds.AbcImport(self.__files[-1], m='open') self.failIf(MayaCmds.getAttr(group1+'.visibility')) self.failIf(MayaCmds.getAttr(group2+'.visibility')) self.failIf(MayaCmds.getAttr(group5+'.visibility')) self.failUnless(MayaCmds.getAttr(group1+'|'+poly1+'.visibility')) self.failUnless(MayaCmds.getAttr(group4+'|'+poly1+'.visibility')) self.failUnless(MayaCmds.getAttr(group3+'.visibility')) self.failUnless(MayaCmds.getAttr(group4+'.visibility')) self.failUnless(MayaCmds.getAttr(root+'.visibility')) def testAnimVisibility(self): poly1 = MayaCmds.polyPlane( sx=2, sy=2, w=1, h=1, ch=0)[0] group1 = MayaCmds.group() group2 = MayaCmds.createNode("transform") MayaCmds.select(group1, group2) group3 = MayaCmds.group() group4 = (MayaCmds.duplicate(group1, rr=1))[0] group5 = MayaCmds.group() MayaCmds.select(group3, group5) root = MayaCmds.group(name='root') MayaCmds.setKeyframe(group1 + '.visibility', v=0, t=[1, 4]) MayaCmds.setKeyframe(group2 + '.visibility', v=0, t=[1, 4]) MayaCmds.setKeyframe(group5 + '.visibility', v=0, t=[1, 4]) MayaCmds.setKeyframe(group1 + '.visibility', v=1, t=2) MayaCmds.setKeyframe(group2 + '.visibility', v=1, t=2) MayaCmds.setKeyframe(group5 + '.visibility', v=1, t=2) self.__files.append(util.expandFileName('animVisibilityTest.abc')) MayaCmds.AbcExport(j='-wv -fr 1 4 -root %s -file %s' % (root, self.__files[-1])) MayaCmds.AbcImport(self.__files[-1], mode='open') MayaCmds.currentTime(1, update = True) self.failIf(MayaCmds.getAttr(group1 + '.visibility')) self.failIf(MayaCmds.getAttr(group2 + '.visibility')) self.failIf(MayaCmds.getAttr(group5 + '.visibility')) self.failUnless(MayaCmds.getAttr(group1 + '|' + poly1 + '.visibility')) self.failUnless(MayaCmds.getAttr(group4 + '|' + poly1 + '.visibility')) self.failUnless(MayaCmds.getAttr(group3 + '.visibility')) self.failUnless(MayaCmds.getAttr(group4 + '.visibility')) self.failUnless(MayaCmds.getAttr(root+'.visibility')) MayaCmds.currentTime(2, update = True) self.failUnless(MayaCmds.getAttr(group1 + '.visibility')) self.failUnless(MayaCmds.getAttr(group2 + '.visibility')) self.failUnless(MayaCmds.getAttr(group5 + '.visibility')) self.failUnless(MayaCmds.getAttr(group1 + '|' + poly1 + '.visibility')) self.failUnless(MayaCmds.getAttr(group4 + '|' + poly1 + '.visibility')) self.failUnless(MayaCmds.getAttr(group3 + '.visibility')) self.failUnless(MayaCmds.getAttr(group4 + '.visibility')) self.failUnless(MayaCmds.getAttr(root + '.visibility')) MayaCmds.currentTime(4, update = True ) self.failIf(MayaCmds.getAttr(group1 + '.visibility')) self.failIf(MayaCmds.getAttr(group2 + '.visibility')) self.failIf(MayaCmds.getAttr(group5 + '.visibility')) self.failUnless(MayaCmds.getAttr(group1 + '|' + poly1 + '.visibility')) self.failUnless(MayaCmds.getAttr(group4 + '|' + poly1 + '.visibility')) self.failUnless(MayaCmds.getAttr(group3 + '.visibility')) self.failUnless(MayaCmds.getAttr(group4 + '.visibility')) self.failUnless(MayaCmds.getAttr(root+'.visibility'))
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import unittest import util def testNurbsCurveRW( self, isGroup, abcFileName, inText): MayaCmds.file(new=True, force=True) name = MayaCmds.textCurves( font='Courier', text=inText ) if isGroup == True : MayaCmds.addAttr(name[0], longName='riCurves', at='bool', dv=True) shapeNames = MayaCmds.ls(type='nurbsCurve') miscinfo=[] cv=[] knot=[] curveInfoNode = MayaCmds.createNode('curveInfo') for i in range(0, len(shapeNames)) : shapeName = shapeNames[i] MayaCmds.connectAttr(shapeName+'.worldSpace', curveInfoNode+'.inputCurve', force=True) controlPoints = MayaCmds.getAttr(curveInfoNode + '.controlPoints[*]') cv.append(controlPoints) numCV = len(controlPoints) spans = MayaCmds.getAttr(shapeName+'.spans') degree = MayaCmds.getAttr(shapeName+'.degree') form = MayaCmds.getAttr(shapeName+'.form') minVal = MayaCmds.getAttr(shapeName+'.minValue') maxVal = MayaCmds.getAttr(shapeName+'.maxValue') misc = [numCV, spans, degree, form, minVal, maxVal] miscinfo.append(misc) knots = MayaCmds.getAttr(curveInfoNode + '.knots[*]') knot.append(knots) MayaCmds.AbcExport(j='-root %s -f %s' % (name[0], abcFileName)) # reading test MayaCmds.AbcImport(abcFileName, mode='open') if isGroup == True: shapeNames = MayaCmds.ls(exactType='nurbsCurve') self.failUnless(MayaCmds.getAttr(name[0]+'.riCurves')) miscinfo2 = [] cv2 = [] knot2 = [] curveInfoNode = MayaCmds.createNode('curveInfo') for i in range(0, len(shapeNames)): name = shapeNames[i] MayaCmds.connectAttr(name+'.worldSpace', curveInfoNode+'.inputCurve', force=True) controlPoints = MayaCmds.getAttr(curveInfoNode + '.controlPoints[*]') cv2.append(controlPoints) numCV = len(controlPoints) spans = MayaCmds.getAttr(name+'.spans') degree = MayaCmds.getAttr(name+'.degree') form = MayaCmds.getAttr(name+'.form') minVal = MayaCmds.getAttr(name+'.minValue') maxVal = MayaCmds.getAttr(name+'.maxValue') misc = [numCV, spans, degree, form, minVal, maxVal] miscinfo2.append(misc) knots = MayaCmds.getAttr(curveInfoNode + '.knots[*]') knot2.append(knots) for i in range(0, len(shapeNames)) : name = shapeNames[i] self.failUnlessEqual(len(cv[i]), len(cv2[i])) for j in range(0, len(cv[i])) : cp1 = cv[i][j] cp2 = cv2[i][j] self.failUnlessAlmostEqual(cp1[0], cp2[0], 3, 'curve[%d].cp[%d].x not equal' % (i,j)) self.failUnlessAlmostEqual(cp1[1], cp2[1], 3, 'curve[%d].cp[%d].y not equal' % (i,j)) self.failUnlessAlmostEqual(cp1[2], cp2[2], 3, 'curve[%d].cp[%d].z not equal' % (i,j)) class StaticNurbsCurveTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files: os.remove(f) def testNurbsSingleCurveReadWrite(self): name = MayaCmds.curve(d=3, p=[(0, 0, 0), (3, 5, 6), (5, 6, 7), (9, 9, 9), (12, 10, 2)], k=[0,0,0,1,2,2,2]) self.__files.append(util.expandFileName('testStaticNurbsSingleCurve.abc')) MayaCmds.AbcExport(j='-root %s -f %s' % (name, self.__files[-1])) # reading test MayaCmds.AbcImport(self.__files[-1], mode='import') shapeNames = MayaCmds.ls(exactType='nurbsCurve') util.compareNurbsCurve(shapeNames[0], shapeNames[1]) def testNurbsCurveGrpReadWrite(self): # test w/r of simple Nurbs Curve self.__files.append(util.expandFileName('testStaticNurbsCurves.abc')) testNurbsCurveRW(self, False, self.__files[-1], 'haka') self.__files.append(util.expandFileName('testStaticNurbsCurveGrp.abc')) testNurbsCurveRW(self, True, self.__files[-1], 'haka') # test if some curves have different degree or close states information MayaCmds.file(new=True, force=True) name = MayaCmds.textCurves(font='Courier', text='Maya') MayaCmds.addAttr(name[0], longName='riCurves', at='bool', dv=True) self.__files.append(util.expandFileName('testStaticNurbsCurveGrp2.abc')) MayaCmds.AbcExport(j='-root %s -f %s' % (name[0], self.__files[-1])) MayaCmds.AbcImport(self.__files[-1], mode='open') if 'riCurves' in MayaCmds.listAttr(name[0]): self.fail(name[0]+".riCurves shouldn't exist") def testNurbsSingleCurveWidthReadWrite(self): MayaCmds.file(new=True, force=True) # single curve with no width information MayaCmds.curve(d=3, p=[(0, 0, 0), (3, 5, 0), (5, 6, 0), (9, 9, 0), (12, 10, 0)], k=[0,0,0,1,2,2,2], name='curve1') # single curve with constant width information MayaCmds.curve(d=3, p=[(0, 0, 3), (3, 5, 3), (5, 6, 3), (9, 9, 3), (12, 10, 3)], k=[0,0,0,1,2,2,2], name='curve2') MayaCmds.select('curveShape2') MayaCmds.addAttr(longName='width', attributeType='double', dv=0.75) # single open curve with width information MayaCmds.curve(d=3, p=[(0, 0, 6), (3, 5, 6), (5, 6, 6), (9, 9, 6), (12, 10, 6)], k=[0,0,0,1,2,2,2], name='curve3') MayaCmds.select('curveShape3') MayaCmds.addAttr(longName='width', dataType='doubleArray') MayaCmds.setAttr('curveShape3.width', [0.2, 0.4, 0.6, 0.8, 1.0], type='doubleArray') # single open curve with wrong width information MayaCmds.curve(d=3, p=[(0, 0, 9), (3, 5, 9), (5, 6, 9), (9, 9, 9), (12, 10, 9)], k=[0,0,0,1,2,2,2], name='curve4') MayaCmds.select('curveShape4') MayaCmds.addAttr(longName='width', dataType='doubleArray') MayaCmds.setAttr('curveShape4.width', [0.12, 1.4, 0.37], type='doubleArray') # single curve circle with width information MayaCmds.circle(ch=False, name='curve5') MayaCmds.select('curve5Shape') MayaCmds.addAttr(longName='width', dataType='doubleArray') MayaCmds.setAttr('curve5Shape.width', [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1], type='doubleArray') # single curve circle with wrong width information MayaCmds.circle(ch=False, name='curve6') MayaCmds.select('curve6Shape') MayaCmds.addAttr(longName='width', dataType='doubleArray') MayaCmds.setAttr('curve6Shape.width', [0.12, 1.4, 0.37], type='doubleArray') self.__files.append(util.expandFileName('testStaticNurbsCurveWidthTest.abc')) MayaCmds.AbcExport(j='-root curve1 -root curve2 -root curve3 -root curve4 -root curve5 -root curve6 -f ' + self.__files[-1]) MayaCmds.AbcImport(self.__files[-1], mode='open') # check the width # curve 1 self.failUnless('width' in MayaCmds.listAttr('curveShape1')) self.failUnlessAlmostEqual( MayaCmds.getAttr('curveShape1.width'), 0.1, 4) # curve 2 self.failUnless('width' in MayaCmds.listAttr('curveShape2')) self.failUnlessAlmostEqual( MayaCmds.getAttr('curveShape2.width'), 0.75, 4) # curve 3 width = MayaCmds.getAttr('curveShape3.width') for i in range(5): self.failUnlessAlmostEqual(width[i], 0.2*i+0.2, 4) # curve 4 (bad width defaults to 0.1) self.failUnless('width' in MayaCmds.listAttr('curveShape4')) width = MayaCmds.getAttr('curveShape4.width') self.failUnlessAlmostEqual( MayaCmds.getAttr('curveShape4.width'), 0.1, 4) # curve 5 self.failUnlessEqual('width' in MayaCmds.listAttr('curve5Shape'), True) width = MayaCmds.getAttr('curve5Shape.width') for i in range(11): self.failUnlessAlmostEqual(width[i], 0.1*i+0.1, 4) # curve 6 (bad width defaults to 0.1) self.failUnless('width' in MayaCmds.listAttr('curve6Shape')) self.failUnlessAlmostEqual( MayaCmds.getAttr('curve6Shape.width'), 0.1, 4) def testNurbsCurveGrpWidthRW1(self): widthVecs = [[0.11, 0.12, 0.13, 0.14, 0.15], [0.1, 0.3, 0.5, 0.7, 0.9], [0.2, 0.3, 0.4, 0.5, 0.6]] MayaCmds.curve(d=3, p=[(0, 0, 0), (3, 5, 0), (5, 6, 0), (9, 9, 0), (12, 10, 0)], k=[0,0,0,1,2,2,2], name='curve1') MayaCmds.select('curveShape1') MayaCmds.addAttr(longName='width', dataType='doubleArray') MayaCmds.setAttr('curveShape1.width', widthVecs[0], type='doubleArray') MayaCmds.curve(d=3, p=[(0, 0, 3), (3, 5, 3), (5, 6, 3), (9, 9, 3), (12, 10, 3)], k=[0,0,0,1,2,2,2], name='curve2') MayaCmds.select('curveShape2') MayaCmds.addAttr(longName='width', dataType='doubleArray') MayaCmds.setAttr('curveShape2.width', widthVecs[1], type='doubleArray') MayaCmds.curve(d=3, p=[(0, 0, 6), (3, 5, 6), (5, 6, 6), (9, 9, 6), (12, 10, 6)], k=[0,0,0,1,2,2,2], name='curve3') MayaCmds.select('curveShape3') MayaCmds.addAttr(longName='width', dataType='doubleArray') MayaCmds.setAttr('curveShape3.width', widthVecs[2], type='doubleArray') MayaCmds.group('curve1', 'curve2', 'curve3', name='group') MayaCmds.addAttr('group', longName='riCurves', at='bool', dv=True) self.__files.append(util.expandFileName('testStaticNurbsCurveGrpWidthTest1.abc')) MayaCmds.AbcExport(j='-root group -file ' + self.__files[-1]) MayaCmds.AbcImport(self.__files[-1], mode='open') # width check for i in range(0,3): shapeName = '|group|group' if i > 0: shapeName = shapeName + str(i) self.failUnless('width' in MayaCmds.listAttr(shapeName)) width = MayaCmds.getAttr(shapeName + '.width') for j in range(len(widthVecs[i])): self.failUnlessAlmostEqual(width[j], widthVecs[i][j], 4) def testNurbsCurveGrpWidthRW2(self): MayaCmds.curve(d=3, p=[(0, 0, 0), (3, 5, 0), (5, 6, 0), (9, 9, 0), (12, 10, 0)], k=[0,0,0,1,2,2,2], name='curve1') MayaCmds.select('curveShape1') MayaCmds.curve(d=3, p=[(0, 0, 3), (3, 5, 3), (5, 6, 3), (9, 9, 3), (12, 10, 3)], k=[0,0,0,1,2,2,2], name='curve2') MayaCmds.curve(d=3, p=[(0, 0, 6), (3, 5, 6), (5, 6, 6), (9, 9, 6), (12, 10, 6)], k=[0,0,0,1,2,2,2], name='curve3') MayaCmds.select('curveShape3') MayaCmds.group('curve1', 'curve2', 'curve3', name='group') MayaCmds.addAttr('group', longName='riCurves', at='bool', dv=True) MayaCmds.addAttr('group', longName='width', attributeType='double', dv=0.75) self.__files.append(util.expandFileName('testStaticNurbsCurveGrpWidthTest2.abc')) MayaCmds.AbcExport(j='-root group -file ' + self.__files[-1]) MayaCmds.AbcImport(self.__files[-1], mode='open') # constant width check self.failUnless('width' in MayaCmds.listAttr('|group')) self.failUnlessAlmostEqual(MayaCmds.getAttr('|group.width'), 0.75, 4)
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import unittest import util def makeRobot(): MayaCmds.polyCube(name="head") MayaCmds.move(0, 4, 0, r=1) MayaCmds.polyCube(name="chest") MayaCmds.scale(2, 2.5, 1) MayaCmds.move(0, 2, 0, r=1) MayaCmds.polyCube(name="leftArm") MayaCmds.move(0, 3, 0, r=1) MayaCmds.scale(2, 0.5, 1, r=1) MayaCmds.duplicate(name="rightArm") MayaCmds.select("leftArm") MayaCmds.move(1.25, 0, 0, r=1) MayaCmds.rotate(0, 0, 32, r=1, os=1) MayaCmds.select("rightArm") MayaCmds.move(-1.25, 0, 0, r=1) MayaCmds.rotate(0, 0, -32, r=1, os=1) MayaCmds.select("rightArm", "leftArm", "chest", r=1) MayaCmds.group(name="body") MayaCmds.polyCube(name="bottom") MayaCmds.scale(2, 0.5, 1) MayaCmds.move(0, 0.5, 0, r=1) MayaCmds.polyCube(name="leftLeg") MayaCmds.scale(0.65, 2.8, 1, r=1) MayaCmds.move(-0.5, -1, 0, r=1) MayaCmds.duplicate(name="rightLeg") MayaCmds.move(1, 0, 0, r=1) MayaCmds.select("rightLeg", "leftLeg", "bottom", r=1) MayaCmds.group(name="lower") MayaCmds.select("head", "body", "lower", r=1) MayaCmds.group(name="robot") class selectionTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files: os.remove(f) def testSelectionFlag(self): makeRobot() MayaCmds.select('bottom', 'leftArm', 'head') self.__files.append(util.expandFileName('selectionTest_partial.abc')) MayaCmds.AbcExport(j='-sl -root head -root body -root lower -file ' + self.__files[-1]) self.__files.append(util.expandFileName('selectionTest.abc')) MayaCmds.AbcExport(j='-sl -file ' + self.__files[-1]) MayaCmds.AbcImport(self.__files[-1], m='open') self.failUnless(MayaCmds.objExists("robot|head")) self.failUnless(MayaCmds.objExists("robot|body|leftArm")) self.failUnless(MayaCmds.objExists("robot|lower|bottom")) self.failIf(MayaCmds.objExists("robot|body|rightArm")) self.failIf(MayaCmds.objExists("robot|body|chest")) self.failIf(MayaCmds.objExists("robot|lower|rightLeg")) self.failIf(MayaCmds.objExists("robot|lower|leftLeg")) MayaCmds.AbcImport(self.__files[-2], m='open') self.failUnless(MayaCmds.objExists("head")) self.failUnless(MayaCmds.objExists("body|leftArm")) self.failUnless(MayaCmds.objExists("lower|bottom")) # we didnt actually select any meshes so there shouldnt # be any in the scene self.failIf(MayaCmds.ls(type='mesh') is not None)
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import maya.OpenMaya as OpenMaya import os import subprocess import unittest import util def createJoints(): name = MayaCmds.joint(position=(0, 0, 0)) MayaCmds.rotate(33.694356, 4.000428, 61.426019, r=True, ws=True) MayaCmds.joint(position=(0, 4, 0), orientation=(0.0, 45.0, 90.0)) MayaCmds.rotate(62.153171, 0.0, 0.0, r=True, os=True) MayaCmds.joint(position=(0, 8, -1), orientation=(90.0, 0.0, 0.0)) MayaCmds.rotate(70.245162, -33.242019, 41.673097, r=True, os=True) MayaCmds.joint(position=(0, 12, 3)) MayaCmds.rotate(0.0, 0.0, -58.973851, r=True, os=True) return name class JointTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] self.__abcStitcher = [os.environ['AbcStitcher']] def tearDown(self): for f in self.__files: os.remove(f) def testStaticJointRW(self): name = createJoints() # write to file self.__files.append(util.expandFileName('testStaticJoints.abc')) MayaCmds.AbcExport(j='-root %s -file %s' % (name, self.__files[-1])) MayaCmds.select(name) MayaCmds.group(name='original') # read from file MayaCmds.AbcImport(self.__files[-1], mode='import') # make sure the translate and rotation are the same nodes1 = ["|original|joint1", "|original|joint1|joint2", "|original|joint1|joint2|joint3", "|original|joint1|joint2|joint3|joint4"] nodes2 = ["|joint1", "|joint1|joint2", "|joint1|joint2|joint3", "|joint1|joint2|joint3|joint4"] for i in range(0, 4): self.failUnlessAlmostEqual(MayaCmds.getAttr(nodes1[i]+'.tx'), MayaCmds.getAttr(nodes2[i]+'.tx'), 4) self.failUnlessAlmostEqual(MayaCmds.getAttr(nodes1[i]+'.ty'), MayaCmds.getAttr(nodes2[i]+'.ty'), 4) self.failUnlessAlmostEqual(MayaCmds.getAttr(nodes1[i]+'.tz'), MayaCmds.getAttr(nodes2[i]+'.tz'), 4) def testStaticIKRW(self): name = createJoints() MayaCmds.ikHandle(sj=name, ee='joint4') MayaCmds.move(-1.040057, -7.278225, 6.498725, r=True) # write to file self.__files.append(util.expandFileName('testStaticIK.abc')) MayaCmds.AbcExport(j='-root %s -f %s' % (name, self.__files[-1])) MayaCmds.select(name) MayaCmds.group(name='original') # read from file MayaCmds.AbcImport(self.__files[-1], mode='import') # make sure the translate and rotation are the same nodes1 = ["|original|joint1", "|original|joint1|joint2", "|original|joint1|joint2|joint3", "|original|joint1|joint2|joint3|joint4"] nodes2 = ["|joint1", "|joint1|joint2", "|joint1|joint2|joint3", "|joint1|joint2|joint3|joint4"] for i in range(0, 4): self.failUnlessAlmostEqual(MayaCmds.getAttr(nodes1[i]+'.tx'), MayaCmds.getAttr(nodes2[i]+'.tx'), 4) self.failUnlessAlmostEqual(MayaCmds.getAttr(nodes1[i]+'.ty'), MayaCmds.getAttr(nodes2[i]+'.ty'), 4) self.failUnlessAlmostEqual(MayaCmds.getAttr(nodes1[i]+'.tz'), MayaCmds.getAttr(nodes2[i]+'.tz'), 4) def testAnimIKRW(self): name = createJoints() handleName = MayaCmds.ikHandle(sj=name, ee='joint4')[0] MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe(handleName, breakdown=0, hierarchy='none', controlPoints=False, shape=False) MayaCmds.currentTime(16, update=True) MayaCmds.move(-1.040057, -7.278225, 6.498725, r=True) MayaCmds.setKeyframe(handleName, breakdown=0, hierarchy='none', controlPoints=False, shape=False) self.__files.append(util.expandFileName('testAnimIKRW.abc')) self.__files.append(util.expandFileName('testAnimIKRW01_08.abc')) self.__files.append(util.expandFileName('testAnimIKRW09-16.abc')) # write to files MayaCmds.AbcExport(j='-fr 1 8 -root %s -f %s' % (name, self.__files[-2])) MayaCmds.AbcExport(j='-fr 9 16 -root %s -f %s' % (name, self.__files[-1])) MayaCmds.select(name) MayaCmds.group(name='original') subprocess.call(self.__abcStitcher + self.__files[-3:]) # read from file MayaCmds.AbcImport(self.__files[-3], mode='import') # make sure the translate and rotation are the same nodes1 = ["|original|joint1", "|original|joint1|joint2", "|original|joint1|joint2|joint3", "|original|joint1|joint2|joint3|joint4"] nodes2 = ["|joint1", "|joint1|joint2", "|joint1|joint2|joint3", "|joint1|joint2|joint3|joint4"] for t in range(1, 25): MayaCmds.currentTime(t, update=True) for i in range(0, 4): self.failUnlessAlmostEqual(MayaCmds.getAttr(nodes1[i]+'.tx'), MayaCmds.getAttr(nodes2[i]+'.tx'), 4) self.failUnlessAlmostEqual(MayaCmds.getAttr(nodes1[i]+'.ty'), MayaCmds.getAttr(nodes2[i]+'.ty'), 4) self.failUnlessAlmostEqual(MayaCmds.getAttr(nodes1[i]+'.tz'), MayaCmds.getAttr(nodes2[i]+'.tz'), 4)
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds from maya import mel as Mel import os import unittest import util def makeRobot(): MayaCmds.polyCube(name="head") MayaCmds.move(0, 4, 0, r=1) MayaCmds.polyCube(name="chest") MayaCmds.scale(2, 2.5, 1) MayaCmds.move(0, 2, 0, r=1) MayaCmds.polyCube(name="leftArm") MayaCmds.move(0, 3, 0, r=1) MayaCmds.scale(2, 0.5, 1, r=1) MayaCmds.duplicate(name="rightArm") MayaCmds.select("leftArm") MayaCmds.move(1.25, 0, 0, r=1) MayaCmds.rotate(0, 0, 32, r=1, os=1) MayaCmds.select("rightArm") MayaCmds.move(-1.25, 0, 0, r=1) MayaCmds.rotate(0, 0, -32, r=1, os=1) MayaCmds.select("rightArm", "leftArm", "chest", r=1) MayaCmds.group(name="body") MayaCmds.polyCube(name="bottom") MayaCmds.scale(2, 0.5, 1) MayaCmds.move(0, 0.5, 0, r=1) MayaCmds.polyCube(name="leftLeg") MayaCmds.scale(0.65, 2.8, 1, r=1) MayaCmds.move(-0.5, -1, 0, r=1) MayaCmds.duplicate(name="rightLeg") MayaCmds.move(1, 0, 0, r=1) MayaCmds.select("rightLeg", "leftLeg", "bottom", r=1) MayaCmds.group(name="lower") MayaCmds.select("head", "body", "lower", r=1) MayaCmds.group(name="robot") def makeRobotAnimated(): makeRobot() #change pivot point of arms and legs MayaCmds.move(0.65, -0.40, 0, 'rightArm.scalePivot', 'rightArm.rotatePivot', relative=True) MayaCmds.move(-0.65, -0.40, 0, 'leftArm.scalePivot', 'leftArm.rotatePivot', relative=True) MayaCmds.move(0, 1.12, 0, 'rightLeg.scalePivot', 'rightLeg.rotatePivot', relative=True) MayaCmds.move(0, 1.12, 0, 'leftLeg.scalePivot', 'leftLeg.rotatePivot', relative=True) MayaCmds.setKeyframe('leftLeg', at='rotateX', value=25, t=[1, 12]) MayaCmds.setKeyframe('leftLeg', at='rotateX', value=-40, t=[6]) MayaCmds.setKeyframe('rightLeg', at='scaleY', value=2.8, t=[1, 12]) MayaCmds.setKeyframe('rightLeg', at='scaleY', value=5.0, t=[6]) MayaCmds.setKeyframe('leftArm', at='rotateZ', value=55, t=[1, 12]) MayaCmds.setKeyframe('leftArm', at='rotateZ', value=-50, t=[6]) MayaCmds.setKeyframe('rightArm', at='scaleX', value=0.5, t=[1, 12]) MayaCmds.setKeyframe('rightArm', at='scaleX', value=3.6, t=[6]) def drawBBox(llx, lly, llz, urx, ury, urz): # delete the old bounding box if MayaCmds.objExists('bbox'): MayaCmds.delete('bbox') p0 = (llx, lly, urz) p1 = (urx, lly, urz) p2 = (urx, lly, llz) p3 = (llx, lly, llz) p4 = (llx, ury, urz) p5 = (urx, ury, urz) p6 = (urx, ury, llz) p7 = (llx, ury, llz) MayaCmds.curve(d=1, p=[p0, p1]) MayaCmds.curve(d=1, p=[p1, p2]) MayaCmds.curve(d=1, p=[p2, p3]) MayaCmds.curve(d=1, p=[p3, p0]) MayaCmds.curve(d=1, p=[p4, p5]) MayaCmds.curve(d=1, p=[p5, p6]) MayaCmds.curve(d=1, p=[p6, p7]) MayaCmds.curve(d=1, p=[p7, p4]) MayaCmds.curve(d=1, p=[p0, p4]) MayaCmds.curve(d=1, p=[p1, p5]) MayaCmds.curve(d=1, p=[p2, p6]) MayaCmds.curve(d=1, p=[p3, p7]) MayaCmds.select(MayaCmds.ls("curve?")) MayaCmds.select(MayaCmds.ls("curve??"), add=True) MayaCmds.group(name="bbox") class callbackTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files: os.remove(f) def testMelPerFrameCallbackFlag(self): makeRobotAnimated() # make a non-zero transform on top of it MayaCmds.select('robot') MayaCmds.group(n='parent') MayaCmds.setAttr('parent.tx', 5) MayaCmds.setAttr('parent.ty', 3.15) MayaCmds.setAttr('parent.tz', 0.8) MayaCmds.setAttr('parent.rx', 2) MayaCmds.setAttr('parent.ry', 90) MayaCmds.setAttr('parent.rz', 1) MayaCmds.setAttr('parent.sx', 0.9) MayaCmds.setAttr('parent.sy', 1.1) MayaCmds.setAttr('parent.sz', 0.5) # create a camera looking at the robot camNames = MayaCmds.camera() MayaCmds.move(50.107, 20.968, 5.802, r=True) MayaCmds.rotate(-22.635, 83.6, 0, r=True) MayaCmds.camera(camNames[1], e=True, centerOfInterest=55.336, focalLength=50, horizontalFilmAperture=0.962, verticalFilmAperture=0.731) MayaCmds.rename(camNames[0], "cam_master") MayaCmds.setKeyframe('cam_master', t=[1, 12]) __builtins__['bboxDict'] = {} self.__files.append(util.expandFileName('pyPerFrameTest.abc')) MayaCmds.AbcExport(j='-fr 1 12 -pfc bboxDict[#FRAME#]=#BOUNDSARRAY# -root robot -file ' + self.__files[-1]) # push the numbers into a flat list array = [] for i in range(1, 13): array.append(bboxDict[i][0]) array.append(bboxDict[i][1]) array.append(bboxDict[i][2]) array.append(bboxDict[i][3]) array.append(bboxDict[i][4]) array.append(bboxDict[i][5]) bboxList_worldSpaceOff = [ -1.10907, -2.4, -1.51815, 1.8204, 4.5, 0.571487, -1.64677, -2.85936, -0.926652, 2.24711, 4.5, 0.540761, -2.25864, -3.38208, -0.531301, 2.37391, 4.5, 0.813599, -2.83342, -3.87312, -0.570038, 2.3177, 4.5, 1.45821, -3.25988, -4.23744, -0.569848, 2.06639, 4.5, 1.86489, -3.42675, -4.38, -0.563003, 1.92087, 4.5, 2.00285, -3.30872, -4.27917, -0.568236, 2.02633, 4.5, 1.9066, -2.99755, -4.01333, -0.572918, 2.24279, 4.5, 1.62326, -2.55762, -3.6375, -0.556938, 2.3781, 4.5, 1.16026, -2.05331, -3.20667, -0.507072, 2.37727, 4.5, 0.564985, -1.549, -2.77583, -1.04022, 2.18975, 4.5, 0.549216, -1.10907, -2.4, -1.51815, 1.8204, 4.5, 0.571487] self.failUnlessEqual(len(array), len(bboxList_worldSpaceOff)) for i in range(0, len(array)): self.failUnlessAlmostEqual(array[i], bboxList_worldSpaceOff[i], 4, '%d element in bbox array does not match.' % i) # test the bounding box calculation when worldSpace flag is on __builtins__['bboxDict'] = {} self.__files.append(util.expandFileName('pyPerFrameWorldspaceTest.abc')) MayaCmds.AbcExport(j='-fr 1 12 -ws -pfc bboxDict[#FRAME#]=#BOUNDSARRAY# -root robot -file ' + self.__files[-1]) # push the numbers into a flat list array = [] for i in range(1, 13): array.append(bboxDict[i][0]) array.append(bboxDict[i][1]) array.append(bboxDict[i][2]) array.append(bboxDict[i][3]) array.append(bboxDict[i][4]) array.append(bboxDict[i][5]) bboxList_worldSpaceOn = [ 4.77569, 0.397085, -0.991594, 5.90849, 7.99465, 1.64493, 5.06518, -0.108135, -1.37563, 5.90849, 7.99465, 2.12886, 5.25725, -0.683039, -1.48975, 5.9344, 7.99465, 2.67954, 5.24782, -1.223100, -1.43916, 6.26283, 7.99465, 3.19685, 5.24083, -1.62379, -1.21298, 6.47282, 7.99465, 3.58066, 5.23809, -1.78058, -1.08202, 6.54482, 7.99465, 3.73084, 5.24003, -1.66968, -1.17693, 6.49454, 7.99465, 3.62461, 5.24513, -1.37731, -1.37175, 6.34772, 7.99465, 3.34456, 5.25234, -0.963958, -1.49352, 6.11048, 7.99465, 2.94862, 5.26062, -0.490114, -1.49277, 5.90849, 7.99465, 2.49475, 5.00931, -0.0162691, -1.32401, 5.90849, 7.99465, 2.04087, 4.77569, 0.397085, -0.991594, 5.90849, 7.99465, 1.64493] self.failUnlessEqual(len(array), len(bboxList_worldSpaceOn)) for i in range(0, len(array)): self.failUnlessAlmostEqual(array[i], bboxList_worldSpaceOn[i], 4, '%d element in bbox array does not match.' % i) # test the bounding box calculation for camera __builtins__['bboxDict'] = {} self.__files.append(util.expandFileName('camPyPerFrameTest.abc')) MayaCmds.AbcExport(j='-fr 1 12 -pfc bboxDict[#FRAME#]=#BOUNDSARRAY# -root cam_master -file ' + self.__files[-1]) # push the numbers into a flat list ( since each frame is the same ) array = [] array.append(bboxDict[1][0]) array.append(bboxDict[1][1]) array.append(bboxDict[1][2]) array.append(bboxDict[1][3]) array.append(bboxDict[1][4]) array.append(bboxDict[1][5]) # cameras aren't included in the bounds bboxList_CAM = [0, 0, 0, 0, 0, 0] for i in range(0, len(array)): self.failUnlessAlmostEqual(array[i], bboxList_CAM[i], 4, '%d element in camera bbox array does not match.' % i)
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import subprocess import unittest import util class AnimNurbsSurfaceTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__abcStitcher = [os.environ['AbcStitcher']] self.__files = [] def tearDown(self): for f in self.__files: os.remove(f) def testAnimNurbsPlaneWrite(self): ret = MayaCmds.nurbsPlane(p=(0, 0, 0), ax=(0, 1, 0), w=1, lr=1, d=3, u=5, v=5, ch=0) name = ret[0] MayaCmds.lattice(name, dv=(4, 5, 4), oc=True) MayaCmds.select('ffd1Lattice.pt[1:2][0:4][1:2]', r=True) MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe() MayaCmds.currentTime(24, update=True) MayaCmds.setKeyframe() MayaCmds.currentTime(12, update=True) MayaCmds.move( 0, 0.18, 0, r=True) MayaCmds.scale( 2.5, 1.0, 2.5, r=True) MayaCmds.setKeyframe() MayaCmds.curveOnSurface(name, uv=((0.597523,0), (0.600359,0.271782), (0.538598,0.564218), (0.496932,0.779936), (0.672153,1)), k=(0,0,0,0.263463,0.530094,0.530094,0.530094)) curvename = MayaCmds.curveOnSurface(name, uv=((0.170718,0.565967), (0.0685088,0.393034), (0.141997,0.206296), (0.95,0.230359), (0.36264,0.441381), (0.251243,0.569889)), k=(0,0,0,0.200545,0.404853,0.598957,0.598957,0.598957)) MayaCmds.closeCurve(curvename, ch=1, ps=1, rpo=1, bb=0.5, bki=0, p=0.1, cos=1) MayaCmds.trim(name, lu=0.23, lv=0.39) degreeU = MayaCmds.getAttr(name+'.degreeU') degreeV = MayaCmds.getAttr(name+'.degreeV') spansU = MayaCmds.getAttr(name+'.spansU') spansV = MayaCmds.getAttr(name+'.spansV') formU = MayaCmds.getAttr(name+'.formU') formV = MayaCmds.getAttr(name+'.formV') minU = MayaCmds.getAttr(name+'.minValueU') maxU = MayaCmds.getAttr(name+'.maxValueU') minV = MayaCmds.getAttr(name+'.minValueV') maxV = MayaCmds.getAttr(name+'.maxValueV') MayaCmds.createNode('surfaceInfo') MayaCmds.connectAttr(name+'.worldSpace', 'surfaceInfo1.inputSurface', force=True) MayaCmds.currentTime(1, update=True) controlPoints = MayaCmds.getAttr('surfaceInfo1.controlPoints[*]') knotsU = MayaCmds.getAttr('surfaceInfo1.knotsU[*]') knotsV = MayaCmds.getAttr('surfaceInfo1.knotsV[*]') MayaCmds.currentTime(12, update=True) controlPoints2 = MayaCmds.getAttr('surfaceInfo1.controlPoints[*]') knotsU2 = MayaCmds.getAttr('surfaceInfo1.knotsU[*]') knotsV2 = MayaCmds.getAttr('surfaceInfo1.knotsV[*]') self.__files.append(util.expandFileName('testAnimNurbsPlane.abc')) self.__files.append(util.expandFileName('testAnimNurbsPlane01_14.abc')) self.__files.append(util.expandFileName('testAnimNurbsPlane15_24.abc')) MayaCmds.AbcExport(j='-fr 1 14 -root %s -file %s' % (name, self.__files[-2])) MayaCmds.AbcExport(j='-fr 15 24 -root %s -file %s' % (name, self.__files[-1])) # use AbcStitcher to combine two files into one subprocess.call(self.__abcStitcher + self.__files[-3:]) # reading test MayaCmds.AbcImport(self.__files[-3], mode='open') self.failUnlessEqual(degreeU, MayaCmds.getAttr(name+'.degreeU')) self.failUnlessEqual(degreeV, MayaCmds.getAttr(name+'.degreeV')) self.failUnlessEqual(spansU, MayaCmds.getAttr(name+'.spansU')) self.failUnlessEqual(spansV, MayaCmds.getAttr(name+'.spansV')) self.failUnlessEqual(formU, MayaCmds.getAttr(name+'.formU')) self.failUnlessEqual(formV, MayaCmds.getAttr(name+'.formV')) self.failUnlessEqual(minU, MayaCmds.getAttr(name+'.minValueU')) self.failUnlessEqual(maxU, MayaCmds.getAttr(name+'.maxValueU')) self.failUnlessEqual(minV, MayaCmds.getAttr(name+'.minValueV')) self.failUnlessEqual(maxV, MayaCmds.getAttr(name+'.maxValueV')) MayaCmds.createNode('surfaceInfo') MayaCmds.connectAttr(name+'.worldSpace', 'surfaceInfo1.inputSurface', force=True) MayaCmds.currentTime(1, update=True) errmsg = "At frame #1, Nurbs Plane's control point #%d.%s not equal" for i in range(0, len(controlPoints)): cp1 = controlPoints[i] cp2 = MayaCmds.getAttr('surfaceInfo1.controlPoints[%d]' % (i)) self.failUnlessAlmostEqual(cp1[0], cp2[0][0], 3, errmsg % (i, 'x')) self.failUnlessAlmostEqual(cp1[1], cp2[0][1], 3, errmsg % (i, 'y')) self.failUnlessAlmostEqual(cp1[2], cp2[0][2], 3, errmsg % (i, 'z')) errmsg = "At frame #1, Nurbs Plane's control knotsU #%d not equal" for i in range(0, len(knotsU)): ku1 = knotsU[i] ku2 = MayaCmds.getAttr('surfaceInfo1.knotsU[%d]' % (i)) self.failUnlessAlmostEqual(ku1, ku2, 3, errmsg % (i)) errmsg = "At frame #1, Nurbs Plane's control knotsV #%d not equal" for i in range(0, len(knotsV)): kv1 = knotsV[i] kv2 = MayaCmds.getAttr('surfaceInfo1.knotsV[%d]' % (i)) self.failUnlessAlmostEqual(kv1, kv2, 3, errmsg % (i)) MayaCmds.currentTime(12, update=True) errmsg = "At frame #12, Nurbs Plane's control point #%d.%s not equal" for i in range(0, len(controlPoints2)): cp1 = controlPoints2[i] cp2 = MayaCmds.getAttr('surfaceInfo1.controlPoints[%d]' % (i)) self.failUnlessAlmostEqual(cp1[0], cp2[0][0], 3, errmsg % (i, 'x')) self.failUnlessAlmostEqual(cp1[1], cp2[0][1], 3, errmsg % (i, 'y')) self.failUnlessAlmostEqual(cp1[2], cp2[0][2], 3, errmsg % (i, 'z')) errmsg = "At frame #12, Nurbs Plane's control knotsU #%d not equal" for i in range(0, len(knotsU2)): ku1 = knotsU2[i] ku2 = MayaCmds.getAttr('surfaceInfo1.knotsU[%d]' % (i)) self.failUnlessAlmostEqual(ku1, ku2, 3, errmsg % (i)) errmsg = "At frame #12, Nurbs Plane's control knotsV #%d not equal" for i in range(0, len(knotsV2)): kv1 = knotsV2[i] kv2 = MayaCmds.getAttr('surfaceInfo1.knotsV[%d]' % (i)) self.failUnlessAlmostEqual(kv1, kv2, 3, errmsg % (i)) MayaCmds.currentTime(24, update=True) errmsg = "At frame #24, Nurbs Plane's control point #%d.%s not equal" for i in range(0, len(controlPoints)): cp1 = controlPoints[i] cp2 = MayaCmds.getAttr('surfaceInfo1.controlPoints[%d]' % (i)) self.failUnlessAlmostEqual(cp1[0], cp2[0][0], 3, errmsg % (i, 'x')) self.failUnlessAlmostEqual(cp1[1], cp2[0][1], 3, errmsg % (i, 'y')) self.failUnlessAlmostEqual(cp1[2], cp2[0][2], 3, errmsg % (i, 'z')) errmsg = "At frame #24, Nurbs Plane's control knotsU #%d not equal" for i in range(0, len(knotsU)): ku1 = knotsU[i] ku2 = MayaCmds.getAttr('surfaceInfo1.knotsU[%d]' % (i)) self.failUnlessAlmostEqual(ku1, ku2, 3, errmsg % (i)) errmsg = "At frame #24, Nurbs Plane's control knotsV #%d not equal" for i in range(0, len(knotsV)): kv1 = knotsV[i] kv2 = MayaCmds.getAttr('surfaceInfo1.knotsV[%d]' % (i)) self.failUnlessAlmostEqual(kv1, kv2, 3, errmsg % (i))
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import maya.OpenMaya as OpenMaya import os import subprocess import unittest import util def createLocator(): shape = MayaCmds.createNode("locator") name = MayaCmds.pickWalk(shape, d="up") MayaCmds.setAttr(shape+'.localPositionX', 0.962) MayaCmds.setAttr(shape+'.localPositionY', 0.731) MayaCmds.setAttr(shape+'.localPositionZ', 5.114) MayaCmds.setAttr(shape+'.localScaleX', 5) MayaCmds.setAttr(shape+'.localScaleY', 1.44) MayaCmds.setAttr(shape+'.localScaleZ', 1.38) return name[0], shape class locatorTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] self.__abcStitcher = [os.environ['AbcStitcher']] def tearDown(self): for f in self.__files: os.remove(f) def testStaticLocatorRW(self): name = createLocator() # write to file self.__files.append(util.expandFileName('testStaticLocatorRW.abc')) MayaCmds.AbcExport(j='-root %s -file %s' % (name[0], self.__files[-1])) # read from file MayaCmds.AbcImport(self.__files[-1], mode='import') locatorList = MayaCmds.ls(type='locator') self.failUnless(util.compareLocator(locatorList[0], locatorList[1])) def testAnimLocatorRW(self): name = createLocator() MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe(name[1], attribute='localPositionX') MayaCmds.setKeyframe(name[1], attribute='localPositionY') MayaCmds.setKeyframe(name[1], attribute='localPositionZ') MayaCmds.setKeyframe(name[1], attribute='localScaleX') MayaCmds.setKeyframe(name[1], attribute='localScaleY') MayaCmds.setKeyframe(name[1], attribute='localScaleZ') MayaCmds.currentTime(24, update=True) MayaCmds.setKeyframe(name[1], attribute='localPositionX', value=0.0) MayaCmds.setKeyframe(name[1], attribute='localPositionY', value=0.0) MayaCmds.setKeyframe(name[1], attribute='localPositionZ', value=0.0) MayaCmds.setKeyframe(name[1], attribute='localScaleX', value=1.0) MayaCmds.setKeyframe(name[1], attribute='localScaleY', value=1.0) MayaCmds.setKeyframe(name[1], attribute='localScaleZ', value=1.0) self.__files.append(util.expandFileName('testAnimLocatorRW.abc')) self.__files.append(util.expandFileName('testAnimLocatorRW01_14.abc')) self.__files.append(util.expandFileName('testAnimLocatorRW15-24.abc')) # write to files MayaCmds.AbcExport(j='-fr 1 14 -root %s -file %s' % (name[0], self.__files[-2])) MayaCmds.AbcExport(j='-fr 15 24 -root %s -file %s' % (name[0], self.__files[-1])) subprocess.call(self.__abcStitcher + self.__files[-3:]) # read from file MayaCmds.AbcImport(self.__files[-3], mode='import') locatorList = MayaCmds.ls(type='locator') for t in range(1, 25): MayaCmds.currentTime(t, update=True) if not util.compareLocator(locatorList[0], locatorList[1]): self.fail('%s and %s are not the same at frame %d' % (locatorList[0], locatorList[1], t))
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import unittest import util class emptyMeshTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files: os.remove(f) def testEmptyMeshFlag(self): MayaCmds.createNode('mesh', name='mesh') MayaCmds.rename('|polySurface1', 'trans') self.__files.append(util.expandFileName('emptyMeshTest.abc')) MayaCmds.AbcExport(j='-root trans -file ' + self.__files[-1]) MayaCmds.AbcImport(self.__files[-1], m='open') self.failUnless(MayaCmds.objExists("trans")) self.failIf(MayaCmds.objExists("head"))
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import unittest import util class TransformTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files : os.remove(f) def testStaticTransformReadWrite(self): nodeName1 = MayaCmds.polyCube() nodeName2 = MayaCmds.duplicate() nodeName3 = MayaCmds.duplicate() self.__files.append(util.expandFileName('reparentflag.abc')) MayaCmds.AbcExport(j='-root %s -root %s -root %s -file %s' % (nodeName1[0], nodeName2[0], nodeName3[0], self.__files[-1])) # reading test MayaCmds.file(new=True, force=True) MayaCmds.createNode('transform', n='root') MayaCmds.AbcImport(self.__files[-1], mode='import', reparent='root') self.failUnlessEqual(MayaCmds.objExists('root|'+nodeName1[0]), 1) self.failUnlessEqual(MayaCmds.objExists('root|'+nodeName2[0]), 1) self.failUnlessEqual(MayaCmds.objExists('root|'+nodeName3[0]), 1)
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import unittest import util class AnimPointPrimitiveTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files: os.remove(f) def testAnimPointPrimitiveReadWrite(self): # Creates a point emitter. MayaCmds.emitter(dx=1, dy=0, dz=0, sp=0.33, pos=(1, 1, 1), n='myEmitter') MayaCmds.particle(n='emittedParticles') MayaCmds.setAttr('emittedParticles.lfm', 2) MayaCmds.setAttr('emittedParticles.lifespan', 50) MayaCmds.setAttr('emittedParticles.lifespanRandom', 2) MayaCmds.connectDynamic('emittedParticles', em='myEmitter') self.__files.append(util.expandFileName('testAnimParticleReadWrite.abc')) MayaCmds.AbcExport(j='-fr 1 24 -root emittedParticles -file ' + self.__files[-1]) # reading test MayaCmds.AbcImport(self.__files[-1], mode='open') # reading animated point clouds into Maya aren't fully supported # yet which is why we don't have any checks on the data here
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import unittest class AbcExport_dupRootsTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) def testStaticTransformReadWrite(self): MayaCmds.polyCube(n='cube') MayaCmds.group(n='group1') MayaCmds.duplicate() self.failUnlessRaises(RuntimeError, MayaCmds.AbcExport, j='-root group1|cube -root group2|cube -f dupRoots.abc') # the abc file shouldn't exist self.failUnless(not os.path.isfile('dupRoots.abc'))
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import maya.OpenMaya as OpenMaya import os import subprocess import unittest import util class AnimMeshTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__abcStitcher = [os.environ['AbcStitcher']] self.__files = [] def tearDown(self): for f in self.__files : os.remove(f) def testAnimSPT_HwColor_ReadWrite(self): numFaces = 6 numVertices = 8 numFaceConnects = 24 vtx_1 = OpenMaya.MFloatPoint(-0.5, -0.5, -0.5) vtx_2 = OpenMaya.MFloatPoint( 0.5, -0.5, -0.5) vtx_3 = OpenMaya.MFloatPoint( 0.5, -0.5, 0.5) vtx_4 = OpenMaya.MFloatPoint(-0.5, -0.5, 0.5) vtx_5 = OpenMaya.MFloatPoint(-0.5, 0.5, -0.5) vtx_6 = OpenMaya.MFloatPoint(-0.5, 0.5, 0.5) vtx_7 = OpenMaya.MFloatPoint( 0.5, 0.5, 0.5) vtx_8 = OpenMaya.MFloatPoint( 0.5, 0.5, -0.5) points = OpenMaya.MFloatPointArray() points.setLength(8) points.set(vtx_1, 0) points.set(vtx_2, 1) points.set(vtx_3, 2) points.set(vtx_4, 3) points.set(vtx_5, 4) points.set(vtx_6, 5) points.set(vtx_7, 6) points.set(vtx_8, 7) faceConnects = OpenMaya.MIntArray() faceConnects.setLength(numFaceConnects) faceConnects.set(0, 0) faceConnects.set(1, 1) faceConnects.set(2, 2) faceConnects.set(3, 3) faceConnects.set(4, 4) faceConnects.set(5, 5) faceConnects.set(6, 6) faceConnects.set(7, 7) faceConnects.set(3, 8) faceConnects.set(2, 9) faceConnects.set(6, 10) faceConnects.set(5, 11) faceConnects.set(0, 12) faceConnects.set(3, 13) faceConnects.set(5, 14) faceConnects.set(4, 15) faceConnects.set(0, 16) faceConnects.set(4, 17) faceConnects.set(7, 18) faceConnects.set(1, 19) faceConnects.set(1, 20) faceConnects.set(7, 21) faceConnects.set(6, 22) faceConnects.set(2, 23) faceCounts = OpenMaya.MIntArray() faceCounts.setLength(6) faceCounts.set(4, 0) faceCounts.set(4, 1) faceCounts.set(4, 2) faceCounts.set(4, 3) faceCounts.set(4, 4) faceCounts.set(4, 5) transFn = OpenMaya.MFnTransform() parent = transFn.create() transFn.setName('poly') meshFn = OpenMaya.MFnMesh() meshFn.create(numVertices, numFaces, points, faceCounts, faceConnects, parent) shapeName = 'polyShape' meshFn.setName(shapeName) # add SPT_HwColor attributes MayaCmds.select( shapeName ) MayaCmds.addAttr(longName='SPT_HwColor', usedAsColor=True, attributeType='float3') MayaCmds.addAttr(longName='SPT_HwColorR', attributeType='float', parent='SPT_HwColor') MayaCmds.addAttr(longName='SPT_HwColorG', attributeType='float', parent='SPT_HwColor') MayaCmds.addAttr(longName='SPT_HwColorB', attributeType='float', parent='SPT_HwColor') # set colors MayaCmds.setAttr(shapeName+'.SPT_HwColor', 0.50, 0.15, 0.75, type='float3') MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe('polyShape.vtx[0:7]') # colors MayaCmds.setKeyframe( shapeName+'.SPT_HwColor') MayaCmds.currentTime(24, update=True) MayaCmds.setKeyframe('polyShape.vtx[0:7]') # colors MayaCmds.setKeyframe( shapeName+'.SPT_HwColor') MayaCmds.currentTime(12, update=True) vtx_11 = OpenMaya.MFloatPoint(-1.0, -1.0, -1.0) vtx_22 = OpenMaya.MFloatPoint( 1.0, -1.0, -1.0) vtx_33 = OpenMaya.MFloatPoint( 1.0, -1.0, 1.0) vtx_44 = OpenMaya.MFloatPoint(-1.0, -1.0, 1.0) vtx_55 = OpenMaya.MFloatPoint(-1.0, 1.0, -1.0) vtx_66 = OpenMaya.MFloatPoint(-1.0, 1.0, 1.0) vtx_77 = OpenMaya.MFloatPoint( 1.0, 1.0, 1.0) vtx_88 = OpenMaya.MFloatPoint( 1.0, 1.0, -1.0) points.set(vtx_11, 0) points.set(vtx_22, 1) points.set(vtx_33, 2) points.set(vtx_44, 3) points.set(vtx_55, 4) points.set(vtx_66, 5) points.set(vtx_77, 6) points.set(vtx_88, 7) meshFn.setPoints(points) MayaCmds.setAttr( shapeName+'.SPT_HwColor', 0.15, 0.5, 0.15, type='float3') MayaCmds.setKeyframe('polyShape.vtx[0:7]') # colors MayaCmds.setKeyframe( shapeName+'.SPT_HwColor') self.__files.append(util.expandFileName('animSPT_HwColor.abc')) self.__files.append(util.expandFileName('animSPT_HwColor_01_14.abc')) self.__files.append(util.expandFileName('animSPT_HwColor_15_24.abc')) MayaCmds.AbcExport(j='-atp SPT_ -fr 1 14 -root poly -file ' + self.__files[-2]) MayaCmds.AbcExport(j='-atp SPT_ -fr 15 24 -root poly -file ' + self.__files[-1]) subprocess.call(self.__abcStitcher + self.__files[-3:]) # reading test MayaCmds.AbcImport(self.__files[-3], mode='open') places = 7 # check colors MayaCmds.currentTime(1, update=True) colorVec_1 = MayaCmds.getAttr(shapeName+'.SPT_HwColor')[0] self.failUnlessAlmostEqual(colorVec_1[0], 0.50, places) self.failUnlessAlmostEqual(colorVec_1[1], 0.15, places) self.failUnlessAlmostEqual(colorVec_1[2], 0.75, places) MayaCmds.currentTime(2, update=True) # only needed for interpolation test on frame 1.422 colorVec_2 = MayaCmds.getAttr(shapeName+'.SPT_HwColor')[0] setTime = MayaCmds.currentTime(1.422, update=True) alpha = (setTime - 1) / (2 - 1) colorVec = MayaCmds.getAttr(shapeName+'.SPT_HwColor')[0] self.failUnlessAlmostEqual(colorVec[0], (1-alpha)*colorVec_1[0]+alpha*colorVec_2[0], places) self.failUnlessAlmostEqual(colorVec[1], (1-alpha)*colorVec_1[1]+alpha*colorVec_2[1], places) self.failUnlessAlmostEqual(colorVec[2], (1-alpha)*colorVec_1[2]+alpha*colorVec_2[2], places) MayaCmds.currentTime(12, update=True) colorVec = MayaCmds.getAttr( shapeName+'.SPT_HwColor' )[0] self.failUnlessAlmostEqual( colorVec[0], 0.15, places) self.failUnlessAlmostEqual( colorVec[1], 0.50, places) self.failUnlessAlmostEqual( colorVec[2], 0.15, places) MayaCmds.currentTime(24, update=True) colorVec = MayaCmds.getAttr(shapeName+'.SPT_HwColor')[0] self.failUnlessAlmostEqual(colorVec[0], 0.50, places) self.failUnlessAlmostEqual(colorVec[1], 0.15, places) self.failUnlessAlmostEqual(colorVec[2], 0.75, places)
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import unittest import util class StaticPointPrimitiveTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files : os.remove(f) def testPointPrimitiveReadWrite(self): # Creates a particle object with four particles name = MayaCmds.particle( p=[(0, 0, 0), (3, 5, 6), (5, 6, 7), (9, 9, 9)]) posVec = [0, 0, 0, 3, 5, 6, 5, 6, 7, 9, 9, 9] self.__files.append(util.expandFileName('testPointPrimitiveReadWrite.abc')) MayaCmds.AbcExport(j='-root %s -f %s' % (name[0], self.__files[-1])) # reading test MayaCmds.AbcImport(self.__files[-1], mode='open') pos = MayaCmds.getAttr(name[1] + '.position') ids = MayaCmds.getAttr(name[1] + '.particleId') self.failUnlessEqual(len(ids), 4) for i in range(0, 4): index = 3*i self.failUnlessAlmostEqual(pos[i][0], posVec[index], 4) self.failUnlessAlmostEqual(pos[i][1], posVec[index+1], 4) self.failUnlessAlmostEqual(pos[i][2], posVec[index+2], 4)
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import unittest import util class LoadWorldSpaceTranslateJobTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files : os.remove(f) def testStaticLoadWorldSpaceTranslateJobReadWrite(self): nodeName = MayaCmds.polyCube(n='cube') root = nodeName[0] MayaCmds.setAttr(root+'.rotateX', 45) MayaCmds.setAttr(root+'.scaleX', 1.5) MayaCmds.setAttr(root+'.translateY', -1.95443) nodeName = MayaCmds.group() MayaCmds.setAttr(nodeName+'.rotateY', 15) MayaCmds.setAttr(nodeName+'.translateY', -3.95443) nodeName = MayaCmds.group() MayaCmds.setAttr(nodeName+'.rotateZ',-90) MayaCmds.setAttr(nodeName+'.shearXZ',2.555) self.__files.append(util.expandFileName('testStaticLoadWorldSpaceTranslateJob.abc')) MayaCmds.AbcExport(j='-ws -root %s -file %s' % (root, self.__files[-1])) # reading test MayaCmds.AbcImport(self.__files[-1], mode='open') self.failUnlessAlmostEqual(0, MayaCmds.getAttr(root+'.translateX'), 3) self.failUnlessAlmostEqual(-5.909, MayaCmds.getAttr(root+'.translateY'), 3) self.failUnlessAlmostEqual(0, MayaCmds.getAttr(root+'.translateZ'), 3) self.failUnlessAlmostEqual(68.211, MayaCmds.getAttr(root+'.rotateX'), 3) self.failUnlessAlmostEqual(40.351, MayaCmds.getAttr(root+'.rotateY'), 3) self.failUnlessAlmostEqual(-90, MayaCmds.getAttr(root+'.rotateZ'), 3) self.failUnlessAlmostEqual(0.600, MayaCmds.getAttr(root+'.scaleX'), 3) self.failUnlessAlmostEqual(1.905, MayaCmds.getAttr(root+'.scaleY'), 3) self.failUnlessAlmostEqual(1.313, MayaCmds.getAttr(root+'.scaleZ'), 3) self.failUnlessAlmostEqual(0.539, MayaCmds.getAttr(root+'.shearXY'), 3) self.failUnlessAlmostEqual(0.782, MayaCmds.getAttr(root+'.shearXZ'), 3) self.failUnlessAlmostEqual(1.051, MayaCmds.getAttr(root+'.shearYZ'), 3) def testAnimLoadWorldSpaceTranslateJobReadWrite(self): nodeName = MayaCmds.polyCube(n='cube') root = nodeName[0] MayaCmds.setAttr(root+'.rotateX', 45) MayaCmds.setAttr(root+'.scaleX', 1.5) MayaCmds.setAttr(root+'.translateY', -1.95443) MayaCmds.setKeyframe(root, value=0, attribute='translateX', t=[1, 24]) MayaCmds.setKeyframe(root, value=1, attribute='translateX', t=12) nodeName = MayaCmds.group() MayaCmds.setAttr(nodeName+'.rotateY', 15) MayaCmds.setAttr(nodeName+'.translateY', -3.95443) nodeName = MayaCmds.group() MayaCmds.setAttr(nodeName+'.rotateZ',-90) MayaCmds.setAttr(nodeName+'.shearXZ',2.555) self.__files.append(util.expandFileName('testAnimLoadWorldSpaceTranslateJob.abc')) MayaCmds.AbcExport(j='-fr 1 24 -ws -root %s -file %s' % (root, self.__files[-1])) # reading test MayaCmds.AbcImport(self.__files[-1], mode='open') # frame 1 MayaCmds.currentTime(1, update=True) self.failUnlessAlmostEqual(0, MayaCmds.getAttr(root+'.translateX'), 3) self.failUnlessAlmostEqual(-5.909, MayaCmds.getAttr(root+'.translateY'), 3) self.failUnlessAlmostEqual(0, MayaCmds.getAttr(root+'.translateZ'), 3) self.failUnlessAlmostEqual(68.211, MayaCmds.getAttr(root+'.rotateX'), 3) self.failUnlessAlmostEqual(40.351, MayaCmds.getAttr(root+'.rotateY'), 3) self.failUnlessAlmostEqual(-90, MayaCmds.getAttr(root+'.rotateZ'), 3) self.failUnlessAlmostEqual(0.600, MayaCmds.getAttr(root+'.scaleX'), 3) self.failUnlessAlmostEqual(1.905, MayaCmds.getAttr(root+'.scaleY'), 3) self.failUnlessAlmostEqual(1.313, MayaCmds.getAttr(root+'.scaleZ'), 3) self.failUnlessAlmostEqual(0.539, MayaCmds.getAttr(root+'.shearXY'), 3) self.failUnlessAlmostEqual(0.782, MayaCmds.getAttr(root+'.shearXZ'), 3) self.failUnlessAlmostEqual(1.051, MayaCmds.getAttr(root+'.shearYZ'), 3) # frame 12 MayaCmds.currentTime(12, update=True) self.failUnlessAlmostEqual(0, MayaCmds.getAttr(root+'.translateX'), 3) self.failUnlessAlmostEqual(-6.2135, MayaCmds.getAttr(root+'.translateY'), 3) self.failUnlessAlmostEqual(-0.258819, MayaCmds.getAttr(root+'.translateZ'), 3) self.failUnlessAlmostEqual(68.211, MayaCmds.getAttr(root+'.rotateX'), 3) self.failUnlessAlmostEqual(40.351, MayaCmds.getAttr(root+'.rotateY'), 3) self.failUnlessAlmostEqual(-90, MayaCmds.getAttr(root+'.rotateZ'), 3) self.failUnlessAlmostEqual(0.600, MayaCmds.getAttr(root+'.scaleX'), 3) self.failUnlessAlmostEqual(1.905, MayaCmds.getAttr(root+'.scaleY'), 3) self.failUnlessAlmostEqual(1.313, MayaCmds.getAttr(root+'.scaleZ'), 3) self.failUnlessAlmostEqual(0.539, MayaCmds.getAttr(root+'.shearXY'), 3) self.failUnlessAlmostEqual(0.782, MayaCmds.getAttr(root+'.shearXZ'), 3) self.failUnlessAlmostEqual(1.051, MayaCmds.getAttr(root+'.shearYZ'), 3) # frame 24 MayaCmds.currentTime(24, update=True) self.failUnlessAlmostEqual(0, MayaCmds.getAttr(root+'.translateX'), 3) self.failUnlessAlmostEqual(-5.909, MayaCmds.getAttr(root+'.translateY'), 3) self.failUnlessAlmostEqual(0, MayaCmds.getAttr(root+'.translateZ'), 3) self.failUnlessAlmostEqual(68.211, MayaCmds.getAttr(root+'.rotateX'), 3) self.failUnlessAlmostEqual(40.351, MayaCmds.getAttr(root+'.rotateY'), 3) self.failUnlessAlmostEqual(-90, MayaCmds.getAttr(root+'.rotateZ'), 3) self.failUnlessAlmostEqual(0.600, MayaCmds.getAttr(root+'.scaleX'), 3) self.failUnlessAlmostEqual(1.905, MayaCmds.getAttr(root+'.scaleY'), 3) self.failUnlessAlmostEqual(1.313, MayaCmds.getAttr(root+'.scaleZ'), 3) self.failUnlessAlmostEqual(0.539, MayaCmds.getAttr(root+'.shearXY'), 3) self.failUnlessAlmostEqual(0.782, MayaCmds.getAttr(root+'.shearXZ'), 3) self.failUnlessAlmostEqual(1.051, MayaCmds.getAttr(root+'.shearYZ'), 3)
Python