jack2 codebase
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

615 lines
16KB

  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. # Thomas Nagy, 2005-2018 (ita)
  4. "Module called for configuring, compiling and installing targets"
  5. from __future__ import with_statement
  6. import os, shlex, shutil, traceback, errno, sys, stat
  7. from waflib import Utils, Configure, Logs, Options, ConfigSet, Context, Errors, Build, Node
  8. build_dir_override = None
  9. no_climb_commands = ['configure']
  10. default_cmd = "build"
  11. def waf_entry_point(current_directory, version, wafdir):
  12. """
  13. This is the main entry point, all Waf execution starts here.
  14. :param current_directory: absolute path representing the current directory
  15. :type current_directory: string
  16. :param version: version number
  17. :type version: string
  18. :param wafdir: absolute path representing the directory of the waf library
  19. :type wafdir: string
  20. """
  21. Logs.init_log()
  22. if Context.WAFVERSION != version:
  23. Logs.error('Waf script %r and library %r do not match (directory %r)', version, Context.WAFVERSION, wafdir)
  24. sys.exit(1)
  25. # Store current directory before any chdir
  26. Context.waf_dir = wafdir
  27. Context.run_dir = Context.launch_dir = current_directory
  28. start_dir = current_directory
  29. no_climb = os.environ.get('NOCLIMB')
  30. if len(sys.argv) > 1:
  31. # os.path.join handles absolute paths
  32. # if sys.argv[1] is not an absolute path, then it is relative to the current working directory
  33. potential_wscript = os.path.join(current_directory, sys.argv[1])
  34. if os.path.basename(potential_wscript) == Context.WSCRIPT_FILE and os.path.isfile(potential_wscript):
  35. # need to explicitly normalize the path, as it may contain extra '/.'
  36. path = os.path.normpath(os.path.dirname(potential_wscript))
  37. start_dir = os.path.abspath(path)
  38. no_climb = True
  39. sys.argv.pop(1)
  40. ctx = Context.create_context('options')
  41. (options, commands, env) = ctx.parse_cmd_args(allow_unknown=True)
  42. if options.top:
  43. start_dir = Context.run_dir = Context.top_dir = options.top
  44. no_climb = True
  45. if options.out:
  46. Context.out_dir = options.out
  47. # if 'configure' is in the commands, do not search any further
  48. if not no_climb:
  49. for k in no_climb_commands:
  50. for y in commands:
  51. if y.startswith(k):
  52. no_climb = True
  53. break
  54. # try to find a lock file (if the project was configured)
  55. # at the same time, store the first wscript file seen
  56. cur = start_dir
  57. while cur:
  58. try:
  59. lst = os.listdir(cur)
  60. except OSError:
  61. lst = []
  62. Logs.error('Directory %r is unreadable!', cur)
  63. if Options.lockfile in lst:
  64. env = ConfigSet.ConfigSet()
  65. try:
  66. env.load(os.path.join(cur, Options.lockfile))
  67. ino = os.stat(cur)[stat.ST_INO]
  68. except EnvironmentError:
  69. pass
  70. else:
  71. # check if the folder was not moved
  72. for x in (env.run_dir, env.top_dir, env.out_dir):
  73. if not x:
  74. continue
  75. if Utils.is_win32:
  76. if cur == x:
  77. load = True
  78. break
  79. else:
  80. # if the filesystem features symlinks, compare the inode numbers
  81. try:
  82. ino2 = os.stat(x)[stat.ST_INO]
  83. except OSError:
  84. pass
  85. else:
  86. if ino == ino2:
  87. load = True
  88. break
  89. else:
  90. Logs.warn('invalid lock file in %s', cur)
  91. load = False
  92. if load:
  93. Context.run_dir = env.run_dir
  94. Context.top_dir = env.top_dir
  95. Context.out_dir = env.out_dir
  96. break
  97. if not Context.run_dir:
  98. if Context.WSCRIPT_FILE in lst:
  99. Context.run_dir = cur
  100. next = os.path.dirname(cur)
  101. if next == cur:
  102. break
  103. cur = next
  104. if no_climb:
  105. break
  106. wscript = os.path.normpath(os.path.join(Context.run_dir, Context.WSCRIPT_FILE))
  107. if not os.path.exists(wscript):
  108. if options.whelp:
  109. Logs.warn('These are the generic options (no wscript/project found)')
  110. ctx.parser.print_help()
  111. sys.exit(0)
  112. Logs.error('Waf: Run from a folder containing a %r file (or try -h for the generic options)', Context.WSCRIPT_FILE)
  113. sys.exit(1)
  114. try:
  115. os.chdir(Context.run_dir)
  116. except OSError:
  117. Logs.error('Waf: The folder %r is unreadable', Context.run_dir)
  118. sys.exit(1)
  119. try:
  120. set_main_module(wscript)
  121. except Errors.WafError as e:
  122. Logs.pprint('RED', e.verbose_msg)
  123. Logs.error(str(e))
  124. sys.exit(1)
  125. except Exception as e:
  126. Logs.error('Waf: The wscript in %r is unreadable', Context.run_dir)
  127. traceback.print_exc(file=sys.stdout)
  128. sys.exit(2)
  129. if options.profile:
  130. import cProfile, pstats
  131. cProfile.runctx('from waflib import Scripting; Scripting.run_commands()', {}, {}, 'profi.txt')
  132. p = pstats.Stats('profi.txt')
  133. p.sort_stats('time').print_stats(75) # or 'cumulative'
  134. else:
  135. try:
  136. try:
  137. run_commands()
  138. except:
  139. if options.pdb:
  140. import pdb
  141. type, value, tb = sys.exc_info()
  142. traceback.print_exc()
  143. pdb.post_mortem(tb)
  144. else:
  145. raise
  146. except Errors.WafError as e:
  147. if Logs.verbose > 1:
  148. Logs.pprint('RED', e.verbose_msg)
  149. Logs.error(e.msg)
  150. sys.exit(1)
  151. except SystemExit:
  152. raise
  153. except Exception as e:
  154. traceback.print_exc(file=sys.stdout)
  155. sys.exit(2)
  156. except KeyboardInterrupt:
  157. Logs.pprint('RED', 'Interrupted')
  158. sys.exit(68)
  159. def set_main_module(file_path):
  160. """
  161. Read the main wscript file into :py:const:`waflib.Context.Context.g_module` and
  162. bind default functions such as ``init``, ``dist``, ``distclean`` if not defined.
  163. Called by :py:func:`waflib.Scripting.waf_entry_point` during the initialization.
  164. :param file_path: absolute path representing the top-level wscript file
  165. :type file_path: string
  166. """
  167. Context.g_module = Context.load_module(file_path)
  168. Context.g_module.root_path = file_path
  169. # note: to register the module globally, use the following:
  170. # sys.modules['wscript_main'] = g_module
  171. def set_def(obj):
  172. name = obj.__name__
  173. if not name in Context.g_module.__dict__:
  174. setattr(Context.g_module, name, obj)
  175. for k in (dist, distclean, distcheck):
  176. set_def(k)
  177. # add dummy init and shutdown functions if they're not defined
  178. if not 'init' in Context.g_module.__dict__:
  179. Context.g_module.init = Utils.nada
  180. if not 'shutdown' in Context.g_module.__dict__:
  181. Context.g_module.shutdown = Utils.nada
  182. if not 'options' in Context.g_module.__dict__:
  183. Context.g_module.options = Utils.nada
  184. def parse_options():
  185. """
  186. Parses the command-line options and initialize the logging system.
  187. Called by :py:func:`waflib.Scripting.waf_entry_point` during the initialization.
  188. """
  189. ctx = Context.create_context('options')
  190. ctx.execute()
  191. if not Options.commands:
  192. Options.commands.append(default_cmd)
  193. if Options.options.whelp:
  194. ctx.parser.print_help()
  195. sys.exit(0)
  196. def run_command(cmd_name):
  197. """
  198. Executes a single Waf command. Called by :py:func:`waflib.Scripting.run_commands`.
  199. :param cmd_name: command to execute, like ``build``
  200. :type cmd_name: string
  201. """
  202. ctx = Context.create_context(cmd_name)
  203. ctx.log_timer = Utils.Timer()
  204. ctx.options = Options.options # provided for convenience
  205. ctx.cmd = cmd_name
  206. try:
  207. ctx.execute()
  208. finally:
  209. # Issue 1374
  210. ctx.finalize()
  211. return ctx
  212. def run_commands():
  213. """
  214. Execute the Waf commands that were given on the command-line, and the other options
  215. Called by :py:func:`waflib.Scripting.waf_entry_point` during the initialization, and executed
  216. after :py:func:`waflib.Scripting.parse_options`.
  217. """
  218. parse_options()
  219. run_command('init')
  220. while Options.commands:
  221. cmd_name = Options.commands.pop(0)
  222. ctx = run_command(cmd_name)
  223. Logs.info('%r finished successfully (%s)', cmd_name, ctx.log_timer)
  224. run_command('shutdown')
  225. ###########################################################################################
  226. def distclean_dir(dirname):
  227. """
  228. Distclean function called in the particular case when::
  229. top == out
  230. :param dirname: absolute path of the folder to clean
  231. :type dirname: string
  232. """
  233. for (root, dirs, files) in os.walk(dirname):
  234. for f in files:
  235. if f.endswith(('.o', '.moc', '.exe')):
  236. fname = os.path.join(root, f)
  237. try:
  238. os.remove(fname)
  239. except OSError:
  240. Logs.warn('Could not remove %r', fname)
  241. for x in (Context.DBFILE, 'config.log'):
  242. try:
  243. os.remove(x)
  244. except OSError:
  245. pass
  246. try:
  247. shutil.rmtree('c4che')
  248. except OSError:
  249. pass
  250. def distclean(ctx):
  251. '''removes build folders and data'''
  252. def remove_and_log(k, fun):
  253. try:
  254. fun(k)
  255. except EnvironmentError as e:
  256. if e.errno != errno.ENOENT:
  257. Logs.warn('Could not remove %r', k)
  258. # remove waf cache folders on the top-level
  259. if not Options.commands:
  260. for k in os.listdir('.'):
  261. for x in '.waf-2 waf-2 .waf3-2 waf3-2'.split():
  262. if k.startswith(x):
  263. remove_and_log(k, shutil.rmtree)
  264. # remove a build folder, if any
  265. cur = '.'
  266. if ctx.options.no_lock_in_top:
  267. cur = ctx.options.out
  268. try:
  269. lst = os.listdir(cur)
  270. except OSError:
  271. Logs.warn('Could not read %r', cur)
  272. return
  273. if Options.lockfile in lst:
  274. f = os.path.join(cur, Options.lockfile)
  275. try:
  276. env = ConfigSet.ConfigSet(f)
  277. except EnvironmentError:
  278. Logs.warn('Could not read %r', f)
  279. return
  280. if not env.out_dir or not env.top_dir:
  281. Logs.warn('Invalid lock file %r', f)
  282. return
  283. if env.out_dir == env.top_dir:
  284. distclean_dir(env.out_dir)
  285. else:
  286. remove_and_log(env.out_dir, shutil.rmtree)
  287. for k in (env.out_dir, env.top_dir, env.run_dir):
  288. p = os.path.join(k, Options.lockfile)
  289. remove_and_log(p, os.remove)
  290. class Dist(Context.Context):
  291. '''creates an archive containing the project source code'''
  292. cmd = 'dist'
  293. fun = 'dist'
  294. algo = 'tar.bz2'
  295. ext_algo = {}
  296. def execute(self):
  297. """
  298. See :py:func:`waflib.Context.Context.execute`
  299. """
  300. self.recurse([os.path.dirname(Context.g_module.root_path)])
  301. self.archive()
  302. def archive(self):
  303. """
  304. Creates the source archive.
  305. """
  306. import tarfile
  307. arch_name = self.get_arch_name()
  308. try:
  309. self.base_path
  310. except AttributeError:
  311. self.base_path = self.path
  312. node = self.base_path.make_node(arch_name)
  313. try:
  314. node.delete()
  315. except OSError:
  316. pass
  317. files = self.get_files()
  318. if self.algo.startswith('tar.'):
  319. tar = tarfile.open(node.abspath(), 'w:' + self.algo.replace('tar.', ''))
  320. for x in files:
  321. self.add_tar_file(x, tar)
  322. tar.close()
  323. elif self.algo == 'zip':
  324. import zipfile
  325. zip = zipfile.ZipFile(node.abspath(), 'w', compression=zipfile.ZIP_DEFLATED)
  326. for x in files:
  327. archive_name = self.get_base_name() + '/' + x.path_from(self.base_path)
  328. zip.write(x.abspath(), archive_name, zipfile.ZIP_DEFLATED)
  329. zip.close()
  330. else:
  331. self.fatal('Valid algo types are tar.bz2, tar.gz, tar.xz or zip')
  332. try:
  333. from hashlib import sha256
  334. except ImportError:
  335. digest = ''
  336. else:
  337. digest = ' (sha256=%r)' % sha256(node.read(flags='rb')).hexdigest()
  338. Logs.info('New archive created: %s%s', self.arch_name, digest)
  339. def get_tar_path(self, node):
  340. """
  341. Return the path to use for a node in the tar archive, the purpose of this
  342. is to let subclases resolve symbolic links or to change file names
  343. :return: absolute path
  344. :rtype: string
  345. """
  346. return node.abspath()
  347. def add_tar_file(self, x, tar):
  348. """
  349. Adds a file to the tar archive. Symlinks are not verified.
  350. :param x: file path
  351. :param tar: tar file object
  352. """
  353. p = self.get_tar_path(x)
  354. tinfo = tar.gettarinfo(name=p, arcname=self.get_tar_prefix() + '/' + x.path_from(self.base_path))
  355. tinfo.uid = 0
  356. tinfo.gid = 0
  357. tinfo.uname = 'root'
  358. tinfo.gname = 'root'
  359. if os.path.isfile(p):
  360. with open(p, 'rb') as f:
  361. tar.addfile(tinfo, fileobj=f)
  362. else:
  363. tar.addfile(tinfo)
  364. def get_tar_prefix(self):
  365. """
  366. Returns the base path for files added into the archive tar file
  367. :rtype: string
  368. """
  369. try:
  370. return self.tar_prefix
  371. except AttributeError:
  372. return self.get_base_name()
  373. def get_arch_name(self):
  374. """
  375. Returns the archive file name.
  376. Set the attribute *arch_name* to change the default value::
  377. def dist(ctx):
  378. ctx.arch_name = 'ctx.tar.bz2'
  379. :rtype: string
  380. """
  381. try:
  382. self.arch_name
  383. except AttributeError:
  384. self.arch_name = self.get_base_name() + '.' + self.ext_algo.get(self.algo, self.algo)
  385. return self.arch_name
  386. def get_base_name(self):
  387. """
  388. Returns the default name of the main directory in the archive, which is set to *appname-version*.
  389. Set the attribute *base_name* to change the default value::
  390. def dist(ctx):
  391. ctx.base_name = 'files'
  392. :rtype: string
  393. """
  394. try:
  395. self.base_name
  396. except AttributeError:
  397. appname = getattr(Context.g_module, Context.APPNAME, 'noname')
  398. version = getattr(Context.g_module, Context.VERSION, '1.0')
  399. self.base_name = appname + '-' + version
  400. return self.base_name
  401. def get_excl(self):
  402. """
  403. Returns the patterns to exclude for finding the files in the top-level directory.
  404. Set the attribute *excl* to change the default value::
  405. def dist(ctx):
  406. ctx.excl = 'build **/*.o **/*.class'
  407. :rtype: string
  408. """
  409. try:
  410. return self.excl
  411. except AttributeError:
  412. self.excl = Node.exclude_regs + ' **/waf-2.* **/.waf-2.* **/waf3-2.* **/.waf3-2.* **/*~ **/*.rej **/*.orig **/*.pyc **/*.pyo **/*.bak **/*.swp **/.lock-w*'
  413. if Context.out_dir:
  414. nd = self.root.find_node(Context.out_dir)
  415. if nd:
  416. self.excl += ' ' + nd.path_from(self.base_path)
  417. return self.excl
  418. def get_files(self):
  419. """
  420. Files to package are searched automatically by :py:func:`waflib.Node.Node.ant_glob`.
  421. Set *files* to prevent this behaviour::
  422. def dist(ctx):
  423. ctx.files = ctx.path.find_node('wscript')
  424. Files are also searched from the directory 'base_path', to change it, set::
  425. def dist(ctx):
  426. ctx.base_path = path
  427. :rtype: list of :py:class:`waflib.Node.Node`
  428. """
  429. try:
  430. files = self.files
  431. except AttributeError:
  432. files = self.base_path.ant_glob('**/*', excl=self.get_excl())
  433. return files
  434. def dist(ctx):
  435. '''makes a tarball for redistributing the sources'''
  436. pass
  437. class DistCheck(Dist):
  438. """creates an archive with dist, then tries to build it"""
  439. fun = 'distcheck'
  440. cmd = 'distcheck'
  441. def execute(self):
  442. """
  443. See :py:func:`waflib.Context.Context.execute`
  444. """
  445. self.recurse([os.path.dirname(Context.g_module.root_path)])
  446. self.archive()
  447. self.check()
  448. def make_distcheck_cmd(self, tmpdir):
  449. cfg = []
  450. if Options.options.distcheck_args:
  451. cfg = shlex.split(Options.options.distcheck_args)
  452. else:
  453. cfg = [x for x in sys.argv if x.startswith('-')]
  454. cmd = [sys.executable, sys.argv[0], 'configure', 'build', 'install', 'uninstall', '--destdir=' + tmpdir] + cfg
  455. return cmd
  456. def check(self):
  457. """
  458. Creates the archive, uncompresses it and tries to build the project
  459. """
  460. import tempfile, tarfile
  461. with tarfile.open(self.get_arch_name()) as t:
  462. for x in t:
  463. t.extract(x)
  464. instdir = tempfile.mkdtemp('.inst', self.get_base_name())
  465. cmd = self.make_distcheck_cmd(instdir)
  466. ret = Utils.subprocess.Popen(cmd, cwd=self.get_base_name()).wait()
  467. if ret:
  468. raise Errors.WafError('distcheck failed with code %r' % ret)
  469. if os.path.exists(instdir):
  470. raise Errors.WafError('distcheck succeeded, but files were left in %s' % instdir)
  471. shutil.rmtree(self.get_base_name())
  472. def distcheck(ctx):
  473. '''checks if the project compiles (tarball from 'dist')'''
  474. pass
  475. def autoconfigure(execute_method):
  476. """
  477. Decorator that enables context commands to run *configure* as needed.
  478. """
  479. def execute(self):
  480. """
  481. Wraps :py:func:`waflib.Context.Context.execute` on the context class
  482. """
  483. if not Configure.autoconfig:
  484. return execute_method(self)
  485. env = ConfigSet.ConfigSet()
  486. do_config = False
  487. try:
  488. env.load(os.path.join(Context.top_dir, Options.lockfile))
  489. except EnvironmentError:
  490. Logs.warn('Configuring the project')
  491. do_config = True
  492. else:
  493. if env.run_dir != Context.run_dir:
  494. do_config = True
  495. else:
  496. h = 0
  497. for f in env.files:
  498. try:
  499. h = Utils.h_list((h, Utils.readf(f, 'rb')))
  500. except EnvironmentError:
  501. do_config = True
  502. break
  503. else:
  504. do_config = h != env.hash
  505. if do_config:
  506. cmd = env.config_cmd or 'configure'
  507. if Configure.autoconfig == 'clobber':
  508. tmp = Options.options.__dict__
  509. if env.options:
  510. Options.options.__dict__ = env.options
  511. try:
  512. run_command(cmd)
  513. finally:
  514. Options.options.__dict__ = tmp
  515. else:
  516. run_command(cmd)
  517. run_command(self.cmd)
  518. else:
  519. return execute_method(self)
  520. return execute
  521. Build.BuildContext.execute = autoconfigure(Build.BuildContext.execute)