Example #1
0
def parse_options():
	"""
	Parse the command-line options and initialize the logging system.
	Called by :py:func:`waflib.Scripting.waf_entry_point` during the initialization.
	"""
	Context.create_context('options').execute()

	for var in Options.envvars:
		(name, value) = var.split('=', 1)
		os.environ[name.strip()] = value

	if not Options.commands:
		Options.commands = [default_cmd]
	Options.commands = [x for x in Options.commands if x != 'options'] # issue 1076

	# process some internal Waf options
	Logs.verbose = Options.options.verbose
	#Logs.init_log()

	if Options.options.zones:
		Logs.zones = Options.options.zones.split(',')
		if not Logs.verbose:
			Logs.verbose = 1
	elif Logs.verbose > 0:
		Logs.zones = ['runner']

	if Logs.verbose > 2:
		Logs.zones = ['*']
Example #2
0
def start(cwd, version, wafdir):
	# this is the entry point of our small build system

	Logs.init_log()
	Context.waf_dir = wafdir
	Context.out_dir = Context.top_dir = Context.run_dir = cwd
	Context.g_module = Context.load_module(cwd + os.sep + 'wscript')
	Context.g_module.configure = configure
	Context.g_module.root_path = cwd
	Context.Context.recurse = recurse_rep

	Context.g_module.top = Context.g_module.out = '.' # no build directory

	# just parse the options and execute a build
	Options.OptionsContext().execute()

	conf = Context.create_context('configure')
	conf.options = Options.options
	conf.execute()

	bld = Context.create_context('build')
	bld.env = conf.env
	bld.options = Options.options
	bld.environ = os.environ
	bld.execute()
def parse_options():
	"""
	Parse the command-line options and initialize the logging system.
	Called by :py:func:`waflib.Scripting.waf_entry_point` during the initialization.
	"""
	Context.create_context('options').execute()

	if not Options.commands:
		Options.commands = [default_cmd]
	Options.commands = [x for x in Options.commands if x != 'options'] # issue 1076

	# process some internal Waf options
	Logs.verbose = Options.options.verbose
	Logs.init_log()

	if Options.options.zones:
		Logs.zones = Options.options.zones.split(',')
		if not Logs.verbose:
			Logs.verbose = 1
	elif Logs.verbose > 0:
		Logs.zones = ['runner']

	if Logs.verbose > 2:
		Logs.zones = ['*']
		
	# Force console mode for SSH connections
	if getattr(Options.options, 'console_mode', None):
		if os.environ.get('SSH_CLIENT') != None or os.environ.get('SSH_TTY') != None:
			Logs.info("[INFO] - SSH Connection detected. Forcing 'console_mode'")
			Options.options.console_mode = str(True)
def parse_options():
	Context.create_context('options').execute()
	if not Options.commands:
		Options.commands=[default_cmd]
	Logs.verbose=Options.options.verbose
	Logs.init_log()
	if Options.options.zones:
		Logs.zones=Options.options.zones.split(',')
		if not Logs.verbose:
			Logs.verbose=1
	elif Logs.verbose>0:
		Logs.zones=['runner']
	if Logs.verbose>2:
		Logs.zones=['*']
Example #5
0
def download_tool(tool,force=False,ctx=None):
	for x in Utils.to_list(Context.remote_repo):
		for sub in Utils.to_list(Context.remote_locs):
			url='/'.join((x,sub,tool+'.py'))
			try:
				web=urlopen(url)
				try:
					if web.getcode()!=200:
						continue
				except AttributeError:
					pass
			except Exception:
				continue
			else:
				tmp=ctx.root.make_node(os.sep.join((Context.waf_dir,'waflib','extras',tool+'.py')))
				tmp.write(web.read(),'wb')
				Logs.warn('Downloaded %s from %s'%(tool,url))
				download_check(tmp)
				try:
					module=Context.load_tool(tool)
				except Exception:
					Logs.warn('The tool %s from %s is unusable'%(tool,url))
					try:
						tmp.delete()
					except Exception:
						pass
					continue
				return module
	raise Errors.WafError('Could not load the Waf tool')
Example #6
0
def download_tool(tool, force=False):
	"""downloads a tool from the waf repository"""
	for x in Utils.to_list(Context.remote_repo):
		for sub in Utils.to_list(Context.remote_locs):
			url = '/'.join((x, sub, tool + '.py'))
			try:
				web = urlopen(url)
				if web.getcode() != 200:
					continue
			except Exception as e:
				# on python3 urlopen throws an exception
				continue
			else:
				tmp = self.root.make_node(os.sep.join((Context.waf_dir, 'waflib', 'extras', tool + '.py')))
				tmp.write(web.read())
				Logs.warn('downloaded %s from %s' % (tool, url))
				download_check(tmp)
				try:
					module = Context.load_tool(tool)
				except:
					Logs.warn('module %s from %s is unusable' % (tool, url))
					try:
						tmp.delete()
					except:
						pass
					continue
				return module
		else:
				break
		raise Errors.WafError('Could not load the Waf tool')
Example #7
0
def download_tool(tool, force=False, ctx=None):
	"""
	Download a Waf tool from the remote repository defined in :py:const:`waflib.Context.remote_repo`::

		$ waf configure --download
	"""
	for x in Utils.to_list(Context.remote_repo):
		for sub in Utils.to_list(Context.remote_locs):
			url = '/'.join((x, sub, tool + '.py'))
			try:
				web = urlopen(url)
				if web.getcode() != 200:
					continue
			except Exception as e:
				# on python3 urlopen throws an exception
				continue
			else:
				tmp = ctx.root.make_node(os.sep.join((Context.waf_dir, 'waflib', 'extras', tool + '.py')))
				tmp.write(web.read())
				Logs.warn('Downloaded %s from %s' % (tool, url))
				download_check(tmp)
				try:
					module = Context.load_tool(tool)
				except:
					Logs.warn('The tool %s from %s is unusable' % (tool, url))
					try:
						tmp.delete()
					except:
						pass
					continue
				return module
	raise Errors.WafError('Could not load the Waf tool')
Example #8
0
def set_main_module(file_path):
	"""
	Read the main wscript file into :py:const:`waflib.Context.Context.g_module` and
	bind default functions such as ``init``, ``dist``, ``distclean`` if not defined.
	Called by :py:func:`waflib.Scripting.waf_entry_point` during the initialization.

	:param file_path: absolute path representing the top-level wscript file
	:type file_path: string
	"""
	Context.g_module = Context.load_module(file_path)
	Context.g_module.root_path = file_path

	# note: to register the module globally, use the following:
	# sys.modules['wscript_main'] = g_module

	def set_def(obj):
		name = obj.__name__
		if not name in Context.g_module.__dict__:
			setattr(Context.g_module, name, obj)
	for k in (update, dist, distclean, distcheck):
		set_def(k)
	# add dummy init and shutdown functions if they're not defined
	if not 'init' in Context.g_module.__dict__:
		Context.g_module.init = Utils.nada
	if not 'shutdown' in Context.g_module.__dict__:
		Context.g_module.shutdown = Utils.nada
	if not 'options' in Context.g_module.__dict__:
		Context.g_module.options = Utils.nada
def build(bld):
	subdirs = getattr(bld, 'subdirs', None)

	if subdirs:
		bld.recurse(subdirs)
		return

	maxdepth = getattr(Context.g_module, 'maxdepth', 1)
	subdirs = [ x.parent.nice_path() for x in bld.path.ant_glob('**/wscript_build', maxdepth=maxdepth ) ]
	what = Options.options.variant or ''
	variants = what.split(',')

	success = False
	for opt in variants:
		for variant in bld.env.variants:
			if opt not in variant:
				continue

			ctx = Context.create_context(bld.cmd)
			ctx.cmd = bld.cmd
			ctx.fun = 'build'
			ctx.subdirs = subdirs
			ctx.options = Options.options
			ctx.variant = variant
			ctx.execute()
			success = True

	if not success:
		raise Errors.WafError('"%s" is not a supported variant' % what)

	# Suppress missing target warnings
	bld.targets = '*'
Example #10
0
	def load(self,input,tooldir=None,funs=None,with_sys_path=True,cache=False):
		tools=Utils.to_list(input)
		if tooldir:tooldir=Utils.to_list(tooldir)
		for tool in tools:
			if cache:
				mag=(tool,id(self.env),tooldir,funs)
				if mag in self.tool_cache:
					self.to_log('(tool %s is already loaded, skipping)'%tool)
					continue
				self.tool_cache.append(mag)
			module=None
			try:
				module=Context.load_tool(tool,tooldir,ctx=self,with_sys_path=with_sys_path)
			except ImportError as e:
				self.fatal('Could not load the Waf tool %r from %r\n%s'%(tool,sys.path,e))
			except Exception as e:
				self.to_log('imp %r (%r & %r)'%(tool,tooldir,funs))
				self.to_log(Utils.ex_stack())
				raise
			if funs is not None:
				self.eval_rules(funs)
			else:
				func=getattr(module,'configure',None)
				if func:
					if type(func)is type(Utils.readf):func(self)
					else:self.eval_rules(func)
			self.tools.append({'tool':tool,'tooldir':tooldir,'funs':funs})
Example #11
0
    def execute(self):
        # first we execute the build
	bld = Context.create_context("build")
	bld.options = Options.options # provided for convenience
	bld.cmd = "build"
	bld.execute()
        _doxygen(bld)
