code
stringlengths
1
1.72M
language
stringclasses
1 value
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Options/ListOption.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" __doc__ = """Place-holder for the old SCons.Options module hierarchy This is for backwards compatibility. The new equivalent is the Variables/ class hierarchy. These will have deprecation warnings added (some day), and will then be removed entirely (some day). """ import SCons.Variables import SCons.Warnings warned = False def ListOption(*args, **kw): global warned if not warned: msg = "The ListOption() function is deprecated; use the ListVariable() function instead." SCons.Warnings.warn(SCons.Warnings.DeprecatedOptionsWarning, msg) warned = True return SCons.Variables.ListVariable(*args, **kw) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Job This module defines the Serial and Parallel classes that execute tasks to complete a build. The Jobs class provides a higher level interface to start, stop, and wait on jobs. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Job.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.compat import os import signal import SCons.Errors # The default stack size (in kilobytes) of the threads used to execute # jobs in parallel. # # We use a stack size of 256 kilobytes. The default on some platforms # is too large and prevents us from creating enough threads to fully # parallelized the build. For example, the default stack size on linux # is 8 MBytes. explicit_stack_size = None default_stack_size = 256 interrupt_msg = 'Build interrupted.' class InterruptState(object): def __init__(self): self.interrupted = False def set(self): self.interrupted = True def __call__(self): return self.interrupted class Jobs(object): """An instance of this class initializes N jobs, and provides methods for starting, stopping, and waiting on all N jobs. """ def __init__(self, num, taskmaster): """ create 'num' jobs using the given taskmaster. If 'num' is 1 or less, then a serial job will be used, otherwise a parallel job with 'num' worker threads will be used. The 'num_jobs' attribute will be set to the actual number of jobs allocated. If more than one job is requested but the Parallel class can't do it, it gets reset to 1. Wrapping interfaces that care should check the value of 'num_jobs' after initialization. """ self.job = None if num > 1: stack_size = explicit_stack_size if stack_size is None: stack_size = default_stack_size try: self.job = Parallel(taskmaster, num, stack_size) self.num_jobs = num except NameError: pass if self.job is None: self.job = Serial(taskmaster) self.num_jobs = 1 def run(self, postfunc=lambda: None): """Run the jobs. postfunc() will be invoked after the jobs has run. It will be invoked even if the jobs are interrupted by a keyboard interrupt (well, in fact by a signal such as either SIGINT, SIGTERM or SIGHUP). The execution of postfunc() is protected against keyboard interrupts and is guaranteed to run to completion.""" self._setup_sig_handler() try: self.job.start() finally: postfunc() self._reset_sig_handler() def were_interrupted(self): """Returns whether the jobs were interrupted by a signal.""" return self.job.interrupted() def _setup_sig_handler(self): """Setup an interrupt handler so that SCons can shutdown cleanly in various conditions: a) SIGINT: Keyboard interrupt b) SIGTERM: kill or system shutdown c) SIGHUP: Controlling shell exiting We handle all of these cases by stopping the taskmaster. It turns out that it very difficult to stop the build process by throwing asynchronously an exception such as KeyboardInterrupt. For example, the python Condition variables (threading.Condition) and queue's do not seem to asynchronous-exception-safe. It would require adding a whole bunch of try/finally block and except KeyboardInterrupt all over the place. Note also that we have to be careful to handle the case when SCons forks before executing another process. In that case, we want the child to exit immediately. """ def handler(signum, stack, self=self, parentpid=os.getpid()): if os.getpid() == parentpid: self.job.taskmaster.stop() self.job.interrupted.set() else: os._exit(2) self.old_sigint = signal.signal(signal.SIGINT, handler) self.old_sigterm = signal.signal(signal.SIGTERM, handler) try: self.old_sighup = signal.signal(signal.SIGHUP, handler) except AttributeError: pass def _reset_sig_handler(self): """Restore the signal handlers to their previous state (before the call to _setup_sig_handler().""" signal.signal(signal.SIGINT, self.old_sigint) signal.signal(signal.SIGTERM, self.old_sigterm) try: signal.signal(signal.SIGHUP, self.old_sighup) except AttributeError: pass class Serial(object): """This class is used to execute tasks in series, and is more efficient than Parallel, but is only appropriate for non-parallel builds. Only one instance of this class should be in existence at a time. This class is not thread safe. """ def __init__(self, taskmaster): """Create a new serial job given a taskmaster. The taskmaster's next_task() method should return the next task that needs to be executed, or None if there are no more tasks. The taskmaster's executed() method will be called for each task when it is successfully executed or failed() will be called if it failed to execute (e.g. execute() raised an exception).""" self.taskmaster = taskmaster self.interrupted = InterruptState() def start(self): """Start the job. This will begin pulling tasks from the taskmaster and executing them, and return when there are no more tasks. If a task fails to execute (i.e. execute() raises an exception), then the job will stop.""" while True: task = self.taskmaster.next_task() if task is None: break try: task.prepare() if task.needs_execute(): task.execute() except: if self.interrupted(): try: raise SCons.Errors.BuildError( task.targets[0], errstr=interrupt_msg) except: task.exception_set() else: task.exception_set() # Let the failed() callback function arrange for the # build to stop if that's appropriate. task.failed() else: task.executed() task.postprocess() self.taskmaster.cleanup() # Trap import failure so that everything in the Job module but the # Parallel class (and its dependent classes) will work if the interpreter # doesn't support threads. try: import queue import threading except ImportError: pass else: class Worker(threading.Thread): """A worker thread waits on a task to be posted to its request queue, dequeues the task, executes it, and posts a tuple including the task and a boolean indicating whether the task executed successfully. """ def __init__(self, requestQueue, resultsQueue, interrupted): threading.Thread.__init__(self) self.setDaemon(1) self.requestQueue = requestQueue self.resultsQueue = resultsQueue self.interrupted = interrupted self.start() def run(self): while True: task = self.requestQueue.get() if task is None: # The "None" value is used as a sentinel by # ThreadPool.cleanup(). This indicates that there # are no more tasks, so we should quit. break try: if self.interrupted(): raise SCons.Errors.BuildError( task.targets[0], errstr=interrupt_msg) task.execute() except: task.exception_set() ok = False else: ok = True self.resultsQueue.put((task, ok)) class ThreadPool(object): """This class is responsible for spawning and managing worker threads.""" def __init__(self, num, stack_size, interrupted): """Create the request and reply queues, and 'num' worker threads. One must specify the stack size of the worker threads. The stack size is specified in kilobytes. """ self.requestQueue = queue.Queue(0) self.resultsQueue = queue.Queue(0) try: prev_size = threading.stack_size(stack_size*1024) except AttributeError, e: # Only print a warning if the stack size has been # explicitly set. if not explicit_stack_size is None: msg = "Setting stack size is unsupported by this version of Python:\n " + \ e.args[0] SCons.Warnings.warn(SCons.Warnings.StackSizeWarning, msg) except ValueError, e: msg = "Setting stack size failed:\n " + str(e) SCons.Warnings.warn(SCons.Warnings.StackSizeWarning, msg) # Create worker threads self.workers = [] for _ in range(num): worker = Worker(self.requestQueue, self.resultsQueue, interrupted) self.workers.append(worker) if 'prev_size' in locals(): threading.stack_size(prev_size) def put(self, task): """Put task into request queue.""" self.requestQueue.put(task) def get(self): """Remove and return a result tuple from the results queue.""" return self.resultsQueue.get() def preparation_failed(self, task): self.resultsQueue.put((task, False)) def cleanup(self): """ Shuts down the thread pool, giving each worker thread a chance to shut down gracefully. """ # For each worker thread, put a sentinel "None" value # on the requestQueue (indicating that there's no work # to be done) so that each worker thread will get one and # terminate gracefully. for _ in self.workers: self.requestQueue.put(None) # Wait for all of the workers to terminate. # # If we don't do this, later Python versions (2.4, 2.5) often # seem to raise exceptions during shutdown. This happens # in requestQueue.get(), as an assertion failure that # requestQueue.not_full is notified while not acquired, # seemingly because the main thread has shut down (or is # in the process of doing so) while the workers are still # trying to pull sentinels off the requestQueue. # # Normally these terminations should happen fairly quickly, # but we'll stick a one-second timeout on here just in case # someone gets hung. for worker in self.workers: worker.join(1.0) self.workers = [] class Parallel(object): """This class is used to execute tasks in parallel, and is somewhat less efficient than Serial, but is appropriate for parallel builds. This class is thread safe. """ def __init__(self, taskmaster, num, stack_size): """Create a new parallel job given a taskmaster. The taskmaster's next_task() method should return the next task that needs to be executed, or None if there are no more tasks. The taskmaster's executed() method will be called for each task when it is successfully executed or failed() will be called if the task failed to execute (i.e. execute() raised an exception). Note: calls to taskmaster are serialized, but calls to execute() on distinct tasks are not serialized, because that is the whole point of parallel jobs: they can execute multiple tasks simultaneously. """ self.taskmaster = taskmaster self.interrupted = InterruptState() self.tp = ThreadPool(num, stack_size, self.interrupted) self.maxjobs = num def start(self): """Start the job. This will begin pulling tasks from the taskmaster and executing them, and return when there are no more tasks. If a task fails to execute (i.e. execute() raises an exception), then the job will stop.""" jobs = 0 while True: # Start up as many available tasks as we're # allowed to. while jobs < self.maxjobs: task = self.taskmaster.next_task() if task is None: break try: # prepare task for execution task.prepare() except: task.exception_set() task.failed() task.postprocess() else: if task.needs_execute(): # dispatch task self.tp.put(task) jobs = jobs + 1 else: task.executed() task.postprocess() if not task and not jobs: break # Let any/all completed tasks finish up before we go # back and put the next batch of tasks on the queue. while True: task, ok = self.tp.get() jobs = jobs - 1 if ok: task.executed() else: if self.interrupted(): try: raise SCons.Errors.BuildError( task.targets[0], errstr=interrupt_msg) except: task.exception_set() # Let the failed() callback function arrange # for the build to stop if that's appropriate. task.failed() task.postprocess() if self.tp.resultsQueue.empty(): break self.tp.cleanup() self.taskmaster.cleanup() # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.SConsign Writing and reading information to the .sconsign file or files. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/SConsign.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.compat import os # compat layer imports "cPickle" for us if it's available. import pickle import SCons.dblite import SCons.Warnings def corrupt_dblite_warning(filename): SCons.Warnings.warn(SCons.Warnings.CorruptSConsignWarning, "Ignoring corrupt .sconsign file: %s"%filename) SCons.dblite.ignore_corrupt_dbfiles = 1 SCons.dblite.corruption_warning = corrupt_dblite_warning #XXX Get rid of the global array so this becomes re-entrant. sig_files = [] # Info for the database SConsign implementation (now the default): # "DataBase" is a dictionary that maps top-level SConstruct directories # to open database handles. # "DB_Module" is the Python database module to create the handles. # "DB_Name" is the base name of the database file (minus any # extension the underlying DB module will add). DataBase = {} DB_Module = SCons.dblite DB_Name = ".sconsign" DB_sync_list = [] def Get_DataBase(dir): global DataBase, DB_Module, DB_Name top = dir.fs.Top if not os.path.isabs(DB_Name) and top.repositories: mode = "c" for d in [top] + top.repositories: if dir.is_under(d): try: return DataBase[d], mode except KeyError: path = d.entry_abspath(DB_Name) try: db = DataBase[d] = DB_Module.open(path, mode) except (IOError, OSError): pass else: if mode != "r": DB_sync_list.append(db) return db, mode mode = "r" try: return DataBase[top], "c" except KeyError: db = DataBase[top] = DB_Module.open(DB_Name, "c") DB_sync_list.append(db) return db, "c" except TypeError: print "DataBase =", DataBase raise def Reset(): """Reset global state. Used by unit tests that end up using SConsign multiple times to get a clean slate for each test.""" global sig_files, DB_sync_list sig_files = [] DB_sync_list = [] normcase = os.path.normcase def write(): global sig_files for sig_file in sig_files: sig_file.write(sync=0) for db in DB_sync_list: try: syncmethod = db.sync except AttributeError: pass # Not all dbm modules have sync() methods. else: syncmethod() try: closemethod = db.close except AttributeError: pass # Not all dbm modules have close() methods. else: closemethod() class SConsignEntry(object): """ Wrapper class for the generic entry in a .sconsign file. The Node subclass populates it with attributes as it pleases. XXX As coded below, we do expect a '.binfo' attribute to be added, but we'll probably generalize this in the next refactorings. """ current_version_id = 1 def __init__(self): # Create an object attribute from the class attribute so it ends up # in the pickled data in the .sconsign file. _version_id = self.current_version_id def convert_to_sconsign(self): self.binfo.convert_to_sconsign() def convert_from_sconsign(self, dir, name): self.binfo.convert_from_sconsign(dir, name) class Base(object): """ This is the controlling class for the signatures for the collection of entries associated with a specific directory. The actual directory association will be maintained by a subclass that is specific to the underlying storage method. This class provides a common set of methods for fetching and storing the individual bits of information that make up signature entry. """ def __init__(self): self.entries = {} self.dirty = False self.to_be_merged = {} def get_entry(self, filename): """ Fetch the specified entry attribute. """ return self.entries[filename] def set_entry(self, filename, obj): """ Set the entry. """ self.entries[filename] = obj self.dirty = True def do_not_set_entry(self, filename, obj): pass def store_info(self, filename, node): entry = node.get_stored_info() entry.binfo.merge(node.get_binfo()) self.to_be_merged[filename] = node self.dirty = True def do_not_store_info(self, filename, node): pass def merge(self): for key, node in self.to_be_merged.items(): entry = node.get_stored_info() try: ninfo = entry.ninfo except AttributeError: # This happens with SConf Nodes, because the configuration # subsystem takes direct control over how the build decision # is made and its information stored. pass else: ninfo.merge(node.get_ninfo()) self.entries[key] = entry self.to_be_merged = {} class DB(Base): """ A Base subclass that reads and writes signature information from a global .sconsign.db* file--the actual file suffix is determined by the database module. """ def __init__(self, dir): Base.__init__(self) self.dir = dir db, mode = Get_DataBase(dir) # Read using the path relative to the top of the Repository # (self.dir.tpath) from which we're fetching the signature # information. path = normcase(dir.tpath) try: rawentries = db[path] except KeyError: pass else: try: self.entries = pickle.loads(rawentries) if not isinstance(self.entries, dict): self.entries = {} raise TypeError except KeyboardInterrupt: raise except Exception, e: SCons.Warnings.warn(SCons.Warnings.CorruptSConsignWarning, "Ignoring corrupt sconsign entry : %s (%s)\n"%(self.dir.tpath, e)) for key, entry in self.entries.items(): entry.convert_from_sconsign(dir, key) if mode == "r": # This directory is actually under a repository, which means # likely they're reaching in directly for a dependency on # a file there. Don't actually set any entry info, so we # won't try to write to that .sconsign.dblite file. self.set_entry = self.do_not_set_entry self.store_info = self.do_not_store_info global sig_files sig_files.append(self) def write(self, sync=1): if not self.dirty: return self.merge() db, mode = Get_DataBase(self.dir) # Write using the path relative to the top of the SConstruct # directory (self.dir.path), not relative to the top of # the Repository; we only write to our own .sconsign file, # not to .sconsign files in Repositories. path = normcase(self.dir.path) for key, entry in self.entries.items(): entry.convert_to_sconsign() db[path] = pickle.dumps(self.entries, 1) if sync: try: syncmethod = db.sync except AttributeError: # Not all anydbm modules have sync() methods. pass else: syncmethod() class Dir(Base): def __init__(self, fp=None, dir=None): """ fp - file pointer to read entries from """ Base.__init__(self) if not fp: return self.entries = pickle.load(fp) if not isinstance(self.entries, dict): self.entries = {} raise TypeError if dir: for key, entry in self.entries.items(): entry.convert_from_sconsign(dir, key) class DirFile(Dir): """ Encapsulates reading and writing a per-directory .sconsign file. """ def __init__(self, dir): """ dir - the directory for the file """ self.dir = dir self.sconsign = os.path.join(dir.path, '.sconsign') try: fp = open(self.sconsign, 'rb') except IOError: fp = None try: Dir.__init__(self, fp, dir) except KeyboardInterrupt: raise except: SCons.Warnings.warn(SCons.Warnings.CorruptSConsignWarning, "Ignoring corrupt .sconsign file: %s"%self.sconsign) global sig_files sig_files.append(self) def write(self, sync=1): """ Write the .sconsign file to disk. Try to write to a temporary file first, and rename it if we succeed. If we can't write to the temporary file, it's probably because the directory isn't writable (and if so, how did we build anything in this directory, anyway?), so try to write directly to the .sconsign file as a backup. If we can't rename, try to copy the temporary contents back to the .sconsign file. Either way, always try to remove the temporary file at the end. """ if not self.dirty: return self.merge() temp = os.path.join(self.dir.path, '.scons%d' % os.getpid()) try: file = open(temp, 'wb') fname = temp except IOError: try: file = open(self.sconsign, 'wb') fname = self.sconsign except IOError: return for key, entry in self.entries.items(): entry.convert_to_sconsign() pickle.dump(self.entries, file, 1) file.close() if fname != self.sconsign: try: mode = os.stat(self.sconsign)[0] os.chmod(self.sconsign, 0666) os.unlink(self.sconsign) except (IOError, OSError): # Try to carry on in the face of either OSError # (things like permission issues) or IOError (disk # or network issues). If there's a really dangerous # issue, it should get re-raised by the calls below. pass try: os.rename(fname, self.sconsign) except OSError: # An OSError failure to rename may indicate something # like the directory has no write permission, but # the .sconsign file itself might still be writable, # so try writing on top of it directly. An IOError # here, or in any of the following calls, would get # raised, indicating something like a potentially # serious disk or network issue. open(self.sconsign, 'wb').write(open(fname, 'rb').read()) os.chmod(self.sconsign, mode) try: os.unlink(temp) except (IOError, OSError): pass ForDirectory = DB def File(name, dbm_module=None): """ Arrange for all signatures to be stored in a global .sconsign.db* file. """ global ForDirectory, DB_Name, DB_Module if name is None: ForDirectory = DirFile DB_Module = None else: ForDirectory = DB DB_Name = name if not dbm_module is None: DB_Module = dbm_module # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __doc__ = """ collections compatibility module for older (pre-2.4) Python versions This does not not NOT (repeat, *NOT*) provide complete collections functionality. It only wraps the portions of collections functionality used by SCons, in an interface that looks enough like collections for our purposes. """ __revision__ = "src/engine/SCons/compat/_scons_collections.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" # Use exec to hide old names from fixers. exec("""if True: from UserDict import UserDict from UserList import UserList from UserString import UserString""") # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # # Portions of the following are derived from the compat.py file in # Twisted, under the following copyright: # # Copyright (c) 2001-2004 Twisted Matrix Laboratories __doc__ = """ Compatibility idioms for builtins names This module adds names to the builtins module for things that we want to use in SCons but which don't show up until later Python versions than the earliest ones we support. This module checks for the following builtins names: all() any() sorted() memoryview() Implementations of functions are *NOT* guaranteed to be fully compliant with these functions in later versions of Python. We are only concerned with adding functionality that we actually use in SCons, so be wary if you lift this code for other uses. (That said, making these more nearly the same as later, official versions is still a desirable goal, we just don't need to be obsessive about it.) If you're looking at this with pydoc and various names don't show up in the FUNCTIONS or DATA output, that means those names are already built in to this version of Python and we don't need to add them from this module. """ __revision__ = "src/engine/SCons/compat/_scons_builtins.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import builtins try: all except NameError: # Pre-2.5 Python has no all() function. def all(iterable): """ Returns True if all elements of the iterable are true. """ for element in iterable: if not element: return False return True builtins.all = all all = all try: any except NameError: # Pre-2.5 Python has no any() function. def any(iterable): """ Returns True if any element of the iterable is true. """ for element in iterable: if element: return True return False builtins.any = any any = any try: memoryview except NameError: # Pre-2.7 doesn't have the memoryview() built-in. class memoryview(object): def __init__(self, obj): # wrapping buffer in () keeps the fixer from changing it self.obj = (buffer)(obj) def __getitem__(self, indx): if isinstance(indx, slice): return self.obj[indx.start:indx.stop] else: return self.obj[indx] builtins.memoryview = memoryview try: sorted except NameError: # Pre-2.4 Python has no sorted() function. # # The pre-2.4 Python list.sort() method does not support # list.sort(key=) nor list.sort(reverse=) keyword arguments, so # we must implement the functionality of those keyword arguments # by hand instead of passing them to list.sort(). def sorted(iterable, cmp=None, key=None, reverse=False): if key is not None: result = [(key(x), x) for x in iterable] else: result = iterable[:] if cmp is None: # Pre-2.3 Python does not support list.sort(None). result.sort() else: result.sort(cmp) if key is not None: result = [t1 for t0,t1 in result] if reverse: result.reverse() return result builtins.sorted = sorted #if sys.version_info[:3] in ((2, 2, 0), (2, 2, 1)): # def lstrip(s, c=string.whitespace): # while s and s[0] in c: # s = s[1:] # return s # def rstrip(s, c=string.whitespace): # while s and s[-1] in c: # s = s[:-1] # return s # def strip(s, c=string.whitespace, l=lstrip, r=rstrip): # return l(r(s, c), c) # # object.__setattr__(str, 'lstrip', lstrip) # object.__setattr__(str, 'rstrip', rstrip) # object.__setattr__(str, 'strip', strip) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __doc__ = """ io compatibility module for older (pre-2.6) Python versions This does not not NOT (repeat, *NOT*) provide complete io functionality. It only wraps the portions of io functionality used by SCons, in an interface that looks enough like io for our purposes. """ __revision__ = "src/engine/SCons/compat/_scons_io.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" # Use the "imp" module to protect the imports below from fixers. import imp _cStringIO = imp.load_module('cStringIO', *imp.find_module('cStringIO')) StringIO = _cStringIO.StringIO del _cStringIO # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __doc__ = """ hashlib backwards-compatibility module for older (pre-2.5) Python versions This does not not NOT (repeat, *NOT*) provide complete hashlib functionality. It only wraps the portions of MD5 functionality used by SCons, in an interface that looks like hashlib (or enough for our purposes, anyway). In fact, this module will raise an ImportError if the underlying md5 module isn't available. """ __revision__ = "src/engine/SCons/compat/_scons_hashlib.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import md5 from string import hexdigits class md5obj(object): md5_module = md5 def __init__(self, name, string=''): if not name in ('MD5', 'md5'): raise ValueError("unsupported hash type") self.name = 'md5' self.m = self.md5_module.md5() def __repr__(self): return '<%s HASH object @ %#x>' % (self.name, id(self)) def copy(self): import copy result = copy.copy(self) result.m = self.m.copy() return result def digest(self): return self.m.digest() def update(self, arg): return self.m.update(arg) def hexdigest(self): return self.m.hexdigest() new = md5obj def md5(string=''): return md5obj('md5', string) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __doc__ = """ SCons compatibility package for old Python versions This subpackage holds modules that provide backwards-compatible implementations of various things that we'd like to use in SCons but which only show up in later versions of Python than the early, old version(s) we still support. Other code will not generally reference things in this package through the SCons.compat namespace. The modules included here add things to the builtins namespace or the global module list so that the rest of our code can use the objects and names imported here regardless of Python version. Simply enough, things that go in the builtins name space come from our _scons_builtins module. The rest of the things here will be in individual compatibility modules that are either: 1) suitably modified copies of the future modules that we want to use; or 2) backwards compatible re-implementations of the specific portions of a future module's API that we want to use. GENERAL WARNINGS: Implementations of functions in the SCons.compat modules are *NOT* guaranteed to be fully compliant with these functions in later versions of Python. We are only concerned with adding functionality that we actually use in SCons, so be wary if you lift this code for other uses. (That said, making these more nearly the same as later, official versions is still a desirable goal, we just don't need to be obsessive about it.) We name the compatibility modules with an initial '_scons_' (for example, _scons_subprocess.py is our compatibility module for subprocess) so that we can still try to import the real module name and fall back to our compatibility module if we get an ImportError. The import_as() function defined below loads the module as the "real" name (without the '_scons'), after which all of the "import {module}" statements in the rest of our code will find our pre-loaded compatibility module. """ __revision__ = "src/engine/SCons/compat/__init__.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os import sys import imp # Use the "imp" module to protect imports from fixers. def import_as(module, name): """ Imports the specified module (from our local directory) as the specified name, returning the loaded module object. """ dir = os.path.split(__file__)[0] return imp.load_module(name, *imp.find_module(module, [dir])) def rename_module(new, old): """ Attempts to import the old module and load it under the new name. Used for purely cosmetic name changes in Python 3.x. """ try: sys.modules[new] = imp.load_module(old, *imp.find_module(old)) return True except ImportError: return False rename_module('builtins', '__builtin__') import _scons_builtins try: import hashlib except ImportError: # Pre-2.5 Python has no hashlib module. try: import_as('_scons_hashlib', 'hashlib') except ImportError: # If we failed importing our compatibility module, it probably # means this version of Python has no md5 module. Don't do # anything and let the higher layer discover this fact, so it # can fall back to using timestamp. pass try: set except NameError: # Pre-2.4 Python has no native set type import_as('_scons_sets', 'sets') import builtins, sets builtins.set = sets.Set try: import collections except ImportError: # Pre-2.4 Python has no collections module. import_as('_scons_collections', 'collections') else: try: collections.UserDict except AttributeError: exec('from UserDict import UserDict as _UserDict') collections.UserDict = _UserDict del _UserDict try: collections.UserList except AttributeError: exec('from UserList import UserList as _UserList') collections.UserList = _UserList del _UserList try: collections.UserString except AttributeError: exec('from UserString import UserString as _UserString') collections.UserString = _UserString del _UserString try: import io except ImportError: # Pre-2.6 Python has no io module. import_as('_scons_io', 'io') try: os.devnull except AttributeError: # Pre-2.4 Python has no os.devnull attribute _names = sys.builtin_module_names if 'posix' in _names: os.devnull = '/dev/null' elif 'nt' in _names: os.devnull = 'nul' os.path.devnull = os.devnull try: os.path.lexists except AttributeError: # Pre-2.4 Python has no os.path.lexists function def lexists(path): return os.path.exists(path) or os.path.islink(path) os.path.lexists = lexists # When we're using the '-3' option during regression tests, importing # cPickle gives a warning no matter how it's done, so always use the # real profile module, whether it's fast or not. if os.environ.get('SCONS_HORRIBLE_REGRESSION_TEST_HACK') is None: # Not a regression test with '-3', so try to use faster version. # In 3.x, 'pickle' automatically loads the fast version if available. rename_module('pickle', 'cPickle') # In 3.x, 'profile' automatically loads the fast version if available. rename_module('profile', 'cProfile') # Before Python 3.0, the 'queue' module was named 'Queue'. rename_module('queue', 'Queue') # Before Python 3.0, the 'winreg' module was named '_winreg' rename_module('winreg', '_winreg') try: import subprocess except ImportError: # Pre-2.4 Python has no subprocess module. import_as('_scons_subprocess', 'subprocess') try: sys.intern except AttributeError: # Pre-2.6 Python has no sys.intern() function. import builtins try: sys.intern = builtins.intern except AttributeError: # Pre-2.x Python has no builtin intern() function. def intern(x): return x sys.intern = intern del intern try: sys.maxsize except AttributeError: # Pre-2.6 Python has no sys.maxsize attribute # Wrapping sys in () is silly, but protects it from 2to3 renames fixer sys.maxsize = (sys).maxint if os.environ.get('SCONS_HORRIBLE_REGRESSION_TEST_HACK') is not None: # We can't apply the 'callable' fixer until the floor is 2.6, but the # '-3' option to Python 2.6 and 2.7 generates almost ten thousand # warnings. This hack allows us to run regression tests with the '-3' # option by replacing the callable() built-in function with a hack # that performs the same function but doesn't generate the warning. # Note that this hack is ONLY intended to be used for regression # testing, and should NEVER be used for real runs. from types import ClassType def callable(obj): if hasattr(obj, '__call__'): return True if isinstance(obj, (ClassType, type)): return True return False import builtins builtins.callable = callable del callable # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __doc__ = """ dbm compatibility module for Python versions that don't have dbm. This does not not NOT (repeat, *NOT*) provide complete dbm functionality. It's just a stub on which to hang just enough pieces of dbm functionality that the whichdb.whichdb() implementstation in the various 2.X versions of Python won't blow up even if dbm wasn't compiled in. """ __revision__ = "src/engine/SCons/compat/_scons_dbm.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" class error(Exception): pass def open(*args, **kw): raise error() # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""Classes to represent arbitrary sets (including sets of sets). This module implements sets using dictionaries whose values are ignored. The usual operations (union, intersection, deletion, etc.) are provided as both methods and operators. Important: sets are not sequences! While they support 'x in s', 'len(s)', and 'for x in s', none of those operations are unique for sequences; for example, mappings support all three as well. The characteristic operation for sequences is subscripting with small integers: s[i], for i in range(len(s)). Sets don't support subscripting at all. Also, sequences allow multiple occurrences and their elements have a definite order; sets on the other hand don't record multiple occurrences and don't remember the order of element insertion (which is why they don't support s[i]). The following classes are provided: BaseSet -- All the operations common to both mutable and immutable sets. This is an abstract class, not meant to be directly instantiated. Set -- Mutable sets, subclass of BaseSet; not hashable. ImmutableSet -- Immutable sets, subclass of BaseSet; hashable. An iterable argument is mandatory to create an ImmutableSet. _TemporarilyImmutableSet -- A wrapper around a Set, hashable, giving the same hash value as the immutable set equivalent would have. Do not use this class directly. Only hashable objects can be added to a Set. In particular, you cannot really add a Set as an element to another Set; if you try, what is actually added is an ImmutableSet built from it (it compares equal to the one you tried adding). When you ask if `x in y' where x is a Set and y is a Set or ImmutableSet, x is wrapped into a _TemporarilyImmutableSet z, and what's tested is actually `z in y'. """ # Code history: # # - Greg V. Wilson wrote the first version, using a different approach # to the mutable/immutable problem, and inheriting from dict. # # - Alex Martelli modified Greg's version to implement the current # Set/ImmutableSet approach, and make the data an attribute. # # - Guido van Rossum rewrote much of the code, made some API changes, # and cleaned up the docstrings. # # - Raymond Hettinger added a number of speedups and other # improvements. # protect this import from the fixers... exec('from itertools import ifilterfalse as filterfalse') __all__ = ['BaseSet', 'Set', 'ImmutableSet'] class BaseSet(object): """Common base class for mutable and immutable sets.""" __slots__ = ['_data'] # Constructor def __init__(self): """This is an abstract class.""" # Don't call this from a concrete subclass! if self.__class__ is BaseSet: raise TypeError("BaseSet is an abstract class. " "Use Set or ImmutableSet.") # Standard protocols: __len__, __repr__, __str__, __iter__ def __len__(self): """Return the number of elements of a set.""" return len(self._data) def __repr__(self): """Return string representation of a set. This looks like 'Set([<list of elements>])'. """ return self._repr() # __str__ is the same as __repr__ __str__ = __repr__ def _repr(self, sort_them=False): elements = list(self._data.keys()) if sort_them: elements.sort() return '%s(%r)' % (self.__class__.__name__, elements) def __iter__(self): """Return an iterator over the elements or a set. This is the keys iterator for the underlying dict. """ # Wrapping name in () prevents fixer from "fixing" this return (self._data.iterkeys)() # Three-way comparison is not supported. However, because __eq__ is # tried before __cmp__, if Set x == Set y, x.__eq__(y) returns True and # then cmp(x, y) returns 0 (Python doesn't actually call __cmp__ in this # case). def __cmp__(self, other): raise TypeError("can't compare sets using cmp()") # Equality comparisons using the underlying dicts. Mixed-type comparisons # are allowed here, where Set == z for non-Set z always returns False, # and Set != z always True. This allows expressions like "x in y" to # give the expected result when y is a sequence of mixed types, not # raising a pointless TypeError just because y contains a Set, or x is # a Set and y contain's a non-set ("in" invokes only __eq__). # Subtle: it would be nicer if __eq__ and __ne__ could return # NotImplemented instead of True or False. Then the other comparand # would get a chance to determine the result, and if the other comparand # also returned NotImplemented then it would fall back to object address # comparison (which would always return False for __eq__ and always # True for __ne__). However, that doesn't work, because this type # *also* implements __cmp__: if, e.g., __eq__ returns NotImplemented, # Python tries __cmp__ next, and the __cmp__ here then raises TypeError. def __eq__(self, other): if isinstance(other, BaseSet): return self._data == other._data else: return False def __ne__(self, other): if isinstance(other, BaseSet): return self._data != other._data else: return True # Copying operations def copy(self): """Return a shallow copy of a set.""" result = self.__class__() result._data.update(self._data) return result __copy__ = copy # For the copy module def __deepcopy__(self, memo): """Return a deep copy of a set; used by copy module.""" # This pre-creates the result and inserts it in the memo # early, in case the deep copy recurses into another reference # to this same set. A set can't be an element of itself, but # it can certainly contain an object that has a reference to # itself. from copy import deepcopy result = self.__class__() memo[id(self)] = result data = result._data value = True for elt in self: data[deepcopy(elt, memo)] = value return result # Standard set operations: union, intersection, both differences. # Each has an operator version (e.g. __or__, invoked with |) and a # method version (e.g. union). # Subtle: Each pair requires distinct code so that the outcome is # correct when the type of other isn't suitable. For example, if # we did "union = __or__" instead, then Set().union(3) would return # NotImplemented instead of raising TypeError (albeit that *why* it # raises TypeError as-is is also a bit subtle). def __or__(self, other): """Return the union of two sets as a new set. (I.e. all elements that are in either set.) """ if not isinstance(other, BaseSet): return NotImplemented return self.union(other) def union(self, other): """Return the union of two sets as a new set. (I.e. all elements that are in either set.) """ result = self.__class__(self) result._update(other) return result def __and__(self, other): """Return the intersection of two sets as a new set. (I.e. all elements that are in both sets.) """ if not isinstance(other, BaseSet): return NotImplemented return self.intersection(other) def intersection(self, other): """Return the intersection of two sets as a new set. (I.e. all elements that are in both sets.) """ if not isinstance(other, BaseSet): other = Set(other) if len(self) <= len(other): little, big = self, other else: little, big = other, self common = iter(filter(big._data.has_key, little)) return self.__class__(common) def __xor__(self, other): """Return the symmetric difference of two sets as a new set. (I.e. all elements that are in exactly one of the sets.) """ if not isinstance(other, BaseSet): return NotImplemented return self.symmetric_difference(other) def symmetric_difference(self, other): """Return the symmetric difference of two sets as a new set. (I.e. all elements that are in exactly one of the sets.) """ result = self.__class__() data = result._data value = True selfdata = self._data try: otherdata = other._data except AttributeError: otherdata = Set(other)._data for elt in filterfalse(otherdata.has_key, selfdata): data[elt] = value for elt in filterfalse(selfdata.has_key, otherdata): data[elt] = value return result def __sub__(self, other): """Return the difference of two sets as a new Set. (I.e. all elements that are in this set and not in the other.) """ if not isinstance(other, BaseSet): return NotImplemented return self.difference(other) def difference(self, other): """Return the difference of two sets as a new Set. (I.e. all elements that are in this set and not in the other.) """ result = self.__class__() data = result._data try: otherdata = other._data except AttributeError: otherdata = Set(other)._data value = True for elt in filterfalse(otherdata.has_key, self): data[elt] = value return result # Membership test def __contains__(self, element): """Report whether an element is a member of a set. (Called in response to the expression `element in self'.) """ try: return element in self._data except TypeError: transform = getattr(element, "__as_temporarily_immutable__", None) if transform is None: raise # re-raise the TypeError exception we caught return transform() in self._data # Subset and superset test def issubset(self, other): """Report whether another set contains this set.""" self._binary_sanity_check(other) if len(self) > len(other): # Fast check for obvious cases return False for elt in filterfalse(other._data.has_key, self): return False return True def issuperset(self, other): """Report whether this set contains another set.""" self._binary_sanity_check(other) if len(self) < len(other): # Fast check for obvious cases return False for elt in filterfalse(self._data.has_key, other): return False return True # Inequality comparisons using the is-subset relation. __le__ = issubset __ge__ = issuperset def __lt__(self, other): self._binary_sanity_check(other) return len(self) < len(other) and self.issubset(other) def __gt__(self, other): self._binary_sanity_check(other) return len(self) > len(other) and self.issuperset(other) # Assorted helpers def _binary_sanity_check(self, other): # Check that the other argument to a binary operation is also # a set, raising a TypeError otherwise. if not isinstance(other, BaseSet): raise TypeError("Binary operation only permitted between sets") def _compute_hash(self): # Calculate hash code for a set by xor'ing the hash codes of # the elements. This ensures that the hash code does not depend # on the order in which elements are added to the set. This is # not called __hash__ because a BaseSet should not be hashable; # only an ImmutableSet is hashable. result = 0 for elt in self: result ^= hash(elt) return result def _update(self, iterable): # The main loop for update() and the subclass __init__() methods. data = self._data # Use the fast update() method when a dictionary is available. if isinstance(iterable, BaseSet): data.update(iterable._data) return value = True if type(iterable) in (list, tuple, xrange): # Optimized: we know that __iter__() and next() can't # raise TypeError, so we can move 'try:' out of the loop. it = iter(iterable) while True: try: for element in it: data[element] = value return except TypeError: transform = getattr(element, "__as_immutable__", None) if transform is None: raise # re-raise the TypeError exception we caught data[transform()] = value else: # Safe: only catch TypeError where intended for element in iterable: try: data[element] = value except TypeError: transform = getattr(element, "__as_immutable__", None) if transform is None: raise # re-raise the TypeError exception we caught data[transform()] = value class ImmutableSet(BaseSet): """Immutable set class.""" __slots__ = ['_hashcode'] # BaseSet + hashing def __init__(self, iterable=None): """Construct an immutable set from an optional iterable.""" self._hashcode = None self._data = {} if iterable is not None: self._update(iterable) def __hash__(self): if self._hashcode is None: self._hashcode = self._compute_hash() return self._hashcode def __getstate__(self): return self._data, self._hashcode def __setstate__(self, state): self._data, self._hashcode = state class Set(BaseSet): """ Mutable set class.""" __slots__ = [] # BaseSet + operations requiring mutability; no hashing def __init__(self, iterable=None): """Construct a set from an optional iterable.""" self._data = {} if iterable is not None: self._update(iterable) def __getstate__(self): # getstate's results are ignored if it is not return self._data, def __setstate__(self, data): self._data, = data def __hash__(self): """A Set cannot be hashed.""" # We inherit object.__hash__, so we must deny this explicitly raise TypeError("Can't hash a Set, only an ImmutableSet.") # In-place union, intersection, differences. # Subtle: The xyz_update() functions deliberately return None, # as do all mutating operations on built-in container types. # The __xyz__ spellings have to return self, though. def __ior__(self, other): """Update a set with the union of itself and another.""" self._binary_sanity_check(other) self._data.update(other._data) return self def union_update(self, other): """Update a set with the union of itself and another.""" self._update(other) def __iand__(self, other): """Update a set with the intersection of itself and another.""" self._binary_sanity_check(other) self._data = (self & other)._data return self def intersection_update(self, other): """Update a set with the intersection of itself and another.""" if isinstance(other, BaseSet): self &= other else: self._data = (self.intersection(other))._data def __ixor__(self, other): """Update a set with the symmetric difference of itself and another.""" self._binary_sanity_check(other) self.symmetric_difference_update(other) return self def symmetric_difference_update(self, other): """Update a set with the symmetric difference of itself and another.""" data = self._data value = True if not isinstance(other, BaseSet): other = Set(other) if self is other: self.clear() for elt in other: if elt in data: del data[elt] else: data[elt] = value def __isub__(self, other): """Remove all elements of another set from this set.""" self._binary_sanity_check(other) self.difference_update(other) return self def difference_update(self, other): """Remove all elements of another set from this set.""" data = self._data if not isinstance(other, BaseSet): other = Set(other) if self is other: self.clear() for elt in filter(data.has_key, other): del data[elt] # Python dict-like mass mutations: update, clear def update(self, iterable): """Add all values from an iterable (such as a list or file).""" self._update(iterable) def clear(self): """Remove all elements from this set.""" self._data.clear() # Single-element mutations: add, remove, discard def add(self, element): """Add an element to a set. This has no effect if the element is already present. """ try: self._data[element] = True except TypeError: transform = getattr(element, "__as_immutable__", None) if transform is None: raise # re-raise the TypeError exception we caught self._data[transform()] = True def remove(self, element): """Remove an element from a set; it must be a member. If the element is not a member, raise a KeyError. """ try: del self._data[element] except TypeError: transform = getattr(element, "__as_temporarily_immutable__", None) if transform is None: raise # re-raise the TypeError exception we caught del self._data[transform()] def discard(self, element): """Remove an element from a set if it is a member. If the element is not a member, do nothing. """ try: self.remove(element) except KeyError: pass def pop(self): """Remove and return an arbitrary set element.""" return self._data.popitem()[0] def __as_immutable__(self): # Return a copy of self as an immutable set return ImmutableSet(self) def __as_temporarily_immutable__(self): # Return self wrapped in a temporarily immutable set return _TemporarilyImmutableSet(self) class _TemporarilyImmutableSet(BaseSet): # Wrap a mutable set as if it was temporarily immutable. # This only supplies hashing and equality comparisons. def __init__(self, set): self._set = set self._data = set._data # Needed by ImmutableSet.__eq__() def __hash__(self): return self._set._compute_hash() # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
# subprocess - Subprocesses with accessible I/O streams # # For more information about this module, see PEP 324. # # This module should remain compatible with Python 2.2, see PEP 291. # # Copyright (c) 2003-2005 by Peter Astrand <astrand@lysator.liu.se> # # Licensed to PSF under a Contributor Agreement. # See http://www.python.org/2.4/license for licensing details. r"""subprocess - Subprocesses with accessible I/O streams This module allows you to spawn processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several other, older modules and functions, like: os.system os.spawn* os.popen* popen2.* commands.* Information about how the subprocess module can be used to replace these modules and functions can be found below. Using the subprocess module =========================== This module defines one class called Popen: class Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0): Arguments are: args should be a string, or a sequence of program arguments. The program to execute is normally the first item in the args sequence or string, but can be explicitly set by using the executable argument. On UNIX, with shell=False (default): In this case, the Popen class uses os.execvp() to execute the child program. args should normally be a sequence. A string will be treated as a sequence with the string as the only item (the program to execute). On UNIX, with shell=True: If args is a string, it specifies the command string to execute through the shell. If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional shell arguments. On Windows: the Popen class uses CreateProcess() to execute the child program, which operates on strings. If args is a sequence, it will be converted to a string using the list2cmdline method. Please note that not all MS Windows applications interpret the command line the same way: The list2cmdline is designed for applications using the same rules as the MS C runtime. bufsize, if given, has the same meaning as the corresponding argument to the built-in open() function: 0 means unbuffered, 1 means line buffered, any other positive value means use a buffer of (approximately) that size. A negative bufsize means to use the system default, which usually means fully buffered. The default value for bufsize is 0 (unbuffered). stdin, stdout and stderr specify the executed programs' standard input, standard output and standard error file handles, respectively. Valid values are PIPE, an existing file descriptor (a positive integer), an existing file object, and None. PIPE indicates that a new pipe to the child should be created. With None, no redirection will occur; the child's file handles will be inherited from the parent. Additionally, stderr can be STDOUT, which indicates that the stderr data from the applications should be captured into the same file handle as for stdout. If preexec_fn is set to a callable object, this object will be called in the child process just before the child is executed. If close_fds is true, all file descriptors except 0, 1 and 2 will be closed before the child process is executed. if shell is true, the specified command will be executed through the shell. If cwd is not None, the current directory will be changed to cwd before the child is executed. If env is not None, it defines the environment variables for the new process. If universal_newlines is true, the file objects stdout and stderr are opened as a text files, but lines may be terminated by any of '\n', the Unix end-of-line convention, '\r', the Macintosh convention or '\r\n', the Windows convention. All of these external representations are seen as '\n' by the Python program. Note: This feature is only available if Python is built with universal newline support (the default). Also, the newlines attribute of the file objects stdout, stdin and stderr are not updated by the communicate() method. The startupinfo and creationflags, if given, will be passed to the underlying CreateProcess() function. They can specify things such as appearance of the main window and priority for the new process. (Windows only) This module also defines two shortcut functions: call(*popenargs, **kwargs): Run command with arguments. Wait for command to complete, then return the returncode attribute. The arguments are the same as for the Popen constructor. Example: retcode = call(["ls", "-l"]) check_call(*popenargs, **kwargs): Run command with arguments. Wait for command to complete. If the exit code was zero then return, otherwise raise CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute. The arguments are the same as for the Popen constructor. Example: check_call(["ls", "-l"]) Exceptions ---------- Exceptions raised in the child process, before the new program has started to execute, will be re-raised in the parent. Additionally, the exception object will have one extra attribute called 'child_traceback', which is a string containing traceback information from the childs point of view. The most common exception raised is OSError. This occurs, for example, when trying to execute a non-existent file. Applications should prepare for OSErrors. A ValueError will be raised if Popen is called with invalid arguments. check_call() will raise CalledProcessError, if the called process returns a non-zero return code. Security -------- Unlike some other popen functions, this implementation will never call /bin/sh implicitly. This means that all characters, including shell metacharacters, can safely be passed to child processes. Popen objects ============= Instances of the Popen class have the following methods: poll() Check if child process has terminated. Returns returncode attribute. wait() Wait for child process to terminate. Returns returncode attribute. communicate(input=None) Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional stdin argument should be a string to be sent to the child process, or None, if no data should be sent to the child. communicate() returns a tuple (stdout, stderr). Note: The data read is buffered in memory, so do not use this method if the data size is large or unlimited. The following attributes are also available: stdin If the stdin argument is PIPE, this attribute is a file object that provides input to the child process. Otherwise, it is None. stdout If the stdout argument is PIPE, this attribute is a file object that provides output from the child process. Otherwise, it is None. stderr If the stderr argument is PIPE, this attribute is file object that provides error output from the child process. Otherwise, it is None. pid The process ID of the child process. returncode The child return code. A None value indicates that the process hasn't terminated yet. A negative value -N indicates that the child was terminated by signal N (UNIX only). Replacing older functions with the subprocess module ==================================================== In this section, "a ==> b" means that b can be used as a replacement for a. Note: All functions in this section fail (more or less) silently if the executed program cannot be found; this module raises an OSError exception. In the following examples, we assume that the subprocess module is imported with "from subprocess import *". Replacing /bin/sh shell backquote --------------------------------- output=`mycmd myarg` ==> output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0] Replacing shell pipe line ------------------------- output=`dmesg | grep hda` ==> p1 = Popen(["dmesg"], stdout=PIPE) p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) output = p2.communicate()[0] Replacing os.system() --------------------- sts = os.system("mycmd" + " myarg") ==> p = Popen("mycmd" + " myarg", shell=True) pid, sts = os.waitpid(p.pid, 0) Note: * Calling the program through the shell is usually not required. * It's easier to look at the returncode attribute than the exitstatus. A more real-world example would look like this: try: retcode = call("mycmd" + " myarg", shell=True) if retcode < 0: print >>sys.stderr, "Child was terminated by signal", -retcode else: print >>sys.stderr, "Child returned", retcode except OSError, e: print >>sys.stderr, "Execution failed:", e Replacing os.spawn* ------------------- P_NOWAIT example: pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg") ==> pid = Popen(["/bin/mycmd", "myarg"]).pid P_WAIT example: retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg") ==> retcode = call(["/bin/mycmd", "myarg"]) Vector example: os.spawnvp(os.P_NOWAIT, path, args) ==> Popen([path] + args[1:]) Environment example: os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env) ==> Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"}) Replacing os.popen* ------------------- pipe = os.popen(cmd, mode='r', bufsize) ==> pipe = Popen(cmd, shell=True, bufsize=bufsize, stdout=PIPE).stdout pipe = os.popen(cmd, mode='w', bufsize) ==> pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin (child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize) ==> p = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE, stdout=PIPE, close_fds=True) (child_stdin, child_stdout) = (p.stdin, p.stdout) (child_stdin, child_stdout, child_stderr) = os.popen3(cmd, mode, bufsize) ==> p = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) (child_stdin, child_stdout, child_stderr) = (p.stdin, p.stdout, p.stderr) (child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize) ==> p = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout) Replacing popen2.* ------------------ Note: If the cmd argument to popen2 functions is a string, the command is executed through /bin/sh. If it is a list, the command is directly executed. (child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode) ==> p = Popen(["somestring"], shell=True, bufsize=bufsize stdin=PIPE, stdout=PIPE, close_fds=True) (child_stdout, child_stdin) = (p.stdout, p.stdin) (child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode) ==> p = Popen(["mycmd", "myarg"], bufsize=bufsize, stdin=PIPE, stdout=PIPE, close_fds=True) (child_stdout, child_stdin) = (p.stdout, p.stdin) The popen2.Popen3 and popen3.Popen4 basically works as subprocess.Popen, except that: * subprocess.Popen raises an exception if the execution fails * the capturestderr argument is replaced with the stderr argument. * stdin=PIPE and stdout=PIPE must be specified. * popen2 closes all filedescriptors by default, but you have to specify close_fds=True with subprocess.Popen. """ import sys mswindows = (sys.platform == "win32") import os import types import traceback # Exception classes used by this module. class CalledProcessError(Exception): """This exception is raised when a process run by check_call() returns a non-zero exit status. The exit status will be stored in the returncode attribute.""" def __init__(self, returncode, cmd): self.returncode = returncode self.cmd = cmd def __str__(self): return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode) if mswindows: try: import threading except ImportError: # SCons: the threading module is only used by the communicate() # method, which we don't actually use, so don't worry if we # can't import it. pass import msvcrt try: # Try to get _subprocess from _subprocess import * class STARTUPINFO(object): dwFlags = 0 hStdInput = None hStdOutput = None hStdError = None wShowWindow = 0 class pywintypes(object): error = IOError except ImportError: # If not there, then drop back to requiring pywin32 # TODO: Should this be wrapped in try as well? To notify user to install # pywin32 ? With URL to it? import pywintypes from win32api import GetStdHandle, STD_INPUT_HANDLE, \ STD_OUTPUT_HANDLE, STD_ERROR_HANDLE from win32api import GetCurrentProcess, DuplicateHandle, \ GetModuleFileName, GetVersion from win32con import DUPLICATE_SAME_ACCESS, SW_HIDE from win32pipe import CreatePipe from win32process import CreateProcess, STARTUPINFO, \ GetExitCodeProcess, STARTF_USESTDHANDLES, \ STARTF_USESHOWWINDOW, CREATE_NEW_CONSOLE from win32event import WaitForSingleObject, INFINITE, WAIT_OBJECT_0 else: import select import errno import fcntl import pickle try: fcntl.F_GETFD except AttributeError: fcntl.F_GETFD = 1 try: fcntl.F_SETFD except AttributeError: fcntl.F_SETFD = 2 __all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", "CalledProcessError"] try: MAXFD = os.sysconf("SC_OPEN_MAX") except KeyboardInterrupt: raise # SCons: don't swallow keyboard interrupts except: MAXFD = 256 try: isinstance(1, int) except TypeError: def is_int(obj): return isinstance(obj, type(1)) def is_int_or_long(obj): return type(obj) in (type(1), type(1L)) else: def is_int(obj): return isinstance(obj, int) def is_int_or_long(obj): return isinstance(obj, (int, long)) try: types.StringTypes except AttributeError: try: types.StringTypes = (str, unicode) except NameError: types.StringTypes = (str,) def is_string(obj): return isinstance(obj, types.StringTypes) _active = [] def _cleanup(): for inst in _active[:]: if inst.poll(_deadstate=sys.maxsize) >= 0: try: _active.remove(inst) except ValueError: # This can happen if two threads create a new Popen instance. # It's harmless that it was already removed, so ignore. pass PIPE = -1 STDOUT = -2 def call(*popenargs, **kwargs): """Run command with arguments. Wait for command to complete, then return the returncode attribute. The arguments are the same as for the Popen constructor. Example: retcode = call(["ls", "-l"]) """ return apply(Popen, popenargs, kwargs).wait() def check_call(*popenargs, **kwargs): """Run command with arguments. Wait for command to complete. If the exit code was zero then return, otherwise raise CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute. The arguments are the same as for the Popen constructor. Example: check_call(["ls", "-l"]) """ retcode = call(*popenargs, **kwargs) cmd = kwargs.get("args") if cmd is None: cmd = popenargs[0] if retcode: raise CalledProcessError(retcode, cmd) return retcode def list2cmdline(seq): """ Translate a sequence of arguments into a command line string, using the same rules as the MS C runtime: 1) Arguments are delimited by white space, which is either a space or a tab. 2) A string surrounded by double quotation marks is interpreted as a single argument, regardless of white space contained within. A quoted string can be embedded in an argument. 3) A double quotation mark preceded by a backslash is interpreted as a literal double quotation mark. 4) Backslashes are interpreted literally, unless they immediately precede a double quotation mark. 5) If backslashes immediately precede a double quotation mark, every pair of backslashes is interpreted as a literal backslash. If the number of backslashes is odd, the last backslash escapes the next double quotation mark as described in rule 3. """ # See # http://msdn.microsoft.com/library/en-us/vccelng/htm/progs_12.asp result = [] needquote = False for arg in seq: bs_buf = [] # Add a space to separate this argument from the others if result: result.append(' ') needquote = (" " in arg) or ("\t" in arg) if needquote: result.append('"') for c in arg: if c == '\\': # Don't know if we need to double yet. bs_buf.append(c) elif c == '"': # Double backspaces. result.append('\\' * len(bs_buf)*2) bs_buf = [] result.append('\\"') else: # Normal char if bs_buf: result.extend(bs_buf) bs_buf = [] result.append(c) # Add remaining backspaces, if any. if bs_buf: result.extend(bs_buf) if needquote: result.extend(bs_buf) result.append('"') return ''.join(result) class Popen(object): def __init__(self, args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0): """Create new Popen instance.""" _cleanup() self._child_created = False if not is_int_or_long(bufsize): raise TypeError("bufsize must be an integer") if mswindows: if preexec_fn is not None: raise ValueError("preexec_fn is not supported on Windows " "platforms") if close_fds: raise ValueError("close_fds is not supported on Windows " "platforms") else: # POSIX if startupinfo is not None: raise ValueError("startupinfo is only supported on Windows " "platforms") if creationflags != 0: raise ValueError("creationflags is only supported on Windows " "platforms") self.stdin = None self.stdout = None self.stderr = None self.pid = None self.returncode = None self.universal_newlines = universal_newlines # Input and output objects. The general principle is like # this: # # Parent Child # ------ ----- # p2cwrite ---stdin---> p2cread # c2pread <--stdout--- c2pwrite # errread <--stderr--- errwrite # # On POSIX, the child objects are file descriptors. On # Windows, these are Windows file handles. The parent objects # are file descriptors on both platforms. The parent objects # are None when not using PIPEs. The child objects are None # when not redirecting. (p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite) = self._get_handles(stdin, stdout, stderr) self._execute_child(args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite) if p2cwrite: self.stdin = os.fdopen(p2cwrite, 'wb', bufsize) if c2pread: if universal_newlines: self.stdout = os.fdopen(c2pread, 'rU', bufsize) else: self.stdout = os.fdopen(c2pread, 'rb', bufsize) if errread: if universal_newlines: self.stderr = os.fdopen(errread, 'rU', bufsize) else: self.stderr = os.fdopen(errread, 'rb', bufsize) def _translate_newlines(self, data): data = data.replace("\r\n", "\n") data = data.replace("\r", "\n") return data def __del__(self): if not self._child_created: # We didn't get to successfully create a child process. return # In case the child hasn't been waited on, check if it's done. self.poll(_deadstate=sys.maxsize) if self.returncode is None and _active is not None: # Child is still running, keep us alive until we can wait on it. _active.append(self) def communicate(self, input=None): """Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child. communicate() returns a tuple (stdout, stderr).""" # Optimization: If we are only using one pipe, or no pipe at # all, using select() or threads is unnecessary. if [self.stdin, self.stdout, self.stderr].count(None) >= 2: stdout = None stderr = None if self.stdin: if input: self.stdin.write(input) self.stdin.close() elif self.stdout: stdout = self.stdout.read() elif self.stderr: stderr = self.stderr.read() self.wait() return (stdout, stderr) return self._communicate(input) if mswindows: # # Windows methods # def _get_handles(self, stdin, stdout, stderr): """Construct and return tupel with IO objects: p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite """ if stdin is None and stdout is None and stderr is None: return (None, None, None, None, None, None) p2cread, p2cwrite = None, None c2pread, c2pwrite = None, None errread, errwrite = None, None if stdin is None: p2cread = GetStdHandle(STD_INPUT_HANDLE) elif stdin == PIPE: p2cread, p2cwrite = CreatePipe(None, 0) # Detach and turn into fd p2cwrite = p2cwrite.Detach() p2cwrite = msvcrt.open_osfhandle(p2cwrite, 0) elif is_int(stdin): p2cread = msvcrt.get_osfhandle(stdin) else: # Assuming file-like object p2cread = msvcrt.get_osfhandle(stdin.fileno()) p2cread = self._make_inheritable(p2cread) if stdout is None: c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE) elif stdout == PIPE: c2pread, c2pwrite = CreatePipe(None, 0) # Detach and turn into fd c2pread = c2pread.Detach() c2pread = msvcrt.open_osfhandle(c2pread, 0) elif is_int(stdout): c2pwrite = msvcrt.get_osfhandle(stdout) else: # Assuming file-like object c2pwrite = msvcrt.get_osfhandle(stdout.fileno()) c2pwrite = self._make_inheritable(c2pwrite) if stderr is None: errwrite = GetStdHandle(STD_ERROR_HANDLE) elif stderr == PIPE: errread, errwrite = CreatePipe(None, 0) # Detach and turn into fd errread = errread.Detach() errread = msvcrt.open_osfhandle(errread, 0) elif stderr == STDOUT: errwrite = c2pwrite elif is_int(stderr): errwrite = msvcrt.get_osfhandle(stderr) else: # Assuming file-like object errwrite = msvcrt.get_osfhandle(stderr.fileno()) errwrite = self._make_inheritable(errwrite) return (p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite) def _make_inheritable(self, handle): """Return a duplicate of handle, which is inheritable""" return DuplicateHandle(GetCurrentProcess(), handle, GetCurrentProcess(), 0, 1, DUPLICATE_SAME_ACCESS) def _find_w9xpopen(self): """Find and return absolut path to w9xpopen.exe""" w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)), "w9xpopen.exe") if not os.path.exists(w9xpopen): # Eeek - file-not-found - possibly an embedding # situation - see if we can locate it in sys.exec_prefix w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix), "w9xpopen.exe") if not os.path.exists(w9xpopen): raise RuntimeError("Cannot locate w9xpopen.exe, which is " "needed for Popen to work with your " "shell or platform.") return w9xpopen def _execute_child(self, args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite): """Execute program (MS Windows version)""" if not isinstance(args, types.StringTypes): args = list2cmdline(args) # Process startup details if startupinfo is None: startupinfo = STARTUPINFO() if None not in (p2cread, c2pwrite, errwrite): startupinfo.dwFlags = startupinfo.dwFlags | STARTF_USESTDHANDLES startupinfo.hStdInput = p2cread startupinfo.hStdOutput = c2pwrite startupinfo.hStdError = errwrite if shell: startupinfo.dwFlags = startupinfo.dwFlags | STARTF_USESHOWWINDOW startupinfo.wShowWindow = SW_HIDE comspec = os.environ.get("COMSPEC", "cmd.exe") args = comspec + " /c " + args if (GetVersion() >= 0x80000000L or os.path.basename(comspec).lower() == "command.com"): # Win9x, or using command.com on NT. We need to # use the w9xpopen intermediate program. For more # information, see KB Q150956 # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp) w9xpopen = self._find_w9xpopen() args = '"%s" %s' % (w9xpopen, args) # Not passing CREATE_NEW_CONSOLE has been known to # cause random failures on win9x. Specifically a # dialog: "Your program accessed mem currently in # use at xxx" and a hopeful warning about the # stability of your system. Cost is Ctrl+C wont # kill children. creationflags = creationflags | CREATE_NEW_CONSOLE # Start the process try: hp, ht, pid, tid = CreateProcess(executable, args, # no special security None, None, # must inherit handles to pass std # handles 1, creationflags, env, cwd, startupinfo) except pywintypes.error, e: # Translate pywintypes.error to WindowsError, which is # a subclass of OSError. FIXME: We should really # translate errno using _sys_errlist (or simliar), but # how can this be done from Python? raise WindowsError(*e.args) # Retain the process handle, but close the thread handle self._child_created = True self._handle = hp self.pid = pid ht.Close() # Child is launched. Close the parent's copy of those pipe # handles that only the child should have open. You need # to make sure that no handles to the write end of the # output pipe are maintained in this process or else the # pipe will not close when the child process exits and the # ReadFile will hang. if p2cread is not None: p2cread.Close() if c2pwrite is not None: c2pwrite.Close() if errwrite is not None: errwrite.Close() def poll(self, _deadstate=None): """Check if child process has terminated. Returns returncode attribute.""" if self.returncode is None: if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0: self.returncode = GetExitCodeProcess(self._handle) return self.returncode def wait(self): """Wait for child process to terminate. Returns returncode attribute.""" if self.returncode is None: obj = WaitForSingleObject(self._handle, INFINITE) self.returncode = GetExitCodeProcess(self._handle) return self.returncode def _readerthread(self, fh, buffer): buffer.append(fh.read()) def _communicate(self, input): stdout = None # Return stderr = None # Return if self.stdout: stdout = [] stdout_thread = threading.Thread(target=self._readerthread, args=(self.stdout, stdout)) stdout_thread.setDaemon(True) stdout_thread.start() if self.stderr: stderr = [] stderr_thread = threading.Thread(target=self._readerthread, args=(self.stderr, stderr)) stderr_thread.setDaemon(True) stderr_thread.start() if self.stdin: if input is not None: self.stdin.write(input) self.stdin.close() if self.stdout: stdout_thread.join() if self.stderr: stderr_thread.join() # All data exchanged. Translate lists into strings. if stdout is not None: stdout = stdout[0] if stderr is not None: stderr = stderr[0] # Translate newlines, if requested. We cannot let the file # object do the translation: It is based on stdio, which is # impossible to combine with select (unless forcing no # buffering). if self.universal_newlines and hasattr(file, 'newlines'): if stdout: stdout = self._translate_newlines(stdout) if stderr: stderr = self._translate_newlines(stderr) self.wait() return (stdout, stderr) else: # # POSIX methods # def _get_handles(self, stdin, stdout, stderr): """Construct and return tupel with IO objects: p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite """ p2cread, p2cwrite = None, None c2pread, c2pwrite = None, None errread, errwrite = None, None if stdin is None: pass elif stdin == PIPE: p2cread, p2cwrite = os.pipe() elif is_int(stdin): p2cread = stdin else: # Assuming file-like object p2cread = stdin.fileno() if stdout is None: pass elif stdout == PIPE: c2pread, c2pwrite = os.pipe() elif is_int(stdout): c2pwrite = stdout else: # Assuming file-like object c2pwrite = stdout.fileno() if stderr is None: pass elif stderr == PIPE: errread, errwrite = os.pipe() elif stderr == STDOUT: errwrite = c2pwrite elif is_int(stderr): errwrite = stderr else: # Assuming file-like object errwrite = stderr.fileno() return (p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite) def _set_cloexec_flag(self, fd): try: cloexec_flag = fcntl.FD_CLOEXEC except AttributeError: cloexec_flag = 1 old = fcntl.fcntl(fd, fcntl.F_GETFD) fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag) def _close_fds(self, but): for i in range(3, MAXFD): if i == but: continue try: os.close(i) except KeyboardInterrupt: raise # SCons: don't swallow keyboard interrupts except: pass def _execute_child(self, args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite): """Execute program (POSIX version)""" if is_string(args): args = [args] if shell: args = ["/bin/sh", "-c"] + args if executable is None: executable = args[0] # For transferring possible exec failure from child to parent # The first char specifies the exception type: 0 means # OSError, 1 means some other error. errpipe_read, errpipe_write = os.pipe() self._set_cloexec_flag(errpipe_write) self.pid = os.fork() self._child_created = True if self.pid == 0: # Child try: # Close parent's pipe ends if p2cwrite: os.close(p2cwrite) if c2pread: os.close(c2pread) if errread: os.close(errread) os.close(errpipe_read) # Dup fds for child if p2cread: os.dup2(p2cread, 0) if c2pwrite: os.dup2(c2pwrite, 1) if errwrite: os.dup2(errwrite, 2) # Close pipe fds. Make sure we don't close the same # fd more than once, or standard fds. try: set except NameError: # Fall-back for earlier Python versions, so epydoc # can use this module directly to execute things. if p2cread: os.close(p2cread) if c2pwrite and c2pwrite not in (p2cread,): os.close(c2pwrite) if errwrite and errwrite not in (p2cread, c2pwrite): os.close(errwrite) else: for fd in set((p2cread, c2pwrite, errwrite))-set((0,1,2)): if fd: os.close(fd) # Close all other fds, if asked for if close_fds: self._close_fds(but=errpipe_write) if cwd is not None: os.chdir(cwd) if preexec_fn: apply(preexec_fn) if env is None: os.execvp(executable, args) else: os.execvpe(executable, args, env) except KeyboardInterrupt: raise # SCons: don't swallow keyboard interrupts except: exc_type, exc_value, tb = sys.exc_info() # Save the traceback and attach it to the exception object exc_lines = traceback.format_exception(exc_type, exc_value, tb) exc_value.child_traceback = ''.join(exc_lines) os.write(errpipe_write, pickle.dumps(exc_value)) # This exitcode won't be reported to applications, so it # really doesn't matter what we return. os._exit(255) # Parent os.close(errpipe_write) if p2cread and p2cwrite: os.close(p2cread) if c2pwrite and c2pread: os.close(c2pwrite) if errwrite and errread: os.close(errwrite) # Wait for exec to fail or succeed; possibly raising exception data = os.read(errpipe_read, 1048576) # Exceptions limited to 1 MB os.close(errpipe_read) if data != "": os.waitpid(self.pid, 0) child_exception = pickle.loads(data) raise child_exception def _handle_exitstatus(self, sts): if os.WIFSIGNALED(sts): self.returncode = -os.WTERMSIG(sts) elif os.WIFEXITED(sts): self.returncode = os.WEXITSTATUS(sts) else: # Should never happen raise RuntimeError("Unknown child exit status!") def poll(self, _deadstate=None): """Check if child process has terminated. Returns returncode attribute.""" if self.returncode is None: try: pid, sts = os.waitpid(self.pid, os.WNOHANG) if pid == self.pid: self._handle_exitstatus(sts) except os.error: if _deadstate is not None: self.returncode = _deadstate return self.returncode def wait(self): """Wait for child process to terminate. Returns returncode attribute.""" if self.returncode is None: pid, sts = os.waitpid(self.pid, 0) self._handle_exitstatus(sts) return self.returncode def _communicate(self, input): read_set = [] write_set = [] stdout = None # Return stderr = None # Return if self.stdin: # Flush stdio buffer. This might block, if the user has # been writing to .stdin in an uncontrolled fashion. self.stdin.flush() if input: write_set.append(self.stdin) else: self.stdin.close() if self.stdout: read_set.append(self.stdout) stdout = [] if self.stderr: read_set.append(self.stderr) stderr = [] input_offset = 0 while read_set or write_set: rlist, wlist, xlist = select.select(read_set, write_set, []) if self.stdin in wlist: # When select has indicated that the file is writable, # we can write up to PIPE_BUF bytes without risk # blocking. POSIX defines PIPE_BUF >= 512 m = memoryview(input)[input_offset:input_offset+512] bytes_written = os.write(self.stdin.fileno(), m) input_offset = input_offset + bytes_written if input_offset >= len(input): self.stdin.close() write_set.remove(self.stdin) if self.stdout in rlist: data = os.read(self.stdout.fileno(), 1024) if data == "": self.stdout.close() read_set.remove(self.stdout) stdout.append(data) if self.stderr in rlist: data = os.read(self.stderr.fileno(), 1024) if data == "": self.stderr.close() read_set.remove(self.stderr) stderr.append(data) # All data exchanged. Translate lists into strings. if stdout is not None: stdout = ''.join(stdout) if stderr is not None: stderr = ''.join(stderr) # Translate newlines, if requested. We cannot let the file # object do the translation: It is based on stdio, which is # impossible to combine with select (unless forcing no # buffering). if self.universal_newlines and hasattr(file, 'newlines'): if stdout: stdout = self._translate_newlines(stdout) if stderr: stderr = self._translate_newlines(stderr) self.wait() return (stdout, stderr) def _demo_posix(): # # Example 1: Simple redirection: Get process list # plist = Popen(["ps"], stdout=PIPE).communicate()[0] print "Process list:" print plist # # Example 2: Change uid before executing child # if os.getuid() == 0: p = Popen(["id"], preexec_fn=lambda: os.setuid(100)) p.wait() # # Example 3: Connecting several subprocesses # print "Looking for 'hda'..." p1 = Popen(["dmesg"], stdout=PIPE) p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) print repr(p2.communicate()[0]) # # Example 4: Catch execution error # print print "Trying a weird file..." try: print Popen(["/this/path/does/not/exist"]).communicate() except OSError, e: if e.errno == errno.ENOENT: print "The file didn't exist. I thought so..." print "Child traceback:" print e.child_traceback else: print "Error", e.errno else: sys.stderr.write( "Gosh. No error.\n" ) def _demo_windows(): # # Example 1: Connecting several subprocesses # print "Looking for 'PROMPT' in set output..." p1 = Popen("set", stdout=PIPE, shell=True) p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE) print repr(p2.communicate()[0]) # # Example 2: Simple execution of program # print "Executing calc..." p = Popen("calc") p.wait() if __name__ == "__main__": if mswindows: _demo_windows() else: _demo_posix() # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""scons.Node.Python Python nodes. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Node/Python.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Node class ValueNodeInfo(SCons.Node.NodeInfoBase): current_version_id = 1 field_list = ['csig'] def str_to_node(self, s): return Value(s) class ValueBuildInfo(SCons.Node.BuildInfoBase): current_version_id = 1 class Value(SCons.Node.Node): """A class for Python variables, typically passed on the command line or generated by a script, but not from a file or some other source. """ NodeInfo = ValueNodeInfo BuildInfo = ValueBuildInfo def __init__(self, value, built_value=None): SCons.Node.Node.__init__(self) self.value = value if built_value is not None: self.built_value = built_value def str_for_display(self): return repr(self.value) def __str__(self): return str(self.value) def make_ready(self): self.get_csig() def build(self, **kw): if not hasattr(self, 'built_value'): SCons.Node.Node.build(self, **kw) is_up_to_date = SCons.Node.Node.children_are_up_to_date def is_under(self, dir): # Make Value nodes get built regardless of # what directory scons was run from. Value nodes # are outside the filesystem: return 1 def write(self, built_value): """Set the value of the node.""" self.built_value = built_value def read(self): """Return the value. If necessary, the value is built.""" self.build() if not hasattr(self, 'built_value'): self.built_value = self.value return self.built_value def get_text_contents(self): """By the assumption that the node.built_value is a deterministic product of the sources, the contents of a Value are the concatenation of all the contents of its sources. As the value need not be built when get_contents() is called, we cannot use the actual node.built_value.""" ###TODO: something reasonable about universal newlines contents = str(self.value) for kid in self.children(None): contents = contents + kid.get_contents() return contents get_contents = get_text_contents ###TODO should return 'bytes' value def changed_since_last_build(self, target, prev_ni): cur_csig = self.get_csig() try: return cur_csig != prev_ni.csig except AttributeError: return 1 def get_csig(self, calc=None): """Because we're a Python value node and don't have a real timestamp, we get to ignore the calculator and just use the value contents.""" try: return self.ninfo.csig except AttributeError: pass contents = self.get_contents() self.get_ninfo().csig = contents return contents # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""scons.Node.FS File system nodes. These Nodes represent the canonical external objects that people think of when they think of building software: files and directories. This holds a "default_fs" variable that should be initialized with an FS that can be used by scripts or modules looking for the canonical default. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. __revision__ = "src/engine/SCons/Node/FS.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import fnmatch import os import re import shutil import stat import sys import time import codecs import SCons.Action from SCons.Debug import logInstanceCreation import SCons.Errors import SCons.Memoize import SCons.Node import SCons.Node.Alias import SCons.Subst import SCons.Util import SCons.Warnings from SCons.Debug import Trace do_store_info = True print_duplicate = 0 class EntryProxyAttributeError(AttributeError): """ An AttributeError subclass for recording and displaying the name of the underlying Entry involved in an AttributeError exception. """ def __init__(self, entry_proxy, attribute): AttributeError.__init__(self) self.entry_proxy = entry_proxy self.attribute = attribute def __str__(self): entry = self.entry_proxy.get() fmt = "%s instance %s has no attribute %s" return fmt % (entry.__class__.__name__, repr(entry.name), repr(self.attribute)) # The max_drift value: by default, use a cached signature value for # any file that's been untouched for more than two days. default_max_drift = 2*24*60*60 # # We stringify these file system Nodes a lot. Turning a file system Node # into a string is non-trivial, because the final string representation # can depend on a lot of factors: whether it's a derived target or not, # whether it's linked to a repository or source directory, and whether # there's duplication going on. The normal technique for optimizing # calculations like this is to memoize (cache) the string value, so you # only have to do the calculation once. # # A number of the above factors, however, can be set after we've already # been asked to return a string for a Node, because a Repository() or # VariantDir() call or the like may not occur until later in SConscript # files. So this variable controls whether we bother trying to save # string values for Nodes. The wrapper interface can set this whenever # they're done mucking with Repository and VariantDir and the other stuff, # to let this module know it can start returning saved string values # for Nodes. # Save_Strings = None def save_strings(val): global Save_Strings Save_Strings = val # # Avoid unnecessary function calls by recording a Boolean value that # tells us whether or not os.path.splitdrive() actually does anything # on this system, and therefore whether we need to bother calling it # when looking up path names in various methods below. # do_splitdrive = None _my_splitdrive =None def initialize_do_splitdrive(): global do_splitdrive global has_unc drive, path = os.path.splitdrive('X:/foo') has_unc = hasattr(os.path, 'splitunc') do_splitdrive = not not drive or has_unc global _my_splitdrive if has_unc: def splitdrive(p): if p[1:2] == ':': return p[:2], p[2:] if p[0:2] == '//': # Note that we leave a leading slash in the path # because UNC paths are always absolute. return '//', p[1:] return '', p else: def splitdrive(p): if p[1:2] == ':': return p[:2], p[2:] return '', p _my_splitdrive = splitdrive # Keep some commonly used values in global variables to skip to # module look-up costs. global OS_SEP global UNC_PREFIX global os_sep_is_slash OS_SEP = os.sep UNC_PREFIX = OS_SEP + OS_SEP os_sep_is_slash = OS_SEP == '/' initialize_do_splitdrive() # Used to avoid invoking os.path.normpath if not necessary. needs_normpath_check = re.compile( r''' # We need to renormalize the path if it contains any consecutive # '/' characters. .*// | # We need to renormalize the path if it contains a '..' directory. # Note that we check for all the following cases: # # a) The path is a single '..' # b) The path starts with '..'. E.g. '../' or '../moredirs' # but we not match '..abc/'. # c) The path ends with '..'. E.g. '/..' or 'dirs/..' # d) The path contains a '..' in the middle. # E.g. dirs/../moredirs (.*/)?\.\.(?:/|$) | # We need to renormalize the path if it contains a '.' # directory, but NOT if it is a single '.' '/' characters. We # do not want to match a single '.' because this case is checked # for explicitely since this is common enough case. # # Note that we check for all the following cases: # # a) We don't match a single '.' # b) We match if the path starts with '.'. E.g. './' or # './moredirs' but we not match '.abc/'. # c) We match if the path ends with '.'. E.g. '/.' or # 'dirs/.' # d) We match if the path contains a '.' in the middle. # E.g. dirs/./moredirs \./|.*/\.(?:/|$) ''', re.VERBOSE ) needs_normpath_match = needs_normpath_check.match # # SCons.Action objects for interacting with the outside world. # # The Node.FS methods in this module should use these actions to # create and/or remove files and directories; they should *not* use # os.{link,symlink,unlink,mkdir}(), etc., directly. # # Using these SCons.Action objects ensures that descriptions of these # external activities are properly displayed, that the displays are # suppressed when the -s (silent) option is used, and (most importantly) # the actions are disabled when the the -n option is used, in which case # there should be *no* changes to the external file system(s)... # if hasattr(os, 'link'): def _hardlink_func(fs, src, dst): # If the source is a symlink, we can't just hard-link to it # because a relative symlink may point somewhere completely # different. We must disambiguate the symlink and then # hard-link the final destination file. while fs.islink(src): link = fs.readlink(src) if not os.path.isabs(link): src = link else: src = os.path.join(os.path.dirname(src), link) fs.link(src, dst) else: _hardlink_func = None if hasattr(os, 'symlink'): def _softlink_func(fs, src, dst): fs.symlink(src, dst) else: _softlink_func = None def _copy_func(fs, src, dest): shutil.copy2(src, dest) st = fs.stat(src) fs.chmod(dest, stat.S_IMODE(st[stat.ST_MODE]) | stat.S_IWRITE) Valid_Duplicates = ['hard-soft-copy', 'soft-hard-copy', 'hard-copy', 'soft-copy', 'copy'] Link_Funcs = [] # contains the callables of the specified duplication style def set_duplicate(duplicate): # Fill in the Link_Funcs list according to the argument # (discarding those not available on the platform). # Set up the dictionary that maps the argument names to the # underlying implementations. We do this inside this function, # not in the top-level module code, so that we can remap os.link # and os.symlink for testing purposes. link_dict = { 'hard' : _hardlink_func, 'soft' : _softlink_func, 'copy' : _copy_func } if not duplicate in Valid_Duplicates: raise SCons.Errors.InternalError("The argument of set_duplicate " "should be in Valid_Duplicates") global Link_Funcs Link_Funcs = [] for func in duplicate.split('-'): if link_dict[func]: Link_Funcs.append(link_dict[func]) def LinkFunc(target, source, env): # Relative paths cause problems with symbolic links, so # we use absolute paths, which may be a problem for people # who want to move their soft-linked src-trees around. Those # people should use the 'hard-copy' mode, softlinks cannot be # used for that; at least I have no idea how ... src = source[0].abspath dest = target[0].abspath dir, file = os.path.split(dest) if dir and not target[0].fs.isdir(dir): os.makedirs(dir) if not Link_Funcs: # Set a default order of link functions. set_duplicate('hard-soft-copy') fs = source[0].fs # Now link the files with the previously specified order. for func in Link_Funcs: try: func(fs, src, dest) break except (IOError, OSError): # An OSError indicates something happened like a permissions # problem or an attempt to symlink across file-system # boundaries. An IOError indicates something like the file # not existing. In either case, keeping trying additional # functions in the list and only raise an error if the last # one failed. if func == Link_Funcs[-1]: # exception of the last link method (copy) are fatal raise return 0 Link = SCons.Action.Action(LinkFunc, None) def LocalString(target, source, env): return 'Local copy of %s from %s' % (target[0], source[0]) LocalCopy = SCons.Action.Action(LinkFunc, LocalString) def UnlinkFunc(target, source, env): t = target[0] t.fs.unlink(t.abspath) return 0 Unlink = SCons.Action.Action(UnlinkFunc, None) def MkdirFunc(target, source, env): t = target[0] if not t.exists(): t.fs.mkdir(t.abspath) return 0 Mkdir = SCons.Action.Action(MkdirFunc, None, presub=None) MkdirBuilder = None def get_MkdirBuilder(): global MkdirBuilder if MkdirBuilder is None: import SCons.Builder import SCons.Defaults # "env" will get filled in by Executor.get_build_env() # calling SCons.Defaults.DefaultEnvironment() when necessary. MkdirBuilder = SCons.Builder.Builder(action = Mkdir, env = None, explain = None, is_explicit = None, target_scanner = SCons.Defaults.DirEntryScanner, name = "MkdirBuilder") return MkdirBuilder class _Null(object): pass _null = _Null() DefaultSCCSBuilder = None DefaultRCSBuilder = None def get_DefaultSCCSBuilder(): global DefaultSCCSBuilder if DefaultSCCSBuilder is None: import SCons.Builder # "env" will get filled in by Executor.get_build_env() # calling SCons.Defaults.DefaultEnvironment() when necessary. act = SCons.Action.Action('$SCCSCOM', '$SCCSCOMSTR') DefaultSCCSBuilder = SCons.Builder.Builder(action = act, env = None, name = "DefaultSCCSBuilder") return DefaultSCCSBuilder def get_DefaultRCSBuilder(): global DefaultRCSBuilder if DefaultRCSBuilder is None: import SCons.Builder # "env" will get filled in by Executor.get_build_env() # calling SCons.Defaults.DefaultEnvironment() when necessary. act = SCons.Action.Action('$RCS_COCOM', '$RCS_COCOMSTR') DefaultRCSBuilder = SCons.Builder.Builder(action = act, env = None, name = "DefaultRCSBuilder") return DefaultRCSBuilder # Cygwin's os.path.normcase pretends it's on a case-sensitive filesystem. _is_cygwin = sys.platform == "cygwin" if os.path.normcase("TeSt") == os.path.normpath("TeSt") and not _is_cygwin: def _my_normcase(x): return x else: def _my_normcase(x): return x.upper() class DiskChecker(object): def __init__(self, type, do, ignore): self.type = type self.do = do self.ignore = ignore self.func = do def __call__(self, *args, **kw): return self.func(*args, **kw) def set(self, list): if self.type in list: self.func = self.do else: self.func = self.ignore def do_diskcheck_match(node, predicate, errorfmt): result = predicate() try: # If calling the predicate() cached a None value from stat(), # remove it so it doesn't interfere with later attempts to # build this Node as we walk the DAG. (This isn't a great way # to do this, we're reaching into an interface that doesn't # really belong to us, but it's all about performance, so # for now we'll just document the dependency...) if node._memo['stat'] is None: del node._memo['stat'] except (AttributeError, KeyError): pass if result: raise TypeError(errorfmt % node.abspath) def ignore_diskcheck_match(node, predicate, errorfmt): pass def do_diskcheck_rcs(node, name): try: rcs_dir = node.rcs_dir except AttributeError: if node.entry_exists_on_disk('RCS'): rcs_dir = node.Dir('RCS') else: rcs_dir = None node.rcs_dir = rcs_dir if rcs_dir: return rcs_dir.entry_exists_on_disk(name+',v') return None def ignore_diskcheck_rcs(node, name): return None def do_diskcheck_sccs(node, name): try: sccs_dir = node.sccs_dir except AttributeError: if node.entry_exists_on_disk('SCCS'): sccs_dir = node.Dir('SCCS') else: sccs_dir = None node.sccs_dir = sccs_dir if sccs_dir: return sccs_dir.entry_exists_on_disk('s.'+name) return None def ignore_diskcheck_sccs(node, name): return None diskcheck_match = DiskChecker('match', do_diskcheck_match, ignore_diskcheck_match) diskcheck_rcs = DiskChecker('rcs', do_diskcheck_rcs, ignore_diskcheck_rcs) diskcheck_sccs = DiskChecker('sccs', do_diskcheck_sccs, ignore_diskcheck_sccs) diskcheckers = [ diskcheck_match, diskcheck_rcs, diskcheck_sccs, ] def set_diskcheck(list): for dc in diskcheckers: dc.set(list) def diskcheck_types(): return [dc.type for dc in diskcheckers] class EntryProxy(SCons.Util.Proxy): __str__ = SCons.Util.Delegate('__str__') def __get_abspath(self): entry = self.get() return SCons.Subst.SpecialAttrWrapper(entry.get_abspath(), entry.name + "_abspath") def __get_filebase(self): name = self.get().name return SCons.Subst.SpecialAttrWrapper(SCons.Util.splitext(name)[0], name + "_filebase") def __get_suffix(self): name = self.get().name return SCons.Subst.SpecialAttrWrapper(SCons.Util.splitext(name)[1], name + "_suffix") def __get_file(self): name = self.get().name return SCons.Subst.SpecialAttrWrapper(name, name + "_file") def __get_base_path(self): """Return the file's directory and file name, with the suffix stripped.""" entry = self.get() return SCons.Subst.SpecialAttrWrapper(SCons.Util.splitext(entry.get_path())[0], entry.name + "_base") def __get_posix_path(self): """Return the path with / as the path separator, regardless of platform.""" if os_sep_is_slash: return self else: entry = self.get() r = entry.get_path().replace(OS_SEP, '/') return SCons.Subst.SpecialAttrWrapper(r, entry.name + "_posix") def __get_windows_path(self): """Return the path with \ as the path separator, regardless of platform.""" if OS_SEP == '\\': return self else: entry = self.get() r = entry.get_path().replace(OS_SEP, '\\') return SCons.Subst.SpecialAttrWrapper(r, entry.name + "_windows") def __get_srcnode(self): return EntryProxy(self.get().srcnode()) def __get_srcdir(self): """Returns the directory containing the source node linked to this node via VariantDir(), or the directory of this node if not linked.""" return EntryProxy(self.get().srcnode().dir) def __get_rsrcnode(self): return EntryProxy(self.get().srcnode().rfile()) def __get_rsrcdir(self): """Returns the directory containing the source node linked to this node via VariantDir(), or the directory of this node if not linked.""" return EntryProxy(self.get().srcnode().rfile().dir) def __get_dir(self): return EntryProxy(self.get().dir) dictSpecialAttrs = { "base" : __get_base_path, "posix" : __get_posix_path, "windows" : __get_windows_path, "win32" : __get_windows_path, "srcpath" : __get_srcnode, "srcdir" : __get_srcdir, "dir" : __get_dir, "abspath" : __get_abspath, "filebase" : __get_filebase, "suffix" : __get_suffix, "file" : __get_file, "rsrcpath" : __get_rsrcnode, "rsrcdir" : __get_rsrcdir, } def __getattr__(self, name): # This is how we implement the "special" attributes # such as base, posix, srcdir, etc. try: attr_function = self.dictSpecialAttrs[name] except KeyError: try: attr = SCons.Util.Proxy.__getattr__(self, name) except AttributeError, e: # Raise our own AttributeError subclass with an # overridden __str__() method that identifies the # name of the entry that caused the exception. raise EntryProxyAttributeError(self, name) return attr else: return attr_function(self) class Base(SCons.Node.Node): """A generic class for file system entries. This class is for when we don't know yet whether the entry being looked up is a file or a directory. Instances of this class can morph into either Dir or File objects by a later, more precise lookup. Note: this class does not define __cmp__ and __hash__ for efficiency reasons. SCons does a lot of comparing of Node.FS.{Base,Entry,File,Dir} objects, so those operations must be as fast as possible, which means we want to use Python's built-in object identity comparisons. """ memoizer_counters = [] def __init__(self, name, directory, fs): """Initialize a generic Node.FS.Base object. Call the superclass initialization, take care of setting up our relative and absolute paths, identify our parent directory, and indicate that this node should use signatures.""" if __debug__: logInstanceCreation(self, 'Node.FS.Base') SCons.Node.Node.__init__(self) # Filenames and paths are probably reused and are intern'ed to # save some memory. #: Filename with extension as it was specified when the object was #: created; to obtain filesystem path, use Python str() function self.name = SCons.Util.silent_intern(name) #: Cached filename extension self.suffix = SCons.Util.silent_intern(SCons.Util.splitext(name)[1]) self.fs = fs #: Reference to parent Node.FS object assert directory, "A directory must be provided" self.abspath = SCons.Util.silent_intern(directory.entry_abspath(name)) self.labspath = SCons.Util.silent_intern(directory.entry_labspath(name)) if directory.path == '.': self.path = SCons.Util.silent_intern(name) else: self.path = SCons.Util.silent_intern(directory.entry_path(name)) if directory.tpath == '.': self.tpath = SCons.Util.silent_intern(name) else: self.tpath = SCons.Util.silent_intern(directory.entry_tpath(name)) self.path_elements = directory.path_elements + [self] self.dir = directory self.cwd = None # will hold the SConscript directory for target nodes self.duplicate = directory.duplicate def str_for_display(self): return '"' + self.__str__() + '"' def must_be_same(self, klass): """ This node, which already existed, is being looked up as the specified klass. Raise an exception if it isn't. """ if isinstance(self, klass) or klass is Entry: return raise TypeError("Tried to lookup %s '%s' as a %s." %\ (self.__class__.__name__, self.path, klass.__name__)) def get_dir(self): return self.dir def get_suffix(self): return self.suffix def rfile(self): return self def __str__(self): """A Node.FS.Base object's string representation is its path name.""" global Save_Strings if Save_Strings: return self._save_str() return self._get_str() memoizer_counters.append(SCons.Memoize.CountValue('_save_str')) def _save_str(self): try: return self._memo['_save_str'] except KeyError: pass result = sys.intern(self._get_str()) self._memo['_save_str'] = result return result def _get_str(self): global Save_Strings if self.duplicate or self.is_derived(): return self.get_path() srcnode = self.srcnode() if srcnode.stat() is None and self.stat() is not None: result = self.get_path() else: result = srcnode.get_path() if not Save_Strings: # We're not at the point where we're saving the string # representations of FS Nodes (because we haven't finished # reading the SConscript files and need to have str() return # things relative to them). That also means we can't yet # cache values returned (or not returned) by stat(), since # Python code in the SConscript files might still create # or otherwise affect the on-disk file. So get rid of the # values that the underlying stat() method saved. try: del self._memo['stat'] except KeyError: pass if self is not srcnode: try: del srcnode._memo['stat'] except KeyError: pass return result rstr = __str__ memoizer_counters.append(SCons.Memoize.CountValue('stat')) def stat(self): try: return self._memo['stat'] except KeyError: pass try: result = self.fs.stat(self.abspath) except os.error: result = None self._memo['stat'] = result return result def exists(self): return self.stat() is not None def rexists(self): return self.rfile().exists() def getmtime(self): st = self.stat() if st: return st[stat.ST_MTIME] else: return None def getsize(self): st = self.stat() if st: return st[stat.ST_SIZE] else: return None def isdir(self): st = self.stat() return st is not None and stat.S_ISDIR(st[stat.ST_MODE]) def isfile(self): st = self.stat() return st is not None and stat.S_ISREG(st[stat.ST_MODE]) if hasattr(os, 'symlink'): def islink(self): try: st = self.fs.lstat(self.abspath) except os.error: return 0 return stat.S_ISLNK(st[stat.ST_MODE]) else: def islink(self): return 0 # no symlinks def is_under(self, dir): if self is dir: return 1 else: return self.dir.is_under(dir) def set_local(self): self._local = 1 def srcnode(self): """If this node is in a build path, return the node corresponding to its source file. Otherwise, return ourself. """ srcdir_list = self.dir.srcdir_list() if srcdir_list: srcnode = srcdir_list[0].Entry(self.name) srcnode.must_be_same(self.__class__) return srcnode return self def get_path(self, dir=None): """Return path relative to the current working directory of the Node.FS.Base object that owns us.""" if not dir: dir = self.fs.getcwd() if self == dir: return '.' path_elems = self.path_elements pathname = '' try: i = path_elems.index(dir) except ValueError: for p in path_elems[:-1]: pathname += p.dirname else: for p in path_elems[i+1:-1]: pathname += p.dirname return pathname + path_elems[-1].name def set_src_builder(self, builder): """Set the source code builder for this node.""" self.sbuilder = builder if not self.has_builder(): self.builder_set(builder) def src_builder(self): """Fetch the source code builder for this node. If there isn't one, we cache the source code builder specified for the directory (which in turn will cache the value from its parent directory, and so on up to the file system root). """ try: scb = self.sbuilder except AttributeError: scb = self.dir.src_builder() self.sbuilder = scb return scb def get_abspath(self): """Get the absolute path of the file.""" return self.abspath def for_signature(self): # Return just our name. Even an absolute path would not work, # because that can change thanks to symlinks or remapped network # paths. return self.name def get_subst_proxy(self): try: return self._proxy except AttributeError: ret = EntryProxy(self) self._proxy = ret return ret def target_from_source(self, prefix, suffix, splitext=SCons.Util.splitext): """ Generates a target entry that corresponds to this entry (usually a source file) with the specified prefix and suffix. Note that this method can be overridden dynamically for generated files that need different behavior. See Tool/swig.py for an example. """ return self.dir.Entry(prefix + splitext(self.name)[0] + suffix) def _Rfindalldirs_key(self, pathlist): return pathlist memoizer_counters.append(SCons.Memoize.CountDict('Rfindalldirs', _Rfindalldirs_key)) def Rfindalldirs(self, pathlist): """ Return all of the directories for a given path list, including corresponding "backing" directories in any repositories. The Node lookups are relative to this Node (typically a directory), so memoizing result saves cycles from looking up the same path for each target in a given directory. """ try: memo_dict = self._memo['Rfindalldirs'] except KeyError: memo_dict = {} self._memo['Rfindalldirs'] = memo_dict else: try: return memo_dict[pathlist] except KeyError: pass create_dir_relative_to_self = self.Dir result = [] for path in pathlist: if isinstance(path, SCons.Node.Node): result.append(path) else: dir = create_dir_relative_to_self(path) result.extend(dir.get_all_rdirs()) memo_dict[pathlist] = result return result def RDirs(self, pathlist): """Search for a list of directories in the Repository list.""" cwd = self.cwd or self.fs._cwd return cwd.Rfindalldirs(pathlist) memoizer_counters.append(SCons.Memoize.CountValue('rentry')) def rentry(self): try: return self._memo['rentry'] except KeyError: pass result = self if not self.exists(): norm_name = _my_normcase(self.name) for dir in self.dir.get_all_rdirs(): try: node = dir.entries[norm_name] except KeyError: if dir.entry_exists_on_disk(self.name): result = dir.Entry(self.name) break self._memo['rentry'] = result return result def _glob1(self, pattern, ondisk=True, source=False, strings=False): return [] class Entry(Base): """This is the class for generic Node.FS entries--that is, things that could be a File or a Dir, but we're just not sure yet. Consequently, the methods in this class really exist just to transform their associated object into the right class when the time comes, and then call the same-named method in the transformed class.""" def diskcheck_match(self): pass def disambiguate(self, must_exist=None): """ """ if self.isdir(): self.__class__ = Dir self._morph() elif self.isfile(): self.__class__ = File self._morph() self.clear() else: # There was nothing on-disk at this location, so look in # the src directory. # # We can't just use self.srcnode() straight away because # that would create an actual Node for this file in the src # directory, and there might not be one. Instead, use the # dir_on_disk() method to see if there's something on-disk # with that name, in which case we can go ahead and call # self.srcnode() to create the right type of entry. srcdir = self.dir.srcnode() if srcdir != self.dir and \ srcdir.entry_exists_on_disk(self.name) and \ self.srcnode().isdir(): self.__class__ = Dir self._morph() elif must_exist: msg = "No such file or directory: '%s'" % self.abspath raise SCons.Errors.UserError(msg) else: self.__class__ = File self._morph() self.clear() return self def rfile(self): """We're a generic Entry, but the caller is actually looking for a File at this point, so morph into one.""" self.__class__ = File self._morph() self.clear() return File.rfile(self) def scanner_key(self): return self.get_suffix() def get_contents(self): """Fetch the contents of the entry. Returns the exact binary contents of the file.""" try: self = self.disambiguate(must_exist=1) except SCons.Errors.UserError: # There was nothing on disk with which to disambiguate # this entry. Leave it as an Entry, but return a null # string so calls to get_contents() in emitters and the # like (e.g. in qt.py) don't have to disambiguate by hand # or catch the exception. return '' else: return self.get_contents() def get_text_contents(self): """Fetch the decoded text contents of a Unicode encoded Entry. Since this should return the text contents from the file system, we check to see into what sort of subclass we should morph this Entry.""" try: self = self.disambiguate(must_exist=1) except SCons.Errors.UserError: # There was nothing on disk with which to disambiguate # this entry. Leave it as an Entry, but return a null # string so calls to get_text_contents() in emitters and # the like (e.g. in qt.py) don't have to disambiguate by # hand or catch the exception. return '' else: return self.get_text_contents() def must_be_same(self, klass): """Called to make sure a Node is a Dir. Since we're an Entry, we can morph into one.""" if self.__class__ is not klass: self.__class__ = klass self._morph() self.clear() # The following methods can get called before the Taskmaster has # had a chance to call disambiguate() directly to see if this Entry # should really be a Dir or a File. We therefore use these to call # disambiguate() transparently (from our caller's point of view). # # Right now, this minimal set of methods has been derived by just # looking at some of the methods that will obviously be called early # in any of the various Taskmasters' calling sequences, and then # empirically figuring out which additional methods are necessary # to make various tests pass. def exists(self): """Return if the Entry exists. Check the file system to see what we should turn into first. Assume a file if there's no directory.""" return self.disambiguate().exists() def rel_path(self, other): d = self.disambiguate() if d.__class__ is Entry: raise Exception("rel_path() could not disambiguate File/Dir") return d.rel_path(other) def new_ninfo(self): return self.disambiguate().new_ninfo() def changed_since_last_build(self, target, prev_ni): return self.disambiguate().changed_since_last_build(target, prev_ni) def _glob1(self, pattern, ondisk=True, source=False, strings=False): return self.disambiguate()._glob1(pattern, ondisk, source, strings) def get_subst_proxy(self): return self.disambiguate().get_subst_proxy() # This is for later so we can differentiate between Entry the class and Entry # the method of the FS class. _classEntry = Entry class LocalFS(object): if SCons.Memoize.use_memoizer: __metaclass__ = SCons.Memoize.Memoized_Metaclass # This class implements an abstraction layer for operations involving # a local file system. Essentially, this wraps any function in # the os, os.path or shutil modules that we use to actually go do # anything with or to the local file system. # # Note that there's a very good chance we'll refactor this part of # the architecture in some way as we really implement the interface(s) # for remote file system Nodes. For example, the right architecture # might be to have this be a subclass instead of a base class. # Nevertheless, we're using this as a first step in that direction. # # We're not using chdir() yet because the calling subclass method # needs to use os.chdir() directly to avoid recursion. Will we # really need this one? #def chdir(self, path): # return os.chdir(path) def chmod(self, path, mode): return os.chmod(path, mode) def copy(self, src, dst): return shutil.copy(src, dst) def copy2(self, src, dst): return shutil.copy2(src, dst) def exists(self, path): return os.path.exists(path) def getmtime(self, path): return os.path.getmtime(path) def getsize(self, path): return os.path.getsize(path) def isdir(self, path): return os.path.isdir(path) def isfile(self, path): return os.path.isfile(path) def link(self, src, dst): return os.link(src, dst) def lstat(self, path): return os.lstat(path) def listdir(self, path): return os.listdir(path) def makedirs(self, path): return os.makedirs(path) def mkdir(self, path): return os.mkdir(path) def rename(self, old, new): return os.rename(old, new) def stat(self, path): return os.stat(path) def symlink(self, src, dst): return os.symlink(src, dst) def open(self, path): return open(path) def unlink(self, path): return os.unlink(path) if hasattr(os, 'symlink'): def islink(self, path): return os.path.islink(path) else: def islink(self, path): return 0 # no symlinks if hasattr(os, 'readlink'): def readlink(self, file): return os.readlink(file) else: def readlink(self, file): return '' #class RemoteFS: # # Skeleton for the obvious methods we might need from the # # abstraction layer for a remote filesystem. # def upload(self, local_src, remote_dst): # pass # def download(self, remote_src, local_dst): # pass class FS(LocalFS): memoizer_counters = [] def __init__(self, path = None): """Initialize the Node.FS subsystem. The supplied path is the top of the source tree, where we expect to find the top-level build file. If no path is supplied, the current directory is the default. The path argument must be a valid absolute path. """ if __debug__: logInstanceCreation(self, 'Node.FS') self._memo = {} self.Root = {} self.SConstruct_dir = None self.max_drift = default_max_drift self.Top = None if path is None: self.pathTop = os.getcwd() else: self.pathTop = path self.defaultDrive = _my_normcase(_my_splitdrive(self.pathTop)[0]) self.Top = self.Dir(self.pathTop) self.Top.path = '.' self.Top.tpath = '.' self._cwd = self.Top DirNodeInfo.fs = self FileNodeInfo.fs = self def set_SConstruct_dir(self, dir): self.SConstruct_dir = dir def get_max_drift(self): return self.max_drift def set_max_drift(self, max_drift): self.max_drift = max_drift def getcwd(self): if hasattr(self, "_cwd"): return self._cwd else: return "<no cwd>" def chdir(self, dir, change_os_dir=0): """Change the current working directory for lookups. If change_os_dir is true, we will also change the "real" cwd to match. """ curr=self._cwd try: if dir is not None: self._cwd = dir if change_os_dir: os.chdir(dir.abspath) except OSError: self._cwd = curr raise def get_root(self, drive): """ Returns the root directory for the specified drive, creating it if necessary. """ drive = _my_normcase(drive) try: return self.Root[drive] except KeyError: root = RootDir(drive, self) self.Root[drive] = root if not drive: self.Root[self.defaultDrive] = root elif drive == self.defaultDrive: self.Root[''] = root return root def _lookup(self, p, directory, fsclass, create=1): """ The generic entry point for Node lookup with user-supplied data. This translates arbitrary input into a canonical Node.FS object of the specified fsclass. The general approach for strings is to turn it into a fully normalized absolute path and then call the root directory's lookup_abs() method for the heavy lifting. If the path name begins with '#', it is unconditionally interpreted relative to the top-level directory of this FS. '#' is treated as a synonym for the top-level SConstruct directory, much like '~' is treated as a synonym for the user's home directory in a UNIX shell. So both '#foo' and '#/foo' refer to the 'foo' subdirectory underneath the top-level SConstruct directory. If the path name is relative, then the path is looked up relative to the specified directory, or the current directory (self._cwd, typically the SConscript directory) if the specified directory is None. """ if isinstance(p, Base): # It's already a Node.FS object. Make sure it's the right # class and return. p.must_be_same(fsclass) return p # str(p) in case it's something like a proxy object p = str(p) if not os_sep_is_slash: p = p.replace(OS_SEP, '/') if p[0:1] == '#': # There was an initial '#', so we strip it and override # whatever directory they may have specified with the # top-level SConstruct directory. p = p[1:] directory = self.Top # There might be a drive letter following the # '#'. Although it is not described in the SCons man page, # the regression test suite explicitly tests for that # syntax. It seems to mean the following thing: # # Assuming the the SCons top dir is in C:/xxx/yyy, # '#X:/toto' means X:/xxx/yyy/toto. # # i.e. it assumes that the X: drive has a directory # structure similar to the one found on drive C:. if do_splitdrive: drive, p = _my_splitdrive(p) if drive: root = self.get_root(drive) else: root = directory.root else: root = directory.root # We can only strip trailing after splitting the drive # since the drive might the UNC '//' prefix. p = p.strip('/') needs_normpath = needs_normpath_match(p) # The path is relative to the top-level SCons directory. if p in ('', '.'): p = directory.labspath else: p = directory.labspath + '/' + p else: if do_splitdrive: drive, p = _my_splitdrive(p) if drive and not p: # This causes a naked drive letter to be treated # as a synonym for the root directory on that # drive. p = '/' else: drive = '' # We can only strip trailing '/' since the drive might the # UNC '//' prefix. if p != '/': p = p.rstrip('/') needs_normpath = needs_normpath_match(p) if p[0:1] == '/': # Absolute path root = self.get_root(drive) else: # This is a relative lookup or to the current directory # (the path name is not absolute). Add the string to the # appropriate directory lookup path, after which the whole # thing gets normalized. if directory: if not isinstance(directory, Dir): directory = self.Dir(directory) else: directory = self._cwd if p in ('', '.'): p = directory.labspath else: p = directory.labspath + '/' + p if drive: root = self.get_root(drive) else: root = directory.root if needs_normpath is not None: # Normalize a pathname. Will return the same result for # equivalent paths. # # We take advantage of the fact that we have an absolute # path here for sure. In addition, we know that the # components of lookup path are separated by slashes at # this point. Because of this, this code is about 2X # faster than calling os.path.normpath() followed by # replacing os.sep with '/' again. ins = p.split('/')[1:] outs = [] for d in ins: if d == '..': try: outs.pop() except IndexError: pass elif d not in ('', '.'): outs.append(d) p = '/' + '/'.join(outs) return root._lookup_abs(p, fsclass, create) def Entry(self, name, directory = None, create = 1): """Look up or create a generic Entry node with the specified name. If the name is a relative path (begins with ./, ../, or a file name), then it is looked up relative to the supplied directory node, or to the top level directory of the FS (supplied at construction time) if no directory is supplied. """ return self._lookup(name, directory, Entry, create) def File(self, name, directory = None, create = 1): """Look up or create a File node with the specified name. If the name is a relative path (begins with ./, ../, or a file name), then it is looked up relative to the supplied directory node, or to the top level directory of the FS (supplied at construction time) if no directory is supplied. This method will raise TypeError if a directory is found at the specified path. """ return self._lookup(name, directory, File, create) def Dir(self, name, directory = None, create = True): """Look up or create a Dir node with the specified name. If the name is a relative path (begins with ./, ../, or a file name), then it is looked up relative to the supplied directory node, or to the top level directory of the FS (supplied at construction time) if no directory is supplied. This method will raise TypeError if a normal file is found at the specified path. """ return self._lookup(name, directory, Dir, create) def VariantDir(self, variant_dir, src_dir, duplicate=1): """Link the supplied variant directory to the source directory for purposes of building files.""" if not isinstance(src_dir, SCons.Node.Node): src_dir = self.Dir(src_dir) if not isinstance(variant_dir, SCons.Node.Node): variant_dir = self.Dir(variant_dir) if src_dir.is_under(variant_dir): raise SCons.Errors.UserError("Source directory cannot be under variant directory.") if variant_dir.srcdir: if variant_dir.srcdir == src_dir: return # We already did this. raise SCons.Errors.UserError("'%s' already has a source directory: '%s'."%(variant_dir, variant_dir.srcdir)) variant_dir.link(src_dir, duplicate) def Repository(self, *dirs): """Specify Repository directories to search.""" for d in dirs: if not isinstance(d, SCons.Node.Node): d = self.Dir(d) self.Top.addRepository(d) def variant_dir_target_climb(self, orig, dir, tail): """Create targets in corresponding variant directories Climb the directory tree, and look up path names relative to any linked variant directories we find. Even though this loops and walks up the tree, we don't memoize the return value because this is really only used to process the command-line targets. """ targets = [] message = None fmt = "building associated VariantDir targets: %s" start_dir = dir while dir: for bd in dir.variant_dirs: if start_dir.is_under(bd): # If already in the build-dir location, don't reflect return [orig], fmt % str(orig) p = os.path.join(bd.path, *tail) targets.append(self.Entry(p)) tail = [dir.name] + tail dir = dir.up() if targets: message = fmt % ' '.join(map(str, targets)) return targets, message def Glob(self, pathname, ondisk=True, source=True, strings=False, cwd=None): """ Globs This is mainly a shim layer """ if cwd is None: cwd = self.getcwd() return cwd.glob(pathname, ondisk, source, strings) class DirNodeInfo(SCons.Node.NodeInfoBase): # This should get reset by the FS initialization. current_version_id = 1 fs = None def str_to_node(self, s): top = self.fs.Top root = top.root if do_splitdrive: drive, s = _my_splitdrive(s) if drive: root = self.fs.get_root(drive) if not os.path.isabs(s): s = top.labspath + '/' + s return root._lookup_abs(s, Entry) class DirBuildInfo(SCons.Node.BuildInfoBase): current_version_id = 1 glob_magic_check = re.compile('[*?[]') def has_glob_magic(s): return glob_magic_check.search(s) is not None class Dir(Base): """A class for directories in a file system. """ memoizer_counters = [] NodeInfo = DirNodeInfo BuildInfo = DirBuildInfo def __init__(self, name, directory, fs): if __debug__: logInstanceCreation(self, 'Node.FS.Dir') Base.__init__(self, name, directory, fs) self._morph() def _morph(self): """Turn a file system Node (either a freshly initialized directory object or a separate Entry object) into a proper directory object. Set up this directory's entries and hook it into the file system tree. Specify that directories (this Node) don't use signatures for calculating whether they're current. """ self.repositories = [] self.srcdir = None self.entries = {} self.entries['.'] = self self.entries['..'] = self.dir self.cwd = self self.searched = 0 self._sconsign = None self.variant_dirs = [] self.root = self.dir.root # For directories, we make a difference between the directory # 'name' and the directory 'dirname'. The 'name' attribute is # used when we need to print the 'name' of the directory or # when we it is used as the last part of a path. The 'dirname' # is used when the directory is not the last element of the # path. The main reason for making that distinction is that # for RoorDir's the dirname can not be easily inferred from # the name. For example, we have to add a '/' after a drive # letter but not after a UNC path prefix ('//'). self.dirname = self.name + OS_SEP # Don't just reset the executor, replace its action list, # because it might have some pre-or post-actions that need to # be preserved. # # But don't reset the executor if there is a non-null executor # attached already. The existing executor might have other # targets, in which case replacing the action list with a # Mkdir action is a big mistake. if not hasattr(self, 'executor'): self.builder = get_MkdirBuilder() self.get_executor().set_action_list(self.builder.action) else: # Prepend MkdirBuilder action to existing action list l = self.get_executor().action_list a = get_MkdirBuilder().action l.insert(0, a) self.get_executor().set_action_list(l) def diskcheck_match(self): diskcheck_match(self, self.isfile, "File %s found where directory expected.") def __clearRepositoryCache(self, duplicate=None): """Called when we change the repository(ies) for a directory. This clears any cached information that is invalidated by changing the repository.""" for node in self.entries.values(): if node != self.dir: if node != self and isinstance(node, Dir): node.__clearRepositoryCache(duplicate) else: node.clear() try: del node._srcreps except AttributeError: pass if duplicate is not None: node.duplicate=duplicate def __resetDuplicate(self, node): if node != self: node.duplicate = node.get_dir().duplicate def Entry(self, name): """ Looks up or creates an entry node named 'name' relative to this directory. """ return self.fs.Entry(name, self) def Dir(self, name, create=True): """ Looks up or creates a directory node named 'name' relative to this directory. """ return self.fs.Dir(name, self, create) def File(self, name): """ Looks up or creates a file node named 'name' relative to this directory. """ return self.fs.File(name, self) def link(self, srcdir, duplicate): """Set this directory as the variant directory for the supplied source directory.""" self.srcdir = srcdir self.duplicate = duplicate self.__clearRepositoryCache(duplicate) srcdir.variant_dirs.append(self) def getRepositories(self): """Returns a list of repositories for this directory. """ if self.srcdir and not self.duplicate: return self.srcdir.get_all_rdirs() + self.repositories return self.repositories memoizer_counters.append(SCons.Memoize.CountValue('get_all_rdirs')) def get_all_rdirs(self): try: return list(self._memo['get_all_rdirs']) except KeyError: pass result = [self] fname = '.' dir = self while dir: for rep in dir.getRepositories(): result.append(rep.Dir(fname)) if fname == '.': fname = dir.name else: fname = dir.name + OS_SEP + fname dir = dir.up() self._memo['get_all_rdirs'] = list(result) return result def addRepository(self, dir): if dir != self and not dir in self.repositories: self.repositories.append(dir) dir.tpath = '.' self.__clearRepositoryCache() def up(self): return self.dir def _rel_path_key(self, other): return str(other) memoizer_counters.append(SCons.Memoize.CountDict('rel_path', _rel_path_key)) def rel_path(self, other): """Return a path to "other" relative to this directory. """ # This complicated and expensive method, which constructs relative # paths between arbitrary Node.FS objects, is no longer used # by SCons itself. It was introduced to store dependency paths # in .sconsign files relative to the target, but that ended up # being significantly inefficient. # # We're continuing to support the method because some SConstruct # files out there started using it when it was available, and # we're all about backwards compatibility.. try: memo_dict = self._memo['rel_path'] except KeyError: memo_dict = {} self._memo['rel_path'] = memo_dict else: try: return memo_dict[other] except KeyError: pass if self is other: result = '.' elif not other in self.path_elements: try: other_dir = other.get_dir() except AttributeError: result = str(other) else: if other_dir is None: result = other.name else: dir_rel_path = self.rel_path(other_dir) if dir_rel_path == '.': result = other.name else: result = dir_rel_path + OS_SEP + other.name else: i = self.path_elements.index(other) + 1 path_elems = ['..'] * (len(self.path_elements) - i) \ + [n.name for n in other.path_elements[i:]] result = OS_SEP.join(path_elems) memo_dict[other] = result return result def get_env_scanner(self, env, kw={}): import SCons.Defaults return SCons.Defaults.DirEntryScanner def get_target_scanner(self): import SCons.Defaults return SCons.Defaults.DirEntryScanner def get_found_includes(self, env, scanner, path): """Return this directory's implicit dependencies. We don't bother caching the results because the scan typically shouldn't be requested more than once (as opposed to scanning .h file contents, which can be requested as many times as the files is #included by other files). """ if not scanner: return [] # Clear cached info for this Dir. If we already visited this # directory on our walk down the tree (because we didn't know at # that point it was being used as the source for another Node) # then we may have calculated build signature before realizing # we had to scan the disk. Now that we have to, though, we need # to invalidate the old calculated signature so that any node # dependent on our directory structure gets one that includes # info about everything on disk. self.clear() return scanner(self, env, path) # # Taskmaster interface subsystem # def prepare(self): pass def build(self, **kw): """A null "builder" for directories.""" global MkdirBuilder if self.builder is not MkdirBuilder: SCons.Node.Node.build(self, **kw) # # # def _create(self): """Create this directory, silently and without worrying about whether the builder is the default or not.""" listDirs = [] parent = self while parent: if parent.exists(): break listDirs.append(parent) p = parent.up() if p is None: # Don't use while: - else: for this condition because # if so, then parent is None and has no .path attribute. raise SCons.Errors.StopError(parent.path) parent = p listDirs.reverse() for dirnode in listDirs: try: # Don't call dirnode.build(), call the base Node method # directly because we definitely *must* create this # directory. The dirnode.build() method will suppress # the build if it's the default builder. SCons.Node.Node.build(dirnode) dirnode.get_executor().nullify() # The build() action may or may not have actually # created the directory, depending on whether the -n # option was used or not. Delete the _exists and # _rexists attributes so they can be reevaluated. dirnode.clear() except OSError: pass def multiple_side_effect_has_builder(self): global MkdirBuilder return self.builder is not MkdirBuilder and self.has_builder() def alter_targets(self): """Return any corresponding targets in a variant directory. """ return self.fs.variant_dir_target_climb(self, self, []) def scanner_key(self): """A directory does not get scanned.""" return None def get_text_contents(self): """We already emit things in text, so just return the binary version.""" return self.get_contents() def get_contents(self): """Return content signatures and names of all our children separated by new-lines. Ensure that the nodes are sorted.""" contents = [] for node in sorted(self.children(), key=lambda t: t.name): contents.append('%s %s\n' % (node.get_csig(), node.name)) return ''.join(contents) def get_csig(self): """Compute the content signature for Directory nodes. In general, this is not needed and the content signature is not stored in the DirNodeInfo. However, if get_contents on a Dir node is called which has a child directory, the child directory should return the hash of its contents.""" contents = self.get_contents() return SCons.Util.MD5signature(contents) def do_duplicate(self, src): pass changed_since_last_build = SCons.Node.Node.state_has_changed def is_up_to_date(self): """If any child is not up-to-date, then this directory isn't, either.""" if self.builder is not MkdirBuilder and not self.exists(): return 0 up_to_date = SCons.Node.up_to_date for kid in self.children(): if kid.get_state() > up_to_date: return 0 return 1 def rdir(self): if not self.exists(): norm_name = _my_normcase(self.name) for dir in self.dir.get_all_rdirs(): try: node = dir.entries[norm_name] except KeyError: node = dir.dir_on_disk(self.name) if node and node.exists() and \ (isinstance(dir, Dir) or isinstance(dir, Entry)): return node return self def sconsign(self): """Return the .sconsign file info for this directory, creating it first if necessary.""" if not self._sconsign: import SCons.SConsign self._sconsign = SCons.SConsign.ForDirectory(self) return self._sconsign def srcnode(self): """Dir has a special need for srcnode()...if we have a srcdir attribute set, then that *is* our srcnode.""" if self.srcdir: return self.srcdir return Base.srcnode(self) def get_timestamp(self): """Return the latest timestamp from among our children""" stamp = 0 for kid in self.children(): if kid.get_timestamp() > stamp: stamp = kid.get_timestamp() return stamp def entry_abspath(self, name): return self.abspath + OS_SEP + name def entry_labspath(self, name): return self.labspath + '/' + name def entry_path(self, name): return self.path + OS_SEP + name def entry_tpath(self, name): return self.tpath + OS_SEP + name def entry_exists_on_disk(self, name): try: d = self.on_disk_entries except AttributeError: d = {} try: entries = os.listdir(self.abspath) except OSError: pass else: for entry in map(_my_normcase, entries): d[entry] = True self.on_disk_entries = d if sys.platform == 'win32': name = _my_normcase(name) result = d.get(name) if result is None: # Belt-and-suspenders for Windows: check directly for # 8.3 file names that don't show up in os.listdir(). result = os.path.exists(self.abspath + OS_SEP + name) d[name] = result return result else: return name in d memoizer_counters.append(SCons.Memoize.CountValue('srcdir_list')) def srcdir_list(self): try: return self._memo['srcdir_list'] except KeyError: pass result = [] dirname = '.' dir = self while dir: if dir.srcdir: result.append(dir.srcdir.Dir(dirname)) dirname = dir.name + OS_SEP + dirname dir = dir.up() self._memo['srcdir_list'] = result return result def srcdir_duplicate(self, name): for dir in self.srcdir_list(): if self.is_under(dir): # We shouldn't source from something in the build path; # variant_dir is probably under src_dir, in which case # we are reflecting. break if dir.entry_exists_on_disk(name): srcnode = dir.Entry(name).disambiguate() if self.duplicate: node = self.Entry(name).disambiguate() node.do_duplicate(srcnode) return node else: return srcnode return None def _srcdir_find_file_key(self, filename): return filename memoizer_counters.append(SCons.Memoize.CountDict('srcdir_find_file', _srcdir_find_file_key)) def srcdir_find_file(self, filename): try: memo_dict = self._memo['srcdir_find_file'] except KeyError: memo_dict = {} self._memo['srcdir_find_file'] = memo_dict else: try: return memo_dict[filename] except KeyError: pass def func(node): if (isinstance(node, File) or isinstance(node, Entry)) and \ (node.is_derived() or node.exists()): return node return None norm_name = _my_normcase(filename) for rdir in self.get_all_rdirs(): try: node = rdir.entries[norm_name] except KeyError: node = rdir.file_on_disk(filename) else: node = func(node) if node: result = (node, self) memo_dict[filename] = result return result for srcdir in self.srcdir_list(): for rdir in srcdir.get_all_rdirs(): try: node = rdir.entries[norm_name] except KeyError: node = rdir.file_on_disk(filename) else: node = func(node) if node: result = (File(filename, self, self.fs), srcdir) memo_dict[filename] = result return result result = (None, None) memo_dict[filename] = result return result def dir_on_disk(self, name): if self.entry_exists_on_disk(name): try: return self.Dir(name) except TypeError: pass node = self.srcdir_duplicate(name) if isinstance(node, File): return None return node def file_on_disk(self, name): if self.entry_exists_on_disk(name) or \ diskcheck_rcs(self, name) or \ diskcheck_sccs(self, name): try: return self.File(name) except TypeError: pass node = self.srcdir_duplicate(name) if isinstance(node, Dir): return None return node def walk(self, func, arg): """ Walk this directory tree by calling the specified function for each directory in the tree. This behaves like the os.path.walk() function, but for in-memory Node.FS.Dir objects. The function takes the same arguments as the functions passed to os.path.walk(): func(arg, dirname, fnames) Except that "dirname" will actually be the directory *Node*, not the string. The '.' and '..' entries are excluded from fnames. The fnames list may be modified in-place to filter the subdirectories visited or otherwise impose a specific order. The "arg" argument is always passed to func() and may be used in any way (or ignored, passing None is common). """ entries = self.entries names = list(entries.keys()) names.remove('.') names.remove('..') func(arg, self, names) for dirname in [n for n in names if isinstance(entries[n], Dir)]: entries[dirname].walk(func, arg) def glob(self, pathname, ondisk=True, source=False, strings=False): """ Returns a list of Nodes (or strings) matching a specified pathname pattern. Pathname patterns follow UNIX shell semantics: * matches any-length strings of any characters, ? matches any character, and [] can enclose lists or ranges of characters. Matches do not span directory separators. The matches take into account Repositories, returning local Nodes if a corresponding entry exists in a Repository (either an in-memory Node or something on disk). By defafult, the glob() function matches entries that exist on-disk, in addition to in-memory Nodes. Setting the "ondisk" argument to False (or some other non-true value) causes the glob() function to only match in-memory Nodes. The default behavior is to return both the on-disk and in-memory Nodes. The "source" argument, when true, specifies that corresponding source Nodes must be returned if you're globbing in a build directory (initialized with VariantDir()). The default behavior is to return Nodes local to the VariantDir(). The "strings" argument, when true, returns the matches as strings, not Nodes. The strings are path names relative to this directory. The underlying algorithm is adapted from the glob.glob() function in the Python library (but heavily modified), and uses fnmatch() under the covers. """ dirname, basename = os.path.split(pathname) if not dirname: return sorted(self._glob1(basename, ondisk, source, strings), key=lambda t: str(t)) if has_glob_magic(dirname): list = self.glob(dirname, ondisk, source, strings=False) else: list = [self.Dir(dirname, create=True)] result = [] for dir in list: r = dir._glob1(basename, ondisk, source, strings) if strings: r = [os.path.join(str(dir), x) for x in r] result.extend(r) return sorted(result, key=lambda a: str(a)) def _glob1(self, pattern, ondisk=True, source=False, strings=False): """ Globs for and returns a list of entry names matching a single pattern in this directory. This searches any repositories and source directories for corresponding entries and returns a Node (or string) relative to the current directory if an entry is found anywhere. TODO: handle pattern with no wildcard """ search_dir_list = self.get_all_rdirs() for srcdir in self.srcdir_list(): search_dir_list.extend(srcdir.get_all_rdirs()) selfEntry = self.Entry names = [] for dir in search_dir_list: # We use the .name attribute from the Node because the keys of # the dir.entries dictionary are normalized (that is, all upper # case) on case-insensitive systems like Windows. node_names = [ v.name for k, v in dir.entries.items() if k not in ('.', '..') ] names.extend(node_names) if not strings: # Make sure the working directory (self) actually has # entries for all Nodes in repositories or variant dirs. for name in node_names: selfEntry(name) if ondisk: try: disk_names = os.listdir(dir.abspath) except os.error: continue names.extend(disk_names) if not strings: # We're going to return corresponding Nodes in # the local directory, so we need to make sure # those Nodes exist. We only want to create # Nodes for the entries that will match the # specified pattern, though, which means we # need to filter the list here, even though # the overall list will also be filtered later, # after we exit this loop. if pattern[0] != '.': #disk_names = [ d for d in disk_names if d[0] != '.' ] disk_names = [x for x in disk_names if x[0] != '.'] disk_names = fnmatch.filter(disk_names, pattern) dirEntry = dir.Entry for name in disk_names: # Add './' before disk filename so that '#' at # beginning of filename isn't interpreted. name = './' + name node = dirEntry(name).disambiguate() n = selfEntry(name) if n.__class__ != node.__class__: n.__class__ = node.__class__ n._morph() names = set(names) if pattern[0] != '.': #names = [ n for n in names if n[0] != '.' ] names = [x for x in names if x[0] != '.'] names = fnmatch.filter(names, pattern) if strings: return names #return [ self.entries[_my_normcase(n)] for n in names ] return [self.entries[_my_normcase(n)] for n in names] class RootDir(Dir): """A class for the root directory of a file system. This is the same as a Dir class, except that the path separator ('/' or '\\') is actually part of the name, so we don't need to add a separator when creating the path names of entries within this directory. """ def __init__(self, drive, fs): if __debug__: logInstanceCreation(self, 'Node.FS.RootDir') # We're going to be our own parent directory (".." entry and .dir # attribute) so we have to set up some values so Base.__init__() # won't gag won't it calls some of our methods. self.abspath = '' self.labspath = '' self.path = '' self.tpath = '' self.path_elements = [] self.duplicate = 0 self.root = self # Handle all the types of drives: if drive == '': # No drive, regular UNIX root or Windows default drive. name = OS_SEP dirname = OS_SEP elif drive == '//': # UNC path name = UNC_PREFIX dirname = UNC_PREFIX else: # Windows drive letter name = drive dirname = drive + OS_SEP Base.__init__(self, name, self, fs) # Now set our paths to what we really want them to be. The # name should already contain any necessary separators, such # as the initial drive letter (the name) plus the directory # separator, except for the "lookup abspath," which does not # have the drive letter. self.abspath = dirname self.labspath = '' self.path = dirname self.tpath = dirname self._morph() # Must be reset after Dir._morph() is invoked... self.dirname = dirname self._lookupDict = {} self._lookupDict[''] = self self._lookupDict['/'] = self # The // entry is necessary because os.path.normpath() # preserves double slashes at the beginning of a path on Posix # platforms. if not has_unc: self._lookupDict['//'] = self def must_be_same(self, klass): if klass is Dir: return Base.must_be_same(self, klass) def _lookup_abs(self, p, klass, create=1): """ Fast (?) lookup of a *normalized* absolute path. This method is intended for use by internal lookups with already-normalized path data. For general-purpose lookups, use the FS.Entry(), FS.Dir() or FS.File() methods. The caller is responsible for making sure we're passed a normalized absolute path; we merely let Python's dictionary look up and return the One True Node.FS object for the path. If a Node for the specified "p" doesn't already exist, and "create" is specified, the Node may be created after recursive invocation to find or create the parent directory or directories. """ k = _my_normcase(p) try: result = self._lookupDict[k] except KeyError: if not create: msg = "No such file or directory: '%s' in '%s' (and create is False)" % (p, str(self)) raise SCons.Errors.UserError(msg) # There is no Node for this path name, and we're allowed # to create it. # (note: would like to use p.rsplit('/',1) here but # that's not in python 2.3) # e.g.: dir_name, file_name = p.rsplit('/',1) last_slash = p.rindex('/') if (last_slash >= 0): dir_name = p[:last_slash] file_name = p[last_slash+1:] else: dir_name = p # shouldn't happen, just in case file_name = '' dir_node = self._lookup_abs(dir_name, Dir) result = klass(file_name, dir_node, self.fs) # Double-check on disk (as configured) that the Node we # created matches whatever is out there in the real world. result.diskcheck_match() self._lookupDict[k] = result dir_node.entries[_my_normcase(file_name)] = result dir_node.implicit = None else: # There is already a Node for this path name. Allow it to # complain if we were looking for an inappropriate type. result.must_be_same(klass) return result def __str__(self): return self.abspath def entry_abspath(self, name): return self.abspath + name def entry_labspath(self, name): return '/' + name def entry_path(self, name): return self.path + name def entry_tpath(self, name): return self.tpath + name def is_under(self, dir): if self is dir: return 1 else: return 0 def up(self): return None def get_dir(self): return None def src_builder(self): return _null class FileNodeInfo(SCons.Node.NodeInfoBase): current_version_id = 1 field_list = ['csig', 'timestamp', 'size'] # This should get reset by the FS initialization. fs = None def str_to_node(self, s): top = self.fs.Top root = top.root if do_splitdrive: drive, s = _my_splitdrive(s) if drive: root = self.fs.get_root(drive) if not os.path.isabs(s): s = top.labspath + '/' + s return root._lookup_abs(s, Entry) class FileBuildInfo(SCons.Node.BuildInfoBase): current_version_id = 1 def convert_to_sconsign(self): """ Converts this FileBuildInfo object for writing to a .sconsign file This replaces each Node in our various dependency lists with its usual string representation: relative to the top-level SConstruct directory, or an absolute path if it's outside. """ if os_sep_is_slash: node_to_str = str else: def node_to_str(n): try: s = n.path except AttributeError: s = str(n) else: s = s.replace(OS_SEP, '/') return s for attr in ['bsources', 'bdepends', 'bimplicit']: try: val = getattr(self, attr) except AttributeError: pass else: setattr(self, attr, list(map(node_to_str, val))) def convert_from_sconsign(self, dir, name): """ Converts a newly-read FileBuildInfo object for in-SCons use For normal up-to-date checking, we don't have any conversion to perform--but we're leaving this method here to make that clear. """ pass def prepare_dependencies(self): """ Prepares a FileBuildInfo object for explaining what changed The bsources, bdepends and bimplicit lists have all been stored on disk as paths relative to the top-level SConstruct directory. Convert the strings to actual Nodes (for use by the --debug=explain code and --implicit-cache). """ attrs = [ ('bsources', 'bsourcesigs'), ('bdepends', 'bdependsigs'), ('bimplicit', 'bimplicitsigs'), ] for (nattr, sattr) in attrs: try: strings = getattr(self, nattr) nodeinfos = getattr(self, sattr) except AttributeError: continue nodes = [] for s, ni in zip(strings, nodeinfos): if not isinstance(s, SCons.Node.Node): s = ni.str_to_node(s) nodes.append(s) setattr(self, nattr, nodes) def format(self, names=0): result = [] bkids = self.bsources + self.bdepends + self.bimplicit bkidsigs = self.bsourcesigs + self.bdependsigs + self.bimplicitsigs for bkid, bkidsig in zip(bkids, bkidsigs): result.append(str(bkid) + ': ' + ' '.join(bkidsig.format(names=names))) result.append('%s [%s]' % (self.bactsig, self.bact)) return '\n'.join(result) class File(Base): """A class for files in a file system. """ memoizer_counters = [] NodeInfo = FileNodeInfo BuildInfo = FileBuildInfo md5_chunksize = 64 def diskcheck_match(self): diskcheck_match(self, self.isdir, "Directory %s found where file expected.") def __init__(self, name, directory, fs): if __debug__: logInstanceCreation(self, 'Node.FS.File') Base.__init__(self, name, directory, fs) self._morph() def Entry(self, name): """Create an entry node named 'name' relative to the directory of this file.""" return self.dir.Entry(name) def Dir(self, name, create=True): """Create a directory node named 'name' relative to the directory of this file.""" return self.dir.Dir(name, create=create) def Dirs(self, pathlist): """Create a list of directories relative to the SConscript directory of this file.""" return [self.Dir(p) for p in pathlist] def File(self, name): """Create a file node named 'name' relative to the directory of this file.""" return self.dir.File(name) #def generate_build_dict(self): # """Return an appropriate dictionary of values for building # this File.""" # return {'Dir' : self.Dir, # 'File' : self.File, # 'RDirs' : self.RDirs} def _morph(self): """Turn a file system node into a File object.""" self.scanner_paths = {} if not hasattr(self, '_local'): self._local = 0 # If there was already a Builder set on this entry, then # we need to make sure we call the target-decider function, # not the source-decider. Reaching in and doing this by hand # is a little bogus. We'd prefer to handle this by adding # an Entry.builder_set() method that disambiguates like the # other methods, but that starts running into problems with the # fragile way we initialize Dir Nodes with their Mkdir builders, # yet still allow them to be overridden by the user. Since it's # not clear right now how to fix that, stick with what works # until it becomes clear... if self.has_builder(): self.changed_since_last_build = self.decide_target def scanner_key(self): return self.get_suffix() def get_contents(self): if not self.rexists(): return '' fname = self.rfile().abspath try: contents = open(fname, "rb").read() except EnvironmentError, e: if not e.filename: e.filename = fname raise return contents # This attempts to figure out what the encoding of the text is # based upon the BOM bytes, and then decodes the contents so that # it's a valid python string. def get_text_contents(self): contents = self.get_contents() # The behavior of various decode() methods and functions # w.r.t. the initial BOM bytes is different for different # encodings and/or Python versions. ('utf-8' does not strip # them, but has a 'utf-8-sig' which does; 'utf-16' seems to # strip them; etc.) Just sidestep all the complication by # explicitly stripping the BOM before we decode(). if contents.startswith(codecs.BOM_UTF8): return contents[len(codecs.BOM_UTF8):].decode('utf-8') if contents.startswith(codecs.BOM_UTF16_LE): return contents[len(codecs.BOM_UTF16_LE):].decode('utf-16-le') if contents.startswith(codecs.BOM_UTF16_BE): return contents[len(codecs.BOM_UTF16_BE):].decode('utf-16-be') return contents def get_content_hash(self): """ Compute and return the MD5 hash for this file. """ if not self.rexists(): return SCons.Util.MD5signature('') fname = self.rfile().abspath try: cs = SCons.Util.MD5filesignature(fname, chunksize=SCons.Node.FS.File.md5_chunksize*1024) except EnvironmentError, e: if not e.filename: e.filename = fname raise return cs memoizer_counters.append(SCons.Memoize.CountValue('get_size')) def get_size(self): try: return self._memo['get_size'] except KeyError: pass if self.rexists(): size = self.rfile().getsize() else: size = 0 self._memo['get_size'] = size return size memoizer_counters.append(SCons.Memoize.CountValue('get_timestamp')) def get_timestamp(self): try: return self._memo['get_timestamp'] except KeyError: pass if self.rexists(): timestamp = self.rfile().getmtime() else: timestamp = 0 self._memo['get_timestamp'] = timestamp return timestamp def store_info(self): # Merge our build information into the already-stored entry. # This accomodates "chained builds" where a file that's a target # in one build (SConstruct file) is a source in a different build. # See test/chained-build.py for the use case. if do_store_info: self.dir.sconsign().store_info(self.name, self) convert_copy_attrs = [ 'bsources', 'bimplicit', 'bdepends', 'bact', 'bactsig', 'ninfo', ] convert_sig_attrs = [ 'bsourcesigs', 'bimplicitsigs', 'bdependsigs', ] def convert_old_entry(self, old_entry): # Convert a .sconsign entry from before the Big Signature # Refactoring, doing what we can to convert its information # to the new .sconsign entry format. # # The old format looked essentially like this: # # BuildInfo # .ninfo (NodeInfo) # .bsig # .csig # .timestamp # .size # .bsources # .bsourcesigs ("signature" list) # .bdepends # .bdependsigs ("signature" list) # .bimplicit # .bimplicitsigs ("signature" list) # .bact # .bactsig # # The new format looks like this: # # .ninfo (NodeInfo) # .bsig # .csig # .timestamp # .size # .binfo (BuildInfo) # .bsources # .bsourcesigs (NodeInfo list) # .bsig # .csig # .timestamp # .size # .bdepends # .bdependsigs (NodeInfo list) # .bsig # .csig # .timestamp # .size # .bimplicit # .bimplicitsigs (NodeInfo list) # .bsig # .csig # .timestamp # .size # .bact # .bactsig # # The basic idea of the new structure is that a NodeInfo always # holds all available information about the state of a given Node # at a certain point in time. The various .b*sigs lists can just # be a list of pointers to the .ninfo attributes of the different # dependent nodes, without any copying of information until it's # time to pickle it for writing out to a .sconsign file. # # The complicating issue is that the *old* format only stored one # "signature" per dependency, based on however the *last* build # was configured. We don't know from just looking at it whether # it was a build signature, a content signature, or a timestamp # "signature". Since we no longer use build signatures, the # best we can do is look at the length and if it's thirty two, # assume that it was (or might have been) a content signature. # If it was actually a build signature, then it will cause a # rebuild anyway when it doesn't match the new content signature, # but that's probably the best we can do. import SCons.SConsign new_entry = SCons.SConsign.SConsignEntry() new_entry.binfo = self.new_binfo() binfo = new_entry.binfo for attr in self.convert_copy_attrs: try: value = getattr(old_entry, attr) except AttributeError: continue setattr(binfo, attr, value) delattr(old_entry, attr) for attr in self.convert_sig_attrs: try: sig_list = getattr(old_entry, attr) except AttributeError: continue value = [] for sig in sig_list: ninfo = self.new_ninfo() if len(sig) == 32: ninfo.csig = sig else: ninfo.timestamp = sig value.append(ninfo) setattr(binfo, attr, value) delattr(old_entry, attr) return new_entry memoizer_counters.append(SCons.Memoize.CountValue('get_stored_info')) def get_stored_info(self): try: return self._memo['get_stored_info'] except KeyError: pass try: sconsign_entry = self.dir.sconsign().get_entry(self.name) except (KeyError, EnvironmentError): import SCons.SConsign sconsign_entry = SCons.SConsign.SConsignEntry() sconsign_entry.binfo = self.new_binfo() sconsign_entry.ninfo = self.new_ninfo() else: if isinstance(sconsign_entry, FileBuildInfo): # This is a .sconsign file from before the Big Signature # Refactoring; convert it as best we can. sconsign_entry = self.convert_old_entry(sconsign_entry) try: delattr(sconsign_entry.ninfo, 'bsig') except AttributeError: pass self._memo['get_stored_info'] = sconsign_entry return sconsign_entry def get_stored_implicit(self): binfo = self.get_stored_info().binfo binfo.prepare_dependencies() try: return binfo.bimplicit except AttributeError: return None def rel_path(self, other): return self.dir.rel_path(other) def _get_found_includes_key(self, env, scanner, path): return (id(env), id(scanner), path) memoizer_counters.append(SCons.Memoize.CountDict('get_found_includes', _get_found_includes_key)) def get_found_includes(self, env, scanner, path): """Return the included implicit dependencies in this file. Cache results so we only scan the file once per path regardless of how many times this information is requested. """ memo_key = (id(env), id(scanner), path) try: memo_dict = self._memo['get_found_includes'] except KeyError: memo_dict = {} self._memo['get_found_includes'] = memo_dict else: try: return memo_dict[memo_key] except KeyError: pass if scanner: # result = [n.disambiguate() for n in scanner(self, env, path)] result = scanner(self, env, path) result = [N.disambiguate() for N in result] else: result = [] memo_dict[memo_key] = result return result def _createDir(self): # ensure that the directories for this node are # created. self.dir._create() def push_to_cache(self): """Try to push the node into a cache """ # This should get called before the Nodes' .built() method is # called, which would clear the build signature if the file has # a source scanner. # # We have to clear the local memoized values *before* we push # the node to cache so that the memoization of the self.exists() # return value doesn't interfere. if self.nocache: return self.clear_memoized_values() if self.exists(): self.get_build_env().get_CacheDir().push(self) def retrieve_from_cache(self): """Try to retrieve the node's content from a cache This method is called from multiple threads in a parallel build, so only do thread safe stuff here. Do thread unsafe stuff in built(). Returns true if the node was successfully retrieved. """ if self.nocache: return None if not self.is_derived(): return None return self.get_build_env().get_CacheDir().retrieve(self) def visited(self): if self.exists(): self.get_build_env().get_CacheDir().push_if_forced(self) ninfo = self.get_ninfo() csig = self.get_max_drift_csig() if csig: ninfo.csig = csig ninfo.timestamp = self.get_timestamp() ninfo.size = self.get_size() if not self.has_builder(): # This is a source file, but it might have been a target file # in another build that included more of the DAG. Copy # any build information that's stored in the .sconsign file # into our binfo object so it doesn't get lost. old = self.get_stored_info() self.get_binfo().__dict__.update(old.binfo.__dict__) self.store_info() def find_src_builder(self): if self.rexists(): return None scb = self.dir.src_builder() if scb is _null: if diskcheck_sccs(self.dir, self.name): scb = get_DefaultSCCSBuilder() elif diskcheck_rcs(self.dir, self.name): scb = get_DefaultRCSBuilder() else: scb = None if scb is not None: try: b = self.builder except AttributeError: b = None if b is None: self.builder_set(scb) return scb def has_src_builder(self): """Return whether this Node has a source builder or not. If this Node doesn't have an explicit source code builder, this is where we figure out, on the fly, if there's a transparent source code builder for it. Note that if we found a source builder, we also set the self.builder attribute, so that all of the methods that actually *build* this file don't have to do anything different. """ try: scb = self.sbuilder except AttributeError: scb = self.sbuilder = self.find_src_builder() return scb is not None def alter_targets(self): """Return any corresponding targets in a variant directory. """ if self.is_derived(): return [], None return self.fs.variant_dir_target_climb(self, self.dir, [self.name]) def _rmv_existing(self): self.clear_memoized_values() if print_duplicate: print "dup: removing existing target %s"%self e = Unlink(self, [], None) if isinstance(e, SCons.Errors.BuildError): raise e # # Taskmaster interface subsystem # def make_ready(self): self.has_src_builder() self.get_binfo() def prepare(self): """Prepare for this file to be created.""" SCons.Node.Node.prepare(self) if self.get_state() != SCons.Node.up_to_date: if self.exists(): if self.is_derived() and not self.precious: self._rmv_existing() else: try: self._createDir() except SCons.Errors.StopError, drive: desc = "No drive `%s' for target `%s'." % (drive, self) raise SCons.Errors.StopError(desc) # # # def remove(self): """Remove this file.""" if self.exists() or self.islink(): self.fs.unlink(self.path) return 1 return None def do_duplicate(self, src): self._createDir() if print_duplicate: print "dup: relinking variant '%s' from '%s'"%(self, src) Unlink(self, None, None) e = Link(self, src, None) if isinstance(e, SCons.Errors.BuildError): desc = "Cannot duplicate `%s' in `%s': %s." % (src.path, self.dir.path, e.errstr) raise SCons.Errors.StopError(desc) self.linked = 1 # The Link() action may or may not have actually # created the file, depending on whether the -n # option was used or not. Delete the _exists and # _rexists attributes so they can be reevaluated. self.clear() memoizer_counters.append(SCons.Memoize.CountValue('exists')) def exists(self): try: return self._memo['exists'] except KeyError: pass # Duplicate from source path if we are set up to do this. if self.duplicate and not self.is_derived() and not self.linked: src = self.srcnode() if src is not self: # At this point, src is meant to be copied in a variant directory. src = src.rfile() if src.abspath != self.abspath: if src.exists(): self.do_duplicate(src) # Can't return 1 here because the duplication might # not actually occur if the -n option is being used. else: # The source file does not exist. Make sure no old # copy remains in the variant directory. if print_duplicate: print "dup: no src for %s, unlinking old variant copy"%self if Base.exists(self) or self.islink(): self.fs.unlink(self.path) # Return None explicitly because the Base.exists() call # above will have cached its value if the file existed. self._memo['exists'] = None return None result = Base.exists(self) self._memo['exists'] = result return result # # SIGNATURE SUBSYSTEM # def get_max_drift_csig(self): """ Returns the content signature currently stored for this node if it's been unmodified longer than the max_drift value, or the max_drift value is 0. Returns None otherwise. """ old = self.get_stored_info() mtime = self.get_timestamp() max_drift = self.fs.max_drift if max_drift > 0: if (time.time() - mtime) > max_drift: try: n = old.ninfo if n.timestamp and n.csig and n.timestamp == mtime: return n.csig except AttributeError: pass elif max_drift == 0: try: return old.ninfo.csig except AttributeError: pass return None def get_csig(self): """ Generate a node's content signature, the digested signature of its content. node - the node cache - alternate node to use for the signature cache returns - the content signature """ ninfo = self.get_ninfo() try: return ninfo.csig except AttributeError: pass csig = self.get_max_drift_csig() if csig is None: try: if self.get_size() < SCons.Node.FS.File.md5_chunksize: contents = self.get_contents() else: csig = self.get_content_hash() except IOError: # This can happen if there's actually a directory on-disk, # which can be the case if they've disabled disk checks, # or if an action with a File target actually happens to # create a same-named directory by mistake. csig = '' else: if not csig: csig = SCons.Util.MD5signature(contents) ninfo.csig = csig return csig # # DECISION SUBSYSTEM # def builder_set(self, builder): SCons.Node.Node.builder_set(self, builder) self.changed_since_last_build = self.decide_target def changed_content(self, target, prev_ni): cur_csig = self.get_csig() try: return cur_csig != prev_ni.csig except AttributeError: return 1 def changed_state(self, target, prev_ni): return self.state != SCons.Node.up_to_date def changed_timestamp_then_content(self, target, prev_ni): if not self.changed_timestamp_match(target, prev_ni): try: self.get_ninfo().csig = prev_ni.csig except AttributeError: pass return False return self.changed_content(target, prev_ni) def changed_timestamp_newer(self, target, prev_ni): try: return self.get_timestamp() > target.get_timestamp() except AttributeError: return 1 def changed_timestamp_match(self, target, prev_ni): try: return self.get_timestamp() != prev_ni.timestamp except AttributeError: return 1 def decide_source(self, target, prev_ni): return target.get_build_env().decide_source(self, target, prev_ni) def decide_target(self, target, prev_ni): return target.get_build_env().decide_target(self, target, prev_ni) # Initialize this Node's decider function to decide_source() because # every file is a source file until it has a Builder attached... changed_since_last_build = decide_source def is_up_to_date(self): T = 0 if T: Trace('is_up_to_date(%s):' % self) if not self.exists(): if T: Trace(' not self.exists():') # The file doesn't exist locally... r = self.rfile() if r != self: # ...but there is one in a Repository... if not self.changed(r): if T: Trace(' changed(%s):' % r) # ...and it's even up-to-date... if self._local: # ...and they'd like a local copy. e = LocalCopy(self, r, None) if isinstance(e, SCons.Errors.BuildError): raise self.store_info() if T: Trace(' 1\n') return 1 self.changed() if T: Trace(' None\n') return None else: r = self.changed() if T: Trace(' self.exists(): %s\n' % r) return not r memoizer_counters.append(SCons.Memoize.CountValue('rfile')) def rfile(self): try: return self._memo['rfile'] except KeyError: pass result = self if not self.exists(): norm_name = _my_normcase(self.name) for dir in self.dir.get_all_rdirs(): try: node = dir.entries[norm_name] except KeyError: node = dir.file_on_disk(self.name) if node and node.exists() and \ (isinstance(node, File) or isinstance(node, Entry) \ or not node.is_derived()): result = node # Copy over our local attributes to the repository # Node so we identify shared object files in the # repository and don't assume they're static. # # This isn't perfect; the attribute would ideally # be attached to the object in the repository in # case it was built statically in the repository # and we changed it to shared locally, but that's # rarely the case and would only occur if you # intentionally used the same suffix for both # shared and static objects anyway. So this # should work well in practice. result.attributes = self.attributes break self._memo['rfile'] = result return result def rstr(self): return str(self.rfile()) def get_cachedir_csig(self): """ Fetch a Node's content signature for purposes of computing another Node's cachesig. This is a wrapper around the normal get_csig() method that handles the somewhat obscure case of using CacheDir with the -n option. Any files that don't exist would normally be "built" by fetching them from the cache, but the normal get_csig() method will try to open up the local file, which doesn't exist because the -n option meant we didn't actually pull the file from cachedir. But since the file *does* actually exist in the cachedir, we can use its contents for the csig. """ try: return self.cachedir_csig except AttributeError: pass cachedir, cachefile = self.get_build_env().get_CacheDir().cachepath(self) if not self.exists() and cachefile and os.path.exists(cachefile): self.cachedir_csig = SCons.Util.MD5filesignature(cachefile, \ SCons.Node.FS.File.md5_chunksize * 1024) else: self.cachedir_csig = self.get_csig() return self.cachedir_csig def get_cachedir_bsig(self): try: return self.cachesig except AttributeError: pass # Add the path to the cache signature, because multiple # targets built by the same action will all have the same # build signature, and we have to differentiate them somehow. children = self.children() executor = self.get_executor() # sigs = [n.get_cachedir_csig() for n in children] sigs = [n.get_cachedir_csig() for n in children] sigs.append(SCons.Util.MD5signature(executor.get_contents())) sigs.append(self.path) result = self.cachesig = SCons.Util.MD5collect(sigs) return result default_fs = None def get_default_fs(): global default_fs if not default_fs: default_fs = FS() return default_fs class FileFinder(object): """ """ if SCons.Memoize.use_memoizer: __metaclass__ = SCons.Memoize.Memoized_Metaclass memoizer_counters = [] def __init__(self): self._memo = {} def filedir_lookup(self, p, fd=None): """ A helper method for find_file() that looks up a directory for a file we're trying to find. This only creates the Dir Node if it exists on-disk, since if the directory doesn't exist we know we won't find any files in it... :-) It would be more compact to just use this as a nested function with a default keyword argument (see the commented-out version below), but that doesn't work unless you have nested scopes, so we define it here just so this work under Python 1.5.2. """ if fd is None: fd = self.default_filedir dir, name = os.path.split(fd) drive, d = _my_splitdrive(dir) if not name and d[:1] in ('/', OS_SEP): #return p.fs.get_root(drive).dir_on_disk(name) return p.fs.get_root(drive) if dir: p = self.filedir_lookup(p, dir) if not p: return None norm_name = _my_normcase(name) try: node = p.entries[norm_name] except KeyError: return p.dir_on_disk(name) if isinstance(node, Dir): return node if isinstance(node, Entry): node.must_be_same(Dir) return node return None def _find_file_key(self, filename, paths, verbose=None): return (filename, paths) memoizer_counters.append(SCons.Memoize.CountDict('find_file', _find_file_key)) def find_file(self, filename, paths, verbose=None): """ find_file(str, [Dir()]) -> [nodes] filename - a filename to find paths - a list of directory path *nodes* to search in. Can be represented as a list, a tuple, or a callable that is called with no arguments and returns the list or tuple. returns - the node created from the found file. Find a node corresponding to either a derived file or a file that exists already. Only the first file found is returned, and none is returned if no file is found. """ memo_key = self._find_file_key(filename, paths) try: memo_dict = self._memo['find_file'] except KeyError: memo_dict = {} self._memo['find_file'] = memo_dict else: try: return memo_dict[memo_key] except KeyError: pass if verbose and not callable(verbose): if not SCons.Util.is_String(verbose): verbose = "find_file" _verbose = u' %s: ' % verbose verbose = lambda s: sys.stdout.write(_verbose + s) filedir, filename = os.path.split(filename) if filedir: # More compact code that we can't use until we drop # support for Python 1.5.2: # #def filedir_lookup(p, fd=filedir): # """ # A helper function that looks up a directory for a file # we're trying to find. This only creates the Dir Node # if it exists on-disk, since if the directory doesn't # exist we know we won't find any files in it... :-) # """ # dir, name = os.path.split(fd) # if dir: # p = filedir_lookup(p, dir) # if not p: # return None # norm_name = _my_normcase(name) # try: # node = p.entries[norm_name] # except KeyError: # return p.dir_on_disk(name) # if isinstance(node, Dir): # return node # if isinstance(node, Entry): # node.must_be_same(Dir) # return node # if isinstance(node, Dir) or isinstance(node, Entry): # return node # return None #paths = [_f for _f in map(filedir_lookup, paths) if _f] self.default_filedir = filedir paths = [_f for _f in map(self.filedir_lookup, paths) if _f] result = None for dir in paths: if verbose: verbose("looking for '%s' in '%s' ...\n" % (filename, dir)) node, d = dir.srcdir_find_file(filename) if node: if verbose: verbose("... FOUND '%s' in '%s'\n" % (filename, d)) result = node break memo_dict[memo_key] = result return result find_file = FileFinder().find_file def invalidate_node_memos(targets): """ Invalidate the memoized values of all Nodes (files or directories) that are associated with the given entries. Has been added to clear the cache of nodes affected by a direct execution of an action (e.g. Delete/Copy/Chmod). Existing Node caches become inconsistent if the action is run through Execute(). The argument `targets` can be a single Node object or filename, or a sequence of Nodes/filenames. """ from traceback import extract_stack # First check if the cache really needs to be flushed. Only # actions run in the SConscript with Execute() seem to be # affected. XXX The way to check if Execute() is in the stacktrace # is a very dirty hack and should be replaced by a more sensible # solution. for f in extract_stack(): if f[2] == 'Execute' and f[0][-14:] == 'Environment.py': break else: # Dont have to invalidate, so return return if not SCons.Util.is_List(targets): targets = [targets] for entry in targets: # If the target is a Node object, clear the cache. If it is a # filename, look up potentially existing Node object first. try: entry.clear_memoized_values() except AttributeError: # Not a Node object, try to look up Node by filename. XXX # This creates Node objects even for those filenames which # do not correspond to an existing Node object. node = get_default_fs().Entry(entry) if node: node.clear_memoized_values() # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Node The Node package for the SCons software construction utility. This is, in many ways, the heart of SCons. A Node is where we encapsulate all of the dependency information about any thing that SCons can build, or about any thing which SCons can use to build some other thing. The canonical "thing," of course, is a file, but a Node can also represent something remote (like a web page) or something completely abstract (like an Alias). Each specific type of "thing" is specifically represented by a subclass of the Node base class: Node.FS.File for files, Node.Alias for aliases, etc. Dependency information is kept here in the base class, and information specific to files/aliases/etc. is in the subclass. The goal, if we've done this correctly, is that any type of "thing" should be able to depend on any other type of "thing." """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. __revision__ = "src/engine/SCons/Node/__init__.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import collections import copy from itertools import chain from SCons.Debug import logInstanceCreation import SCons.Executor import SCons.Memoize import SCons.Util from SCons.Debug import Trace def classname(obj): return str(obj.__class__).split('.')[-1] # Node states # # These are in "priority" order, so that the maximum value for any # child/dependency of a node represents the state of that node if # it has no builder of its own. The canonical example is a file # system directory, which is only up to date if all of its children # were up to date. no_state = 0 pending = 1 executing = 2 up_to_date = 3 executed = 4 failed = 5 StateString = { 0 : "no_state", 1 : "pending", 2 : "executing", 3 : "up_to_date", 4 : "executed", 5 : "failed", } # controls whether implicit dependencies are cached: implicit_cache = 0 # controls whether implicit dep changes are ignored: implicit_deps_unchanged = 0 # controls whether the cached implicit deps are ignored: implicit_deps_changed = 0 # A variable that can be set to an interface-specific function be called # to annotate a Node with information about its creation. def do_nothing(node): pass Annotate = do_nothing # Classes for signature info for Nodes. class NodeInfoBase(object): """ The generic base class for signature information for a Node. Node subclasses should subclass NodeInfoBase to provide their own logic for dealing with their own Node-specific signature information. """ current_version_id = 1 def __init__(self, node=None): # Create an object attribute from the class attribute so it ends up # in the pickled data in the .sconsign file. self._version_id = self.current_version_id def update(self, node): try: field_list = self.field_list except AttributeError: return for f in field_list: try: delattr(self, f) except AttributeError: pass try: func = getattr(node, 'get_' + f) except AttributeError: pass else: setattr(self, f, func()) def convert(self, node, val): pass def merge(self, other): self.__dict__.update(other.__dict__) def format(self, field_list=None, names=0): if field_list is None: try: field_list = self.field_list except AttributeError: field_list = sorted(self.__dict__.keys()) fields = [] for field in field_list: try: f = getattr(self, field) except AttributeError: f = None f = str(f) if names: f = field + ': ' + f fields.append(f) return fields class BuildInfoBase(object): """ The generic base class for build information for a Node. This is what gets stored in a .sconsign file for each target file. It contains a NodeInfo instance for this node (signature information that's specific to the type of Node) and direct attributes for the generic build stuff we have to track: sources, explicit dependencies, implicit dependencies, and action information. """ current_version_id = 1 def __init__(self, node=None): # Create an object attribute from the class attribute so it ends up # in the pickled data in the .sconsign file. self._version_id = self.current_version_id self.bsourcesigs = [] self.bdependsigs = [] self.bimplicitsigs = [] self.bactsig = None def merge(self, other): self.__dict__.update(other.__dict__) class Node(object): """The base Node class, for entities that we know how to build, or use to build other Nodes. """ if SCons.Memoize.use_memoizer: __metaclass__ = SCons.Memoize.Memoized_Metaclass memoizer_counters = [] class Attrs(object): pass def __init__(self): if __debug__: logInstanceCreation(self, 'Node.Node') # Note that we no longer explicitly initialize a self.builder # attribute to None here. That's because the self.builder # attribute may be created on-the-fly later by a subclass (the # canonical example being a builder to fetch a file from a # source code system like CVS or Subversion). # Each list of children that we maintain is accompanied by a # dictionary used to look up quickly whether a node is already # present in the list. Empirical tests showed that it was # fastest to maintain them as side-by-side Node attributes in # this way, instead of wrapping up each list+dictionary pair in # a class. (Of course, we could always still do that in the # future if we had a good reason to...). self.sources = [] # source files used to build node self.sources_set = set() self._specific_sources = False self.depends = [] # explicit dependencies (from Depends) self.depends_set = set() self.ignore = [] # dependencies to ignore self.ignore_set = set() self.prerequisites = SCons.Util.UniqueList() self.implicit = None # implicit (scanned) dependencies (None means not scanned yet) self.waiting_parents = set() self.waiting_s_e = set() self.ref_count = 0 self.wkids = None # Kids yet to walk, when it's an array self.env = None self.state = no_state self.precious = None self.noclean = 0 self.nocache = 0 self.cached = 0 # is this node pulled from cache? self.always_build = None self.includes = None self.attributes = self.Attrs() # Generic place to stick information about the Node. self.side_effect = 0 # true iff this node is a side effect self.side_effects = [] # the side effects of building this target self.linked = 0 # is this node linked to the variant directory? self.clear_memoized_values() # Let the interface in which the build engine is embedded # annotate this Node with its own info (like a description of # what line in what file created the node, for example). Annotate(self) def disambiguate(self, must_exist=None): return self def get_suffix(self): return '' memoizer_counters.append(SCons.Memoize.CountValue('get_build_env')) def get_build_env(self): """Fetch the appropriate Environment to build this node. """ try: return self._memo['get_build_env'] except KeyError: pass result = self.get_executor().get_build_env() self._memo['get_build_env'] = result return result def get_build_scanner_path(self, scanner): """Fetch the appropriate scanner path for this node.""" return self.get_executor().get_build_scanner_path(scanner) def set_executor(self, executor): """Set the action executor for this node.""" self.executor = executor def get_executor(self, create=1): """Fetch the action executor for this node. Create one if there isn't already one, and requested to do so.""" try: executor = self.executor except AttributeError: if not create: raise try: act = self.builder.action except AttributeError: executor = SCons.Executor.Null(targets=[self]) else: executor = SCons.Executor.Executor(act, self.env or self.builder.env, [self.builder.overrides], [self], self.sources) self.executor = executor return executor def executor_cleanup(self): """Let the executor clean up any cached information.""" try: executor = self.get_executor(create=None) except AttributeError: pass else: executor.cleanup() def reset_executor(self): "Remove cached executor; forces recompute when needed." try: delattr(self, 'executor') except AttributeError: pass def push_to_cache(self): """Try to push a node into a cache """ pass def retrieve_from_cache(self): """Try to retrieve the node's content from a cache This method is called from multiple threads in a parallel build, so only do thread safe stuff here. Do thread unsafe stuff in built(). Returns true if the node was successfully retrieved. """ return 0 # # Taskmaster interface subsystem # def make_ready(self): """Get a Node ready for evaluation. This is called before the Taskmaster decides if the Node is up-to-date or not. Overriding this method allows for a Node subclass to be disambiguated if necessary, or for an implicit source builder to be attached. """ pass def prepare(self): """Prepare for this Node to be built. This is called after the Taskmaster has decided that the Node is out-of-date and must be rebuilt, but before actually calling the method to build the Node. This default implementation checks that explicit or implicit dependencies either exist or are derived, and initializes the BuildInfo structure that will hold the information about how this node is, uh, built. (The existence of source files is checked separately by the Executor, which aggregates checks for all of the targets built by a specific action.) Overriding this method allows for for a Node subclass to remove the underlying file from the file system. Note that subclass methods should call this base class method to get the child check and the BuildInfo structure. """ for d in self.depends: if d.missing(): msg = "Explicit dependency `%s' not found, needed by target `%s'." raise SCons.Errors.StopError(msg % (d, self)) if self.implicit is not None: for i in self.implicit: if i.missing(): msg = "Implicit dependency `%s' not found, needed by target `%s'." raise SCons.Errors.StopError(msg % (i, self)) self.binfo = self.get_binfo() def build(self, **kw): """Actually build the node. This is called by the Taskmaster after it's decided that the Node is out-of-date and must be rebuilt, and after the prepare() method has gotten everything, uh, prepared. This method is called from multiple threads in a parallel build, so only do thread safe stuff here. Do thread unsafe stuff in built(). """ try: self.get_executor()(self, **kw) except SCons.Errors.BuildError, e: e.node = self raise def built(self): """Called just after this node is successfully built.""" # Clear the implicit dependency caches of any Nodes # waiting for this Node to be built. for parent in self.waiting_parents: parent.implicit = None self.clear() self.ninfo.update(self) def visited(self): """Called just after this node has been visited (with or without a build).""" try: binfo = self.binfo except AttributeError: # Apparently this node doesn't need build info, so # don't bother calculating or storing it. pass else: self.ninfo.update(self) self.store_info() # # # def add_to_waiting_s_e(self, node): self.waiting_s_e.add(node) def add_to_waiting_parents(self, node): """ Returns the number of nodes added to our waiting parents list: 1 if we add a unique waiting parent, 0 if not. (Note that the returned values are intended to be used to increment a reference count, so don't think you can "clean up" this function by using True and False instead...) """ wp = self.waiting_parents if node in wp: return 0 wp.add(node) return 1 def postprocess(self): """Clean up anything we don't need to hang onto after we've been built.""" self.executor_cleanup() self.waiting_parents = set() def clear(self): """Completely clear a Node of all its cached state (so that it can be re-evaluated by interfaces that do continuous integration builds). """ # The del_binfo() call here isn't necessary for normal execution, # but is for interactive mode, where we might rebuild the same # target and need to start from scratch. self.del_binfo() self.clear_memoized_values() self.ninfo = self.new_ninfo() self.executor_cleanup() try: delattr(self, '_calculated_sig') except AttributeError: pass self.includes = None def clear_memoized_values(self): self._memo = {} def builder_set(self, builder): self.builder = builder try: del self.executor except AttributeError: pass def has_builder(self): """Return whether this Node has a builder or not. In Boolean tests, this turns out to be a *lot* more efficient than simply examining the builder attribute directly ("if node.builder: ..."). When the builder attribute is examined directly, it ends up calling __getattr__ for both the __len__ and __nonzero__ attributes on instances of our Builder Proxy class(es), generating a bazillion extra calls and slowing things down immensely. """ try: b = self.builder except AttributeError: # There was no explicit builder for this Node, so initialize # the self.builder attribute to None now. b = self.builder = None return b is not None def set_explicit(self, is_explicit): self.is_explicit = is_explicit def has_explicit_builder(self): """Return whether this Node has an explicit builder This allows an internal Builder created by SCons to be marked non-explicit, so that it can be overridden by an explicit builder that the user supplies (the canonical example being directories).""" try: return self.is_explicit except AttributeError: self.is_explicit = None return self.is_explicit def get_builder(self, default_builder=None): """Return the set builder, or a specified default value""" try: return self.builder except AttributeError: return default_builder multiple_side_effect_has_builder = has_builder def is_derived(self): """ Returns true iff this node is derived (i.e. built). This should return true only for nodes whose path should be in the variant directory when duplicate=0 and should contribute their build signatures when they are used as source files to other derived files. For example: source with source builders are not derived in this sense, and hence should not return true. """ return self.has_builder() or self.side_effect def alter_targets(self): """Return a list of alternate targets for this Node. """ return [], None def get_found_includes(self, env, scanner, path): """Return the scanned include lines (implicit dependencies) found in this node. The default is no implicit dependencies. We expect this method to be overridden by any subclass that can be scanned for implicit dependencies. """ return [] def get_implicit_deps(self, env, scanner, path): """Return a list of implicit dependencies for this node. This method exists to handle recursive invocation of the scanner on the implicit dependencies returned by the scanner, if the scanner's recursive flag says that we should. """ if not scanner: return [] # Give the scanner a chance to select a more specific scanner # for this Node. #scanner = scanner.select(self) nodes = [self] seen = {} seen[self] = 1 deps = [] while nodes: n = nodes.pop(0) d = [x for x in n.get_found_includes(env, scanner, path) if x not in seen] if d: deps.extend(d) for n in d: seen[n] = 1 nodes.extend(scanner.recurse_nodes(d)) return deps def get_env_scanner(self, env, kw={}): return env.get_scanner(self.scanner_key()) def get_target_scanner(self): return self.builder.target_scanner def get_source_scanner(self, node): """Fetch the source scanner for the specified node NOTE: "self" is the target being built, "node" is the source file for which we want to fetch the scanner. Implies self.has_builder() is true; again, expect to only be called from locations where this is already verified. This function may be called very often; it attempts to cache the scanner found to improve performance. """ scanner = None try: scanner = self.builder.source_scanner except AttributeError: pass if not scanner: # The builder didn't have an explicit scanner, so go look up # a scanner from env['SCANNERS'] based on the node's scanner # key (usually the file extension). scanner = self.get_env_scanner(self.get_build_env()) if scanner: scanner = scanner.select(node) return scanner def add_to_implicit(self, deps): if not hasattr(self, 'implicit') or self.implicit is None: self.implicit = [] self.implicit_set = set() self._children_reset() self._add_child(self.implicit, self.implicit_set, deps) def scan(self): """Scan this node's dependents for implicit dependencies.""" # Don't bother scanning non-derived files, because we don't # care what their dependencies are. # Don't scan again, if we already have scanned. if self.implicit is not None: return self.implicit = [] self.implicit_set = set() self._children_reset() if not self.has_builder(): return build_env = self.get_build_env() executor = self.get_executor() # Here's where we implement --implicit-cache. if implicit_cache and not implicit_deps_changed: implicit = self.get_stored_implicit() if implicit is not None: # We now add the implicit dependencies returned from the # stored .sconsign entry to have already been converted # to Nodes for us. (We used to run them through a # source_factory function here.) # Update all of the targets with them. This # essentially short-circuits an N*M scan of the # sources for each individual target, which is a hell # of a lot more efficient. for tgt in executor.get_all_targets(): tgt.add_to_implicit(implicit) if implicit_deps_unchanged or self.is_up_to_date(): return # one of this node's sources has changed, # so we must recalculate the implicit deps for all targets for tgt in executor.get_all_targets(): tgt.implicit = [] tgt.implicit_set = set() # Have the executor scan the sources. executor.scan_sources(self.builder.source_scanner) # If there's a target scanner, have the executor scan the target # node itself and associated targets that might be built. scanner = self.get_target_scanner() if scanner: executor.scan_targets(scanner) def scanner_key(self): return None def select_scanner(self, scanner): """Selects a scanner for this Node. This is a separate method so it can be overridden by Node subclasses (specifically, Node.FS.Dir) that *must* use their own Scanner and don't select one the Scanner.Selector that's configured for the target. """ return scanner.select(self) def env_set(self, env, safe=0): if safe and self.env: return self.env = env # # SIGNATURE SUBSYSTEM # NodeInfo = NodeInfoBase BuildInfo = BuildInfoBase def new_ninfo(self): ninfo = self.NodeInfo(self) return ninfo def get_ninfo(self): try: return self.ninfo except AttributeError: self.ninfo = self.new_ninfo() return self.ninfo def new_binfo(self): binfo = self.BuildInfo(self) return binfo def get_binfo(self): """ Fetch a node's build information. node - the node whose sources will be collected cache - alternate node to use for the signature cache returns - the build signature This no longer handles the recursive descent of the node's children's signatures. We expect that they're already built and updated by someone else, if that's what's wanted. """ try: return self.binfo except AttributeError: pass binfo = self.new_binfo() self.binfo = binfo executor = self.get_executor() ignore_set = self.ignore_set if self.has_builder(): binfo.bact = str(executor) binfo.bactsig = SCons.Util.MD5signature(executor.get_contents()) if self._specific_sources: sources = [] for s in self.sources: if s not in ignore_set: sources.append(s) else: sources = executor.get_unignored_sources(self, self.ignore) seen = set() bsources = [] bsourcesigs = [] for s in sources: if not s in seen: seen.add(s) bsources.append(s) bsourcesigs.append(s.get_ninfo()) binfo.bsources = bsources binfo.bsourcesigs = bsourcesigs depends = self.depends dependsigs = [] for d in depends: if d not in ignore_set: dependsigs.append(d.get_ninfo()) binfo.bdepends = depends binfo.bdependsigs = dependsigs implicit = self.implicit or [] implicitsigs = [] for i in implicit: if i not in ignore_set: implicitsigs.append(i.get_ninfo()) binfo.bimplicit = implicit binfo.bimplicitsigs = implicitsigs return binfo def del_binfo(self): """Delete the build info from this node.""" try: delattr(self, 'binfo') except AttributeError: pass def get_csig(self): try: return self.ninfo.csig except AttributeError: ninfo = self.get_ninfo() ninfo.csig = SCons.Util.MD5signature(self.get_contents()) return self.ninfo.csig def get_cachedir_csig(self): return self.get_csig() def store_info(self): """Make the build signature permanent (that is, store it in the .sconsign file or equivalent).""" pass def do_not_store_info(self): pass def get_stored_info(self): return None def get_stored_implicit(self): """Fetch the stored implicit dependencies""" return None # # # def set_precious(self, precious = 1): """Set the Node's precious value.""" self.precious = precious def set_noclean(self, noclean = 1): """Set the Node's noclean value.""" # Make sure noclean is an integer so the --debug=stree # output in Util.py can use it as an index. self.noclean = noclean and 1 or 0 def set_nocache(self, nocache = 1): """Set the Node's nocache value.""" # Make sure nocache is an integer so the --debug=stree # output in Util.py can use it as an index. self.nocache = nocache and 1 or 0 def set_always_build(self, always_build = 1): """Set the Node's always_build value.""" self.always_build = always_build def exists(self): """Does this node exists?""" # All node exist by default: return 1 def rexists(self): """Does this node exist locally or in a repositiory?""" # There are no repositories by default: return self.exists() def missing(self): return not self.is_derived() and \ not self.linked and \ not self.rexists() def remove(self): """Remove this Node: no-op by default.""" return None def add_dependency(self, depend): """Adds dependencies.""" try: self._add_child(self.depends, self.depends_set, depend) except TypeError, e: e = e.args[0] if SCons.Util.is_List(e): s = list(map(str, e)) else: s = str(e) raise SCons.Errors.UserError("attempted to add a non-Node dependency to %s:\n\t%s is a %s, not a Node" % (str(self), s, type(e))) def add_prerequisite(self, prerequisite): """Adds prerequisites""" self.prerequisites.extend(prerequisite) self._children_reset() def add_ignore(self, depend): """Adds dependencies to ignore.""" try: self._add_child(self.ignore, self.ignore_set, depend) except TypeError, e: e = e.args[0] if SCons.Util.is_List(e): s = list(map(str, e)) else: s = str(e) raise SCons.Errors.UserError("attempted to ignore a non-Node dependency of %s:\n\t%s is a %s, not a Node" % (str(self), s, type(e))) def add_source(self, source): """Adds sources.""" if self._specific_sources: return try: self._add_child(self.sources, self.sources_set, source) except TypeError, e: e = e.args[0] if SCons.Util.is_List(e): s = list(map(str, e)) else: s = str(e) raise SCons.Errors.UserError("attempted to add a non-Node as source of %s:\n\t%s is a %s, not a Node" % (str(self), s, type(e))) def _add_child(self, collection, set, child): """Adds 'child' to 'collection', first checking 'set' to see if it's already present.""" #if type(child) is not type([]): # child = [child] #for c in child: # if not isinstance(c, Node): # raise TypeError, c added = None for c in child: if c not in set: set.add(c) collection.append(c) added = 1 if added: self._children_reset() def set_specific_source(self, source): self.add_source(source) self._specific_sources = True def add_wkid(self, wkid): """Add a node to the list of kids waiting to be evaluated""" if self.wkids is not None: self.wkids.append(wkid) def _children_reset(self): self.clear_memoized_values() # We need to let the Executor clear out any calculated # build info that it's cached so we can re-calculate it. self.executor_cleanup() memoizer_counters.append(SCons.Memoize.CountValue('_children_get')) def _children_get(self): try: return self._memo['children_get'] except KeyError: pass # The return list may contain duplicate Nodes, especially in # source trees where there are a lot of repeated #includes # of a tangle of .h files. Profiling shows, however, that # eliminating the duplicates with a brute-force approach that # preserves the order (that is, something like: # # u = [] # for n in list: # if n not in u: # u.append(n)" # # takes more cycles than just letting the underlying methods # hand back cached values if a Node's information is requested # multiple times. (Other methods of removing duplicates, like # using dictionary keys, lose the order, and the only ordered # dictionary patterns I found all ended up using "not in" # internally anyway...) if self.ignore_set: if self.implicit is None: iter = chain(self.sources,self.depends) else: iter = chain(self.sources, self.depends, self.implicit) children = [] for i in iter: if i not in self.ignore_set: children.append(i) else: if self.implicit is None: children = self.sources + self.depends else: children = self.sources + self.depends + self.implicit self._memo['children_get'] = children return children def all_children(self, scan=1): """Return a list of all the node's direct children.""" if scan: self.scan() # The return list may contain duplicate Nodes, especially in # source trees where there are a lot of repeated #includes # of a tangle of .h files. Profiling shows, however, that # eliminating the duplicates with a brute-force approach that # preserves the order (that is, something like: # # u = [] # for n in list: # if n not in u: # u.append(n)" # # takes more cycles than just letting the underlying methods # hand back cached values if a Node's information is requested # multiple times. (Other methods of removing duplicates, like # using dictionary keys, lose the order, and the only ordered # dictionary patterns I found all ended up using "not in" # internally anyway...) if self.implicit is None: return self.sources + self.depends else: return self.sources + self.depends + self.implicit def children(self, scan=1): """Return a list of the node's direct children, minus those that are ignored by this node.""" if scan: self.scan() return self._children_get() def set_state(self, state): self.state = state def get_state(self): return self.state def state_has_changed(self, target, prev_ni): return (self.state != SCons.Node.up_to_date) def get_env(self): env = self.env if not env: import SCons.Defaults env = SCons.Defaults.DefaultEnvironment() return env def changed_since_last_build(self, target, prev_ni): """ Must be overridden in a specific subclass to return True if this Node (a dependency) has changed since the last time it was used to build the specified target. prev_ni is this Node's state (for example, its file timestamp, length, maybe content signature) as of the last time the target was built. Note that this method is called through the dependency, not the target, because a dependency Node must be able to use its own logic to decide if it changed. For example, File Nodes need to obey if we're configured to use timestamps, but Python Value Nodes never use timestamps and always use the content. If this method were called through the target, then each Node's implementation of this method would have to have more complicated logic to handle all the different Node types on which it might depend. """ raise NotImplementedError def Decider(self, function): SCons.Util.AddMethod(self, function, 'changed_since_last_build') def changed(self, node=None): """ Returns if the node is up-to-date with respect to the BuildInfo stored last time it was built. The default behavior is to compare it against our own previously stored BuildInfo, but the stored BuildInfo from another Node (typically one in a Repository) can be used instead. Note that we now *always* check every dependency. We used to short-circuit the check by returning as soon as we detected any difference, but we now rely on checking every dependency to make sure that any necessary Node information (for example, the content signature of an #included .h file) is updated. """ t = 0 if t: Trace('changed(%s [%s], %s)' % (self, classname(self), node)) if node is None: node = self result = False bi = node.get_stored_info().binfo then = bi.bsourcesigs + bi.bdependsigs + bi.bimplicitsigs children = self.children() diff = len(children) - len(then) if diff: # The old and new dependency lists are different lengths. # This always indicates that the Node must be rebuilt. # We also extend the old dependency list with enough None # entries to equal the new dependency list, for the benefit # of the loop below that updates node information. then.extend([None] * diff) if t: Trace(': old %s new %s' % (len(then), len(children))) result = True for child, prev_ni in zip(children, then): if child.changed_since_last_build(self, prev_ni): if t: Trace(': %s changed' % child) result = True contents = self.get_executor().get_contents() if self.has_builder(): import SCons.Util newsig = SCons.Util.MD5signature(contents) if bi.bactsig != newsig: if t: Trace(': bactsig %s != newsig %s' % (bi.bactsig, newsig)) result = True if not result: if t: Trace(': up to date') if t: Trace('\n') return result def is_up_to_date(self): """Default check for whether the Node is current: unknown Node subtypes are always out of date, so they will always get built.""" return None def children_are_up_to_date(self): """Alternate check for whether the Node is current: If all of our children were up-to-date, then this Node was up-to-date, too. The SCons.Node.Alias and SCons.Node.Python.Value subclasses rebind their current() method to this method.""" # Allow the children to calculate their signatures. self.binfo = self.get_binfo() if self.always_build: return None state = 0 for kid in self.children(None): s = kid.get_state() if s and (not state or s > state): state = s return (state == 0 or state == SCons.Node.up_to_date) def is_literal(self): """Always pass the string representation of a Node to the command interpreter literally.""" return 1 def render_include_tree(self): """ Return a text representation, suitable for displaying to the user, of the include tree for the sources of this node. """ if self.is_derived() and self.env: env = self.get_build_env() for s in self.sources: scanner = self.get_source_scanner(s) if scanner: path = self.get_build_scanner_path(scanner) else: path = None def f(node, env=env, scanner=scanner, path=path): return node.get_found_includes(env, scanner, path) return SCons.Util.render_tree(s, f, 1) else: return None def get_abspath(self): """ Return an absolute path to the Node. This will return simply str(Node) by default, but for Node types that have a concept of relative path, this might return something different. """ return str(self) def for_signature(self): """ Return a string representation of the Node that will always be the same for this particular Node, no matter what. This is by contrast to the __str__() method, which might, for instance, return a relative path for a file Node. The purpose of this method is to generate a value to be used in signature calculation for the command line used to build a target, and we use this method instead of str() to avoid unnecessary rebuilds. This method does not need to return something that would actually work in a command line; it can return any kind of nonsense, so long as it does not change. """ return str(self) def get_string(self, for_signature): """This is a convenience function designed primarily to be used in command generators (i.e., CommandGeneratorActions or Environment variables that are callable), which are called with a for_signature argument that is nonzero if the command generator is being called to generate a signature for the command line, which determines if we should rebuild or not. Such command generators should use this method in preference to str(Node) when converting a Node to a string, passing in the for_signature parameter, such that we will call Node.for_signature() or str(Node) properly, depending on whether we are calculating a signature or actually constructing a command line.""" if for_signature: return self.for_signature() return str(self) def get_subst_proxy(self): """ This method is expected to return an object that will function exactly like this Node, except that it implements any additional special features that we would like to be in effect for Environment variable substitution. The principle use is that some Nodes would like to implement a __getattr__() method, but putting that in the Node type itself has a tendency to kill performance. We instead put it in a proxy and return it from this method. It is legal for this method to return self if no new functionality is needed for Environment substitution. """ return self def explain(self): if not self.exists(): return "building `%s' because it doesn't exist\n" % self if self.always_build: return "rebuilding `%s' because AlwaysBuild() is specified\n" % self old = self.get_stored_info() if old is None: return None old = old.binfo old.prepare_dependencies() try: old_bkids = old.bsources + old.bdepends + old.bimplicit old_bkidsigs = old.bsourcesigs + old.bdependsigs + old.bimplicitsigs except AttributeError: return "Cannot explain why `%s' is being rebuilt: No previous build information found\n" % self new = self.get_binfo() new_bkids = new.bsources + new.bdepends + new.bimplicit new_bkidsigs = new.bsourcesigs + new.bdependsigs + new.bimplicitsigs osig = dict(zip(old_bkids, old_bkidsigs)) nsig = dict(zip(new_bkids, new_bkidsigs)) # The sources and dependencies we'll want to report are all stored # as relative paths to this target's directory, but we want to # report them relative to the top-level SConstruct directory, # so we only print them after running them through this lambda # to turn them into the right relative Node and then return # its string. def stringify( s, E=self.dir.Entry ) : if hasattr( s, 'dir' ) : return str(E(s)) return str(s) lines = [] removed = [x for x in old_bkids if not x in new_bkids] if removed: removed = list(map(stringify, removed)) fmt = "`%s' is no longer a dependency\n" lines.extend([fmt % s for s in removed]) for k in new_bkids: if not k in old_bkids: lines.append("`%s' is a new dependency\n" % stringify(k)) elif k.changed_since_last_build(self, osig[k]): lines.append("`%s' changed\n" % stringify(k)) if len(lines) == 0 and old_bkids != new_bkids: lines.append("the dependency order changed:\n" + "%sold: %s\n" % (' '*15, list(map(stringify, old_bkids))) + "%snew: %s\n" % (' '*15, list(map(stringify, new_bkids)))) if len(lines) == 0: def fmt_with_title(title, strlines): lines = strlines.split('\n') sep = '\n' + ' '*(15 + len(title)) return ' '*15 + title + sep.join(lines) + '\n' if old.bactsig != new.bactsig: if old.bact == new.bact: lines.append("the contents of the build action changed\n" + fmt_with_title('action: ', new.bact)) else: lines.append("the build action changed:\n" + fmt_with_title('old: ', old.bact) + fmt_with_title('new: ', new.bact)) if len(lines) == 0: return "rebuilding `%s' for unknown reasons\n" % self preamble = "rebuilding `%s' because" % self if len(lines) == 1: return "%s %s" % (preamble, lines[0]) else: lines = ["%s:\n" % preamble] + lines return ( ' '*11).join(lines) class NodeList(collections.UserList): def __str__(self): return str(list(map(str, self.data))) def get_children(node, parent): return node.children() def ignore_cycle(node, stack): pass def do_nothing(node, parent): pass class Walker(object): """An iterator for walking a Node tree. This is depth-first, children are visited before the parent. The Walker object can be initialized with any node, and returns the next node on the descent with each get_next() call. 'kids_func' is an optional function that will be called to get the children of a node instead of calling 'children'. 'cycle_func' is an optional function that will be called when a cycle is detected. This class does not get caught in node cycles caused, for example, by C header file include loops. """ def __init__(self, node, kids_func=get_children, cycle_func=ignore_cycle, eval_func=do_nothing): self.kids_func = kids_func self.cycle_func = cycle_func self.eval_func = eval_func node.wkids = copy.copy(kids_func(node, None)) self.stack = [node] self.history = {} # used to efficiently detect and avoid cycles self.history[node] = None def get_next(self): """Return the next node for this walk of the tree. This function is intentionally iterative, not recursive, to sidestep any issues of stack size limitations. """ while self.stack: if self.stack[-1].wkids: node = self.stack[-1].wkids.pop(0) if not self.stack[-1].wkids: self.stack[-1].wkids = None if node in self.history: self.cycle_func(node, self.stack) else: node.wkids = copy.copy(self.kids_func(node, self.stack[-1])) self.stack.append(node) self.history[node] = None else: node = self.stack.pop() del self.history[node] if node: if self.stack: parent = self.stack[-1] else: parent = None self.eval_func(node, parent) return node return None def is_done(self): return not self.stack arg2nodes_lookups = [] # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""scons.Node.Alias Alias nodes. This creates a hash of global Aliases (dummy targets). """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Node/Alias.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import collections import SCons.Errors import SCons.Node import SCons.Util class AliasNameSpace(collections.UserDict): def Alias(self, name, **kw): if isinstance(name, SCons.Node.Alias.Alias): return name try: a = self[name] except KeyError: a = SCons.Node.Alias.Alias(name, **kw) self[name] = a return a def lookup(self, name, **kw): try: return self[name] except KeyError: return None class AliasNodeInfo(SCons.Node.NodeInfoBase): current_version_id = 1 field_list = ['csig'] def str_to_node(self, s): return default_ans.Alias(s) class AliasBuildInfo(SCons.Node.BuildInfoBase): current_version_id = 1 class Alias(SCons.Node.Node): NodeInfo = AliasNodeInfo BuildInfo = AliasBuildInfo def __init__(self, name): SCons.Node.Node.__init__(self) self.name = name def str_for_display(self): return '"' + self.__str__() + '"' def __str__(self): return self.name def make_ready(self): self.get_csig() really_build = SCons.Node.Node.build is_up_to_date = SCons.Node.Node.children_are_up_to_date def is_under(self, dir): # Make Alias nodes get built regardless of # what directory scons was run from. Alias nodes # are outside the filesystem: return 1 def get_contents(self): """The contents of an alias is the concatenation of the content signatures of all its sources.""" childsigs = [n.get_csig() for n in self.children()] return ''.join(childsigs) def sconsign(self): """An Alias is not recorded in .sconsign files""" pass # # # def changed_since_last_build(self, target, prev_ni): cur_csig = self.get_csig() try: return cur_csig != prev_ni.csig except AttributeError: return 1 def build(self): """A "builder" for aliases.""" pass def convert(self): try: del self.builder except AttributeError: pass self.reset_executor() self.build = self.really_build def get_csig(self): """ Generate a node's content signature, the digested signature of its content. node - the node cache - alternate node to use for the signature cache returns - the content signature """ try: return self.ninfo.csig except AttributeError: pass contents = self.get_contents() csig = SCons.Util.MD5signature(contents) self.get_ninfo().csig = csig return csig default_ans = AliasNameSpace() SCons.Node.arg2nodes_lookups.append(default_ans.lookup) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/cpp.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" __doc__ = """ SCons C Pre-Processor module """ #TODO 2.3 and before has no sorted() import SCons.compat import os import re # # First "subsystem" of regular expressions that we set up: # # Stuff to turn the C preprocessor directives in a file's contents into # a list of tuples that we can process easily. # # A table of regular expressions that fetch the arguments from the rest of # a C preprocessor line. Different directives have different arguments # that we want to fetch, using the regular expressions to which the lists # of preprocessor directives map. cpp_lines_dict = { # Fetch the rest of a #if/#elif/#ifdef/#ifndef as one argument, # separated from the keyword by white space. ('if', 'elif', 'ifdef', 'ifndef',) : '\s+(.+)', # Fetch the rest of a #import/#include/#include_next line as one # argument, with white space optional. ('import', 'include', 'include_next',) : '\s*(.+)', # We don't care what comes after a #else or #endif line. ('else', 'endif',) : '', # Fetch three arguments from a #define line: # 1) The #defined keyword. # 2) The optional parentheses and arguments (if it's a function-like # macro, '' if it's not). # 3) The expansion value. ('define',) : '\s+([_A-Za-z][_A-Za-z0-9_]*)(\([^)]*\))?\s*(.*)', # Fetch the #undefed keyword from a #undef line. ('undef',) : '\s+([_A-Za-z][A-Za-z0-9_]*)', } # Create a table that maps each individual C preprocessor directive to # the corresponding compiled regular expression that fetches the arguments # we care about. Table = {} for op_list, expr in cpp_lines_dict.items(): e = re.compile(expr) for op in op_list: Table[op] = e del e del op del op_list # Create a list of the expressions we'll use to match all of the # preprocessor directives. These are the same as the directives # themselves *except* that we must use a negative lookahead assertion # when matching "if" so it doesn't match the "if" in "ifdef." override = { 'if' : 'if(?!def)', } l = [override.get(x, x) for x in Table.keys()] # Turn the list of expressions into one big honkin' regular expression # that will match all the preprocessor lines at once. This will return # a list of tuples, one for each preprocessor line. The preprocessor # directive will be the first element in each tuple, and the rest of # the line will be the second element. e = '^\s*#\s*(' + '|'.join(l) + ')(.*)$' # And last but not least, compile the expression. CPP_Expression = re.compile(e, re.M) # # Second "subsystem" of regular expressions that we set up: # # Stuff to translate a C preprocessor expression (as found on a #if or # #elif line) into an equivalent Python expression that we can eval(). # # A dictionary that maps the C representation of Boolean operators # to their Python equivalents. CPP_to_Python_Ops_Dict = { '!' : ' not ', '!=' : ' != ', '&&' : ' and ', '||' : ' or ', '?' : ' and ', ':' : ' or ', '\r' : '', } CPP_to_Python_Ops_Sub = lambda m: CPP_to_Python_Ops_Dict[m.group(0)] # We have to sort the keys by length so that longer expressions # come *before* shorter expressions--in particular, "!=" must # come before "!" in the alternation. Without this, the Python # re module, as late as version 2.2.2, empirically matches the # "!" in "!=" first, instead of finding the longest match. # What's up with that? l = sorted(CPP_to_Python_Ops_Dict.keys(), key=lambda a: len(a), reverse=True) # Turn the list of keys into one regular expression that will allow us # to substitute all of the operators at once. expr = '|'.join(map(re.escape, l)) # ...and compile the expression. CPP_to_Python_Ops_Expression = re.compile(expr) # A separate list of expressions to be evaluated and substituted # sequentially, not all at once. CPP_to_Python_Eval_List = [ ['defined\s+(\w+)', '"\\1" in __dict__'], ['defined\s*\((\w+)\)', '"\\1" in __dict__'], ['/\*.*\*/', ''], ['/\*.*', ''], ['//.*', ''], ['(0x[0-9A-Fa-f]*)[UL]+', '\\1'], ] # Replace the string representations of the regular expressions in the # list with compiled versions. for l in CPP_to_Python_Eval_List: l[0] = re.compile(l[0]) # Wrap up all of the above into a handy function. def CPP_to_Python(s): """ Converts a C pre-processor expression into an equivalent Python expression that can be evaluated. """ s = CPP_to_Python_Ops_Expression.sub(CPP_to_Python_Ops_Sub, s) for expr, repl in CPP_to_Python_Eval_List: s = expr.sub(repl, s) return s del expr del l del override class FunctionEvaluator(object): """ Handles delayed evaluation of a #define function call. """ def __init__(self, name, args, expansion): """ Squirrels away the arguments and expansion value of a #define macro function for later evaluation when we must actually expand a value that uses it. """ self.name = name self.args = function_arg_separator.split(args) try: expansion = expansion.split('##') except AttributeError: pass self.expansion = expansion def __call__(self, *values): """ Evaluates the expansion of a #define macro function called with the specified values. """ if len(self.args) != len(values): raise ValueError("Incorrect number of arguments to `%s'" % self.name) # Create a dictionary that maps the macro arguments to the # corresponding values in this "call." We'll use this when we # eval() the expansion so that arguments will get expanded to # the right values. locals = {} for k, v in zip(self.args, values): locals[k] = v parts = [] for s in self.expansion: if not s in self.args: s = repr(s) parts.append(s) statement = ' + '.join(parts) return eval(statement, globals(), locals) # Find line continuations. line_continuations = re.compile('\\\\\r?\n') # Search for a "function call" macro on an expansion. Returns the # two-tuple of the "function" name itself, and a string containing the # arguments within the call parentheses. function_name = re.compile('(\S+)\(([^)]*)\)') # Split a string containing comma-separated function call arguments into # the separate arguments. function_arg_separator = re.compile(',\s*') class PreProcessor(object): """ The main workhorse class for handling C pre-processing. """ def __init__(self, current=os.curdir, cpppath=(), dict={}, all=0): global Table cpppath = tuple(cpppath) self.searchpath = { '"' : (current,) + cpppath, '<' : cpppath + (current,), } # Initialize our C preprocessor namespace for tracking the # values of #defined keywords. We use this namespace to look # for keywords on #ifdef/#ifndef lines, and to eval() the # expressions on #if/#elif lines (after massaging them from C to # Python). self.cpp_namespace = dict.copy() self.cpp_namespace['__dict__'] = self.cpp_namespace if all: self.do_include = self.all_include # For efficiency, a dispatch table maps each C preprocessor # directive (#if, #define, etc.) to the method that should be # called when we see it. We accomodate state changes (#if, # #ifdef, #ifndef) by pushing the current dispatch table on a # stack and changing what method gets called for each relevant # directive we might see next at this level (#else, #elif). # #endif will simply pop the stack. d = { 'scons_current_file' : self.scons_current_file } for op in Table.keys(): d[op] = getattr(self, 'do_' + op) self.default_table = d # Controlling methods. def tupleize(self, contents): """ Turns the contents of a file into a list of easily-processed tuples describing the CPP lines in the file. The first element of each tuple is the line's preprocessor directive (#if, #include, #define, etc., minus the initial '#'). The remaining elements are specific to the type of directive, as pulled apart by the regular expression. """ global CPP_Expression, Table contents = line_continuations.sub('', contents) cpp_tuples = CPP_Expression.findall(contents) return [(m[0],) + Table[m[0]].match(m[1]).groups() for m in cpp_tuples] def __call__(self, file): """ Pre-processes a file. This is the main public entry point. """ self.current_file = file return self.process_contents(self.read_file(file), file) def process_contents(self, contents, fname=None): """ Pre-processes a file contents. This is the main internal entry point. """ self.stack = [] self.dispatch_table = self.default_table.copy() self.current_file = fname self.tuples = self.tupleize(contents) self.initialize_result(fname) while self.tuples: t = self.tuples.pop(0) # Uncomment to see the list of tuples being processed (e.g., # to validate the CPP lines are being translated correctly). #print t self.dispatch_table[t[0]](t) return self.finalize_result(fname) # Dispatch table stack manipulation methods. def save(self): """ Pushes the current dispatch table on the stack and re-initializes the current dispatch table to the default. """ self.stack.append(self.dispatch_table) self.dispatch_table = self.default_table.copy() def restore(self): """ Pops the previous dispatch table off the stack and makes it the current one. """ try: self.dispatch_table = self.stack.pop() except IndexError: pass # Utility methods. def do_nothing(self, t): """ Null method for when we explicitly want the action for a specific preprocessor directive to do nothing. """ pass def scons_current_file(self, t): self.current_file = t[1] def eval_expression(self, t): """ Evaluates a C preprocessor expression. This is done by converting it to a Python equivalent and eval()ing it in the C preprocessor namespace we use to track #define values. """ t = CPP_to_Python(' '.join(t[1:])) try: return eval(t, self.cpp_namespace) except (NameError, TypeError): return 0 def initialize_result(self, fname): self.result = [fname] def finalize_result(self, fname): return self.result[1:] def find_include_file(self, t): """ Finds the #include file for a given preprocessor tuple. """ fname = t[2] for d in self.searchpath[t[1]]: if d == os.curdir: f = fname else: f = os.path.join(d, fname) if os.path.isfile(f): return f return None def read_file(self, file): return open(file).read() # Start and stop processing include lines. def start_handling_includes(self, t=None): """ Causes the PreProcessor object to start processing #import, #include and #include_next lines. This method will be called when a #if, #ifdef, #ifndef or #elif evaluates True, or when we reach the #else in a #if, #ifdef, #ifndef or #elif block where a condition already evaluated False. """ d = self.dispatch_table d['import'] = self.do_import d['include'] = self.do_include d['include_next'] = self.do_include def stop_handling_includes(self, t=None): """ Causes the PreProcessor object to stop processing #import, #include and #include_next lines. This method will be called when a #if, #ifdef, #ifndef or #elif evaluates False, or when we reach the #else in a #if, #ifdef, #ifndef or #elif block where a condition already evaluated True. """ d = self.dispatch_table d['import'] = self.do_nothing d['include'] = self.do_nothing d['include_next'] = self.do_nothing # Default methods for handling all of the preprocessor directives. # (Note that what actually gets called for a given directive at any # point in time is really controlled by the dispatch_table.) def _do_if_else_condition(self, condition): """ Common logic for evaluating the conditions on #if, #ifdef and #ifndef lines. """ self.save() d = self.dispatch_table if condition: self.start_handling_includes() d['elif'] = self.stop_handling_includes d['else'] = self.stop_handling_includes else: self.stop_handling_includes() d['elif'] = self.do_elif d['else'] = self.start_handling_includes def do_ifdef(self, t): """ Default handling of a #ifdef line. """ self._do_if_else_condition(t[1] in self.cpp_namespace) def do_ifndef(self, t): """ Default handling of a #ifndef line. """ self._do_if_else_condition(t[1] not in self.cpp_namespace) def do_if(self, t): """ Default handling of a #if line. """ self._do_if_else_condition(self.eval_expression(t)) def do_elif(self, t): """ Default handling of a #elif line. """ d = self.dispatch_table if self.eval_expression(t): self.start_handling_includes() d['elif'] = self.stop_handling_includes d['else'] = self.stop_handling_includes def do_else(self, t): """ Default handling of a #else line. """ pass def do_endif(self, t): """ Default handling of a #endif line. """ self.restore() def do_define(self, t): """ Default handling of a #define line. """ _, name, args, expansion = t try: expansion = int(expansion) except (TypeError, ValueError): pass if args: evaluator = FunctionEvaluator(name, args[1:-1], expansion) self.cpp_namespace[name] = evaluator else: self.cpp_namespace[name] = expansion def do_undef(self, t): """ Default handling of a #undef line. """ try: del self.cpp_namespace[t[1]] except KeyError: pass def do_import(self, t): """ Default handling of a #import line. """ # XXX finish this -- maybe borrow/share logic from do_include()...? pass def do_include(self, t): """ Default handling of a #include line. """ t = self.resolve_include(t) include_file = self.find_include_file(t) if include_file: #print "include_file =", include_file self.result.append(include_file) contents = self.read_file(include_file) new_tuples = [('scons_current_file', include_file)] + \ self.tupleize(contents) + \ [('scons_current_file', self.current_file)] self.tuples[:] = new_tuples + self.tuples # Date: Tue, 22 Nov 2005 20:26:09 -0500 # From: Stefan Seefeld <seefeld@sympatico.ca> # # By the way, #include_next is not the same as #include. The difference # being that #include_next starts its search in the path following the # path that let to the including file. In other words, if your system # include paths are ['/foo', '/bar'], and you are looking at a header # '/foo/baz.h', it might issue an '#include_next <baz.h>' which would # correctly resolve to '/bar/baz.h' (if that exists), but *not* see # '/foo/baz.h' again. See http://www.delorie.com/gnu/docs/gcc/cpp_11.html # for more reasoning. # # I have no idea in what context 'import' might be used. # XXX is #include_next really the same as #include ? do_include_next = do_include # Utility methods for handling resolution of include files. def resolve_include(self, t): """Resolve a tuple-ized #include line. This handles recursive expansion of values without "" or <> surrounding the name until an initial " or < is found, to handle #include FILE where FILE is a #define somewhere else. """ s = t[1] while not s[0] in '<"': #print "s =", s try: s = self.cpp_namespace[s] except KeyError: m = function_name.search(s) s = self.cpp_namespace[m.group(1)] if callable(s): args = function_arg_separator.split(m.group(2)) s = s(*args) if not s: return None return (t[0], s[0], s[1:-1]) def all_include(self, t): """ """ self.result.append(self.resolve_include(t)) class DumbPreProcessor(PreProcessor): """A preprocessor that ignores all #if/#elif/#else/#endif directives and just reports back *all* of the #include files (like the classic SCons scanner did). This is functionally equivalent to using a regular expression to find all of the #include lines, only slower. It exists mainly as an example of how the main PreProcessor class can be sub-classed to tailor its behavior. """ def __init__(self, *args, **kw): PreProcessor.__init__(self, *args, **kw) d = self.default_table for func in ['if', 'elif', 'else', 'endif', 'ifdef', 'ifndef']: d[func] = d[func] = self.do_nothing del __revision__ # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Conftest Autoconf-like configuration support; low level implementation of tests. """ # # Copyright (c) 2003 Stichting NLnet Labs # Copyright (c) 2001, 2002, 2003 Steven Knight # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # # # The purpose of this module is to define how a check is to be performed. # Use one of the Check...() functions below. # # # A context class is used that defines functions for carrying out the tests, # logging and messages. The following methods and members must be present: # # context.Display(msg) Function called to print messages that are normally # displayed for the user. Newlines are explicitly used. # The text should also be written to the logfile! # # context.Log(msg) Function called to write to a log file. # # context.BuildProg(text, ext) # Function called to build a program, using "ext" for the # file extention. Must return an empty string for # success, an error message for failure. # For reliable test results building should be done just # like an actual program would be build, using the same # command and arguments (including configure results so # far). # # context.CompileProg(text, ext) # Function called to compile a program, using "ext" for # the file extention. Must return an empty string for # success, an error message for failure. # For reliable test results compiling should be done just # like an actual source file would be compiled, using the # same command and arguments (including configure results # so far). # # context.AppendLIBS(lib_name_list) # Append "lib_name_list" to the value of LIBS. # "lib_namelist" is a list of strings. # Return the value of LIBS before changing it (any type # can be used, it is passed to SetLIBS() later.) # # context.PrependLIBS(lib_name_list) # Prepend "lib_name_list" to the value of LIBS. # "lib_namelist" is a list of strings. # Return the value of LIBS before changing it (any type # can be used, it is passed to SetLIBS() later.) # # context.SetLIBS(value) # Set LIBS to "value". The type of "value" is what # AppendLIBS() returned. # Return the value of LIBS before changing it (any type # can be used, it is passed to SetLIBS() later.) # # context.headerfilename # Name of file to append configure results to, usually # "confdefs.h". # The file must not exist or be empty when starting. # Empty or None to skip this (some tests will not work!). # # context.config_h (may be missing). If present, must be a string, which # will be filled with the contents of a config_h file. # # context.vardict Dictionary holding variables used for the tests and # stores results from the tests, used for the build # commands. # Normally contains "CC", "LIBS", "CPPFLAGS", etc. # # context.havedict Dictionary holding results from the tests that are to # be used inside a program. # Names often start with "HAVE_". These are zero # (feature not present) or one (feature present). Other # variables may have any value, e.g., "PERLVERSION" can # be a number and "SYSTEMNAME" a string. # import re from types import IntType # # PUBLIC VARIABLES # LogInputFiles = 1 # Set that to log the input files in case of a failed test LogErrorMessages = 1 # Set that to log Conftest-generated error messages # # PUBLIC FUNCTIONS # # Generic remarks: # - When a language is specified which is not supported the test fails. The # message is a bit different, because not all the arguments for the normal # message are available yet (chicken-egg problem). def CheckBuilder(context, text = None, language = None): """ Configure check to see if the compiler works. Note that this uses the current value of compiler and linker flags, make sure $CFLAGS, $CPPFLAGS and $LIBS are set correctly. "language" should be "C" or "C++" and is used to select the compiler. Default is "C". "text" may be used to specify the code to be build. Returns an empty string for success, an error message for failure. """ lang, suffix, msg = _lang2suffix(language) if msg: context.Display("%s\n" % msg) return msg if not text: text = """ int main() { return 0; } """ context.Display("Checking if building a %s file works... " % lang) ret = context.BuildProg(text, suffix) _YesNoResult(context, ret, None, text) return ret def CheckCC(context): """ Configure check for a working C compiler. This checks whether the C compiler, as defined in the $CC construction variable, can compile a C source file. It uses the current $CCCOM value too, so that it can test against non working flags. """ context.Display("Checking whether the C compiler works") text = """ int main() { return 0; } """ ret = _check_empty_program(context, 'CC', text, 'C') _YesNoResult(context, ret, None, text) return ret def CheckSHCC(context): """ Configure check for a working shared C compiler. This checks whether the C compiler, as defined in the $SHCC construction variable, can compile a C source file. It uses the current $SHCCCOM value too, so that it can test against non working flags. """ context.Display("Checking whether the (shared) C compiler works") text = """ int foo() { return 0; } """ ret = _check_empty_program(context, 'SHCC', text, 'C', use_shared = True) _YesNoResult(context, ret, None, text) return ret def CheckCXX(context): """ Configure check for a working CXX compiler. This checks whether the CXX compiler, as defined in the $CXX construction variable, can compile a CXX source file. It uses the current $CXXCOM value too, so that it can test against non working flags. """ context.Display("Checking whether the C++ compiler works") text = """ int main() { return 0; } """ ret = _check_empty_program(context, 'CXX', text, 'C++') _YesNoResult(context, ret, None, text) return ret def CheckSHCXX(context): """ Configure check for a working shared CXX compiler. This checks whether the CXX compiler, as defined in the $SHCXX construction variable, can compile a CXX source file. It uses the current $SHCXXCOM value too, so that it can test against non working flags. """ context.Display("Checking whether the (shared) C++ compiler works") text = """ int main() { return 0; } """ ret = _check_empty_program(context, 'SHCXX', text, 'C++', use_shared = True) _YesNoResult(context, ret, None, text) return ret def _check_empty_program(context, comp, text, language, use_shared = False): """Return 0 on success, 1 otherwise.""" if comp not in context.env or not context.env[comp]: # The compiler construction variable is not set or empty return 1 lang, suffix, msg = _lang2suffix(language) if msg: return 1 if use_shared: return context.CompileSharedObject(text, suffix) else: return context.CompileProg(text, suffix) def CheckFunc(context, function_name, header = None, language = None): """ Configure check for a function "function_name". "language" should be "C" or "C++" and is used to select the compiler. Default is "C". Optional "header" can be defined to define a function prototype, include a header file or anything else that comes before main(). Sets HAVE_function_name in context.havedict according to the result. Note that this uses the current value of compiler and linker flags, make sure $CFLAGS, $CPPFLAGS and $LIBS are set correctly. Returns an empty string for success, an error message for failure. """ # Remarks from autoconf: # - Don't include <ctype.h> because on OSF/1 3.0 it includes <sys/types.h> # which includes <sys/select.h> which contains a prototype for select. # Similarly for bzero. # - assert.h is included to define __stub macros and hopefully few # prototypes, which can conflict with char $1(); below. # - Override any gcc2 internal prototype to avoid an error. # - We use char for the function declaration because int might match the # return type of a gcc2 builtin and then its argument prototype would # still apply. # - The GNU C library defines this for functions which it implements to # always fail with ENOSYS. Some functions are actually named something # starting with __ and the normal name is an alias. if context.headerfilename: includetext = '#include "%s"' % context.headerfilename else: includetext = '' if not header: header = """ #ifdef __cplusplus extern "C" #endif char %s();""" % function_name lang, suffix, msg = _lang2suffix(language) if msg: context.Display("Cannot check for %s(): %s\n" % (function_name, msg)) return msg text = """ %(include)s #include <assert.h> %(hdr)s int main() { #if defined (__stub_%(name)s) || defined (__stub___%(name)s) fail fail fail #else %(name)s(); #endif return 0; } """ % { 'name': function_name, 'include': includetext, 'hdr': header } context.Display("Checking for %s function %s()... " % (lang, function_name)) ret = context.BuildProg(text, suffix) _YesNoResult(context, ret, "HAVE_" + function_name, text, "Define to 1 if the system has the function `%s'." %\ function_name) return ret def CheckHeader(context, header_name, header = None, language = None, include_quotes = None): """ Configure check for a C or C++ header file "header_name". Optional "header" can be defined to do something before including the header file (unusual, supported for consistency). "language" should be "C" or "C++" and is used to select the compiler. Default is "C". Sets HAVE_header_name in context.havedict according to the result. Note that this uses the current value of compiler and linker flags, make sure $CFLAGS and $CPPFLAGS are set correctly. Returns an empty string for success, an error message for failure. """ # Why compile the program instead of just running the preprocessor? # It is possible that the header file exists, but actually using it may # fail (e.g., because it depends on other header files). Thus this test is # more strict. It may require using the "header" argument. # # Use <> by default, because the check is normally used for system header # files. SCons passes '""' to overrule this. # Include "confdefs.h" first, so that the header can use HAVE_HEADER_H. if context.headerfilename: includetext = '#include "%s"\n' % context.headerfilename else: includetext = '' if not header: header = "" lang, suffix, msg = _lang2suffix(language) if msg: context.Display("Cannot check for header file %s: %s\n" % (header_name, msg)) return msg if not include_quotes: include_quotes = "<>" text = "%s%s\n#include %s%s%s\n\n" % (includetext, header, include_quotes[0], header_name, include_quotes[1]) context.Display("Checking for %s header file %s... " % (lang, header_name)) ret = context.CompileProg(text, suffix) _YesNoResult(context, ret, "HAVE_" + header_name, text, "Define to 1 if you have the <%s> header file." % header_name) return ret def CheckType(context, type_name, fallback = None, header = None, language = None): """ Configure check for a C or C++ type "type_name". Optional "header" can be defined to include a header file. "language" should be "C" or "C++" and is used to select the compiler. Default is "C". Sets HAVE_type_name in context.havedict according to the result. Note that this uses the current value of compiler and linker flags, make sure $CFLAGS, $CPPFLAGS and $LIBS are set correctly. Returns an empty string for success, an error message for failure. """ # Include "confdefs.h" first, so that the header can use HAVE_HEADER_H. if context.headerfilename: includetext = '#include "%s"' % context.headerfilename else: includetext = '' if not header: header = "" lang, suffix, msg = _lang2suffix(language) if msg: context.Display("Cannot check for %s type: %s\n" % (type_name, msg)) return msg # Remarks from autoconf about this test: # - Grepping for the type in include files is not reliable (grep isn't # portable anyway). # - Using "TYPE my_var;" doesn't work for const qualified types in C++. # Adding an initializer is not valid for some C++ classes. # - Using the type as parameter to a function either fails for K&$ C or for # C++. # - Using "TYPE *my_var;" is valid in C for some types that are not # declared (struct something). # - Using "sizeof(TYPE)" is valid when TYPE is actually a variable. # - Using the previous two together works reliably. text = """ %(include)s %(header)s int main() { if ((%(name)s *) 0) return 0; if (sizeof (%(name)s)) return 0; } """ % { 'include': includetext, 'header': header, 'name': type_name } context.Display("Checking for %s type %s... " % (lang, type_name)) ret = context.BuildProg(text, suffix) _YesNoResult(context, ret, "HAVE_" + type_name, text, "Define to 1 if the system has the type `%s'." % type_name) if ret and fallback and context.headerfilename: f = open(context.headerfilename, "a") f.write("typedef %s %s;\n" % (fallback, type_name)) f.close() return ret def CheckTypeSize(context, type_name, header = None, language = None, expect = None): """This check can be used to get the size of a given type, or to check whether the type is of expected size. Arguments: - type : str the type to check - includes : sequence list of headers to include in the test code before testing the type - language : str 'C' or 'C++' - expect : int if given, will test wether the type has the given number of bytes. If not given, will automatically find the size. Returns: status : int 0 if the check failed, or the found size of the type if the check succeeded.""" # Include "confdefs.h" first, so that the header can use HAVE_HEADER_H. if context.headerfilename: includetext = '#include "%s"' % context.headerfilename else: includetext = '' if not header: header = "" lang, suffix, msg = _lang2suffix(language) if msg: context.Display("Cannot check for %s type: %s\n" % (type_name, msg)) return msg src = includetext + header if not expect is None: # Only check if the given size is the right one context.Display('Checking %s is %d bytes... ' % (type_name, expect)) # test code taken from autoconf: this is a pretty clever hack to find that # a type is of a given size using only compilation. This speeds things up # quite a bit compared to straightforward code using TryRun src = src + r""" typedef %s scons_check_type; int main() { static int test_array[1 - 2 * !(((long int) (sizeof(scons_check_type))) == %d)]; test_array[0] = 0; return 0; } """ st = context.CompileProg(src % (type_name, expect), suffix) if not st: context.Display("yes\n") _Have(context, "SIZEOF_%s" % type_name, expect, "The size of `%s', as computed by sizeof." % type_name) return expect else: context.Display("no\n") _LogFailed(context, src, st) return 0 else: # Only check if the given size is the right one context.Message('Checking size of %s ... ' % type_name) # We have to be careful with the program we wish to test here since # compilation will be attempted using the current environment's flags. # So make sure that the program will compile without any warning. For # example using: 'int main(int argc, char** argv)' will fail with the # '-Wall -Werror' flags since the variables argc and argv would not be # used in the program... # src = src + """ #include <stdlib.h> #include <stdio.h> int main() { printf("%d", (int)sizeof(""" + type_name + """)); return 0; } """ st, out = context.RunProg(src, suffix) try: size = int(out) except ValueError: # If cannot convert output of test prog to an integer (the size), # something went wront, so just fail st = 1 size = 0 if not st: context.Display("yes\n") _Have(context, "SIZEOF_%s" % type_name, size, "The size of `%s', as computed by sizeof." % type_name) return size else: context.Display("no\n") _LogFailed(context, src, st) return 0 return 0 def CheckDeclaration(context, symbol, includes = None, language = None): """Checks whether symbol is declared. Use the same test as autoconf, that is test whether the symbol is defined as a macro or can be used as an r-value. Arguments: symbol : str the symbol to check includes : str Optional "header" can be defined to include a header file. language : str only C and C++ supported. Returns: status : bool True if the check failed, False if succeeded.""" # Include "confdefs.h" first, so that the header can use HAVE_HEADER_H. if context.headerfilename: includetext = '#include "%s"' % context.headerfilename else: includetext = '' if not includes: includes = "" lang, suffix, msg = _lang2suffix(language) if msg: context.Display("Cannot check for declaration %s: %s\n" % (symbol, msg)) return msg src = includetext + includes context.Display('Checking whether %s is declared... ' % symbol) src = src + r""" int main() { #ifndef %s (void) %s; #endif ; return 0; } """ % (symbol, symbol) st = context.CompileProg(src, suffix) _YesNoResult(context, st, "HAVE_DECL_" + symbol, src, "Set to 1 if %s is defined." % symbol) return st def CheckLib(context, libs, func_name = None, header = None, extra_libs = None, call = None, language = None, autoadd = 1, append = True): """ Configure check for a C or C++ libraries "libs". Searches through the list of libraries, until one is found where the test succeeds. Tests if "func_name" or "call" exists in the library. Note: if it exists in another library the test succeeds anyway! Optional "header" can be defined to include a header file. If not given a default prototype for "func_name" is added. Optional "extra_libs" is a list of library names to be added after "lib_name" in the build command. To be used for libraries that "lib_name" depends on. Optional "call" replaces the call to "func_name" in the test code. It must consist of complete C statements, including a trailing ";". Both "func_name" and "call" arguments are optional, and in that case, just linking against the libs is tested. "language" should be "C" or "C++" and is used to select the compiler. Default is "C". Note that this uses the current value of compiler and linker flags, make sure $CFLAGS, $CPPFLAGS and $LIBS are set correctly. Returns an empty string for success, an error message for failure. """ # Include "confdefs.h" first, so that the header can use HAVE_HEADER_H. if context.headerfilename: includetext = '#include "%s"' % context.headerfilename else: includetext = '' if not header: header = "" text = """ %s %s""" % (includetext, header) # Add a function declaration if needed. if func_name and func_name != "main": if not header: text = text + """ #ifdef __cplusplus extern "C" #endif char %s(); """ % func_name # The actual test code. if not call: call = "%s();" % func_name # if no function to test, leave main() blank text = text + """ int main() { %s return 0; } """ % (call or "") if call: i = call.find("\n") if i > 0: calltext = call[:i] + ".." elif call[-1] == ';': calltext = call[:-1] else: calltext = call for lib_name in libs: lang, suffix, msg = _lang2suffix(language) if msg: context.Display("Cannot check for library %s: %s\n" % (lib_name, msg)) return msg # if a function was specified to run in main(), say it if call: context.Display("Checking for %s in %s library %s... " % (calltext, lang, lib_name)) # otherwise, just say the name of library and language else: context.Display("Checking for %s library %s... " % (lang, lib_name)) if lib_name: l = [ lib_name ] if extra_libs: l.extend(extra_libs) if append: oldLIBS = context.AppendLIBS(l) else: oldLIBS = context.PrependLIBS(l) sym = "HAVE_LIB" + lib_name else: oldLIBS = -1 sym = None ret = context.BuildProg(text, suffix) _YesNoResult(context, ret, sym, text, "Define to 1 if you have the `%s' library." % lib_name) if oldLIBS != -1 and (ret or not autoadd): context.SetLIBS(oldLIBS) if not ret: return ret return ret # # END OF PUBLIC FUNCTIONS # def _YesNoResult(context, ret, key, text, comment = None): """ Handle the result of a test with a "yes" or "no" result. "ret" is the return value: empty if OK, error message when not. "key" is the name of the symbol to be defined (HAVE_foo). "text" is the source code of the program used for testing. "comment" is the C comment to add above the line defining the symbol (the comment is automatically put inside a /* */). If None, no comment is added. """ if key: _Have(context, key, not ret, comment) if ret: context.Display("no\n") _LogFailed(context, text, ret) else: context.Display("yes\n") def _Have(context, key, have, comment = None): """ Store result of a test in context.havedict and context.headerfilename. "key" is a "HAVE_abc" name. It is turned into all CAPITALS and non- alphanumerics are replaced by an underscore. The value of "have" can be: 1 - Feature is defined, add "#define key". 0 - Feature is not defined, add "/* #undef key */". Adding "undef" is what autoconf does. Not useful for the compiler, but it shows that the test was done. number - Feature is defined to this number "#define key have". Doesn't work for 0 or 1, use a string then. string - Feature is defined to this string "#define key have". Give "have" as is should appear in the header file, include quotes when desired and escape special characters! """ key_up = key.upper() key_up = re.sub('[^A-Z0-9_]', '_', key_up) context.havedict[key_up] = have if have == 1: line = "#define %s 1\n" % key_up elif have == 0: line = "/* #undef %s */\n" % key_up elif isinstance(have, IntType): line = "#define %s %d\n" % (key_up, have) else: line = "#define %s %s\n" % (key_up, str(have)) if comment is not None: lines = "\n/* %s */\n" % comment + line else: lines = "\n" + line if context.headerfilename: f = open(context.headerfilename, "a") f.write(lines) f.close() elif hasattr(context,'config_h'): context.config_h = context.config_h + lines def _LogFailed(context, text, msg): """ Write to the log about a failed program. Add line numbers, so that error messages can be understood. """ if LogInputFiles: context.Log("Failed program was:\n") lines = text.split('\n') if len(lines) and lines[-1] == '': lines = lines[:-1] # remove trailing empty line n = 1 for line in lines: context.Log("%d: %s\n" % (n, line)) n = n + 1 if LogErrorMessages: context.Log("Error message: %s\n" % msg) def _lang2suffix(lang): """ Convert a language name to a suffix. When "lang" is empty or None C is assumed. Returns a tuple (lang, suffix, None) when it works. For an unrecognized language returns (None, None, msg). Where: lang = the unified language name suffix = the suffix, including the leading dot msg = an error message """ if not lang or lang in ["C", "c"]: return ("C", ".c", None) if lang in ["c++", "C++", "cpp", "CXX", "cxx"]: return ("C++", ".cpp", None) return None, None, "Unsupported language: %s" % lang # vim: set sw=4 et sts=4 tw=79 fo+=l: # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""engine.SCons.Platform.darwin Platform-specific initialization for Mac OS X systems. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Platform.Platform() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Platform/darwin.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import posix import os def generate(env): posix.generate(env) env['SHLIBSUFFIX'] = '.dylib' # put macports paths at front to override Apple's versions, fink path is after # For now let people who want Macports or Fink tools specify it! # env['ENV']['PATH'] = '/opt/local/bin:/opt/local/sbin:' + env['ENV']['PATH'] + ':/sw/bin' # Store extra system paths in env['ENV']['PATHOSX'] filelist = ['/etc/paths',] # make sure this works on Macs with Tiger or earlier try: dirlist = os.listdir('/etc/paths.d') except: dirlist = [] for file in dirlist: filelist.append('/etc/paths.d/'+file) for file in filelist: if os.path.isfile(file): f = open(file, 'r') lines = f.readlines() for line in lines: if line: env.AppendENVPath('PATHOSX', line.strip('\n')) f.close() # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Platform.cygwin Platform-specific initialization for Cygwin systems. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Platform.Platform() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Platform/cygwin.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import posix from SCons.Platform import TempFileMunge def generate(env): posix.generate(env) env['PROGPREFIX'] = '' env['PROGSUFFIX'] = '.exe' env['SHLIBPREFIX'] = '' env['SHLIBSUFFIX'] = '.dll' env['LIBPREFIXES'] = [ '$LIBPREFIX', '$SHLIBPREFIX' ] env['LIBSUFFIXES'] = [ '$LIBSUFFIX', '$SHLIBSUFFIX' ] env['TEMPFILE'] = TempFileMunge env['TEMPFILEPREFIX'] = '@' env['MAXLINELENGTH'] = 2048 # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Platform.win32 Platform-specific initialization for Win32 systems. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Platform.Platform() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Platform/win32.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os import os.path import sys import tempfile from SCons.Platform.posix import exitvalmap from SCons.Platform import TempFileMunge import SCons.Util try: import msvcrt import win32api import win32con msvcrt.get_osfhandle win32api.SetHandleInformation win32con.HANDLE_FLAG_INHERIT except ImportError: parallel_msg = \ "you do not seem to have the pywin32 extensions installed;\n" + \ "\tparallel (-j) builds may not work reliably with open Python files." except AttributeError: parallel_msg = \ "your pywin32 extensions do not support file handle operations;\n" + \ "\tparallel (-j) builds may not work reliably with open Python files." else: parallel_msg = None import builtins _builtin_file = builtins.file _builtin_open = builtins.open class _scons_file(_builtin_file): def __init__(self, *args, **kw): _builtin_file.__init__(self, *args, **kw) win32api.SetHandleInformation(msvcrt.get_osfhandle(self.fileno()), win32con.HANDLE_FLAG_INHERIT, 0) def _scons_open(*args, **kw): fp = _builtin_open(*args, **kw) win32api.SetHandleInformation(msvcrt.get_osfhandle(fp.fileno()), win32con.HANDLE_FLAG_INHERIT, 0) return fp builtins.file = _scons_file builtins.open = _scons_open # The upshot of all this is that, if you are using Python 1.5.2, # you had better have cmd or command.com in your PATH when you run # scons. def piped_spawn(sh, escape, cmd, args, env, stdout, stderr): # There is no direct way to do that in python. What we do # here should work for most cases: # In case stdout (stderr) is not redirected to a file, # we redirect it into a temporary file tmpFileStdout # (tmpFileStderr) and copy the contents of this file # to stdout (stderr) given in the argument if not sh: sys.stderr.write("scons: Could not find command interpreter, is it in your PATH?\n") return 127 else: # one temporary file for stdout and stderr tmpFileStdout = os.path.normpath(tempfile.mktemp()) tmpFileStderr = os.path.normpath(tempfile.mktemp()) # check if output is redirected stdoutRedirected = 0 stderrRedirected = 0 for arg in args: # are there more possibilities to redirect stdout ? if (arg.find( ">", 0, 1 ) != -1 or arg.find( "1>", 0, 2 ) != -1): stdoutRedirected = 1 # are there more possibilities to redirect stderr ? if arg.find( "2>", 0, 2 ) != -1: stderrRedirected = 1 # redirect output of non-redirected streams to our tempfiles if stdoutRedirected == 0: args.append(">" + str(tmpFileStdout)) if stderrRedirected == 0: args.append("2>" + str(tmpFileStderr)) # actually do the spawn try: args = [sh, '/C', escape(' '.join(args)) ] ret = os.spawnve(os.P_WAIT, sh, args, env) except OSError, e: # catch any error try: ret = exitvalmap[e[0]] except KeyError: sys.stderr.write("scons: unknown OSError exception code %d - %s: %s\n" % (e[0], cmd, e[1])) if stderr is not None: stderr.write("scons: %s: %s\n" % (cmd, e[1])) # copy child output from tempfiles to our streams # and do clean up stuff if stdout is not None and stdoutRedirected == 0: try: stdout.write(open( tmpFileStdout, "r" ).read()) os.remove( tmpFileStdout ) except (IOError, OSError): pass if stderr is not None and stderrRedirected == 0: try: stderr.write(open( tmpFileStderr, "r" ).read()) os.remove( tmpFileStderr ) except (IOError, OSError): pass return ret def exec_spawn(l, env): try: result = os.spawnve(os.P_WAIT, l[0], l, env) except OSError, e: try: result = exitvalmap[e[0]] sys.stderr.write("scons: %s: %s\n" % (l[0], e[1])) except KeyError: result = 127 if len(l) > 2: if len(l[2]) < 1000: command = ' '.join(l[0:3]) else: command = l[0] else: command = l[0] sys.stderr.write("scons: unknown OSError exception code %d - '%s': %s\n" % (e[0], command, e[1])) return result def spawn(sh, escape, cmd, args, env): if not sh: sys.stderr.write("scons: Could not find command interpreter, is it in your PATH?\n") return 127 return exec_spawn([sh, '/C', escape(' '.join(args))], env) # Windows does not allow special characters in file names anyway, so no # need for a complex escape function, we will just quote the arg, except # that "cmd /c" requires that if an argument ends with a backslash it # needs to be escaped so as not to interfere with closing double quote # that we add. def escape(x): if x[-1] == '\\': x = x + '\\' return '"' + x + '"' # Get the windows system directory name _system_root = None def get_system_root(): global _system_root if _system_root is not None: return _system_root # A resonable default if we can't read the registry val = os.environ.get('SystemRoot', "C:\\WINDOWS") if SCons.Util.can_read_reg: try: # Look for Windows NT system root k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE, 'Software\\Microsoft\\Windows NT\\CurrentVersion') val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot') except SCons.Util.RegError: try: # Okay, try the Windows 9x system root k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE, 'Software\\Microsoft\\Windows\\CurrentVersion') val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot') except KeyboardInterrupt: raise except: pass _system_root = val return val # Get the location of the program files directory def get_program_files_dir(): # Now see if we can look in the registry... val = '' if SCons.Util.can_read_reg: try: # Look for Windows Program Files directory k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE, 'Software\\Microsoft\\Windows\\CurrentVersion') val, tok = SCons.Util.RegQueryValueEx(k, 'ProgramFilesDir') except SCons.Util.RegError: val = '' pass if val == '': # A reasonable default if we can't read the registry # (Actually, it's pretty reasonable even if we can :-) val = os.path.join(os.path.dirname(get_system_root()),"Program Files") return val # Determine which windows CPU were running on. class ArchDefinition(object): """ A class for defining architecture-specific settings and logic. """ def __init__(self, arch, synonyms=[]): self.arch = arch self.synonyms = synonyms SupportedArchitectureList = [ ArchDefinition( 'x86', ['i386', 'i486', 'i586', 'i686'], ), ArchDefinition( 'x86_64', ['AMD64', 'amd64', 'em64t', 'EM64T', 'x86_64'], ), ArchDefinition( 'ia64', ['IA64'], ), ] SupportedArchitectureMap = {} for a in SupportedArchitectureList: SupportedArchitectureMap[a.arch] = a for s in a.synonyms: SupportedArchitectureMap[s] = a def get_architecture(arch=None): """Returns the definition for the specified architecture string. If no string is specified, the system default is returned (as defined by the PROCESSOR_ARCHITEW6432 or PROCESSOR_ARCHITECTURE environment variables). """ if arch is None: arch = os.environ.get('PROCESSOR_ARCHITEW6432') if not arch: arch = os.environ.get('PROCESSOR_ARCHITECTURE') return SupportedArchitectureMap.get(arch, ArchDefinition('', [''])) def generate(env): # Attempt to find cmd.exe (for WinNT/2k/XP) or # command.com for Win9x cmd_interp = '' # First see if we can look in the registry... if SCons.Util.can_read_reg: try: # Look for Windows NT system root k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE, 'Software\\Microsoft\\Windows NT\\CurrentVersion') val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot') cmd_interp = os.path.join(val, 'System32\\cmd.exe') except SCons.Util.RegError: try: # Okay, try the Windows 9x system root k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE, 'Software\\Microsoft\\Windows\\CurrentVersion') val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot') cmd_interp = os.path.join(val, 'command.com') except KeyboardInterrupt: raise except: pass # For the special case of not having access to the registry, we # use a temporary path and pathext to attempt to find the command # interpreter. If we fail, we try to find the interpreter through # the env's PATH. The problem with that is that it might not # contain an ENV and a PATH. if not cmd_interp: systemroot = get_system_root() tmp_path = systemroot + os.pathsep + \ os.path.join(systemroot,'System32') tmp_pathext = '.com;.exe;.bat;.cmd' if 'PATHEXT' in os.environ: tmp_pathext = os.environ['PATHEXT'] cmd_interp = SCons.Util.WhereIs('cmd', tmp_path, tmp_pathext) if not cmd_interp: cmd_interp = SCons.Util.WhereIs('command', tmp_path, tmp_pathext) if not cmd_interp: cmd_interp = env.Detect('cmd') if not cmd_interp: cmd_interp = env.Detect('command') if 'ENV' not in env: env['ENV'] = {} # Import things from the external environment to the construction # environment's ENV. This is a potential slippery slope, because we # *don't* want to make builds dependent on the user's environment by # default. We're doing this for SystemRoot, though, because it's # needed for anything that uses sockets, and seldom changes, and # for SystemDrive because it's related. # # Weigh the impact carefully before adding other variables to this list. import_env = [ 'SystemDrive', 'SystemRoot', 'TEMP', 'TMP' ] for var in import_env: v = os.environ.get(var) if v: env['ENV'][var] = v if 'COMSPEC' not in env['ENV']: v = os.environ.get("COMSPEC") if v: env['ENV']['COMSPEC'] = v env.AppendENVPath('PATH', get_system_root() + '\System32') env['ENV']['PATHEXT'] = '.COM;.EXE;.BAT;.CMD' env['OBJPREFIX'] = '' env['OBJSUFFIX'] = '.obj' env['SHOBJPREFIX'] = '$OBJPREFIX' env['SHOBJSUFFIX'] = '$OBJSUFFIX' env['PROGPREFIX'] = '' env['PROGSUFFIX'] = '.exe' env['LIBPREFIX'] = '' env['LIBSUFFIX'] = '.lib' env['SHLIBPREFIX'] = '' env['SHLIBSUFFIX'] = '.dll' env['LIBPREFIXES'] = [ '$LIBPREFIX' ] env['LIBSUFFIXES'] = [ '$LIBSUFFIX' ] env['PSPAWN'] = piped_spawn env['SPAWN'] = spawn env['SHELL'] = cmd_interp env['TEMPFILE'] = TempFileMunge env['TEMPFILEPREFIX'] = '@' env['MAXLINELENGTH'] = 2048 env['ESCAPE'] = escape env['HOST_OS'] = 'win32' env['HOST_ARCH'] = get_architecture().arch # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Platform SCons platform selection. This looks for modules that define a callable object that can modify a construction environment as appropriate for a given platform. Note that we take a more simplistic view of "platform" than Python does. We're looking for a single string that determines a set of tool-independent variables with which to initialize a construction environment. Consequently, we'll examine both sys.platform and os.name (and anything else that might come in to play) in order to return some specification which is unique enough for our purposes. Note that because this subsysem just *selects* a callable that can modify a construction environment, it's possible for people to define their own "platform specification" in an arbitrary callable function. No one needs to use or tie in to this subsystem in order to roll their own platform definition. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Platform/__init__.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.compat import imp import os import sys import tempfile import SCons.Errors import SCons.Subst import SCons.Tool def platform_default(): """Return the platform string for our execution environment. The returned value should map to one of the SCons/Platform/*.py files. Since we're architecture independent, though, we don't care about the machine architecture. """ osname = os.name if osname == 'java': osname = os._osType if osname == 'posix': if sys.platform == 'cygwin': return 'cygwin' elif sys.platform.find('irix') != -1: return 'irix' elif sys.platform.find('sunos') != -1: return 'sunos' elif sys.platform.find('hp-ux') != -1: return 'hpux' elif sys.platform.find('aix') != -1: return 'aix' elif sys.platform.find('darwin') != -1: return 'darwin' else: return 'posix' elif os.name == 'os2': return 'os2' else: return sys.platform def platform_module(name = platform_default()): """Return the imported module for the platform. This looks for a module name that matches the specified argument. If the name is unspecified, we fetch the appropriate default for our execution environment. """ full_name = 'SCons.Platform.' + name if full_name not in sys.modules: if os.name == 'java': eval(full_name) else: try: file, path, desc = imp.find_module(name, sys.modules['SCons.Platform'].__path__) try: mod = imp.load_module(full_name, file, path, desc) finally: if file: file.close() except ImportError: try: import zipimport importer = zipimport.zipimporter( sys.modules['SCons.Platform'].__path__[0] ) mod = importer.load_module(full_name) except ImportError: raise SCons.Errors.UserError("No platform named '%s'" % name) setattr(SCons.Platform, name, mod) return sys.modules[full_name] def DefaultToolList(platform, env): """Select a default tool list for the specified platform. """ return SCons.Tool.tool_list(platform, env) class PlatformSpec(object): def __init__(self, name, generate): self.name = name self.generate = generate def __call__(self, *args, **kw): return self.generate(*args, **kw) def __str__(self): return self.name class TempFileMunge(object): """A callable class. You can set an Environment variable to this, then call it with a string argument, then it will perform temporary file substitution on it. This is used to circumvent the long command line limitation. Example usage: env["TEMPFILE"] = TempFileMunge env["LINKCOM"] = "${TEMPFILE('$LINK $TARGET $SOURCES')}" By default, the name of the temporary file used begins with a prefix of '@'. This may be configred for other tool chains by setting '$TEMPFILEPREFIX'. env["TEMPFILEPREFIX"] = '-@' # diab compiler env["TEMPFILEPREFIX"] = '-via' # arm tool chain """ def __init__(self, cmd): self.cmd = cmd def __call__(self, target, source, env, for_signature): if for_signature: # If we're being called for signature calculation, it's # because we're being called by the string expansion in # Subst.py, which has the logic to strip any $( $) that # may be in the command line we squirreled away. So we # just return the raw command line and let the upper # string substitution layers do their thing. return self.cmd # Now we're actually being called because someone is actually # going to try to execute the command, so we have to do our # own expansion. cmd = env.subst_list(self.cmd, SCons.Subst.SUBST_CMD, target, source)[0] try: maxline = int(env.subst('$MAXLINELENGTH')) except ValueError: maxline = 2048 length = 0 for c in cmd: length += len(c) if length <= maxline: return self.cmd # We do a normpath because mktemp() has what appears to be # a bug in Windows that will use a forward slash as a path # delimiter. Windows's link mistakes that for a command line # switch and barfs. # # We use the .lnk suffix for the benefit of the Phar Lap # linkloc linker, which likes to append an .lnk suffix if # none is given. (fd, tmp) = tempfile.mkstemp('.lnk', text=True) native_tmp = SCons.Util.get_native_path(os.path.normpath(tmp)) if env['SHELL'] and env['SHELL'] == 'sh': # The sh shell will try to escape the backslashes in the # path, so unescape them. native_tmp = native_tmp.replace('\\', r'\\\\') # In Cygwin, we want to use rm to delete the temporary # file, because del does not exist in the sh shell. rm = env.Detect('rm') or 'del' else: # Don't use 'rm' if the shell is not sh, because rm won't # work with the Windows shells (cmd.exe or command.com) or # Windows path names. rm = 'del' prefix = env.subst('$TEMPFILEPREFIX') if not prefix: prefix = '@' args = list(map(SCons.Subst.quote_spaces, cmd[1:])) os.write(fd, " ".join(args) + "\n") os.close(fd) # XXX Using the SCons.Action.print_actions value directly # like this is bogus, but expedient. This class should # really be rewritten as an Action that defines the # __call__() and strfunction() methods and lets the # normal action-execution logic handle whether or not to # print/execute the action. The problem, though, is all # of that is decided before we execute this method as # part of expanding the $TEMPFILE construction variable. # Consequently, refactoring this will have to wait until # we get more flexible with allowing Actions to exist # independently and get strung together arbitrarily like # Ant tasks. In the meantime, it's going to be more # user-friendly to not let obsession with architectural # purity get in the way of just being helpful, so we'll # reach into SCons.Action directly. if SCons.Action.print_actions: print("Using tempfile "+native_tmp+" for command line:\n"+ str(cmd[0]) + " " + " ".join(args)) return [ cmd[0], prefix + native_tmp + '\n' + rm, native_tmp ] def Platform(name = platform_default()): """Select a canned Platform specification. """ module = platform_module(name) spec = PlatformSpec(name, module.generate) return spec # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Platform.posix Platform-specific initialization for POSIX (Linux, UNIX, etc.) systems. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Platform.Platform() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Platform/posix.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import errno import os import os.path import subprocess import sys import select import SCons.Util from SCons.Platform import TempFileMunge exitvalmap = { 2 : 127, 13 : 126, } def escape(arg): "escape shell special characters" slash = '\\' special = '"$()' arg = arg.replace(slash, slash+slash) for c in special: arg = arg.replace(c, slash+c) return '"' + arg + '"' def exec_system(l, env): stat = os.system(' '.join(l)) if stat & 0xff: return stat | 0x80 return stat >> 8 def exec_spawnvpe(l, env): stat = os.spawnvpe(os.P_WAIT, l[0], l, env) # os.spawnvpe() returns the actual exit code, not the encoding # returned by os.waitpid() or os.system(). return stat def exec_fork(l, env): pid = os.fork() if not pid: # Child process. exitval = 127 try: os.execvpe(l[0], l, env) except OSError, e: exitval = exitvalmap.get(e[0], e[0]) sys.stderr.write("scons: %s: %s\n" % (l[0], e[1])) os._exit(exitval) else: # Parent process. pid, stat = os.waitpid(pid, 0) if stat & 0xff: return stat | 0x80 return stat >> 8 def _get_env_command(sh, escape, cmd, args, env): s = ' '.join(args) if env: l = ['env', '-'] + \ [escape(t[0])+'='+escape(t[1]) for t in env.items()] + \ [sh, '-c', escape(s)] s = ' '.join(l) return s def env_spawn(sh, escape, cmd, args, env): return exec_system([_get_env_command( sh, escape, cmd, args, env)], env) def spawnvpe_spawn(sh, escape, cmd, args, env): return exec_spawnvpe([sh, '-c', ' '.join(args)], env) def fork_spawn(sh, escape, cmd, args, env): return exec_fork([sh, '-c', ' '.join(args)], env) def process_cmd_output(cmd_stdout, cmd_stderr, stdout, stderr): stdout_eof = stderr_eof = 0 while not (stdout_eof and stderr_eof): try: (i,o,e) = select.select([cmd_stdout, cmd_stderr], [], []) if cmd_stdout in i: str = cmd_stdout.read() if len(str) == 0: stdout_eof = 1 elif stdout is not None: stdout.write(str) if cmd_stderr in i: str = cmd_stderr.read() if len(str) == 0: #sys.__stderr__.write( "stderr_eof=1\n" ) stderr_eof = 1 else: #sys.__stderr__.write( "str(stderr) = %s\n" % str ) stderr.write(str) except select.error, (_errno, _strerror): if _errno != errno.EINTR: raise def exec_popen3(l, env, stdout, stderr): proc = subprocess.Popen(' '.join(l), stdout=stdout, stderr=stderr, shell=True) stat = proc.wait() if stat & 0xff: return stat | 0x80 return stat >> 8 def exec_piped_fork(l, env, stdout, stderr): # spawn using fork / exec and providing a pipe for the command's # stdout / stderr stream if stdout != stderr: (rFdOut, wFdOut) = os.pipe() (rFdErr, wFdErr) = os.pipe() else: (rFdOut, wFdOut) = os.pipe() rFdErr = rFdOut wFdErr = wFdOut # do the fork pid = os.fork() if not pid: # Child process os.close( rFdOut ) if rFdOut != rFdErr: os.close( rFdErr ) os.dup2( wFdOut, 1 ) # is there some symbolic way to do that ? os.dup2( wFdErr, 2 ) os.close( wFdOut ) if stdout != stderr: os.close( wFdErr ) exitval = 127 try: os.execvpe(l[0], l, env) except OSError, e: exitval = exitvalmap.get(e[0], e[0]) stderr.write("scons: %s: %s\n" % (l[0], e[1])) os._exit(exitval) else: # Parent process pid, stat = os.waitpid(pid, 0) os.close( wFdOut ) if stdout != stderr: os.close( wFdErr ) childOut = os.fdopen( rFdOut ) if stdout != stderr: childErr = os.fdopen( rFdErr ) else: childErr = childOut process_cmd_output(childOut, childErr, stdout, stderr) os.close( rFdOut ) if stdout != stderr: os.close( rFdErr ) if stat & 0xff: return stat | 0x80 return stat >> 8 def piped_env_spawn(sh, escape, cmd, args, env, stdout, stderr): # spawn using Popen3 combined with the env command # the command name and the command's stdout is written to stdout # the command's stderr is written to stderr return exec_popen3([_get_env_command(sh, escape, cmd, args, env)], env, stdout, stderr) def piped_fork_spawn(sh, escape, cmd, args, env, stdout, stderr): # spawn using fork / exec and providing a pipe for the command's # stdout / stderr stream return exec_piped_fork([sh, '-c', ' '.join(args)], env, stdout, stderr) def generate(env): # If os.spawnvpe() exists, we use it to spawn commands. Otherwise # if the env utility exists, we use os.system() to spawn commands, # finally we fall back on os.fork()/os.exec(). # # os.spawnvpe() is prefered because it is the most efficient. But # for Python versions without it, os.system() is prefered because it # is claimed that it works better with threads (i.e. -j) and is more # efficient than forking Python. # # NB: Other people on the scons-users mailing list have claimed that # os.fork()/os.exec() works better than os.system(). There may just # not be a default that works best for all users. if 'spawnvpe' in os.__dict__: spawn = spawnvpe_spawn elif env.Detect('env'): spawn = env_spawn else: spawn = fork_spawn if env.Detect('env'): pspawn = piped_env_spawn else: pspawn = piped_fork_spawn if 'ENV' not in env: env['ENV'] = {} env['ENV']['PATH'] = '/usr/local/bin:/opt/bin:/bin:/usr/bin' env['OBJPREFIX'] = '' env['OBJSUFFIX'] = '.o' env['SHOBJPREFIX'] = '$OBJPREFIX' env['SHOBJSUFFIX'] = '$OBJSUFFIX' env['PROGPREFIX'] = '' env['PROGSUFFIX'] = '' env['LIBPREFIX'] = 'lib' env['LIBSUFFIX'] = '.a' env['SHLIBPREFIX'] = '$LIBPREFIX' env['SHLIBSUFFIX'] = '.so' env['LIBPREFIXES'] = [ '$LIBPREFIX' ] env['LIBSUFFIXES'] = [ '$LIBSUFFIX', '$SHLIBSUFFIX' ] env['PSPAWN'] = pspawn env['SPAWN'] = spawn env['SHELL'] = 'sh' env['ESCAPE'] = escape env['TEMPFILE'] = TempFileMunge env['TEMPFILEPREFIX'] = '@' #Based on LINUX: ARG_MAX=ARG_MAX=131072 - 3000 for environment expansion #Note: specific platforms might rise or lower this value env['MAXLINELENGTH'] = 128072 # This platform supports RPATH specifications. env['__RPATH'] = '$_RPATH' # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Platform.os2 Platform-specific initialization for OS/2 systems. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Platform.Platform() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Platform/os2.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import win32 def generate(env): if 'ENV' not in env: env['ENV'] = {} env['OBJPREFIX'] = '' env['OBJSUFFIX'] = '.obj' env['SHOBJPREFIX'] = '$OBJPREFIX' env['SHOBJSUFFIX'] = '$OBJSUFFIX' env['PROGPREFIX'] = '' env['PROGSUFFIX'] = '.exe' env['LIBPREFIX'] = '' env['LIBSUFFIX'] = '.lib' env['SHLIBPREFIX'] = '' env['SHLIBSUFFIX'] = '.dll' env['LIBPREFIXES'] = '$LIBPREFIX' env['LIBSUFFIXES'] = [ '$LIBSUFFIX', '$SHLIBSUFFIX' ] env['HOST_OS'] = 'os2' env['HOST_ARCH'] = win32.get_architecture().arch # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""engine.SCons.Platform.hpux Platform-specific initialization for HP-UX systems. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Platform.Platform() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Platform/hpux.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import posix def generate(env): posix.generate(env) #Based on HP-UX11i: ARG_MAX=2048000 - 3000 for environment expansion env['MAXLINELENGTH'] = 2045000 # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""engine.SCons.Platform.sunos Platform-specific initialization for Sun systems. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Platform.Platform() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Platform/sunos.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import posix def generate(env): posix.generate(env) # Based on sunSparc 8:32bit # ARG_MAX=1048320 - 3000 for environment expansion env['MAXLINELENGTH'] = 1045320 env['PKGINFO'] = 'pkginfo' env['PKGCHK'] = '/usr/sbin/pkgchk' env['ENV']['PATH'] = env['ENV']['PATH'] + ':/opt/SUNWspro/bin:/usr/ccs/bin' # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Platform.irix Platform-specific initialization for SGI IRIX systems. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Platform.Platform() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Platform/irix.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import posix def generate(env): posix.generate(env) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""engine.SCons.Platform.aix Platform-specific initialization for IBM AIX systems. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Platform.Platform() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Platform/aix.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os import posix def get_xlc(env, xlc=None, xlc_r=None, packages=[]): # Use the AIX package installer tool lslpp to figure out where a # given xl* compiler is installed and what version it is. xlcPath = None xlcVersion = None if xlc is None: xlc = env.get('CC', 'xlc') if xlc_r is None: xlc_r = xlc + '_r' for package in packages: cmd = "lslpp -fc " + package + " 2>/dev/null | egrep '" + xlc + "([^-_a-zA-Z0-9].*)?$'" line = os.popen(cmd).readline() if line: v, p = line.split(':')[1:3] xlcVersion = v.split()[1] xlcPath = p.split()[0] xlcPath = xlcPath[:xlcPath.rindex('/')] break return (xlcPath, xlc, xlc_r, xlcVersion) def generate(env): posix.generate(env) #Based on AIX 5.2: ARG_MAX=24576 - 3000 for environment expansion env['MAXLINELENGTH'] = 21576 # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # """SCons.Warnings This file implements the warnings framework for SCons. """ __revision__ = "src/engine/SCons/Warnings.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import sys import SCons.Errors class Warning(SCons.Errors.UserError): pass class WarningOnByDefault(Warning): pass # NOTE: If you add a new warning class, add it to the man page, too! class CacheWriteErrorWarning(Warning): pass class CorruptSConsignWarning(WarningOnByDefault): pass class DependencyWarning(Warning): pass class DuplicateEnvironmentWarning(WarningOnByDefault): pass class FutureReservedVariableWarning(WarningOnByDefault): pass class LinkWarning(WarningOnByDefault): pass class MisleadingKeywordsWarning(WarningOnByDefault): pass class MissingSConscriptWarning(WarningOnByDefault): pass class NoMD5ModuleWarning(WarningOnByDefault): pass class NoMetaclassSupportWarning(WarningOnByDefault): pass class NoObjectCountWarning(WarningOnByDefault): pass class NoParallelSupportWarning(WarningOnByDefault): pass class ReservedVariableWarning(WarningOnByDefault): pass class StackSizeWarning(WarningOnByDefault): pass class VisualCMissingWarning(WarningOnByDefault): pass # Used when MSVC_VERSION and MSVS_VERSION do not point to the # same version (MSVS_VERSION is deprecated) class VisualVersionMismatch(WarningOnByDefault): pass class VisualStudioMissingWarning(Warning): pass class FortranCxxMixWarning(LinkWarning): pass # Deprecation warnings class FutureDeprecatedWarning(Warning): pass class DeprecatedWarning(Warning): pass class MandatoryDeprecatedWarning(DeprecatedWarning): pass # Special case; base always stays DeprecatedWarning class PythonVersionWarning(DeprecatedWarning): pass class DeprecatedSourceCodeWarning(FutureDeprecatedWarning): pass class DeprecatedBuildDirWarning(DeprecatedWarning): pass class TaskmasterNeedsExecuteWarning(DeprecatedWarning): pass class DeprecatedCopyWarning(MandatoryDeprecatedWarning): pass class DeprecatedOptionsWarning(MandatoryDeprecatedWarning): pass class DeprecatedSourceSignaturesWarning(MandatoryDeprecatedWarning): pass class DeprecatedTargetSignaturesWarning(MandatoryDeprecatedWarning): pass class DeprecatedDebugOptionsWarning(MandatoryDeprecatedWarning): pass class DeprecatedSigModuleWarning(MandatoryDeprecatedWarning): pass class DeprecatedBuilderKeywordsWarning(MandatoryDeprecatedWarning): pass # The below is a list of 2-tuples. The first element is a class object. # The second element is true if that class is enabled, false if it is disabled. _enabled = [] # If set, raise the warning as an exception _warningAsException = 0 # If not None, a function to call with the warning _warningOut = None def suppressWarningClass(clazz): """Suppresses all warnings that are of type clazz or derived from clazz.""" _enabled.insert(0, (clazz, 0)) def enableWarningClass(clazz): """Enables all warnings that are of type clazz or derived from clazz.""" _enabled.insert(0, (clazz, 1)) def warningAsException(flag=1): """Turn warnings into exceptions. Returns the old value of the flag.""" global _warningAsException old = _warningAsException _warningAsException = flag return old def warn(clazz, *args): global _enabled, _warningAsException, _warningOut warning = clazz(args) for clazz, flag in _enabled: if isinstance(warning, clazz): if flag: if _warningAsException: raise warning if _warningOut: _warningOut(warning) break def process_warn_strings(arguments): """Process string specifications of enabling/disabling warnings, as passed to the --warn option or the SetOption('warn') function. An argument to this option should be of the form <warning-class> or no-<warning-class>. The warning class is munged in order to get an actual class name from the classes above, which we need to pass to the {enable,disable}WarningClass() functions. The supplied <warning-class> is split on hyphens, each element is capitalized, then smushed back together. Then the string "Warning" is appended to get the class name. For example, 'deprecated' will enable the DeprecatedWarning class. 'no-dependency' will disable the DependencyWarning class. As a special case, --warn=all and --warn=no-all will enable or disable (respectively) the base Warning class of all warnings. """ def _capitalize(s): if s[:5] == "scons": return "SCons" + s[5:] else: return s.capitalize() for arg in arguments: elems = arg.lower().split('-') enable = 1 if elems[0] == 'no': enable = 0 del elems[0] if len(elems) == 1 and elems[0] == 'all': class_name = "Warning" else: class_name = ''.join(map(_capitalize, elems)) + "Warning" try: clazz = globals()[class_name] except KeyError: sys.stderr.write("No warning type: '%s'\n" % arg) else: if enable: enableWarningClass(clazz) elif issubclass(clazz, MandatoryDeprecatedWarning): fmt = "Can not disable mandataory warning: '%s'\n" sys.stderr.write(fmt % arg) else: suppressWarningClass(clazz) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Scanner.LaTeX This module implements the dependency scanner for LaTeX code. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Scanner/LaTeX.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os.path import re import SCons.Scanner import SCons.Util # list of graphics file extensions for TeX and LaTeX TexGraphics = ['.eps', '.ps'] LatexGraphics = ['.pdf', '.png', '.jpg', '.gif', '.tif'] # Used as a return value of modify_env_var if the variable is not set. class _Null(object): pass _null = _Null # The user specifies the paths in env[variable], similar to other builders. # They may be relative and must be converted to absolute, as expected # by LaTeX and Co. The environment may already have some paths in # env['ENV'][var]. These paths are honored, but the env[var] paths have # higher precedence. All changes are un-done on exit. def modify_env_var(env, var, abspath): try: save = env['ENV'][var] except KeyError: save = _null env.PrependENVPath(var, abspath) try: if SCons.Util.is_List(env[var]): env.PrependENVPath(var, [os.path.abspath(str(p)) for p in env[var]]) else: # Split at os.pathsep to convert into absolute path env.PrependENVPath(var, [os.path.abspath(p) for p in str(env[var]).split(os.pathsep)]) except KeyError: pass # Convert into a string explicitly to append ":" (without which it won't search system # paths as well). The problem is that env.AppendENVPath(var, ":") # does not work, refuses to append ":" (os.pathsep). if SCons.Util.is_List(env['ENV'][var]): env['ENV'][var] = os.pathsep.join(env['ENV'][var]) # Append the trailing os.pathsep character here to catch the case with no env[var] env['ENV'][var] = env['ENV'][var] + os.pathsep return save class FindENVPathDirs(object): """A class to bind a specific *PATH variable name to a function that will return all of the *path directories.""" def __init__(self, variable): self.variable = variable def __call__(self, env, dir=None, target=None, source=None, argument=None): import SCons.PathList try: path = env['ENV'][self.variable] except KeyError: return () dir = dir or env.fs._cwd path = SCons.PathList.PathList(path).subst_path(env, target, source) return tuple(dir.Rfindalldirs(path)) def LaTeXScanner(): """Return a prototype Scanner instance for scanning LaTeX source files when built with latex. """ ds = LaTeX(name = "LaTeXScanner", suffixes = '$LATEXSUFFIXES', # in the search order, see below in LaTeX class docstring graphics_extensions = TexGraphics, recursive = 0) return ds def PDFLaTeXScanner(): """Return a prototype Scanner instance for scanning LaTeX source files when built with pdflatex. """ ds = LaTeX(name = "PDFLaTeXScanner", suffixes = '$LATEXSUFFIXES', # in the search order, see below in LaTeX class docstring graphics_extensions = LatexGraphics, recursive = 0) return ds class LaTeX(SCons.Scanner.Base): """Class for scanning LaTeX files for included files. Unlike most scanners, which use regular expressions that just return the included file name, this returns a tuple consisting of the keyword for the inclusion ("include", "includegraphics", "input", or "bibliography"), and then the file name itself. Based on a quick look at LaTeX documentation, it seems that we should append .tex suffix for the "include" keywords, append .tex if there is no extension for the "input" keyword, and need to add .bib for the "bibliography" keyword that does not accept extensions by itself. Finally, if there is no extension for an "includegraphics" keyword latex will append .ps or .eps to find the file, while pdftex may use .pdf, .jpg, .tif, .mps, or .png. The actual subset and search order may be altered by DeclareGraphicsExtensions command. This complication is ignored. The default order corresponds to experimentation with teTeX $ latex --version pdfeTeX 3.141592-1.21a-2.2 (Web2C 7.5.4) kpathsea version 3.5.4 The order is: ['.eps', '.ps'] for latex ['.png', '.pdf', '.jpg', '.tif']. Another difference is that the search path is determined by the type of the file being searched: env['TEXINPUTS'] for "input" and "include" keywords env['TEXINPUTS'] for "includegraphics" keyword env['TEXINPUTS'] for "lstinputlisting" keyword env['BIBINPUTS'] for "bibliography" keyword env['BSTINPUTS'] for "bibliographystyle" keyword env['INDEXSTYLE'] for "makeindex" keyword, no scanning support needed just allows user to set it if needed. FIXME: also look for the class or style in document[class|style]{} FIXME: also look for the argument of bibliographystyle{} """ keyword_paths = {'include': 'TEXINPUTS', 'input': 'TEXINPUTS', 'includegraphics': 'TEXINPUTS', 'bibliography': 'BIBINPUTS', 'bibliographystyle': 'BSTINPUTS', 'addbibresource': 'BIBINPUTS', 'addglobalbib': 'BIBINPUTS', 'addsectionbib': 'BIBINPUTS', 'makeindex': 'INDEXSTYLE', 'usepackage': 'TEXINPUTS', 'lstinputlisting': 'TEXINPUTS'} env_variables = SCons.Util.unique(list(keyword_paths.values())) def __init__(self, name, suffixes, graphics_extensions, *args, **kw): # We have to include \n with the % we exclude from the first part # part of the regex because the expression is compiled with re.M. # Without the \n, the ^ could match the beginning of a *previous* # line followed by one or more newline characters (i.e. blank # lines), interfering with a match on the next line. # add option for whitespace before the '[options]' or the '{filename}' regex = r'^[^%\n]*\\(include|includegraphics(?:\s*\[[^\]]+\])?|lstinputlisting(?:\[[^\]]+\])?|input|bibliography|addbibresource|addglobalbib|addsectionbib|usepackage)\s*{([^}]*)}' self.cre = re.compile(regex, re.M) self.comment_re = re.compile(r'^((?:(?:\\%)|[^%\n])*)(.*)$', re.M) self.graphics_extensions = graphics_extensions def _scan(node, env, path=(), self=self): node = node.rfile() if not node.exists(): return [] return self.scan_recurse(node, path) class FindMultiPathDirs(object): """The stock FindPathDirs function has the wrong granularity: it is called once per target, while we need the path that depends on what kind of included files is being searched. This wrapper hides multiple instances of FindPathDirs, one per the LaTeX path variable in the environment. When invoked, the function calculates and returns all the required paths as a dictionary (converted into a tuple to become hashable). Then the scan function converts it back and uses a dictionary of tuples rather than a single tuple of paths. """ def __init__(self, dictionary): self.dictionary = {} for k,n in dictionary.items(): self.dictionary[k] = ( SCons.Scanner.FindPathDirs(n), FindENVPathDirs(n) ) def __call__(self, env, dir=None, target=None, source=None, argument=None): di = {} for k,(c,cENV) in self.dictionary.items(): di[k] = ( c(env, dir=None, target=None, source=None, argument=None) , cENV(env, dir=None, target=None, source=None, argument=None) ) # To prevent "dict is not hashable error" return tuple(di.items()) class LaTeXScanCheck(object): """Skip all but LaTeX source files, i.e., do not scan *.eps, *.pdf, *.jpg, etc. """ def __init__(self, suffixes): self.suffixes = suffixes def __call__(self, node, env): current = not node.has_builder() or node.is_up_to_date() scannable = node.get_suffix() in env.subst_list(self.suffixes)[0] # Returning false means that the file is not scanned. return scannable and current kw['function'] = _scan kw['path_function'] = FindMultiPathDirs(LaTeX.keyword_paths) kw['recursive'] = 0 kw['skeys'] = suffixes kw['scan_check'] = LaTeXScanCheck(suffixes) kw['name'] = name SCons.Scanner.Base.__init__(self, *args, **kw) def _latex_names(self, include): filename = include[1] if include[0] == 'input': base, ext = os.path.splitext( filename ) if ext == "": return [filename + '.tex'] if (include[0] == 'include'): return [filename + '.tex'] if include[0] == 'bibliography': base, ext = os.path.splitext( filename ) if ext == "": return [filename + '.bib'] if include[0] == 'usepackage': base, ext = os.path.splitext( filename ) if ext == "": return [filename + '.sty'] if include[0] == 'includegraphics': base, ext = os.path.splitext( filename ) if ext == "": #return [filename+e for e in self.graphics_extensions + TexGraphics] # use the line above to find dependencies for the PDF builder # when only an .eps figure is present. Since it will be found # if the user tells scons how to make the pdf figure, leave # it out for now. return [filename+e for e in self.graphics_extensions] return [filename] def sort_key(self, include): return SCons.Node.FS._my_normcase(str(include)) def find_include(self, include, source_dir, path): try: sub_path = path[include[0]] except (IndexError, KeyError): sub_path = () try_names = self._latex_names(include) for n in try_names: # see if we find it using the path in env[var] i = SCons.Node.FS.find_file(n, (source_dir,) + sub_path[0]) if i: return i, include # see if we find it using the path in env['ENV'][var] i = SCons.Node.FS.find_file(n, (source_dir,) + sub_path[1]) if i: return i, include return i, include def canonical_text(self, text): """Standardize an input TeX-file contents. Currently: * removes comments, unwrapping comment-wrapped lines. """ out = [] line_continues_a_comment = False for line in text.splitlines(): line,comment = self.comment_re.findall(line)[0] if line_continues_a_comment == True: out[-1] = out[-1] + line.lstrip() else: out.append(line) line_continues_a_comment = len(comment) > 0 return '\n'.join(out).rstrip()+'\n' def scan(self, node): # Modify the default scan function to allow for the regular # expression to return a comma separated list of file names # as can be the case with the bibliography keyword. # Cache the includes list in node so we only scan it once: # path_dict = dict(list(path)) # add option for whitespace (\s) before the '[' noopt_cre = re.compile('\s*\[.*$') if node.includes != None: includes = node.includes else: text = self.canonical_text(node.get_text_contents()) includes = self.cre.findall(text) # 1. Split comma-separated lines, e.g. # ('bibliography', 'phys,comp') # should become two entries # ('bibliography', 'phys') # ('bibliography', 'comp') # 2. Remove the options, e.g., such as # ('includegraphics[clip,width=0.7\\linewidth]', 'picture.eps') # should become # ('includegraphics', 'picture.eps') split_includes = [] for include in includes: inc_type = noopt_cre.sub('', include[0]) inc_list = include[1].split(',') for j in range(len(inc_list)): split_includes.append( (inc_type, inc_list[j]) ) # includes = split_includes node.includes = includes return includes def scan_recurse(self, node, path=()): """ do a recursive scan of the top level target file This lets us search for included files based on the directory of the main file just as latex does""" path_dict = dict(list(path)) queue = [] queue.extend( self.scan(node) ) seen = {} # This is a hand-coded DSU (decorate-sort-undecorate, or # Schwartzian transform) pattern. The sort key is the raw name # of the file as specifed on the \include, \input, etc. line. # TODO: what about the comment in the original Classic scanner: # """which lets # us keep the sort order constant regardless of whether the file # is actually found in a Repository or locally.""" nodes = [] source_dir = node.get_dir() #for include in includes: while queue: include = queue.pop() try: if seen[include[1]] == 1: continue except KeyError: seen[include[1]] = 1 # # Handle multiple filenames in include[1] # n, i = self.find_include(include, source_dir, path_dict) if n is None: # Do not bother with 'usepackage' warnings, as they most # likely refer to system-level files if include[0] != 'usepackage': SCons.Warnings.warn(SCons.Warnings.DependencyWarning, "No dependency generated for file: %s (included from: %s) -- file not found" % (i, node)) else: sortkey = self.sort_key(n) nodes.append((sortkey, n)) # recurse down queue.extend( self.scan(n) ) return [pair[1] for pair in sorted(nodes)] # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Scanner.RC This module implements the depenency scanner for RC (Interface Definition Language) files. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Scanner/RC.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Node.FS import SCons.Scanner import re def RCScan(): """Return a prototype Scanner instance for scanning RC source files""" res_re= r'^(?:\s*#\s*(?:include)|' \ '.*?\s+(?:ICON|BITMAP|CURSOR|HTML|FONT|MESSAGETABLE|TYPELIB|REGISTRY|D3DFX)' \ '\s*.*?)' \ '\s*(<|"| )([^>"\s]+)(?:[>"\s])*$' resScanner = SCons.Scanner.ClassicCPP( "ResourceScanner", "$RCSUFFIXES", "CPPPATH", res_re ) return resScanner # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Scanner/Prog.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Node import SCons.Node.FS import SCons.Scanner import SCons.Util # global, set by --debug=findlibs print_find_libs = None def ProgramScanner(**kw): """Return a prototype Scanner instance for scanning executable files for static-lib dependencies""" kw['path_function'] = SCons.Scanner.FindPathDirs('LIBPATH') ps = SCons.Scanner.Base(scan, "ProgramScanner", **kw) return ps def scan(node, env, libpath = ()): """ This scanner scans program files for static-library dependencies. It will search the LIBPATH environment variable for libraries specified in the LIBS variable, returning any files it finds as dependencies. """ try: libs = env['LIBS'] except KeyError: # There are no LIBS in this environment, so just return a null list: return [] if SCons.Util.is_String(libs): libs = libs.split() else: libs = SCons.Util.flatten(libs) try: prefix = env['LIBPREFIXES'] if not SCons.Util.is_List(prefix): prefix = [ prefix ] except KeyError: prefix = [ '' ] try: suffix = env['LIBSUFFIXES'] if not SCons.Util.is_List(suffix): suffix = [ suffix ] except KeyError: suffix = [ '' ] pairs = [] for suf in map(env.subst, suffix): for pref in map(env.subst, prefix): pairs.append((pref, suf)) result = [] if callable(libpath): libpath = libpath() find_file = SCons.Node.FS.find_file adjustixes = SCons.Util.adjustixes for lib in libs: if SCons.Util.is_String(lib): lib = env.subst(lib) for pref, suf in pairs: l = adjustixes(lib, pref, suf) l = find_file(l, libpath, verbose=print_find_libs) if l: result.append(l) else: result.append(lib) return result # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Scanner.D Scanner for the Digital Mars "D" programming language. Coded by Andy Friesen 17 Nov 2003 """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Scanner/D.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import re import SCons.Scanner def DScanner(): """Return a prototype Scanner instance for scanning D source files""" ds = D() return ds class D(SCons.Scanner.Classic): def __init__ (self): SCons.Scanner.Classic.__init__ (self, name = "DScanner", suffixes = '$DSUFFIXES', path_variable = 'DPATH', regex = 'import\s+(?:[a-zA-Z0-9_.]+)\s*(?:,\s*(?:[a-zA-Z0-9_.]+)\s*)*;') self.cre2 = re.compile ('(?:import\s)?\s*([a-zA-Z0-9_.]+)\s*(?:,|;)', re.M) def find_include(self, include, source_dir, path): # translate dots (package separators) to slashes inc = include.replace('.', '/') i = SCons.Node.FS.find_file(inc + '.d', (source_dir,) + path) if i is None: i = SCons.Node.FS.find_file (inc + '.di', (source_dir,) + path) return i, include def find_include_names(self, node): includes = [] for i in self.cre.findall(node.get_text_contents()): includes = includes + self.cre2.findall(i) return includes # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Scanner.C This module implements the depenency scanner for C/C++ code. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Scanner/C.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Node.FS import SCons.Scanner import SCons.Util import SCons.cpp class SConsCPPScanner(SCons.cpp.PreProcessor): """ SCons-specific subclass of the cpp.py module's processing. We subclass this so that: 1) we can deal with files represented by Nodes, not strings; 2) we can keep track of the files that are missing. """ def __init__(self, *args, **kw): SCons.cpp.PreProcessor.__init__(self, *args, **kw) self.missing = [] def initialize_result(self, fname): self.result = SCons.Util.UniqueList([fname]) def finalize_result(self, fname): return self.result[1:] def find_include_file(self, t): keyword, quote, fname = t result = SCons.Node.FS.find_file(fname, self.searchpath[quote]) if not result: self.missing.append((fname, self.current_file)) return result def read_file(self, file): try: fp = open(str(file.rfile())) except EnvironmentError, e: self.missing.append((file, self.current_file)) return '' else: return fp.read() def dictify_CPPDEFINES(env): cppdefines = env.get('CPPDEFINES', {}) if cppdefines is None: return {} if SCons.Util.is_Sequence(cppdefines): result = {} for c in cppdefines: if SCons.Util.is_Sequence(c): result[c[0]] = c[1] else: result[c] = None return result if not SCons.Util.is_Dict(cppdefines): return {cppdefines : None} return cppdefines class SConsCPPScannerWrapper(object): """ The SCons wrapper around a cpp.py scanner. This is the actual glue between the calling conventions of generic SCons scanners, and the (subclass of) cpp.py class that knows how to look for #include lines with reasonably real C-preprocessor-like evaluation of #if/#ifdef/#else/#elif lines. """ def __init__(self, name, variable): self.name = name self.path = SCons.Scanner.FindPathDirs(variable) def __call__(self, node, env, path = ()): cpp = SConsCPPScanner(current = node.get_dir(), cpppath = path, dict = dictify_CPPDEFINES(env)) result = cpp(node) for included, includer in cpp.missing: fmt = "No dependency generated for file: %s (included from: %s) -- file not found" SCons.Warnings.warn(SCons.Warnings.DependencyWarning, fmt % (included, includer)) return result def recurse_nodes(self, nodes): return nodes def select(self, node): return self def CScanner(): """Return a prototype Scanner instance for scanning source files that use the C pre-processor""" # Here's how we would (or might) use the CPP scanner code above that # knows how to evaluate #if/#ifdef/#else/#elif lines when searching # for #includes. This is commented out for now until we add the # right configurability to let users pick between the scanners. #return SConsCPPScannerWrapper("CScanner", "CPPPATH") cs = SCons.Scanner.ClassicCPP("CScanner", "$CPPSUFFIXES", "CPPPATH", '^[ \t]*#[ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")') return cs # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Scanner.IDL This module implements the depenency scanner for IDL (Interface Definition Language) files. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Scanner/IDL.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Node.FS import SCons.Scanner def IDLScan(): """Return a prototype Scanner instance for scanning IDL source files""" cs = SCons.Scanner.ClassicCPP("IDLScan", "$IDLSUFFIXES", "CPPPATH", '^[ \t]*(?:#[ \t]*include|[ \t]*import)[ \t]+(<|")([^>"]+)(>|")') return cs # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Scanner.Fortran This module implements the dependency scanner for Fortran code. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. __revision__ = "src/engine/SCons/Scanner/Fortran.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import re import SCons.Node import SCons.Node.FS import SCons.Scanner import SCons.Util import SCons.Warnings class F90Scanner(SCons.Scanner.Classic): """ A Classic Scanner subclass for Fortran source files which takes into account both USE and INCLUDE statements. This scanner will work for both F77 and F90 (and beyond) compilers. Currently, this scanner assumes that the include files do not contain USE statements. To enable the ability to deal with USE statements in include files, add logic right after the module names are found to loop over each include file, search for and locate each USE statement, and append each module name to the list of dependencies. Caching the search results in a common dictionary somewhere so that the same include file is not searched multiple times would be a smart thing to do. """ def __init__(self, name, suffixes, path_variable, use_regex, incl_regex, def_regex, *args, **kw): self.cre_use = re.compile(use_regex, re.M) self.cre_incl = re.compile(incl_regex, re.M) self.cre_def = re.compile(def_regex, re.M) def _scan(node, env, path, self=self): node = node.rfile() if not node.exists(): return [] return self.scan(node, env, path) kw['function'] = _scan kw['path_function'] = SCons.Scanner.FindPathDirs(path_variable) kw['recursive'] = 1 kw['skeys'] = suffixes kw['name'] = name SCons.Scanner.Current.__init__(self, *args, **kw) def scan(self, node, env, path=()): # cache the includes list in node so we only scan it once: if node.includes != None: mods_and_includes = node.includes else: # retrieve all included filenames includes = self.cre_incl.findall(node.get_text_contents()) # retrieve all USE'd module names modules = self.cre_use.findall(node.get_text_contents()) # retrieve all defined module names defmodules = self.cre_def.findall(node.get_text_contents()) # Remove all USE'd module names that are defined in the same file # (case-insensitively) d = {} for m in defmodules: d[m.lower()] = 1 modules = [m for m in modules if m.lower() not in d] # Convert module name to a .mod filename suffix = env.subst('$FORTRANMODSUFFIX') modules = [x.lower() + suffix for x in modules] # Remove unique items from the list mods_and_includes = SCons.Util.unique(includes+modules) node.includes = mods_and_includes # This is a hand-coded DSU (decorate-sort-undecorate, or # Schwartzian transform) pattern. The sort key is the raw name # of the file as specifed on the USE or INCLUDE line, which lets # us keep the sort order constant regardless of whether the file # is actually found in a Repository or locally. nodes = [] source_dir = node.get_dir() if callable(path): path = path() for dep in mods_and_includes: n, i = self.find_include(dep, source_dir, path) if n is None: SCons.Warnings.warn(SCons.Warnings.DependencyWarning, "No dependency generated for file: %s (referenced by: %s) -- file not found" % (i, node)) else: sortkey = self.sort_key(dep) nodes.append((sortkey, n)) return [pair[1] for pair in sorted(nodes)] def FortranScan(path_variable="FORTRANPATH"): """Return a prototype Scanner instance for scanning source files for Fortran USE & INCLUDE statements""" # The USE statement regex matches the following: # # USE module_name # USE :: module_name # USE, INTRINSIC :: module_name # USE, NON_INTRINSIC :: module_name # # Limitations # # -- While the regex can handle multiple USE statements on one line, # it cannot properly handle them if they are commented out. # In either of the following cases: # # ! USE mod_a ; USE mod_b [entire line is commented out] # USE mod_a ! ; USE mod_b [in-line comment of second USE statement] # # the second module name (mod_b) will be picked up as a dependency # even though it should be ignored. The only way I can see # to rectify this would be to modify the scanner to eliminate # the call to re.findall, read in the contents of the file, # treating the comment character as an end-of-line character # in addition to the normal linefeed, loop over each line, # weeding out the comments, and looking for the USE statements. # One advantage to this is that the regex passed to the scanner # would no longer need to match a semicolon. # # -- I question whether or not we need to detect dependencies to # INTRINSIC modules because these are built-in to the compiler. # If we consider them a dependency, will SCons look for them, not # find them, and kill the build? Or will we there be standard # compiler-specific directories we will need to point to so the # compiler and SCons can locate the proper object and mod files? # Here is a breakdown of the regex: # # (?i) : regex is case insensitive # ^ : start of line # (?: : group a collection of regex symbols without saving the match as a "group" # ^|; : matches either the start of the line or a semicolon - semicolon # ) : end the unsaved grouping # \s* : any amount of white space # USE : match the string USE, case insensitive # (?: : group a collection of regex symbols without saving the match as a "group" # \s+| : match one or more whitespace OR .... (the next entire grouped set of regex symbols) # (?: : group a collection of regex symbols without saving the match as a "group" # (?: : establish another unsaved grouping of regex symbols # \s* : any amount of white space # , : match a comma # \s* : any amount of white space # (?:NON_)? : optionally match the prefix NON_, case insensitive # INTRINSIC : match the string INTRINSIC, case insensitive # )? : optionally match the ", INTRINSIC/NON_INTRINSIC" grouped expression # \s* : any amount of white space # :: : match a double colon that must appear after the INTRINSIC/NON_INTRINSIC attribute # ) : end the unsaved grouping # ) : end the unsaved grouping # \s* : match any amount of white space # (\w+) : match the module name that is being USE'd # # use_regex = "(?i)(?:^|;)\s*USE(?:\s+|(?:(?:\s*,\s*(?:NON_)?INTRINSIC)?\s*::))\s*(\w+)" # The INCLUDE statement regex matches the following: # # INCLUDE 'some_Text' # INCLUDE "some_Text" # INCLUDE "some_Text" ; INCLUDE "some_Text" # INCLUDE kind_"some_Text" # INCLUDE kind_'some_Text" # # where some_Text can include any alphanumeric and/or special character # as defined by the Fortran 2003 standard. # # Limitations: # # -- The Fortran standard dictates that a " or ' in the INCLUDE'd # string must be represented as a "" or '', if the quotes that wrap # the entire string are either a ' or ", respectively. While the # regular expression below can detect the ' or " characters just fine, # the scanning logic, presently is unable to detect them and reduce # them to a single instance. This probably isn't an issue since, # in practice, ' or " are not generally used in filenames. # # -- This regex will not properly deal with multiple INCLUDE statements # when the entire line has been commented out, ala # # ! INCLUDE 'some_file' ; INCLUDE 'some_file' # # In such cases, it will properly ignore the first INCLUDE file, # but will actually still pick up the second. Interestingly enough, # the regex will properly deal with these cases: # # INCLUDE 'some_file' # INCLUDE 'some_file' !; INCLUDE 'some_file' # # To get around the above limitation, the FORTRAN programmer could # simply comment each INCLUDE statement separately, like this # # ! INCLUDE 'some_file' !; INCLUDE 'some_file' # # The way I see it, the only way to get around this limitation would # be to modify the scanning logic to replace the calls to re.findall # with a custom loop that processes each line separately, throwing # away fully commented out lines before attempting to match against # the INCLUDE syntax. # # Here is a breakdown of the regex: # # (?i) : regex is case insensitive # (?: : begin a non-saving group that matches the following: # ^ : either the start of the line # | : or # ['">]\s*; : a semicolon that follows a single quote, # double quote or greater than symbol (with any # amount of whitespace in between). This will # allow the regex to match multiple INCLUDE # statements per line (although it also requires # the positive lookahead assertion that is # used below). It will even properly deal with # (i.e. ignore) cases in which the additional # INCLUDES are part of an in-line comment, ala # " INCLUDE 'someFile' ! ; INCLUDE 'someFile2' " # ) : end of non-saving group # \s* : any amount of white space # INCLUDE : match the string INCLUDE, case insensitive # \s+ : match one or more white space characters # (?\w+_)? : match the optional "kind-param _" prefix allowed by the standard # [<"'] : match the include delimiter - an apostrophe, double quote, or less than symbol # (.+?) : match one or more characters that make up # the included path and file name and save it # in a group. The Fortran standard allows for # any non-control character to be used. The dot # operator will pick up any character, including # control codes, but I can't conceive of anyone # putting control codes in their file names. # The question mark indicates it is non-greedy so # that regex will match only up to the next quote, # double quote, or greater than symbol # (?=["'>]) : positive lookahead assertion to match the include # delimiter - an apostrophe, double quote, or # greater than symbol. This level of complexity # is required so that the include delimiter is # not consumed by the match, thus allowing the # sub-regex discussed above to uniquely match a # set of semicolon-separated INCLUDE statements # (as allowed by the F2003 standard) include_regex = """(?i)(?:^|['">]\s*;)\s*INCLUDE\s+(?:\w+_)?[<"'](.+?)(?=["'>])""" # The MODULE statement regex finds module definitions by matching # the following: # # MODULE module_name # # but *not* the following: # # MODULE PROCEDURE procedure_name # # Here is a breakdown of the regex: # # (?i) : regex is case insensitive # ^\s* : any amount of white space # MODULE : match the string MODULE, case insensitive # \s+ : match one or more white space characters # (?!PROCEDURE) : but *don't* match if the next word matches # PROCEDURE (negative lookahead assertion), # case insensitive # (\w+) : match one or more alphanumeric characters # that make up the defined module name and # save it in a group def_regex = """(?i)^\s*MODULE\s+(?!PROCEDURE)(\w+)""" scanner = F90Scanner("FortranScan", "$FORTRANSUFFIXES", path_variable, use_regex, include_regex, def_regex) return scanner # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Scanner The Scanner package for the SCons software construction utility. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Scanner/__init__.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import re import SCons.Node.FS import SCons.Util class _Null(object): pass # This is used instead of None as a default argument value so None can be # used as an actual argument value. _null = _Null def Scanner(function, *args, **kw): """ Public interface factory function for creating different types of Scanners based on the different types of "functions" that may be supplied. TODO: Deprecate this some day. We've moved the functionality inside the Base class and really don't need this factory function any more. It was, however, used by some of our Tool modules, so the call probably ended up in various people's custom modules patterned on SCons code. """ if SCons.Util.is_Dict(function): return Selector(function, *args, **kw) else: return Base(function, *args, **kw) class FindPathDirs(object): """A class to bind a specific *PATH variable name to a function that will return all of the *path directories.""" def __init__(self, variable): self.variable = variable def __call__(self, env, dir=None, target=None, source=None, argument=None): import SCons.PathList try: path = env[self.variable] except KeyError: return () dir = dir or env.fs._cwd path = SCons.PathList.PathList(path).subst_path(env, target, source) return tuple(dir.Rfindalldirs(path)) class Base(object): """ The base class for dependency scanners. This implements straightforward, single-pass scanning of a single file. """ def __init__(self, function, name = "NONE", argument = _null, skeys = _null, path_function = None, # Node.FS.Base so that, by default, it's okay for a # scanner to return a Dir, File or Entry. node_class = SCons.Node.FS.Base, node_factory = None, scan_check = None, recursive = None): """ Construct a new scanner object given a scanner function. 'function' - a scanner function taking two or three arguments and returning a list of strings. 'name' - a name for identifying this scanner object. 'argument' - an optional argument that, if specified, will be passed to both the scanner function and the path_function. 'skeys' - an optional list argument that can be used to determine which scanner should be used for a given Node. In the case of File nodes, for example, the 'skeys' would be file suffixes. 'path_function' - a function that takes four or five arguments (a construction environment, Node for the directory containing the SConscript file that defined the primary target, list of target nodes, list of source nodes, and optional argument for this instance) and returns a tuple of the directories that can be searched for implicit dependency files. May also return a callable() which is called with no args and returns the tuple (supporting Bindable class). 'node_class' - the class of Nodes which this scan will return. If node_class is None, then this scanner will not enforce any Node conversion and will return the raw results from the underlying scanner function. 'node_factory' - the factory function to be called to translate the raw results returned by the scanner function into the expected node_class objects. 'scan_check' - a function to be called to first check whether this node really needs to be scanned. 'recursive' - specifies that this scanner should be invoked recursively on all of the implicit dependencies it returns (the canonical example being #include lines in C source files). May be a callable, which will be called to filter the list of nodes found to select a subset for recursive scanning (the canonical example being only recursively scanning subdirectories within a directory). The scanner function's first argument will be a Node that should be scanned for dependencies, the second argument will be an Environment object, the third argument will be the tuple of paths returned by the path_function, and the fourth argument will be the value passed into 'argument', and the returned list should contain the Nodes for all the direct dependencies of the file. Examples: s = Scanner(my_scanner_function) s = Scanner(function = my_scanner_function) s = Scanner(function = my_scanner_function, argument = 'foo') """ # Note: this class could easily work with scanner functions that take # something other than a filename as an argument (e.g. a database # node) and a dependencies list that aren't file names. All that # would need to be changed is the documentation. self.function = function self.path_function = path_function self.name = name self.argument = argument if skeys is _null: if SCons.Util.is_Dict(function): skeys = list(function.keys()) else: skeys = [] self.skeys = skeys self.node_class = node_class self.node_factory = node_factory self.scan_check = scan_check if callable(recursive): self.recurse_nodes = recursive elif recursive: self.recurse_nodes = self._recurse_all_nodes else: self.recurse_nodes = self._recurse_no_nodes def path(self, env, dir=None, target=None, source=None): if not self.path_function: return () if not self.argument is _null: return self.path_function(env, dir, target, source, self.argument) else: return self.path_function(env, dir, target, source) def __call__(self, node, env, path = ()): """ This method scans a single object. 'node' is the node that will be passed to the scanner function, and 'env' is the environment that will be passed to the scanner function. A list of direct dependency nodes for the specified node will be returned. """ if self.scan_check and not self.scan_check(node, env): return [] self = self.select(node) if not self.argument is _null: list = self.function(node, env, path, self.argument) else: list = self.function(node, env, path) kw = {} if hasattr(node, 'dir'): kw['directory'] = node.dir node_factory = env.get_factory(self.node_factory) nodes = [] for l in list: if self.node_class and not isinstance(l, self.node_class): l = node_factory(l, **kw) nodes.append(l) return nodes def __cmp__(self, other): try: return cmp(self.__dict__, other.__dict__) except AttributeError: # other probably doesn't have a __dict__ return cmp(self.__dict__, other) def __hash__(self): return id(self) def __str__(self): return self.name def add_skey(self, skey): """Add a skey to the list of skeys""" self.skeys.append(skey) def get_skeys(self, env=None): if env and SCons.Util.is_String(self.skeys): return env.subst_list(self.skeys)[0] return self.skeys def select(self, node): if SCons.Util.is_Dict(self.function): key = node.scanner_key() try: return self.function[key] except KeyError: return None else: return self def _recurse_all_nodes(self, nodes): return nodes def _recurse_no_nodes(self, nodes): return [] recurse_nodes = _recurse_no_nodes def add_scanner(self, skey, scanner): self.function[skey] = scanner self.add_skey(skey) class Selector(Base): """ A class for selecting a more specific scanner based on the scanner_key() (suffix) for a specific Node. TODO: This functionality has been moved into the inner workings of the Base class, and this class will be deprecated at some point. (It was never exposed directly as part of the public interface, although it is used by the Scanner() factory function that was used by various Tool modules and therefore was likely a template for custom modules that may be out there.) """ def __init__(self, dict, *args, **kw): Base.__init__(self, None, *args, **kw) self.dict = dict self.skeys = list(dict.keys()) def __call__(self, node, env, path = ()): return self.select(node)(node, env, path) def select(self, node): try: return self.dict[node.scanner_key()] except KeyError: return None def add_scanner(self, skey, scanner): self.dict[skey] = scanner self.add_skey(skey) class Current(Base): """ A class for scanning files that are source files (have no builder) or are derived files and are current (which implies that they exist, either locally or in a repository). """ def __init__(self, *args, **kw): def current_check(node, env): return not node.has_builder() or node.is_up_to_date() kw['scan_check'] = current_check Base.__init__(self, *args, **kw) class Classic(Current): """ A Scanner subclass to contain the common logic for classic CPP-style include scanning, but which can be customized to use different regular expressions to find the includes. Note that in order for this to work "out of the box" (without overriding the find_include() and sort_key() methods), the regular expression passed to the constructor must return the name of the include file in group 0. """ def __init__(self, name, suffixes, path_variable, regex, *args, **kw): self.cre = re.compile(regex, re.M) def _scan(node, env, path=(), self=self): node = node.rfile() if not node.exists(): return [] return self.scan(node, path) kw['function'] = _scan kw['path_function'] = FindPathDirs(path_variable) kw['recursive'] = 1 kw['skeys'] = suffixes kw['name'] = name Current.__init__(self, *args, **kw) def find_include(self, include, source_dir, path): n = SCons.Node.FS.find_file(include, (source_dir,) + tuple(path)) return n, include def sort_key(self, include): return SCons.Node.FS._my_normcase(include) def find_include_names(self, node): return self.cre.findall(node.get_text_contents()) def scan(self, node, path=()): # cache the includes list in node so we only scan it once: if node.includes is not None: includes = node.includes else: includes = self.find_include_names (node) # Intern the names of the include files. Saves some memory # if the same header is included many times. node.includes = list(map(SCons.Util.silent_intern, includes)) # This is a hand-coded DSU (decorate-sort-undecorate, or # Schwartzian transform) pattern. The sort key is the raw name # of the file as specifed on the #include line (including the # " or <, since that may affect what file is found), which lets # us keep the sort order constant regardless of whether the file # is actually found in a Repository or locally. nodes = [] source_dir = node.get_dir() if callable(path): path = path() for include in includes: n, i = self.find_include(include, source_dir, path) if n is None: SCons.Warnings.warn(SCons.Warnings.DependencyWarning, "No dependency generated for file: %s (included from: %s) -- file not found" % (i, node)) else: nodes.append((self.sort_key(include), n)) return [pair[1] for pair in sorted(nodes)] class ClassicCPP(Classic): """ A Classic Scanner subclass which takes into account the type of bracketing used to include the file, and uses classic CPP rules for searching for the files based on the bracketing. Note that in order for this to work, the regular expression passed to the constructor must return the leading bracket in group 0, and the contained filename in group 1. """ def find_include(self, include, source_dir, path): if include[0] == '"': paths = (source_dir,) + tuple(path) else: paths = tuple(path) + (source_dir,) n = SCons.Node.FS.find_file(include[1], paths) i = SCons.Util.silent_intern(include[1]) return n, i def sort_key(self, include): return SCons.Node.FS._my_normcase(' '.join(include)) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. __revision__ = "src/engine/SCons/Scanner/Dir.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Node.FS import SCons.Scanner def only_dirs(nodes): is_Dir = lambda n: isinstance(n.disambiguate(), SCons.Node.FS.Dir) return list(filter(is_Dir, nodes)) def DirScanner(**kw): """Return a prototype Scanner instance for scanning directories for on-disk files""" kw['node_factory'] = SCons.Node.FS.Entry kw['recursive'] = only_dirs return SCons.Scanner.Base(scan_on_disk, "DirScanner", **kw) def DirEntryScanner(**kw): """Return a prototype Scanner instance for "scanning" directory Nodes for their in-memory entries""" kw['node_factory'] = SCons.Node.FS.Entry kw['recursive'] = None return SCons.Scanner.Base(scan_in_memory, "DirEntryScanner", **kw) skip_entry = {} skip_entry_list = [ '.', '..', '.sconsign', # Used by the native dblite.py module. '.sconsign.dblite', # Used by dbm and dumbdbm. '.sconsign.dir', # Used by dbm. '.sconsign.pag', # Used by dumbdbm. '.sconsign.dat', '.sconsign.bak', # Used by some dbm emulations using Berkeley DB. '.sconsign.db', ] for skip in skip_entry_list: skip_entry[skip] = 1 skip_entry[SCons.Node.FS._my_normcase(skip)] = 1 do_not_scan = lambda k: k not in skip_entry def scan_on_disk(node, env, path=()): """ Scans a directory for on-disk files and directories therein. Looking up the entries will add these to the in-memory Node tree representation of the file system, so all we have to do is just that and then call the in-memory scanning function. """ try: flist = node.fs.listdir(node.abspath) except (IOError, OSError): return [] e = node.Entry for f in filter(do_not_scan, flist): # Add ./ to the beginning of the file name so if it begins with a # '#' we don't look it up relative to the top-level directory. e('./' + f) return scan_in_memory(node, env, path) def scan_in_memory(node, env, path=()): """ "Scans" a Node.FS.Dir for its in-memory entries. """ try: entries = node.entries except AttributeError: # It's not a Node.FS.Dir (or doesn't look enough like one for # our purposes), which can happen if a target list containing # mixed Node types (Dirs and Files, for example) has a Dir as # the first entry. return [] entry_list = sorted(filter(do_not_scan, list(entries.keys()))) return [entries[n] for n in entry_list] # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Util Various utility functions go here. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. __revision__ = "src/engine/SCons/Util.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os import sys import copy import re import types from collections import UserDict, UserList, UserString # Don't "from types import ..." these because we need to get at the # types module later to look for UnicodeType. InstanceType = types.InstanceType MethodType = types.MethodType FunctionType = types.FunctionType try: unicode except NameError: UnicodeType = None else: UnicodeType = unicode def dictify(keys, values, result={}): for k, v in zip(keys, values): result[k] = v return result _altsep = os.altsep if _altsep is None and sys.platform == 'win32': # My ActivePython 2.0.1 doesn't set os.altsep! What gives? _altsep = '/' if _altsep: def rightmost_separator(path, sep): return max(path.rfind(sep), path.rfind(_altsep)) else: def rightmost_separator(path, sep): return path.rfind(sep) # First two from the Python Cookbook, just for completeness. # (Yeah, yeah, YAGNI...) def containsAny(str, set): """Check whether sequence str contains ANY of the items in set.""" for c in set: if c in str: return 1 return 0 def containsAll(str, set): """Check whether sequence str contains ALL of the items in set.""" for c in set: if c not in str: return 0 return 1 def containsOnly(str, set): """Check whether sequence str contains ONLY items in set.""" for c in str: if c not in set: return 0 return 1 def splitext(path): "Same as os.path.splitext() but faster." sep = rightmost_separator(path, os.sep) dot = path.rfind('.') # An ext is only real if it has at least one non-digit char if dot > sep and not containsOnly(path[dot:], "0123456789."): return path[:dot],path[dot:] else: return path,"" def updrive(path): """ Make the drive letter (if any) upper case. This is useful because Windows is inconsitent on the case of the drive letter, which can cause inconsistencies when calculating command signatures. """ drive, rest = os.path.splitdrive(path) if drive: path = drive.upper() + rest return path class NodeList(UserList): """This class is almost exactly like a regular list of Nodes (actually it can hold any object), with one important difference. If you try to get an attribute from this list, it will return that attribute from every item in the list. For example: >>> someList = NodeList([ ' foo ', ' bar ' ]) >>> someList.strip() [ 'foo', 'bar' ] """ def __nonzero__(self): return len(self.data) != 0 def __str__(self): return ' '.join(map(str, self.data)) def __iter__(self): return iter(self.data) def __call__(self, *args, **kwargs): result = [x(*args, **kwargs) for x in self.data] return self.__class__(result) def __getattr__(self, name): result = [getattr(x, name) for x in self.data] return self.__class__(result) _get_env_var = re.compile(r'^\$([_a-zA-Z]\w*|{[_a-zA-Z]\w*})$') def get_environment_var(varstr): """Given a string, first determine if it looks like a reference to a single environment variable, like "$FOO" or "${FOO}". If so, return that variable with no decorations ("FOO"). If not, return None.""" mo=_get_env_var.match(to_String(varstr)) if mo: var = mo.group(1) if var[0] == '{': return var[1:-1] else: return var else: return None class DisplayEngine(object): print_it = True def __call__(self, text, append_newline=1): if not self.print_it: return if append_newline: text = text + '\n' try: sys.stdout.write(unicode(text)) except IOError: # Stdout might be connected to a pipe that has been closed # by now. The most likely reason for the pipe being closed # is that the user has press ctrl-c. It this is the case, # then SCons is currently shutdown. We therefore ignore # IOError's here so that SCons can continue and shutdown # properly so that the .sconsign is correctly written # before SCons exits. pass def set_mode(self, mode): self.print_it = mode def render_tree(root, child_func, prune=0, margin=[0], visited={}): """ Render a tree of nodes into an ASCII tree view. root - the root node of the tree child_func - the function called to get the children of a node prune - don't visit the same node twice margin - the format of the left margin to use for children of root. 1 results in a pipe, and 0 results in no pipe. visited - a dictionary of visited nodes in the current branch if not prune, or in the whole tree if prune. """ rname = str(root) children = child_func(root) retval = "" for pipe in margin[:-1]: if pipe: retval = retval + "| " else: retval = retval + " " if rname in visited: return retval + "+-[" + rname + "]\n" retval = retval + "+-" + rname + "\n" if not prune: visited = copy.copy(visited) visited[rname] = 1 for i in range(len(children)): margin.append(i<len(children)-1) retval = retval + render_tree(children[i], child_func, prune, margin, visited ) margin.pop() return retval IDX = lambda N: N and 1 or 0 def print_tree(root, child_func, prune=0, showtags=0, margin=[0], visited={}): """ Print a tree of nodes. This is like render_tree, except it prints lines directly instead of creating a string representation in memory, so that huge trees can be printed. root - the root node of the tree child_func - the function called to get the children of a node prune - don't visit the same node twice showtags - print status information to the left of each node line margin - the format of the left margin to use for children of root. 1 results in a pipe, and 0 results in no pipe. visited - a dictionary of visited nodes in the current branch if not prune, or in the whole tree if prune. """ rname = str(root) if showtags: if showtags == 2: legend = (' E = exists\n' + ' R = exists in repository only\n' + ' b = implicit builder\n' + ' B = explicit builder\n' + ' S = side effect\n' + ' P = precious\n' + ' A = always build\n' + ' C = current\n' + ' N = no clean\n' + ' H = no cache\n' + '\n') sys.stdout.write(unicode(legend)) tags = ['['] tags.append(' E'[IDX(root.exists())]) tags.append(' R'[IDX(root.rexists() and not root.exists())]) tags.append(' BbB'[[0,1][IDX(root.has_explicit_builder())] + [0,2][IDX(root.has_builder())]]) tags.append(' S'[IDX(root.side_effect)]) tags.append(' P'[IDX(root.precious)]) tags.append(' A'[IDX(root.always_build)]) tags.append(' C'[IDX(root.is_up_to_date())]) tags.append(' N'[IDX(root.noclean)]) tags.append(' H'[IDX(root.nocache)]) tags.append(']') else: tags = [] def MMM(m): return [" ","| "][m] margins = list(map(MMM, margin[:-1])) children = child_func(root) if prune and rname in visited and children: sys.stdout.write(''.join(tags + margins + ['+-[', rname, ']']) + u'\n') return sys.stdout.write(''.join(tags + margins + ['+-', rname]) + u'\n') visited[rname] = 1 if children: margin.append(1) idx = IDX(showtags) for C in children[:-1]: print_tree(C, child_func, prune, idx, margin, visited) margin[-1] = 0 print_tree(children[-1], child_func, prune, idx, margin, visited) margin.pop() # Functions for deciding if things are like various types, mainly to # handle UserDict, UserList and UserString like their underlying types. # # Yes, all of this manual testing breaks polymorphism, and the real # Pythonic way to do all of this would be to just try it and handle the # exception, but handling the exception when it's not the right type is # often too slow. # We are using the following trick to speed up these # functions. Default arguments are used to take a snapshot of the # the global functions and constants used by these functions. This # transforms accesses to global variable into local variables # accesses (i.e. LOAD_FAST instead of LOAD_GLOBAL). DictTypes = (dict, UserDict) ListTypes = (list, UserList) SequenceTypes = (list, tuple, UserList) # Note that profiling data shows a speed-up when comparing # explicitely with str and unicode instead of simply comparing # with basestring. (at least on Python 2.5.1) StringTypes = (str, unicode, UserString) # Empirically, it is faster to check explicitely for str and # unicode than for basestring. BaseStringTypes = (str, unicode) def is_Dict(obj, isinstance=isinstance, DictTypes=DictTypes): return isinstance(obj, DictTypes) def is_List(obj, isinstance=isinstance, ListTypes=ListTypes): return isinstance(obj, ListTypes) def is_Sequence(obj, isinstance=isinstance, SequenceTypes=SequenceTypes): return isinstance(obj, SequenceTypes) def is_Tuple(obj, isinstance=isinstance, tuple=tuple): return isinstance(obj, tuple) def is_String(obj, isinstance=isinstance, StringTypes=StringTypes): return isinstance(obj, StringTypes) def is_Scalar(obj, isinstance=isinstance, StringTypes=StringTypes, SequenceTypes=SequenceTypes): # Profiling shows that there is an impressive speed-up of 2x # when explicitely checking for strings instead of just not # sequence when the argument (i.e. obj) is already a string. # But, if obj is a not string then it is twice as fast to # check only for 'not sequence'. The following code therefore # assumes that the obj argument is a string must of the time. return isinstance(obj, StringTypes) or not isinstance(obj, SequenceTypes) def do_flatten(sequence, result, isinstance=isinstance, StringTypes=StringTypes, SequenceTypes=SequenceTypes): for item in sequence: if isinstance(item, StringTypes) or not isinstance(item, SequenceTypes): result.append(item) else: do_flatten(item, result) def flatten(obj, isinstance=isinstance, StringTypes=StringTypes, SequenceTypes=SequenceTypes, do_flatten=do_flatten): """Flatten a sequence to a non-nested list. Flatten() converts either a single scalar or a nested sequence to a non-nested list. Note that flatten() considers strings to be scalars instead of sequences like Python would. """ if isinstance(obj, StringTypes) or not isinstance(obj, SequenceTypes): return [obj] result = [] for item in obj: if isinstance(item, StringTypes) or not isinstance(item, SequenceTypes): result.append(item) else: do_flatten(item, result) return result def flatten_sequence(sequence, isinstance=isinstance, StringTypes=StringTypes, SequenceTypes=SequenceTypes, do_flatten=do_flatten): """Flatten a sequence to a non-nested list. Same as flatten(), but it does not handle the single scalar case. This is slightly more efficient when one knows that the sequence to flatten can not be a scalar. """ result = [] for item in sequence: if isinstance(item, StringTypes) or not isinstance(item, SequenceTypes): result.append(item) else: do_flatten(item, result) return result # Generic convert-to-string functions that abstract away whether or # not the Python we're executing has Unicode support. The wrapper # to_String_for_signature() will use a for_signature() method if the # specified object has one. # def to_String(s, isinstance=isinstance, str=str, UserString=UserString, BaseStringTypes=BaseStringTypes): if isinstance(s,BaseStringTypes): # Early out when already a string! return s elif isinstance(s, UserString): # s.data can only be either a unicode or a regular # string. Please see the UserString initializer. return s.data else: return str(s) def to_String_for_subst(s, isinstance=isinstance, str=str, to_String=to_String, BaseStringTypes=BaseStringTypes, SequenceTypes=SequenceTypes, UserString=UserString): # Note that the test cases are sorted by order of probability. if isinstance(s, BaseStringTypes): return s elif isinstance(s, SequenceTypes): l = [] for e in s: l.append(to_String_for_subst(e)) return ' '.join( s ) elif isinstance(s, UserString): # s.data can only be either a unicode or a regular # string. Please see the UserString initializer. return s.data else: return str(s) def to_String_for_signature(obj, to_String_for_subst=to_String_for_subst, AttributeError=AttributeError): try: f = obj.for_signature except AttributeError: return to_String_for_subst(obj) else: return f() # The SCons "semi-deep" copy. # # This makes separate copies of lists (including UserList objects) # dictionaries (including UserDict objects) and tuples, but just copies # references to anything else it finds. # # A special case is any object that has a __semi_deepcopy__() method, # which we invoke to create the copy. Currently only used by # BuilderDict to actually prevent the copy operation (as invalid on that object) # # The dispatch table approach used here is a direct rip-off from the # normal Python copy module. _semi_deepcopy_dispatch = d = {} def semi_deepcopy_dict(x, exclude = [] ): copy = {} for key, val in x.items(): # The regular Python copy.deepcopy() also deepcopies the key, # as follows: # # copy[semi_deepcopy(key)] = semi_deepcopy(val) # # Doesn't seem like we need to, but we'll comment it just in case. if key not in exclude: copy[key] = semi_deepcopy(val) return copy d[dict] = semi_deepcopy_dict def _semi_deepcopy_list(x): return list(map(semi_deepcopy, x)) d[list] = _semi_deepcopy_list def _semi_deepcopy_tuple(x): return tuple(map(semi_deepcopy, x)) d[tuple] = _semi_deepcopy_tuple def semi_deepcopy(x): copier = _semi_deepcopy_dispatch.get(type(x)) if copier: return copier(x) else: if hasattr(x, '__semi_deepcopy__') and callable(x.__semi_deepcopy__): return x.__semi_deepcopy__() elif isinstance(x, UserDict): return x.__class__(semi_deepcopy_dict(x)) elif isinstance(x, UserList): return x.__class__(_semi_deepcopy_list(x)) return x class Proxy(object): """A simple generic Proxy class, forwarding all calls to subject. So, for the benefit of the python newbie, what does this really mean? Well, it means that you can take an object, let's call it 'objA', and wrap it in this Proxy class, with a statement like this proxyObj = Proxy(objA), Then, if in the future, you do something like this x = proxyObj.var1, since Proxy does not have a 'var1' attribute (but presumably objA does), the request actually is equivalent to saying x = objA.var1 Inherit from this class to create a Proxy. Note that, with new-style classes, this does *not* work transparently for Proxy subclasses that use special .__*__() method names, because those names are now bound to the class, not the individual instances. You now need to know in advance which .__*__() method names you want to pass on to the underlying Proxy object, and specifically delegate their calls like this: class Foo(Proxy): __str__ = Delegate('__str__') """ def __init__(self, subject): """Wrap an object as a Proxy object""" self._subject = subject def __getattr__(self, name): """Retrieve an attribute from the wrapped object. If the named attribute doesn't exist, AttributeError is raised""" return getattr(self._subject, name) def get(self): """Retrieve the entire wrapped object""" return self._subject def __cmp__(self, other): if issubclass(other.__class__, self._subject.__class__): return cmp(self._subject, other) return cmp(self.__dict__, other.__dict__) class Delegate(object): """A Python Descriptor class that delegates attribute fetches to an underlying wrapped subject of a Proxy. Typical use: class Foo(Proxy): __str__ = Delegate('__str__') """ def __init__(self, attribute): self.attribute = attribute def __get__(self, obj, cls): if isinstance(obj, cls): return getattr(obj._subject, self.attribute) else: return self # attempt to load the windows registry module: can_read_reg = 0 try: import winreg can_read_reg = 1 hkey_mod = winreg RegOpenKeyEx = winreg.OpenKeyEx RegEnumKey = winreg.EnumKey RegEnumValue = winreg.EnumValue RegQueryValueEx = winreg.QueryValueEx RegError = winreg.error except ImportError: try: import win32api import win32con can_read_reg = 1 hkey_mod = win32con RegOpenKeyEx = win32api.RegOpenKeyEx RegEnumKey = win32api.RegEnumKey RegEnumValue = win32api.RegEnumValue RegQueryValueEx = win32api.RegQueryValueEx RegError = win32api.error except ImportError: class _NoError(Exception): pass RegError = _NoError if can_read_reg: HKEY_CLASSES_ROOT = hkey_mod.HKEY_CLASSES_ROOT HKEY_LOCAL_MACHINE = hkey_mod.HKEY_LOCAL_MACHINE HKEY_CURRENT_USER = hkey_mod.HKEY_CURRENT_USER HKEY_USERS = hkey_mod.HKEY_USERS def RegGetValue(root, key): """This utility function returns a value in the registry without having to open the key first. Only available on Windows platforms with a version of Python that can read the registry. Returns the same thing as SCons.Util.RegQueryValueEx, except you just specify the entire path to the value, and don't have to bother opening the key first. So: Instead of: k = SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE, r'SOFTWARE\Microsoft\Windows\CurrentVersion') out = SCons.Util.RegQueryValueEx(k, 'ProgramFilesDir') You can write: out = SCons.Util.RegGetValue(SCons.Util.HKEY_LOCAL_MACHINE, r'SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesDir') """ # I would use os.path.split here, but it's not a filesystem # path... p = key.rfind('\\') + 1 keyp = key[:p-1] # -1 to omit trailing slash val = key[p:] k = RegOpenKeyEx(root, keyp) return RegQueryValueEx(k,val) else: try: e = WindowsError except NameError: # Make sure we have a definition of WindowsError so we can # run platform-independent tests of Windows functionality on # platforms other than Windows. (WindowsError is, in fact, an # OSError subclass on Windows.) class WindowsError(OSError): pass import builtins builtins.WindowsError = WindowsError else: del e HKEY_CLASSES_ROOT = None HKEY_LOCAL_MACHINE = None HKEY_CURRENT_USER = None HKEY_USERS = None def RegGetValue(root, key): raise WindowsError def RegOpenKeyEx(root, key): raise WindowsError if sys.platform == 'win32': def WhereIs(file, path=None, pathext=None, reject=[]): if path is None: try: path = os.environ['PATH'] except KeyError: return None if is_String(path): path = path.split(os.pathsep) if pathext is None: try: pathext = os.environ['PATHEXT'] except KeyError: pathext = '.COM;.EXE;.BAT;.CMD' if is_String(pathext): pathext = pathext.split(os.pathsep) for ext in pathext: if ext.lower() == file[-len(ext):].lower(): pathext = [''] break if not is_List(reject) and not is_Tuple(reject): reject = [reject] for dir in path: f = os.path.join(dir, file) for ext in pathext: fext = f + ext if os.path.isfile(fext): try: reject.index(fext) except ValueError: return os.path.normpath(fext) continue return None elif os.name == 'os2': def WhereIs(file, path=None, pathext=None, reject=[]): if path is None: try: path = os.environ['PATH'] except KeyError: return None if is_String(path): path = path.split(os.pathsep) if pathext is None: pathext = ['.exe', '.cmd'] for ext in pathext: if ext.lower() == file[-len(ext):].lower(): pathext = [''] break if not is_List(reject) and not is_Tuple(reject): reject = [reject] for dir in path: f = os.path.join(dir, file) for ext in pathext: fext = f + ext if os.path.isfile(fext): try: reject.index(fext) except ValueError: return os.path.normpath(fext) continue return None else: def WhereIs(file, path=None, pathext=None, reject=[]): import stat if path is None: try: path = os.environ['PATH'] except KeyError: return None if is_String(path): path = path.split(os.pathsep) if not is_List(reject) and not is_Tuple(reject): reject = [reject] for d in path: f = os.path.join(d, file) if os.path.isfile(f): try: st = os.stat(f) except OSError: # os.stat() raises OSError, not IOError if the file # doesn't exist, so in this case we let IOError get # raised so as to not mask possibly serious disk or # network issues. continue if stat.S_IMODE(st[stat.ST_MODE]) & 0111: try: reject.index(f) except ValueError: return os.path.normpath(f) continue return None def PrependPath(oldpath, newpath, sep = os.pathsep, delete_existing=1, canonicalize=None): """This prepends newpath elements to the given oldpath. Will only add any particular path once (leaving the first one it encounters and ignoring the rest, to preserve path order), and will os.path.normpath and os.path.normcase all paths to help assure this. This can also handle the case where the given old path variable is a list instead of a string, in which case a list will be returned instead of a string. Example: Old Path: "/foo/bar:/foo" New Path: "/biz/boom:/foo" Result: "/biz/boom:/foo:/foo/bar" If delete_existing is 0, then adding a path that exists will not move it to the beginning; it will stay where it is in the list. If canonicalize is not None, it is applied to each element of newpath before use. """ orig = oldpath is_list = 1 paths = orig if not is_List(orig) and not is_Tuple(orig): paths = paths.split(sep) is_list = 0 if is_String(newpath): newpaths = newpath.split(sep) elif not is_List(newpath) and not is_Tuple(newpath): newpaths = [ newpath ] # might be a Dir else: newpaths = newpath if canonicalize: newpaths=list(map(canonicalize, newpaths)) if not delete_existing: # First uniquify the old paths, making sure to # preserve the first instance (in Unix/Linux, # the first one wins), and remembering them in normpaths. # Then insert the new paths at the head of the list # if they're not already in the normpaths list. result = [] normpaths = [] for path in paths: if not path: continue normpath = os.path.normpath(os.path.normcase(path)) if normpath not in normpaths: result.append(path) normpaths.append(normpath) newpaths.reverse() # since we're inserting at the head for path in newpaths: if not path: continue normpath = os.path.normpath(os.path.normcase(path)) if normpath not in normpaths: result.insert(0, path) normpaths.append(normpath) paths = result else: newpaths = newpaths + paths # prepend new paths normpaths = [] paths = [] # now we add them only if they are unique for path in newpaths: normpath = os.path.normpath(os.path.normcase(path)) if path and not normpath in normpaths: paths.append(path) normpaths.append(normpath) if is_list: return paths else: return sep.join(paths) def AppendPath(oldpath, newpath, sep = os.pathsep, delete_existing=1, canonicalize=None): """This appends new path elements to the given old path. Will only add any particular path once (leaving the last one it encounters and ignoring the rest, to preserve path order), and will os.path.normpath and os.path.normcase all paths to help assure this. This can also handle the case where the given old path variable is a list instead of a string, in which case a list will be returned instead of a string. Example: Old Path: "/foo/bar:/foo" New Path: "/biz/boom:/foo" Result: "/foo/bar:/biz/boom:/foo" If delete_existing is 0, then adding a path that exists will not move it to the end; it will stay where it is in the list. If canonicalize is not None, it is applied to each element of newpath before use. """ orig = oldpath is_list = 1 paths = orig if not is_List(orig) and not is_Tuple(orig): paths = paths.split(sep) is_list = 0 if is_String(newpath): newpaths = newpath.split(sep) elif not is_List(newpath) and not is_Tuple(newpath): newpaths = [ newpath ] # might be a Dir else: newpaths = newpath if canonicalize: newpaths=list(map(canonicalize, newpaths)) if not delete_existing: # add old paths to result, then # add new paths if not already present # (I thought about using a dict for normpaths for speed, # but it's not clear hashing the strings would be faster # than linear searching these typically short lists.) result = [] normpaths = [] for path in paths: if not path: continue result.append(path) normpaths.append(os.path.normpath(os.path.normcase(path))) for path in newpaths: if not path: continue normpath = os.path.normpath(os.path.normcase(path)) if normpath not in normpaths: result.append(path) normpaths.append(normpath) paths = result else: # start w/ new paths, add old ones if not present, # then reverse. newpaths = paths + newpaths # append new paths newpaths.reverse() normpaths = [] paths = [] # now we add them only if they are unique for path in newpaths: normpath = os.path.normpath(os.path.normcase(path)) if path and not normpath in normpaths: paths.append(path) normpaths.append(normpath) paths.reverse() if is_list: return paths else: return sep.join(paths) if sys.platform == 'cygwin': def get_native_path(path): """Transforms an absolute path into a native path for the system. In Cygwin, this converts from a Cygwin path to a Windows one.""" return os.popen('cygpath -w ' + path).read().replace('\n', '') else: def get_native_path(path): """Transforms an absolute path into a native path for the system. Non-Cygwin version, just leave the path alone.""" return path display = DisplayEngine() def Split(arg): if is_List(arg) or is_Tuple(arg): return arg elif is_String(arg): return arg.split() else: return [arg] class CLVar(UserList): """A class for command-line construction variables. This is a list that uses Split() to split an initial string along white-space arguments, and similarly to split any strings that get added. This allows us to Do the Right Thing with Append() and Prepend() (as well as straight Python foo = env['VAR'] + 'arg1 arg2') regardless of whether a user adds a list or a string to a command-line construction variable. """ def __init__(self, seq = []): UserList.__init__(self, Split(seq)) def __add__(self, other): return UserList.__add__(self, CLVar(other)) def __radd__(self, other): return UserList.__radd__(self, CLVar(other)) def __coerce__(self, other): return (self, CLVar(other)) def __str__(self): return ' '.join(self.data) # A dictionary that preserves the order in which items are added. # Submitted by David Benjamin to ActiveState's Python Cookbook web site: # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/107747 # Including fixes/enhancements from the follow-on discussions. class OrderedDict(UserDict): def __init__(self, dict = None): self._keys = [] UserDict.__init__(self, dict) def __delitem__(self, key): UserDict.__delitem__(self, key) self._keys.remove(key) def __setitem__(self, key, item): UserDict.__setitem__(self, key, item) if key not in self._keys: self._keys.append(key) def clear(self): UserDict.clear(self) self._keys = [] def copy(self): dict = OrderedDict() dict.update(self) return dict def items(self): return list(zip(self._keys, list(self.values()))) def keys(self): return self._keys[:] def popitem(self): try: key = self._keys[-1] except IndexError: raise KeyError('dictionary is empty') val = self[key] del self[key] return (key, val) def setdefault(self, key, failobj = None): UserDict.setdefault(self, key, failobj) if key not in self._keys: self._keys.append(key) def update(self, dict): for (key, val) in dict.items(): self.__setitem__(key, val) def values(self): return list(map(self.get, self._keys)) class Selector(OrderedDict): """A callable ordered dictionary that maps file suffixes to dictionary values. We preserve the order in which items are added so that get_suffix() calls always return the first suffix added.""" def __call__(self, env, source, ext=None): if ext is None: try: ext = source[0].suffix except IndexError: ext = "" try: return self[ext] except KeyError: # Try to perform Environment substitution on the keys of # the dictionary before giving up. s_dict = {} for (k,v) in self.items(): if k is not None: s_k = env.subst(k) if s_k in s_dict: # We only raise an error when variables point # to the same suffix. If one suffix is literal # and a variable suffix contains this literal, # the literal wins and we don't raise an error. raise KeyError(s_dict[s_k][0], k, s_k) s_dict[s_k] = (k,v) try: return s_dict[ext][1] except KeyError: try: return self[None] except KeyError: return None if sys.platform == 'cygwin': # On Cygwin, os.path.normcase() lies, so just report back the # fact that the underlying Windows OS is case-insensitive. def case_sensitive_suffixes(s1, s2): return 0 else: def case_sensitive_suffixes(s1, s2): return (os.path.normcase(s1) != os.path.normcase(s2)) def adjustixes(fname, pre, suf, ensure_suffix=False): if pre: path, fn = os.path.split(os.path.normpath(fname)) if fn[:len(pre)] != pre: fname = os.path.join(path, pre + fn) # Only append a suffix if the suffix we're going to add isn't already # there, and if either we've been asked to ensure the specific suffix # is present or there's no suffix on it at all. if suf and fname[-len(suf):] != suf and \ (ensure_suffix or not splitext(fname)[1]): fname = fname + suf return fname # From Tim Peters, # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560 # ASPN: Python Cookbook: Remove duplicates from a sequence # (Also in the printed Python Cookbook.) def unique(s): """Return a list of the elements in s, but without duplicates. For example, unique([1,2,3,1,2,3]) is some permutation of [1,2,3], unique("abcabc") some permutation of ["a", "b", "c"], and unique(([1, 2], [2, 3], [1, 2])) some permutation of [[2, 3], [1, 2]]. For best speed, all sequence elements should be hashable. Then unique() will usually work in linear time. If not possible, the sequence elements should enjoy a total ordering, and if list(s).sort() doesn't raise TypeError it's assumed that they do enjoy a total ordering. Then unique() will usually work in O(N*log2(N)) time. If that's not possible either, the sequence elements must support equality-testing. Then unique() will usually work in quadratic time. """ n = len(s) if n == 0: return [] # Try using a dict first, as that's the fastest and will usually # work. If it doesn't work, it will usually fail quickly, so it # usually doesn't cost much to *try* it. It requires that all the # sequence elements be hashable, and support equality comparison. u = {} try: for x in s: u[x] = 1 except TypeError: pass # move on to the next method else: return list(u.keys()) del u # We can't hash all the elements. Second fastest is to sort, # which brings the equal elements together; then duplicates are # easy to weed out in a single pass. # NOTE: Python's list.sort() was designed to be efficient in the # presence of many duplicate elements. This isn't true of all # sort functions in all languages or libraries, so this approach # is more effective in Python than it may be elsewhere. try: t = sorted(s) except TypeError: pass # move on to the next method else: assert n > 0 last = t[0] lasti = i = 1 while i < n: if t[i] != last: t[lasti] = last = t[i] lasti = lasti + 1 i = i + 1 return t[:lasti] del t # Brute force is all that's left. u = [] for x in s: if x not in u: u.append(x) return u # From Alex Martelli, # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560 # ASPN: Python Cookbook: Remove duplicates from a sequence # First comment, dated 2001/10/13. # (Also in the printed Python Cookbook.) def uniquer(seq, idfun=None): if idfun is None: def idfun(x): return x seen = {} result = [] for item in seq: marker = idfun(item) # in old Python versions: # if seen.has_key(marker) # but in new ones: if marker in seen: continue seen[marker] = 1 result.append(item) return result # A more efficient implementation of Alex's uniquer(), this avoids the # idfun() argument and function-call overhead by assuming that all # items in the sequence are hashable. def uniquer_hashables(seq): seen = {} result = [] for item in seq: #if not item in seen: if item not in seen: seen[item] = 1 result.append(item) return result # Much of the logic here was originally based on recipe 4.9 from the # Python CookBook, but we had to dumb it way down for Python 1.5.2. class LogicalLines(object): def __init__(self, fileobj): self.fileobj = fileobj def readline(self): result = [] while True: line = self.fileobj.readline() if not line: break if line[-2:] == '\\\n': result.append(line[:-2]) else: result.append(line) break return ''.join(result) def readlines(self): result = [] while True: line = self.readline() if not line: break result.append(line) return result class UniqueList(UserList): def __init__(self, seq = []): UserList.__init__(self, seq) self.unique = True def __make_unique(self): if not self.unique: self.data = uniquer_hashables(self.data) self.unique = True def __lt__(self, other): self.__make_unique() return UserList.__lt__(self, other) def __le__(self, other): self.__make_unique() return UserList.__le__(self, other) def __eq__(self, other): self.__make_unique() return UserList.__eq__(self, other) def __ne__(self, other): self.__make_unique() return UserList.__ne__(self, other) def __gt__(self, other): self.__make_unique() return UserList.__gt__(self, other) def __ge__(self, other): self.__make_unique() return UserList.__ge__(self, other) def __cmp__(self, other): self.__make_unique() return UserList.__cmp__(self, other) def __len__(self): self.__make_unique() return UserList.__len__(self) def __getitem__(self, i): self.__make_unique() return UserList.__getitem__(self, i) def __setitem__(self, i, item): UserList.__setitem__(self, i, item) self.unique = False def __getslice__(self, i, j): self.__make_unique() return UserList.__getslice__(self, i, j) def __setslice__(self, i, j, other): UserList.__setslice__(self, i, j, other) self.unique = False def __add__(self, other): result = UserList.__add__(self, other) result.unique = False return result def __radd__(self, other): result = UserList.__radd__(self, other) result.unique = False return result def __iadd__(self, other): result = UserList.__iadd__(self, other) result.unique = False return result def __mul__(self, other): result = UserList.__mul__(self, other) result.unique = False return result def __rmul__(self, other): result = UserList.__rmul__(self, other) result.unique = False return result def __imul__(self, other): result = UserList.__imul__(self, other) result.unique = False return result def append(self, item): UserList.append(self, item) self.unique = False def insert(self, i): UserList.insert(self, i) self.unique = False def count(self, item): self.__make_unique() return UserList.count(self, item) def index(self, item): self.__make_unique() return UserList.index(self, item) def reverse(self): self.__make_unique() UserList.reverse(self) def sort(self, *args, **kwds): self.__make_unique() return UserList.sort(self, *args, **kwds) def extend(self, other): UserList.extend(self, other) self.unique = False class Unbuffered(object): """ A proxy class that wraps a file object, flushing after every write, and delegating everything else to the wrapped object. """ def __init__(self, file): self.file = file self.softspace = 0 ## backward compatibility; not supported in Py3k def write(self, arg): try: self.file.write(arg) self.file.flush() except IOError: # Stdout might be connected to a pipe that has been closed # by now. The most likely reason for the pipe being closed # is that the user has press ctrl-c. It this is the case, # then SCons is currently shutdown. We therefore ignore # IOError's here so that SCons can continue and shutdown # properly so that the .sconsign is correctly written # before SCons exits. pass def __getattr__(self, attr): return getattr(self.file, attr) def make_path_relative(path): """ makes an absolute path name to a relative pathname. """ if os.path.isabs(path): drive_s,path = os.path.splitdrive(path) import re if not drive_s: path=re.compile("/*(.*)").findall(path)[0] else: path=path[1:] assert( not os.path.isabs( path ) ), path return path # The original idea for AddMethod() and RenameFunction() come from the # following post to the ActiveState Python Cookbook: # # ASPN: Python Cookbook : Install bound methods in an instance # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/223613 # # That code was a little fragile, though, so the following changes # have been wrung on it: # # * Switched the installmethod() "object" and "function" arguments, # so the order reflects that the left-hand side is the thing being # "assigned to" and the right-hand side is the value being assigned. # # * Changed explicit type-checking to the "try: klass = object.__class__" # block in installmethod() below so that it still works with the # old-style classes that SCons uses. # # * Replaced the by-hand creation of methods and functions with use of # the "new" module, as alluded to in Alex Martelli's response to the # following Cookbook post: # # ASPN: Python Cookbook : Dynamically added methods to a class # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81732 def AddMethod(obj, function, name=None): """ Adds either a bound method to an instance or an unbound method to a class. If name is ommited the name of the specified function is used by default. Example: a = A() def f(self, x, y): self.z = x + y AddMethod(f, A, "add") a.add(2, 4) print a.z AddMethod(lambda self, i: self.l[i], a, "listIndex") print a.listIndex(5) """ if name is None: name = function.func_name else: function = RenameFunction(function, name) if hasattr(obj, '__class__') and obj.__class__ is not type: # "obj" is an instance, so it gets a bound method. setattr(obj, name, MethodType(function, obj, obj.__class__)) else: # "obj" is a class, so it gets an unbound method. setattr(obj, name, MethodType(function, None, obj)) def RenameFunction(function, name): """ Returns a function identical to the specified function, but with the specified name. """ return FunctionType(function.func_code, function.func_globals, name, function.func_defaults) md5 = False def MD5signature(s): return str(s) def MD5filesignature(fname, chunksize=65536): f = open(fname, "rb") result = f.read() f.close() return result try: import hashlib except ImportError: pass else: if hasattr(hashlib, 'md5'): md5 = True def MD5signature(s): m = hashlib.md5() m.update(str(s)) return m.hexdigest() def MD5filesignature(fname, chunksize=65536): m = hashlib.md5() f = open(fname, "rb") while True: blck = f.read(chunksize) if not blck: break m.update(str(blck)) f.close() return m.hexdigest() def MD5collect(signatures): """ Collects a list of signatures into an aggregate signature. signatures - a list of signatures returns - the aggregate signature """ if len(signatures) == 1: return signatures[0] else: return MD5signature(', '.join(signatures)) def silent_intern(x): """ Perform sys.intern() on the passed argument and return the result. If the input is ineligible (e.g. a unicode string) the original argument is returned and no exception is thrown. """ try: return sys.intern(x) except TypeError: return x # From Dinu C. Gherman, # Python Cookbook, second edition, recipe 6.17, p. 277. # Also: # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68205 # ASPN: Python Cookbook: Null Object Design Pattern #TODO??? class Null(object): class Null(object): """ Null objects always and reliably "do nothing." """ def __new__(cls, *args, **kwargs): if not '_instance' in vars(cls): cls._instance = super(Null, cls).__new__(cls, *args, **kwargs) return cls._instance def __init__(self, *args, **kwargs): pass def __call__(self, *args, **kwargs): return self def __repr__(self): return "Null(0x%08X)" % id(self) def __nonzero__(self): return False def __getattr__(self, name): return self def __setattr__(self, name, value): return self def __delattr__(self, name): return self class NullSeq(Null): def __len__(self): return 0 def __iter__(self): return iter(()) def __getitem__(self, i): return self def __delitem__(self, i): return self def __setitem__(self, i, v): return self del __revision__ # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.exitfuncs Register functions which are executed when SCons exits for any reason. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/exitfuncs.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" _exithandlers = [] def _run_exitfuncs(): """run any registered exit functions _exithandlers is traversed in reverse order so functions are executed last in, first out. """ while _exithandlers: func, targs, kargs = _exithandlers.pop() func(*targs, **kargs) def register(func, *targs, **kargs): """register a function to be executed upon normal program termination func - function to be called at exit targs - optional arguments to pass to func kargs - optional keyword arguments to pass to func """ _exithandlers.append((func, targs, kargs)) import sys try: x = sys.exitfunc # if x isn't our own exit func executive, assume it's another # registered exit function - append it to our list... if x != _run_exitfuncs: register(x) except AttributeError: pass # make our exit function get run by python when it exits: sys.exitfunc = _run_exitfuncs del sys # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Action This encapsulates information about executing any sort of action that can build one or more target Nodes (typically files) from one or more source Nodes (also typically files) given a specific Environment. The base class here is ActionBase. The base class supplies just a few OO utility methods and some generic methods for displaying information about an Action in response to the various commands that control printing. A second-level base class is _ActionAction. This extends ActionBase by providing the methods that can be used to show and perform an action. True Action objects will subclass _ActionAction; Action factory class objects will subclass ActionBase. The heavy lifting is handled by subclasses for the different types of actions we might execute: CommandAction CommandGeneratorAction FunctionAction ListAction The subclasses supply the following public interface methods used by other modules: __call__() THE public interface, "calling" an Action object executes the command or Python function. This also takes care of printing a pre-substitution command for debugging purposes. get_contents() Fetches the "contents" of an Action for signature calculation plus the varlist. This is what gets MD5 checksummed to decide if a target needs to be rebuilt because its action changed. genstring() Returns a string representation of the Action *without* command substitution, but allows a CommandGeneratorAction to generate the right action based on the specified target, source and env. This is used by the Signature subsystem (through the Executor) to obtain an (imprecise) representation of the Action operation for informative purposes. Subclasses also supply the following methods for internal use within this module: __str__() Returns a string approximation of the Action; no variable substitution is performed. execute() The internal method that really, truly, actually handles the execution of a command or Python function. This is used so that the __call__() methods can take care of displaying any pre-substitution representations, and *then* execute an action without worrying about the specific Actions involved. get_presig() Fetches the "contents" of a subclass for signature calculation. The varlist is added to this to produce the Action's contents. strfunction() Returns a substituted string representation of the Action. This is used by the _ActionAction.show() command to display the command/function that will be executed to generate the target(s). There is a related independent ActionCaller class that looks like a regular Action, and which serves as a wrapper for arbitrary functions that we want to let the user specify the arguments to now, but actually execute later (when an out-of-date check determines that it's needed to be executed, for example). Objects of this class are returned by an ActionFactory class that provides a __call__() method as a convenient way for wrapping up the functions. """ # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. __revision__ = "src/engine/SCons/Action.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.compat import dis import os # compat layer imports "cPickle" for us if it's available. import pickle import re import sys import subprocess from SCons.Debug import logInstanceCreation import SCons.Errors import SCons.Executor import SCons.Util import SCons.Subst # we use these a lot, so try to optimize them is_String = SCons.Util.is_String is_List = SCons.Util.is_List class _null(object): pass print_actions = 1 execute_actions = 1 print_actions_presub = 0 def rfile(n): try: return n.rfile() except AttributeError: return n def default_exitstatfunc(s): return s try: SET_LINENO = dis.SET_LINENO HAVE_ARGUMENT = dis.HAVE_ARGUMENT except AttributeError: remove_set_lineno_codes = lambda x: x else: def remove_set_lineno_codes(code): result = [] n = len(code) i = 0 while i < n: c = code[i] op = ord(c) if op >= HAVE_ARGUMENT: if op != SET_LINENO: result.append(code[i:i+3]) i = i+3 else: result.append(c) i = i+1 return ''.join(result) strip_quotes = re.compile('^[\'"](.*)[\'"]$') def _callable_contents(obj): """Return the signature contents of a callable Python object. """ try: # Test if obj is a method. return _function_contents(obj.im_func) except AttributeError: try: # Test if obj is a callable object. return _function_contents(obj.__call__.im_func) except AttributeError: try: # Test if obj is a code object. return _code_contents(obj) except AttributeError: # Test if obj is a function object. return _function_contents(obj) def _object_contents(obj): """Return the signature contents of any Python object. We have to handle the case where object contains a code object since it can be pickled directly. """ try: # Test if obj is a method. return _function_contents(obj.im_func) except AttributeError: try: # Test if obj is a callable object. return _function_contents(obj.__call__.im_func) except AttributeError: try: # Test if obj is a code object. return _code_contents(obj) except AttributeError: try: # Test if obj is a function object. return _function_contents(obj) except AttributeError: # Should be a pickable Python object. try: return pickle.dumps(obj) except (pickle.PicklingError, TypeError): # This is weird, but it seems that nested classes # are unpickable. The Python docs say it should # always be a PicklingError, but some Python # versions seem to return TypeError. Just do # the best we can. return str(obj) def _code_contents(code): """Return the signature contents of a code object. By providing direct access to the code object of the function, Python makes this extremely easy. Hooray! Unfortunately, older versions of Python include line number indications in the compiled byte code. Boo! So we remove the line number byte codes to prevent recompilations from moving a Python function. """ contents = [] # The code contents depends on the number of local variables # but not their actual names. contents.append("%s,%s" % (code.co_argcount, len(code.co_varnames))) try: contents.append(",%s,%s" % (len(code.co_cellvars), len(code.co_freevars))) except AttributeError: # Older versions of Python do not support closures. contents.append(",0,0") # The code contents depends on any constants accessed by the # function. Note that we have to call _object_contents on each # constants because the code object of nested functions can # show-up among the constants. # # Note that we also always ignore the first entry of co_consts # which contains the function doc string. We assume that the # function does not access its doc string. contents.append(',(' + ','.join(map(_object_contents,code.co_consts[1:])) + ')') # The code contents depends on the variable names used to # accessed global variable, as changing the variable name changes # the variable actually accessed and therefore changes the # function result. contents.append(',(' + ','.join(map(_object_contents,code.co_names)) + ')') # The code contents depends on its actual code!!! contents.append(',(' + str(remove_set_lineno_codes(code.co_code)) + ')') return ''.join(contents) def _function_contents(func): """Return the signature contents of a function.""" contents = [_code_contents(func.func_code)] # The function contents depends on the value of defaults arguments if func.func_defaults: contents.append(',(' + ','.join(map(_object_contents,func.func_defaults)) + ')') else: contents.append(',()') # The function contents depends on the closure captured cell values. try: closure = func.func_closure or [] except AttributeError: # Older versions of Python do not support closures. closure = [] #xxx = [_object_contents(x.cell_contents) for x in closure] try: xxx = [_object_contents(x.cell_contents) for x in closure] except AttributeError: xxx = [] contents.append(',(' + ','.join(xxx) + ')') return ''.join(contents) def _actionAppend(act1, act2): # This function knows how to slap two actions together. # Mainly, it handles ListActions by concatenating into # a single ListAction. a1 = Action(act1) a2 = Action(act2) if a1 is None: return a2 if a2 is None: return a1 if isinstance(a1, ListAction): if isinstance(a2, ListAction): return ListAction(a1.list + a2.list) else: return ListAction(a1.list + [ a2 ]) else: if isinstance(a2, ListAction): return ListAction([ a1 ] + a2.list) else: return ListAction([ a1, a2 ]) def _do_create_keywords(args, kw): """This converts any arguments after the action argument into their equivalent keywords and adds them to the kw argument. """ v = kw.get('varlist', ()) # prevent varlist="FOO" from being interpreted as ['F', 'O', 'O'] if is_String(v): v = (v,) kw['varlist'] = tuple(v) if args: # turn positional args into equivalent keywords cmdstrfunc = args[0] if cmdstrfunc is None or is_String(cmdstrfunc): kw['cmdstr'] = cmdstrfunc elif callable(cmdstrfunc): kw['strfunction'] = cmdstrfunc else: raise SCons.Errors.UserError( 'Invalid command display variable type. ' 'You must either pass a string or a callback which ' 'accepts (target, source, env) as parameters.') if len(args) > 1: kw['varlist'] = args[1:] + kw['varlist'] if kw.get('strfunction', _null) is not _null \ and kw.get('cmdstr', _null) is not _null: raise SCons.Errors.UserError( 'Cannot have both strfunction and cmdstr args to Action()') def _do_create_action(act, kw): """This is the actual "implementation" for the Action factory method, below. This handles the fact that passing lists to Action() itself has different semantics than passing lists as elements of lists. The former will create a ListAction, the latter will create a CommandAction by converting the inner list elements to strings.""" if isinstance(act, ActionBase): return act if is_List(act): return CommandAction(act, **kw) if callable(act): try: gen = kw['generator'] del kw['generator'] except KeyError: gen = 0 if gen: action_type = CommandGeneratorAction else: action_type = FunctionAction return action_type(act, kw) if is_String(act): var=SCons.Util.get_environment_var(act) if var: # This looks like a string that is purely an Environment # variable reference, like "$FOO" or "${FOO}". We do # something special here...we lazily evaluate the contents # of that Environment variable, so a user could put something # like a function or a CommandGenerator in that variable # instead of a string. return LazyAction(var, kw) commands = str(act).split('\n') if len(commands) == 1: return CommandAction(commands[0], **kw) # The list of string commands may include a LazyAction, so we # reprocess them via _do_create_list_action. return _do_create_list_action(commands, kw) # Catch a common error case with a nice message: if isinstance(act, int) or isinstance(act, float): raise TypeError("Don't know how to create an Action from a number (%s)"%act) # Else fail silently (???) return None def _do_create_list_action(act, kw): """A factory for list actions. Convert the input list into Actions and then wrap them in a ListAction.""" acts = [] for a in act: aa = _do_create_action(a, kw) if aa is not None: acts.append(aa) if not acts: return ListAction([]) elif len(acts) == 1: return acts[0] else: return ListAction(acts) def Action(act, *args, **kw): """A factory for action objects.""" # Really simple: the _do_create_* routines do the heavy lifting. _do_create_keywords(args, kw) if is_List(act): return _do_create_list_action(act, kw) return _do_create_action(act, kw) class ActionBase(object): """Base class for all types of action objects that can be held by other objects (Builders, Executors, etc.) This provides the common methods for manipulating and combining those actions.""" def __cmp__(self, other): return cmp(self.__dict__, other) def no_batch_key(self, env, target, source): return None batch_key = no_batch_key def genstring(self, target, source, env): return str(self) def get_contents(self, target, source, env): result = [ self.get_presig(target, source, env) ] # This should never happen, as the Action() factory should wrap # the varlist, but just in case an action is created directly, # we duplicate this check here. vl = self.get_varlist(target, source, env) if is_String(vl): vl = (vl,) for v in vl: result.append(env.subst('${'+v+'}')) return ''.join(result) def __add__(self, other): return _actionAppend(self, other) def __radd__(self, other): return _actionAppend(other, self) def presub_lines(self, env): # CommandGeneratorAction needs a real environment # in order to return the proper string here, since # it may call LazyAction, which looks up a key # in that env. So we temporarily remember the env here, # and CommandGeneratorAction will use this env # when it calls its _generate method. self.presub_env = env lines = str(self).split('\n') self.presub_env = None # don't need this any more return lines def get_varlist(self, target, source, env, executor=None): return self.varlist def get_targets(self, env, executor): """ Returns the type of targets ($TARGETS, $CHANGED_TARGETS) used by this action. """ return self.targets class _ActionAction(ActionBase): """Base class for actions that create output objects.""" def __init__(self, cmdstr=_null, strfunction=_null, varlist=(), presub=_null, chdir=None, exitstatfunc=None, batch_key=None, targets='$TARGETS', **kw): self.cmdstr = cmdstr if strfunction is not _null: if strfunction is None: self.cmdstr = None else: self.strfunction = strfunction self.varlist = varlist self.presub = presub self.chdir = chdir if not exitstatfunc: exitstatfunc = default_exitstatfunc self.exitstatfunc = exitstatfunc self.targets = targets if batch_key: if not callable(batch_key): # They have set batch_key, but not to their own # callable. The default behavior here will batch # *all* targets+sources using this action, separated # for each construction environment. def default_batch_key(self, env, target, source): return (id(self), id(env)) batch_key = default_batch_key SCons.Util.AddMethod(self, batch_key, 'batch_key') def print_cmd_line(self, s, target, source, env): # In python 3, and in some of our tests, sys.stdout is # a String io object, and it takes unicode strings only # In other cases it's a regular Python 2.x file object # which takes strings (bytes), and if you pass those a # unicode object they try to decode with 'ascii' codec # which fails if the cmd line has any hi-bit-set chars. # This code assumes s is a regular string, but should # work if it's unicode too. try: sys.stdout.write(unicode(s + "\n")) except UnicodeDecodeError: sys.stdout.write(s + "\n") def __call__(self, target, source, env, exitstatfunc=_null, presub=_null, show=_null, execute=_null, chdir=_null, executor=None): if not is_List(target): target = [target] if not is_List(source): source = [source] if presub is _null: presub = self.presub if presub is _null: presub = print_actions_presub if exitstatfunc is _null: exitstatfunc = self.exitstatfunc if show is _null: show = print_actions if execute is _null: execute = execute_actions if chdir is _null: chdir = self.chdir save_cwd = None if chdir: save_cwd = os.getcwd() try: chdir = str(chdir.abspath) except AttributeError: if not is_String(chdir): if executor: chdir = str(executor.batches[0].targets[0].dir) else: chdir = str(target[0].dir) if presub: if executor: target = executor.get_all_targets() source = executor.get_all_sources() t = ' and '.join(map(str, target)) l = '\n '.join(self.presub_lines(env)) out = u"Building %s with action:\n %s\n" % (t, l) sys.stdout.write(out) cmd = None if show and self.strfunction: if executor: target = executor.get_all_targets() source = executor.get_all_sources() try: cmd = self.strfunction(target, source, env, executor) except TypeError: cmd = self.strfunction(target, source, env) if cmd: if chdir: cmd = ('os.chdir(%s)\n' % repr(chdir)) + cmd try: get = env.get except AttributeError: print_func = self.print_cmd_line else: print_func = get('PRINT_CMD_LINE_FUNC') if not print_func: print_func = self.print_cmd_line print_func(cmd, target, source, env) stat = 0 if execute: if chdir: os.chdir(chdir) try: stat = self.execute(target, source, env, executor=executor) if isinstance(stat, SCons.Errors.BuildError): s = exitstatfunc(stat.status) if s: stat.status = s else: stat = s else: stat = exitstatfunc(stat) finally: if save_cwd: os.chdir(save_cwd) if cmd and save_cwd: print_func('os.chdir(%s)' % repr(save_cwd), target, source, env) return stat def _string_from_cmd_list(cmd_list): """Takes a list of command line arguments and returns a pretty representation for printing.""" cl = [] for arg in map(str, cmd_list): if ' ' in arg or '\t' in arg: arg = '"' + arg + '"' cl.append(arg) return ' '.join(cl) # A fiddlin' little function that has an 'import SCons.Environment' which # can't be moved to the top level without creating an import loop. Since # this import creates a local variable named 'SCons', it blocks access to # the global variable, so we move it here to prevent complaints about local # variables being used uninitialized. default_ENV = None def get_default_ENV(env): global default_ENV try: return env['ENV'] except KeyError: if not default_ENV: import SCons.Environment # This is a hideously expensive way to get a default shell # environment. What it really should do is run the platform # setup to get the default ENV. Fortunately, it's incredibly # rare for an Environment not to have a shell environment, so # we're not going to worry about it overmuch. default_ENV = SCons.Environment.Environment()['ENV'] return default_ENV # This function is still in draft mode. We're going to need something like # it in the long run as more and more places use subprocess, but I'm sure # it'll have to be tweaked to get the full desired functionality. # one special arg (so far?), 'error', to tell what to do with exceptions. def _subproc(scons_env, cmd, error = 'ignore', **kw): """Do common setup for a subprocess.Popen() call""" # allow std{in,out,err} to be "'devnull'" io = kw.get('stdin') if is_String(io) and io == 'devnull': kw['stdin'] = open(os.devnull) io = kw.get('stdout') if is_String(io) and io == 'devnull': kw['stdout'] = open(os.devnull, 'w') io = kw.get('stderr') if is_String(io) and io == 'devnull': kw['stderr'] = open(os.devnull, 'w') # Figure out what shell environment to use ENV = kw.get('env', None) if ENV is None: ENV = get_default_ENV(scons_env) # Ensure that the ENV values are all strings: new_env = {} for key, value in ENV.items(): if is_List(value): # If the value is a list, then we assume it is a path list, # because that's a pretty common list-like value to stick # in an environment variable: value = SCons.Util.flatten_sequence(value) new_env[key] = os.pathsep.join(map(str, value)) else: # It's either a string or something else. If it's a string, # we still want to call str() because it might be a *Unicode* # string, which makes subprocess.Popen() gag. If it isn't a # string or a list, then we just coerce it to a string, which # is the proper way to handle Dir and File instances and will # produce something reasonable for just about everything else: new_env[key] = str(value) kw['env'] = new_env try: return subprocess.Popen(cmd, **kw) except EnvironmentError, e: if error == 'raise': raise # return a dummy Popen instance that only returns error class dummyPopen(object): def __init__(self, e): self.exception = e def communicate(self): return ('','') def wait(self): return -self.exception.errno stdin = None class f(object): def read(self): return '' def readline(self): return '' stdout = stderr = f() return dummyPopen(e) class CommandAction(_ActionAction): """Class for command-execution actions.""" def __init__(self, cmd, **kw): # Cmd can actually be a list or a single item; if it's a # single item it should be the command string to execute; if a # list then it should be the words of the command string to # execute. Only a single command should be executed by this # object; lists of commands should be handled by embedding # these objects in a ListAction object (which the Action() # factory above does). cmd will be passed to # Environment.subst_list() for substituting environment # variables. if __debug__: logInstanceCreation(self, 'Action.CommandAction') _ActionAction.__init__(self, **kw) if is_List(cmd): if list(filter(is_List, cmd)): raise TypeError("CommandAction should be given only " \ "a single command") self.cmd_list = cmd def __str__(self): if is_List(self.cmd_list): return ' '.join(map(str, self.cmd_list)) return str(self.cmd_list) def process(self, target, source, env, executor=None): if executor: result = env.subst_list(self.cmd_list, 0, executor=executor) else: result = env.subst_list(self.cmd_list, 0, target, source) silent = None ignore = None while True: try: c = result[0][0][0] except IndexError: c = None if c == '@': silent = 1 elif c == '-': ignore = 1 else: break result[0][0] = result[0][0][1:] try: if not result[0][0]: result[0] = result[0][1:] except IndexError: pass return result, ignore, silent def strfunction(self, target, source, env, executor=None): if self.cmdstr is None: return None if self.cmdstr is not _null: from SCons.Subst import SUBST_RAW if executor: c = env.subst(self.cmdstr, SUBST_RAW, executor=executor) else: c = env.subst(self.cmdstr, SUBST_RAW, target, source) if c: return c cmd_list, ignore, silent = self.process(target, source, env, executor) if silent: return '' return _string_from_cmd_list(cmd_list[0]) def execute(self, target, source, env, executor=None): """Execute a command action. This will handle lists of commands as well as individual commands, because construction variable substitution may turn a single "command" into a list. This means that this class can actually handle lists of commands, even though that's not how we use it externally. """ escape_list = SCons.Subst.escape_list flatten_sequence = SCons.Util.flatten_sequence try: shell = env['SHELL'] except KeyError: raise SCons.Errors.UserError('Missing SHELL construction variable.') try: spawn = env['SPAWN'] except KeyError: raise SCons.Errors.UserError('Missing SPAWN construction variable.') else: if is_String(spawn): spawn = env.subst(spawn, raw=1, conv=lambda x: x) escape = env.get('ESCAPE', lambda x: x) ENV = get_default_ENV(env) # Ensure that the ENV values are all strings: for key, value in ENV.items(): if not is_String(value): if is_List(value): # If the value is a list, then we assume it is a # path list, because that's a pretty common list-like # value to stick in an environment variable: value = flatten_sequence(value) ENV[key] = os.pathsep.join(map(str, value)) else: # If it isn't a string or a list, then we just coerce # it to a string, which is the proper way to handle # Dir and File instances and will produce something # reasonable for just about everything else: ENV[key] = str(value) if executor: target = executor.get_all_targets() source = executor.get_all_sources() cmd_list, ignore, silent = self.process(target, list(map(rfile, source)), env, executor) # Use len() to filter out any "command" that's zero-length. for cmd_line in filter(len, cmd_list): # Escape the command line for the interpreter we are using. cmd_line = escape_list(cmd_line, escape) result = spawn(shell, escape, cmd_line[0], cmd_line, ENV) if not ignore and result: msg = "Error %s" % result return SCons.Errors.BuildError(errstr=msg, status=result, action=self, command=cmd_line) return 0 def get_presig(self, target, source, env, executor=None): """Return the signature contents of this action's command line. This strips $(-$) and everything in between the string, since those parts don't affect signatures. """ from SCons.Subst import SUBST_SIG cmd = self.cmd_list if is_List(cmd): cmd = ' '.join(map(str, cmd)) else: cmd = str(cmd) if executor: return env.subst_target_source(cmd, SUBST_SIG, executor=executor) else: return env.subst_target_source(cmd, SUBST_SIG, target, source) def get_implicit_deps(self, target, source, env, executor=None): icd = env.get('IMPLICIT_COMMAND_DEPENDENCIES', True) if is_String(icd) and icd[:1] == '$': icd = env.subst(icd) if not icd or icd in ('0', 'None'): return [] from SCons.Subst import SUBST_SIG if executor: cmd_list = env.subst_list(self.cmd_list, SUBST_SIG, executor=executor) else: cmd_list = env.subst_list(self.cmd_list, SUBST_SIG, target, source) res = [] for cmd_line in cmd_list: if cmd_line: d = str(cmd_line[0]) m = strip_quotes.match(d) if m: d = m.group(1) d = env.WhereIs(d) if d: res.append(env.fs.File(d)) return res class CommandGeneratorAction(ActionBase): """Class for command-generator actions.""" def __init__(self, generator, kw): if __debug__: logInstanceCreation(self, 'Action.CommandGeneratorAction') self.generator = generator self.gen_kw = kw self.varlist = kw.get('varlist', ()) self.targets = kw.get('targets', '$TARGETS') def _generate(self, target, source, env, for_signature, executor=None): # ensure that target is a list, to make it easier to write # generator functions: if not is_List(target): target = [target] if executor: target = executor.get_all_targets() source = executor.get_all_sources() ret = self.generator(target=target, source=source, env=env, for_signature=for_signature) gen_cmd = Action(ret, **self.gen_kw) if not gen_cmd: raise SCons.Errors.UserError("Object returned from command generator: %s cannot be used to create an Action." % repr(ret)) return gen_cmd def __str__(self): try: env = self.presub_env except AttributeError: env = None if env is None: env = SCons.Defaults.DefaultEnvironment() act = self._generate([], [], env, 1) return str(act) def batch_key(self, env, target, source): return self._generate(target, source, env, 1).batch_key(env, target, source) def genstring(self, target, source, env, executor=None): return self._generate(target, source, env, 1, executor).genstring(target, source, env) def __call__(self, target, source, env, exitstatfunc=_null, presub=_null, show=_null, execute=_null, chdir=_null, executor=None): act = self._generate(target, source, env, 0, executor) if act is None: raise SCons.Errors.UserError("While building `%s': " "Cannot deduce file extension from source files: %s" % (repr(list(map(str, target))), repr(list(map(str, source))))) return act(target, source, env, exitstatfunc, presub, show, execute, chdir, executor) def get_presig(self, target, source, env, executor=None): """Return the signature contents of this action's command line. This strips $(-$) and everything in between the string, since those parts don't affect signatures. """ return self._generate(target, source, env, 1, executor).get_presig(target, source, env) def get_implicit_deps(self, target, source, env, executor=None): return self._generate(target, source, env, 1, executor).get_implicit_deps(target, source, env) def get_varlist(self, target, source, env, executor=None): return self._generate(target, source, env, 1, executor).get_varlist(target, source, env, executor) def get_targets(self, env, executor): return self._generate(None, None, env, 1, executor).get_targets(env, executor) # A LazyAction is a kind of hybrid generator and command action for # strings of the form "$VAR". These strings normally expand to other # strings (think "$CCCOM" to "$CC -c -o $TARGET $SOURCE"), but we also # want to be able to replace them with functions in the construction # environment. Consequently, we want lazy evaluation and creation of # an Action in the case of the function, but that's overkill in the more # normal case of expansion to other strings. # # So we do this with a subclass that's both a generator *and* # a command action. The overridden methods all do a quick check # of the construction variable, and if it's a string we just call # the corresponding CommandAction method to do the heavy lifting. # If not, then we call the same-named CommandGeneratorAction method. # The CommandGeneratorAction methods work by using the overridden # _generate() method, that is, our own way of handling "generation" of # an action based on what's in the construction variable. class LazyAction(CommandGeneratorAction, CommandAction): def __init__(self, var, kw): if __debug__: logInstanceCreation(self, 'Action.LazyAction') #FUTURE CommandAction.__init__(self, '${'+var+'}', **kw) CommandAction.__init__(self, '${'+var+'}', **kw) self.var = SCons.Util.to_String(var) self.gen_kw = kw def get_parent_class(self, env): c = env.get(self.var) if is_String(c) and not '\n' in c: return CommandAction return CommandGeneratorAction def _generate_cache(self, env): if env: c = env.get(self.var, '') else: c = '' gen_cmd = Action(c, **self.gen_kw) if not gen_cmd: raise SCons.Errors.UserError("$%s value %s cannot be used to create an Action." % (self.var, repr(c))) return gen_cmd def _generate(self, target, source, env, for_signature, executor=None): return self._generate_cache(env) def __call__(self, target, source, env, *args, **kw): c = self.get_parent_class(env) return c.__call__(self, target, source, env, *args, **kw) def get_presig(self, target, source, env): c = self.get_parent_class(env) return c.get_presig(self, target, source, env) def get_varlist(self, target, source, env, executor=None): c = self.get_parent_class(env) return c.get_varlist(self, target, source, env, executor) class FunctionAction(_ActionAction): """Class for Python function actions.""" def __init__(self, execfunction, kw): if __debug__: logInstanceCreation(self, 'Action.FunctionAction') self.execfunction = execfunction try: self.funccontents = _callable_contents(execfunction) except AttributeError: try: # See if execfunction will do the heavy lifting for us. self.gc = execfunction.get_contents except AttributeError: # This is weird, just do the best we can. self.funccontents = _object_contents(execfunction) _ActionAction.__init__(self, **kw) def function_name(self): try: return self.execfunction.__name__ except AttributeError: try: return self.execfunction.__class__.__name__ except AttributeError: return "unknown_python_function" def strfunction(self, target, source, env, executor=None): if self.cmdstr is None: return None if self.cmdstr is not _null: from SCons.Subst import SUBST_RAW if executor: c = env.subst(self.cmdstr, SUBST_RAW, executor=executor) else: c = env.subst(self.cmdstr, SUBST_RAW, target, source) if c: return c def array(a): def quote(s): try: str_for_display = s.str_for_display except AttributeError: s = repr(s) else: s = str_for_display() return s return '[' + ", ".join(map(quote, a)) + ']' try: strfunc = self.execfunction.strfunction except AttributeError: pass else: if strfunc is None: return None if callable(strfunc): return strfunc(target, source, env) name = self.function_name() tstr = array(target) sstr = array(source) return "%s(%s, %s)" % (name, tstr, sstr) def __str__(self): name = self.function_name() if name == 'ActionCaller': return str(self.execfunction) return "%s(target, source, env)" % name def execute(self, target, source, env, executor=None): exc_info = (None,None,None) try: if executor: target = executor.get_all_targets() source = executor.get_all_sources() rsources = list(map(rfile, source)) try: result = self.execfunction(target=target, source=rsources, env=env) except KeyboardInterrupt, e: raise except SystemExit, e: raise except Exception, e: result = e exc_info = sys.exc_info() if result: result = SCons.Errors.convert_to_BuildError(result, exc_info) result.node=target result.action=self try: result.command=self.strfunction(target, source, env, executor) except TypeError: result.command=self.strfunction(target, source, env) # FIXME: This maintains backward compatibility with respect to # which type of exceptions were returned by raising an # exception and which ones were returned by value. It would # probably be best to always return them by value here, but # some codes do not check the return value of Actions and I do # not have the time to modify them at this point. if (exc_info[1] and not isinstance(exc_info[1],EnvironmentError)): raise result return result finally: # Break the cycle between the traceback object and this # function stack frame. See the sys.exc_info() doc info for # more information about this issue. del exc_info def get_presig(self, target, source, env): """Return the signature contents of this callable action.""" try: return self.gc(target, source, env) except AttributeError: return self.funccontents def get_implicit_deps(self, target, source, env): return [] class ListAction(ActionBase): """Class for lists of other actions.""" def __init__(self, actionlist): if __debug__: logInstanceCreation(self, 'Action.ListAction') def list_of_actions(x): if isinstance(x, ActionBase): return x return Action(x) self.list = list(map(list_of_actions, actionlist)) # our children will have had any varlist # applied; we don't need to do it again self.varlist = () self.targets = '$TARGETS' def genstring(self, target, source, env): return '\n'.join([a.genstring(target, source, env) for a in self.list]) def __str__(self): return '\n'.join(map(str, self.list)) def presub_lines(self, env): return SCons.Util.flatten_sequence( [a.presub_lines(env) for a in self.list]) def get_presig(self, target, source, env): """Return the signature contents of this action list. Simple concatenation of the signatures of the elements. """ return "".join([x.get_contents(target, source, env) for x in self.list]) def __call__(self, target, source, env, exitstatfunc=_null, presub=_null, show=_null, execute=_null, chdir=_null, executor=None): if executor: target = executor.get_all_targets() source = executor.get_all_sources() for act in self.list: stat = act(target, source, env, exitstatfunc, presub, show, execute, chdir, executor) if stat: return stat return 0 def get_implicit_deps(self, target, source, env): result = [] for act in self.list: result.extend(act.get_implicit_deps(target, source, env)) return result def get_varlist(self, target, source, env, executor=None): result = SCons.Util.OrderedDict() for act in self.list: for var in act.get_varlist(target, source, env, executor): result[var] = True return list(result.keys()) class ActionCaller(object): """A class for delaying calling an Action function with specific (positional and keyword) arguments until the Action is actually executed. This class looks to the rest of the world like a normal Action object, but what it's really doing is hanging on to the arguments until we have a target, source and env to use for the expansion. """ def __init__(self, parent, args, kw): self.parent = parent self.args = args self.kw = kw def get_contents(self, target, source, env): actfunc = self.parent.actfunc try: # "self.actfunc" is a function. contents = str(actfunc.func_code.co_code) except AttributeError: # "self.actfunc" is a callable object. try: contents = str(actfunc.__call__.im_func.func_code.co_code) except AttributeError: # No __call__() method, so it might be a builtin # or something like that. Do the best we can. contents = str(actfunc) contents = remove_set_lineno_codes(contents) return contents def subst(self, s, target, source, env): # If s is a list, recursively apply subst() # to every element in the list if is_List(s): result = [] for elem in s: result.append(self.subst(elem, target, source, env)) return self.parent.convert(result) # Special-case hack: Let a custom function wrapped in an # ActionCaller get at the environment through which the action # was called by using this hard-coded value as a special return. if s == '$__env__': return env elif is_String(s): return env.subst(s, 1, target, source) return self.parent.convert(s) def subst_args(self, target, source, env): return [self.subst(x, target, source, env) for x in self.args] def subst_kw(self, target, source, env): kw = {} for key in self.kw.keys(): kw[key] = self.subst(self.kw[key], target, source, env) return kw def __call__(self, target, source, env, executor=None): args = self.subst_args(target, source, env) kw = self.subst_kw(target, source, env) return self.parent.actfunc(*args, **kw) def strfunction(self, target, source, env): args = self.subst_args(target, source, env) kw = self.subst_kw(target, source, env) return self.parent.strfunc(*args, **kw) def __str__(self): return self.parent.strfunc(*self.args, **self.kw) class ActionFactory(object): """A factory class that will wrap up an arbitrary function as an SCons-executable Action object. The real heavy lifting here is done by the ActionCaller class. We just collect the (positional and keyword) arguments that we're called with and give them to the ActionCaller object we create, so it can hang onto them until it needs them. """ def __init__(self, actfunc, strfunc, convert=lambda x: x): self.actfunc = actfunc self.strfunc = strfunc self.convert = convert def __call__(self, *args, **kw): ac = ActionCaller(self, args, kw) action = Action(ac, strfunction=ac.strfunction) return action # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Sig.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" __doc__ = """Place-holder for the old SCons.Sig module hierarchy This is no longer used, but code out there (such as the NSIS module on the SCons wiki) may try to import SCons.Sig. If so, we generate a warning that points them to the line that caused the import, and don't die. If someone actually tried to use the sub-modules or functions within the package (for example, SCons.Sig.MD5.signature()), then they'll still get an AttributeError, but at least they'll know where to start looking. """ import SCons.Util import SCons.Warnings msg = 'The SCons.Sig module no longer exists.\n' \ ' Remove the following "import SCons.Sig" line to eliminate this warning:' SCons.Warnings.warn(SCons.Warnings.DeprecatedSigModuleWarning, msg) default_calc = None default_module = None class MD5Null(SCons.Util.Null): def __repr__(self): return "MD5Null()" class TimeStampNull(SCons.Util.Null): def __repr__(self): return "TimeStampNull()" MD5 = MD5Null() TimeStamp = TimeStampNull() # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.SConf Autoconf-like configuration support. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/SConf.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.compat import io import os import re import sys import traceback import SCons.Action import SCons.Builder import SCons.Errors import SCons.Job import SCons.Node.FS import SCons.Taskmaster import SCons.Util import SCons.Warnings import SCons.Conftest from SCons.Debug import Trace # Turn off the Conftest error logging SCons.Conftest.LogInputFiles = 0 SCons.Conftest.LogErrorMessages = 0 # Set build_type = None build_types = ['clean', 'help'] def SetBuildType(type): global build_type build_type = type # to be set, if we are in dry-run mode dryrun = 0 AUTO=0 # use SCons dependency scanning for up-to-date checks FORCE=1 # force all tests to be rebuilt CACHE=2 # force all tests to be taken from cache (raise an error, if necessary) cache_mode = AUTO def SetCacheMode(mode): """Set the Configure cache mode. mode must be one of "auto", "force", or "cache".""" global cache_mode if mode == "auto": cache_mode = AUTO elif mode == "force": cache_mode = FORCE elif mode == "cache": cache_mode = CACHE else: raise ValueError("SCons.SConf.SetCacheMode: Unknown mode " + mode) progress_display = SCons.Util.display # will be overwritten by SCons.Script def SetProgressDisplay(display): """Set the progress display to use (called from SCons.Script)""" global progress_display progress_display = display SConfFS = None _ac_build_counter = 0 # incremented, whenever TryBuild is called _ac_config_logs = {} # all config.log files created in this build _ac_config_hs = {} # all config.h files created in this build sconf_global = None # current sconf object def _createConfigH(target, source, env): t = open(str(target[0]), "w") defname = re.sub('[^A-Za-z0-9_]', '_', str(target[0]).upper()) t.write("""#ifndef %(DEFNAME)s_SEEN #define %(DEFNAME)s_SEEN """ % {'DEFNAME' : defname}) t.write(source[0].get_contents()) t.write(""" #endif /* %(DEFNAME)s_SEEN */ """ % {'DEFNAME' : defname}) t.close() def _stringConfigH(target, source, env): return "scons: Configure: creating " + str(target[0]) def CreateConfigHBuilder(env): """Called just before the building targets phase begins.""" if len(_ac_config_hs) == 0: return action = SCons.Action.Action(_createConfigH, _stringConfigH) sconfigHBld = SCons.Builder.Builder(action=action) env.Append( BUILDERS={'SConfigHBuilder':sconfigHBld} ) for k in _ac_config_hs.keys(): env.SConfigHBuilder(k, env.Value(_ac_config_hs[k])) class SConfWarning(SCons.Warnings.Warning): pass SCons.Warnings.enableWarningClass(SConfWarning) # some error definitions class SConfError(SCons.Errors.UserError): def __init__(self,msg): SCons.Errors.UserError.__init__(self,msg) class ConfigureDryRunError(SConfError): """Raised when a file or directory needs to be updated during a Configure process, but the user requested a dry-run""" def __init__(self,target): if not isinstance(target, SCons.Node.FS.File): msg = 'Cannot create configure directory "%s" within a dry-run.' % str(target) else: msg = 'Cannot update configure test "%s" within a dry-run.' % str(target) SConfError.__init__(self,msg) class ConfigureCacheError(SConfError): """Raised when a use explicitely requested the cache feature, but the test is run the first time.""" def __init__(self,target): SConfError.__init__(self, '"%s" is not yet built and cache is forced.' % str(target)) # define actions for building text files def _createSource( target, source, env ): fd = open(str(target[0]), "w") fd.write(source[0].get_contents()) fd.close() def _stringSource( target, source, env ): return (str(target[0]) + ' <-\n |' + source[0].get_contents().replace( '\n', "\n |" ) ) class SConfBuildInfo(SCons.Node.FS.FileBuildInfo): """ Special build info for targets of configure tests. Additional members are result (did the builder succeed last time?) and string, which contains messages of the original build phase. """ result = None # -> 0/None -> no error, != 0 error string = None # the stdout / stderr output when building the target def set_build_result(self, result, string): self.result = result self.string = string class Streamer(object): """ 'Sniffer' for a file-like writable object. Similar to the unix tool tee. """ def __init__(self, orig): self.orig = orig self.s = io.StringIO() def write(self, str): if self.orig: self.orig.write(unicode(str)) self.s.write(unicode(str)) def writelines(self, lines): for l in lines: self.write(unicode(l + '\n')) def getvalue(self): """ Return everything written to orig since the Streamer was created. """ return self.s.getvalue() def flush(self): if self.orig: self.orig.flush() self.s.flush() class SConfBuildTask(SCons.Taskmaster.AlwaysTask): """ This is almost the same as SCons.Script.BuildTask. Handles SConfErrors correctly and knows about the current cache_mode. """ def display(self, message): if sconf_global.logstream: sconf_global.logstream.write("scons: Configure: " + message + "\n") def display_cached_string(self, bi): """ Logs the original builder messages, given the SConfBuildInfo instance bi. """ if not isinstance(bi, SConfBuildInfo): SCons.Warnings.warn(SConfWarning, "The stored build information has an unexpected class: %s" % bi.__class__) else: self.display("The original builder output was:\n" + (" |" + str(bi.string)).replace("\n", "\n |")) def failed(self): # check, if the reason was a ConfigureDryRunError or a # ConfigureCacheError and if yes, reraise the exception exc_type = self.exc_info()[0] if issubclass(exc_type, SConfError): raise elif issubclass(exc_type, SCons.Errors.BuildError): # we ignore Build Errors (occurs, when a test doesn't pass) # Clear the exception to prevent the contained traceback # to build a reference cycle. self.exc_clear() else: self.display('Caught exception while building "%s":\n' % self.targets[0]) try: excepthook = sys.excepthook except AttributeError: # Earlier versions of Python don't have sys.excepthook... def excepthook(type, value, tb): traceback.print_tb(tb) print type, value excepthook(*self.exc_info()) return SCons.Taskmaster.Task.failed(self) def collect_node_states(self): # returns (is_up_to_date, cached_error, cachable) # where is_up_to_date is 1, if the node(s) are up_to_date # cached_error is 1, if the node(s) are up_to_date, but the # build will fail # cachable is 0, if some nodes are not in our cache T = 0 changed = False cached_error = False cachable = True for t in self.targets: if T: Trace('%s' % (t)) bi = t.get_stored_info().binfo if isinstance(bi, SConfBuildInfo): if T: Trace(': SConfBuildInfo') if cache_mode == CACHE: t.set_state(SCons.Node.up_to_date) if T: Trace(': set_state(up_to-date)') else: if T: Trace(': get_state() %s' % t.get_state()) if T: Trace(': changed() %s' % t.changed()) if (t.get_state() != SCons.Node.up_to_date and t.changed()): changed = True if T: Trace(': changed %s' % changed) cached_error = cached_error or bi.result else: if T: Trace(': else') # the node hasn't been built in a SConf context or doesn't # exist cachable = False changed = ( t.get_state() != SCons.Node.up_to_date ) if T: Trace(': changed %s' % changed) if T: Trace('\n') return (not changed, cached_error, cachable) def execute(self): if not self.targets[0].has_builder(): return sconf = sconf_global is_up_to_date, cached_error, cachable = self.collect_node_states() if cache_mode == CACHE and not cachable: raise ConfigureCacheError(self.targets[0]) elif cache_mode == FORCE: is_up_to_date = 0 if cached_error and is_up_to_date: self.display("Building \"%s\" failed in a previous run and all " "its sources are up to date." % str(self.targets[0])) binfo = self.targets[0].get_stored_info().binfo self.display_cached_string(binfo) raise SCons.Errors.BuildError # will be 'caught' in self.failed elif is_up_to_date: self.display("\"%s\" is up to date." % str(self.targets[0])) binfo = self.targets[0].get_stored_info().binfo self.display_cached_string(binfo) elif dryrun: raise ConfigureDryRunError(self.targets[0]) else: # note stdout and stderr are the same here s = sys.stdout = sys.stderr = Streamer(sys.stdout) try: env = self.targets[0].get_build_env() if cache_mode == FORCE: # Set up the Decider() to force rebuilds by saying # that every source has changed. Note that we still # call the environment's underlying source decider so # that the correct .sconsign info will get calculated # and keep the build state consistent. def force_build(dependency, target, prev_ni, env_decider=env.decide_source): env_decider(dependency, target, prev_ni) return True if env.decide_source.func_code is not force_build.func_code: env.Decider(force_build) env['PSTDOUT'] = env['PSTDERR'] = s try: sconf.cached = 0 self.targets[0].build() finally: sys.stdout = sys.stderr = env['PSTDOUT'] = \ env['PSTDERR'] = sconf.logstream except KeyboardInterrupt: raise except SystemExit: exc_value = sys.exc_info()[1] raise SCons.Errors.ExplicitExit(self.targets[0],exc_value.code) except Exception, e: for t in self.targets: binfo = t.get_binfo() binfo.__class__ = SConfBuildInfo binfo.set_build_result(1, s.getvalue()) sconsign_entry = SCons.SConsign.SConsignEntry() sconsign_entry.binfo = binfo #sconsign_entry.ninfo = self.get_ninfo() # We'd like to do this as follows: # t.store_info(binfo) # However, we need to store it as an SConfBuildInfo # object, and store_info() will turn it into a # regular FileNodeInfo if the target is itself a # regular File. sconsign = t.dir.sconsign() sconsign.set_entry(t.name, sconsign_entry) sconsign.merge() raise e else: for t in self.targets: binfo = t.get_binfo() binfo.__class__ = SConfBuildInfo binfo.set_build_result(0, s.getvalue()) sconsign_entry = SCons.SConsign.SConsignEntry() sconsign_entry.binfo = binfo #sconsign_entry.ninfo = self.get_ninfo() # We'd like to do this as follows: # t.store_info(binfo) # However, we need to store it as an SConfBuildInfo # object, and store_info() will turn it into a # regular FileNodeInfo if the target is itself a # regular File. sconsign = t.dir.sconsign() sconsign.set_entry(t.name, sconsign_entry) sconsign.merge() class SConfBase(object): """This is simply a class to represent a configure context. After creating a SConf object, you can call any tests. After finished with your tests, be sure to call the Finish() method, which returns the modified environment. Some words about caching: In most cases, it is not necessary to cache Test results explicitely. Instead, we use the scons dependency checking mechanism. For example, if one wants to compile a test program (SConf.TryLink), the compiler is only called, if the program dependencies have changed. However, if the program could not be compiled in a former SConf run, we need to explicitely cache this error. """ def __init__(self, env, custom_tests = {}, conf_dir='$CONFIGUREDIR', log_file='$CONFIGURELOG', config_h = None, _depth = 0): """Constructor. Pass additional tests in the custom_tests-dictinary, e.g. custom_tests={'CheckPrivate':MyPrivateTest}, where MyPrivateTest defines a custom test. Note also the conf_dir and log_file arguments (you may want to build tests in the VariantDir, not in the SourceDir) """ global SConfFS if not SConfFS: SConfFS = SCons.Node.FS.default_fs or \ SCons.Node.FS.FS(env.fs.pathTop) if sconf_global is not None: raise SCons.Errors.UserError self.env = env if log_file is not None: log_file = SConfFS.File(env.subst(log_file)) self.logfile = log_file self.logstream = None self.lastTarget = None self.depth = _depth self.cached = 0 # will be set, if all test results are cached # add default tests default_tests = { 'CheckCC' : CheckCC, 'CheckCXX' : CheckCXX, 'CheckSHCC' : CheckSHCC, 'CheckSHCXX' : CheckSHCXX, 'CheckFunc' : CheckFunc, 'CheckType' : CheckType, 'CheckTypeSize' : CheckTypeSize, 'CheckDeclaration' : CheckDeclaration, 'CheckHeader' : CheckHeader, 'CheckCHeader' : CheckCHeader, 'CheckCXXHeader' : CheckCXXHeader, 'CheckLib' : CheckLib, 'CheckLibWithHeader' : CheckLibWithHeader, } self.AddTests(default_tests) self.AddTests(custom_tests) self.confdir = SConfFS.Dir(env.subst(conf_dir)) if config_h is not None: config_h = SConfFS.File(config_h) self.config_h = config_h self._startup() def Finish(self): """Call this method after finished with your tests: env = sconf.Finish() """ self._shutdown() return self.env def Define(self, name, value = None, comment = None): """ Define a pre processor symbol name, with the optional given value in the current config header. If value is None (default), then #define name is written. If value is not none, then #define name value is written. comment is a string which will be put as a C comment in the header, to explain the meaning of the value (appropriate C comments /* and */ will be put automatically.""" lines = [] if comment: comment_str = "/* %s */" % comment lines.append(comment_str) if value is not None: define_str = "#define %s %s" % (name, value) else: define_str = "#define %s" % name lines.append(define_str) lines.append('') self.config_h_text = self.config_h_text + '\n'.join(lines) def BuildNodes(self, nodes): """ Tries to build the given nodes immediately. Returns 1 on success, 0 on error. """ if self.logstream is not None: # override stdout / stderr to write in log file oldStdout = sys.stdout sys.stdout = self.logstream oldStderr = sys.stderr sys.stderr = self.logstream # the engine assumes the current path is the SConstruct directory ... old_fs_dir = SConfFS.getcwd() old_os_dir = os.getcwd() SConfFS.chdir(SConfFS.Top, change_os_dir=1) # Because we take responsibility here for writing out our # own .sconsign info (see SConfBuildTask.execute(), above), # we override the store_info() method with a null place-holder # so we really control how it gets written. for n in nodes: n.store_info = n.do_not_store_info ret = 1 try: # ToDo: use user options for calc save_max_drift = SConfFS.get_max_drift() SConfFS.set_max_drift(0) tm = SCons.Taskmaster.Taskmaster(nodes, SConfBuildTask) # we don't want to build tests in parallel jobs = SCons.Job.Jobs(1, tm ) jobs.run() for n in nodes: state = n.get_state() if (state != SCons.Node.executed and state != SCons.Node.up_to_date): # the node could not be built. we return 0 in this case ret = 0 finally: SConfFS.set_max_drift(save_max_drift) os.chdir(old_os_dir) SConfFS.chdir(old_fs_dir, change_os_dir=0) if self.logstream is not None: # restore stdout / stderr sys.stdout = oldStdout sys.stderr = oldStderr return ret def pspawn_wrapper(self, sh, escape, cmd, args, env): """Wrapper function for handling piped spawns. This looks to the calling interface (in Action.py) like a "normal" spawn, but associates the call with the PSPAWN variable from the construction environment and with the streams to which we want the output logged. This gets slid into the construction environment as the SPAWN variable so Action.py doesn't have to know or care whether it's spawning a piped command or not. """ return self.pspawn(sh, escape, cmd, args, env, self.logstream, self.logstream) def TryBuild(self, builder, text = None, extension = ""): """Low level TryBuild implementation. Normally you don't need to call that - you can use TryCompile / TryLink / TryRun instead """ global _ac_build_counter # Make sure we have a PSPAWN value, and save the current # SPAWN value. try: self.pspawn = self.env['PSPAWN'] except KeyError: raise SCons.Errors.UserError('Missing PSPAWN construction variable.') try: save_spawn = self.env['SPAWN'] except KeyError: raise SCons.Errors.UserError('Missing SPAWN construction variable.') nodesToBeBuilt = [] f = "conftest_" + str(_ac_build_counter) pref = self.env.subst( builder.builder.prefix ) suff = self.env.subst( builder.builder.suffix ) target = self.confdir.File(pref + f + suff) try: # Slide our wrapper into the construction environment as # the SPAWN function. self.env['SPAWN'] = self.pspawn_wrapper sourcetext = self.env.Value(text) if text is not None: textFile = self.confdir.File(f + extension) textFileNode = self.env.SConfSourceBuilder(target=textFile, source=sourcetext) nodesToBeBuilt.extend(textFileNode) source = textFileNode else: source = None nodes = builder(target = target, source = source) if not SCons.Util.is_List(nodes): nodes = [nodes] nodesToBeBuilt.extend(nodes) result = self.BuildNodes(nodesToBeBuilt) finally: self.env['SPAWN'] = save_spawn _ac_build_counter = _ac_build_counter + 1 if result: self.lastTarget = nodes[0] else: self.lastTarget = None return result def TryAction(self, action, text = None, extension = ""): """Tries to execute the given action with optional source file contents <text> and optional source file extension <extension>, Returns the status (0 : failed, 1 : ok) and the contents of the output file. """ builder = SCons.Builder.Builder(action=action) self.env.Append( BUILDERS = {'SConfActionBuilder' : builder} ) ok = self.TryBuild(self.env.SConfActionBuilder, text, extension) del self.env['BUILDERS']['SConfActionBuilder'] if ok: outputStr = self.lastTarget.get_contents() return (1, outputStr) return (0, "") def TryCompile( self, text, extension): """Compiles the program given in text to an env.Object, using extension as file extension (e.g. '.c'). Returns 1, if compilation was successful, 0 otherwise. The target is saved in self.lastTarget (for further processing). """ return self.TryBuild(self.env.Object, text, extension) def TryLink( self, text, extension ): """Compiles the program given in text to an executable env.Program, using extension as file extension (e.g. '.c'). Returns 1, if compilation was successful, 0 otherwise. The target is saved in self.lastTarget (for further processing). """ return self.TryBuild(self.env.Program, text, extension ) def TryRun(self, text, extension ): """Compiles and runs the program given in text, using extension as file extension (e.g. '.c'). Returns (1, outputStr) on success, (0, '') otherwise. The target (a file containing the program's stdout) is saved in self.lastTarget (for further processing). """ ok = self.TryLink(text, extension) if( ok ): prog = self.lastTarget pname = prog.path output = self.confdir.File(os.path.basename(pname)+'.out') node = self.env.Command(output, prog, [ [ pname, ">", "${TARGET}"] ]) ok = self.BuildNodes(node) if ok: outputStr = output.get_contents() return( 1, outputStr) return (0, "") class TestWrapper(object): """A wrapper around Tests (to ensure sanity)""" def __init__(self, test, sconf): self.test = test self.sconf = sconf def __call__(self, *args, **kw): if not self.sconf.active: raise SCons.Errors.UserError context = CheckContext(self.sconf) ret = self.test(context, *args, **kw) if self.sconf.config_h is not None: self.sconf.config_h_text = self.sconf.config_h_text + context.config_h context.Result("error: no result") return ret def AddTest(self, test_name, test_instance): """Adds test_class to this SConf instance. It can be called with self.test_name(...)""" setattr(self, test_name, SConfBase.TestWrapper(test_instance, self)) def AddTests(self, tests): """Adds all the tests given in the tests dictionary to this SConf instance """ for name in tests.keys(): self.AddTest(name, tests[name]) def _createDir( self, node ): dirName = str(node) if dryrun: if not os.path.isdir( dirName ): raise ConfigureDryRunError(dirName) else: if not os.path.isdir( dirName ): os.makedirs( dirName ) node._exists = 1 def _startup(self): """Private method. Set up logstream, and set the environment variables necessary for a piped build """ global _ac_config_logs global sconf_global global SConfFS self.lastEnvFs = self.env.fs self.env.fs = SConfFS self._createDir(self.confdir) self.confdir.up().add_ignore( [self.confdir] ) if self.logfile is not None and not dryrun: # truncate logfile, if SConf.Configure is called for the first time # in a build if self.logfile in _ac_config_logs: log_mode = "a" else: _ac_config_logs[self.logfile] = None log_mode = "w" fp = open(str(self.logfile), log_mode) self.logstream = SCons.Util.Unbuffered(fp) # logfile may stay in a build directory, so we tell # the build system not to override it with a eventually # existing file with the same name in the source directory self.logfile.dir.add_ignore( [self.logfile] ) tb = traceback.extract_stack()[-3-self.depth] old_fs_dir = SConfFS.getcwd() SConfFS.chdir(SConfFS.Top, change_os_dir=0) self.logstream.write('file %s,line %d:\n\tConfigure(confdir = %s)\n' % (tb[0], tb[1], str(self.confdir)) ) SConfFS.chdir(old_fs_dir) else: self.logstream = None # we use a special builder to create source files from TEXT action = SCons.Action.Action(_createSource, _stringSource) sconfSrcBld = SCons.Builder.Builder(action=action) self.env.Append( BUILDERS={'SConfSourceBuilder':sconfSrcBld} ) self.config_h_text = _ac_config_hs.get(self.config_h, "") self.active = 1 # only one SConf instance should be active at a time ... sconf_global = self def _shutdown(self): """Private method. Reset to non-piped spawn""" global sconf_global, _ac_config_hs if not self.active: raise SCons.Errors.UserError("Finish may be called only once!") if self.logstream is not None and not dryrun: self.logstream.write("\n") self.logstream.close() self.logstream = None # remove the SConfSourceBuilder from the environment blds = self.env['BUILDERS'] del blds['SConfSourceBuilder'] self.env.Replace( BUILDERS=blds ) self.active = 0 sconf_global = None if not self.config_h is None: _ac_config_hs[self.config_h] = self.config_h_text self.env.fs = self.lastEnvFs class CheckContext(object): """Provides a context for configure tests. Defines how a test writes to the screen and log file. A typical test is just a callable with an instance of CheckContext as first argument: def CheckCustom(context, ...) context.Message('Checking my weird test ... ') ret = myWeirdTestFunction(...) context.Result(ret) Often, myWeirdTestFunction will be one of context.TryCompile/context.TryLink/context.TryRun. The results of those are cached, for they are only rebuild, if the dependencies have changed. """ def __init__(self, sconf): """Constructor. Pass the corresponding SConf instance.""" self.sconf = sconf self.did_show_result = 0 # for Conftest.py: self.vardict = {} self.havedict = {} self.headerfilename = None self.config_h = "" # config_h text will be stored here # we don't regenerate the config.h file after each test. That means, # that tests won't be able to include the config.h file, and so # they can't do an #ifdef HAVE_XXX_H. This shouldn't be a major # issue, though. If it turns out, that we need to include config.h # in tests, we must ensure, that the dependencies are worked out # correctly. Note that we can't use Conftest.py's support for config.h, # cause we will need to specify a builder for the config.h file ... def Message(self, text): """Inform about what we are doing right now, e.g. 'Checking for SOMETHING ... ' """ self.Display(text) self.sconf.cached = 1 self.did_show_result = 0 def Result(self, res): """Inform about the result of the test. res may be an integer or a string. In case of an integer, the written text will be 'yes' or 'no'. The result is only displayed when self.did_show_result is not set. """ if isinstance(res, (int, bool)): if res: text = "yes" else: text = "no" elif isinstance(res, str): text = res else: raise TypeError("Expected string, int or bool, got " + str(type(res))) if self.did_show_result == 0: # Didn't show result yet, do it now. self.Display(text + "\n") self.did_show_result = 1 def TryBuild(self, *args, **kw): return self.sconf.TryBuild(*args, **kw) def TryAction(self, *args, **kw): return self.sconf.TryAction(*args, **kw) def TryCompile(self, *args, **kw): return self.sconf.TryCompile(*args, **kw) def TryLink(self, *args, **kw): return self.sconf.TryLink(*args, **kw) def TryRun(self, *args, **kw): return self.sconf.TryRun(*args, **kw) def __getattr__( self, attr ): if( attr == 'env' ): return self.sconf.env elif( attr == 'lastTarget' ): return self.sconf.lastTarget else: raise AttributeError("CheckContext instance has no attribute '%s'" % attr) #### Stuff used by Conftest.py (look there for explanations). def BuildProg(self, text, ext): self.sconf.cached = 1 # TODO: should use self.vardict for $CC, $CPPFLAGS, etc. return not self.TryBuild(self.env.Program, text, ext) def CompileProg(self, text, ext): self.sconf.cached = 1 # TODO: should use self.vardict for $CC, $CPPFLAGS, etc. return not self.TryBuild(self.env.Object, text, ext) def CompileSharedObject(self, text, ext): self.sconf.cached = 1 # TODO: should use self.vardict for $SHCC, $CPPFLAGS, etc. return not self.TryBuild(self.env.SharedObject, text, ext) def RunProg(self, text, ext): self.sconf.cached = 1 # TODO: should use self.vardict for $CC, $CPPFLAGS, etc. st, out = self.TryRun(text, ext) return not st, out def AppendLIBS(self, lib_name_list): oldLIBS = self.env.get( 'LIBS', [] ) self.env.Append(LIBS = lib_name_list) return oldLIBS def PrependLIBS(self, lib_name_list): oldLIBS = self.env.get( 'LIBS', [] ) self.env.Prepend(LIBS = lib_name_list) return oldLIBS def SetLIBS(self, val): oldLIBS = self.env.get( 'LIBS', [] ) self.env.Replace(LIBS = val) return oldLIBS def Display(self, msg): if self.sconf.cached: # We assume that Display is called twice for each test here # once for the Checking for ... message and once for the result. # The self.sconf.cached flag can only be set between those calls msg = "(cached) " + msg self.sconf.cached = 0 progress_display(msg, append_newline=0) self.Log("scons: Configure: " + msg + "\n") def Log(self, msg): if self.sconf.logstream is not None: self.sconf.logstream.write(msg) #### End of stuff used by Conftest.py. def SConf(*args, **kw): if kw.get(build_type, True): kw['_depth'] = kw.get('_depth', 0) + 1 for bt in build_types: try: del kw[bt] except KeyError: pass return SConfBase(*args, **kw) else: return SCons.Util.Null() def CheckFunc(context, function_name, header = None, language = None): res = SCons.Conftest.CheckFunc(context, function_name, header = header, language = language) context.did_show_result = 1 return not res def CheckType(context, type_name, includes = "", language = None): res = SCons.Conftest.CheckType(context, type_name, header = includes, language = language) context.did_show_result = 1 return not res def CheckTypeSize(context, type_name, includes = "", language = None, expect = None): res = SCons.Conftest.CheckTypeSize(context, type_name, header = includes, language = language, expect = expect) context.did_show_result = 1 return res def CheckDeclaration(context, declaration, includes = "", language = None): res = SCons.Conftest.CheckDeclaration(context, declaration, includes = includes, language = language) context.did_show_result = 1 return not res def createIncludesFromHeaders(headers, leaveLast, include_quotes = '""'): # used by CheckHeader and CheckLibWithHeader to produce C - #include # statements from the specified header (list) if not SCons.Util.is_List(headers): headers = [headers] l = [] if leaveLast: lastHeader = headers[-1] headers = headers[:-1] else: lastHeader = None for s in headers: l.append("#include %s%s%s\n" % (include_quotes[0], s, include_quotes[1])) return ''.join(l), lastHeader def CheckHeader(context, header, include_quotes = '<>', language = None): """ A test for a C or C++ header file. """ prog_prefix, hdr_to_check = \ createIncludesFromHeaders(header, 1, include_quotes) res = SCons.Conftest.CheckHeader(context, hdr_to_check, prog_prefix, language = language, include_quotes = include_quotes) context.did_show_result = 1 return not res def CheckCC(context): res = SCons.Conftest.CheckCC(context) context.did_show_result = 1 return not res def CheckCXX(context): res = SCons.Conftest.CheckCXX(context) context.did_show_result = 1 return not res def CheckSHCC(context): res = SCons.Conftest.CheckSHCC(context) context.did_show_result = 1 return not res def CheckSHCXX(context): res = SCons.Conftest.CheckSHCXX(context) context.did_show_result = 1 return not res # Bram: Make this function obsolete? CheckHeader() is more generic. def CheckCHeader(context, header, include_quotes = '""'): """ A test for a C header file. """ return CheckHeader(context, header, include_quotes, language = "C") # Bram: Make this function obsolete? CheckHeader() is more generic. def CheckCXXHeader(context, header, include_quotes = '""'): """ A test for a C++ header file. """ return CheckHeader(context, header, include_quotes, language = "C++") def CheckLib(context, library = None, symbol = "main", header = None, language = None, autoadd = 1): """ A test for a library. See also CheckLibWithHeader. Note that library may also be None to test whether the given symbol compiles without flags. """ if library == []: library = [None] if not SCons.Util.is_List(library): library = [library] # ToDo: accept path for the library res = SCons.Conftest.CheckLib(context, library, symbol, header = header, language = language, autoadd = autoadd) context.did_show_result = 1 return not res # XXX # Bram: Can only include one header and can't use #ifdef HAVE_HEADER_H. def CheckLibWithHeader(context, libs, header, language, call = None, autoadd = 1): # ToDo: accept path for library. Support system header files. """ Another (more sophisticated) test for a library. Checks, if library and header is available for language (may be 'C' or 'CXX'). Call maybe be a valid expression _with_ a trailing ';'. As in CheckLib, we support library=None, to test if the call compiles without extra link flags. """ prog_prefix, dummy = \ createIncludesFromHeaders(header, 0) if libs == []: libs = [None] if not SCons.Util.is_List(libs): libs = [libs] res = SCons.Conftest.CheckLib(context, libs, None, prog_prefix, call = call, language = language, autoadd = autoadd) context.did_show_result = 1 return not res # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Builder Builder object subsystem. A Builder object is a callable that encapsulates information about how to execute actions to create a target Node (file) from source Nodes (files), and how to create those dependencies for tracking. The main entry point here is the Builder() factory method. This provides a procedural interface that creates the right underlying Builder object based on the keyword arguments supplied and the types of the arguments. The goal is for this external interface to be simple enough that the vast majority of users can create new Builders as necessary to support building new types of files in their configurations, without having to dive any deeper into this subsystem. The base class here is BuilderBase. This is a concrete base class which does, in fact, represent the Builder objects that we (or users) create. There is also a proxy that looks like a Builder: CompositeBuilder This proxies for a Builder with an action that is actually a dictionary that knows how to map file suffixes to a specific action. This is so that we can invoke different actions (compilers, compile options) for different flavors of source files. Builders and their proxies have the following public interface methods used by other modules: __call__() THE public interface. Calling a Builder object (with the use of internal helper methods) sets up the target and source dependencies, appropriate mapping to a specific action, and the environment manipulation necessary for overridden construction variable. This also takes care of warning about possible mistakes in keyword arguments. add_emitter() Adds an emitter for a specific file suffix, used by some Tool modules to specify that (for example) a yacc invocation on a .y can create a .h *and* a .c file. add_action() Adds an action for a specific file suffix, heavily used by Tool modules to add their specific action(s) for turning a source file into an object file to the global static and shared object file Builders. There are the following methods for internal use within this module: _execute() The internal method that handles the heavily lifting when a Builder is called. This is used so that the __call__() methods can set up warning about possible mistakes in keyword-argument overrides, and *then* execute all of the steps necessary so that the warnings only occur once. get_name() Returns the Builder's name within a specific Environment, primarily used to try to return helpful information in error messages. adjust_suffix() get_prefix() get_suffix() get_src_suffix() set_src_suffix() Miscellaneous stuff for handling the prefix and suffix manipulation we use in turning source file names into target file names. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. __revision__ = "src/engine/SCons/Builder.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import collections import SCons.Action from SCons.Debug import logInstanceCreation from SCons.Errors import InternalError, UserError import SCons.Executor import SCons.Memoize import SCons.Node import SCons.Node.FS import SCons.Util import SCons.Warnings class _Null(object): pass _null = _Null def match_splitext(path, suffixes = []): if suffixes: matchsuf = [S for S in suffixes if path[-len(S):] == S] if matchsuf: suf = max([(len(_f),_f) for _f in matchsuf])[1] return [path[:-len(suf)], path[-len(suf):]] return SCons.Util.splitext(path) class DictCmdGenerator(SCons.Util.Selector): """This is a callable class that can be used as a command generator function. It holds on to a dictionary mapping file suffixes to Actions. It uses that dictionary to return the proper action based on the file suffix of the source file.""" def __init__(self, dict=None, source_ext_match=1): SCons.Util.Selector.__init__(self, dict) self.source_ext_match = source_ext_match def src_suffixes(self): return list(self.keys()) def add_action(self, suffix, action): """Add a suffix-action pair to the mapping. """ self[suffix] = action def __call__(self, target, source, env, for_signature): if not source: return [] if self.source_ext_match: suffixes = self.src_suffixes() ext = None for src in map(str, source): my_ext = match_splitext(src, suffixes)[1] if ext and my_ext != ext: raise UserError("While building `%s' from `%s': Cannot build multiple sources with different extensions: %s, %s" % (repr(list(map(str, target))), src, ext, my_ext)) ext = my_ext else: ext = match_splitext(str(source[0]), self.src_suffixes())[1] if not ext: #return ext raise UserError("While building `%s': " "Cannot deduce file extension from source files: %s" % (repr(list(map(str, target))), repr(list(map(str, source))))) try: ret = SCons.Util.Selector.__call__(self, env, source, ext) except KeyError, e: raise UserError("Ambiguous suffixes after environment substitution: %s == %s == %s" % (e.args[0], e.args[1], e.args[2])) if ret is None: raise UserError("While building `%s' from `%s': Don't know how to build from a source file with suffix `%s'. Expected a suffix in this list: %s." % \ (repr(list(map(str, target))), repr(list(map(str, source))), ext, repr(list(self.keys())))) return ret class CallableSelector(SCons.Util.Selector): """A callable dictionary that will, in turn, call the value it finds if it can.""" def __call__(self, env, source): value = SCons.Util.Selector.__call__(self, env, source) if callable(value): value = value(env, source) return value class DictEmitter(SCons.Util.Selector): """A callable dictionary that maps file suffixes to emitters. When called, it finds the right emitter in its dictionary for the suffix of the first source file, and calls that emitter to get the right lists of targets and sources to return. If there's no emitter for the suffix in its dictionary, the original target and source are returned. """ def __call__(self, target, source, env): emitter = SCons.Util.Selector.__call__(self, env, source) if emitter: target, source = emitter(target, source, env) return (target, source) class ListEmitter(collections.UserList): """A callable list of emitters that calls each in sequence, returning the result. """ def __call__(self, target, source, env): for e in self.data: target, source = e(target, source, env) return (target, source) # These are a common errors when calling a Builder; # they are similar to the 'target' and 'source' keyword args to builders, # so we issue warnings when we see them. The warnings can, of course, # be disabled. misleading_keywords = { 'targets' : 'target', 'sources' : 'source', } class OverrideWarner(collections.UserDict): """A class for warning about keyword arguments that we use as overrides in a Builder call. This class exists to handle the fact that a single Builder call can actually invoke multiple builders. This class only emits the warnings once, no matter how many Builders are invoked. """ def __init__(self, dict): collections.UserDict.__init__(self, dict) if __debug__: logInstanceCreation(self, 'Builder.OverrideWarner') self.already_warned = None def warn(self): if self.already_warned: return for k in self.keys(): if k in misleading_keywords: alt = misleading_keywords[k] msg = "Did you mean to use `%s' instead of `%s'?" % (alt, k) SCons.Warnings.warn(SCons.Warnings.MisleadingKeywordsWarning, msg) self.already_warned = 1 def Builder(**kw): """A factory for builder objects.""" composite = None if 'generator' in kw: if 'action' in kw: raise UserError("You must not specify both an action and a generator.") kw['action'] = SCons.Action.CommandGeneratorAction(kw['generator'], {}) del kw['generator'] elif 'action' in kw: source_ext_match = kw.get('source_ext_match', 1) if 'source_ext_match' in kw: del kw['source_ext_match'] if SCons.Util.is_Dict(kw['action']): composite = DictCmdGenerator(kw['action'], source_ext_match) kw['action'] = SCons.Action.CommandGeneratorAction(composite, {}) kw['src_suffix'] = composite.src_suffixes() else: kw['action'] = SCons.Action.Action(kw['action']) if 'emitter' in kw: emitter = kw['emitter'] if SCons.Util.is_String(emitter): # This allows users to pass in an Environment # variable reference (like "$FOO") as an emitter. # We will look in that Environment variable for # a callable to use as the actual emitter. var = SCons.Util.get_environment_var(emitter) if not var: raise UserError("Supplied emitter '%s' does not appear to refer to an Environment variable" % emitter) kw['emitter'] = EmitterProxy(var) elif SCons.Util.is_Dict(emitter): kw['emitter'] = DictEmitter(emitter) elif SCons.Util.is_List(emitter): kw['emitter'] = ListEmitter(emitter) result = BuilderBase(**kw) if not composite is None: result = CompositeBuilder(result, composite) return result def _node_errors(builder, env, tlist, slist): """Validate that the lists of target and source nodes are legal for this builder and environment. Raise errors or issue warnings as appropriate. """ # First, figure out if there are any errors in the way the targets # were specified. for t in tlist: if t.side_effect: raise UserError("Multiple ways to build the same target were specified for: %s" % t) if t.has_explicit_builder(): if not t.env is None and not t.env is env: action = t.builder.action t_contents = action.get_contents(tlist, slist, t.env) contents = action.get_contents(tlist, slist, env) if t_contents == contents: msg = "Two different environments were specified for target %s,\n\tbut they appear to have the same action: %s" % (t, action.genstring(tlist, slist, t.env)) SCons.Warnings.warn(SCons.Warnings.DuplicateEnvironmentWarning, msg) else: msg = "Two environments with different actions were specified for the same target: %s" % t raise UserError(msg) if builder.multi: if t.builder != builder: msg = "Two different builders (%s and %s) were specified for the same target: %s" % (t.builder.get_name(env), builder.get_name(env), t) raise UserError(msg) # TODO(batch): list constructed each time! if t.get_executor().get_all_targets() != tlist: msg = "Two different target lists have a target in common: %s (from %s and from %s)" % (t, list(map(str, t.get_executor().get_all_targets())), list(map(str, tlist))) raise UserError(msg) elif t.sources != slist: msg = "Multiple ways to build the same target were specified for: %s (from %s and from %s)" % (t, list(map(str, t.sources)), list(map(str, slist))) raise UserError(msg) if builder.single_source: if len(slist) > 1: raise UserError("More than one source given for single-source builder: targets=%s sources=%s" % (list(map(str,tlist)), list(map(str,slist)))) class EmitterProxy(object): """This is a callable class that can act as a Builder emitter. It holds on to a string that is a key into an Environment dictionary, and will look there at actual build time to see if it holds a callable. If so, we will call that as the actual emitter.""" def __init__(self, var): self.var = SCons.Util.to_String(var) def __call__(self, target, source, env): emitter = self.var # Recursively substitute the variable. # We can't use env.subst() because it deals only # in strings. Maybe we should change that? while SCons.Util.is_String(emitter) and emitter in env: emitter = env[emitter] if callable(emitter): target, source = emitter(target, source, env) elif SCons.Util.is_List(emitter): for e in emitter: target, source = e(target, source, env) return (target, source) def __cmp__(self, other): return cmp(self.var, other.var) class BuilderBase(object): """Base class for Builders, objects that create output nodes (files) from input nodes (files). """ if SCons.Memoize.use_memoizer: __metaclass__ = SCons.Memoize.Memoized_Metaclass memoizer_counters = [] def __init__(self, action = None, prefix = '', suffix = '', src_suffix = '', target_factory = None, source_factory = None, target_scanner = None, source_scanner = None, emitter = None, multi = 0, env = None, single_source = 0, name = None, chdir = _null, is_explicit = 1, src_builder = None, ensure_suffix = False, **overrides): if __debug__: logInstanceCreation(self, 'Builder.BuilderBase') self._memo = {} self.action = action self.multi = multi if SCons.Util.is_Dict(prefix): prefix = CallableSelector(prefix) self.prefix = prefix if SCons.Util.is_Dict(suffix): suffix = CallableSelector(suffix) self.env = env self.single_source = single_source if 'overrides' in overrides: SCons.Warnings.warn(SCons.Warnings.DeprecatedBuilderKeywordsWarning, "The \"overrides\" keyword to Builder() creation has been deprecated;\n" +\ "\tspecify the items as keyword arguments to the Builder() call instead.") overrides.update(overrides['overrides']) del overrides['overrides'] if 'scanner' in overrides: SCons.Warnings.warn(SCons.Warnings.DeprecatedBuilderKeywordsWarning, "The \"scanner\" keyword to Builder() creation has been deprecated;\n" "\tuse: source_scanner or target_scanner as appropriate.") del overrides['scanner'] self.overrides = overrides self.set_suffix(suffix) self.set_src_suffix(src_suffix) self.ensure_suffix = ensure_suffix self.target_factory = target_factory self.source_factory = source_factory self.target_scanner = target_scanner self.source_scanner = source_scanner self.emitter = emitter # Optional Builder name should only be used for Builders # that don't get attached to construction environments. if name: self.name = name self.executor_kw = {} if not chdir is _null: self.executor_kw['chdir'] = chdir self.is_explicit = is_explicit if src_builder is None: src_builder = [] elif not SCons.Util.is_List(src_builder): src_builder = [ src_builder ] self.src_builder = src_builder def __nonzero__(self): raise InternalError("Do not test for the Node.builder attribute directly; use Node.has_builder() instead") def get_name(self, env): """Attempts to get the name of the Builder. Look at the BUILDERS variable of env, expecting it to be a dictionary containing this Builder, and return the key of the dictionary. If there's no key, then return a directly-configured name (if there is one) or the name of the class (by default).""" try: index = list(env['BUILDERS'].values()).index(self) return list(env['BUILDERS'].keys())[index] except (AttributeError, KeyError, TypeError, ValueError): try: return self.name except AttributeError: return str(self.__class__) def __cmp__(self, other): return cmp(self.__dict__, other.__dict__) def splitext(self, path, env=None): if not env: env = self.env if env: suffixes = self.src_suffixes(env) else: suffixes = [] return match_splitext(path, suffixes) def _adjustixes(self, files, pre, suf, ensure_suffix=False): if not files: return [] result = [] if not SCons.Util.is_List(files): files = [files] for f in files: if SCons.Util.is_String(f): f = SCons.Util.adjustixes(f, pre, suf, ensure_suffix) result.append(f) return result def _create_nodes(self, env, target = None, source = None): """Create and return lists of target and source nodes. """ src_suf = self.get_src_suffix(env) target_factory = env.get_factory(self.target_factory) source_factory = env.get_factory(self.source_factory) source = self._adjustixes(source, None, src_suf) slist = env.arg2nodes(source, source_factory) pre = self.get_prefix(env, slist) suf = self.get_suffix(env, slist) if target is None: try: t_from_s = slist[0].target_from_source except AttributeError: raise UserError("Do not know how to create a target from source `%s'" % slist[0]) except IndexError: tlist = [] else: splitext = lambda S: self.splitext(S,env) tlist = [ t_from_s(pre, suf, splitext) ] else: target = self._adjustixes(target, pre, suf, self.ensure_suffix) tlist = env.arg2nodes(target, target_factory, target=target, source=source) if self.emitter: # The emitter is going to do str(node), but because we're # being called *from* a builder invocation, the new targets # don't yet have a builder set on them and will look like # source files. Fool the emitter's str() calls by setting # up a temporary builder on the new targets. new_targets = [] for t in tlist: if not t.is_derived(): t.builder_set(self) new_targets.append(t) orig_tlist = tlist[:] orig_slist = slist[:] target, source = self.emitter(target=tlist, source=slist, env=env) # Now delete the temporary builders that we attached to any # new targets, so that _node_errors() doesn't do weird stuff # to them because it thinks they already have builders. for t in new_targets: if t.builder is self: # Only delete the temporary builder if the emitter # didn't change it on us. t.builder_set(None) # Have to call arg2nodes yet again, since it is legal for # emitters to spit out strings as well as Node instances. tlist = env.arg2nodes(target, target_factory, target=orig_tlist, source=orig_slist) slist = env.arg2nodes(source, source_factory, target=orig_tlist, source=orig_slist) return tlist, slist def _execute(self, env, target, source, overwarn={}, executor_kw={}): # We now assume that target and source are lists or None. if self.src_builder: source = self.src_builder_sources(env, source, overwarn) if self.single_source and len(source) > 1 and target is None: result = [] if target is None: target = [None]*len(source) for tgt, src in zip(target, source): if not tgt is None: tgt = [tgt] if not src is None: src = [src] result.extend(self._execute(env, tgt, src, overwarn)) return SCons.Node.NodeList(result) overwarn.warn() tlist, slist = self._create_nodes(env, target, source) # Check for errors with the specified target/source lists. _node_errors(self, env, tlist, slist) # The targets are fine, so find or make the appropriate Executor to # build this particular list of targets from this particular list of # sources. executor = None key = None if self.multi: try: executor = tlist[0].get_executor(create = 0) except (AttributeError, IndexError): pass else: executor.add_sources(slist) if executor is None: if not self.action: fmt = "Builder %s must have an action to build %s." raise UserError(fmt % (self.get_name(env or self.env), list(map(str,tlist)))) key = self.action.batch_key(env or self.env, tlist, slist) if key: try: executor = SCons.Executor.GetBatchExecutor(key) except KeyError: pass else: executor.add_batch(tlist, slist) if executor is None: executor = SCons.Executor.Executor(self.action, env, [], tlist, slist, executor_kw) if key: SCons.Executor.AddBatchExecutor(key, executor) # Now set up the relevant information in the target Nodes themselves. for t in tlist: t.cwd = env.fs.getcwd() t.builder_set(self) t.env_set(env) t.add_source(slist) t.set_executor(executor) t.set_explicit(self.is_explicit) return SCons.Node.NodeList(tlist) def __call__(self, env, target=None, source=None, chdir=_null, **kw): # We now assume that target and source are lists or None. # The caller (typically Environment.BuilderWrapper) is # responsible for converting any scalar values to lists. if chdir is _null: ekw = self.executor_kw else: ekw = self.executor_kw.copy() ekw['chdir'] = chdir if kw: if 'srcdir' in kw: def prependDirIfRelative(f, srcdir=kw['srcdir']): import os.path if SCons.Util.is_String(f) and not os.path.isabs(f): f = os.path.join(srcdir, f) return f if not SCons.Util.is_List(source): source = [source] source = list(map(prependDirIfRelative, source)) del kw['srcdir'] if self.overrides: env_kw = self.overrides.copy() env_kw.update(kw) else: env_kw = kw else: env_kw = self.overrides env = env.Override(env_kw) return self._execute(env, target, source, OverrideWarner(kw), ekw) def adjust_suffix(self, suff): if suff and not suff[0] in [ '.', '_', '$' ]: return '.' + suff return suff def get_prefix(self, env, sources=[]): prefix = self.prefix if callable(prefix): prefix = prefix(env, sources) return env.subst(prefix) def set_suffix(self, suffix): if not callable(suffix): suffix = self.adjust_suffix(suffix) self.suffix = suffix def get_suffix(self, env, sources=[]): suffix = self.suffix if callable(suffix): suffix = suffix(env, sources) return env.subst(suffix) def set_src_suffix(self, src_suffix): if not src_suffix: src_suffix = [] elif not SCons.Util.is_List(src_suffix): src_suffix = [ src_suffix ] self.src_suffix = [callable(suf) and suf or self.adjust_suffix(suf) for suf in src_suffix] def get_src_suffix(self, env): """Get the first src_suffix in the list of src_suffixes.""" ret = self.src_suffixes(env) if not ret: return '' return ret[0] def add_emitter(self, suffix, emitter): """Add a suffix-emitter mapping to this Builder. This assumes that emitter has been initialized with an appropriate dictionary type, and will throw a TypeError if not, so the caller is responsible for knowing that this is an appropriate method to call for the Builder in question. """ self.emitter[suffix] = emitter def add_src_builder(self, builder): """ Add a new Builder to the list of src_builders. This requires wiping out cached values so that the computed lists of source suffixes get re-calculated. """ self._memo = {} self.src_builder.append(builder) def _get_sdict(self, env): """ Returns a dictionary mapping all of the source suffixes of all src_builders of this Builder to the underlying Builder that should be called first. This dictionary is used for each target specified, so we save a lot of extra computation by memoizing it for each construction environment. Note that this is re-computed each time, not cached, because there might be changes to one of our source Builders (or one of their source Builders, and so on, and so on...) that we can't "see." The underlying methods we call cache their computed values, though, so we hope repeatedly aggregating them into a dictionary like this won't be too big a hit. We may need to look for a better way to do this if performance data show this has turned into a significant bottleneck. """ sdict = {} for bld in self.get_src_builders(env): for suf in bld.src_suffixes(env): sdict[suf] = bld return sdict def src_builder_sources(self, env, source, overwarn={}): sdict = self._get_sdict(env) src_suffixes = self.src_suffixes(env) lengths = list(set(map(len, src_suffixes))) def match_src_suffix(name, src_suffixes=src_suffixes, lengths=lengths): node_suffixes = [name[-l:] for l in lengths] for suf in src_suffixes: if suf in node_suffixes: return suf return None result = [] for s in SCons.Util.flatten(source): if SCons.Util.is_String(s): match_suffix = match_src_suffix(env.subst(s)) if not match_suffix and not '.' in s: src_suf = self.get_src_suffix(env) s = self._adjustixes(s, None, src_suf)[0] else: match_suffix = match_src_suffix(s.name) if match_suffix: try: bld = sdict[match_suffix] except KeyError: result.append(s) else: tlist = bld._execute(env, None, [s], overwarn) # If the subsidiary Builder returned more than one # target, then filter out any sources that this # Builder isn't capable of building. if len(tlist) > 1: tlist = [t for t in tlist if match_src_suffix(t.name)] result.extend(tlist) else: result.append(s) source_factory = env.get_factory(self.source_factory) return env.arg2nodes(result, source_factory) def _get_src_builders_key(self, env): return id(env) memoizer_counters.append(SCons.Memoize.CountDict('get_src_builders', _get_src_builders_key)) def get_src_builders(self, env): """ Returns the list of source Builders for this Builder. This exists mainly to look up Builders referenced as strings in the 'BUILDER' variable of the construction environment and cache the result. """ memo_key = id(env) try: memo_dict = self._memo['get_src_builders'] except KeyError: memo_dict = {} self._memo['get_src_builders'] = memo_dict else: try: return memo_dict[memo_key] except KeyError: pass builders = [] for bld in self.src_builder: if SCons.Util.is_String(bld): try: bld = env['BUILDERS'][bld] except KeyError: continue builders.append(bld) memo_dict[memo_key] = builders return builders def _subst_src_suffixes_key(self, env): return id(env) memoizer_counters.append(SCons.Memoize.CountDict('subst_src_suffixes', _subst_src_suffixes_key)) def subst_src_suffixes(self, env): """ The suffix list may contain construction variable expansions, so we have to evaluate the individual strings. To avoid doing this over and over, we memoize the results for each construction environment. """ memo_key = id(env) try: memo_dict = self._memo['subst_src_suffixes'] except KeyError: memo_dict = {} self._memo['subst_src_suffixes'] = memo_dict else: try: return memo_dict[memo_key] except KeyError: pass suffixes = [env.subst(x) for x in self.src_suffix] memo_dict[memo_key] = suffixes return suffixes def src_suffixes(self, env): """ Returns the list of source suffixes for all src_builders of this Builder. This is essentially a recursive descent of the src_builder "tree." (This value isn't cached because there may be changes in a src_builder many levels deep that we can't see.) """ sdict = {} suffixes = self.subst_src_suffixes(env) for s in suffixes: sdict[s] = 1 for builder in self.get_src_builders(env): for s in builder.src_suffixes(env): if s not in sdict: sdict[s] = 1 suffixes.append(s) return suffixes class CompositeBuilder(SCons.Util.Proxy): """A Builder Proxy whose main purpose is to always have a DictCmdGenerator as its action, and to provide access to the DictCmdGenerator's add_action() method. """ def __init__(self, builder, cmdgen): if __debug__: logInstanceCreation(self, 'Builder.CompositeBuilder') SCons.Util.Proxy.__init__(self, builder) # cmdgen should always be an instance of DictCmdGenerator. self.cmdgen = cmdgen self.builder = builder __call__ = SCons.Util.Delegate('__call__') def add_action(self, suffix, action): self.cmdgen.add_action(suffix, action) self.set_src_suffix(self.cmdgen.src_suffixes()) def is_a_Builder(obj): """"Returns True iff the specified obj is one of our Builder classes. The test is complicated a bit by the fact that CompositeBuilder is a proxy, not a subclass of BuilderBase. """ return (isinstance(obj, BuilderBase) or isinstance(obj, CompositeBuilder) or callable(obj)) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
""" msgmerget tool Tool specific initialization for `msgmerge` tool. """ # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. __revision__ = "src/engine/SCons/Tool/msgmerge.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" ############################################################################# def _update_or_init_po_files(target, source, env): """ Action function for `POUpdate` builder """ import SCons.Action from SCons.Tool.GettextCommon import _init_po_files for tgt in target: if tgt.rexists(): action = SCons.Action.Action('$MSGMERGECOM', '$MSGMERGECOMSTR') else: action = _init_po_files status = action([tgt], source, env) if status : return status return 0 ############################################################################# ############################################################################# def _POUpdateBuilder(env, **kw): """ Create an object of `POUpdate` builder """ import SCons.Action from SCons.Tool.GettextCommon import _POFileBuilder action = SCons.Action.Action(_update_or_init_po_files, None) return _POFileBuilder(env, action=action, target_alias='$POUPDATE_ALIAS') ############################################################################# ############################################################################# from SCons.Environment import _null ############################################################################# def _POUpdateBuilderWrapper(env, target=None, source=_null, **kw): """ Wrapper for `POUpdate` builder - make user's life easier """ if source is _null: if 'POTDOMAIN' in kw: domain = kw['POTDOMAIN'] elif env.has_key('POTDOMAIN') and env['POTDOMAIN']: domain = env['POTDOMAIN'] else: domain = 'messages' source = [ domain ] # NOTE: Suffix shall be appended automatically return env._POUpdateBuilder(target, source, **kw) ############################################################################# ############################################################################# def generate(env,**kw): """ Generate the `xgettext` tool """ from SCons.Tool.GettextCommon import _detect_msgmerge env['MSGMERGE'] = _detect_msgmerge(env) env.SetDefault( POTSUFFIX = ['.pot'], POSUFFIX = ['.po'], MSGMERGECOM = '$MSGMERGE $MSGMERGEFLAGS --update $TARGET $SOURCE', MSGMERGECOMSTR = '', MSGMERGEFLAGS = [ ], POUPDATE_ALIAS = 'po-update' ) env.Append(BUILDERS = { '_POUpdateBuilder':_POUpdateBuilder(env) }) env.AddMethod(_POUpdateBuilderWrapper, 'POUpdate') env.AlwaysBuild(env.Alias('$POUPDATE_ALIAS')) ############################################################################# ############################################################################# def exists(env): """ Check if the tool exists """ from SCons.Tool.GettextCommon import _msgmerge_exists return _msgmerge_exists(env) ############################################################################# # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.hplink Tool-specific initialization for the HP linker. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/hplink.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os import os.path import SCons.Util import link ccLinker = None # search for the acc compiler and linker front end try: dirs = os.listdir('/opt') except (IOError, OSError): # Not being able to read the directory because it doesn't exist # (IOError) or isn't readable (OSError) is okay. dirs = [] for dir in dirs: linker = '/opt/' + dir + '/bin/aCC' if os.path.exists(linker): ccLinker = linker break def generate(env): """ Add Builders and construction variables for Visual Age linker to an Environment. """ link.generate(env) env['LINKFLAGS'] = SCons.Util.CLVar('-Wl,+s -Wl,+vnocompatwarnings') env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -b') env['SHLIBSUFFIX'] = '.sl' def exists(env): return ccLinker # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.m4 Tool-specific initialization for m4. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/m4.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Action import SCons.Builder import SCons.Util def generate(env): """Add Builders and construction variables for m4 to an Environment.""" M4Action = SCons.Action.Action('$M4COM', '$M4COMSTR') bld = SCons.Builder.Builder(action = M4Action, src_suffix = '.m4') env['BUILDERS']['M4'] = bld # .m4 files might include other files, and it would be pretty hard # to write a scanner for it, so let's just cd to the dir of the m4 # file and run from there. # The src_suffix setup is like so: file.c.m4 -> file.c, # file.cpp.m4 -> file.cpp etc. env['M4'] = 'm4' env['M4FLAGS'] = SCons.Util.CLVar('-E') env['M4COM'] = 'cd ${SOURCE.rsrcdir} && $M4 $M4FLAGS < ${SOURCE.file} > ${TARGET.abspath}' def exists(env): return env.Detect('m4') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.g++ Tool-specific initialization for g++. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/g++.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os.path import re import subprocess import SCons.Tool import SCons.Util cplusplus = __import__('c++', globals(), locals(), []) compilers = ['g++'] def generate(env): """Add Builders and construction variables for g++ to an Environment.""" static_obj, shared_obj = SCons.Tool.createObjBuilders(env) cplusplus.generate(env) env['CXX'] = env.Detect(compilers) # platform specific settings if env['PLATFORM'] == 'aix': env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS -mminimal-toc') env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1 env['SHOBJSUFFIX'] = '$OBJSUFFIX' elif env['PLATFORM'] == 'hpux': env['SHOBJSUFFIX'] = '.pic.o' elif env['PLATFORM'] == 'sunos': env['SHOBJSUFFIX'] = '.pic.o' # determine compiler version if env['CXX']: #pipe = SCons.Action._subproc(env, [env['CXX'], '-dumpversion'], pipe = SCons.Action._subproc(env, [env['CXX'], '--version'], stdin = 'devnull', stderr = 'devnull', stdout = subprocess.PIPE) if pipe.wait() != 0: return # -dumpversion was added in GCC 3.0. As long as we're supporting # GCC versions older than that, we should use --version and a # regular expression. #line = pipe.stdout.read().strip() #if line: # env['CXXVERSION'] = line line = pipe.stdout.readline() match = re.search(r'[0-9]+(\.[0-9]+)+', line) if match: env['CXXVERSION'] = match.group(0) def exists(env): return env.Detect(compilers) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.masm Tool-specific initialization for the Microsoft Assembler. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/masm.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Defaults import SCons.Tool import SCons.Util ASSuffixes = ['.s', '.asm', '.ASM'] ASPPSuffixes = ['.spp', '.SPP', '.sx'] if SCons.Util.case_sensitive_suffixes('.s', '.S'): ASPPSuffixes.extend(['.S']) else: ASSuffixes.extend(['.S']) def generate(env): """Add Builders and construction variables for masm to an Environment.""" static_obj, shared_obj = SCons.Tool.createObjBuilders(env) for suffix in ASSuffixes: static_obj.add_action(suffix, SCons.Defaults.ASAction) shared_obj.add_action(suffix, SCons.Defaults.ASAction) static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter) shared_obj.add_emitter(suffix, SCons.Defaults.SharedObjectEmitter) for suffix in ASPPSuffixes: static_obj.add_action(suffix, SCons.Defaults.ASPPAction) shared_obj.add_action(suffix, SCons.Defaults.ASPPAction) static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter) shared_obj.add_emitter(suffix, SCons.Defaults.SharedObjectEmitter) env['AS'] = 'ml' env['ASFLAGS'] = SCons.Util.CLVar('/nologo') env['ASPPFLAGS'] = '$ASFLAGS' env['ASCOM'] = '$AS $ASFLAGS /c /Fo$TARGET $SOURCES' env['ASPPCOM'] = '$CC $ASPPFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS /c /Fo$TARGET $SOURCES' env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1 def exists(env): return env.Detect('ml') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""engine.SCons.Tool.sunar Tool-specific initialization for Solaris (Forte) ar (library archive). If CC exists, static libraries should be built with it, so that template instantians can be resolved. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/sunar.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Defaults import SCons.Tool import SCons.Util def generate(env): """Add Builders and construction variables for ar to an Environment.""" SCons.Tool.createStaticLibBuilder(env) if env.Detect('CC'): env['AR'] = 'CC' env['ARFLAGS'] = SCons.Util.CLVar('-xar') env['ARCOM'] = '$AR $ARFLAGS -o $TARGET $SOURCES' else: env['AR'] = 'ar' env['ARFLAGS'] = SCons.Util.CLVar('r') env['ARCOM'] = '$AR $ARFLAGS $TARGET $SOURCES' env['SHLINK'] = '$LINK' env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -G') env['SHLINKCOM'] = '$SHLINK $SHLINKFLAGS -o $TARGET $SOURCES $_LIBDIRFLAGS $_LIBFLAGS' env['LIBPREFIX'] = 'lib' env['LIBSUFFIX'] = '.a' def exists(env): return env.Detect('CC') or env.Detect('ar') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.RCS.py Tool-specific initialization for RCS. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. __revision__ = "src/engine/SCons/Tool/RCS.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Action import SCons.Builder import SCons.Util def generate(env): """Add a Builder factory function and construction variables for RCS to an Environment.""" def RCSFactory(env=env): """ """ import SCons.Warnings as W W.warn(W.DeprecatedSourceCodeWarning, """The RCS() factory is deprecated and there is no replacement.""") act = SCons.Action.Action('$RCS_COCOM', '$RCS_COCOMSTR') return SCons.Builder.Builder(action = act, env = env) #setattr(env, 'RCS', RCSFactory) env.RCS = RCSFactory env['RCS'] = 'rcs' env['RCS_CO'] = 'co' env['RCS_COFLAGS'] = SCons.Util.CLVar('') env['RCS_COCOM'] = '$RCS_CO $RCS_COFLAGS $TARGET' def exists(env): return env.Detect('rcs') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # # TODO: # * supported arch for versions: for old versions of batch file without # argument, giving bogus argument cannot be detected, so we have to hardcode # this here # * print warning when msvc version specified but not found # * find out why warning do not print # * test on 64 bits XP + VS 2005 (and VS 6 if possible) # * SDK # * Assembly __revision__ = "src/engine/SCons/Tool/MSCommon/vc.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" __doc__ = """Module for Visual C/C++ detection and configuration. """ import SCons.compat import os import platform from string import digits as string_digits import SCons.Warnings import common debug = common.debug import sdk get_installed_sdks = sdk.get_installed_sdks class VisualCException(Exception): pass class UnsupportedVersion(VisualCException): pass class UnsupportedArch(VisualCException): pass class MissingConfiguration(VisualCException): pass class NoVersionFound(VisualCException): pass class BatchFileExecutionError(VisualCException): pass # Dict to 'canonalize' the arch _ARCH_TO_CANONICAL = { "amd64" : "amd64", "emt64" : "amd64", "i386" : "x86", "i486" : "x86", "i586" : "x86", "i686" : "x86", "ia64" : "ia64", "itanium" : "ia64", "x86" : "x86", "x86_64" : "amd64", } # Given a (host, target) tuple, return the argument for the bat file. Both host # and targets should be canonalized. _HOST_TARGET_ARCH_TO_BAT_ARCH = { ("x86", "x86"): "x86", ("x86", "amd64"): "x86_amd64", ("amd64", "amd64"): "amd64", ("amd64", "x86"): "x86", ("x86", "ia64"): "x86_ia64" } def get_host_target(env): debug('vc.py:get_host_target()') host_platform = env.get('HOST_ARCH') if not host_platform: host_platform = platform.machine() # TODO(2.5): the native Python platform.machine() function returns # '' on all Python versions before 2.6, after which it also uses # PROCESSOR_ARCHITECTURE. if not host_platform: host_platform = os.environ.get('PROCESSOR_ARCHITECTURE', '') # Retain user requested TARGET_ARCH req_target_platform = env.get('TARGET_ARCH') debug('vc.py:get_host_target() req_target_platform:%s'%req_target_platform) if req_target_platform: # If user requested a specific platform then only try that one. target_platform = req_target_platform else: target_platform = host_platform try: host = _ARCH_TO_CANONICAL[host_platform.lower()] except KeyError, e: msg = "Unrecognized host architecture %s" raise ValueError(msg % repr(host_platform)) try: target = _ARCH_TO_CANONICAL[target_platform.lower()] except KeyError, e: all_archs = str(_ARCH_TO_CANONICAL.keys()) raise ValueError("Unrecognized target architecture %s\n\tValid architectures: %s" % (target_platform, all_archs)) return (host, target,req_target_platform) _VCVER = ["11.0", "11.0Exp", "10.0", "10.0Exp", "9.0", "9.0Exp","8.0", "8.0Exp","7.1", "7.0", "6.0"] _VCVER_TO_PRODUCT_DIR = { '11.0': [ r'Microsoft\VisualStudio\11.0\Setup\VC\ProductDir'], '11.0Exp' : [ r'Microsoft\VCExpress\11.0\Setup\VC\ProductDir'], '10.0': [ r'Microsoft\VisualStudio\10.0\Setup\VC\ProductDir'], '10.0Exp' : [ r'Microsoft\VCExpress\10.0\Setup\VC\ProductDir'], '9.0': [ r'Microsoft\VisualStudio\9.0\Setup\VC\ProductDir'], '9.0Exp' : [ r'Microsoft\VCExpress\9.0\Setup\VC\ProductDir'], '8.0': [ r'Microsoft\VisualStudio\8.0\Setup\VC\ProductDir'], '8.0Exp': [ r'Microsoft\VCExpress\8.0\Setup\VC\ProductDir'], '7.1': [ r'Microsoft\VisualStudio\7.1\Setup\VC\ProductDir'], '7.0': [ r'Microsoft\VisualStudio\7.0\Setup\VC\ProductDir'], '6.0': [ r'Microsoft\VisualStudio\6.0\Setup\Microsoft Visual C++\ProductDir'] } def msvc_version_to_maj_min(msvc_version): msvc_version_numeric = ''.join([x for x in msvc_version if x in string_digits + '.']) t = msvc_version_numeric.split(".") if not len(t) == 2: raise ValueError("Unrecognized version %s (%s)" % (msvc_version,msvc_version_numeric)) try: maj = int(t[0]) min = int(t[1]) return maj, min except ValueError, e: raise ValueError("Unrecognized version %s (%s)" % (msvc_version,msvc_version_numeric)) def is_host_target_supported(host_target, msvc_version): """Return True if the given (host, target) tuple is supported given the msvc version. Parameters ---------- host_target: tuple tuple of (canonalized) host-target, e.g. ("x86", "amd64") for cross compilation from 32 bits windows to 64 bits. msvc_version: str msvc version (major.minor, e.g. 10.0) Note ---- This only check whether a given version *may* support the given (host, target), not that the toolchain is actually present on the machine. """ # We assume that any Visual Studio version supports x86 as a target if host_target[1] != "x86": maj, min = msvc_version_to_maj_min(msvc_version) if maj < 8: return False return True def find_vc_pdir(msvc_version): """Try to find the product directory for the given version. Note ---- If for some reason the requested version could not be found, an exception which inherits from VisualCException will be raised.""" root = 'Software\\' if common.is_win64(): root = root + 'Wow6432Node\\' try: hkeys = _VCVER_TO_PRODUCT_DIR[msvc_version] except KeyError: debug("Unknown version of MSVC: %s" % msvc_version) raise UnsupportedVersion("Unknown version %s" % msvc_version) for key in hkeys: key = root + key try: comps = common.read_reg(key) except WindowsError, e: debug('find_vc_dir(): no VC registry key %s' % repr(key)) else: debug('find_vc_dir(): found VC in registry: %s' % comps) if os.path.exists(comps): return comps else: debug('find_vc_dir(): reg says dir is %s, but it does not exist. (ignoring)'\ % comps) raise MissingConfiguration("registry dir %s not found on the filesystem" % comps) return None def find_batch_file(env,msvc_version,host_arch,target_arch): """ Find the location of the batch script which should set up the compiler for any TARGET_ARCH whose compilers were installed by Visual Studio/VCExpress """ pdir = find_vc_pdir(msvc_version) if pdir is None: raise NoVersionFound("No version of Visual Studio found") debug('vc.py: find_batch_file() pdir:%s'%pdir) # filter out e.g. "Exp" from the version name msvc_ver_numeric = ''.join([x for x in msvc_version if x in string_digits + "."]) vernum = float(msvc_ver_numeric) if 7 <= vernum < 8: pdir = os.path.join(pdir, os.pardir, "Common7", "Tools") batfilename = os.path.join(pdir, "vsvars32.bat") elif vernum < 7: pdir = os.path.join(pdir, "Bin") batfilename = os.path.join(pdir, "vcvars32.bat") else: # >= 8 batfilename = os.path.join(pdir, "vcvarsall.bat") if not os.path.exists(batfilename): debug("Not found: %s" % batfilename) batfilename = None installed_sdks=get_installed_sdks() for _sdk in installed_sdks: sdk_bat_file=_sdk.get_sdk_vc_script(host_arch,target_arch) sdk_bat_file_path=os.path.join(pdir,sdk_bat_file) debug('vc.py:find_batch_file() sdk_bat_file_path:%s'%sdk_bat_file_path) if os.path.exists(sdk_bat_file_path): return (batfilename,sdk_bat_file_path) else: debug("vc.py:find_batch_file() not found:%s"%sdk_bat_file_path) else: return (batfilename,None) __INSTALLED_VCS_RUN = None def cached_get_installed_vcs(): global __INSTALLED_VCS_RUN if __INSTALLED_VCS_RUN is None: ret = get_installed_vcs() __INSTALLED_VCS_RUN = ret return __INSTALLED_VCS_RUN def get_installed_vcs(): installed_versions = [] for ver in _VCVER: debug('trying to find VC %s' % ver) try: if find_vc_pdir(ver): debug('found VC %s' % ver) installed_versions.append(ver) else: debug('find_vc_pdir return None for ver %s' % ver) except VisualCException, e: debug('did not find VC %s: caught exception %s' % (ver, str(e))) return installed_versions def reset_installed_vcs(): """Make it try again to find VC. This is just for the tests.""" __INSTALLED_VCS_RUN = None def script_env(script, args=None): stdout = common.get_output(script, args) # Stupid batch files do not set return code: we take a look at the # beginning of the output for an error message instead olines = stdout.splitlines() if olines[0].startswith("The specified configuration type is missing"): raise BatchFileExecutionError("\n".join(olines[:2])) return common.parse_output(stdout) def get_default_version(env): debug('get_default_version()') msvc_version = env.get('MSVC_VERSION') msvs_version = env.get('MSVS_VERSION') debug('get_default_version(): msvc_version:%s msvs_version:%s'%(msvc_version,msvs_version)) if msvs_version and not msvc_version: SCons.Warnings.warn( SCons.Warnings.DeprecatedWarning, "MSVS_VERSION is deprecated: please use MSVC_VERSION instead ") return msvs_version elif msvc_version and msvs_version: if not msvc_version == msvs_version: SCons.Warnings.warn( SCons.Warnings.VisualVersionMismatch, "Requested msvc version (%s) and msvs version (%s) do " \ "not match: please use MSVC_VERSION only to request a " \ "visual studio version, MSVS_VERSION is deprecated" \ % (msvc_version, msvs_version)) return msvs_version if not msvc_version: installed_vcs = cached_get_installed_vcs() debug('installed_vcs:%s' % installed_vcs) if not installed_vcs: #msg = 'No installed VCs' #debug('msv %s\n' % repr(msg)) #SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, msg) debug('msvc_setup_env: No installed VCs') return None msvc_version = installed_vcs[0] debug('msvc_setup_env: using default installed MSVC version %s\n' % repr(msvc_version)) return msvc_version def msvc_setup_env_once(env): try: has_run = env["MSVC_SETUP_RUN"] except KeyError: has_run = False if not has_run: msvc_setup_env(env) env["MSVC_SETUP_RUN"] = True def msvc_find_valid_batch_script(env,version): debug('vc.py:msvc_find_valid_batch_script()') # Find the host platform, target platform, and if present the requested # target platform (host_platform, target_platform,req_target_platform) = get_host_target(env) # If the user hasn't specifically requested a TARGET_ARCH, and # The TARGET_ARCH is amd64 then also try 32 bits if there are no viable # 64 bit tools installed try_target_archs = [target_platform] if not req_target_platform and target_platform in ('amd64','x86_64'): try_target_archs.append('x86') d = None for tp in try_target_archs: # Set to current arch. env['TARGET_ARCH']=tp debug("vc.py:msvc_find_valid_batch_script() trying target_platform:%s"%tp) host_target = (host_platform, tp) if not is_host_target_supported(host_target, version): warn_msg = "host, target = %s not supported for MSVC version %s" % \ (host_target, version) SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, warn_msg) arg = _HOST_TARGET_ARCH_TO_BAT_ARCH[host_target] # Try to locate a batch file for this host/target platform combo try: (vc_script,sdk_script) = find_batch_file(env,version,host_platform,tp) debug('vc.py:msvc_find_valid_batch_script() vc_script:%s sdk_script:%s'%(vc_script,sdk_script)) except VisualCException, e: msg = str(e) debug('Caught exception while looking for batch file (%s)' % msg) warn_msg = "VC version %s not installed. " + \ "C/C++ compilers are most likely not set correctly.\n" + \ " Installed versions are: %s" warn_msg = warn_msg % (version, cached_get_installed_vcs()) SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, warn_msg) continue # Try to use the located batch file for this host/target platform combo debug('vc.py:msvc_find_valid_batch_script() use_script 2 %s, args:%s\n' % (repr(vc_script), arg)) if vc_script: try: d = script_env(vc_script, args=arg) except BatchFileExecutionError, e: debug('vc.py:msvc_find_valid_batch_script() use_script 3: failed running VC script %s: %s: Error:%s'%(repr(vc_script),arg,e)) vc_script=None if not vc_script and sdk_script: debug('vc.py:msvc_find_valid_batch_script() use_script 4: trying sdk script: %s'%(sdk_script)) try: d = script_env(sdk_script,args=[]) except BatchFileExecutionError,e: debug('vc.py:msvc_find_valid_batch_script() use_script 5: failed running SDK script %s: Error:%s'%(repr(sdk_script),e)) continue elif not vc_script and not sdk_script: debug('vc.py:msvc_find_valid_batch_script() use_script 6: Neither VC script nor SDK script found') continue # If we cannot find a viable installed compiler, reset the TARGET_ARCH # To it's initial value if not d: env['TARGET_ARCH']=req_target_platform return d def msvc_setup_env(env): debug('msvc_setup_env()') version = get_default_version(env) if version is None: warn_msg = "No version of Visual Studio compiler found - C/C++ " \ "compilers most likely not set correctly" SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, warn_msg) return None debug('msvc_setup_env: using specified MSVC version %s\n' % repr(version)) # XXX: we set-up both MSVS version for backward # compatibility with the msvs tool env['MSVC_VERSION'] = version env['MSVS_VERSION'] = version env['MSVS'] = {} use_script = env.get('MSVC_USE_SCRIPT', True) if SCons.Util.is_String(use_script): debug('vc.py:msvc_setup_env() use_script 1 %s\n' % repr(use_script)) d = script_env(use_script) elif use_script: d = msvc_find_valid_batch_script(env,version) debug('vc.py:msvc_setup_env() use_script 2 %s\n' % d) if not d: return d else: debug('MSVC_USE_SCRIPT set to False') warn_msg = "MSVC_USE_SCRIPT set to False, assuming environment " \ "set correctly." SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, warn_msg) return None for k, v in d.items(): debug('vc.py:msvc_setup_env() env:%s -> %s'%(k,v)) env.PrependENVPath(k, v, delete_existing=True) def msvc_exists(version=None): vcs = cached_get_installed_vcs() if version is None: return len(vcs) > 0 return version in vcs
Python
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/MSCommon/vs.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" __doc__ = """Module to detect Visual Studio and/or Visual C/C++ """ import os import SCons.Errors import SCons.Util from common import debug, \ get_output, \ is_win64, \ normalize_env, \ parse_output, \ read_reg import SCons.Tool.MSCommon.vc class VisualStudio(object): """ An abstract base class for trying to find installed versions of Visual Studio. """ def __init__(self, version, **kw): self.version = version kw['vc_version'] = kw.get('vc_version', version) kw['sdk_version'] = kw.get('sdk_version', version) self.__dict__.update(kw) self._cache = {} # def find_batch_file(self): vs_dir = self.get_vs_dir() if not vs_dir: debug('find_executable(): no vs_dir') return None batch_file = os.path.join(vs_dir, self.batch_file_path) batch_file = os.path.normpath(batch_file) if not os.path.isfile(batch_file): debug('find_batch_file(): %s not on file system' % batch_file) return None return batch_file def find_vs_dir_by_vc(self): SCons.Tool.MSCommon.vc.get_installed_vcs() dir = SCons.Tool.MSCommon.vc.find_vc_pdir(self.vc_version) if not dir: debug('find_vs_dir(): no installed VC %s' % self.vc_version) return None return dir def find_vs_dir_by_reg(self): root = 'Software\\' if is_win64(): root = root + 'Wow6432Node\\' for key in self.hkeys: if key=='use_dir': return self.find_vs_dir_by_vc() key = root + key try: comps = read_reg(key) except WindowsError, e: debug('find_vs_dir_by_reg(): no VS registry key %s' % repr(key)) else: debug('find_vs_dir_by_reg(): found VS in registry: %s' % comps) return comps return None def find_vs_dir(self): """ Can use registry or location of VC to find vs dir First try to find by registry, and if that fails find via VC dir """ if True: vs_dir=self.find_vs_dir_by_reg() return vs_dir else: return self.find_vs_dir_by_vc() def find_executable(self): vs_dir = self.get_vs_dir() if not vs_dir: debug('find_executable(): no vs_dir (%s)'%vs_dir) return None executable = os.path.join(vs_dir, self.executable_path) executable = os.path.normpath(executable) if not os.path.isfile(executable): debug('find_executable(): %s not on file system' % executable) return None return executable # def get_batch_file(self): try: return self._cache['batch_file'] except KeyError: batch_file = self.find_batch_file() self._cache['batch_file'] = batch_file return batch_file def get_executable(self): try: debug('get_executable using cache:%s'%self._cache['executable']) return self._cache['executable'] except KeyError: executable = self.find_executable() self._cache['executable'] = executable debug('get_executable not in cache:%s'%executable) return executable def get_vs_dir(self): try: return self._cache['vs_dir'] except KeyError: vs_dir = self.find_vs_dir() self._cache['vs_dir'] = vs_dir return vs_dir def get_supported_arch(self): try: return self._cache['supported_arch'] except KeyError: # RDEVE: for the time being use hardcoded lists # supported_arch = self.find_supported_arch() self._cache['supported_arch'] = self.supported_arch return self.supported_arch def reset(self): self._cache = {} # The list of supported Visual Studio versions we know how to detect. # # How to look for .bat file ? # - VS 2008 Express (x86): # * from registry key productdir, gives the full path to vsvarsall.bat. In # HKEY_LOCAL_MACHINE): # Software\Microsoft\VCEpress\9.0\Setup\VC\productdir # * from environmnent variable VS90COMNTOOLS: the path is then ..\..\VC # relatively to the path given by the variable. # # - VS 2008 Express (WoW6432: 32 bits on windows x64): # Software\Wow6432Node\Microsoft\VCEpress\9.0\Setup\VC\productdir # # - VS 2005 Express (x86): # * from registry key productdir, gives the full path to vsvarsall.bat. In # HKEY_LOCAL_MACHINE): # Software\Microsoft\VCEpress\8.0\Setup\VC\productdir # * from environmnent variable VS80COMNTOOLS: the path is then ..\..\VC # relatively to the path given by the variable. # # - VS 2005 Express (WoW6432: 32 bits on windows x64): does not seem to have a # productdir ? # # - VS 2003 .Net (pro edition ? x86): # * from registry key productdir. The path is then ..\Common7\Tools\ # relatively to the key. The key is in HKEY_LOCAL_MACHINE): # Software\Microsoft\VisualStudio\7.1\Setup\VC\productdir # * from environmnent variable VS71COMNTOOLS: the path is the full path to # vsvars32.bat # # - VS 98 (VS 6): # * from registry key productdir. The path is then Bin # relatively to the key. The key is in HKEY_LOCAL_MACHINE): # Software\Microsoft\VisualStudio\6.0\Setup\VC98\productdir # # The first version found in the list is the one used by default if # there are multiple versions installed. Barring good reasons to # the contrary, this means we should list versions from most recent # to oldest. Pro versions get listed before Express versions on the # assumption that, by default, you'd rather use the version you paid # good money for in preference to whatever Microsoft makes available # for free. # # If you update this list, update the documentation in Tool/msvs.xml. SupportedVSList = [ # Visual Studio 2010 # TODO: find the settings, perhaps from someone with a CTP copy? #VisualStudio('TBD', # hkey_root=r'TBD', # common_tools_var='TBD', # executable_path=r'TBD', # default_dirname='TBD', #), # Visual Studio 11 # The batch file we look for is in the VC directory, # so the devenv.com executable is up in ..\..\Common7\IDE. VisualStudio('11.0', sdk_version='6.1', hkeys=[r'Microsoft\VisualStudio\11.0\Setup\VS\ProductDir'], common_tools_var='VS110COMNTOOLS', executable_path=r'Common7\IDE\devenv.com', batch_file_path=r'Common7\Tools\vsvars32.bat', default_dirname='Microsoft Visual Studio 11', supported_arch=['x86', 'amd64'], ), # Visual C++ 11 Express Edition # The batch file we look for is in the VC directory, # so the VCExpress.exe executable is up in ..\..\Common7\IDE. VisualStudio('11.0Exp', vc_version='11.0', sdk_version='6.1', hkeys=[r'Microsoft\VCExpress\11.0\Setup\VS\ProductDir'], common_tools_var='VS110COMNTOOLS', executable_path=r'Common7\IDE\VCExpress.exe', batch_file_path=r'Common7\Tools\vsvars32.bat', default_dirname='Microsoft Visual Studio 11', supported_arch=['x86'], ), # Visual Studio 2010 # The batch file we look for is in the VC directory, # so the devenv.com executable is up in ..\..\Common7\IDE. VisualStudio('10.0', sdk_version='6.1', hkeys=[r'Microsoft\VisualStudio\10.0\Setup\VS\ProductDir'], common_tools_var='VS100COMNTOOLS', executable_path=r'Common7\IDE\devenv.com', batch_file_path=r'Common7\Tools\vsvars32.bat', default_dirname='Microsoft Visual Studio 10', supported_arch=['x86', 'amd64'], ), # Visual C++ 2010 Express Edition # The batch file we look for is in the VC directory, # so the VCExpress.exe executable is up in ..\..\Common7\IDE. VisualStudio('10.0Exp', vc_version='10.0', sdk_version='6.1', hkeys=[r'Microsoft\VCExpress\10.0\Setup\VS\ProductDir'], common_tools_var='VS100COMNTOOLS', executable_path=r'Common7\IDE\VCExpress.exe', batch_file_path=r'Common7\Tools\vsvars32.bat', default_dirname='Microsoft Visual Studio 10', supported_arch=['x86'], ), # Visual Studio 2008 # The batch file we look for is in the VC directory, # so the devenv.com executable is up in ..\..\Common7\IDE. VisualStudio('9.0', sdk_version='6.1', hkeys=[r'Microsoft\VisualStudio\9.0\Setup\VS\ProductDir'], common_tools_var='VS90COMNTOOLS', executable_path=r'Common7\IDE\devenv.com', batch_file_path=r'Common7\Tools\vsvars32.bat', default_dirname='Microsoft Visual Studio 9', supported_arch=['x86', 'amd64'], ), # Visual C++ 2008 Express Edition # The batch file we look for is in the VC directory, # so the VCExpress.exe executable is up in ..\..\Common7\IDE. VisualStudio('9.0Exp', vc_version='9.0', sdk_version='6.1', hkeys=[r'Microsoft\VCExpress\9.0\Setup\VS\ProductDir'], common_tools_var='VS90COMNTOOLS', executable_path=r'Common7\IDE\VCExpress.exe', batch_file_path=r'Common7\Tools\vsvars32.bat', default_dirname='Microsoft Visual Studio 9', supported_arch=['x86'], ), # Visual Studio 2005 # The batch file we look for is in the VC directory, # so the devenv.com executable is up in ..\..\Common7\IDE. VisualStudio('8.0', sdk_version='6.0A', hkeys=[r'Microsoft\VisualStudio\8.0\Setup\VS\ProductDir'], common_tools_var='VS80COMNTOOLS', executable_path=r'Common7\IDE\devenv.com', batch_file_path=r'Common7\Tools\vsvars32.bat', default_dirname='Microsoft Visual Studio 8', supported_arch=['x86', 'amd64'], ), # Visual C++ 2005 Express Edition # The batch file we look for is in the VC directory, # so the VCExpress.exe executable is up in ..\..\Common7\IDE. VisualStudio('8.0Exp', vc_version='8.0Exp', sdk_version='6.0A', hkeys=[r'Microsoft\VCExpress\8.0\Setup\VS\ProductDir'], common_tools_var='VS80COMNTOOLS', executable_path=r'Common7\IDE\VCExpress.exe', batch_file_path=r'Common7\Tools\vsvars32.bat', default_dirname='Microsoft Visual Studio 8', supported_arch=['x86'], ), # Visual Studio .NET 2003 # The batch file we look for is in the Common7\Tools directory, # so the devenv.com executable is next door in ..\IDE. VisualStudio('7.1', sdk_version='6.0', hkeys=[r'Microsoft\VisualStudio\7.1\Setup\VS\ProductDir'], common_tools_var='VS71COMNTOOLS', executable_path=r'Common7\IDE\devenv.com', batch_file_path=r'Common7\Tools\vsvars32.bat', default_dirname='Microsoft Visual Studio .NET 2003', supported_arch=['x86'], ), # Visual Studio .NET # The batch file we look for is in the Common7\Tools directory, # so the devenv.com executable is next door in ..\IDE. VisualStudio('7.0', sdk_version='2003R2', hkeys=[r'Microsoft\VisualStudio\7.0\Setup\VS\ProductDir'], common_tools_var='VS70COMNTOOLS', executable_path=r'IDE\devenv.com', batch_file_path=r'Common7\Tools\vsvars32.bat', default_dirname='Microsoft Visual Studio .NET', supported_arch=['x86'], ), # Visual Studio 6.0 VisualStudio('6.0', sdk_version='2003R1', hkeys=[r'Microsoft\VisualStudio\6.0\Setup\Microsoft Visual Studio\ProductDir', 'use_dir'], common_tools_var='VS60COMNTOOLS', executable_path=r'Common\MSDev98\Bin\MSDEV.COM', batch_file_path=r'Common7\Tools\vsvars32.bat', default_dirname='Microsoft Visual Studio', supported_arch=['x86'], ), ] SupportedVSMap = {} for vs in SupportedVSList: SupportedVSMap[vs.version] = vs # Finding installed versions of Visual Studio isn't cheap, because it # goes not only to the registry but also to the disk to sanity-check # that there is, in fact, a Visual Studio directory there and that the # registry entry isn't just stale. Find this information once, when # requested, and cache it. InstalledVSList = None InstalledVSMap = None def get_installed_visual_studios(): global InstalledVSList global InstalledVSMap if InstalledVSList is None: InstalledVSList = [] InstalledVSMap = {} for vs in SupportedVSList: debug('trying to find VS %s' % vs.version) if vs.get_executable(): debug('found VS %s' % vs.version) InstalledVSList.append(vs) InstalledVSMap[vs.version] = vs return InstalledVSList def reset_installed_visual_studios(): global InstalledVSList global InstalledVSMap InstalledVSList = None InstalledVSMap = None for vs in SupportedVSList: vs.reset() # Need to clear installed VC's as well as they are used in finding # installed VS's SCons.Tool.MSCommon.vc.reset_installed_vcs() # We may be asked to update multiple construction environments with # SDK information. When doing this, we check on-disk for whether # the SDK has 'mfc' and 'atl' subdirectories. Since going to disk # is expensive, cache results by directory. #SDKEnvironmentUpdates = {} # #def set_sdk_by_directory(env, sdk_dir): # global SDKEnvironmentUpdates # try: # env_tuple_list = SDKEnvironmentUpdates[sdk_dir] # except KeyError: # env_tuple_list = [] # SDKEnvironmentUpdates[sdk_dir] = env_tuple_list # # include_path = os.path.join(sdk_dir, 'include') # mfc_path = os.path.join(include_path, 'mfc') # atl_path = os.path.join(include_path, 'atl') # # if os.path.exists(mfc_path): # env_tuple_list.append(('INCLUDE', mfc_path)) # if os.path.exists(atl_path): # env_tuple_list.append(('INCLUDE', atl_path)) # env_tuple_list.append(('INCLUDE', include_path)) # # env_tuple_list.append(('LIB', os.path.join(sdk_dir, 'lib'))) # env_tuple_list.append(('LIBPATH', os.path.join(sdk_dir, 'lib'))) # env_tuple_list.append(('PATH', os.path.join(sdk_dir, 'bin'))) # # for variable, directory in env_tuple_list: # env.PrependENVPath(variable, directory) def msvs_exists(): return (len(get_installed_visual_studios()) > 0) def get_vs_by_version(msvs): global InstalledVSMap global SupportedVSMap debug('vs.py:get_vs_by_version()') if msvs not in SupportedVSMap: msg = "Visual Studio version %s is not supported" % repr(msvs) raise SCons.Errors.UserError(msg) get_installed_visual_studios() vs = InstalledVSMap.get(msvs) debug('InstalledVSMap:%s'%InstalledVSMap) debug('vs.py:get_vs_by_version: found vs:%s'%vs) # Some check like this would let us provide a useful error message # if they try to set a Visual Studio version that's not installed. # However, we also want to be able to run tests (like the unit # tests) on systems that don't, or won't ever, have it installed. # It might be worth resurrecting this, with some configurable # setting that the tests can use to bypass the check. #if not vs: # msg = "Visual Studio version %s is not installed" % repr(msvs) # raise SCons.Errors.UserError, msg return vs def get_default_version(env): """Returns the default version string to use for MSVS. If no version was requested by the user through the MSVS environment variable, query all the available the visual studios through query_versions, and take the highest one. Return ------ version: str the default version. """ if 'MSVS' not in env or not SCons.Util.is_Dict(env['MSVS']): versions = [vs.version for vs in get_installed_visual_studios()] env['MSVS'] = {'VERSIONS' : versions} else: versions = env['MSVS'].get('VERSIONS', []) if 'MSVS_VERSION' not in env: if versions: env['MSVS_VERSION'] = versions[0] #use highest version by default else: env['MSVS_VERSION'] = SupportedVSList[0].version env['MSVS']['VERSION'] = env['MSVS_VERSION'] return env['MSVS_VERSION'] def get_default_arch(env): """Return the default arch to use for MSVS if no version was requested by the user through the MSVS_ARCH environment variable, select x86 Return ------ arch: str """ arch = env.get('MSVS_ARCH', 'x86') msvs = InstalledVSMap.get(env['MSVS_VERSION']) if not msvs: arch = 'x86' elif not arch in msvs.get_supported_arch(): fmt = "Visual Studio version %s does not support architecture %s" raise SCons.Errors.UserError(fmt % (env['MSVS_VERSION'], arch)) return arch def merge_default_version(env): version = get_default_version(env) arch = get_default_arch(env) def msvs_setup_env(env): batfilename = msvs.get_batch_file() msvs = get_vs_by_version(version) if msvs is None: return # XXX: I think this is broken. This will silently set a bogus tool instead # of failing, but there is no other way with the current scons tool # framework if batfilename is not None: vars = ('LIB', 'LIBPATH', 'PATH', 'INCLUDE') msvs_list = get_installed_visual_studios() vscommonvarnames = [vs.common_tools_var for vs in msvs_list] save_ENV = env['ENV'] nenv = normalize_env(env['ENV'], ['COMSPEC'] + vscommonvarnames, force=True) try: output = get_output(batfilename, arch, env=nenv) finally: env['ENV'] = save_ENV vars = parse_output(output, vars) for k, v in vars.items(): env.PrependENVPath(k, v, delete_existing=1) def query_versions(): """Query the system to get available versions of VS. A version is considered when a batfile is found.""" msvs_list = get_installed_visual_studios() versions = [msvs.version for msvs in msvs_list] return versions # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. __revision__ = "src/engine/SCons/Tool/MSCommon/netframework.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" __doc__ = """ """ import os import re from common import read_reg, debug # Original value recorded by dcournapeau _FRAMEWORKDIR_HKEY_ROOT = r'Software\Microsoft\.NETFramework\InstallRoot' # On SGK's system _FRAMEWORKDIR_HKEY_ROOT = r'Software\Microsoft\Microsoft SDKs\.NETFramework\v2.0\InstallationFolder' def find_framework_root(): # XXX: find it from environment (FrameworkDir) try: froot = read_reg(_FRAMEWORKDIR_HKEY_ROOT) debug("Found framework install root in registry: %s" % froot) except WindowsError, e: debug("Could not read reg key %s" % _FRAMEWORKDIR_HKEY_ROOT) return None if not os.path.exists(froot): debug("%s not found on fs" % froot) return None return froot def query_versions(): froot = find_framework_root() if froot: contents = os.listdir(froot) l = re.compile('v[0-9]+.*') versions = [e for e in contents if l.match(e)] def versrt(a,b): # since version numbers aren't really floats... aa = a[1:] bb = b[1:] aal = aa.split('.') bbl = bb.split('.') # sequence comparison in python is lexicographical # which is exactly what we want. # Note we sort backwards so the highest version is first. return cmp(bbl,aal) versions.sort(versrt) else: versions = [] return versions # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/MSCommon/sdk.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" __doc__ = """Module to detect the Platform/Windows SDK PSDK 2003 R1 is the earliest version detected. """ import os import SCons.Errors import SCons.Util import common debug = common.debug # SDK Checks. This is of course a mess as everything else on MS platforms. Here # is what we do to detect the SDK: # # For Windows SDK >= 6.0: just look into the registry entries: # HKLM\Software\Microsoft\Microsoft SDKs\Windows # All the keys in there are the available versions. # # For Platform SDK before 6.0 (2003 server R1 and R2, etc...), there does not # seem to be any sane registry key, so the precise location is hardcoded. # # For versions below 2003R1, it seems the PSDK is included with Visual Studio? # # Also, per the following: # http://benjamin.smedbergs.us/blog/tag/atl/ # VC++ Professional comes with the SDK, VC++ Express does not. # Location of the SDK (checked for 6.1 only) _CURINSTALLED_SDK_HKEY_ROOT = \ r"Software\Microsoft\Microsoft SDKs\Windows\CurrentInstallFolder" class SDKDefinition(object): """ An abstract base class for trying to find installed SDK directories. """ def __init__(self, version, **kw): self.version = version self.__dict__.update(kw) def find_sdk_dir(self): """Try to find the MS SDK from the registry. Return None if failed or the directory does not exist. """ if not SCons.Util.can_read_reg: debug('find_sdk_dir(): can not read registry') return None hkey = self.HKEY_FMT % self.hkey_data debug('find_sdk_dir(): checking registry:%s'%hkey) try: sdk_dir = common.read_reg(hkey) except WindowsError, e: debug('find_sdk_dir(): no SDK registry key %s' % repr(hkey)) return None debug('find_sdk_dir(): Trying SDK Dir: %s'%sdk_dir) if not os.path.exists(sdk_dir): debug('find_sdk_dir(): %s not on file system' % sdk_dir) return None ftc = os.path.join(sdk_dir, self.sanity_check_file) if not os.path.exists(ftc): debug("find_sdk_dir(): sanity check %s not found" % ftc) return None return sdk_dir def get_sdk_dir(self): """Return the MSSSDK given the version string.""" try: return self._sdk_dir except AttributeError: sdk_dir = self.find_sdk_dir() self._sdk_dir = sdk_dir return sdk_dir def get_sdk_vc_script(self,host_arch, target_arch): """ Return the script to initialize the VC compiler installed by SDK """ if (host_arch == 'amd64' and target_arch == 'x86'): # No cross tools needed compiling 32 bits on 64 bit machine host_arch=target_arch arch_string=target_arch if (host_arch != target_arch): arch_string='%s_%s'%(host_arch,target_arch) debug("sdk.py: get_sdk_vc_script():arch_string:%s host_arch:%s target_arch:%s"%(arch_string, host_arch, target_arch)) file=self.vc_setup_scripts.get(arch_string,None) debug("sdk.py: get_sdk_vc_script():file:%s"%file) return file class WindowsSDK(SDKDefinition): """ A subclass for trying to find installed Windows SDK directories. """ HKEY_FMT = r'Software\Microsoft\Microsoft SDKs\Windows\v%s\InstallationFolder' def __init__(self, *args, **kw): SDKDefinition.__init__(self, *args, **kw) self.hkey_data = self.version class PlatformSDK(SDKDefinition): """ A subclass for trying to find installed Platform SDK directories. """ HKEY_FMT = r'Software\Microsoft\MicrosoftSDK\InstalledSDKS\%s\Install Dir' def __init__(self, *args, **kw): SDKDefinition.__init__(self, *args, **kw) self.hkey_data = self.uuid # # The list of VC initialization scripts installed by the SDK # These should be tried if the vcvarsall.bat TARGET_ARCH fails preSDK61VCSetupScripts = { 'x86' : r'bin\vcvars32.bat', 'amd64' : r'bin\vcvarsamd64.bat', 'x86_amd64': r'bin\vcvarsx86_amd64.bat', 'x86_ia64' : r'bin\vcvarsx86_ia64.bat', 'ia64' : r'bin\vcvarsia64.bat'} SDK61VCSetupScripts = {'x86' : r'bin\vcvars32.bat', 'amd64' : r'bin\amd64\vcvarsamd64.bat', 'x86_amd64': r'bin\x86_amd64\vcvarsx86_amd64.bat', 'x86_ia64' : r'bin\x86_ia64\vcvarsx86_ia64.bat', 'ia64' : r'bin\ia64\vcvarsia64.bat'} SDK70VCSetupScripts = { 'x86' : r'bin\vcvars32.bat', 'amd64' : r'bin\vcvars64.bat', 'x86_amd64': r'bin\vcvarsx86_amd64.bat', 'x86_ia64' : r'bin\vcvarsx86_ia64.bat', 'ia64' : r'bin\vcvarsia64.bat'} # The list of support SDKs which we know how to detect. # # The first SDK found in the list is the one used by default if there # are multiple SDKs installed. Barring good reasons to the contrary, # this means we should list SDKs with from most recent to oldest. # # If you update this list, update the documentation in Tool/mssdk.xml. SupportedSDKList = [ WindowsSDK('7.0', sanity_check_file=r'bin\SetEnv.Cmd', include_subdir='include', lib_subdir={ 'x86' : ['lib'], 'x86_64' : [r'lib\x64'], 'ia64' : [r'lib\ia64'], }, vc_setup_scripts = SDK70VCSetupScripts, ), WindowsSDK('6.1', sanity_check_file=r'bin\SetEnv.Cmd', include_subdir='include', lib_subdir={ 'x86' : ['lib'], 'x86_64' : [r'lib\x64'], 'ia64' : [r'lib\ia64'], }, vc_setup_scripts = SDK61VCSetupScripts, ), WindowsSDK('6.0A', sanity_check_file=r'include\windows.h', include_subdir='include', lib_subdir={ 'x86' : ['lib'], 'x86_64' : [r'lib\x64'], 'ia64' : [r'lib\ia64'], }, vc_setup_scripts = preSDK61VCSetupScripts, ), WindowsSDK('6.0', sanity_check_file=r'bin\gacutil.exe', include_subdir='include', lib_subdir='lib', vc_setup_scripts = preSDK61VCSetupScripts, ), PlatformSDK('2003R2', sanity_check_file=r'SetEnv.Cmd', uuid="D2FF9F89-8AA2-4373-8A31-C838BF4DBBE1", vc_setup_scripts = preSDK61VCSetupScripts, ), PlatformSDK('2003R1', sanity_check_file=r'SetEnv.Cmd', uuid="8F9E5EF3-A9A5-491B-A889-C58EFFECE8B3", vc_setup_scripts = preSDK61VCSetupScripts, ), ] SupportedSDKMap = {} for sdk in SupportedSDKList: SupportedSDKMap[sdk.version] = sdk # Finding installed SDKs isn't cheap, because it goes not only to the # registry but also to the disk to sanity-check that there is, in fact, # an SDK installed there and that the registry entry isn't just stale. # Find this information once, when requested, and cache it. InstalledSDKList = None InstalledSDKMap = None def get_installed_sdks(): global InstalledSDKList global InstalledSDKMap debug('sdk.py:get_installed_sdks()') if InstalledSDKList is None: InstalledSDKList = [] InstalledSDKMap = {} for sdk in SupportedSDKList: debug('MSCommon/sdk.py: trying to find SDK %s' % sdk.version) if sdk.get_sdk_dir(): debug('MSCommon/sdk.py:found SDK %s' % sdk.version) InstalledSDKList.append(sdk) InstalledSDKMap[sdk.version] = sdk return InstalledSDKList # We may be asked to update multiple construction environments with # SDK information. When doing this, we check on-disk for whether # the SDK has 'mfc' and 'atl' subdirectories. Since going to disk # is expensive, cache results by directory. SDKEnvironmentUpdates = {} def set_sdk_by_directory(env, sdk_dir): global SDKEnvironmentUpdates debug('set_sdk_by_directory: Using dir:%s'%sdk_dir) try: env_tuple_list = SDKEnvironmentUpdates[sdk_dir] except KeyError: env_tuple_list = [] SDKEnvironmentUpdates[sdk_dir] = env_tuple_list include_path = os.path.join(sdk_dir, 'include') mfc_path = os.path.join(include_path, 'mfc') atl_path = os.path.join(include_path, 'atl') if os.path.exists(mfc_path): env_tuple_list.append(('INCLUDE', mfc_path)) if os.path.exists(atl_path): env_tuple_list.append(('INCLUDE', atl_path)) env_tuple_list.append(('INCLUDE', include_path)) env_tuple_list.append(('LIB', os.path.join(sdk_dir, 'lib'))) env_tuple_list.append(('LIBPATH', os.path.join(sdk_dir, 'lib'))) env_tuple_list.append(('PATH', os.path.join(sdk_dir, 'bin'))) for variable, directory in env_tuple_list: env.PrependENVPath(variable, directory) # TODO(sgk): currently unused; remove? def get_cur_sdk_dir_from_reg(): """Try to find the platform sdk directory from the registry. Return None if failed or the directory does not exist""" if not SCons.Util.can_read_reg: debug('SCons cannot read registry') return None try: val = common.read_reg(_CURINSTALLED_SDK_HKEY_ROOT) debug("Found current sdk dir in registry: %s" % val) except WindowsError, e: debug("Did not find current sdk in registry") return None if not os.path.exists(val): debug("Current sdk dir %s not on fs" % val) return None return val def get_sdk_by_version(mssdk): if mssdk not in SupportedSDKMap: msg = "SDK version %s is not supported" % repr(mssdk) raise SCons.Errors.UserError(msg) get_installed_sdks() return InstalledSDKMap.get(mssdk) def get_default_sdk(): """Set up the default Platform/Windows SDK.""" get_installed_sdks() if not InstalledSDKList: return None return InstalledSDKList[0] def mssdk_setup_env(env): debug('sdk.py:mssdk_setup_env()') if 'MSSDK_DIR' in env: sdk_dir = env['MSSDK_DIR'] if sdk_dir is None: return sdk_dir = env.subst(sdk_dir) debug('sdk.py:mssdk_setup_env: Using MSSDK_DIR:%s'%sdk_dir) elif 'MSSDK_VERSION' in env: sdk_version = env['MSSDK_VERSION'] if sdk_version is None: msg = "SDK version %s is not installed" % repr(mssdk) raise SCons.Errors.UserError(msg) sdk_version = env.subst(sdk_version) mssdk = get_sdk_by_version(sdk_version) sdk_dir = mssdk.get_sdk_dir() debug('sdk.py:mssdk_setup_env: Using MSSDK_VERSION:%s'%sdk_dir) elif 'MSVS_VERSION' in env: msvs_version = env['MSVS_VERSION'] debug('sdk.py:mssdk_setup_env:Getting MSVS_VERSION from env:%s'%msvs_version) if msvs_version is None: debug('sdk.py:mssdk_setup_env thinks msvs_version is None') return msvs_version = env.subst(msvs_version) import vs msvs = vs.get_vs_by_version(msvs_version) debug('sdk.py:mssdk_setup_env:msvs is :%s'%msvs) if not msvs: debug('sdk.py:mssdk_setup_env: no VS version detected, bailingout:%s'%msvs) return sdk_version = msvs.sdk_version debug('sdk.py:msvs.sdk_version is %s'%sdk_version) if not sdk_version: return mssdk = get_sdk_by_version(sdk_version) if not mssdk: mssdk = get_default_sdk() if not mssdk: return sdk_dir = mssdk.get_sdk_dir() debug('sdk.py:mssdk_setup_env: Using MSVS_VERSION:%s'%sdk_dir) else: mssdk = get_default_sdk() if not mssdk: return sdk_dir = mssdk.get_sdk_dir() debug('sdk.py:mssdk_setup_env: not using any env values. sdk_dir:%s'%sdk_dir) set_sdk_by_directory(env, sdk_dir) #print "No MSVS_VERSION: this is likely to be a bug" def mssdk_exists(version=None): sdks = get_installed_sdks() if version is None: return len(sdks) > 0 return version in sdks # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/MSCommon/arch.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" __doc__ = """Module to define supported Windows chip architectures. """ import os class ArchDefinition(object): """ A class for defining architecture-specific settings and logic. """ def __init__(self, arch, synonyms=[]): self.arch = arch self.synonyms = synonyms SupportedArchitectureList = [ ArchitectureDefinition( 'x86', ['i386', 'i486', 'i586', 'i686'], ), ArchitectureDefinition( 'x86_64', ['AMD64', 'amd64', 'em64t', 'EM64T', 'x86_64'], ), ArchitectureDefinition( 'ia64', ['IA64'], ), ] SupportedArchitectureMap = {} for a in SupportedArchitectureList: SupportedArchitectureMap[a.arch] = a for s in a.synonyms: SupportedArchitectureMap[s] = a
Python
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/MSCommon/__init__.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" __doc__ = """ Common functions for Microsoft Visual Studio and Visual C/C++. """ import copy import os import re import subprocess import SCons.Errors import SCons.Platform.win32 import SCons.Util from SCons.Tool.MSCommon.sdk import mssdk_exists, \ mssdk_setup_env from SCons.Tool.MSCommon.vc import msvc_exists, \ msvc_setup_env, \ msvc_setup_env_once from SCons.Tool.MSCommon.vs import get_default_version, \ get_vs_by_version, \ merge_default_version, \ msvs_exists, \ query_versions # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/MSCommon/common.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" __doc__ = """ Common helper functions for working with the Microsoft tool chain. """ import copy import os import subprocess import re import SCons.Util logfile = os.environ.get('SCONS_MSCOMMON_DEBUG') if logfile == '-': def debug(x): print x elif logfile: try: import logging except ImportError: debug = lambda x: open(logfile, 'a').write(x + '\n') else: logging.basicConfig(filename=logfile, level=logging.DEBUG) debug = logging.debug else: debug = lambda x: None _is_win64 = None def is_win64(): """Return true if running on windows 64 bits. Works whether python itself runs in 64 bits or 32 bits.""" # Unfortunately, python does not provide a useful way to determine # if the underlying Windows OS is 32-bit or 64-bit. Worse, whether # the Python itself is 32-bit or 64-bit affects what it returns, # so nothing in sys.* or os.* help. # Apparently the best solution is to use env vars that Windows # sets. If PROCESSOR_ARCHITECTURE is not x86, then the python # process is running in 64 bit mode (on a 64-bit OS, 64-bit # hardware, obviously). # If this python is 32-bit but the OS is 64, Windows will set # ProgramW6432 and PROCESSOR_ARCHITEW6432 to non-null. # (Checking for HKLM\Software\Wow6432Node in the registry doesn't # work, because some 32-bit installers create it.) global _is_win64 if _is_win64 is None: # I structured these tests to make it easy to add new ones or # add exceptions in the future, because this is a bit fragile. _is_win64 = False if os.environ.get('PROCESSOR_ARCHITECTURE','x86') != 'x86': _is_win64 = True if os.environ.get('PROCESSOR_ARCHITEW6432'): _is_win64 = True if os.environ.get('ProgramW6432'): _is_win64 = True return _is_win64 def read_reg(value): return SCons.Util.RegGetValue(SCons.Util.HKEY_LOCAL_MACHINE, value)[0] def has_reg(value): """Return True if the given key exists in HKEY_LOCAL_MACHINE, False otherwise.""" try: SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE, value) ret = True except WindowsError: ret = False return ret # Functions for fetching environment variable settings from batch files. def normalize_env(env, keys, force=False): """Given a dictionary representing a shell environment, add the variables from os.environ needed for the processing of .bat files; the keys are controlled by the keys argument. It also makes sure the environment values are correctly encoded. If force=True, then all of the key values that exist are copied into the returned dictionary. If force=false, values are only copied if the key does not already exist in the copied dictionary. Note: the environment is copied.""" normenv = {} if env: for k in env.keys(): normenv[k] = copy.deepcopy(env[k]).encode('mbcs') for k in keys: if k in os.environ and (force or not k in normenv): normenv[k] = os.environ[k].encode('mbcs') return normenv def get_output(vcbat, args = None, env = None): """Parse the output of given bat file, with given args.""" if env is None: # Create a blank environment, for use in launching the tools env = SCons.Environment.Environment(tools=[]) # TODO: This is a hard-coded list of the variables that (may) need # to be imported from os.environ[] for v[sc]*vars*.bat file # execution to work. This list should really be either directly # controlled by vc.py, or else derived from the common_tools_var # settings in vs.py. vars = [ 'COMSPEC', 'VS90COMNTOOLS', 'VS80COMNTOOLS', 'VS71COMNTOOLS', 'VS70COMNTOOLS', 'VS60COMNTOOLS', ] env['ENV'] = normalize_env(env['ENV'], vars, force=False) if args: debug("Calling '%s %s'" % (vcbat, args)) popen = SCons.Action._subproc(env, '"%s" %s & set' % (vcbat, args), stdin = 'devnull', stdout=subprocess.PIPE, stderr=subprocess.PIPE) else: debug("Calling '%s'" % vcbat) popen = SCons.Action._subproc(env, '"%s" & set' % vcbat, stdin = 'devnull', stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Use the .stdout and .stderr attributes directly because the # .communicate() method uses the threading module on Windows # and won't work under Pythons not built with threading. stdout = popen.stdout.read() stderr = popen.stderr.read() if stderr: # TODO: find something better to do with stderr; # this at least prevents errors from getting swallowed. import sys sys.stderr.write(stderr) if popen.wait() != 0: raise IOError(stderr.decode("mbcs")) output = stdout.decode("mbcs") return output def parse_output(output, keep = ("INCLUDE", "LIB", "LIBPATH", "PATH")): # dkeep is a dict associating key: path_list, where key is one item from # keep, and pat_list the associated list of paths dkeep = dict([(i, []) for i in keep]) # rdk will keep the regex to match the .bat file output line starts rdk = {} for i in keep: rdk[i] = re.compile('%s=(.*)' % i, re.I) def add_env(rmatch, key, dkeep=dkeep): plist = rmatch.group(1).split(os.pathsep) for p in plist: # Do not add empty paths (when a var ends with ;) if p: p = p.encode('mbcs') # XXX: For some reason, VC98 .bat file adds "" around the PATH # values, and it screws up the environment later, so we strip # it. p = p.strip('"') dkeep[key].append(p) for line in output.splitlines(): for k,v in rdk.items(): m = v.match(line) if m: add_env(m, k) return dkeep # TODO(sgk): unused def output_to_dict(output): """Given an output string, parse it to find env variables. Return a dict where keys are variables names, and values their content""" envlinem = re.compile(r'^([a-zA-z0-9]+)=([\S\s]*)$') parsedenv = {} for line in output.splitlines(): m = envlinem.match(line) if m: parsedenv[m.group(1)] = m.group(2) return parsedenv # TODO(sgk): unused def get_new(l1, l2): """Given two list l1 and l2, return the items in l2 which are not in l1. Order is maintained.""" # We don't try to be smart: lists are small, and this is not the bottleneck # is any case new = [] for i in l2: if i not in l1: new.append(i) return new # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.qt Tool-specific initialization for Qt. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/qt.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os.path import re import SCons.Action import SCons.Builder import SCons.Defaults import SCons.Scanner import SCons.Tool import SCons.Util class ToolQtWarning(SCons.Warnings.Warning): pass class GeneratedMocFileNotIncluded(ToolQtWarning): pass class QtdirNotFound(ToolQtWarning): pass SCons.Warnings.enableWarningClass(ToolQtWarning) header_extensions = [".h", ".hxx", ".hpp", ".hh"] if SCons.Util.case_sensitive_suffixes('.h', '.H'): header_extensions.append('.H') cplusplus = __import__('c++', globals(), locals(), []) cxx_suffixes = cplusplus.CXXSuffixes def checkMocIncluded(target, source, env): moc = target[0] cpp = source[0] # looks like cpp.includes is cleared before the build stage :-( # not really sure about the path transformations (moc.cwd? cpp.cwd?) :-/ path = SCons.Defaults.CScan.path(env, moc.cwd) includes = SCons.Defaults.CScan(cpp, env, path) if not moc in includes: SCons.Warnings.warn( GeneratedMocFileNotIncluded, "Generated moc file '%s' is not included by '%s'" % (str(moc), str(cpp))) def find_file(filename, paths, node_factory): for dir in paths: node = node_factory(filename, dir) if node.rexists(): return node return None class _Automoc(object): """ Callable class, which works as an emitter for Programs, SharedLibraries and StaticLibraries. """ def __init__(self, objBuilderName): self.objBuilderName = objBuilderName def __call__(self, target, source, env): """ Smart autoscan function. Gets the list of objects for the Program or Lib. Adds objects and builders for the special qt files. """ try: if int(env.subst('$QT_AUTOSCAN')) == 0: return target, source except ValueError: pass try: debug = int(env.subst('$QT_DEBUG')) except ValueError: debug = 0 # some shortcuts used in the scanner splitext = SCons.Util.splitext objBuilder = getattr(env, self.objBuilderName) # some regular expressions: # Q_OBJECT detection q_object_search = re.compile(r'[^A-Za-z0-9]Q_OBJECT[^A-Za-z0-9]') # cxx and c comment 'eater' #comment = re.compile(r'(//.*)|(/\*(([^*])|(\*[^/]))*\*/)') # CW: something must be wrong with the regexp. See also bug #998222 # CURRENTLY THERE IS NO TEST CASE FOR THAT # The following is kind of hacky to get builders working properly (FIXME) objBuilderEnv = objBuilder.env objBuilder.env = env mocBuilderEnv = env.Moc.env env.Moc.env = env # make a deep copy for the result; MocH objects will be appended out_sources = source[:] for obj in source: if not obj.has_builder(): # binary obj file provided if debug: print "scons: qt: '%s' seems to be a binary. Discarded." % str(obj) continue cpp = obj.sources[0] if not splitext(str(cpp))[1] in cxx_suffixes: if debug: print "scons: qt: '%s' is no cxx file. Discarded." % str(cpp) # c or fortran source continue #cpp_contents = comment.sub('', cpp.get_text_contents()) cpp_contents = cpp.get_text_contents() h=None for h_ext in header_extensions: # try to find the header file in the corresponding source # directory hname = splitext(cpp.name)[0] + h_ext h = find_file(hname, (cpp.get_dir(),), env.File) if h: if debug: print "scons: qt: Scanning '%s' (header of '%s')" % (str(h), str(cpp)) #h_contents = comment.sub('', h.get_text_contents()) h_contents = h.get_text_contents() break if not h and debug: print "scons: qt: no header for '%s'." % (str(cpp)) if h and q_object_search.search(h_contents): # h file with the Q_OBJECT macro found -> add moc_cpp moc_cpp = env.Moc(h) moc_o = objBuilder(moc_cpp) out_sources.append(moc_o) #moc_cpp.target_scanner = SCons.Defaults.CScan if debug: print "scons: qt: found Q_OBJECT macro in '%s', moc'ing to '%s'" % (str(h), str(moc_cpp)) if cpp and q_object_search.search(cpp_contents): # cpp file with Q_OBJECT macro found -> add moc # (to be included in cpp) moc = env.Moc(cpp) env.Ignore(moc, moc) if debug: print "scons: qt: found Q_OBJECT macro in '%s', moc'ing to '%s'" % (str(cpp), str(moc)) #moc.source_scanner = SCons.Defaults.CScan # restore the original env attributes (FIXME) objBuilder.env = objBuilderEnv env.Moc.env = mocBuilderEnv return (target, out_sources) AutomocShared = _Automoc('SharedObject') AutomocStatic = _Automoc('StaticObject') def _detect(env): """Not really safe, but fast method to detect the QT library""" QTDIR = None if not QTDIR: QTDIR = env.get('QTDIR',None) if not QTDIR: QTDIR = os.environ.get('QTDIR',None) if not QTDIR: moc = env.WhereIs('moc') if moc: QTDIR = os.path.dirname(os.path.dirname(moc)) SCons.Warnings.warn( QtdirNotFound, "Could not detect qt, using moc executable as a hint (QTDIR=%s)" % QTDIR) else: QTDIR = None SCons.Warnings.warn( QtdirNotFound, "Could not detect qt, using empty QTDIR") return QTDIR def uicEmitter(target, source, env): adjustixes = SCons.Util.adjustixes bs = SCons.Util.splitext(str(source[0].name))[0] bs = os.path.join(str(target[0].get_dir()),bs) # first target (header) is automatically added by builder if len(target) < 2: # second target is implementation target.append(adjustixes(bs, env.subst('$QT_UICIMPLPREFIX'), env.subst('$QT_UICIMPLSUFFIX'))) if len(target) < 3: # third target is moc file target.append(adjustixes(bs, env.subst('$QT_MOCHPREFIX'), env.subst('$QT_MOCHSUFFIX'))) return target, source def uicScannerFunc(node, env, path): lookout = [] lookout.extend(env['CPPPATH']) lookout.append(str(node.rfile().dir)) includes = re.findall("<include.*?>(.*?)</include>", node.get_text_contents()) result = [] for incFile in includes: dep = env.FindFile(incFile,lookout) if dep: result.append(dep) return result uicScanner = SCons.Scanner.Base(uicScannerFunc, name = "UicScanner", node_class = SCons.Node.FS.File, node_factory = SCons.Node.FS.File, recursive = 0) def generate(env): """Add Builders and construction variables for qt to an Environment.""" CLVar = SCons.Util.CLVar Action = SCons.Action.Action Builder = SCons.Builder.Builder env.SetDefault(QTDIR = _detect(env), QT_BINPATH = os.path.join('$QTDIR', 'bin'), QT_CPPPATH = os.path.join('$QTDIR', 'include'), QT_LIBPATH = os.path.join('$QTDIR', 'lib'), QT_MOC = os.path.join('$QT_BINPATH','moc'), QT_UIC = os.path.join('$QT_BINPATH','uic'), QT_LIB = 'qt', # may be set to qt-mt QT_AUTOSCAN = 1, # scan for moc'able sources # Some QT specific flags. I don't expect someone wants to # manipulate those ... QT_UICIMPLFLAGS = CLVar(''), QT_UICDECLFLAGS = CLVar(''), QT_MOCFROMHFLAGS = CLVar(''), QT_MOCFROMCXXFLAGS = CLVar('-i'), # suffixes/prefixes for the headers / sources to generate QT_UICDECLPREFIX = '', QT_UICDECLSUFFIX = '.h', QT_UICIMPLPREFIX = 'uic_', QT_UICIMPLSUFFIX = '$CXXFILESUFFIX', QT_MOCHPREFIX = 'moc_', QT_MOCHSUFFIX = '$CXXFILESUFFIX', QT_MOCCXXPREFIX = '', QT_MOCCXXSUFFIX = '.moc', QT_UISUFFIX = '.ui', # Commands for the qt support ... # command to generate header, implementation and moc-file # from a .ui file QT_UICCOM = [ CLVar('$QT_UIC $QT_UICDECLFLAGS -o ${TARGETS[0]} $SOURCE'), CLVar('$QT_UIC $QT_UICIMPLFLAGS -impl ${TARGETS[0].file} ' '-o ${TARGETS[1]} $SOURCE'), CLVar('$QT_MOC $QT_MOCFROMHFLAGS -o ${TARGETS[2]} ${TARGETS[0]}')], # command to generate meta object information for a class # declarated in a header QT_MOCFROMHCOM = ( '$QT_MOC $QT_MOCFROMHFLAGS -o ${TARGETS[0]} $SOURCE'), # command to generate meta object information for a class # declarated in a cpp file QT_MOCFROMCXXCOM = [ CLVar('$QT_MOC $QT_MOCFROMCXXFLAGS -o ${TARGETS[0]} $SOURCE'), Action(checkMocIncluded,None)]) # ... and the corresponding builders uicBld = Builder(action=SCons.Action.Action('$QT_UICCOM', '$QT_UICCOMSTR'), emitter=uicEmitter, src_suffix='$QT_UISUFFIX', suffix='$QT_UICDECLSUFFIX', prefix='$QT_UICDECLPREFIX', source_scanner=uicScanner) mocBld = Builder(action={}, prefix={}, suffix={}) for h in header_extensions: act = SCons.Action.Action('$QT_MOCFROMHCOM', '$QT_MOCFROMHCOMSTR') mocBld.add_action(h, act) mocBld.prefix[h] = '$QT_MOCHPREFIX' mocBld.suffix[h] = '$QT_MOCHSUFFIX' for cxx in cxx_suffixes: act = SCons.Action.Action('$QT_MOCFROMCXXCOM', '$QT_MOCFROMCXXCOMSTR') mocBld.add_action(cxx, act) mocBld.prefix[cxx] = '$QT_MOCCXXPREFIX' mocBld.suffix[cxx] = '$QT_MOCCXXSUFFIX' # register the builders env['BUILDERS']['Uic'] = uicBld env['BUILDERS']['Moc'] = mocBld static_obj, shared_obj = SCons.Tool.createObjBuilders(env) static_obj.add_src_builder('Uic') shared_obj.add_src_builder('Uic') # We use the emitters of Program / StaticLibrary / SharedLibrary # to scan for moc'able files # We can't refer to the builders directly, we have to fetch them # as Environment attributes because that sets them up to be called # correctly later by our emitter. env.AppendUnique(PROGEMITTER =[AutomocStatic], SHLIBEMITTER=[AutomocShared], LIBEMITTER =[AutomocStatic], # Of course, we need to link against the qt libraries CPPPATH=["$QT_CPPPATH"], LIBPATH=["$QT_LIBPATH"], LIBS=['$QT_LIB']) def exists(env): return _detect(env) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.GettextCommon module Used by several tools of `gettext` toolset. """ # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. __revision__ = "src/engine/SCons/Tool/GettextCommon.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Warnings import re ############################################################################# class XgettextToolWarning(SCons.Warnings.Warning): pass class XgettextNotFound(XgettextToolWarning): pass class MsginitToolWarning(SCons.Warnings.Warning): pass class MsginitNotFound(MsginitToolWarning): pass class MsgmergeToolWarning(SCons.Warnings.Warning): pass class MsgmergeNotFound(MsgmergeToolWarning): pass class MsgfmtToolWarning(SCons.Warnings.Warning): pass class MsgfmtNotFound(MsgfmtToolWarning): pass ############################################################################# SCons.Warnings.enableWarningClass(XgettextToolWarning) SCons.Warnings.enableWarningClass(XgettextNotFound) SCons.Warnings.enableWarningClass(MsginitToolWarning) SCons.Warnings.enableWarningClass(MsginitNotFound) SCons.Warnings.enableWarningClass(MsgmergeToolWarning) SCons.Warnings.enableWarningClass(MsgmergeNotFound) SCons.Warnings.enableWarningClass(MsgfmtToolWarning) SCons.Warnings.enableWarningClass(MsgfmtNotFound) ############################################################################# ############################################################################# class _POTargetFactory(object): """ A factory of `PO` target files. Factory defaults differ from these of `SCons.Node.FS.FS`. We set `precious` (this is required by builders and actions gettext) and `noclean` flags by default for all produced nodes. """ def __init__( self, env, nodefault = True, alias = None, precious = True , noclean = True ): """ Object constructor. **Arguments** - *env* (`SCons.Environment.Environment`) - *nodefault* (`boolean`) - if `True`, produced nodes will be ignored from default target `'.'` - *alias* (`string`) - if provided, produced nodes will be automatically added to this alias, and alias will be set as `AlwaysBuild` - *precious* (`boolean`) - if `True`, the produced nodes will be set as `Precious`. - *noclen* (`boolean`) - if `True`, the produced nodes will be excluded from `Clean`. """ self.env = env self.alias = alias self.precious = precious self.noclean = noclean self.nodefault = nodefault def _create_node(self, name, factory, directory = None, create = 1): """ Create node, and set it up to factory settings. """ import SCons.Util node = factory(name, directory, create) node.set_noclean(self.noclean) node.set_precious(self.precious) if self.nodefault: self.env.Ignore('.', node) if self.alias: self.env.AlwaysBuild(self.env.Alias(self.alias, node)) return node def Entry(self, name, directory = None, create = 1): """ Create `SCons.Node.FS.Entry` """ return self._create_node(name, self.env.fs.Entry, directory, create) def File(self, name, directory = None, create = 1): """ Create `SCons.Node.FS.File` """ return self._create_node(name, self.env.fs.File, directory, create) ############################################################################# ############################################################################# _re_comment = re.compile(r'(#[^\n\r]+)$', re.M) _re_lang = re.compile(r'([a-zA-Z0-9_]+)', re.M) ############################################################################# def _read_linguas_from_files(env, linguas_files = None): """ Parse `LINGUAS` file and return list of extracted languages """ import SCons.Util import SCons.Environment global _re_comment global _re_lang if not SCons.Util.is_List(linguas_files) \ and not SCons.Util.is_String(linguas_files) \ and not isinstance(linguas_files, SCons.Node.FS.Base) \ and linguas_files: # If, linguas_files==True or such, then read 'LINGUAS' file. linguas_files = [ 'LINGUAS' ] if linguas_files is None: return [] fnodes = env.arg2nodes(linguas_files) linguas = [] for fnode in fnodes: contents = _re_comment.sub("", fnode.get_text_contents()) ls = [ l for l in _re_lang.findall(contents) if l ] linguas.extend(ls) return linguas ############################################################################# ############################################################################# from SCons.Builder import BuilderBase ############################################################################# class _POFileBuilder(BuilderBase): """ `PO` file builder. This is multi-target single-source builder. In typical situation the source is single `POT` file, e.g. `messages.pot`, and there are multiple `PO` targets to be updated from this `POT`. We must run `SCons.Builder.BuilderBase._execute()` separatelly for each target to track dependencies separatelly for each target file. **NOTE**: if we call `SCons.Builder.BuilderBase._execute(.., target, ...)` with target being list of all targets, all targets would be rebuilt each time one of the targets from this list is missing. This would happen, for example, when new language `ll` enters `LINGUAS_FILE` (at this moment there is no `ll.po` file yet). To avoid this, we override `SCons.Builder.BuilerBase._execute()` and call it separatelly for each target. Here we also append to the target list the languages read from `LINGUAS_FILE`. """ # #* The argument for overriding _execute(): We must use environment with # builder overrides applied (see BuilderBase.__init__(). Here it comes for # free. #* The argument against using 'emitter': The emitter is called too late # by BuilderBase._execute(). If user calls, for example: # # env.POUpdate(LINGUAS_FILE = 'LINGUAS') # # the builder throws error, because it is called with target=None, # source=None and is trying to "generate" sources or target list first. # If user calls # # env.POUpdate(['foo', 'baz'], LINGUAS_FILE = 'LINGUAS') # # the env.BuilderWrapper() calls our builder with target=None, # source=['foo', 'baz']. The BuilderBase._execute() then splits execution # and execute iterativelly (recursion) self._execute(None, source[i]). # After that it calls emitter (which is quite too late). The emitter is # also called in each iteration, what makes things yet worse. def __init__(self, env, **kw): if not 'suffix' in kw: kw['suffix'] = '$POSUFFIX' if not 'src_suffix' in kw: kw['src_suffix'] = '$POTSUFFIX' if not 'src_builder' in kw: kw['src_builder'] = '_POTUpdateBuilder' if not 'single_source' in kw: kw['single_source'] = True alias = None if 'target_alias' in kw: alias = kw['target_alias'] del kw['target_alias'] if not 'target_factory' in kw: kw['target_factory'] = _POTargetFactory(env, alias=alias).File BuilderBase.__init__(self, **kw) def _execute(self, env, target, source, *args, **kw): """ Execute builder's actions. Here we append to `target` the languages read from `$LINGUAS_FILE` and apply `SCons.Builder.BuilderBase._execute()` separatelly to each target. The arguments and return value are same as for `SCons.Builder.BuilderBase._execute()`. """ import SCons.Util import SCons.Node linguas_files = None if env.has_key('LINGUAS_FILE') and env['LINGUAS_FILE']: linguas_files = env['LINGUAS_FILE'] # This prevents endless recursion loop (we'll be invoked once for # each target appended here, we must not extend the list again). env['LINGUAS_FILE'] = None linguas = _read_linguas_from_files(env,linguas_files) if SCons.Util.is_List(target): target.extend(linguas) elif target is not None: target = [target] + linguas else: target = linguas if not target: # Let the SCons.BuilderBase to handle this patologic situation return BuilderBase._execute( self, env, target, source, *args, **kw) # The rest is ours if not SCons.Util.is_List(target): target = [ target ] result = [] for tgt in target: r = BuilderBase._execute( self, env, [tgt], source, *args, **kw) result.extend(r) if linguas_files is not None: env['LINGUAS_FILE'] = linguas_files return SCons.Node.NodeList(result) ############################################################################# import SCons.Environment ############################################################################# def _translate(env, target=[], source=SCons.Environment._null, *args, **kw): """ Function for `Translate()` pseudo-builder """ pot = env.POTUpdate(None, source, *args, **kw) po = env.POUpdate(target, pot, *args, **kw) return po ############################################################################# ############################################################################# class RPaths(object): """ Callable object, which returns pathnames relative to SCons current working directory. It seems like `SCons.Node.FS.Base.get_path()` returns absolute paths for nodes that are outside of current working directory (`env.fs.getcwd()`). Here, we often have `SConscript`, `POT` and `PO` files within `po/` directory and source files (e.g. `*.c`) outside of it. When generating `POT` template file, references to source files are written to `POT` template, so a translator may later quickly jump to appropriate source file and line from its `PO` editor (e.g. `poedit`). Relative paths in `PO` file are usually interpreted by `PO` editor as paths relative to the place, where `PO` file lives. The absolute paths would make resultant `POT` file nonportable, as the references would be correct only on the machine, where `POT` file was recently re-created. For such reason, we need a function, which always returns relative paths. This is the purpose of `RPaths` callable object. The `__call__` method returns paths relative to current woking directory, but we assume, that *xgettext(1)* is run from the directory, where target file is going to be created. Note, that this may not work for files distributed over several hosts or across different drives on windows. We assume here, that single local filesystem holds both source files and target `POT` templates. Intended use of `RPaths` - in `xgettext.py`:: def generate(env): from GettextCommon import RPaths ... sources = '$( ${_concat( "", SOURCES, "", __env__, XgettextRPaths, TARGET, SOURCES)} $)' env.Append( ... XGETTEXTCOM = 'XGETTEXT ... ' + sources, ... XgettextRPaths = RPaths(env) ) """ # NOTE: This callable object returns pathnames of dirs/files relative to # current working directory. The pathname remains relative also for entries # that are outside of current working directory (node, that # SCons.Node.FS.File and siblings return absolute path in such case). For # simplicity we compute path relative to current working directory, this # seems be enough for our purposes (don't need TARGET variable and # SCons.Defaults.Variable_Caller stuff). def __init__(self, env): """ Initialize `RPaths` callable object. **Arguments**: - *env* - a `SCons.Environment.Environment` object, defines *current working dir*. """ self.env = env # FIXME: I'm not sure, how it should be implemented (what the *args are in # general, what is **kw). def __call__(self, nodes, *args, **kw): """ Return nodes' paths (strings) relative to current working directory. **Arguments**: - *nodes* ([`SCons.Node.FS.Base`]) - list of nodes. - *args* - currently unused. - *kw* - currently unused. **Returns**: - Tuple of strings, which represent paths relative to current working directory (for given environment). """ # os.path.relpath is available only on python >= 2.6. We use our own # implementation. It's taken from BareNecessities package: # http://jimmyg.org/work/code/barenecessities/index.html from posixpath import curdir def relpath(path, start=curdir): import posixpath """Return a relative version of a path""" if not path: raise ValueError("no path specified") start_list = posixpath.abspath(start).split(posixpath.sep) path_list = posixpath.abspath(path).split(posixpath.sep) # Work out how much of the filepath is shared by start and path. i = len(posixpath.commonprefix([start_list, path_list])) rel_list = [posixpath.pardir] * (len(start_list)-i) + path_list[i:] if not rel_list: return posixpath.curdir return posixpath.join(*rel_list) import os import SCons.Node.FS rpaths = () cwd = self.env.fs.getcwd().get_abspath() for node in nodes: rpath = None if isinstance(node, SCons.Node.FS.Base): rpath = relpath(node.get_abspath(), cwd) # FIXME: Other types possible here? if rpath is not None: rpaths += (rpath,) return rpaths ############################################################################# ############################################################################# def _init_po_files(target, source, env): """ Action function for `POInit` builder. """ nop = lambda target, source, env : 0 if env.has_key('POAUTOINIT'): autoinit = env['POAUTOINIT'] else: autoinit = False # Well, if everything outside works well, this loop should do single # iteration. Otherwise we are rebuilding all the targets even, if just # one has changed (but is this out fault?). for tgt in target: if not tgt.exists(): if autoinit: action = SCons.Action.Action('$MSGINITCOM', '$MSGINITCOMSTR') else: msg = 'File ' + repr(str(tgt)) + ' does not exist. ' \ + 'If you are a translator, you can create it through: \n' \ + '$MSGINITCOM' action = SCons.Action.Action(nop, msg) status = action([tgt], source, env) if status: return status return 0 ############################################################################# ############################################################################# def _detect_xgettext(env): """ Detects *xgettext(1)* binary """ if env.has_key('XGETTEXT'): return env['XGETTEXT'] xgettext = env.Detect('xgettext'); if xgettext: return xgettext raise SCons.Errors.StopError(XgettextNotFound,"Could not detect xgettext") return None ############################################################################# def _xgettext_exists(env): return _detect_xgettext(env) ############################################################################# ############################################################################# def _detect_msginit(env): """ Detects *msginit(1)* program. """ if env.has_key('MSGINIT'): return env['MSGINIT'] msginit = env.Detect('msginit'); if msginit: return msginit raise SCons.Errors.StopError(MsginitNotFound, "Could not detect msginit") return None ############################################################################# def _msginit_exists(env): return _detect_msginit(env) ############################################################################# ############################################################################# def _detect_msgmerge(env): """ Detects *msgmerge(1)* program. """ if env.has_key('MSGMERGE'): return env['MSGMERGE'] msgmerge = env.Detect('msgmerge'); if msgmerge: return msgmerge raise SCons.Errors.StopError(MsgmergeNotFound, "Could not detect msgmerge") return None ############################################################################# def _msgmerge_exists(env): return _detect_msgmerge(env) ############################################################################# ############################################################################# def _detect_msgfmt(env): """ Detects *msgmfmt(1)* program. """ if env.has_key('MSGFMT'): return env['MSGFMT'] msgfmt = env.Detect('msgfmt'); if msgfmt: return msgfmt raise SCons.Errors.StopError(MsgfmtNotFound, "Could not detect msgfmt") return None ############################################################################# def _msgfmt_exists(env): return _detect_msgfmt(env) ############################################################################# ############################################################################# def tool_list(platform, env): """ List tools that shall be generated by top-level `gettext` tool """ return [ 'xgettext', 'msginit', 'msgmerge', 'msgfmt' ] #############################################################################
Python
"""SCons.Tool.gs Tool-specific initialization for Ghostscript. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/gs.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Action import SCons.Platform import SCons.Util # Ghostscript goes by different names on different platforms... platform = SCons.Platform.platform_default() if platform == 'os2': gs = 'gsos2' elif platform == 'win32': gs = 'gswin32c' else: gs = 'gs' GhostscriptAction = None def generate(env): """Add Builders and construction variables for Ghostscript to an Environment.""" global GhostscriptAction if GhostscriptAction is None: GhostscriptAction = SCons.Action.Action('$GSCOM', '$GSCOMSTR') import pdf pdf.generate(env) bld = env['BUILDERS']['PDF'] bld.add_action('.ps', GhostscriptAction) env['GS'] = gs env['GSFLAGS'] = SCons.Util.CLVar('-dNOPAUSE -dBATCH -sDEVICE=pdfwrite') env['GSCOM'] = '$GS $GSFLAGS -sOutputFile=$TARGET $SOURCES' def exists(env): if 'PS2PDF' in env: return env.Detect(env['PS2PDF']) else: return env.Detect(gs) or SCons.Util.WhereIs(gs) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""engine.SCons.Tool.g77 Tool-specific initialization for g77. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/g77.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Util from SCons.Tool.FortranCommon import add_all_to_env, add_f77_to_env compilers = ['g77', 'f77'] def generate(env): """Add Builders and construction variables for g77 to an Environment.""" add_all_to_env(env) add_f77_to_env(env) fcomp = env.Detect(compilers) or 'g77' if env['PLATFORM'] in ['cygwin', 'win32']: env['SHFORTRANFLAGS'] = SCons.Util.CLVar('$FORTRANFLAGS') env['SHF77FLAGS'] = SCons.Util.CLVar('$F77FLAGS') else: env['SHFORTRANFLAGS'] = SCons.Util.CLVar('$FORTRANFLAGS -fPIC') env['SHF77FLAGS'] = SCons.Util.CLVar('$F77FLAGS -fPIC') env['FORTRAN'] = fcomp env['SHFORTRAN'] = '$FORTRAN' env['F77'] = fcomp env['SHF77'] = '$F77' env['INCFORTRANPREFIX'] = "-I" env['INCFORTRANSUFFIX'] = "" env['INCF77PREFIX'] = "-I" env['INCF77SUFFIX'] = "" def exists(env): return env.Detect(compilers) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""engine.SCons.Tool.cvf Tool-specific initialization for the Compaq Visual Fortran compiler. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/cvf.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import fortran compilers = ['f90'] def generate(env): """Add Builders and construction variables for compaq visual fortran to an Environment.""" fortran.generate(env) env['FORTRAN'] = 'f90' env['FORTRANCOM'] = '$FORTRAN $FORTRANFLAGS $_FORTRANMODFLAG $_FORTRANINCFLAGS /compile_only ${SOURCES.windows} /object:${TARGET.windows}' env['FORTRANPPCOM'] = '$FORTRAN $FORTRANFLAGS $CPPFLAGS $_CPPDEFFLAGS $_FORTRANMODFLAG $_FORTRANINCFLAGS /compile_only ${SOURCES.windows} /object:${TARGET.windows}' env['SHFORTRANCOM'] = '$SHFORTRAN $SHFORTRANFLAGS $_FORTRANMODFLAG $_FORTRANINCFLAGS /compile_only ${SOURCES.windows} /object:${TARGET.windows}' env['SHFORTRANPPCOM'] = '$SHFORTRAN $SHFORTRANFLAGS $CPPFLAGS $_CPPDEFFLAGS $_FORTRANMODFLAG $_FORTRANINCFLAGS /compile_only ${SOURCES.windows} /object:${TARGET.windows}' env['OBJSUFFIX'] = '.obj' env['FORTRANMODDIR'] = '${TARGET.dir}' env['FORTRANMODDIRPREFIX'] = '/module:' env['FORTRANMODDIRSUFFIX'] = '' def exists(env): return env.Detect(compilers) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.gcc Tool-specific initialization for MinGW (http://www.mingw.org/) There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/mingw.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os import os.path import SCons.Action import SCons.Builder import SCons.Defaults import SCons.Tool import SCons.Util # This is what we search for to find mingw: key_program = 'mingw32-gcc' def find(env): # First search in the SCons path path=env.WhereIs(key_program) if (path): return path # then the OS path: path=SCons.Util.WhereIs(key_program) if (path): return path # If that doesn't work try default location for mingw save_path=env['ENV']['PATH'] env.AppendENVPath('PATH',r'c:\MinGW\bin') path =env.WhereIs(key_program) if not path: env['ENV']['PATH']=save_path return path def shlib_generator(target, source, env, for_signature): cmd = SCons.Util.CLVar(['$SHLINK', '$SHLINKFLAGS']) dll = env.FindIxes(target, 'SHLIBPREFIX', 'SHLIBSUFFIX') if dll: cmd.extend(['-o', dll]) cmd.extend(['$SOURCES', '$_LIBDIRFLAGS', '$_LIBFLAGS']) implib = env.FindIxes(target, 'LIBPREFIX', 'LIBSUFFIX') if implib: cmd.append('-Wl,--out-implib,'+implib.get_string(for_signature)) def_target = env.FindIxes(target, 'WINDOWSDEFPREFIX', 'WINDOWSDEFSUFFIX') insert_def = env.subst("$WINDOWS_INSERT_DEF") if not insert_def in ['', '0', 0] and def_target: \ cmd.append('-Wl,--output-def,'+def_target.get_string(for_signature)) return [cmd] def shlib_emitter(target, source, env): dll = env.FindIxes(target, 'SHLIBPREFIX', 'SHLIBSUFFIX') no_import_lib = env.get('no_import_lib', 0) if not dll: raise SCons.Errors.UserError("A shared library should have exactly one target with the suffix: %s" % env.subst("$SHLIBSUFFIX")) if not no_import_lib and \ not env.FindIxes(target, 'LIBPREFIX', 'LIBSUFFIX'): # Create list of target libraries as strings targetStrings=env.ReplaceIxes(dll, 'SHLIBPREFIX', 'SHLIBSUFFIX', 'LIBPREFIX', 'LIBSUFFIX') # Now add file nodes to target list target.append(env.fs.File(targetStrings)) # Append a def file target if there isn't already a def file target # or a def file source or the user has explicitly asked for the target # to be emitted. def_source = env.FindIxes(source, 'WINDOWSDEFPREFIX', 'WINDOWSDEFSUFFIX') def_target = env.FindIxes(target, 'WINDOWSDEFPREFIX', 'WINDOWSDEFSUFFIX') skip_def_insert = env.subst("$WINDOWS_INSERT_DEF") in ['', '0', 0] if not def_source and not def_target and not skip_def_insert: # Create list of target libraries and def files as strings targetStrings=env.ReplaceIxes(dll, 'SHLIBPREFIX', 'SHLIBSUFFIX', 'WINDOWSDEFPREFIX', 'WINDOWSDEFSUFFIX') # Now add file nodes to target list target.append(env.fs.File(targetStrings)) return (target, source) shlib_action = SCons.Action.Action(shlib_generator, generator=1) res_action = SCons.Action.Action('$RCCOM', '$RCCOMSTR') res_builder = SCons.Builder.Builder(action=res_action, suffix='.o', source_scanner=SCons.Tool.SourceFileScanner) SCons.Tool.SourceFileScanner.add_scanner('.rc', SCons.Defaults.CScan) def generate(env): mingw = find(env) if mingw: dir = os.path.dirname(mingw) env.PrependENVPath('PATH', dir ) # Most of mingw is the same as gcc and friends... gnu_tools = ['gcc', 'g++', 'gnulink', 'ar', 'gas', 'm4'] for tool in gnu_tools: SCons.Tool.Tool(tool)(env) #... but a few things differ: env['CC'] = 'gcc' env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS') env['CXX'] = 'g++' env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS') env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -shared') env['SHLINKCOM'] = shlib_action env['LDMODULECOM'] = shlib_action env.Append(SHLIBEMITTER = [shlib_emitter]) env['AS'] = 'as' env['WIN32DEFPREFIX'] = '' env['WIN32DEFSUFFIX'] = '.def' env['WINDOWSDEFPREFIX'] = '${WIN32DEFPREFIX}' env['WINDOWSDEFSUFFIX'] = '${WIN32DEFSUFFIX}' env['SHOBJSUFFIX'] = '.o' env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1 env['RC'] = 'windres' env['RCFLAGS'] = SCons.Util.CLVar('') env['RCINCFLAGS'] = '$( ${_concat(RCINCPREFIX, CPPPATH, RCINCSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)' env['RCINCPREFIX'] = '--include-dir ' env['RCINCSUFFIX'] = '' env['RCCOM'] = '$RC $_CPPDEFFLAGS $RCINCFLAGS ${RCINCPREFIX} ${SOURCE.dir} $RCFLAGS -i $SOURCE -o $TARGET' env['BUILDERS']['RES'] = res_builder # Some setting from the platform also have to be overridden: env['OBJSUFFIX'] = '.o' env['LIBPREFIX'] = 'lib' env['LIBSUFFIX'] = '.a' def exists(env): return find(env) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.sgicc Tool-specific initialization for MIPSPro cc on SGI. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/sgicc.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import cc def generate(env): """Add Builders and construction variables for gcc to an Environment.""" cc.generate(env) env['CXX'] = 'CC' env['SHOBJSUFFIX'] = '.o' env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1 def exists(env): return env.Detect('cc') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.SCCS.py Tool-specific initialization for SCCS. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. __revision__ = "src/engine/SCons/Tool/SCCS.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Action import SCons.Builder import SCons.Util def generate(env): """Add a Builder factory function and construction variables for SCCS to an Environment.""" def SCCSFactory(env=env): """ """ import SCons.Warnings as W W.warn(W.DeprecatedSourceCodeWarning, """The SCCS() factory is deprecated and there is no replacement.""") act = SCons.Action.Action('$SCCSCOM', '$SCCSCOMSTR') return SCons.Builder.Builder(action = act, env = env) #setattr(env, 'SCCS', SCCSFactory) env.SCCS = SCCSFactory env['SCCS'] = 'sccs' env['SCCSFLAGS'] = SCons.Util.CLVar('') env['SCCSGETFLAGS'] = SCons.Util.CLVar('') env['SCCSCOM'] = '$SCCS $SCCSFLAGS get $SCCSGETFLAGS $TARGET' def exists(env): return env.Detect('sccs') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.gcc Tool-specific initialization for gcc. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/gcc.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import cc import os import re import subprocess import SCons.Util compilers = ['gcc', 'cc'] def generate(env): """Add Builders and construction variables for gcc to an Environment.""" cc.generate(env) env['CC'] = env.Detect(compilers) or 'gcc' if env['PLATFORM'] in ['cygwin', 'win32']: env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS') else: env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS -fPIC') # determine compiler version if env['CC']: #pipe = SCons.Action._subproc(env, [env['CC'], '-dumpversion'], pipe = SCons.Action._subproc(env, [env['CC'], '--version'], stdin = 'devnull', stderr = 'devnull', stdout = subprocess.PIPE) if pipe.wait() != 0: return # -dumpversion was added in GCC 3.0. As long as we're supporting # GCC versions older than that, we should use --version and a # regular expression. #line = pipe.stdout.read().strip() #if line: # env['CCVERSION'] = line line = pipe.stdout.readline() match = re.search(r'[0-9]+(\.[0-9]+)+', line) if match: env['CCVERSION'] = match.group(0) def exists(env): return env.Detect(compilers) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.tar Tool-specific initialization for tar. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/tar.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Action import SCons.Builder import SCons.Defaults import SCons.Node.FS import SCons.Util tars = ['tar', 'gtar'] TarAction = SCons.Action.Action('$TARCOM', '$TARCOMSTR') TarBuilder = SCons.Builder.Builder(action = TarAction, source_factory = SCons.Node.FS.Entry, source_scanner = SCons.Defaults.DirScanner, suffix = '$TARSUFFIX', multi = 1) def generate(env): """Add Builders and construction variables for tar to an Environment.""" try: bld = env['BUILDERS']['Tar'] except KeyError: bld = TarBuilder env['BUILDERS']['Tar'] = bld env['TAR'] = env.Detect(tars) or 'gtar' env['TARFLAGS'] = SCons.Util.CLVar('-c') env['TARCOM'] = '$TAR $TARFLAGS -f $TARGET $SOURCES' env['TARSUFFIX'] = '.tar' def exists(env): return env.Detect(tars) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.sunlink Tool-specific initialization for the Sun Solaris (Forte) linker. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/sunlink.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os import os.path import SCons.Util import link ccLinker = None # search for the acc compiler and linker front end try: dirs = os.listdir('/opt') except (IOError, OSError): # Not being able to read the directory because it doesn't exist # (IOError) or isn't readable (OSError) is okay. dirs = [] for d in dirs: linker = '/opt/' + d + '/bin/CC' if os.path.exists(linker): ccLinker = linker break def generate(env): """Add Builders and construction variables for Forte to an Environment.""" link.generate(env) env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -G') env['RPATHPREFIX'] = '-R' env['RPATHSUFFIX'] = '' env['_RPATH'] = '${_concat(RPATHPREFIX, RPATH, RPATHSUFFIX, __env__)}' def exists(env): return ccLinker # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
""" msginit tool Tool specific initialization of msginit tool. """ # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. __revision__ = "src/engine/SCons/Tool/msginit.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Warnings import SCons.Builder import re ############################################################################# def _optional_no_translator_flag(env): """ Return '--no-translator' flag if we run *msginit(1)* in non-interactive mode.""" import SCons.Util if env.has_key('POAUTOINIT'): autoinit = env['POAUTOINIT'] else: autoinit = False if autoinit: return [SCons.Util.CLVar('--no-translator')] else: return [SCons.Util.CLVar('')] ############################################################################# ############################################################################# def _POInitBuilder(env, **kw): """ Create builder object for `POInit` builder. """ import SCons.Action from SCons.Tool.GettextCommon import _init_po_files, _POFileBuilder action = SCons.Action.Action(_init_po_files, None) return _POFileBuilder(env, action=action, target_alias='$POCREATE_ALIAS') ############################################################################# ############################################################################# from SCons.Environment import _null ############################################################################# def _POInitBuilderWrapper(env, target=None, source=_null, **kw): """ Wrapper for _POFileBuilder. We use it to make user's life easier. This wrapper checks for `$POTDOMAIN` construction variable (or override in `**kw`) and treats it appropriatelly. """ if source is _null: if 'POTDOMAIN' in kw: domain = kw['POTDOMAIN'] elif env.has_key('POTDOMAIN'): domain = env['POTDOMAIN'] else: domain = 'messages' source = [ domain ] # NOTE: Suffix shall be appended automatically return env._POInitBuilder(target, source, **kw) ############################################################################# ############################################################################# def generate(env,**kw): """ Generate the `msginit` tool """ import SCons.Util from SCons.Tool.GettextCommon import _detect_msginit env['MSGINIT'] = _detect_msginit(env) msginitcom = '$MSGINIT ${_MSGNoTranslator(__env__)} -l ${_MSGINITLOCALE}' \ + ' $MSGINITFLAGS -i $SOURCE -o $TARGET' # NOTE: We set POTSUFFIX here, in case the 'xgettext' is not loaded # (sometimes we really don't need it) env.SetDefault( POSUFFIX = ['.po'], POTSUFFIX = ['.pot'], _MSGINITLOCALE = '${TARGET.filebase}', _MSGNoTranslator = _optional_no_translator_flag, MSGINITCOM = msginitcom, MSGINITCOMSTR = '', MSGINITFLAGS = [ ], POAUTOINIT = False, POCREATE_ALIAS = 'po-create' ) env.Append( BUILDERS = { '_POInitBuilder' : _POInitBuilder(env) } ) env.AddMethod(_POInitBuilderWrapper, 'POInit') env.AlwaysBuild(env.Alias('$POCREATE_ALIAS')) ############################################################################# ############################################################################# def exists(env): """ Check if the tool exists """ from SCons.Tool.GettextCommon import _msginit_exists return _msginit_exists(env) ############################################################################# # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.CVS.py Tool-specific initialization for CVS. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. __revision__ = "src/engine/SCons/Tool/CVS.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Action import SCons.Builder import SCons.Util def generate(env): """Add a Builder factory function and construction variables for CVS to an Environment.""" def CVSFactory(repos, module='', env=env): """ """ import SCons.Warnings as W W.warn(W.DeprecatedSourceCodeWarning, """The CVS() factory is deprecated and there is no replacement.""") # fail if repos is not an absolute path name? if module != '': # Don't use os.path.join() because the name we fetch might # be across a network and must use POSIX slashes as separators. module = module + '/' env['CVSCOM'] = '$CVS $CVSFLAGS co $CVSCOFLAGS -d ${TARGET.dir} $CVSMODULE${TARGET.posix}' act = SCons.Action.Action('$CVSCOM', '$CVSCOMSTR') return SCons.Builder.Builder(action = act, env = env, CVSREPOSITORY = repos, CVSMODULE = module) #setattr(env, 'CVS', CVSFactory) env.CVS = CVSFactory env['CVS'] = 'cvs' env['CVSFLAGS'] = SCons.Util.CLVar('-d $CVSREPOSITORY') env['CVSCOFLAGS'] = SCons.Util.CLVar('') env['CVSCOM'] = '$CVS $CVSFLAGS co $CVSCOFLAGS ${TARGET.posix}' def exists(env): return env.Detect('cvs') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.nasm Tool-specific initialization for nasm, the famous Netwide Assembler. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/nasm.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Defaults import SCons.Tool import SCons.Util ASSuffixes = ['.s', '.asm', '.ASM'] ASPPSuffixes = ['.spp', '.SPP', '.sx'] if SCons.Util.case_sensitive_suffixes('.s', '.S'): ASPPSuffixes.extend(['.S']) else: ASSuffixes.extend(['.S']) def generate(env): """Add Builders and construction variables for nasm to an Environment.""" static_obj, shared_obj = SCons.Tool.createObjBuilders(env) for suffix in ASSuffixes: static_obj.add_action(suffix, SCons.Defaults.ASAction) static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter) for suffix in ASPPSuffixes: static_obj.add_action(suffix, SCons.Defaults.ASPPAction) static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter) env['AS'] = 'nasm' env['ASFLAGS'] = SCons.Util.CLVar('') env['ASPPFLAGS'] = '$ASFLAGS' env['ASCOM'] = '$AS $ASFLAGS -o $TARGET $SOURCES' env['ASPPCOM'] = '$CC $ASPPFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS -c -o $TARGET $SOURCES' def exists(env): return env.Detect('nasm') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.c++ Tool-specific initialization for generic Posix C++ compilers. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/c++.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os.path import SCons.Tool import SCons.Defaults import SCons.Util compilers = ['CC', 'c++'] CXXSuffixes = ['.cpp', '.cc', '.cxx', '.c++', '.C++', '.mm'] if SCons.Util.case_sensitive_suffixes('.c', '.C'): CXXSuffixes.append('.C') def iscplusplus(source): if not source: # Source might be None for unusual cases like SConf. return 0 for s in source: if s.sources: ext = os.path.splitext(str(s.sources[0]))[1] if ext in CXXSuffixes: return 1 return 0 def generate(env): """ Add Builders and construction variables for Visual Age C++ compilers to an Environment. """ import SCons.Tool import SCons.Tool.cc static_obj, shared_obj = SCons.Tool.createObjBuilders(env) for suffix in CXXSuffixes: static_obj.add_action(suffix, SCons.Defaults.CXXAction) shared_obj.add_action(suffix, SCons.Defaults.ShCXXAction) static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter) shared_obj.add_emitter(suffix, SCons.Defaults.SharedObjectEmitter) SCons.Tool.cc.add_common_cc_variables(env) env['CXX'] = 'c++' env['CXXFLAGS'] = SCons.Util.CLVar('') env['CXXCOM'] = '$CXX -o $TARGET -c $CXXFLAGS $CCFLAGS $_CCCOMCOM $SOURCES' env['SHCXX'] = '$CXX' env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS') env['SHCXXCOM'] = '$SHCXX -o $TARGET -c $SHCXXFLAGS $SHCCFLAGS $_CCCOMCOM $SOURCES' env['CPPDEFPREFIX'] = '-D' env['CPPDEFSUFFIX'] = '' env['INCPREFIX'] = '-I' env['INCSUFFIX'] = '' env['SHOBJSUFFIX'] = '.os' env['OBJSUFFIX'] = '.o' env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 0 env['CXXFILESUFFIX'] = '.cc' def exists(env): return env.Detect(compilers) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.Subversion.py Tool-specific initialization for Subversion. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. __revision__ = "src/engine/SCons/Tool/Subversion.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os.path import SCons.Action import SCons.Builder import SCons.Util def generate(env): """Add a Builder factory function and construction variables for Subversion to an Environment.""" def SubversionFactory(repos, module='', env=env): """ """ # fail if repos is not an absolute path name? import SCons.Warnings as W W.warn(W.DeprecatedSourceCodeWarning, """The Subversion() factory is deprecated and there is no replacement.""") if module != '': module = os.path.join(module, '') act = SCons.Action.Action('$SVNCOM', '$SVNCOMSTR') return SCons.Builder.Builder(action = act, env = env, SVNREPOSITORY = repos, SVNMODULE = module) #setattr(env, 'Subversion', SubversionFactory) env.Subversion = SubversionFactory env['SVN'] = 'svn' env['SVNFLAGS'] = SCons.Util.CLVar('') env['SVNCOM'] = '$SVN $SVNFLAGS cat $SVNREPOSITORY/$SVNMODULE$TARGET > $TARGET' def exists(env): return env.Detect('svn') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.pdf Common PDF Builder definition for various other Tool modules that use it. Add an explicit action to run epstopdf to convert .eps files to .pdf """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/pdf.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Builder import SCons.Tool PDFBuilder = None EpsPdfAction = SCons.Action.Action('$EPSTOPDFCOM', '$EPSTOPDFCOMSTR') def generate(env): try: env['BUILDERS']['PDF'] except KeyError: global PDFBuilder if PDFBuilder is None: PDFBuilder = SCons.Builder.Builder(action = {}, source_scanner = SCons.Tool.PDFLaTeXScanner, prefix = '$PDFPREFIX', suffix = '$PDFSUFFIX', emitter = {}, source_ext_match = None, single_source=True) env['BUILDERS']['PDF'] = PDFBuilder env['PDFPREFIX'] = '' env['PDFSUFFIX'] = '.pdf' # put the epstopdf builder in this routine so we can add it after # the pdftex builder so that one is the default for no source suffix def generate2(env): bld = env['BUILDERS']['PDF'] #bld.add_action('.ps', EpsPdfAction) # this is covered by direct Ghostcript action in gs.py bld.add_action('.eps', EpsPdfAction) env['EPSTOPDF'] = 'epstopdf' env['EPSTOPDFFLAGS'] = SCons.Util.CLVar('') env['EPSTOPDFCOM'] = '$EPSTOPDF $EPSTOPDFFLAGS ${SOURCE} --outfile=${TARGET}' def exists(env): # This only puts a skeleton Builder in place, so if someone # references this Tool directly, it's always "available." return 1 # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.filesystem Tool-specific initialization for the filesystem tools. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/filesystem.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons from SCons.Tool.install import copyFunc copyToBuilder, copyAsBuilder = None, None def copyto_emitter(target, source, env): """ changes the path of the source to be under the target (which are assumed to be directories. """ n_target = [] for t in target: n_target = n_target + [t.File( str( s ) ) for s in source] return (n_target, source) def copy_action_func(target, source, env): assert( len(target) == len(source) ), "\ntarget: %s\nsource: %s" %(list(map(str, target)),list(map(str, source))) for t, s in zip(target, source): if copyFunc(t.get_path(), s.get_path(), env): return 1 return 0 def copy_action_str(target, source, env): return env.subst_target_source(env['COPYSTR'], 0, target, source) copy_action = SCons.Action.Action( copy_action_func, copy_action_str ) def generate(env): try: env['BUILDERS']['CopyTo'] env['BUILDERS']['CopyAs'] except KeyError, e: global copyToBuilder if copyToBuilder is None: copyToBuilder = SCons.Builder.Builder( action = copy_action, target_factory = env.fs.Dir, source_factory = env.fs.Entry, multi = 1, emitter = [ copyto_emitter, ] ) global copyAsBuilder if copyAsBuilder is None: copyAsBuilder = SCons.Builder.Builder( action = copy_action, target_factory = env.fs.Entry, source_factory = env.fs.Entry ) env['BUILDERS']['CopyTo'] = copyToBuilder env['BUILDERS']['CopyAs'] = copyAsBuilder env['COPYSTR'] = 'Copy file(s): "$SOURCES" to "$TARGETS"' def exists(env): return 1 # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.dmd Tool-specific initialization for the Digital Mars D compiler. (http://digitalmars.com/d) Coded by Andy Friesen (andy@ikagames.com) 15 November 2003 Amended by Russel Winder (russel@russel.org.uk) 2010-02-07 There are a number of problems with this script at this point in time. The one that irritates me the most is the Windows linker setup. The D linker doesn't have a way to add lib paths on the commandline, as far as I can see. You have to specify paths relative to the SConscript or use absolute paths. To hack around it, add '#/blah'. This will link blah.lib from the directory where SConstruct resides. Compiler variables: DC - The name of the D compiler to use. Defaults to dmd or gdmd, whichever is found. DPATH - List of paths to search for import modules. DVERSIONS - List of version tags to enable when compiling. DDEBUG - List of debug tags to enable when compiling. Linker related variables: LIBS - List of library files to link in. DLINK - Name of the linker to use. Defaults to dmd or gdmd. DLINKFLAGS - List of linker flags. Lib tool variables: DLIB - Name of the lib tool to use. Defaults to lib. DLIBFLAGS - List of flags to pass to the lib tool. LIBS - Same as for the linker. (libraries to pull into the .lib) """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/dmd.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os import SCons.Action import SCons.Builder import SCons.Defaults import SCons.Scanner.D import SCons.Tool # Adapted from c++.py def isD(source): if not source: return 0 for s in source: if s.sources: ext = os.path.splitext(str(s.sources[0]))[1] if ext == '.d': return 1 return 0 smart_link = {} smart_lib = {} def generate(env): global smart_link global smart_lib static_obj, shared_obj = SCons.Tool.createObjBuilders(env) DAction = SCons.Action.Action('$DCOM', '$DCOMSTR') static_obj.add_action('.d', DAction) shared_obj.add_action('.d', DAction) static_obj.add_emitter('.d', SCons.Defaults.StaticObjectEmitter) shared_obj.add_emitter('.d', SCons.Defaults.SharedObjectEmitter) dc = env.Detect(['dmd', 'gdmd']) env['DC'] = dc env['DCOM'] = '$DC $_DINCFLAGS $_DVERFLAGS $_DDEBUGFLAGS $_DFLAGS -c -of$TARGET $SOURCES' env['_DINCFLAGS'] = '$( ${_concat(DINCPREFIX, DPATH, DINCSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)' env['_DVERFLAGS'] = '$( ${_concat(DVERPREFIX, DVERSIONS, DVERSUFFIX, __env__)} $)' env['_DDEBUGFLAGS'] = '$( ${_concat(DDEBUGPREFIX, DDEBUG, DDEBUGSUFFIX, __env__)} $)' env['_DFLAGS'] = '$( ${_concat(DFLAGPREFIX, DFLAGS, DFLAGSUFFIX, __env__)} $)' env['DPATH'] = ['#/'] env['DFLAGS'] = [] env['DVERSIONS'] = [] env['DDEBUG'] = [] if dc: # Add the path to the standard library. # This is merely for the convenience of the dependency scanner. dmd_path = env.WhereIs(dc) if dmd_path: x = dmd_path.rindex(dc) phobosDir = dmd_path[:x] + '/../src/phobos' if os.path.isdir(phobosDir): env.Append(DPATH = [phobosDir]) env['DINCPREFIX'] = '-I' env['DINCSUFFIX'] = '' env['DVERPREFIX'] = '-version=' env['DVERSUFFIX'] = '' env['DDEBUGPREFIX'] = '-debug=' env['DDEBUGSUFFIX'] = '' env['DFLAGPREFIX'] = '-' env['DFLAGSUFFIX'] = '' env['DFILESUFFIX'] = '.d' # Need to use the Digital Mars linker/lib on windows. # *nix can just use GNU link. if env['PLATFORM'] == 'win32': env['DLINK'] = '$DC' env['DLINKCOM'] = '$DLINK -of$TARGET $SOURCES $DFLAGS $DLINKFLAGS $_DLINKLIBFLAGS' env['DLIB'] = 'lib' env['DLIBCOM'] = '$DLIB $_DLIBFLAGS -c $TARGET $SOURCES $_DLINKLIBFLAGS' env['_DLINKLIBFLAGS'] = '$( ${_concat(DLIBLINKPREFIX, LIBS, DLIBLINKSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)' env['_DLIBFLAGS'] = '$( ${_concat(DLIBFLAGPREFIX, DLIBFLAGS, DLIBFLAGSUFFIX, __env__)} $)' env['DLINKFLAGS'] = [] env['DLIBLINKPREFIX'] = '' env['DLIBLINKSUFFIX'] = '.lib' env['DLIBFLAGPREFIX'] = '-' env['DLIBFLAGSUFFIX'] = '' env['DLINKFLAGPREFIX'] = '-' env['DLINKFLAGSUFFIX'] = '' SCons.Tool.createStaticLibBuilder(env) # Basically, we hijack the link and ar builders with our own. # these builders check for the presence of D source, and swap out # the system's defaults for the Digital Mars tools. If there's no D # source, then we silently return the previous settings. linkcom = env.get('LINKCOM') try: env['SMART_LINKCOM'] = smart_link[linkcom] except KeyError: def _smartLink(source, target, env, for_signature, defaultLinker=linkcom): if isD(source): # XXX I'm not sure how to add a $DLINKCOMSTR variable # so that it works with this _smartLink() logic, # and I don't have a D compiler/linker to try it out, # so we'll leave it alone for now. return '$DLINKCOM' else: return defaultLinker env['SMART_LINKCOM'] = smart_link[linkcom] = _smartLink arcom = env.get('ARCOM') try: env['SMART_ARCOM'] = smart_lib[arcom] except KeyError: def _smartLib(source, target, env, for_signature, defaultLib=arcom): if isD(source): # XXX I'm not sure how to add a $DLIBCOMSTR variable # so that it works with this _smartLib() logic, and # I don't have a D compiler/archiver to try it out, # so we'll leave it alone for now. return '$DLIBCOM' else: return defaultLib env['SMART_ARCOM'] = smart_lib[arcom] = _smartLib # It is worth noting that the final space in these strings is # absolutely pivotal. SCons sees these as actions and not generators # if it is not there. (very bad) env['ARCOM'] = '$SMART_ARCOM ' env['LINKCOM'] = '$SMART_LINKCOM ' else: # assuming linux linkcom = env.get('LINKCOM') try: env['SMART_LINKCOM'] = smart_link[linkcom] except KeyError: def _smartLink(source, target, env, for_signature, defaultLinker=linkcom, dc=dc): if isD(source): try: libs = env['LIBS'] except KeyError: libs = [] if dc == 'dmd': # TODO: This assumes that the dmd executable is in the # bin directory and that the libraries are in a peer # directory lib. This true of the Digital Mars # distribution but . . . import glob dHome = env.WhereIs(dc).replace('/dmd' , '/..') if glob.glob(dHome + '/lib/*phobos2*'): if 'phobos2' not in libs: env.Append(LIBPATH = [dHome + '/lib']) env.Append(LIBS = ['phobos2']) # TODO: Find out when there will be a # 64-bit version of D. env.Append(LINKFLAGS = ['-m32']) else: if 'phobos' not in libs: env.Append(LIBS = ['phobos']) elif dc is 'gdmd': env.Append(LIBS = ['gphobos']) if 'pthread' not in libs: env.Append(LIBS = ['pthread']) if 'm' not in libs: env.Append(LIBS = ['m']) return defaultLinker env['SMART_LINKCOM'] = smart_link[linkcom] = _smartLink env['LINKCOM'] = '$SMART_LINKCOM ' def exists(env): return env.Detect(['dmd', 'gdmd']) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.swig Tool-specific initialization for swig. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/swig.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os.path import re import subprocess import SCons.Action import SCons.Defaults import SCons.Scanner import SCons.Tool import SCons.Util SwigAction = SCons.Action.Action('$SWIGCOM', '$SWIGCOMSTR') def swigSuffixEmitter(env, source): if '-c++' in SCons.Util.CLVar(env.subst("$SWIGFLAGS", source=source)): return '$SWIGCXXFILESUFFIX' else: return '$SWIGCFILESUFFIX' # Match '%module test', as well as '%module(directors="1") test' # Also allow for test to be quoted (SWIG permits double quotes, but not single) # Also allow for the line to have spaces after test if not quoted _reModule = re.compile(r'%module(\s*\(.*\))?\s+("?)(\S+)\2') def _find_modules(src): """Find all modules referenced by %module lines in `src`, a SWIG .i file. Returns a list of all modules, and a flag set if SWIG directors have been requested (SWIG will generate an additional header file in this case.)""" directors = 0 mnames = [] try: matches = _reModule.findall(open(src).read()) except IOError: # If the file's not yet generated, guess the module name from the file stem matches = [] mnames.append(os.path.splitext(os.path.basename(src))[0]) for m in matches: mnames.append(m[2]) directors = directors or m[0].find('directors') >= 0 return mnames, directors def _add_director_header_targets(target, env): # Directors only work with C++ code, not C suffix = env.subst(env['SWIGCXXFILESUFFIX']) # For each file ending in SWIGCXXFILESUFFIX, add a new target director # header by replacing the ending with SWIGDIRECTORSUFFIX. for x in target[:]: n = x.name d = x.dir if n[-len(suffix):] == suffix: target.append(d.File(n[:-len(suffix)] + env['SWIGDIRECTORSUFFIX'])) def _swigEmitter(target, source, env): swigflags = env.subst("$SWIGFLAGS", target=target, source=source) flags = SCons.Util.CLVar(swigflags) for src in source: src = str(src.rfile()) mnames = None if "-python" in flags and "-noproxy" not in flags: if mnames is None: mnames, directors = _find_modules(src) if directors: _add_director_header_targets(target, env) python_files = [m + ".py" for m in mnames] outdir = env.subst('$SWIGOUTDIR', target=target, source=source) # .py files should be generated in SWIGOUTDIR if specified, # otherwise in the same directory as the target if outdir: python_files = [env.fs.File(os.path.join(outdir, j)) for j in python_files] else: python_files = [target[0].dir.File(m) for m in python_files] target.extend(python_files) if "-java" in flags: if mnames is None: mnames, directors = _find_modules(src) if directors: _add_director_header_targets(target, env) java_files = [[m + ".java", m + "JNI.java"] for m in mnames] java_files = SCons.Util.flatten(java_files) outdir = env.subst('$SWIGOUTDIR', target=target, source=source) if outdir: java_files = [os.path.join(outdir, j) for j in java_files] java_files = list(map(env.fs.File, java_files)) for jf in java_files: t_from_s = lambda t, p, s, x: t.dir SCons.Util.AddMethod(jf, t_from_s, 'target_from_source') target.extend(java_files) return (target, source) def _get_swig_version(env): """Run the SWIG command line tool to get and return the version number""" pipe = SCons.Action._subproc(env, [env['SWIG'], '-version'], stdin = 'devnull', stderr = 'devnull', stdout = subprocess.PIPE) if pipe.wait() != 0: return out = pipe.stdout.read() match = re.search(r'SWIG Version\s+(\S+)$', out, re.MULTILINE) if match: return match.group(1) def generate(env): """Add Builders and construction variables for swig to an Environment.""" c_file, cxx_file = SCons.Tool.createCFileBuilders(env) c_file.suffix['.i'] = swigSuffixEmitter cxx_file.suffix['.i'] = swigSuffixEmitter c_file.add_action('.i', SwigAction) c_file.add_emitter('.i', _swigEmitter) cxx_file.add_action('.i', SwigAction) cxx_file.add_emitter('.i', _swigEmitter) java_file = SCons.Tool.CreateJavaFileBuilder(env) java_file.suffix['.i'] = swigSuffixEmitter java_file.add_action('.i', SwigAction) java_file.add_emitter('.i', _swigEmitter) env['SWIG'] = 'swig' env['SWIGVERSION'] = _get_swig_version(env) env['SWIGFLAGS'] = SCons.Util.CLVar('') env['SWIGDIRECTORSUFFIX'] = '_wrap.h' env['SWIGCFILESUFFIX'] = '_wrap$CFILESUFFIX' env['SWIGCXXFILESUFFIX'] = '_wrap$CXXFILESUFFIX' env['_SWIGOUTDIR'] = r'${"-outdir \"%s\"" % SWIGOUTDIR}' env['SWIGPATH'] = [] env['SWIGINCPREFIX'] = '-I' env['SWIGINCSUFFIX'] = '' env['_SWIGINCFLAGS'] = '$( ${_concat(SWIGINCPREFIX, SWIGPATH, SWIGINCSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)' env['SWIGCOM'] = '$SWIG -o $TARGET ${_SWIGOUTDIR} ${_SWIGINCFLAGS} $SWIGFLAGS $SOURCES' expr = '^[ \t]*%[ \t]*(?:include|import|extern)[ \t]*(<|"?)([^>\s"]+)(?:>|"?)' scanner = SCons.Scanner.ClassicCPP("SWIGScan", ".i", "SWIGPATH", expr) env.Append(SCANNERS = scanner) def exists(env): return env.Detect(['swig']) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""engine.SCons.Tool.f95 Tool-specific initialization for the generic Posix f95 Fortran compiler. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/f95.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Defaults import SCons.Tool import SCons.Util import fortran from SCons.Tool.FortranCommon import add_all_to_env, add_f95_to_env compilers = ['f95'] def generate(env): add_all_to_env(env) add_f95_to_env(env) fcomp = env.Detect(compilers) or 'f95' env['F95'] = fcomp env['SHF95'] = fcomp env['FORTRAN'] = fcomp env['SHFORTRAN'] = fcomp def exists(env): return env.Detect(compilers) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.rpm Tool-specific initialization for rpm. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. The rpm tool calls the rpmbuild command. The first and only argument should a tar.gz consisting of the source file and a specfile. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/rpm.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os import re import shutil import subprocess import SCons.Builder import SCons.Node.FS import SCons.Util import SCons.Action import SCons.Defaults def get_cmd(source, env): tar_file_with_included_specfile = source if SCons.Util.is_List(source): tar_file_with_included_specfile = source[0] return "%s %s %s"%(env['RPM'], env['RPMFLAGS'], tar_file_with_included_specfile.abspath ) def build_rpm(target, source, env): # create a temporary rpm build root. tmpdir = os.path.join( os.path.dirname( target[0].abspath ), 'rpmtemp' ) if os.path.exists(tmpdir): shutil.rmtree(tmpdir) # now create the mandatory rpm directory structure. for d in ['RPMS', 'SRPMS', 'SPECS', 'BUILD']: os.makedirs( os.path.join( tmpdir, d ) ) # set the topdir as an rpmflag. env.Prepend( RPMFLAGS = '--define \'_topdir %s\'' % tmpdir ) # now call rpmbuild to create the rpm package. handle = subprocess.Popen(get_cmd(source, env), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True) output = handle.stdout.read() status = handle.wait() if status: raise SCons.Errors.BuildError( node=target[0], errstr=output, filename=str(target[0]) ) else: # XXX: assume that LC_ALL=c is set while running rpmbuild output_files = re.compile( 'Wrote: (.*)' ).findall( output ) for output, input in zip( output_files, target ): rpm_output = os.path.basename(output) expected = os.path.basename(input.get_path()) assert expected == rpm_output, "got %s but expected %s" % (rpm_output, expected) shutil.copy( output, input.abspath ) # cleanup before leaving. shutil.rmtree(tmpdir) return status def string_rpm(target, source, env): try: return env['RPMCOMSTR'] except KeyError: return get_cmd(source, env) rpmAction = SCons.Action.Action(build_rpm, string_rpm) RpmBuilder = SCons.Builder.Builder(action = SCons.Action.Action('$RPMCOM', '$RPMCOMSTR'), source_scanner = SCons.Defaults.DirScanner, suffix = '$RPMSUFFIX') def generate(env): """Add Builders and construction variables for rpm to an Environment.""" try: bld = env['BUILDERS']['Rpm'] except KeyError: bld = RpmBuilder env['BUILDERS']['Rpm'] = bld env.SetDefault(RPM = 'LC_ALL=c rpmbuild') env.SetDefault(RPMFLAGS = SCons.Util.CLVar('-ta')) env.SetDefault(RPMCOM = rpmAction) env.SetDefault(RPMSUFFIX = '.rpm') def exists(env): return env.Detect('rpmbuild') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.rpcgen Tool-specific initialization for RPCGEN tools. Three normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/rpcgen.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" from SCons.Builder import Builder import SCons.Util cmd = "cd ${SOURCE.dir} && $RPCGEN -%s $RPCGENFLAGS %s -o ${TARGET.abspath} ${SOURCE.file}" rpcgen_client = cmd % ('l', '$RPCGENCLIENTFLAGS') rpcgen_header = cmd % ('h', '$RPCGENHEADERFLAGS') rpcgen_service = cmd % ('m', '$RPCGENSERVICEFLAGS') rpcgen_xdr = cmd % ('c', '$RPCGENXDRFLAGS') def generate(env): "Add RPCGEN Builders and construction variables for an Environment." client = Builder(action=rpcgen_client, suffix='_clnt.c', src_suffix='.x') header = Builder(action=rpcgen_header, suffix='.h', src_suffix='.x') service = Builder(action=rpcgen_service, suffix='_svc.c', src_suffix='.x') xdr = Builder(action=rpcgen_xdr, suffix='_xdr.c', src_suffix='.x') env.Append(BUILDERS={'RPCGenClient' : client, 'RPCGenHeader' : header, 'RPCGenService' : service, 'RPCGenXDR' : xdr}) env['RPCGEN'] = 'rpcgen' env['RPCGENFLAGS'] = SCons.Util.CLVar('') env['RPCGENCLIENTFLAGS'] = SCons.Util.CLVar('') env['RPCGENHEADERFLAGS'] = SCons.Util.CLVar('') env['RPCGENSERVICEFLAGS'] = SCons.Util.CLVar('') env['RPCGENXDRFLAGS'] = SCons.Util.CLVar('') def exists(env): return env.Detect('rpcgen') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.sunc++ Tool-specific initialization for C++ on SunOS / Solaris. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/sunc++.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons import os import re import subprocess cplusplus = __import__('c++', globals(), locals(), []) package_info = {} def get_package_info(package_name, pkginfo, pkgchk): try: return package_info[package_name] except KeyError: version = None pathname = None try: sadm_contents = open('/var/sadm/install/contents', 'r').read() except EnvironmentError: pass else: sadm_re = re.compile('^(\S*/bin/CC)(=\S*)? %s$' % package_name, re.M) sadm_match = sadm_re.search(sadm_contents) if sadm_match: pathname = os.path.dirname(sadm_match.group(1)) try: p = subprocess.Popen([pkginfo, '-l', package_name], stdout=subprocess.PIPE, stderr=open('/dev/null', 'w')) except EnvironmentError: pass else: pkginfo_contents = p.communicate()[0] version_re = re.compile('^ *VERSION:\s*(.*)$', re.M) version_match = version_re.search(pkginfo_contents) if version_match: version = version_match.group(1) if pathname is None: try: p = subprocess.Popen([pkgchk, '-l', package_name], stdout=subprocess.PIPE, stderr=open('/dev/null', 'w')) except EnvironmentError: pass else: pkgchk_contents = p.communicate()[0] pathname_re = re.compile(r'^Pathname:\s*(.*/bin/CC)$', re.M) pathname_match = pathname_re.search(pkgchk_contents) if pathname_match: pathname = os.path.dirname(pathname_match.group(1)) package_info[package_name] = (pathname, version) return package_info[package_name] # use the package installer tool lslpp to figure out where cppc and what # version of it is installed def get_cppc(env): cxx = env.subst('$CXX') if cxx: cppcPath = os.path.dirname(cxx) else: cppcPath = None cppcVersion = None pkginfo = env.subst('$PKGINFO') pkgchk = env.subst('$PKGCHK') for package in ['SPROcpl']: path, version = get_package_info(package, pkginfo, pkgchk) if path and version: cppcPath, cppcVersion = path, version break return (cppcPath, 'CC', 'CC', cppcVersion) def generate(env): """Add Builders and construction variables for SunPRO C++.""" path, cxx, shcxx, version = get_cppc(env) if path: cxx = os.path.join(path, cxx) shcxx = os.path.join(path, shcxx) cplusplus.generate(env) env['CXX'] = cxx env['SHCXX'] = shcxx env['CXXVERSION'] = version env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS -KPIC') env['SHOBJPREFIX'] = 'so_' env['SHOBJSUFFIX'] = '.o' def exists(env): path, cxx, shcxx, version = get_cppc(env) if path and cxx: cppc = os.path.join(path, cxx) if os.path.exists(cppc): return cppc return None # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.linkloc Tool specification for the LinkLoc linker for the Phar Lap ETS embedded operating system. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/linkloc.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os.path import re import SCons.Action import SCons.Defaults import SCons.Errors import SCons.Tool import SCons.Util from SCons.Tool.MSCommon import msvs_exists, merge_default_version from SCons.Tool.PharLapCommon import addPharLapPaths _re_linker_command = re.compile(r'(\s)@\s*([^\s]+)') def repl_linker_command(m): # Replaces any linker command file directives (e.g. "@foo.lnk") with # the actual contents of the file. try: f=open(m.group(2), "r") return m.group(1) + f.read() except IOError: # the linker should return an error if it can't # find the linker command file so we will remain quiet. # However, we will replace the @ with a # so we will not continue # to find it with recursive substitution return m.group(1) + '#' + m.group(2) class LinklocGenerator(object): def __init__(self, cmdline): self.cmdline = cmdline def __call__(self, env, target, source, for_signature): if for_signature: # Expand the contents of any linker command files recursively subs = 1 strsub = env.subst(self.cmdline, target=target, source=source) while subs: strsub, subs = _re_linker_command.subn(repl_linker_command, strsub) return strsub else: return "${TEMPFILE('" + self.cmdline + "')}" def generate(env): """Add Builders and construction variables for ar to an Environment.""" SCons.Tool.createSharedLibBuilder(env) SCons.Tool.createProgBuilder(env) env['SUBST_CMD_FILE'] = LinklocGenerator env['SHLINK'] = '$LINK' env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS') env['SHLINKCOM'] = '${SUBST_CMD_FILE("$SHLINK $SHLINKFLAGS $_LIBDIRFLAGS $_LIBFLAGS -dll $TARGET $SOURCES")}' env['SHLIBEMITTER']= None env['LINK'] = "linkloc" env['LINKFLAGS'] = SCons.Util.CLVar('') env['LINKCOM'] = '${SUBST_CMD_FILE("$LINK $LINKFLAGS $_LIBDIRFLAGS $_LIBFLAGS -exe $TARGET $SOURCES")}' env['LIBDIRPREFIX']='-libpath ' env['LIBDIRSUFFIX']='' env['LIBLINKPREFIX']='-lib ' env['LIBLINKSUFFIX']='$LIBSUFFIX' # Set-up ms tools paths for default version merge_default_version(env) addPharLapPaths(env) def exists(env): if msvs_exists(): return env.Detect('linkloc') else: return 0 # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.ifl Tool-specific initialization for the Intel Fortran compiler. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/ifl.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Defaults from SCons.Scanner.Fortran import FortranScan from FortranCommon import add_all_to_env def generate(env): """Add Builders and construction variables for ifl to an Environment.""" fscan = FortranScan("FORTRANPATH") SCons.Tool.SourceFileScanner.add_scanner('.i', fscan) SCons.Tool.SourceFileScanner.add_scanner('.i90', fscan) if 'FORTRANFILESUFFIXES' not in env: env['FORTRANFILESUFFIXES'] = ['.i'] else: env['FORTRANFILESUFFIXES'].append('.i') if 'F90FILESUFFIXES' not in env: env['F90FILESUFFIXES'] = ['.i90'] else: env['F90FILESUFFIXES'].append('.i90') add_all_to_env(env) env['FORTRAN'] = 'ifl' env['SHFORTRAN'] = '$FORTRAN' env['FORTRANCOM'] = '$FORTRAN $FORTRANFLAGS $_FORTRANINCFLAGS /c $SOURCES /Fo$TARGET' env['FORTRANPPCOM'] = '$FORTRAN $FORTRANFLAGS $CPPFLAGS $_CPPDEFFLAGS $_FORTRANINCFLAGS /c $SOURCES /Fo$TARGET' env['SHFORTRANCOM'] = '$SHFORTRAN $SHFORTRANFLAGS $_FORTRANINCFLAGS /c $SOURCES /Fo$TARGET' env['SHFORTRANPPCOM'] = '$SHFORTRAN $SHFORTRANFLAGS $CPPFLAGS $_CPPDEFFLAGS $_FORTRANINCFLAGS /c $SOURCES /Fo$TARGET' def exists(env): return env.Detect('ifl') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.rmic Tool-specific initialization for rmic. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/rmic.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os.path import SCons.Action import SCons.Builder import SCons.Node.FS import SCons.Util def emit_rmic_classes(target, source, env): """Create and return lists of Java RMI stub and skeleton class files to be created from a set of class files. """ class_suffix = env.get('JAVACLASSSUFFIX', '.class') classdir = env.get('JAVACLASSDIR') if not classdir: try: s = source[0] except IndexError: classdir = '.' else: try: classdir = s.attributes.java_classdir except AttributeError: classdir = '.' classdir = env.Dir(classdir).rdir() if str(classdir) == '.': c_ = None else: c_ = str(classdir) + os.sep slist = [] for src in source: try: classname = src.attributes.java_classname except AttributeError: classname = str(src) if c_ and classname[:len(c_)] == c_: classname = classname[len(c_):] if class_suffix and classname[:-len(class_suffix)] == class_suffix: classname = classname[-len(class_suffix):] s = src.rfile() s.attributes.java_classdir = classdir s.attributes.java_classname = classname slist.append(s) stub_suffixes = ['_Stub'] if env.get('JAVAVERSION') == '1.4': stub_suffixes.append('_Skel') tlist = [] for s in source: for suff in stub_suffixes: fname = s.attributes.java_classname.replace('.', os.sep) + \ suff + class_suffix t = target[0].File(fname) t.attributes.java_lookupdir = target[0] tlist.append(t) return tlist, source RMICAction = SCons.Action.Action('$RMICCOM', '$RMICCOMSTR') RMICBuilder = SCons.Builder.Builder(action = RMICAction, emitter = emit_rmic_classes, src_suffix = '$JAVACLASSSUFFIX', target_factory = SCons.Node.FS.Dir, source_factory = SCons.Node.FS.File) def generate(env): """Add Builders and construction variables for rmic to an Environment.""" env['BUILDERS']['RMIC'] = RMICBuilder env['RMIC'] = 'rmic' env['RMICFLAGS'] = SCons.Util.CLVar('') env['RMICCOM'] = '$RMIC $RMICFLAGS -d ${TARGET.attributes.java_lookupdir} -classpath ${SOURCE.attributes.java_classdir} ${SOURCES.attributes.java_classname}' env['JAVACLASSSUFFIX'] = '.class' def exists(env): # As reported by Jan Nijtmans in issue #2730, the simple # return env.Detect('rmic') # doesn't always work during initialization. For now, we # stop trying to detect an executable (analogous to the # javac Builder). # TODO: Come up with a proper detect() routine...and enable it. return 1 # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""engine.SCons.Tool.icc Tool-specific initialization for the OS/2 icc compiler. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/icc.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import cc def generate(env): """Add Builders and construction variables for the OS/2 to an Environment.""" cc.generate(env) env['CC'] = 'icc' env['CCCOM'] = '$CC $CFLAGS $CCFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS /c $SOURCES /Fo$TARGET' env['CXXCOM'] = '$CXX $CXXFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS /c $SOURCES /Fo$TARGET' env['CPPDEFPREFIX'] = '/D' env['CPPDEFSUFFIX'] = '' env['INCPREFIX'] = '/I' env['INCSUFFIX'] = '' env['CFILESUFFIX'] = '.c' env['CXXFILESUFFIX'] = '.cc' def exists(env): return env.Detect('icc') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""engine.SCons.Tool.f90 Tool-specific initialization for the generic Posix f90 Fortran compiler. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/f90.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Defaults import SCons.Scanner.Fortran import SCons.Tool import SCons.Util from SCons.Tool.FortranCommon import add_all_to_env, add_f90_to_env compilers = ['f90'] def generate(env): add_all_to_env(env) add_f90_to_env(env) fc = env.Detect(compilers) or 'f90' env['F90'] = fc env['SHF90'] = fc env['FORTRAN'] = fc env['SHFORTRAN'] = fc def exists(env): return env.Detect(compilers) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""engine.SCons.Tool.aixf77 Tool-specific initialization for IBM Visual Age f77 Fortran compiler. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/aixf77.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os.path #import SCons.Platform.aix import f77 # It would be good to look for the AIX F77 package the same way we're now # looking for the C and C++ packages. This should be as easy as supplying # the correct package names in the following list and uncommenting the # SCons.Platform.aix_get_xlc() call the in the function below. packages = [] def get_xlf77(env): xlf77 = env.get('F77', 'xlf77') xlf77_r = env.get('SHF77', 'xlf77_r') #return SCons.Platform.aix.get_xlc(env, xlf77, xlf77_r, packages) return (None, xlf77, xlf77_r, None) def generate(env): """ Add Builders and construction variables for the Visual Age FORTRAN compiler to an Environment. """ path, _f77, _shf77, version = get_xlf77(env) if path: _f77 = os.path.join(path, _f77) _shf77 = os.path.join(path, _shf77) f77.generate(env) env['F77'] = _f77 env['SHF77'] = _shf77 def exists(env): path, _f77, _shf77, version = get_xlf77(env) if path and _f77: xlf77 = os.path.join(path, _f77) if os.path.exists(xlf77): return xlf77 return None # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.386asm Tool specification for the 386ASM assembler for the Phar Lap ETS embedded operating system. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/386asm.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" from SCons.Tool.PharLapCommon import addPharLapPaths import SCons.Util as_module = __import__('as', globals(), locals(), []) def generate(env): """Add Builders and construction variables for ar to an Environment.""" as_module.generate(env) env['AS'] = '386asm' env['ASFLAGS'] = SCons.Util.CLVar('') env['ASPPFLAGS'] = '$ASFLAGS' env['ASCOM'] = '$AS $ASFLAGS $SOURCES -o $TARGET' env['ASPPCOM'] = '$CC $ASPPFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS $SOURCES -o $TARGET' addPharLapPaths(env) def exists(env): return env.Detect('386asm') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.ifort Tool-specific initialization for newer versions of the Intel Fortran Compiler for Linux/Windows (and possibly Mac OS X). There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/ifort.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Defaults from SCons.Scanner.Fortran import FortranScan from FortranCommon import add_all_to_env def generate(env): """Add Builders and construction variables for ifort to an Environment.""" # ifort supports Fortran 90 and Fortran 95 # Additionally, ifort recognizes more file extensions. fscan = FortranScan("FORTRANPATH") SCons.Tool.SourceFileScanner.add_scanner('.i', fscan) SCons.Tool.SourceFileScanner.add_scanner('.i90', fscan) if 'FORTRANFILESUFFIXES' not in env: env['FORTRANFILESUFFIXES'] = ['.i'] else: env['FORTRANFILESUFFIXES'].append('.i') if 'F90FILESUFFIXES' not in env: env['F90FILESUFFIXES'] = ['.i90'] else: env['F90FILESUFFIXES'].append('.i90') add_all_to_env(env) fc = 'ifort' for dialect in ['F77', 'F90', 'FORTRAN', 'F95']: env['%s' % dialect] = fc env['SH%s' % dialect] = '$%s' % dialect if env['PLATFORM'] == 'posix': env['SH%sFLAGS' % dialect] = SCons.Util.CLVar('$%sFLAGS -fPIC' % dialect) if env['PLATFORM'] == 'win32': # On Windows, the ifort compiler specifies the object on the # command line with -object:, not -o. Massage the necessary # command-line construction variables. for dialect in ['F77', 'F90', 'FORTRAN', 'F95']: for var in ['%sCOM' % dialect, '%sPPCOM' % dialect, 'SH%sCOM' % dialect, 'SH%sPPCOM' % dialect]: env[var] = env[var].replace('-o $TARGET', '-object:$TARGET') env['FORTRANMODDIRPREFIX'] = "/module:" else: env['FORTRANMODDIRPREFIX'] = "-module " def exists(env): return env.Detect('ifort') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.latex Tool-specific initialization for LaTeX. Generates .dvi files from .latex or .ltx files There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/latex.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Action import SCons.Defaults import SCons.Scanner.LaTeX import SCons.Util import SCons.Tool import SCons.Tool.tex def LaTeXAuxFunction(target = None, source= None, env=None): result = SCons.Tool.tex.InternalLaTeXAuxAction( SCons.Tool.tex.LaTeXAction, target, source, env ) if result != 0: SCons.Tool.tex.check_file_error_message(env['LATEX']) return result LaTeXAuxAction = SCons.Action.Action(LaTeXAuxFunction, strfunction=SCons.Tool.tex.TeXLaTeXStrFunction) def generate(env): """Add Builders and construction variables for LaTeX to an Environment.""" env.AppendUnique(LATEXSUFFIXES=SCons.Tool.LaTeXSuffixes) import dvi dvi.generate(env) import pdf pdf.generate(env) bld = env['BUILDERS']['DVI'] bld.add_action('.ltx', LaTeXAuxAction) bld.add_action('.latex', LaTeXAuxAction) bld.add_emitter('.ltx', SCons.Tool.tex.tex_eps_emitter) bld.add_emitter('.latex', SCons.Tool.tex.tex_eps_emitter) SCons.Tool.tex.generate_common(env) def exists(env): SCons.Tool.tex.generate_darwin(env) return env.Detect('latex') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.mslink Tool-specific initialization for the Microsoft linker. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/mslink.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os.path import SCons.Action import SCons.Defaults import SCons.Errors import SCons.Platform.win32 import SCons.Tool import SCons.Tool.msvc import SCons.Tool.msvs import SCons.Util from MSCommon import msvc_setup_env_once, msvc_exists def pdbGenerator(env, target, source, for_signature): try: return ['/PDB:%s' % target[0].attributes.pdb, '/DEBUG'] except (AttributeError, IndexError): return None def _dllTargets(target, source, env, for_signature, paramtp): listCmd = [] dll = env.FindIxes(target, '%sPREFIX' % paramtp, '%sSUFFIX' % paramtp) if dll: listCmd.append("/out:%s"%dll.get_string(for_signature)) implib = env.FindIxes(target, 'LIBPREFIX', 'LIBSUFFIX') if implib: listCmd.append("/implib:%s"%implib.get_string(for_signature)) return listCmd def _dllSources(target, source, env, for_signature, paramtp): listCmd = [] deffile = env.FindIxes(source, "WINDOWSDEFPREFIX", "WINDOWSDEFSUFFIX") for src in source: # Check explicitly for a non-None deffile so that the __cmp__ # method of the base SCons.Util.Proxy class used for some Node # proxies doesn't try to use a non-existent __dict__ attribute. if deffile and src == deffile: # Treat this source as a .def file. listCmd.append("/def:%s" % src.get_string(for_signature)) else: # Just treat it as a generic source file. listCmd.append(src) return listCmd def windowsShlinkTargets(target, source, env, for_signature): return _dllTargets(target, source, env, for_signature, 'SHLIB') def windowsShlinkSources(target, source, env, for_signature): return _dllSources(target, source, env, for_signature, 'SHLIB') def _windowsLdmodTargets(target, source, env, for_signature): """Get targets for loadable modules.""" return _dllTargets(target, source, env, for_signature, 'LDMODULE') def _windowsLdmodSources(target, source, env, for_signature): """Get sources for loadable modules.""" return _dllSources(target, source, env, for_signature, 'LDMODULE') def _dllEmitter(target, source, env, paramtp): """Common implementation of dll emitter.""" SCons.Tool.msvc.validate_vars(env) extratargets = [] extrasources = [] dll = env.FindIxes(target, '%sPREFIX' % paramtp, '%sSUFFIX' % paramtp) no_import_lib = env.get('no_import_lib', 0) if not dll: raise SCons.Errors.UserError('A shared library should have exactly one target with the suffix: %s' % env.subst('$%sSUFFIX' % paramtp)) insert_def = env.subst("$WINDOWS_INSERT_DEF") if not insert_def in ['', '0', 0] and \ not env.FindIxes(source, "WINDOWSDEFPREFIX", "WINDOWSDEFSUFFIX"): # append a def file to the list of sources extrasources.append( env.ReplaceIxes(dll, '%sPREFIX' % paramtp, '%sSUFFIX' % paramtp, "WINDOWSDEFPREFIX", "WINDOWSDEFSUFFIX")) version_num, suite = SCons.Tool.msvs.msvs_parse_version(env.get('MSVS_VERSION', '6.0')) if version_num >= 8.0 and \ (env.get('WINDOWS_INSERT_MANIFEST', 0) or env.get('WINDOWS_EMBED_MANIFEST', 0)): # MSVC 8 and above automatically generate .manifest files that must be installed extratargets.append( env.ReplaceIxes(dll, '%sPREFIX' % paramtp, '%sSUFFIX' % paramtp, "WINDOWSSHLIBMANIFESTPREFIX", "WINDOWSSHLIBMANIFESTSUFFIX")) if 'PDB' in env and env['PDB']: pdb = env.arg2nodes('$PDB', target=target, source=source)[0] extratargets.append(pdb) target[0].attributes.pdb = pdb if not no_import_lib and \ not env.FindIxes(target, "LIBPREFIX", "LIBSUFFIX"): # Append an import library to the list of targets. extratargets.append( env.ReplaceIxes(dll, '%sPREFIX' % paramtp, '%sSUFFIX' % paramtp, "LIBPREFIX", "LIBSUFFIX")) # and .exp file is created if there are exports from a DLL extratargets.append( env.ReplaceIxes(dll, '%sPREFIX' % paramtp, '%sSUFFIX' % paramtp, "WINDOWSEXPPREFIX", "WINDOWSEXPSUFFIX")) return (target+extratargets, source+extrasources) def windowsLibEmitter(target, source, env): return _dllEmitter(target, source, env, 'SHLIB') def ldmodEmitter(target, source, env): """Emitter for loadable modules. Loadable modules are identical to shared libraries on Windows, but building them is subject to different parameters (LDMODULE*). """ return _dllEmitter(target, source, env, 'LDMODULE') def prog_emitter(target, source, env): SCons.Tool.msvc.validate_vars(env) extratargets = [] extrasources = [] exe = env.FindIxes(target, "PROGPREFIX", "PROGSUFFIX") if not exe: raise SCons.Errors.UserError("An executable should have exactly one target with the suffix: %s" % env.subst("$PROGSUFFIX")) version_num, suite = SCons.Tool.msvs.msvs_parse_version(env.get('MSVS_VERSION', '6.0')) if version_num >= 8.0 and \ (env.get('WINDOWS_INSERT_MANIFEST', 0) or env.get('WINDOWS_EMBED_MANIFEST', 0)): # MSVC 8 and above automatically generate .manifest files that have to be installed extratargets.append( env.ReplaceIxes(exe, "PROGPREFIX", "PROGSUFFIX", "WINDOWSPROGMANIFESTPREFIX", "WINDOWSPROGMANIFESTSUFFIX")) if 'PDB' in env and env['PDB']: pdb = env.arg2nodes('$PDB', target=target, source=source)[0] extratargets.append(pdb) target[0].attributes.pdb = pdb if version_num >= 11.0 and env.get('PCH', 0): # MSVC 11 and above need the PCH object file to be added to the link line, # otherwise you get link error LNK2011. pchobj = SCons.Util.splitext(str(env['PCH']))[0] + '.obj' # print "prog_emitter, version %s, appending pchobj %s"%(version_num, pchobj) if pchobj not in extrasources: extrasources.append(pchobj) return (target+extratargets,source+extrasources) def RegServerFunc(target, source, env): if 'register' in env and env['register']: ret = regServerAction([target[0]], [source[0]], env) if ret: raise SCons.Errors.UserError("Unable to register %s" % target[0]) else: print "Registered %s sucessfully" % target[0] return ret return 0 # These are the actual actions run to embed the manifest. # They are only called from the Check versions below. embedManifestExeAction = SCons.Action.Action('$MTEXECOM') embedManifestDllAction = SCons.Action.Action('$MTSHLIBCOM') def embedManifestDllCheck(target, source, env): """Function run by embedManifestDllCheckAction to check for existence of manifest and other conditions, and embed the manifest by calling embedManifestDllAction if so.""" if env.get('WINDOWS_EMBED_MANIFEST', 0): manifestSrc = target[0].abspath + '.manifest' if os.path.exists(manifestSrc): ret = (embedManifestDllAction) ([target[0]],None,env) if ret: raise SCons.Errors.UserError, "Unable to embed manifest into %s" % (target[0]) return ret else: print '(embed: no %s.manifest found; not embedding.)'%str(target[0]) return 0 def embedManifestExeCheck(target, source, env): """Function run by embedManifestExeCheckAction to check for existence of manifest and other conditions, and embed the manifest by calling embedManifestExeAction if so.""" if env.get('WINDOWS_EMBED_MANIFEST', 0): manifestSrc = target[0].abspath + '.manifest' if os.path.exists(manifestSrc): ret = (embedManifestExeAction) ([target[0]],None,env) if ret: raise SCons.Errors.UserError, "Unable to embed manifest into %s" % (target[0]) return ret else: print '(embed: no %s.manifest found; not embedding.)'%str(target[0]) return 0 embedManifestDllCheckAction = SCons.Action.Action(embedManifestDllCheck, None) embedManifestExeCheckAction = SCons.Action.Action(embedManifestExeCheck, None) regServerAction = SCons.Action.Action("$REGSVRCOM", "$REGSVRCOMSTR") regServerCheck = SCons.Action.Action(RegServerFunc, None) shlibLinkAction = SCons.Action.Action('${TEMPFILE("$SHLINK $SHLINKFLAGS $_SHLINK_TARGETS $_LIBDIRFLAGS $_LIBFLAGS $_PDB $_SHLINK_SOURCES")}', '$SHLINKCOMSTR') compositeShLinkAction = shlibLinkAction + regServerCheck + embedManifestDllCheckAction ldmodLinkAction = SCons.Action.Action('${TEMPFILE("$LDMODULE $LDMODULEFLAGS $_LDMODULE_TARGETS $_LIBDIRFLAGS $_LIBFLAGS $_PDB $_LDMODULE_SOURCES")}', '$LDMODULECOMSTR') compositeLdmodAction = ldmodLinkAction + regServerCheck + embedManifestDllCheckAction exeLinkAction = SCons.Action.Action('${TEMPFILE("$LINK $LINKFLAGS /OUT:$TARGET.windows $_LIBDIRFLAGS $_LIBFLAGS $_PDB $SOURCES.windows")}', '$LINKCOMSTR') compositeLinkAction = exeLinkAction + embedManifestExeCheckAction def generate(env): """Add Builders and construction variables for ar to an Environment.""" SCons.Tool.createSharedLibBuilder(env) SCons.Tool.createProgBuilder(env) env['SHLINK'] = '$LINK' env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS /dll') env['_SHLINK_TARGETS'] = windowsShlinkTargets env['_SHLINK_SOURCES'] = windowsShlinkSources env['SHLINKCOM'] = compositeShLinkAction env.Append(SHLIBEMITTER = [windowsLibEmitter]) env['LINK'] = 'link' env['LINKFLAGS'] = SCons.Util.CLVar('/nologo') env['_PDB'] = pdbGenerator env['LINKCOM'] = compositeLinkAction env.Append(PROGEMITTER = [prog_emitter]) env['LIBDIRPREFIX']='/LIBPATH:' env['LIBDIRSUFFIX']='' env['LIBLINKPREFIX']='' env['LIBLINKSUFFIX']='$LIBSUFFIX' env['WIN32DEFPREFIX'] = '' env['WIN32DEFSUFFIX'] = '.def' env['WIN32_INSERT_DEF'] = 0 env['WINDOWSDEFPREFIX'] = '${WIN32DEFPREFIX}' env['WINDOWSDEFSUFFIX'] = '${WIN32DEFSUFFIX}' env['WINDOWS_INSERT_DEF'] = '${WIN32_INSERT_DEF}' env['WIN32EXPPREFIX'] = '' env['WIN32EXPSUFFIX'] = '.exp' env['WINDOWSEXPPREFIX'] = '${WIN32EXPPREFIX}' env['WINDOWSEXPSUFFIX'] = '${WIN32EXPSUFFIX}' env['WINDOWSSHLIBMANIFESTPREFIX'] = '' env['WINDOWSSHLIBMANIFESTSUFFIX'] = '${SHLIBSUFFIX}.manifest' env['WINDOWSPROGMANIFESTPREFIX'] = '' env['WINDOWSPROGMANIFESTSUFFIX'] = '${PROGSUFFIX}.manifest' env['REGSVRACTION'] = regServerCheck env['REGSVR'] = os.path.join(SCons.Platform.win32.get_system_root(),'System32','regsvr32') env['REGSVRFLAGS'] = '/s ' env['REGSVRCOM'] = '$REGSVR $REGSVRFLAGS ${TARGET.windows}' env['WINDOWS_EMBED_MANIFEST'] = 0 env['MT'] = 'mt' #env['MTFLAGS'] = ['-hashupdate'] env['MTFLAGS'] = SCons.Util.CLVar('/nologo') # Note: use - here to prevent build failure if no manifest produced. # This seems much simpler than a fancy system using a function action to see # if the manifest actually exists before trying to run mt with it. env['MTEXECOM'] = '-$MT $MTFLAGS -manifest ${TARGET}.manifest $_MANIFEST_SOURCES -outputresource:$TARGET;1' env['MTSHLIBCOM'] = '-$MT $MTFLAGS -manifest ${TARGET}.manifest $_MANIFEST_SOURCES -outputresource:$TARGET;2' # Future work garyo 27-Feb-11 env['_MANIFEST_SOURCES'] = None # _windowsManifestSources # Set-up ms tools paths msvc_setup_env_once(env) # Loadable modules are on Windows the same as shared libraries, but they # are subject to different build parameters (LDMODULE* variables). # Therefore LDMODULE* variables correspond as much as possible to # SHLINK*/SHLIB* ones. SCons.Tool.createLoadableModuleBuilder(env) env['LDMODULE'] = '$SHLINK' env['LDMODULEPREFIX'] = '$SHLIBPREFIX' env['LDMODULESUFFIX'] = '$SHLIBSUFFIX' env['LDMODULEFLAGS'] = '$SHLINKFLAGS' env['_LDMODULE_TARGETS'] = _windowsLdmodTargets env['_LDMODULE_SOURCES'] = _windowsLdmodSources env['LDMODULEEMITTER'] = [ldmodEmitter] env['LDMODULECOM'] = compositeLdmodAction def exists(env): return msvc_exists() # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.aixc++ Tool-specific initialization for IBM xlC / Visual Age C++ compiler. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/aixc++.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os.path import SCons.Platform.aix cplusplus = __import__('c++', globals(), locals(), []) packages = ['vacpp.cmp.core', 'vacpp.cmp.batch', 'vacpp.cmp.C', 'ibmcxx.cmp'] def get_xlc(env): xlc = env.get('CXX', 'xlC') xlc_r = env.get('SHCXX', 'xlC_r') return SCons.Platform.aix.get_xlc(env, xlc, xlc_r, packages) def smart_cxxflags(source, target, env, for_signature): build_dir = env.GetBuildPath() if build_dir: return '-qtempinc=' + os.path.join(build_dir, 'tempinc') return '' def generate(env): """Add Builders and construction variables for xlC / Visual Age suite to an Environment.""" path, _cxx, _shcxx, version = get_xlc(env) if path: _cxx = os.path.join(path, _cxx) _shcxx = os.path.join(path, _shcxx) cplusplus.generate(env) env['CXX'] = _cxx env['SHCXX'] = _shcxx env['CXXVERSION'] = version env['SHOBJSUFFIX'] = '.pic.o' def exists(env): path, _cxx, _shcxx, version = get_xlc(env) if path and _cxx: xlc = os.path.join(path, _cxx) if os.path.exists(xlc): return xlc return None # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.sgiar Tool-specific initialization for SGI ar (library archive). If CC exists, static libraries should be built with it, so the prelinker has a chance to resolve C++ template instantiations. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/sgiar.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Defaults import SCons.Tool import SCons.Util def generate(env): """Add Builders and construction variables for ar to an Environment.""" SCons.Tool.createStaticLibBuilder(env) if env.Detect('CC'): env['AR'] = 'CC' env['ARFLAGS'] = SCons.Util.CLVar('-ar') env['ARCOM'] = '$AR $ARFLAGS -o $TARGET $SOURCES' else: env['AR'] = 'ar' env['ARFLAGS'] = SCons.Util.CLVar('r') env['ARCOM'] = '$AR $ARFLAGS $TARGET $SOURCES' env['SHLINK'] = '$LINK' env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -shared') env['SHLINKCOM'] = '$SHLINK $SHLINKFLAGS -o $TARGET $SOURCES $_LIBDIRFLAGS $_LIBFLAGS' env['LIBPREFIX'] = 'lib' env['LIBSUFFIX'] = '.a' def exists(env): return env.Detect('CC') or env.Detect('ar') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.midl Tool-specific initialization for midl (Microsoft IDL compiler). There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/midl.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Action import SCons.Builder import SCons.Defaults import SCons.Scanner.IDL import SCons.Util from MSCommon import msvc_exists def midl_emitter(target, source, env): """Produces a list of outputs from the MIDL compiler""" base, ext = SCons.Util.splitext(str(target[0])) tlb = target[0] incl = base + '.h' interface = base + '_i.c' t = [tlb, incl, interface] midlcom = env['MIDLCOM'] if midlcom.find('/proxy') != -1: proxy = base + '_p.c' t.append(proxy) if midlcom.find('/dlldata') != -1: dlldata = base + '_data.c' t.append(dlldata) return (t,source) idl_scanner = SCons.Scanner.IDL.IDLScan() midl_action = SCons.Action.Action('$MIDLCOM', '$MIDLCOMSTR') midl_builder = SCons.Builder.Builder(action = midl_action, src_suffix = '.idl', suffix='.tlb', emitter = midl_emitter, source_scanner = idl_scanner) def generate(env): """Add Builders and construction variables for midl to an Environment.""" env['MIDL'] = 'MIDL.EXE' env['MIDLFLAGS'] = SCons.Util.CLVar('/nologo') env['MIDLCOM'] = '$MIDL $MIDLFLAGS /tlb ${TARGETS[0]} /h ${TARGETS[1]} /iid ${TARGETS[2]} /proxy ${TARGETS[3]} /dlldata ${TARGETS[4]} $SOURCE 2> NUL' env['BUILDERS']['TypeLibrary'] = midl_builder def exists(env): return msvc_exists() # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.javac Tool-specific initialization for javac. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. __revision__ = "src/engine/SCons/Tool/javac.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import os import os.path import SCons.Action import SCons.Builder from SCons.Node.FS import _my_normcase from SCons.Tool.JavaCommon import parse_java_file import SCons.Util def classname(path): """Turn a string (path name) into a Java class name.""" return os.path.normpath(path).replace(os.sep, '.') def emit_java_classes(target, source, env): """Create and return lists of source java files and their corresponding target class files. """ java_suffix = env.get('JAVASUFFIX', '.java') class_suffix = env.get('JAVACLASSSUFFIX', '.class') target[0].must_be_same(SCons.Node.FS.Dir) classdir = target[0] s = source[0].rentry().disambiguate() if isinstance(s, SCons.Node.FS.File): sourcedir = s.dir.rdir() elif isinstance(s, SCons.Node.FS.Dir): sourcedir = s.rdir() else: raise SCons.Errors.UserError("Java source must be File or Dir, not '%s'" % s.__class__) slist = [] js = _my_normcase(java_suffix) for entry in source: entry = entry.rentry().disambiguate() if isinstance(entry, SCons.Node.FS.File): slist.append(entry) elif isinstance(entry, SCons.Node.FS.Dir): result = SCons.Util.OrderedDict() dirnode = entry.rdir() def find_java_files(arg, dirpath, filenames): java_files = sorted([n for n in filenames if _my_normcase(n).endswith(js)]) mydir = dirnode.Dir(dirpath) java_paths = [mydir.File(f) for f in java_files] for jp in java_paths: arg[jp] = True for dirpath, dirnames, filenames in os.walk(dirnode.get_abspath()): find_java_files(result, dirpath, filenames) entry.walk(find_java_files, result) slist.extend(list(result.keys())) else: raise SCons.Errors.UserError("Java source must be File or Dir, not '%s'" % entry.__class__) version = env.get('JAVAVERSION', '1.4') full_tlist = [] for f in slist: tlist = [] source_file_based = True pkg_dir = None if not f.is_derived(): pkg_dir, classes = parse_java_file(f.rfile().get_abspath(), version) if classes: source_file_based = False if pkg_dir: d = target[0].Dir(pkg_dir) p = pkg_dir + os.sep else: d = target[0] p = '' for c in classes: t = d.File(c + class_suffix) t.attributes.java_classdir = classdir t.attributes.java_sourcedir = sourcedir t.attributes.java_classname = classname(p + c) tlist.append(t) if source_file_based: base = f.name[:-len(java_suffix)] if pkg_dir: t = target[0].Dir(pkg_dir).File(base + class_suffix) else: t = target[0].File(base + class_suffix) t.attributes.java_classdir = classdir t.attributes.java_sourcedir = f.dir t.attributes.java_classname = classname(base) tlist.append(t) for t in tlist: t.set_specific_source([f]) full_tlist.extend(tlist) return full_tlist, slist JavaAction = SCons.Action.Action('$JAVACCOM', '$JAVACCOMSTR') JavaBuilder = SCons.Builder.Builder(action = JavaAction, emitter = emit_java_classes, target_factory = SCons.Node.FS.Entry, source_factory = SCons.Node.FS.Entry) class pathopt(object): """ Callable object for generating javac-style path options from a construction variable (e.g. -classpath, -sourcepath). """ def __init__(self, opt, var, default=None): self.opt = opt self.var = var self.default = default def __call__(self, target, source, env, for_signature): path = env[self.var] if path and not SCons.Util.is_List(path): path = [path] if self.default: default = env[self.default] if default: if not SCons.Util.is_List(default): default = [default] path = path + default if path: return [self.opt, os.pathsep.join(map(str, path))] else: return [] def Java(env, target, source, *args, **kw): """ A pseudo-Builder wrapper around the separate JavaClass{File,Dir} Builders. """ if not SCons.Util.is_List(target): target = [target] if not SCons.Util.is_List(source): source = [source] # Pad the target list with repetitions of the last element in the # list so we have a target for every source element. target = target + ([target[-1]] * (len(source) - len(target))) java_suffix = env.subst('$JAVASUFFIX') result = [] for t, s in zip(target, source): if isinstance(s, SCons.Node.FS.Base): if isinstance(s, SCons.Node.FS.File): b = env.JavaClassFile else: b = env.JavaClassDir else: if os.path.isfile(s): b = env.JavaClassFile elif os.path.isdir(s): b = env.JavaClassDir elif s[-len(java_suffix):] == java_suffix: b = env.JavaClassFile else: b = env.JavaClassDir result.extend(b(t, s, *args, **kw)) return result def generate(env): """Add Builders and construction variables for javac to an Environment.""" java_file = SCons.Tool.CreateJavaFileBuilder(env) java_class = SCons.Tool.CreateJavaClassFileBuilder(env) java_class_dir = SCons.Tool.CreateJavaClassDirBuilder(env) java_class.add_emitter(None, emit_java_classes) java_class.add_emitter(env.subst('$JAVASUFFIX'), emit_java_classes) java_class_dir.emitter = emit_java_classes env.AddMethod(Java) env['JAVAC'] = 'javac' env['JAVACFLAGS'] = SCons.Util.CLVar('') env['JAVABOOTCLASSPATH'] = [] env['JAVACLASSPATH'] = [] env['JAVASOURCEPATH'] = [] env['_javapathopt'] = pathopt env['_JAVABOOTCLASSPATH'] = '${_javapathopt("-bootclasspath", "JAVABOOTCLASSPATH")} ' env['_JAVACLASSPATH'] = '${_javapathopt("-classpath", "JAVACLASSPATH")} ' env['_JAVASOURCEPATH'] = '${_javapathopt("-sourcepath", "JAVASOURCEPATH", "_JAVASOURCEPATHDEFAULT")} ' env['_JAVASOURCEPATHDEFAULT'] = '${TARGET.attributes.java_sourcedir}' env['_JAVACCOM'] = '$JAVAC $JAVACFLAGS $_JAVABOOTCLASSPATH $_JAVACLASSPATH -d ${TARGET.attributes.java_classdir} $_JAVASOURCEPATH $SOURCES' env['JAVACCOM'] = "${TEMPFILE('$_JAVACCOM')}" env['JAVACLASSSUFFIX'] = '.class' env['JAVASUFFIX'] = '.java' def exists(env): return 1 # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.applelink Tool-specific initialization for the Apple gnu-like linker. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/applelink.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Util # Even though the Mac is based on the GNU toolchain, it doesn't understand # the -rpath option, so we use the "link" tool instead of "gnulink". import link def generate(env): """Add Builders and construction variables for applelink to an Environment.""" link.generate(env) env['FRAMEWORKPATHPREFIX'] = '-F' env['_FRAMEWORKPATH'] = '${_concat(FRAMEWORKPATHPREFIX, FRAMEWORKPATH, "", __env__)}' env['_FRAMEWORKS'] = '${_concat("-framework ", FRAMEWORKS, "", __env__)}' env['LINKCOM'] = env['LINKCOM'] + ' $_FRAMEWORKPATH $_FRAMEWORKS $FRAMEWORKSFLAGS' env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -dynamiclib') env['SHLINKCOM'] = env['SHLINKCOM'] + ' $_FRAMEWORKPATH $_FRAMEWORKS $FRAMEWORKSFLAGS' # override the default for loadable modules, which are different # on OS X than dynamic shared libs. echoing what XCode does for # pre/suffixes: env['LDMODULEPREFIX'] = '' env['LDMODULESUFFIX'] = '' env['LDMODULEFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -bundle') env['LDMODULECOM'] = '$LDMODULE -o ${TARGET} $LDMODULEFLAGS $SOURCES $_LIBDIRFLAGS $_LIBFLAGS $_FRAMEWORKPATH $_FRAMEWORKS $FRAMEWORKSFLAGS' def exists(env): return env['PLATFORM'] == 'darwin' # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
""" msgfmt tool """ # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. __revision__ = "src/engine/SCons/Tool/msgfmt.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" from SCons.Builder import BuilderBase ############################################################################# class _MOFileBuilder(BuilderBase): """ The builder class for `MO` files. The reason for this builder to exists and its purpose is quite simillar as for `_POFileBuilder`. This time, we extend list of sources, not targets, and call `BuilderBase._execute()` only once (as we assume single-target here). """ def _execute(self, env, target, source, *args, **kw): # Here we add support for 'LINGUAS_FILE' keyword. Emitter is not suitable # in this case, as it is called too late (after multiple sources # are handled single_source builder. import SCons.Util from SCons.Tool.GettextCommon import _read_linguas_from_files linguas_files = None if env.has_key('LINGUAS_FILE') and env['LINGUAS_FILE'] is not None: linguas_files = env['LINGUAS_FILE'] # This should prevent from endless recursion. env['LINGUAS_FILE'] = None # We read only languages. Suffixes shall be added automatically. linguas = _read_linguas_from_files(env, linguas_files) if SCons.Util.is_List(source): source.extend(linguas) elif source is not None: source = [source] + linguas else: source = linguas result = BuilderBase._execute(self,env,target,source,*args, **kw) if linguas_files is not None: env['LINGUAS_FILE'] = linguas_files return result ############################################################################# ############################################################################# def _create_mo_file_builder(env, **kw): """ Create builder object for `MOFiles` builder """ import SCons.Action # FIXME: What factory use for source? Ours or their? kw['action'] = SCons.Action.Action('$MSGFMTCOM','$MSGFMTCOMSTR') kw['suffix'] = '$MOSUFFIX' kw['src_suffix'] = '$POSUFFIX' kw['src_builder'] = '_POUpdateBuilder' kw['single_source'] = True return _MOFileBuilder(**kw) ############################################################################# ############################################################################# def generate(env,**kw): """ Generate `msgfmt` tool """ import SCons.Util from SCons.Tool.GettextCommon import _detect_msgfmt env['MSGFMT'] = _detect_msgfmt(env) env.SetDefault( MSGFMTFLAGS = [ SCons.Util.CLVar('-c') ], MSGFMTCOM = '$MSGFMT $MSGFMTFLAGS -o $TARGET $SOURCE', MSGFMTCOMSTR = '', MOSUFFIX = ['.mo'], POSUFFIX = ['.po'] ) env.Append( BUILDERS = { 'MOFiles' : _create_mo_file_builder(env) } ) ############################################################################# ############################################################################# def exists(env): """ Check if the tool exists """ from SCons.Tool.GettextCommon import _msgfmt_exists return _msgfmt_exists(env) ############################################################################# # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.FortranCommon Stuff for processing Fortran, common to all fortran dialects. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/FortranCommon.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import re import os.path import SCons.Action import SCons.Defaults import SCons.Scanner.Fortran import SCons.Tool import SCons.Util def isfortran(env, source): """Return 1 if any of code in source has fortran files in it, 0 otherwise.""" try: fsuffixes = env['FORTRANSUFFIXES'] except KeyError: # If no FORTRANSUFFIXES, no fortran tool, so there is no need to look # for fortran sources. return 0 if not source: # Source might be None for unusual cases like SConf. return 0 for s in source: if s.sources: ext = os.path.splitext(str(s.sources[0]))[1] if ext in fsuffixes: return 1 return 0 def _fortranEmitter(target, source, env): node = source[0].rfile() if not node.exists() and not node.is_derived(): print "Could not locate " + str(node.name) return ([], []) mod_regex = """(?i)^\s*MODULE\s+(?!PROCEDURE)(\w+)""" cre = re.compile(mod_regex,re.M) # Retrieve all USE'd module names modules = cre.findall(node.get_text_contents()) # Remove unique items from the list modules = SCons.Util.unique(modules) # Convert module name to a .mod filename suffix = env.subst('$FORTRANMODSUFFIX', target=target, source=source) moddir = env.subst('$FORTRANMODDIR', target=target, source=source) modules = [x.lower() + suffix for x in modules] for m in modules: target.append(env.fs.File(m, moddir)) return (target, source) def FortranEmitter(target, source, env): target, source = _fortranEmitter(target, source, env) return SCons.Defaults.StaticObjectEmitter(target, source, env) def ShFortranEmitter(target, source, env): target, source = _fortranEmitter(target, source, env) return SCons.Defaults.SharedObjectEmitter(target, source, env) def ComputeFortranSuffixes(suffixes, ppsuffixes): """suffixes are fortran source files, and ppsuffixes the ones to be pre-processed. Both should be sequences, not strings.""" assert len(suffixes) > 0 s = suffixes[0] sup = s.upper() upper_suffixes = [_.upper() for _ in suffixes] if SCons.Util.case_sensitive_suffixes(s, sup): ppsuffixes.extend(upper_suffixes) else: suffixes.extend(upper_suffixes) def CreateDialectActions(dialect): """Create dialect specific actions.""" CompAction = SCons.Action.Action('$%sCOM ' % dialect, '$%sCOMSTR' % dialect) CompPPAction = SCons.Action.Action('$%sPPCOM ' % dialect, '$%sPPCOMSTR' % dialect) ShCompAction = SCons.Action.Action('$SH%sCOM ' % dialect, '$SH%sCOMSTR' % dialect) ShCompPPAction = SCons.Action.Action('$SH%sPPCOM ' % dialect, '$SH%sPPCOMSTR' % dialect) return CompAction, CompPPAction, ShCompAction, ShCompPPAction def DialectAddToEnv(env, dialect, suffixes, ppsuffixes, support_module = 0): """Add dialect specific construction variables.""" ComputeFortranSuffixes(suffixes, ppsuffixes) fscan = SCons.Scanner.Fortran.FortranScan("%sPATH" % dialect) for suffix in suffixes + ppsuffixes: SCons.Tool.SourceFileScanner.add_scanner(suffix, fscan) env.AppendUnique(FORTRANSUFFIXES = suffixes + ppsuffixes) compaction, compppaction, shcompaction, shcompppaction = \ CreateDialectActions(dialect) static_obj, shared_obj = SCons.Tool.createObjBuilders(env) for suffix in suffixes: static_obj.add_action(suffix, compaction) shared_obj.add_action(suffix, shcompaction) static_obj.add_emitter(suffix, FortranEmitter) shared_obj.add_emitter(suffix, ShFortranEmitter) for suffix in ppsuffixes: static_obj.add_action(suffix, compppaction) shared_obj.add_action(suffix, shcompppaction) static_obj.add_emitter(suffix, FortranEmitter) shared_obj.add_emitter(suffix, ShFortranEmitter) if '%sFLAGS' % dialect not in env: env['%sFLAGS' % dialect] = SCons.Util.CLVar('') if 'SH%sFLAGS' % dialect not in env: env['SH%sFLAGS' % dialect] = SCons.Util.CLVar('$%sFLAGS' % dialect) # If a tool does not define fortran prefix/suffix for include path, use C ones if 'INC%sPREFIX' % dialect not in env: env['INC%sPREFIX' % dialect] = '$INCPREFIX' if 'INC%sSUFFIX' % dialect not in env: env['INC%sSUFFIX' % dialect] = '$INCSUFFIX' env['_%sINCFLAGS' % dialect] = '$( ${_concat(INC%sPREFIX, %sPATH, INC%sSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)' % (dialect, dialect, dialect) if support_module == 1: env['%sCOM' % dialect] = '$%s -o $TARGET -c $%sFLAGS $_%sINCFLAGS $_FORTRANMODFLAG $SOURCES' % (dialect, dialect, dialect) env['%sPPCOM' % dialect] = '$%s -o $TARGET -c $%sFLAGS $CPPFLAGS $_CPPDEFFLAGS $_%sINCFLAGS $_FORTRANMODFLAG $SOURCES' % (dialect, dialect, dialect) env['SH%sCOM' % dialect] = '$SH%s -o $TARGET -c $SH%sFLAGS $_%sINCFLAGS $_FORTRANMODFLAG $SOURCES' % (dialect, dialect, dialect) env['SH%sPPCOM' % dialect] = '$SH%s -o $TARGET -c $SH%sFLAGS $CPPFLAGS $_CPPDEFFLAGS $_%sINCFLAGS $_FORTRANMODFLAG $SOURCES' % (dialect, dialect, dialect) else: env['%sCOM' % dialect] = '$%s -o $TARGET -c $%sFLAGS $_%sINCFLAGS $SOURCES' % (dialect, dialect, dialect) env['%sPPCOM' % dialect] = '$%s -o $TARGET -c $%sFLAGS $CPPFLAGS $_CPPDEFFLAGS $_%sINCFLAGS $SOURCES' % (dialect, dialect, dialect) env['SH%sCOM' % dialect] = '$SH%s -o $TARGET -c $SH%sFLAGS $_%sINCFLAGS $SOURCES' % (dialect, dialect, dialect) env['SH%sPPCOM' % dialect] = '$SH%s -o $TARGET -c $SH%sFLAGS $CPPFLAGS $_CPPDEFFLAGS $_%sINCFLAGS $SOURCES' % (dialect, dialect, dialect) def add_fortran_to_env(env): """Add Builders and construction variables for Fortran to an Environment.""" try: FortranSuffixes = env['FORTRANFILESUFFIXES'] except KeyError: FortranSuffixes = ['.f', '.for', '.ftn'] #print "Adding %s to fortran suffixes" % FortranSuffixes try: FortranPPSuffixes = env['FORTRANPPFILESUFFIXES'] except KeyError: FortranPPSuffixes = ['.fpp', '.FPP'] DialectAddToEnv(env, "FORTRAN", FortranSuffixes, FortranPPSuffixes, support_module = 1) env['FORTRANMODPREFIX'] = '' # like $LIBPREFIX env['FORTRANMODSUFFIX'] = '.mod' # like $LIBSUFFIX env['FORTRANMODDIR'] = '' # where the compiler should place .mod files env['FORTRANMODDIRPREFIX'] = '' # some prefix to $FORTRANMODDIR - similar to $INCPREFIX env['FORTRANMODDIRSUFFIX'] = '' # some suffix to $FORTRANMODDIR - similar to $INCSUFFIX env['_FORTRANMODFLAG'] = '$( ${_concat(FORTRANMODDIRPREFIX, FORTRANMODDIR, FORTRANMODDIRSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)' def add_f77_to_env(env): """Add Builders and construction variables for f77 to an Environment.""" try: F77Suffixes = env['F77FILESUFFIXES'] except KeyError: F77Suffixes = ['.f77'] #print "Adding %s to f77 suffixes" % F77Suffixes try: F77PPSuffixes = env['F77PPFILESUFFIXES'] except KeyError: F77PPSuffixes = [] DialectAddToEnv(env, "F77", F77Suffixes, F77PPSuffixes) def add_f90_to_env(env): """Add Builders and construction variables for f90 to an Environment.""" try: F90Suffixes = env['F90FILESUFFIXES'] except KeyError: F90Suffixes = ['.f90'] #print "Adding %s to f90 suffixes" % F90Suffixes try: F90PPSuffixes = env['F90PPFILESUFFIXES'] except KeyError: F90PPSuffixes = [] DialectAddToEnv(env, "F90", F90Suffixes, F90PPSuffixes, support_module = 1) def add_f95_to_env(env): """Add Builders and construction variables for f95 to an Environment.""" try: F95Suffixes = env['F95FILESUFFIXES'] except KeyError: F95Suffixes = ['.f95'] #print "Adding %s to f95 suffixes" % F95Suffixes try: F95PPSuffixes = env['F95PPFILESUFFIXES'] except KeyError: F95PPSuffixes = [] DialectAddToEnv(env, "F95", F95Suffixes, F95PPSuffixes, support_module = 1) def add_f03_to_env(env): """Add Builders and construction variables for f03 to an Environment.""" try: F03Suffixes = env['F03FILESUFFIXES'] except KeyError: F03Suffixes = ['.f03'] #print "Adding %s to f95 suffixes" % F95Suffixes try: F03PPSuffixes = env['F03PPFILESUFFIXES'] except KeyError: F03PPSuffixes = [] DialectAddToEnv(env, "F03", F03Suffixes, F03PPSuffixes, support_module = 1) def add_all_to_env(env): """Add builders and construction variables for all supported fortran dialects.""" add_fortran_to_env(env) add_f77_to_env(env) add_f90_to_env(env) add_f95_to_env(env) add_f03_to_env(env) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
# -*- python -*- # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __doc__ = """ Textfile/Substfile builder for SCons. Create file 'target' which typically is a textfile. The 'source' may be any combination of strings, Nodes, or lists of same. A 'linesep' will be put between any part written and defaults to os.linesep. The only difference between the Textfile builder and the Substfile builder is that strings are converted to Value() nodes for the former and File() nodes for the latter. To insert files in the former or strings in the latter, wrap them in a File() or Value(), respectively. The values of SUBST_DICT first have any construction variables expanded (its keys are not expanded). If a value of SUBST_DICT is a python callable function, it is called and the result is expanded as the value. Values are substituted in a "random" order; if any substitution could be further expanded by another subsitition, it is unpredictible whether the expansion will occur. """ __revision__ = "src/engine/SCons/Tool/textfile.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons import os import re from SCons.Node import Node from SCons.Node.Python import Value from SCons.Util import is_String, is_Sequence, is_Dict def _do_subst(node, subs): """ Fetch the node contents and replace all instances of the keys with their values. For example, if subs is {'%VERSION%': '1.2345', '%BASE%': 'MyProg', '%prefix%': '/bin'}, then all instances of %VERSION% in the file will be replaced with 1.2345 and so forth. """ contents = node.get_text_contents() if not subs: return contents for (k,v) in subs: contents = re.sub(k, v, contents) return contents def _action(target, source, env): # prepare the line separator linesep = env['LINESEPARATOR'] if linesep is None: linesep = os.linesep elif is_String(linesep): pass elif isinstance(linesep, Value): linesep = linesep.get_text_contents() else: raise SCons.Errors.UserError( 'unexpected type/class for LINESEPARATOR: %s' % repr(linesep), None) # create a dictionary to use for the substitutions if 'SUBST_DICT' not in env: subs = None # no substitutions else: d = env['SUBST_DICT'] if is_Dict(d): d = list(d.items()) elif is_Sequence(d): pass else: raise SCons.Errors.UserError('SUBST_DICT must be dict or sequence') subs = [] for (k,v) in d: if callable(v): v = v() if is_String(v): v = env.subst(v) else: v = str(v) subs.append((k,v)) # write the file try: fd = open(target[0].get_path(), "wb") except (OSError,IOError), e: raise SCons.Errors.UserError("Can't write target file %s" % target[0]) # separate lines by 'linesep' only if linesep is not empty lsep = None for s in source: if lsep: fd.write(lsep) fd.write(_do_subst(s, subs)) lsep = linesep fd.close() def _strfunc(target, source, env): return "Creating '%s'" % target[0] def _convert_list_R(newlist, sources): for elem in sources: if is_Sequence(elem): _convert_list_R(newlist, elem) elif isinstance(elem, Node): newlist.append(elem) else: newlist.append(Value(elem)) def _convert_list(target, source, env): if len(target) != 1: raise SCons.Errors.UserError("Only one target file allowed") newlist = [] _convert_list_R(newlist, source) return target, newlist _common_varlist = ['SUBST_DICT', 'LINESEPARATOR'] _text_varlist = _common_varlist + ['TEXTFILEPREFIX', 'TEXTFILESUFFIX'] _text_builder = SCons.Builder.Builder( action = SCons.Action.Action(_action, _strfunc, varlist = _text_varlist), source_factory = Value, emitter = _convert_list, prefix = '$TEXTFILEPREFIX', suffix = '$TEXTFILESUFFIX', ) _subst_varlist = _common_varlist + ['SUBSTFILEPREFIX', 'TEXTFILESUFFIX'] _subst_builder = SCons.Builder.Builder( action = SCons.Action.Action(_action, _strfunc, varlist = _subst_varlist), source_factory = SCons.Node.FS.File, emitter = _convert_list, prefix = '$SUBSTFILEPREFIX', suffix = '$SUBSTFILESUFFIX', src_suffix = ['.in'], ) def generate(env): env['LINESEPARATOR'] = os.linesep env['BUILDERS']['Textfile'] = _text_builder env['TEXTFILEPREFIX'] = '' env['TEXTFILESUFFIX'] = '.txt' env['BUILDERS']['Substfile'] = _subst_builder env['SUBSTFILEPREFIX'] = '' env['SUBSTFILESUFFIX'] = '' def exists(env): return 1 # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python
"""SCons.Tool.mslib Tool-specific initialization for lib (MicroSoft library archiver). There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/mslib.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" import SCons.Defaults import SCons.Tool import SCons.Tool.msvs import SCons.Tool.msvc import SCons.Util from MSCommon import msvc_exists, msvc_setup_env_once def generate(env): """Add Builders and construction variables for lib to an Environment.""" SCons.Tool.createStaticLibBuilder(env) # Set-up ms tools paths msvc_setup_env_once(env) env['AR'] = 'lib' env['ARFLAGS'] = SCons.Util.CLVar('/nologo') env['ARCOM'] = "${TEMPFILE('$AR $ARFLAGS /OUT:$TARGET $SOURCES')}" env['LIBPREFIX'] = '' env['LIBSUFFIX'] = '.lib' def exists(env): return msvc_exists() # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
Python