### Install Example with User/Group Source: https://waf.io/apidocs/Build An example demonstrating how to use `install_as` and `symlink_as` with `install_user` and `install_group` attributes to set ownership during installation. ```Python def build(bld): bld.install_as('${PREFIX}/wscript', 'wscript', install_user='nobody', install_group='nogroup') bld.symlink_as('${PREFIX}/wscript_link', Utils.subst_vars('${PREFIX}/wscript', bld.env), install_user='nobody', install_group='nogroup') ``` -------------------------------- ### InstallContext for System Installations Source: https://waf.io/apidocs/Build The `InstallContext` class is used to install targets onto the system. It manages the process of installing files and symbolic links. ```Python class waflib.Build.InstallContext(_** kw_) ``` -------------------------------- ### Configure Build and Installation Options in Waf Source: https://waf.io/apidocs/_modules/waflib/Options This snippet demonstrates how to add various build and installation options to the Waf build system. It includes options for installation prefix, binary and library directories, progress bar display, target generators, file processing, destination directory, and force installation. ```Python gr.add_option('--no-lock-in-out', action='store_true', default=os.environ.get('NO_LOCK_IN_OUT', ''), help=argparse.SUPPRESS, dest='no_lock_in_out') gr.add_option('--no-lock-in-top', action='store_true', default=os.environ.get('NO_LOCK_IN_TOP', ''), help=argparse.SUPPRESS, dest='no_lock_in_top') default_prefix = getattr(Context.g_module, 'default_prefix', os.environ.get('PREFIX')) if not default_prefix: if Utils.unversioned_sys_platform() == 'win32': d = tempfile.gettempdir() default_prefix = d[0].upper() + d[1:] else: default_prefix = '/usr/local/' gr.add_option('--prefix', dest='prefix', default=default_prefix, help='installation prefix [default: %r]' % default_prefix) gr.add_option('--bindir', dest='bindir', help='bindir') gr.add_option('--libdir', dest='libdir', help='libdir') gr = self.add_option_group('Build and installation options') gr.add_option('-p', '--progress', dest='progress_bar', default=0, action='count', help= '-p: progress bar; -pp: ide output') gr.add_option('--targets', dest='targets', default='', action='store', help='task generators, e.g. "target1,target2"') gr = self.add_option_group('Step options') gr.add_option('--files', dest='files', default='', action='store', help='files to process, by regexp, e.g. "*/main.c,*/test/main.o"') default_destdir = os.environ.get('DESTDIR', '') gr = self.add_option_group('Installation and uninstallation options') gr.add_option('--destdir', help='installation root [default: %r]' % default_destdir, default=default_destdir, dest='destdir') gr.add_option('-f', '--force', dest='force', default=False, action='store_true', help='disable file installation caching') gr.add_option('--distcheck-args', metavar='ARGS', help='arguments to pass to distcheck', default=None, action='store') ``` -------------------------------- ### Get Installation Path Source: https://waf.io/apidocs/_modules/waflib/Build Retrieves the destination path for installation, optionally prepending a directory. It handles both absolute and relative paths, resolving them against the environment's PREFIX if necessary, and can prepend the destdir option. ```Python def get_install_path(self, destdir=True): """ Returns the destination path where files will be installed, pre-pending `destdir`. Relative paths will be interpreted relative to `PREFIX` if no `destdir` is given. :rtype: string """ if isinstance(self.install_to, Node.Node): dest = self.install_to.abspath() else: dest = os.path.normpath(Utils.subst_vars(self.install_to, self.env)) if not os.path.isabs(dest): dest = os.path.join(self.env.PREFIX, dest) if destdir and Options.options.destdir: dest = Options.options.destdir.rstrip(os.sep) + os.sep + os.path.splitdrive(dest)[1].lstrip(os.sep) return dest ``` -------------------------------- ### Create Installation Task for a Symbolic Link Source: https://waf.io/apidocs/Build Creates an installation task specifically for a symbolic link. This allows for the installation of symlinks as part of the build process. ```Python waflib.Build.add_symlink_as(_self_ , _** kw_) ``` -------------------------------- ### Install Files with Waflib Source: https://waf.io/apidocs/Build Creates a task generator to install files to a specified destination directory. Supports various parameters for controlling the installation process. ```Python def build(bld): bld.install_files('${DATADIR}', self.path.find_resource('wscript')) ``` -------------------------------- ### Add Installation Task in Waflib Source: https://waf.io/apidocs/Build A task generator method that creates an installation task and optionally executes it immediately. Returns the created installation task. ```Python add_install_task(_self_ , ** kw_) ``` -------------------------------- ### Create Installation Task for a Single File Source: https://waf.io/apidocs/Build Generates an installation task for a single file. This task is typically executed by `InstallContext` or `UnInstallContext` to manage file installations. ```Python waflib.Build.add_install_as(_self_ , _** kw_) ``` -------------------------------- ### Add Installation As Task in Waflib Source: https://waf.io/apidocs/Build A task generator method for creating an installation task where a file is installed with a different name. ```Python add_install_as(_self_ , ** kw_) ``` -------------------------------- ### Waflib Build Installation Task Logic Source: https://waf.io/apidocs/Build This code snippet represents the core logic for installation tasks within Waflib. It handles file copying, symlink creation, and installation status checks. ```Python hcode _ = b'\tdef run(self):\n\t\t ``` -------------------------------- ### Add Installation Files Task in Waflib Source: https://waf.io/apidocs/Build A task generator method specifically for creating an installation task for files. Returns the created installation task. ```Python add_install_files(_self_ , ** kw_) ``` -------------------------------- ### Process Installation Task in Waflib Source: https://waf.io/apidocs/Build A task generator method that creates the installation task for the current task generator, internally using `add_install_task`. ```Python process_install_task(_self_) ``` -------------------------------- ### Waf Feature: Install Task Source: https://waf.io/apidocs/featuremap Handles the installation of build artifacts. This feature relies on 'process_source' and 'process_rule' to manage the source files and build rules for installation. ```Python def process_install_task(self): # Implementation details for install tasks pass def process_source(self): # Implementation details for processing source files pass def process_rule(self): # Implementation details for processing build rules pass ``` -------------------------------- ### Install Files or Symlinks Source: https://waf.io/apidocs/Build The `inst` class represents a task that installs files or symbolic links. It's managed by `InstallContext` and `UnInstallContext` and handles the actual copying or linking process. ```Python class waflib.Build.inst(_* k_, _** kw_) ``` -------------------------------- ### Setup Waf Tools Source: https://waf.io/apidocs/_modules/waflib/Build Imports Waf tools defined during configuration. It can load a single tool or iterate through a list of tools. The `setup` method on the tool module is called if it exists. ```Python def setup(self, tool, tooldir=None, funs=None): """ Import waf tools defined during the configuration:: def configure(conf): conf.load('glib2') def build(bld): pass # glib2 is imported implicitly :param tool: tool list :type tool: list :param tooldir: optional tool directory (sys.path) :type tooldir: list of string :param funs: unused variable """ if isinstance(tool, list): for i in tool: self.setup(i, tooldir) return module = Context.load_tool(tool, tooldir) if hasattr(module, "setup"): module.setup(self) ``` -------------------------------- ### Add Installation Task (Waf) Source: https://waf.io/apidocs/_modules/waflib/Build A core method for creating installation tasks. It handles the logic for creating the 'inst' task, setting its attributes based on provided keyword arguments, and optionally running it immediately. It also includes platform-specific handling for Windows symlinks. ```Python @TaskGen.taskgen_method def add_install_task(self, **kw): """ Creates the installation task for the current task generator, and executes it immediately if necessary :returns: An installation task :rtype: :py:class:`waflib.Build.inst` """ if not self.bld.is_install: return if not kw['install_to']: return if kw['type'] == 'symlink_as' and Utils.is_win32: if kw.get('win32_install'): kw['type'] = 'install_as' else: # just exit return tsk = self.install_task = self.create_task('inst') tsk.chmod = kw.get('chmod', Utils.O644) tsk.link = kw.get('link', '') or kw.get('install_from', '') tsk.relative_trick = kw.get('relative_trick', False) tsk.type = kw['type'] tsk.install_to = tsk.dest = kw['install_to'] tsk.install_from = kw['install_from'] tsk.relative_base = kw.get('cwd') or kw.get('relative_base', self.path) tsk.install_user = kw.get('install_user') tsk.install_group = kw.get('install_group') tsk.init_files() if not kw.get('postpone', True): tsk.run_now() return tsk ``` -------------------------------- ### Create Symlink Installation Task in Waflib Source: https://waf.io/apidocs/Build Creates a task generator to install a symbolic link. Supports specifying the destination, source, and whether the symlink should be relative. ```Python def build(bld): bld.symlink_as('${PREFIX}/lib/libfoo.so', 'libfoo.so.1.2.3') ``` -------------------------------- ### Add Install Files Task Helper (Waf) Source: https://waf.io/apidocs/_modules/waflib/Build A convenience method that sets the task type to 'install_files' and then calls `add_install_task` to create the installation task for files. ```Python @TaskGen.taskgen_method def add_install_files(self, **kw): """ Creates an installation task for files :returns: An installation task :rtype: :py:class:`waflib.Build.inst` """ kw['type'] = 'install_files' return self.add_install_task(**kw) ``` -------------------------------- ### Wafcache Upload Example with gsutil Source: https://waf.io/apidocs/tools/wafcache Illustrates an example of uploading a build artifact to a GCS bucket configured via WAFCACHE. This command uses gsutil to copy the local file to the specified bucket path. ```bash gsutil cp build/myprogram gs://mybucket/aa/aaaaa/1 ``` -------------------------------- ### Add Install As Task Helper (Waf) Source: https://waf.io/apidocs/_modules/waflib/Build A convenience method that sets the task type to 'install_as' and then calls `add_install_task` to create the installation task for a single file, potentially with a different name. ```Python @TaskGen.taskgen_method def add_install_as(self, **kw): """ Creates an installation task for a single file :returns: An installation task :rtype: :py:class:`waflib.Build.inst` """ kw['type'] = 'install_as' return self.add_install_task(**kw) ``` -------------------------------- ### Get File Suffix Source: https://waf.io/apidocs/_modules/waflib/Node Extracts the file extension (the rightmost part starting with a dot) from the node's name. For example, `a.b.c.d` returns `.d`. ```Python # ... inside a class method ... k = max(0, self.name.rfind('.')) return self.name[k:] ``` -------------------------------- ### Executing Waf Build Commands Source: https://waf.io/apidocs/tutorial Demonstrates how to execute Waf build commands from the command line. It shows the process of running the Waf script with 'configure' and 'build' arguments and the expected output. ```bash $ python ./waf-2.0.0 configure build configure! build! ``` -------------------------------- ### Waflib: Tool Setup Methods Source: https://waf.io/apidocs/genindex Details methods for setting up specific build tools and configurations, such as for Fortran, MSVC, and C preprocessor. ```Python setup_ifort() (in module waflib.Tools.ifort) setup_msvc() (in module waflib.Tools.msvc) set_define_comment() (in module waflib.Tools.c_config) stringize() (in module waflib.Tools.c_preproc) STR (in module waflib.Tools.c_preproc) ``` -------------------------------- ### Waf: Qt5 Package Configuration Source: https://waf.io/apidocs/genindex Utility function to get the pkg-config path for Qt5 installations. ```Python waflib.Tools.qt5.qt_pkg_config_path() ``` -------------------------------- ### Executing Waf Build Commands Source: https://waf.io/apidocs/_sources/tutorial Demonstrates how to execute Waf build commands from the terminal. It shows the command to run the 'configure' and 'build' steps. ```bash $ python ./waf-2.0.0 configure build ``` -------------------------------- ### Get Intel Fortran Versions Source: https://waf.io/apidocs/_sources/confmap Retrieves all available versions of the Intel Fortran compiler. This can be useful when multiple versions are installed. ```Python from waflib.Tools.ifort import get_ifort_versions ``` -------------------------------- ### Configure and Build C/C++ Project with Waf Source: https://waf.io/apidocs/tutorial This snippet demonstrates a Waf build script for a C and C++ project. It defines options, configuration steps including library checks (like 'm'), and build steps for creating shared libraries and executables, managing dependencies and build variables. ```Python def options(opt): opt.load('compiler_c compiler_cxx') def configure(cnf): cnf.load('compiler_c compiler_cxx') cnf.check(features='cxx cxxprogram', lib=['m'], cflags=['-Wall'], defines=['var=foo'], uselib_store='M') def build(bld): bld(features='c cshlib', source='b.c', target='mylib') bld(features='c cxx cxxprogram', source='a.c main.cpp', target='app', use=['M','mylib'], lib=['dl']) ``` -------------------------------- ### Get File Extensions with c_aliases Source: https://waf.io/apidocs/tools/c_aliases Provides an example of the `get_extensions` function, which returns the file extensions for a given list of source files. ```python # Example usage (not directly in the provided text, but implied by function signature): # from waflib.Tools import c_aliases # extensions = c_aliases.get_extensions(['file1.c', 'file2.cpp']) # print(extensions) ``` -------------------------------- ### Get MSVC Compiler Versions Source: https://waf.io/apidocs/_sources/confmap Retrieves all installed versions of the Microsoft Visual C++ compiler. This allows selection of a specific MSVC version for the build. ```Python from waflib.Tools.msvc import get_msvc_versions ``` -------------------------------- ### Waf Project Setup for C Language Source: https://waf.io/apidocs/_sources/tutorial Provides a Waf script configuration for a C project. It loads the 'compiler_c' tool and defines a build task for a C program. ```python def options(opt): opt.load('compiler_c') def configure(cnf): cnf.load('compiler_c') def build(bld): bld(features='c cprogram', source='main.c', target='app') ``` -------------------------------- ### Waf: Configuration Context Methods Source: https://waf.io/apidocs/genindex Methods for preparing the build environment and managing configuration settings. This includes environment setup and value prepending. ```Python waflib.Configure.ConfigurationContext.prepare_env() waflib.Configure.ConfigurationContext.post_recurse() waflib.ConfigSet.ConfigSet.prepend_value() ``` -------------------------------- ### Get MSVC Version and Environment Source: https://waf.io/apidocs/tools/msvc Verifies that an installed MSVC compiler runs correctly and uses the `vcvars` script to set up the necessary environment variables for the compiler. ```Python def get_msvc_version(_conf_ , _compiler_ , _version_ , _target_ , _vcvars_): """ Configuration Method bound to `waflib.Configure.ConfigurationContext` Checks that an installed compiler actually runs and uses vcvars to obtain the environment needed by the compiler. Parameters compiler – compiler type, for looking up the executable name version – compiler version, for debugging only target – target architecture vcvars – batch file to run to check the environment Returns the location of the compiler executable, the location of include dirs, and the library paths Return type tuple of strings """ pass ``` -------------------------------- ### Get Build Path Source: https://waf.io/apidocs/_modules/waflib/Node Returns the relative path of the Node from the build directory. For example, 'src/foo.cpp' would be returned if the build directory is the project root. ```Python def bldpath(self): """ Returns the relative path seen from the build directory ``src/foo.cpp`` :rtype: string """ return self.path_from(self.ctx.bldnode) ``` -------------------------------- ### Waf Configuration for C Programs Source: https://waf.io/apidocs/tutorial Provides an example of configuring Waf for C projects. It loads the 'compiler_c' tool, configures it, and then defines a build task for a C program using features like 'c' and 'cprogram'. ```python def options(opt): opt.load('compiler_c') def configure(cnf): cnf.load('compiler_c') def build(bld): bld(features='c cprogram', source='main.c', target='app') ``` -------------------------------- ### Get Source Path Source: https://waf.io/apidocs/_modules/waflib/Node Returns the relative path of the Node from the source directory. For example, '../src/foo.cpp' would be returned if the build directory is a subdirectory of the project root. ```Python def srcpath(self): """ Returns the relative path seen from the source directory ``../src/foo.cpp`` :rtype: string """ return self.path_from(self.ctx.srcnode) ``` -------------------------------- ### Prepare Build Environment Source: https://waf.io/apidocs/_modules/waflib/Configure Prepares the build environment by inserting PREFIX, BINDIR, and LIBDIR values into the env configuration. It handles default values if options are not provided. ```Python def prepare_env(self, env): """ Insert *PREFIX*, *BINDIR* and *LIBDIR* values into ``env`` :type env: :py:class:`waflib.ConfigSet.ConfigSet` :param env: a ConfigSet, usually ``conf.env`` """ if not env.PREFIX: if getattr(Options.options, 'prefix', None): env.PREFIX = Options.options.prefix else: env.PREFIX = '/' if not env.BINDIR: if getattr(Options.options, 'bindir', None): env.BINDIR = Options.options.bindir else: env.BINDIR = Utils.subst_vars('${PREFIX}/bin', env) if not env.LIBDIR: if getattr(Options.options, 'libdir', None): env.LIBDIR = Options.options.libdir else: env.LIBDIR = Utils.subst_vars('${PREFIX}/lib%s' % Utils.lib64(), env) ``` -------------------------------- ### Setup MSVC Compiler Configuration Source: https://waf.io/apidocs/tools/msvc Configures the MSVC compiler by checking installed compilers and targets. It selects the first suitable combination based on user options, environment, or global lists. ```Python def setup_msvc(_conf_ , _versiondict_): """ Configuration Method bound to `waflib.Configure.ConfigurationContext` Checks installed compilers and targets and returns the first combination from the user’s options, env, or the global supported lists that checks. Parameters versiondict (_dict_ _(__string - > dict_ _(__string - > target_compiler_ _)_) – dict(platform -> dict(architecture -> configuration)) Returns the compiler, revision, path, include dirs, library paths and target architecture Return type tuple of strings """ pass ``` -------------------------------- ### Add Command-Line Options for GNU Directories Source: https://waf.io/apidocs/tools/gnu_dirs Shows how the 'gnu_dirs' module adds command-line options to Waf for configuring standard GNU installation directories. An example of adding the `--exec-prefix` option is provided. ```python conf.options(_opt_) # Example of adding an option: # --exec-prefix: EXEC_PREFIX ``` -------------------------------- ### Load Waf Tool Example Source: https://waf.io/apidocs/tools Demonstrates how to load a Waf tool within a user script. This is a common pattern for integrating specific build functionalities provided by Waf tools. ```Python def function(ctx): # ... ctx.load('toolname') ``` -------------------------------- ### Setup Intel Fortran Compiler Configuration Source: https://waf.io/apidocs/_modules/waflib/Tools/ifort Provides the interface for checking installed compilers and targets, returning the first suitable combination based on user options, environment variables, or global lists. ```Python @conf def setup_ifort(conf, versiondict): """ Checks installed compilers and targets and returns the first combination from the user's options, env, or the global supported lists that checks. :param versiondict: dict(platform -> dict(architecture -> configuration)) :type versiondict: dict(string -> dict(string -> target_compiler) :return: the compiler, revision, path, include dirs, library paths and target architecture :rtype: tuple of strings """ ``` -------------------------------- ### Configure Waf with Tools Source: https://waf.io/apidocs/Build Demonstrates how to configure Waf to load specific tools, such as 'glib2', and defines a placeholder build function. ```Python def configure(conf): conf.load('glib2') def build(bld): pass # glib2 is imported implicitly ``` -------------------------------- ### Get Option Group Wrapper in Waf Source: https://waf.io/apidocs/_modules/waflib/Options This function retrieves an option group from the Waf parser, wrapping `optparse.get_option_group`. It provides an example of how to access and add options to a specific group. ```Python def get_option_group(self, opt_str): """ Wraps ``optparse.get_option_group``:: def options(ctx): gr = ctx.get_option_group('configure options') gr.add_option('-o', '--out', action='store', default='', help='build dir for the project', dest='out') :rtype: optparse option group object """ try: return self.option_groups[opt_str] except KeyError: for group in self.parser._action_groups: if group.title == opt_str: return group return None ``` -------------------------------- ### Basic Waf Configuration and Build Functions Source: https://waf.io/apidocs/tutorial Defines the essential 'configure' and 'build' functions for a Waf project. The 'configure' function prints a message indicating the configuration phase, and the 'build' function prints a message for the build phase. ```python def configure(cnf): print("configure!") def build(bld): print("build!") ``` -------------------------------- ### Initialize Gruik and Get Nodes/Names in Python Source: https://waf.io/apidocs/_modules/waflib/Tools/d_scan This snippet shows how to start the gruik object and retrieve the list of nodes and their corresponding names. It's a fundamental operation for interacting with the Waf build system's scanning tools. ```Python gruik.start(node) nodes = gruik.nodes names = gruik.names return (nodes, names) ``` -------------------------------- ### Basic Waf Configuration and Build Source: https://waf.io/apidocs/_sources/tutorial Defines the basic 'configure' and 'build' functions for a Waf project. These functions print messages to indicate their execution. ```python def configure(cnf): print("configure!") def build(bld): print("build!") ``` -------------------------------- ### C/C++ Compiler Loading Example Source: https://waf.io/apidocs/tools Shows the standard method for loading C or C++ compiler tools in Waf. This is typically done in the options and configure steps of a build script. ```Python def options(opt): opt.load('compiler_c') def configure(conf): conf.load('compiler_c') ``` -------------------------------- ### Waf Feature for Python File Installation Source: https://waf.io/apidocs/_modules/waflib/Tools/python Defines a Waf feature 'py' to handle the installation of Python files. It manages installation paths, checks for Python version compatibility for installation, and sets up installation targets. ```Python @before_method('process_source') @feature('py') def feature_py(self): """ Create tasks to byte-compile .py files and install them, if requested """ self.install_path = getattr(self, 'install_path', '${PYTHONDIR}') install_from = getattr(self, 'install_from', None) if install_from and not isinstance(install_from, Node.Node): install_from = self.path.find_dir(install_from) self.install_from = install_from ver = self.env.PYTHON_VERSION if not ver: self.bld.fatal('Installing python files requires PYTHON_VERSION, try conf.check_python_version') if int(ver.replace('.', '')) > 31: self.install_32 = True ``` -------------------------------- ### Waf Command-Line Options Example Source: https://waf.io/apidocs/Options Demonstrates how to set a user-provided command-line option using the 'waf --foo=bar' syntax. This option is stored in the global 'options' dictionary. ```bash $ waf --foo=bar ``` -------------------------------- ### Waflib: Build Task Initialization Source: https://waf.io/apidocs/genindex Details methods for initializing tasks and their components, including setting up parsers and handlers. ```Python start() (waflib.Tools.c_preproc.c_parser method) (waflib.Tools.d_scan.d_parser method) (waflib.Tools.fc_scan.fortran_parser method) startDocument() (waflib.Tools.qt5.ContentHandler method) startElement() (waflib.Tools.qt5.ContentHandler method) startElementNS() (waflib.Tools.qt5.ContentHandler method) startPrefixMapping() (waflib.Tools.qt5.ContentHandler method) ``` -------------------------------- ### Initialize Project Directories Source: https://waf.io/apidocs/_modules/waflib/Configure Initializes the project's source and build directories. It determines the top-level source directory and creates the build directory, ensuring they are properly set up for the build process. Includes error handling for directory creation. ```Python def init_dirs(self): """ Initialize the project directory and the build directory """ top = self.top_dir if not top: top = getattr(Options.options, 'top', None) if not top: top = getattr(Context.g_module, Context.TOP, None) if not top: top = self.path.abspath() top = os.path.abspath(top) self.srcnode = (os.path.isabs(top) and self.root or self.path).find_dir(top) assert(self.srcnode) out = self.out_dir if not out: out = getattr(Options.options, 'out', None) if not out: out = getattr(Context.g_module, Context.OUT, None) if not out: out = Options.lockfile.replace('.lock-waf_%s_' % sys.platform, '').replace('.lock-waf', '') # someone can be messing with symlinks out = os.path.realpath(out) self.bldnode = (os.path.isabs(out) and self.root or self.path).make_node(out) self.bldnode.mkdir() if not os.path.isdir(self.bldnode.abspath()): self.fatal('Could not create the build directory %s' % self.bldnode.abspath()) ``` -------------------------------- ### Wafcache Download Example with gsutil Source: https://waf.io/apidocs/tools/wafcache Demonstrates downloading a cached artifact from a GCS bucket using gsutil. The command fetches a file from the bucket and places it in the local build directory. ```bash gsutil cp gs://mybucket/bb/bbbbb/2 build/somefile ``` -------------------------------- ### Waf Project Setup for C and C++ Languages Source: https://waf.io/apidocs/_sources/tutorial Configures a Waf project for both C and C++ compilation. It loads the respective compiler tools, checks for libraries, and defines build tasks for a shared library and an executable. ```python def options(opt): opt.load('compiler_c compiler_cxx') def configure(cnf): cnf.load('compiler_c compiler_cxx') cnf.check(features='cxx cxxprogram', lib=['m'], cflags=['-Wall'], defines=['var=foo'], uselib_store='M') def build(bld): bld(features='c cshlib', source='b.c', target='mylib') bld(features='c cxx cxxprogram', source='a.c main.cpp', target='app', use=['M','mylib'], lib=['dl']) ``` -------------------------------- ### Install File with Different Name in Waflib Source: https://waf.io/apidocs/Build Creates a task generator to install a file with a different name at the destination. Allows specifying permissions and other installation options. ```Python def build(bld): bld.install_as('${PREFIX}/bin', 'myapp', chmod=Utils.O755) ``` -------------------------------- ### Load Waf Tool Example Source: https://waf.io/apidocs/_sources/tools Demonstrates the typical usage of loading a Waf tool within a user script. The `load` function is used to integrate specific tool functionalities into the build context. ```python def function(ctx): # ... ctx.load('toolname') ``` -------------------------------- ### Get MSVC Environment Variables Source: https://waf.io/apidocs/_modules/waflib/Tools/msvc This function checks if an installed MSVC compiler is usable by executing a batch file (`vcvars`) to obtain the necessary environment variables (PATH, INCLUDE, LIB). It parses the output to extract these paths and then attempts to find the compiler executable using the resolved PATH. Error handling is included for Unicode issues and general execution failures. ```Python def get_msvc_version(conf, compiler, version, target, vcvars): """ Checks that an installed compiler actually runs and uses vcvars to obtain the environment needed by the compiler. :param compiler: compiler type, for looking up the executable name :param version: compiler version, for debugging only :param target: target architecture :param vcvars: batch file to run to check the environment :return: the location of the compiler executable, the location of include dirs, and the library paths :rtype: tuple of strings """ Logs.debug('msvc: get_msvc_version: %r %r %r', compiler, version, target) try: conf.msvc_cnt += 1 except AttributeError: conf.msvc_cnt = 1 batfile = conf.bldnode.make_node('waf-print-msvc-%d.bat' % conf.msvc_cnt) batfile.write("@echo off\nset INCLUDE=\nset LIB=\ncall \"%s\" %s\necho PATH=%%PATH%%\necho INCLUDE=%%INCLUDE%%\necho LIB=%%LIB%%;%%LIBPATH%%\n" % (vcvars,target)) sout = conf.cmd_and_log(['cmd.exe', '/E:on', '/V:on', '/C', batfile.abspath()], stdin=getattr(Utils.subprocess, 'DEVNULL', None)) lines = sout.splitlines() if not lines[0]: lines.pop(0) MSVC_PATH = MSVC_INCDIR = MSVC_LIBDIR = None for line in lines: if line.startswith('PATH=') : path = line[5:] MSVC_PATH = path.split(';') elif line.startswith('INCLUDE=') : MSVC_INCDIR = [i for i in line[8:].split(';') if i] elif line.startswith('LIB=') : MSVC_LIBDIR = [i for i in line[4:].split(';') if i] if None in (MSVC_PATH, MSVC_INCDIR, MSVC_LIBDIR): conf.fatal('msvc: Could not find a valid architecture for building (get_msvc_version_3)') # Check if the compiler is usable at all. # The detection may return 64-bit versions even on 32-bit systems, and these would fail to run. env = dict(os.environ) env.update(PATH = path) compiler_name, linker_name, lib_name = _get_prog_names(conf, compiler) cxx = conf.find_program(compiler_name, path_list=MSVC_PATH) # delete CL if exists. because it could contain parameters which can change cl's behaviour rather catastrophically. if 'CL' in env: del(env['CL']) try: conf.cmd_and_log(cxx + ['/help'], env=env) except UnicodeError: st = traceback.format_exc() if conf.logger: conf.logger.error(st) conf.fatal('msvc: Unicode error - check the code page?') except Exception as e: Logs.debug('msvc: get_msvc_version: %r %r %r -> failure %s', compiler, version, target, str(e)) conf.fatal('msvc: cannot run the compiler in get_msvc_version (run with -v to display errors)') else: Logs.debug('msvc: get_msvc_version: %r %r %r -> OK', compiler, version, target) finally: conf.env[compiler_name] = '' return (MSVC_PATH, MSVC_INCDIR, MSVC_LIBDIR) ``` -------------------------------- ### Defining Build Targets with Copy Rule Source: https://waf.io/apidocs/tutorial Illustrates how to define build targets in Waf using the 'cp' rule for copying files. It shows creating a target 'foo.txt' from 'wscript' and then 'bar.txt' from 'foo.txt'. ```python def build(bld): tg = bld(rule='cp ${SRC} ${TGT}', source='wscript', target='foo.txt') bld(rule='cp ${SRC} ${TGT}', source='foo.txt', target='bar.txt') ``` -------------------------------- ### Initial Qt Configuration Logic Source: https://waf.io/apidocs/_modules/waflib/Tools/qt5 This Python code snippet sets up initial variables for Qt configuration, including determining whether to use Qt6 or Qt5 based on the `want_qt6` flag. It also includes logic to handle potential missing XML support, which can lead to incomplete RCC dependencies, and defines a basic C++ fragment for testing compilation. ```Python if self.want_qt6: self.qt_vars = Utils.to_list(getattr(self, 'qt6_vars', [])) else: self.qt_vars = Utils.to_list(getattr(self, 'qt5_vars', [])) self.find_qt5_binaries() self.set_qt5_libs_dir() self.set_qt5_libs_to_check() sself.set_qt5_defines() sself.find_qt5_libraries() sself.add_qt5_rpath() sself.simplify_qt5_libs() # warn about this during the configuration too if not has_xml: Logs.error('No xml.sax support was found, rcc dependencies will be incomplete!') feature = 'qt6' if self.want_qt6 else 'qt5' # Qt5 may be compiled with '-reduce-relocations' which requires dependent programs to have -fPIE or -fPIC? frag = '#include \nint main(int argc, char **argv) {QMap m;return m.keys().size();}\n' uses = 'QT6CORE' if self.want_qt6 else 'QT5CORE' ``` -------------------------------- ### Process Installation Task (Waf) Source: https://waf.io/apidocs/_modules/waflib/Build This function is a Waf feature that processes an installation task. It's designed to be called before other processing methods and internally uses `add_install_task` to create the actual installation task. ```Python @TaskGen.feature('install_task') @TaskGen.before_method('process_rule', 'process_source') def process_install_task(self): """Creates the installation task for the current task generator; uses :py:func:`waflib.Build.add_install_task` internally.""" self.add_install_task(**self.__dict__) ``` -------------------------------- ### Install File As Task Generator (Waf) Source: https://waf.io/apidocs/_modules/waflib/Build Generates a task to install a file to a specified destination with a potentially different name. This is useful for renaming files during installation. The task can be postponed or executed immediately. ```Python def install_as(self, dest, srcfile, **kw): """ Creates a task generator to install a file on the system with a different name:: def build(bld): bld.install_as('${PREFIX}/bin', 'myapp', chmod=Utils.O755) :param dest: destination file :type dest: :py:class:`waflib.Node.Node` or string (absolute path) :param srcfile: input file :type srcfile: string or :py:class:`waflib.Node.Node` :param cwd: parent node for searching srcfile, when srcfile is not an instance of :py:class:`waflib.Node.Node` :type cwd: :py:class:`waflib.Node.Node` :param env: configuration set for performing substitutions in dest :type env: :py:class:`waflib.ConfigSet.ConfigSet` :param postpone: execute the task immediately to perform the installation (False by default) :type postpone: bool """ assert(dest) tg = self(features='install_task', install_to=dest, install_from=srcfile, **kw) tg.dest = tg.install_to tg.type = 'install_as' if not kw.get('postpone', True): tg.post() return tg ``` -------------------------------- ### Install Files Task Generator (Waf) Source: https://waf.io/apidocs/_modules/waflib/Build Generates a task to install files to a specified destination. It handles the installation process, including setting permissions and managing the source files. The task can be postponed or executed immediately. ```Python def install_files(self, dest, files, **kw): """ Creates a task generator to install files on the system:: def build(bld): bld.install_files('${PREFIX}/bin', ['myapp.py']) :param dest: destination file :type dest: :py:class:`waflib.Node.Node` or string (absolute path) :param files: files to install :type files: list of strings or :py:class:`waflib.Node.Node` :param cwd: parent node for searching files, when files are not instances of :py:class:`waflib.Node.Node` :type cwd: :py:class:`waflib.Node.Node` :param env: configuration set for performing substitutions in dest :type env: :py:class:`waflib.ConfigSet.ConfigSet` :param postpone: execute the task immediately to perform the installation (False by default) :type postpone: bool """ assert(dest) tg = self(features='install_task', install_to=dest, install_from=files, **kw) tg.dest = tg.install_to tg.type = 'install_files' if not kw.get('postpone', True): tg.post() return tg ``` -------------------------------- ### Waf: Build Install Task Processing Source: https://waf.io/apidocs/genindex Processes installation tasks within the build system. ```Python waflib.Build.process_install_task() ``` -------------------------------- ### Waf Entry Point Source: https://waf.io/apidocs/Scripting The main entry point for all Waf executions. It initializes the build process by setting the current directory, version, and Waf directory. ```python waflib.Scripting.waf_entry_point(_current_directory_ , _version_ , _wafdir_) ``` -------------------------------- ### Configure Qt5 Build Source: https://waf.io/apidocs/_modules/waflib/Tools/qt5 This snippet shows how to load the 'compiler_cxx' and 'qt5' tools in Waf's options and configure functions. It's the initial step for setting up a project that uses Qt5. ```Python def options(opt): opt.load('compiler_cxx qt5') def configure(conf): conf.load('compiler_cxx qt5') ``` -------------------------------- ### Handle DLL Import Libraries on Windows (Waf) Source: https://waf.io/apidocs/_modules/waflib/Tools/ccroot This Python function handles the creation and installation of import libraries for DLLs on Windows-like systems. It generates a '.dll.a' file, ensures it's installed, and links it appropriately. It also manages the installation of definition files if provided. ```Python val = env['%s_%s' % (var, x)] if val: app(var, val) # ============ the code above must not know anything about import libs ========== [docs]@feature('cshlib', 'cxxshlib', 'fcshlib') @after_method('apply_link') def apply_implib(self): """ Handle dlls and their import libs on Windows-like systems. A ``.dll.a`` file called *import library* is generated. It must be installed as it is required for linking the library. """ if not self.env.DEST_BINFMT == 'pe': return dll = self.link_task.outputs[0] if isinstance(self.target, Node.Node): name = self.target.name else: name = os.path.split(self.target)[1] implib = self.env.implib_PATTERN % name implib = dll.parent.find_or_declare(implib) self.env.append_value('LINKFLAGS', self.env.IMPLIB_ST % implib.bldpath()) self.link_task.outputs.append(implib) if getattr(self, 'defs', None) and self.env.DEST_BINFMT == 'pe': node = self.path.find_resource(self.defs) if not node: raise Errors.WafError('invalid def file %r' % self.defs) if self.env.def_PATTERN: self.env.append_value('LINKFLAGS', self.env.def_PATTERN % node.path_from(self.get_cwd())) self.link_task.dep_nodes.append(node) else: # gcc for windows takes *.def file as input without any special flag self.link_task.inputs.append(node) # where to put the import library if getattr(self, 'install_task', None): try: # user has given a specific installation path for the import library inst_to = self.install_path_implib except AttributeError: try: # user has given an installation path for the main library, put the import library in it inst_to = self.install_path except AttributeError: # else, put the library in BINDIR and the import library in LIBDIR inst_to = '${IMPLIBDIR}' self.install_task.install_to = '${BINDIR}' if not self.env.IMPLIBDIR: self.env.IMPLIBDIR = self.env.LIBDIR self.implib_install_task = self.add_install_files(install_to=inst_to, install_from=implib, chmod=self.link_task.chmod, task=self.link_task) ``` -------------------------------- ### Waflib Build Installation Path Retrieval Source: https://waf.io/apidocs/genindex This snippet retrieves the installation path for build artifacts in Waflib. ```Python get_install_path() ``` -------------------------------- ### Retrieve Install Path in Waflib Source: https://waf.io/apidocs/genindex This snippet retrieves the installation path for files within the Waflib build system. ```Python get_install_path() ``` -------------------------------- ### Gather VSWhere Versions Source: https://waf.io/apidocs/_sources/confmap Uses `vswhere` to find installed Visual Studio versions. A modern method for detecting Visual Studio installations. ```python waflib.Tools.msvc.gather_vswhere_versions ``` -------------------------------- ### Execute Task Immediately Source: https://waf.io/apidocs/_modules/waflib/Build Attempts to execute the installation task immediately by checking its runnable status. If the status indicates the task is ready to run or should be skipped, it proceeds with the `run` method and marks the task as successful. ```Python def run_now(self): """ Try executing the installation task right now :raises: :py:class:`waflib.Errors.TaskNotReady` """ status = self.runnable_status() if status not in (Task.RUN_ME, Task.SKIP_ME): raise Errors.TaskNotReady('Could not process %r: status %r' % (self, status)) self.run() self.hasrun = Task.SUCCESS ``` -------------------------------- ### Gather Intel Fortran Compiler Versions Source: https://waf.io/apidocs/_sources/confmap Retrieves installed Intel Fortran compiler versions. Helps in identifying available IFORT installations. ```python waflib.Tools.ifort.gather_ifort_versions ```