Example #12
0
def run_command(cmd_name):
	ctx=Context.create_context(cmd_name)
	ctx.log_timer=Utils.Timer()
	ctx.options=Options.options
	ctx.cmd=cmd_name
	ctx.execute()
	return ctx
Example #13
0
	def load(self,input,tooldir=None,funs=None,download=True):
		tools=Utils.to_list(input)
		if tooldir:tooldir=Utils.to_list(tooldir)
		for tool in tools:
			mag=(tool,id(self.env),funs)
			if mag in self.tool_cache:
				self.to_log('(tool %s is already loaded, skipping)'%tool)
				continue
			self.tool_cache.append(mag)
			module=None
			try:
				module=Context.load_tool(tool,tooldir)
			except ImportError as e:
				if Options.options.download:
					module=download_tool(tool,ctx=self)
					if not module:
						self.fatal('Could not load the Waf tool %r or download a suitable replacement from the repository (sys.path %r)\n%s'%(tool,sys.path,e))
				else:
					self.fatal('Could not load the Waf tool %r from %r (try the --download option?):\n%s'%(tool,sys.path,e))
			except Exception as e:
				self.to_log('imp %r (%r & %r)'%(tool,tooldir,funs))
				self.to_log(Utils.ex_stack())
				raise
			if funs is not None:
				self.eval_rules(funs)
			else:
				func=getattr(module,'configure',None)
				if func:
					if type(func)is type(Utils.readf):func(self)
					else:self.eval_rules(func)
			self.tools.append({'tool':tool,'tooldir':tooldir,'funs':funs})
Example #14
0
 def load(self, input, tooldir=None, funs=None, download=True):
     tools = Utils.to_list(input)
     if tooldir:
         tooldir = Utils.to_list(tooldir)
     for tool in tools:
         mag = (tool, id(self.env), funs)
         if mag in self.tool_cache:
             self.to_log("(tool %s is already loaded, skipping)" % tool)
             continue
         self.tool_cache.append(mag)
         module = None
         try:
             module = Context.load_tool(tool, tooldir)
         except ImportError, e:
             if Options.options.download:
                 module = download_tool(tool, ctx=self)
                 if not module:
                     self.fatal(
                         "Could not load the Waf tool %r or download a suitable replacement from the repository (sys.path %r)\n%s"
                         % (tool, sys.path, e)
                     )
             else:
                 self.fatal(
                     "Could not load the Waf tool %r from %r (try the --download option?):\n%s" % (tool, sys.path, e)
                 )
         except Exception, e:
             self.to_log("imp %r (%r & %r)" % (tool, tooldir, funs))
             self.to_log(Utils.ex_stack())
             raise
Example #15
0
def run_command(cmd_name):
	"""run a single command (usually given on the command line)"""
	ctx = Context.create_context(cmd_name)
	ctx.options = Options.options # provided for convenience
	ctx.cmd = cmd_name
	ctx.execute()
	return ctx
Example #16
0
File: Build.py Project: zsx/waf
	def setup(self, tool, tooldir=None, funs=None):
		"""Loads the waf tools declared in the configuration section"""
		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)
Example #17
0
def parse_options():
	Context.create_context('options').execute()
	for var in Options.envvars:
		(name,value)=var.split('=',1)
		os.environ[name.strip()]=value
	if not Options.commands:
		Options.commands=[default_cmd]
	Options.commands=[x for x in Options.commands if x!='options']
	Logs.verbose=Options.options.verbose
	if Options.options.zones:
		Logs.zones=Options.options.zones.split(',')
		if not Logs.verbose:
			Logs.verbose=1
	elif Logs.verbose>0:
		Logs.zones=['runner']
	if Logs.verbose>2:
		Logs.zones=['*']
Example #18
0
 def setup(self, tool, tooldir=None, funs=None):
     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)
Example #19
0
    def execute(self):

        # first we execute the build
	bld = Context.create_context("build")
	bld.options = Options.options # provided for convenience
	bld.cmd = "build"
	bld.execute()

        wutils.bld = bld
        wutils.run_python_program("test.py -n -c core", bld.env)
Example #20
0
def load_tool(tool, tooldir=None, ctx=None, with_sys_path=True):
	try:
		module = Context.load_tool_default(tool, tooldir, ctx, with_sys_path)
	except ImportError as e:
		if Options.options.download:
			module = download_tool(tool, ctx=ctx)
			if not module:
				ctx.fatal('Could not load the Waf tool %r or download a suitable replacement from the repository (sys.path %r)\n%s' % (tool, sys.path, e))
		else:
			ctx.fatal('Could not load the Waf tool %r from %r (try the --download option?):\n%s' % (tool, sys.path, e))
	return module
Example #21
0
def parse_options():
	"""
	Parses the command-line options and initialize the logging system.
	Called by :py:func:`waflib.Scripting.waf_entry_point` during the initialization.
	"""
	ctx = Context.create_context('options')
	ctx.execute()
	if not Options.commands:
		Options.commands.append(default_cmd)
	if Options.options.whelp:
		ctx.parser.print_help()
		sys.exit(0)
Example #22
0
def subdir(path) :
    currpackages = Package.packages()
    currglobal = Package.globalpackage
    Package.initPackages()

    def src(p) :
        return os.path.join(os.path.abspath(path), p)

    mpath = os.path.join(os.path.abspath(path), 'wscript')
    oldsrc = Context.wscript_vars.get('src', None)
    Context.wscript_vars['src'] = src
    #fcode = self.root.find_node(mpath).read('rU')
    #exec_dict = dict(Context.wscript_vars)
    #exec(compile(fcode, mpath, 'exec'), exec_dict)
    Context.load_module(mpath)

    respackages = Package.packages()
    Package.packdict[path] = respackages
    Package.initPackages(currpackages, currglobal)
    Context.wscript_vars['src'] = oldsrc
    return respackages
Example #23
0
    def load(self, input, tooldir=None, funs=None, download=True):
        """
        Load Waf tools, which will be imported whenever a build is started.

        :param input: waf tools to import
        :type input: list of string
        :param tooldir: paths for the imports
        :type tooldir: list of string
        :param funs: functions to execute from the waf tools
        :type funs: list of string
        :param download: whether to download the tool from the waf repository
        :type download: bool
        """

        tools = Utils.to_list(input)
        if tooldir:
            tooldir = Utils.to_list(tooldir)
        for tool in tools:
            # avoid loading the same tool more than once with the same functions
            # used by composite projects

            mag = (tool, id(self.env), funs)
            if mag in self.tool_cache:
                self.to_log('(tool %s is already loaded, skipping)' % tool)
                continue
            self.tool_cache.append(mag)

            module = None
            try:
                module = Context.load_tool(tool, tooldir)
            except ImportError as e:
                if Options.options.download:
                    module = download_tool(tool, ctx=self)
                    if not module:
                        self.fatal('Could not load the Waf tool %r or download a suitable replacement from the repository (sys.path %r)\n%s' % (tool, sys.path, e))
                else:
                    self.fatal('Could not load the Waf tool %r from %r (try the --download option?):\n%s' % (tool, sys.path, e))
            except Exception as e:
                self.to_log('imp %r (%r & %r)' % (tool, tooldir, funs))
                self.to_log(Utils.ex_stack())
                raise

            if funs is not None:
                self.eval_rules(funs)
            else:
                func = getattr(module, 'configure', None)
                if func:
                    if type(func) is type(Utils.readf):
                        func(self)
                    else:
                        self.eval_rules(func)

            self.tools.append({'tool': tool, 'tooldir': tooldir, 'funs': funs})
Example #24
0
def run_build(self,*k,**kw):
	lst=[str(v)for(p,v)in kw.items()if p!='env']
	h=Utils.h_list(lst)
	dir=self.bldnode.abspath()+os.sep+(not Utils.is_win32 and'.'or'')+'conf_check_'+Utils.to_hex(h)
	try:
		os.makedirs(dir)
	except OSError:
		pass
	try:
		os.stat(dir)
	except OSError:
		self.fatal('cannot use the configuration test folder %r'%dir)
	cachemode=getattr(Options.options,'confcache',None)
	if cachemode==1:
		try:
			proj=ConfigSet.ConfigSet(os.path.join(dir,'cache_run_build'))
		except EnvironmentError:
			pass
		else:
			ret=proj['cache_run_build']
			if isinstance(ret,str)and ret.startswith('Test does not build'):
				self.fatal(ret)
			return ret
	bdir=os.path.join(dir,'testbuild')
	if not os.path.exists(bdir):
		os.makedirs(bdir)
	self.test_bld=bld=Context.create_context('build',top_dir=dir,out_dir=bdir)
	bld.init_dirs()
	bld.progress_bar=0
	bld.targets='*'
	bld.logger=self.logger
	bld.all_envs.update(self.all_envs)
	bld.env=kw['env']
	bld.kw=kw
	bld.conf=self
	kw['build_fun'](bld)
	ret=-1
	try:
		try:
			bld.compile()
		except Errors.WafError:
			ret='Test does not build: %s'%Utils.ex_stack()
			self.fatal(ret)
		else:
			ret=getattr(bld,'retval',0)
	finally:
		if cachemode==1:
			proj=ConfigSet.ConfigSet()
			proj['cache_run_build']=ret
			proj.store(os.path.join(dir,'cache_run_build'))
		else:
			shutil.rmtree(dir)
	return ret
Example #25
0
def run_command(cmd_name):
	"""
	Execute a single command. Called by :py:func:`waflib.Scripting.run_commands`.

	:param cmd_name: command to execute, like ``build``
	:type cmd_name: string
	"""
	ctx = Context.create_context(cmd_name)
	ctx.options = Options.options # provided for convenience
	ctx.cmd = cmd_name
	ctx.execute()
	return ctx
Example #26
0
def start(cwd, version, wafdir):
	# this is the entry point of our small build system
	# no script file here
	Logs.init_log()
	Context.waf_dir = wafdir
	Context.out_dir = Context.top_dir = Context.run_dir = cwd
	Context.g_module = imp.new_module('wscript')
	Context.g_module.root_path = cwd
	Context.Context.recurse = recurse_rep

	Context.g_module.configure = configure
	Context.g_module.build = build
	Context.g_module.options = options
	Context.g_module.top = Context.g_module.out = '.'

	Options.OptionsContext().execute()

	do_config = 'configure' in sys.argv
	try:
		os.stat(cwd + os.sep + 'c4che')
	except:
		do_config = True
	if do_config:
		Context.create_context('configure').execute()

	if 'clean' in sys.argv:
		Context.create_context('clean').execute()

	if 'build' in sys.argv:
		Context.create_context('build').execute()
Example #27
0
def start(cwd, version, wafdir):
	# simple example, the file main.c is hard-coded
	try:
		os.stat(cwd + os.sep + 'cbit')
	except:
		print('call from a folder containing a file named "cbit"')
		sys.exit(1)

	Logs.init_log()
	Context.waf_dir = wafdir
	Context.top_dir = Context.run_dir = cwd
	Context.out_dir = os.path.join(cwd, 'build')
	Context.g_module = imp.new_module('wscript')
	Context.g_module.root_path = os.path.join(cwd, 'cbit')
	Context.Context.recurse = recurse_rep

	# this is a fake module, which looks like a standard wscript file
	Context.g_module.options = options
	Context.g_module.configure = configure
	Context.g_module.build = build

	Options.OptionsContext().execute()

	do_config = 'configure' in sys.argv
	try:
		os.stat(cwd + os.sep + 'build')
	except:
		do_config = True
	if do_config:
		Context.create_context('configure').execute()

	if 'clean' in sys.argv:
		Context.create_context('clean').execute()
	if 'build' in sys.argv:
		Context.create_context('build').execute()
Example #28
0
def start(cwd, version, wafdir):
	# simple example, the file main.c is hard-coded
	try:
		os.stat(cwd + os.sep + 'bbit')
	except:
		print('call from a folder containing a file named "bbit"')
		sys.exit(1)

	Logs.init_log()
	Context.waf_dir = wafdir
	Context.top_dir = Context.run_dir = cwd
	Context.out_dir = os.path.join(cwd, 'build')
	Context.g_module = imp.new_module('wscript')
	Context.g_module.root_path = os.path.join(cwd, 'bbit')
	Context.Context.recurse = \
		lambda x, y: getattr(Context.g_module, x.cmd or x.fun, Utils.nada)(x)

	Context.g_module.configure = lambda ctx: ctx.load('g++')
	Context.g_module.build = lambda bld: bld.objects(source='main.c')

	Options.OptionsContext().execute()

	do_config = 'configure' in sys.argv
	try:
		os.stat(cwd + os.sep + 'build')
	except:
		do_config = True
	if do_config:
		Context.create_context('configure').execute()

	if 'clean' in sys.argv:
		Context.create_context('clean').execute()
	if 'build' in sys.argv:
		Context.create_context('build').execute()
Example #29
0
def start(cwd, version, wafdir):
    # this is the entry point of our small build system
    # no script file here
    Logs.init_log()
    Context.waf_dir = wafdir
    Context.out_dir = Context.top_dir = Context.run_dir = cwd
    Context.g_module = imp.new_module("wscript")
    Context.g_module.root_path = cwd
    Context.Context.recurse = recurse_rep

    Context.g_module.configure = configure
    Context.g_module.build = build
    Context.g_module.options = options
    Context.g_module.top = Context.g_module.out = "."

    Options.OptionsContext().execute()

    do_config = "configure" in sys.argv
    try:
        os.stat(cwd + os.sep + "c4che")
    except:
        do_config = True
    if do_config:
        Context.create_context("configure").execute()

    if "clean" in sys.argv:
        Context.create_context("clean").execute()

    if "build" in sys.argv:
        Context.create_context("build").execute()
Example #30
0
def parse_options():
	"""
	Parse the command-line options and initialize the logging system.
	Called by :py:func:`waflib.Scripting.waf_entry_point` during the initialization.
	"""
	Context.create_context('options').execute()

	if not Options.commands:
		Options.commands = [default_cmd]

	# process some internal Waf options
	Logs.verbose = Options.options.verbose
	Logs.init_log()

	if Options.options.zones:
		Logs.zones = Options.options.zones.split(',')
		if not Logs.verbose:
			Logs.verbose = 1
	elif Logs.verbose > 0:
		Logs.zones = ['runner']

	if Logs.verbose > 2:
		Logs.zones = ['*']
Example #31
0
def set_main_module(file_path):
    Context.g_module = Context.load_module(file_path)
    Context.g_module.root_path = file_path

    def set_def(obj):
        name = obj.__name__
        if not name in Context.g_module.__dict__:
            setattr(Context.g_module, name, obj)

    for k in (dist, distclean, distcheck):
        set_def(k)
    if not 'init' in Context.g_module.__dict__:
        Context.g_module.init = Utils.nada
    if not 'shutdown' in Context.g_module.__dict__:
        Context.g_module.shutdown = Utils.nada
    if not 'options' in Context.g_module.__dict__:
        Context.g_module.options = Utils.nada
def run_command(cmd_name):
	"""
	Execute a single command. Called by :py:func:`waflib.Scripting.run_commands`.

	:param cmd_name: command to execute, like ``build``
	:type cmd_name: string
	"""
	ctx = Context.create_context(cmd_name)
	ctx.log_timer = Utils.Timer()
	ctx.options = Options.options # provided for convenience
	ctx.cmd = cmd_name
	try:
		ctx.execute()
	finally:
		# Issue 1374
		ctx.finalize()
	return ctx
Example #33
0
	def load(self,input,tooldir=None,funs=None):
		tools=Utils.to_list(input)
		if tooldir:tooldir=Utils.to_list(tooldir)
		for tool in tools:
			mag=(tool,id(self.env),funs)
			if mag in self.tool_cache:
				self.to_log('(tool %s is already loaded, skipping)'%tool)
				continue
			self.tool_cache.append(mag)
			module=None
			try:
				module=Context.load_tool(tool,tooldir,ctx=self)
			except ImportError ,e:
				self.fatal('Could not load the Waf tool %r from %r\n%s'%(tool,sys.path,e))
			except Exception ,e:
				self.to_log('imp %r (%r & %r)'%(tool,tooldir,funs))
				self.to_log(Utils.ex_stack())
				raise
Example #34
0
    def load(self, input, tooldir=None, funs=None):
        """
		Load Waf tools, which will be imported whenever a build is started.

		:param input: waf tools to import
		:type input: list of string
		:param tooldir: paths for the imports
		:type tooldir: list of string
		:param funs: functions to execute from the waf tools
		:type funs: list of string
		"""

        tools = Utils.to_list(input)
        if tooldir: tooldir = Utils.to_list(tooldir)
        for tool in tools:
            # avoid loading the same tool more than once with the same functions
            # used by composite projects

            mag = (tool, id(self.env), funs)
            if mag in self.tool_cache:
                self.to_log('(tool %s is already loaded, skipping)' % tool)
                continue
            self.tool_cache.append(mag)

            module = None
            try:
                module = Context.load_tool(tool, tooldir, ctx=self)
            except ImportError as e:
                self.fatal('Could not load the Waf tool %r from %r\n%s' %
                           (tool, sys.path, e))
            except Exception as e:
                self.to_log('imp %r (%r & %r)' % (tool, tooldir, funs))
                self.to_log(Utils.ex_stack())
                raise

            if funs is not None:
                self.eval_rules(funs)
            else:
                func = getattr(module, 'configure', None)
                if func:
                    if type(func) is type(Utils.readf): func(self)
                    else: self.eval_rules(func)

            self.tools.append({'tool': tool, 'tooldir': tooldir, 'funs': funs})
Example #35
0
    def pre_recurse(self, node):
        wscript_module = Context.load_module(node.abspath())
        group_name = wscript_module.APPNAME
        self.stack.append(TestScope(self, group_name, self.defaults()))
        self.max_depth = max(self.max_depth, len(self.stack) - 1)

        bld_dir = node.get_bld().parent
        if bld_dir != self.path.get_bld():
            Logs.info('')

        self.original_dir = os.getcwd()
        Logs.info("Waf: Entering directory `%s'\n", bld_dir)
        os.chdir(str(bld_dir))

        if str(node.parent) == Context.top_dir:
            self.clear_coverage()

        self.log_good('=' * 10, 'Running %s tests', group_name)
        super(TestContext, self).pre_recurse(node)
def load_tool(tool, tooldir=None, ctx=None, with_sys_path=True):
    try:
        module = Context.load_tool_default(tool, tooldir, ctx, with_sys_path)
    except ImportError as e:
        if not ctx or not hasattr(Options.options, "download"):
            Logs.error(
                "Could not load %r during options phase (download unavailable at this point)"
                % tool)
            raise
        if Options.options.download:
            module = download_tool(tool, ctx=ctx)
            if not module:
                ctx.fatal(
                    f"Could not load the Waf tool {tool!r} or download a suitable replacement from the repository (sys.path {sys.path!r})\n{e}"
                )
        else:
            ctx.fatal(
                f"Could not load the Waf tool {tool!r} from {sys.path!r} (try the --download option?):\n{e}"
            )
    return module
Example #37
0
	def load(self,tool_list,tooldir=None,funs=None,with_sys_path=True,cache=False):
		tools=Utils.to_list(tool_list)
		if tooldir:
			tooldir=Utils.to_list(tooldir)
		for tool in tools:
			if cache:
				mag=(tool,id(self.env),tooldir,funs)
				if mag in self.tool_cache:
					self.to_log('(tool %s is already loaded, skipping)'%tool)
					continue
				self.tool_cache.append(mag)
			module=None
			try:
				module=Context.load_tool(tool,tooldir,ctx=self,with_sys_path=with_sys_path)
			except ImportError ,e:
				self.fatal('Could not load the Waf tool %r from %r\n%s'%(tool,getattr(e,'waf_sys_path',sys.path),e))
			except Exception ,e:
				self.to_log('imp %r (%r & %r)'%(tool,tooldir,funs))
				self.to_log(traceback.format_exc())
				raise
Example #38
0
def load_tool(tool, tooldir=None, ctx=None, with_sys_path=True):
    try:
        module = Context.load_tool_default(tool, tooldir, ctx, with_sys_path)
    except ImportError as e:
        if not ctx or not hasattr(Options.options, 'download'):
            Logs.error(
                'Could not load %r during options phase (download unavailable at this point)'
                % tool)
            raise
        if Options.options.download:
            module = download_tool(tool, ctx=ctx)
            if not module:
                ctx.fatal(
                    'Could not load the Waf tool %r or download a suitable replacement from the repository (sys.path %r)\n%s'
                    % (tool, sys.path, e))
        else:
            ctx.fatal(
                'Could not load the Waf tool %r from %r (try the --download option?):\n%s'
                % (tool, sys.path, e))
    return module
Example #39
0
    def recurse(self, folders, *args, **kwargs):
        if isinstance(folders, basestring):
            folders = [folders]
        for f in folders:
            self.pathstack.append(f)
            path = os.path.join(*self.pathstack)
            progress_report("Processing " + path)
            self.path = PathNode(path)
            if (os.path.isfile(path + '/wscript')):
                m = Context.load_module(path + '/wscript')

                def PathWrapper(p):
                    return p

                def SettingsWrapper(*k, **kw):
                    return (k, kw)

                m.Path = PathWrapper
                m.Settings = SettingsWrapper
                m.build(self)
            self.pathstack.pop()
Example #40
0
    def pre_recurse(self, node):
        wscript_module = Context.load_module(node.abspath())
        group_name = wscript_module.APPNAME
        self.stack.append(TestScope(self, group_name, self.defaults()))
        self.max_depth = max(self.max_depth, len(self.stack) - 1)

        bld_dir = node.get_bld().parent

        if hasattr(wscript_module, 'test'):
            self.original_dir = os.getcwd()
            Logs.info("Waf: Entering directory `%s'", bld_dir)
            os.chdir(str(bld_dir))

            parent_is_top = str(node.parent) == Context.top_dir
            if not self.env.NO_COVERAGE and parent_is_top:
                self.clear_coverage()

            Logs.info('')
            self.log_good('=' * 10, 'Running %s tests\n', group_name)

        super(TestContext, self).pre_recurse(node)
Example #41
0
 def load(self,
          tool_list,
          tooldir=None,
          funs=None,
          with_sys_path=True,
          cache=False):
     tools = Utils.to_list(tool_list)
     if tooldir:
         tooldir = Utils.to_list(tooldir)
     for tool in tools:
         if cache:
             mag = (tool, id(self.env), tooldir, funs)
             if mag in self.tool_cache:
                 self.to_log('(tool %s is already loaded, skipping)' % tool)
                 continue
             self.tool_cache.append(mag)
         module = None
         try:
             module = Context.load_tool(tool,
                                        tooldir,
                                        ctx=self,
                                        with_sys_path=with_sys_path)
         except ImportError as e:
             self.fatal('Could not load the Waf tool %r from %r\n%s' %
                        (tool, getattr(e, 'waf_sys_path', sys.path), e))
         except Exception as e:
             self.to_log('imp %r (%r & %r)' % (tool, tooldir, funs))
             self.to_log(traceback.format_exc())
             raise
         if funs is not None:
             self.eval_rules(funs)
         else:
             func = getattr(module, 'configure', None)
             if func:
                 if type(func) is type(Utils.readf):
                     func(self)
                 else:
                     self.eval_rules(func)
         self.tools.append({'tool': tool, 'tooldir': tooldir, 'funs': funs})
Example #42
0
	def setup(self, tool, tooldir=None, funs=None):
		"""
		Import waf tools, used to import those accessed 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)
Example #43
0
def download_tool(tool, force=False, ctx=None):
    """
	Download a Waf tool from the remote repository defined in :py:const:`waflib.extras.use_config.remote_repo`::

		$ waf configure --download
	"""
    for x in Utils.to_list(remote_repo):
        for sub in Utils.to_list(remote_locs):
            url = '/'.join((x, sub, tool + '.py'))
            try:
                web = urlopen(url)
                try:
                    if web.getcode() != 200:
                        continue
                except AttributeError:
                    pass
            except Exception:
                # on python3 urlopen throws an exception
                # python 2.3 does not have getcode and throws an exception to fail
                continue
            else:
                tmp = ctx.root.make_node(
                    os.sep.join(
                        (Context.waf_dir, 'waflib', 'extras', tool + '.py')))
                tmp.write(web.read(), 'wb')
                Logs.warn('Downloaded %s from %s', tool, url)
                download_check(tmp)
                try:
                    module = Context.load_tool(tool)
                except Exception:
                    Logs.warn('The tool %s from %s is unusable', tool, url)
                    try:
                        tmp.delete()
                    except Exception:
                        pass
                    continue
                return module

    raise Errors.WafError('Could not load the Waf tool')
Example #44
0
def daemon(ctx):
    """waf command: rebuild as soon as something changes"""
    bld = None
    while True:
        bld = Context.create_context('build')
        try:
            bld.options = Options.options
            bld.cmd = 'build'
            bld.execute()
        except ctx.errors.WafError as e:
            print(e)
        except KeyboardInterrupt:
            Utils.pprint('RED', 'interrupted')
            break

        try:
            x = ctx.state
        except AttributeError:
            setattr(ctx, 'state', DirWatch())
            x = ctx.state

        x.wait(bld)
Example #45
0
def run_command(cmd_name):
    """
	Execute a single command. Called by :py:func:`waflib.Scripting.run_commands`.

	:param cmd_name: command to execute, like ``build``
	:type cmd_name: string
	"""
    ctx = Context.create_context(cmd_name)
    ctx.log_timer = Utils.Timer()
    ctx.options = Options.options  # provided for convenience
    ctx.cmd = cmd_name
    try:
        ctx.execute()
    except AttributeError as e:
        t, v, tb = sys.exc_info()
        if str(v) == "'Context' object has no attribute 'add_group'":
            Logs.warn(
                '[WARN] Received invalid command "%s" - please check your command line'
                % cmd_name)
            ctx.skip_finish_message = True
        else:
            raise
    return ctx
Example #46
0
	def load(self,input,tooldir=None,funs=None,download=True):
		tools=Utils.to_list(input)
		if tooldir:tooldir=Utils.to_list(tooldir)
		for tool in tools:
			mag=(tool,id(self.env),funs)
			if mag in self.tool_cache:
				self.to_log('(tool %s is already loaded, skipping)'%tool)
				continue
			self.tool_cache.append(mag)
			module=None
			try:
				module=Context.load_tool(tool,tooldir)
			except ImportError ,e:
				if Options.options.download:
					module=download_tool(tool,ctx=self)
					if not module:
						self.fatal('Could not load the Waf tool %r or download a suitable replacement from the repository (sys.path %r)\n%s'%(tool,sys.path,e))
				else:
					self.fatal('Could not load the Waf tool %r from %r (try the --download option?):\n%s'%(tool,sys.path,e))
			except Exception ,e:
				self.to_log('imp %r (%r & %r)'%(tool,tooldir,funs))
				self.to_log(Utils.ex_stack())
				raise
Example #47
0
	def setup(self,tool,tooldir=None,funs=None):
		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)
def waf_entry_point(current_directory, version, wafdir):
	"""
	This is the main entry point, all Waf execution starts here.

	:param current_directory: absolute path representing the current directory
	:type current_directory: string
	:param version: version number
	:type version: string
	:param wafdir: absolute path representing the directory of the waf library
	:type wafdir: string
	"""

	Logs.init_log()

	if Context.WAFVERSION != version:
		Logs.error('Waf script %r and library %r do not match (directory %r)' % (version, Context.WAFVERSION, wafdir))
		sys.exit(1)

	if '--version' in sys.argv:
		Context.run_dir = current_directory
		ctx = Context.create_context('options')
		ctx.curdir = current_directory
		ctx.parse_args()
		sys.exit(0)

	if len(sys.argv) > 1:
		# os.path.join handles absolute paths in sys.argv[1] accordingly (it discards the previous ones)
		# if sys.argv[1] is not an absolute path, then it is relative to the current working directory
		potential_wscript = os.path.join(current_directory, sys.argv[1])
		# maybe check if the file is executable
		# perhaps extract 'wscript' as a constant
		if os.path.basename(potential_wscript) == 'wscript' and os.path.isfile(potential_wscript):
			# need to explicitly normalize the path, as it may contain extra '/.'
			# TODO abspath?
			current_directory = os.path.normpath(os.path.dirname(potential_wscript))
			sys.argv.pop(1)

	Context.waf_dir = wafdir
	Context.launch_dir = current_directory

	# if 'configure' is in the commands, do not search any further
	no_climb = os.environ.get('NOCLIMB', None)
	if not no_climb:
		for k in no_climb_commands:
			for y in sys.argv:
				if y.startswith(k):
					no_climb = True
					break

	# if --top is provided assume the build started in the top directory
	for i, x in enumerate(sys.argv):
		# WARNING: this modifies sys.argv
		if x.startswith('--top='):
			Context.run_dir = Context.top_dir = Utils.sane_path(x[6:])
			sys.argv[i] = '--top=' + Context.run_dir
		if x.startswith('--out='):
			Context.out_dir = Utils.sane_path(x[6:])
			sys.argv[i] = '--out=' + Context.out_dir

	# try to find a lock file (if the project was configured)
	# at the same time, store the first wscript file seen
	cur = current_directory
	while cur and not Context.top_dir:
		lst = os.listdir(cur)
		if Options.lockfile in lst:
			env = ConfigSet.ConfigSet()
			try:
				env.load(os.path.join(cur, Options.lockfile))
				ino = os.stat(cur)[stat.ST_INO]
			except Exception:
				pass
			else:
				# check if the folder was not moved
				for x in (env.run_dir, env.top_dir, env.out_dir):
					if Utils.is_win32:
						if cur == x:
							load = True
							break
					else:
						# if the filesystem features symlinks, compare the inode numbers
						try:
							ino2 = os.stat(x)[stat.ST_INO]
						except OSError:
							pass
						else:
							if ino == ino2:
								load = True
								break
				else:
					Logs.warn('invalid lock file in %s' % cur)
					load = False

				if load:
					Context.run_dir = env.run_dir
					Context.top_dir = env.top_dir
					Context.out_dir = env.out_dir
					break

		if not Context.run_dir:
			if Context.WSCRIPT_FILE in lst:
				Context.run_dir = cur

		next = os.path.dirname(cur)
		if next == cur:
			break
		cur = next

		if no_climb:
			break

	if not Context.run_dir:
		if '-h' in sys.argv or '--help' in sys.argv:
			Logs.warn('No wscript file found: the help message may be incomplete')
			Context.run_dir = current_directory
			ctx = Context.create_context('options')
			ctx.curdir = current_directory
			ctx.parse_args()
			sys.exit(0)
		Logs.error('Waf: Run from a directory containing a file named %r' % Context.WSCRIPT_FILE)
		sys.exit(1)

	try:
		os.chdir(Context.run_dir)
	except OSError:
		Logs.error('Waf: The folder %r is unreadable' % Context.run_dir)
		sys.exit(1)

	try:
		set_main_module(os.path.normpath(os.path.join(Context.run_dir, Context.WSCRIPT_FILE)))
	except Errors.WafError as e:
		Logs.pprint('RED', e.verbose_msg)
		Logs.error(str(e))
		sys.exit(1)
	except Exception as e:
		Logs.error('Waf: The wscript in %r is unreadable' % Context.run_dir, e)
		traceback.print_exc(file=sys.stdout)
		sys.exit(2)

	"""
	import cProfile, pstats
	cProfile.runctx("from waflib import Scripting; Scripting.run_commands()", {}, {}, 'profi.txt')
	p = pstats.Stats('profi.txt')
	p.sort_stats('time').print_stats(75) # or 'cumulative'
	"""
	try:
		run_commands()
	except Errors.WafError as e:
		if Logs.verbose > 1:
			Logs.pprint('RED', e.verbose_msg)
		Logs.error(e.msg)
		sys.exit(1)
	except SystemExit:
		raise
	except Exception as e:
		traceback.print_exc(file=sys.stdout)
		sys.exit(2)
	except KeyboardInterrupt:
		Logs.pprint('RED', 'Interrupted')
		sys.exit(68)
Example #49
0
def waf_entry_point(current_directory, version, wafdir):
    Logs.init_log()
    if Context.WAFVERSION != version:
        Logs.error('Waf script %r and library %r do not match (directory %r)',
                   version, Context.WAFVERSION, wafdir)
        sys.exit(1)
    if '--version' in sys.argv:
        Context.run_dir = current_directory
        ctx = Context.create_context('options')
        ctx.curdir = current_directory
        ctx.parse_args()
        sys.exit(0)
    if len(sys.argv) > 1:
        potential_wscript = os.path.join(current_directory, sys.argv[1])
        if os.path.basename(potential_wscript) == 'wscript' and os.path.isfile(
                potential_wscript):
            current_directory = os.path.normpath(
                os.path.dirname(potential_wscript))
            sys.argv.pop(1)
    Context.waf_dir = wafdir
    Context.launch_dir = current_directory
    no_climb = os.environ.get('NOCLIMB')
    if not no_climb:
        for k in no_climb_commands:
            for y in sys.argv:
                if y.startswith(k):
                    no_climb = True
                    break
    for i, x in enumerate(sys.argv):
        if x.startswith('--top='):
            Context.run_dir = Context.top_dir = Utils.sane_path(x[6:])
            sys.argv[i] = '--top=' + Context.run_dir
        if x.startswith('--out='):
            Context.out_dir = Utils.sane_path(x[6:])
            sys.argv[i] = '--out=' + Context.out_dir
    cur = current_directory
    while cur and not Context.top_dir:
        try:
            lst = os.listdir(cur)
        except OSError:
            lst = []
            Logs.error('Directory %r is unreadable!', cur)
        if Options.lockfile in lst:
            env = ConfigSet.ConfigSet()
            try:
                env.load(os.path.join(cur, Options.lockfile))
                ino = os.stat(cur)[stat.ST_INO]
            except EnvironmentError:
                pass
            else:
                for x in (env.run_dir, env.top_dir, env.out_dir):
                    if Utils.is_win32:
                        if cur == x:
                            load = True
                            break
                    else:
                        try:
                            ino2 = os.stat(x)[stat.ST_INO]
                        except OSError:
                            pass
                        else:
                            if ino == ino2:
                                load = True
                                break
                else:
                    Logs.warn('invalid lock file in %s', cur)
                    load = False
                if load:
                    Context.run_dir = env.run_dir
                    Context.top_dir = env.top_dir
                    Context.out_dir = env.out_dir
                    break
        if not Context.run_dir:
            if Context.WSCRIPT_FILE in lst:
                Context.run_dir = cur
        next = os.path.dirname(cur)
        if next == cur:
            break
        cur = next
        if no_climb:
            break
    if not Context.run_dir:
        if '-h' in sys.argv or '--help' in sys.argv:
            Logs.warn(
                'No wscript file found: the help message may be incomplete')
            Context.run_dir = current_directory
            ctx = Context.create_context('options')
            ctx.curdir = current_directory
            ctx.parse_args()
            sys.exit(0)
        Logs.error('Waf: Run from a directory containing a file named %r',
                   Context.WSCRIPT_FILE)
        sys.exit(1)
    try:
        os.chdir(Context.run_dir)
    except OSError:
        Logs.error('Waf: The folder %r is unreadable', Context.run_dir)
        sys.exit(1)
    try:
        set_main_module(
            os.path.normpath(
                os.path.join(Context.run_dir, Context.WSCRIPT_FILE)))
    except Errors.WafError, e:
        Logs.pprint('RED', e.verbose_msg)
        Logs.error(str(e))
        sys.exit(1)
Example #50
0
def waf_entry_point(current_directory, version, wafdir):
	"""
	This is the main entry point, all Waf execution starts here.

	:param current_directory: absolute path representing the current directory
	:type current_directory: string
	:param version: version number
	:type version: string
	:param wafdir: absolute path representing the directory of the waf library
	:type wafdir: string
	"""
	Logs.init_log()

	if Context.WAFVERSION != version:
		Logs.error('Waf script %r and library %r do not match (directory %r)', version, Context.WAFVERSION, wafdir)
		sys.exit(1)

	# Store current directory before any chdir
	Context.waf_dir = wafdir
	Context.run_dir = Context.launch_dir = current_directory
	start_dir = current_directory
	no_climb = os.environ.get('NOCLIMB')

	if len(sys.argv) > 1:
		# os.path.join handles absolute paths
		# if sys.argv[1] is not an absolute path, then it is relative to the current working directory
		potential_wscript = os.path.join(current_directory, sys.argv[1])
		if os.path.basename(potential_wscript) == Context.WSCRIPT_FILE and os.path.isfile(potential_wscript):
			# need to explicitly normalize the path, as it may contain extra '/.'
			path = os.path.normpath(os.path.dirname(potential_wscript))
			start_dir = os.path.abspath(path)
			no_climb = True
			sys.argv.pop(1)

	ctx = Context.create_context('options')
	(options, commands, env) = ctx.parse_cmd_args(allow_unknown=True)
	if options.top:
		start_dir = Context.run_dir = Context.top_dir = options.top
		no_climb = True
	if options.out:
		Context.out_dir = options.out

	# if 'configure' is in the commands, do not search any further
	if not no_climb:
		for k in no_climb_commands:
			for y in commands:
				if y.startswith(k):
					no_climb = True
					break

	# try to find a lock file (if the project was configured)
	# at the same time, store the first wscript file seen
	cur = start_dir
	while cur:
		try:
			lst = os.listdir(cur)
		except OSError:
			lst = []
			Logs.error('Directory %r is unreadable!', cur)
		if Options.lockfile in lst:
			env = ConfigSet.ConfigSet()
			try:
				env.load(os.path.join(cur, Options.lockfile))
				ino = os.stat(cur)[stat.ST_INO]
			except EnvironmentError:
				pass
			else:
				# check if the folder was not moved
				for x in (env.run_dir, env.top_dir, env.out_dir):
					if not x:
						continue
					if Utils.is_win32:
						if cur == x:
							load = True
							break
					else:
						# if the filesystem features symlinks, compare the inode numbers
						try:
							ino2 = os.stat(x)[stat.ST_INO]
						except OSError:
							pass
						else:
							if ino == ino2:
								load = True
								break
				else:
					Logs.warn('invalid lock file in %s', cur)
					load = False

				if load:
					Context.run_dir = env.run_dir
					Context.top_dir = env.top_dir
					Context.out_dir = env.out_dir
					break

		if not Context.run_dir:
			if Context.WSCRIPT_FILE in lst:
				Context.run_dir = cur

		next = os.path.dirname(cur)
		if next == cur:
			break
		cur = next

		if no_climb:
			break

	wscript = os.path.normpath(os.path.join(Context.run_dir, Context.WSCRIPT_FILE))
	if not os.path.exists(wscript):
		if options.whelp:
			Logs.warn('These are the generic options (no wscript/project found)')
			ctx.parser.print_help()
			sys.exit(0)
		Logs.error('Waf: Run from a folder containing a %r file (or try -h for the generic options)', Context.WSCRIPT_FILE)
		sys.exit(1)

	try:
		os.chdir(Context.run_dir)
	except OSError:
		Logs.error('Waf: The folder %r is unreadable', Context.run_dir)
		sys.exit(1)

	try:
		set_main_module(wscript)
	except Errors.WafError as e:
		Logs.pprint('RED', e.verbose_msg)
		Logs.error(str(e))
		sys.exit(1)
	except Exception as e:
		Logs.error('Waf: The wscript in %r is unreadable', Context.run_dir)
		traceback.print_exc(file=sys.stdout)
		sys.exit(2)

	if options.profile:
		import cProfile, pstats
		cProfile.runctx('from waflib import Scripting; Scripting.run_commands()', {}, {}, 'profi.txt')
		p = pstats.Stats('profi.txt')
		p.sort_stats('time').print_stats(75) # or 'cumulative'
	else:
		try:
			try:
				run_commands()
			except:
				if options.pdb:
					import pdb
					type, value, tb = sys.exc_info()
					traceback.print_exc()
					pdb.post_mortem(tb)
				else:
					raise
		except Errors.WafError as e:
			if Logs.verbose > 1:
				Logs.pprint('RED', e.verbose_msg)
			Logs.error(e.msg)
			sys.exit(1)
		except SystemExit:
			raise
		except Exception as e:
			traceback.print_exc(file=sys.stdout)
			sys.exit(2)
		except KeyboardInterrupt:
			Logs.pprint('RED', 'Interrupted')
			sys.exit(68)
Example #51
0
def run_build(self, *k, **kw):
	"""
	Create a temporary build context to execute a build. A reference to that build
	context is kept on self.test_bld for debugging purposes, and you should not rely
	on it too much (read the note on the cache below).
	The parameters given in the arguments to this function are passed as arguments for
	a single task generator created in the build. Only three parameters are obligatory:

	:param features: features to pass to a task generator created in the build
	:type features: list of string
	:param compile_filename: file to create for the compilation (default: *test.c*)
	:type compile_filename: string
	:param code: code to write in the filename to compile
	:type code: string

	Though this function returns *0* by default, the build may set an attribute named *retval* on the
	build context object to return a particular value. See :py:func:`waflib.Tools.c_config.test_exec_fun` for example.

	This function also provides a limited cache. To use it, provide the following option::

		def options(opt):
			opt.add_option('--confcache', dest='confcache', default=0,
				action='count', help='Use a configuration cache')

	And execute the configuration with the following command-line::

		$ waf configure --confcache

	"""
	lst = [str(v) for (p, v) in kw.items() if p != 'env']
	h = Utils.h_list(lst)
	dir = self.bldnode.abspath() + os.sep + (not Utils.is_win32 and '.' or '') + 'conf_check_' + Utils.to_hex(h)

	try:
		os.makedirs(dir)
	except OSError:
		pass

	try:
		os.stat(dir)
	except OSError:
		self.fatal('cannot use the configuration test folder %r' % dir)

	cachemode = getattr(Options.options, 'confcache', None)
	if cachemode == 1:
		try:
			proj = ConfigSet.ConfigSet(os.path.join(dir, 'cache_run_build'))
		except EnvironmentError:
			pass
		else:
			ret = proj['cache_run_build']
			if isinstance(ret, str) and ret.startswith('Test does not build'):
				self.fatal(ret)
			return ret

	bdir = os.path.join(dir, 'testbuild')

	if not os.path.exists(bdir):
		os.makedirs(bdir)

	cls_name = kw.get('run_build_cls') or getattr(self, 'run_build_cls', 'build')
	self.test_bld = bld = Context.create_context(cls_name, top_dir=dir, out_dir=bdir)
	bld.init_dirs()
	bld.progress_bar = 0
	bld.targets = '*'

	bld.logger = self.logger
	bld.all_envs.update(self.all_envs) # not really necessary
	bld.env = kw['env']

	bld.kw = kw
	bld.conf = self
	kw['build_fun'](bld)
	ret = -1
	try:
		try:
			bld.compile()
		except Errors.WafError:
			ret = 'Test does not build: %s' % traceback.format_exc()
			self.fatal(ret)
		else:
			ret = getattr(bld, 'retval', 0)
	finally:
		if cachemode == 1:
			# cache the results each time
			proj = ConfigSet.ConfigSet()
			proj['cache_run_build'] = ret
			proj.store(os.path.join(dir, 'cache_run_build'))
		else:
			shutil.rmtree(dir)
	return ret
Example #52
0
def run_build(self, *k, **kw):
    """
	Create a temporary build context to execute a build. A temporary reference to that build
	context is kept on self.test_bld for debugging purposes.
	The arguments to this function are passed to a single task generator for that build.
	Only three parameters are mandatory:

	:param features: features to pass to a task generator created in the build
	:type features: list of string
	:param compile_filename: file to create for the compilation (default: *test.c*)
	:type compile_filename: string
	:param code: input file contents
	:type code: string

	Though this function returns *0* by default, the build may bind attribute named *retval* on the
	build context object to return a particular value. See :py:func:`waflib.Tools.c_config.test_exec_fun` for example.

	The temporary builds creates a temporary folder; the name of that folder is calculated
	by hashing input arguments to this function, with the exception of :py:class:`waflib.ConfigSet.ConfigSet`
	objects which are used for both reading and writing values.

	This function also features a cache which is disabled by default; that cache relies
	on the hash value calculated as indicated above::

		def options(opt):
			opt.add_option('--confcache', dest='confcache', default=0,
				action='count', help='Use a configuration cache')

	And execute the configuration with the following command-line::

		$ waf configure --confcache

	"""
    buf = []
    for key in sorted(kw.keys()):
        v = kw[key]
        if isinstance(v, ConfigSet.ConfigSet):
            # values are being written to, so they are excluded from contributing to the hash
            continue
        elif hasattr(v, '__call__'):
            buf.append(Utils.h_fun(v))
        else:
            buf.append(str(v))
    h = Utils.h_list(buf)
    dir = self.bldnode.abspath() + os.sep + (
        not Utils.is_win32 and '.' or '') + 'conf_check_' + Utils.to_hex(h)

    cachemode = kw.get('confcache', getattr(Options.options, 'confcache',
                                            None))

    if not cachemode and os.path.exists(dir):
        shutil.rmtree(dir)

    try:
        os.makedirs(dir)
    except OSError:
        pass

    try:
        os.stat(dir)
    except OSError:
        self.fatal('cannot use the configuration test folder %r' % dir)

    if cachemode == 1:
        try:
            proj = ConfigSet.ConfigSet(os.path.join(dir, 'cache_run_build'))
        except EnvironmentError:
            pass
        else:
            ret = proj['cache_run_build']
            if isinstance(ret, str) and ret.startswith('Test does not build'):
                self.fatal(ret)
            return ret

    bdir = os.path.join(dir, 'testbuild')

    if not os.path.exists(bdir):
        os.makedirs(bdir)

    cls_name = kw.get('run_build_cls') or getattr(self, 'run_build_cls',
                                                  'build')
    self.test_bld = bld = Context.create_context(cls_name,
                                                 top_dir=dir,
                                                 out_dir=bdir)
    bld.init_dirs()
    bld.progress_bar = 0
    bld.targets = '*'

    bld.logger = self.logger
    bld.all_envs.update(self.all_envs)  # not really necessary
    bld.env = kw['env']

    bld.kw = kw
    bld.conf = self
    kw['build_fun'](bld)
    ret = -1
    try:
        try:
            bld.compile()
        except Errors.WafError:
            ret = 'Test does not build: %s' % traceback.format_exc()
            self.fatal(ret)
        else:
            ret = getattr(bld, 'retval', 0)
    finally:
        if cachemode:
            # cache the results each time
            proj = ConfigSet.ConfigSet()
            proj['cache_run_build'] = ret
            proj.store(os.path.join(dir, 'cache_run_build'))
        else:
            shutil.rmtree(dir)
    return ret
def waf_entry_point(current_directory, version, wafdir):
    Logs.init_log()
    if Context.WAFVERSION != version:
        Logs.error('Waf script %r and library %r do not match (directory %r)',
                   version, Context.WAFVERSION, wafdir)
        sys.exit(1)
    Context.waf_dir = wafdir
    Context.run_dir = Context.launch_dir = current_directory
    start_dir = current_directory
    no_climb = os.environ.get('NOCLIMB')
    if len(sys.argv) > 1:
        potential_wscript = os.path.join(current_directory, sys.argv[1])
        if os.path.basename(
                potential_wscript) == Context.WSCRIPT_FILE and os.path.isfile(
                    potential_wscript):
            path = os.path.normpath(os.path.dirname(potential_wscript))
            start_dir = os.path.abspath(path)
            no_climb = True
            sys.argv.pop(1)
    ctx = Context.create_context('options')
    (options, commands, env) = ctx.parse_cmd_args(allow_unknown=True)
    if options.top:
        start_dir = Context.run_dir = Context.top_dir = options.top
        no_climb = True
    if options.out:
        Context.out_dir = options.out
    if not no_climb:
        for k in no_climb_commands:
            for y in commands:
                if y.startswith(k):
                    no_climb = True
                    break
    cur = start_dir
    while cur:
        try:
            lst = os.listdir(cur)
        except OSError:
            lst = []
            Logs.error('Directory %r is unreadable!', cur)
        if Options.lockfile in lst:
            env = ConfigSet.ConfigSet()
            try:
                env.load(os.path.join(cur, Options.lockfile))
                ino = os.stat(cur)[stat.ST_INO]
            except EnvironmentError:
                pass
            else:
                for x in (env.run_dir, env.top_dir, env.out_dir):
                    if not x:
                        continue
                    if Utils.is_win32:
                        if cur == x:
                            load = True
                            break
                    else:
                        try:
                            ino2 = os.stat(x)[stat.ST_INO]
                        except OSError:
                            pass
                        else:
                            if ino == ino2:
                                load = True
                                break
                else:
                    Logs.warn('invalid lock file in %s', cur)
                    load = False
                if load:
                    Context.run_dir = env.run_dir
                    Context.top_dir = env.top_dir
                    Context.out_dir = env.out_dir
                    break
        if not Context.run_dir:
            if Context.WSCRIPT_FILE in lst:
                Context.run_dir = cur
        next = os.path.dirname(cur)
        if next == cur:
            break
        cur = next
        if no_climb:
            break
    wscript = os.path.normpath(
        os.path.join(Context.run_dir, Context.WSCRIPT_FILE))
    if not os.path.exists(wscript):
        if options.whelp:
            Logs.warn(
                'These are the generic options (no wscript/project found)')
            ctx.parser.print_help()
            sys.exit(0)
        Logs.error(
            'Waf: Run from a folder containing a %r file (or try -h for the generic options)',
            Context.WSCRIPT_FILE)
        sys.exit(1)
    try:
        os.chdir(Context.run_dir)
    except OSError:
        Logs.error('Waf: The folder %r is unreadable', Context.run_dir)
        sys.exit(1)
    try:
        set_main_module(wscript)
    except Errors.WafError as e:
        Logs.pprint('RED', e.verbose_msg)
        Logs.error(str(e))
        sys.exit(1)
    except Exception as e:
        Logs.error('Waf: The wscript in %r is unreadable', Context.run_dir)
        traceback.print_exc(file=sys.stdout)
        sys.exit(2)
    if options.profile:
        import cProfile, pstats
        cProfile.runctx(
            'from waflib import Scripting; Scripting.run_commands()', {}, {},
            'profi.txt')
        p = pstats.Stats('profi.txt')
        p.sort_stats('time').print_stats(75)
    else:
        try:
            try:
                run_commands()
            except:
                if options.pdb:
                    import pdb
                    type, value, tb = sys.exc_info()
                    traceback.print_exc()
                    pdb.post_mortem(tb)
                else:
                    raise
        except Errors.WafError as e:
            if Logs.verbose > 1:
                Logs.pprint('RED', e.verbose_msg)
            Logs.error(e.msg)
            sys.exit(1)
        except SystemExit:
            raise
        except Exception as e:
            traceback.print_exc(file=sys.stdout)
            sys.exit(2)
        except KeyboardInterrupt:
            Logs.pprint('RED', 'Interrupted')
            sys.exit(68)
Example #54
0
	def parse_args(self):
		self.prepare_config_review()
		self.parser.get_option('--prefix').help = 'installation prefix'
		super(OptionsReview, self).parse_args()
		Context.create_context('review').refresh_review_set()
Example #55
0
def new_configure_execute(self):
    old_configure_execute(self)
    Context.create_context("review").store_review_set(new_review_set)
Example #56
0
 def parse_args(self):
     self.prepare_config_review()
     self.parser.get_option("--prefix").help = "installation prefix"
     super().parse_args()
     Context.create_context("review").refresh_review_set()
Example #57
0
def waf_entry_point(current_directory, version, wafdir):
    """
	This is the main entry point, all Waf execution starts here.

	:param current_directory: absolute path representing the current directory
	:type current_directory: string
	:param version: version number
	:type version: string
	:param wafdir: absolute path representing the directory of the waf library
	:type wafdir: string
	"""
    def _wait_for_user_input():
        """ Helper function to wait for a key press when needed (like on windows to prevent closing the windows """
        try:
            if not Utils.unversioned_sys_platform() == 'win32':
                return  # No need on non windows platforms

            if not _is_option_true(Options.options, 'ask_for_user_input'):
                return  # Obey what the user wants

            if Options.options.execsolution:
                return  # Dont ask for input in visual studio

            if _is_option_true(Options.options,
                               'internal_dont_check_recursive_execution'):
                return  # Dont ask from within Incredibuild

            import msvcrt
            Logs.error('Please Press Any Key to Continue')
            msvcrt.getch()
        except:
            pass  # Crashed to early to do something meaningful

    def _dump_call_stack():
        """ Util function to dump a callstack, and if running from Visual Studio, to format the error to be clickable """
        if getattr(Options.options, 'execsolution', None):
            exc_type, exc_value, exc_traceback = sys.exc_info()
            stackstace = traceback.format_tb(exc_traceback)
            sys.stdout.write('Traceback (most recent call last):\n')
            python_to_vs = re.compile(r'(.*?)"(.+?)", line ([0-9]+?),(.*)',
                                      re.M)

            # Align output vertically
            nAlignedPos = 0
            for line in stackstace[:-1]:
                m = re.match(python_to_vs, line)
                if m:
                    nNeededLenght = len('%s(%s):' % (m.group(2), m.group(3)))
                    if nNeededLenght > nAlignedPos:
                        nAlignedPos = nNeededLenght

            # output
            for line in stackstace[:-1]:
                m = re.match(python_to_vs, line)
                if m:
                    nNeededSpaces = 1 + (nAlignedPos -
                                         len('%s(%s):' %
                                             (m.group(2), m.group(3))))
                    sys.stdout.write('%s(%s):%s%s\n' %
                                     (m.group(2), m.group(3),
                                      ' ' * nNeededSpaces, m.group(4)))
                else:
                    sys.stdout.write(line)

            m = re.match(python_to_vs, stackstace[-1])
            if m:
                sys.stdout.write(
                    '%s(%s): error : %s %s\n' %
                    (m.group(2), m.group(3), m.group(4), str(exc_value)))
            else:
                sys.stdout.write(line)
        else:
            traceback.print_exc(file=sys.stdout)

    Logs.init_log()

    if Context.WAFVERSION != version:
        Logs.error('Waf script %r and library %r do not match (directory %r)' %
                   (version, Context.WAFVERSION, wafdir))
        _wait_for_user_input()
        sys.exit(1)

    # import waf branch spec
    branch_spec_globals = Context.load_branch_spec(current_directory)

    if Utils.is_win32:  # Make sure we always have the same path, regardless of used shell
        current_directory = current_directory[0].lower(
        ) + current_directory[1:]

    if '--version' in sys.argv:
        Context.run_dir = current_directory
        ctx = Context.create_context('options')
        ctx.curdir = current_directory
        ctx.parse_args()
        sys.exit(0)

    Context.waf_dir = wafdir
    Context.launch_dir = current_directory

    # if 'configure' is in the commands, do not search any further
    no_climb = os.environ.get('NOCLIMB', None)
    if not no_climb:
        for k in no_climb_commands:
            if k in sys.argv:
                no_climb = True
                break

    # try to find a lock file (if the project was configured)
    cur_lockfile = current_directory + os.sep + branch_spec_globals[
        'BINTEMP_FOLDER']

    try:
        lst_lockfile = os.listdir(cur_lockfile)
    except OSError:
        pass
    else:
        if Options.lockfile in lst_lockfile:
            env = ConfigSet.ConfigSet()
            try:
                env.load(os.path.join(cur_lockfile, Options.lockfile))
                ino = os.stat(cur_lockfile)[stat.ST_INO]
                Context.lock_dir = cur_lockfile
            except Exception:
                pass
            else:
                # check if the folder was not moved
                for x in [env.lock_dir]:
                    if Utils.is_win32:
                        if cur_lockfile == x:
                            load = True
                            break
                    else:
                        # if the filesystem features symlinks, compare the inode numbers
                        try:
                            ino2 = os.stat(x)[stat.ST_INO]
                        except OSError:
                            pass
                        else:
                            if ino == ino2:
                                load = True
                                break
                else:
                    Logs.warn('invalid lock file in %s' % cur_lockfile)
                    load = False

                if load:
                    Context.run_dir = env.run_dir
                    Context.top_dir = env.top_dir
                    Context.out_dir = env.out_dir
                    Context.lock_dir = env.lock_dir

    # store the first wscript file seen (if the project was not configured)
    if not Context.run_dir:
        cur = current_directory
        while cur:
            lst = os.listdir(cur)
            if Context.WSCRIPT_FILE in lst:
                Context.run_dir = cur

            next = os.path.dirname(cur)
            if next == cur:
                break
            cur = next

            if no_climb:
                break

    if not Context.run_dir:
        if '-h' in sys.argv or '--help' in sys.argv:
            Logs.warn(
                'No wscript file found: the help message may be incomplete')
            Context.run_dir = current_directory
            ctx = Context.create_context('options')
            ctx.curdir = current_directory
            ctx.parse_args()
            sys.exit(0)
        Logs.error('Waf: Run from a directory containing a file named %r' %
                   Context.WSCRIPT_FILE)
        _wait_for_user_input()
        sys.exit(1)

    try:
        os.chdir(Context.run_dir)
    except OSError:
        Logs.error('Waf: The folder %r is unreadable' % Context.run_dir)
        _wait_for_user_input()
        sys.exit(1)

    try:
        set_main_module(Context.run_dir + os.sep + Context.WSCRIPT_FILE)
    except Errors.WafError as e:
        Logs.pprint('RED', e.verbose_msg)
        Logs.error(str(e))
        _wait_for_user_input()
        sys.exit(1)
    except Exception as e:
        Logs.error('Waf: The wscript in %r is unreadable' % Context.run_dir, e)
        _dump_call_stack()
        _wait_for_user_input()
        sys.exit(2)
    """
	import cProfile, pstats
	cProfile.runctx("from waflib import Scripting; Scripting.run_commands()", {}, {}, 'profi.txt')
	p = pstats.Stats('profi.txt')
	p.sort_stats('time').print_stats(25) # or 'cumulative'
	"""

    try:
        run_commands()
    except Errors.WafError as e:
        if Logs.verbose > 1:
            Logs.pprint('RED', e.verbose_msg)
        Logs.error(e.msg)
        _wait_for_user_input()
        sys.exit(1)
    except SystemExit:
        raise
    except Exception as e:
        _dump_call_stack()
        _wait_for_user_input()
        sys.exit(2)
    except KeyboardInterrupt:
        Logs.pprint('RED', 'Interrupted')
        _wait_for_user_input()
        sys.exit(68)
Example #58
0
def run_command(cmd_name):
	ctx=Context.create_context(cmd_name)
	ctx.options=Options.options
	ctx.cmd=cmd_name
	ctx.execute()
	return ctx
Example #59
0
def waf_entry_point(current_directory, version, wafdir):
    """
	This is the main entry point, all Waf execution starts here.

	:param current_directory: absolute path representing the current directory
	:type current_directory: string
	:param version: version number
	:type version: string
	:param wafdir: absolute path representing the directory of the waf library
	:type wafdir: string
	"""

    Logs.init_log()

    if Context.WAFVERSION != version:
        Logs.error('Waf script %r and library %r do not match (directory %r)' %
                   (version, Context.WAFVERSION, wafdir))
        sys.exit(1)

    if '--version' in sys.argv:
        Context.run_dir = current_directory
        ctx = Context.create_context('options')
        ctx.curdir = current_directory
        ctx.parse_args()
        sys.exit(0)

    Context.waf_dir = wafdir
    Context.launch_dir = current_directory

    # if 'configure' is in the commands, do not search any further
    no_climb = os.environ.get('NOCLIMB', None)
    if not no_climb:
        for k in no_climb_commands:
            for y in sys.argv:
                if y.startswith(k):
                    no_climb = True
                    break

    # try to find a lock file (if the project was configured)
    # at the same time, store the first wscript file seen
    cur = current_directory
    while cur:
        lst = os.listdir(cur)
        if Options.lockfile in lst:
            env = ConfigSet.ConfigSet()
            try:
                env.load(os.path.join(cur, Options.lockfile))
                ino = os.stat(cur)[stat.ST_INO]
            except Exception:
                pass
            else:
                # check if the folder was not moved
                for x in (env.run_dir, env.top_dir, env.out_dir):
                    if Utils.is_win32:
                        if cur == x:
                            load = True
                            break
                    else:
                        # if the filesystem features symlinks, compare the inode numbers
                        try:
                            ino2 = os.stat(x)[stat.ST_INO]
                        except OSError:
                            pass
                        else:
                            if ino == ino2:
                                load = True
                                break
                else:
                    Logs.warn('invalid lock file in %s' % cur)
                    load = False

                if load:
                    Context.run_dir = env.run_dir
                    Context.top_dir = env.top_dir
                    Context.out_dir = env.out_dir
                    break

        if not Context.run_dir:
            if Context.WSCRIPT_FILE in lst:
                Context.run_dir = cur

        next = os.path.dirname(cur)
        if next == cur:
            break
        cur = next

        if no_climb:
            break

    if not Context.run_dir:
        if '-h' in sys.argv or '--help' in sys.argv:
            Logs.warn(
                'No wscript file found: the help message may be incomplete')
            Context.run_dir = current_directory
            ctx = Context.create_context('options')
            ctx.curdir = current_directory
            ctx.parse_args()
            sys.exit(0)
        Logs.error('Waf: Run from a directory containing a file named %r' %
                   Context.WSCRIPT_FILE)
        sys.exit(1)

    try:
        os.chdir(Context.run_dir)
    except OSError:
        Logs.error('Waf: The folder %r is unreadable' % Context.run_dir)
        sys.exit(1)

    try:
        set_main_module(os.path.join(Context.run_dir, Context.WSCRIPT_FILE))
    except Errors.WafError as e:
        Logs.pprint('RED', e.verbose_msg)
        Logs.error(str(e))
        sys.exit(1)
    except Exception as e:
        Logs.error('Waf: The wscript in %r is unreadable' % Context.run_dir, e)
        traceback.print_exc(file=sys.stdout)
        sys.exit(2)
    """
	import cProfile, pstats
	cProfile.runctx("from waflib import Scripting; Scripting.run_commands()", {}, {}, 'profi.txt')
	p = pstats.Stats('profi.txt')
	p.sort_stats('time').print_stats(25) # or 'cumulative'
	"""
    try:
        run_commands()
    except Errors.WafError as e:
        if Logs.verbose > 1:
            Logs.pprint('RED', e.verbose_msg)
        Logs.error(e.msg)
        sys.exit(1)
    except SystemExit:
        raise
    except Exception as e:
        traceback.print_exc(file=sys.stdout)
        sys.exit(2)
    except KeyboardInterrupt:
        Logs.pprint('RED', 'Interrupted')
        sys.exit(68)
Example #60
0
def waf_entry_point(current_directory, version, wafdir):
    Logs.init_log()
    if Context.WAFVERSION != version:
        Logs.error('Waf script %r and library %r do not match (directory %r)' %
                   (version, Context.WAFVERSION, wafdir))
        sys.exit(1)
    if '--version' in sys.argv:
        Context.run_dir = current_directory
        ctx = Context.create_context('options')
        ctx.curdir = current_directory
        ctx.parse_args()
        sys.exit(0)
    Context.waf_dir = wafdir
    Context.launch_dir = current_directory
    no_climb = os.environ.get('NOCLIMB', None)
    if not no_climb:
        for k in no_climb_commands:
            if k in sys.argv:
                no_climb = True
                break
    cur = current_directory
    while cur:
        lst = os.listdir(cur)
        if Options.lockfile in lst:
            env = ConfigSet.ConfigSet()
            try:
                env.load(os.path.join(cur, Options.lockfile))
                ino = os.stat(cur)[stat.ST_INO]
            except Exception:
                pass
            else:
                for x in [env.run_dir, env.top_dir, env.out_dir]:
                    if Utils.is_win32:
                        if cur == x:
                            load = True
                            break
                    else:
                        try:
                            ino2 = os.stat(x)[stat.ST_INO]
                        except OSError:
                            pass
                        else:
                            if ino == ino2:
                                load = True
                                break
                else:
                    Logs.warn('invalid lock file in %s' % cur)
                    load = False
                if load:
                    Context.run_dir = env.run_dir
                    Context.top_dir = env.top_dir
                    Context.out_dir = env.out_dir
                    break
        if not Context.run_dir:
            if Context.WSCRIPT_FILE in lst:
                Context.run_dir = cur
        next = os.path.dirname(cur)
        if next == cur:
            break
        cur = next
        if no_climb:
            break
    if not Context.run_dir:
        if '-h' in sys.argv or '--help' in sys.argv:
            Logs.warn(
                'No wscript file found: the help message may be incomplete')
            Context.run_dir = current_directory
            ctx = Context.create_context('options')
            ctx.curdir = current_directory
            ctx.parse_args()
            sys.exit(0)
        Logs.error('Waf: Run from a directory containing a file named %r' %
                   Context.WSCRIPT_FILE)
        sys.exit(1)
    try:
        os.chdir(Context.run_dir)
    except OSError:
        Logs.error('Waf: The folder %r is unreadable' % Context.run_dir)
        sys.exit(1)
    try:
        set_main_module(Context.run_dir + os.sep + Context.WSCRIPT_FILE)
    except Errors.WafError, e:
        Logs.pprint('RED', e.verbose_msg)
        Logs.error(str(e))
        sys.exit(1)