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.

632 lines
17KB

  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. if isinstance(default_cmd, list):
  193. Options.commands.extend(default_cmd)
  194. else:
  195. Options.commands.append(default_cmd)
  196. if Options.options.whelp:
  197. ctx.parser.print_help()
  198. sys.exit(0)
  199. def run_command(cmd_name):
  200. """
  201. Executes a single Waf command. Called by :py:func:`waflib.Scripting.run_commands`.
  202. :param cmd_name: command to execute, like ``build``
  203. :type cmd_name: string
  204. """
  205. ctx = Context.create_context(cmd_name)
  206. ctx.log_timer = Utils.Timer()
  207. ctx.options = Options.options # provided for convenience
  208. ctx.cmd = cmd_name
  209. try:
  210. ctx.execute()
  211. finally:
  212. # Issue 1374
  213. ctx.finalize()
  214. return ctx
  215. def run_commands():
  216. """
  217. Execute the Waf commands that were given on the command-line, and the other options
  218. Called by :py:func:`waflib.Scripting.waf_entry_point` during the initialization, and executed
  219. after :py:func:`waflib.Scripting.parse_options`.
  220. """
  221. parse_options()
  222. run_command('init')
  223. while Options.commands:
  224. cmd_name = Options.commands.pop(0)
  225. ctx = run_command(cmd_name)
  226. Logs.info('%r finished successfully (%s)', cmd_name, ctx.log_timer)
  227. run_command('shutdown')
  228. ###########################################################################################
  229. def distclean_dir(dirname):
  230. """
  231. Distclean function called in the particular case when::
  232. top == out
  233. :param dirname: absolute path of the folder to clean
  234. :type dirname: string
  235. """
  236. for (root, dirs, files) in os.walk(dirname):
  237. for f in files:
  238. if f.endswith(('.o', '.moc', '.exe')):
  239. fname = os.path.join(root, f)
  240. try:
  241. os.remove(fname)
  242. except OSError:
  243. Logs.warn('Could not remove %r', fname)
  244. for x in (Context.DBFILE, 'config.log'):
  245. try:
  246. os.remove(x)
  247. except OSError:
  248. pass
  249. try:
  250. shutil.rmtree(Build.CACHE_DIR)
  251. except OSError:
  252. pass
  253. def distclean(ctx):
  254. '''removes build folders and data'''
  255. def remove_and_log(k, fun):
  256. try:
  257. fun(k)
  258. except EnvironmentError as e:
  259. if e.errno != errno.ENOENT:
  260. Logs.warn('Could not remove %r', k)
  261. # remove waf cache folders on the top-level
  262. if not Options.commands:
  263. for k in os.listdir('.'):
  264. for x in '.waf-2 waf-2 .waf3-2 waf3-2'.split():
  265. if k.startswith(x):
  266. remove_and_log(k, shutil.rmtree)
  267. # remove a build folder, if any
  268. cur = '.'
  269. if os.environ.get('NO_LOCK_IN_TOP') or ctx.options.no_lock_in_top:
  270. cur = ctx.options.out
  271. try:
  272. lst = os.listdir(cur)
  273. except OSError:
  274. Logs.warn('Could not read %r', cur)
  275. return
  276. if Options.lockfile in lst:
  277. f = os.path.join(cur, Options.lockfile)
  278. try:
  279. env = ConfigSet.ConfigSet(f)
  280. except EnvironmentError:
  281. Logs.warn('Could not read %r', f)
  282. return
  283. if not env.out_dir or not env.top_dir:
  284. Logs.warn('Invalid lock file %r', f)
  285. return
  286. if env.out_dir == env.top_dir:
  287. distclean_dir(env.out_dir)
  288. else:
  289. remove_and_log(env.out_dir, shutil.rmtree)
  290. env_dirs = [env.out_dir]
  291. if not (os.environ.get('NO_LOCK_IN_TOP') or ctx.options.no_lock_in_top):
  292. env_dirs.append(env.top_dir)
  293. if not (os.environ.get('NO_LOCK_IN_RUN') or ctx.options.no_lock_in_run):
  294. env_dirs.append(env.run_dir)
  295. for k in env_dirs:
  296. p = os.path.join(k, Options.lockfile)
  297. remove_and_log(p, os.remove)
  298. class Dist(Context.Context):
  299. '''creates an archive containing the project source code'''
  300. cmd = 'dist'
  301. fun = 'dist'
  302. algo = 'tar.bz2'
  303. ext_algo = {}
  304. def execute(self):
  305. """
  306. See :py:func:`waflib.Context.Context.execute`
  307. """
  308. self.recurse([os.path.dirname(Context.g_module.root_path)])
  309. self.archive()
  310. def archive(self):
  311. """
  312. Creates the source archive.
  313. """
  314. import tarfile
  315. arch_name = self.get_arch_name()
  316. try:
  317. self.base_path
  318. except AttributeError:
  319. self.base_path = self.path
  320. node = self.base_path.make_node(arch_name)
  321. try:
  322. node.delete()
  323. except OSError:
  324. pass
  325. files = self.get_files()
  326. if self.algo.startswith('tar.'):
  327. tar = tarfile.open(node.abspath(), 'w:' + self.algo.replace('tar.', ''))
  328. for x in files:
  329. self.add_tar_file(x, tar)
  330. tar.close()
  331. elif self.algo == 'zip':
  332. import zipfile
  333. zip = zipfile.ZipFile(node.abspath(), 'w', compression=zipfile.ZIP_DEFLATED)
  334. for x in files:
  335. archive_name = self.get_base_name() + '/' + x.path_from(self.base_path)
  336. if os.environ.get('SOURCE_DATE_EPOCH'):
  337. # TODO: parse that timestamp
  338. zip.writestr(zipfile.ZipInfo(archive_name), x.read(), zipfile.ZIP_DEFLATED)
  339. else:
  340. zip.write(x.abspath(), archive_name, zipfile.ZIP_DEFLATED)
  341. zip.close()
  342. else:
  343. self.fatal('Valid algo types are tar.bz2, tar.gz, tar.xz or zip')
  344. try:
  345. from hashlib import sha256
  346. except ImportError:
  347. digest = ''
  348. else:
  349. digest = ' (sha256=%r)' % sha256(node.read(flags='rb')).hexdigest()
  350. Logs.info('New archive created: %s%s', self.arch_name, digest)
  351. def get_tar_path(self, node):
  352. """
  353. Return the path to use for a node in the tar archive, the purpose of this
  354. is to let subclases resolve symbolic links or to change file names
  355. :return: absolute path
  356. :rtype: string
  357. """
  358. return node.abspath()
  359. def add_tar_file(self, x, tar):
  360. """
  361. Adds a file to the tar archive. Symlinks are not verified.
  362. :param x: file path
  363. :param tar: tar file object
  364. """
  365. p = self.get_tar_path(x)
  366. tinfo = tar.gettarinfo(name=p, arcname=self.get_tar_prefix() + '/' + x.path_from(self.base_path))
  367. tinfo.uid = 0
  368. tinfo.gid = 0
  369. tinfo.uname = 'root'
  370. tinfo.gname = 'root'
  371. if os.environ.get('SOURCE_DATE_EPOCH'):
  372. tinfo.mtime = int(os.environ.get('SOURCE_DATE_EPOCH'))
  373. if os.path.isfile(p):
  374. with open(p, 'rb') as f:
  375. tar.addfile(tinfo, fileobj=f)
  376. else:
  377. tar.addfile(tinfo)
  378. def get_tar_prefix(self):
  379. """
  380. Returns the base path for files added into the archive tar file
  381. :rtype: string
  382. """
  383. try:
  384. return self.tar_prefix
  385. except AttributeError:
  386. return self.get_base_name()
  387. def get_arch_name(self):
  388. """
  389. Returns the archive file name.
  390. Set the attribute *arch_name* to change the default value::
  391. def dist(ctx):
  392. ctx.arch_name = 'ctx.tar.bz2'
  393. :rtype: string
  394. """
  395. try:
  396. self.arch_name
  397. except AttributeError:
  398. self.arch_name = self.get_base_name() + '.' + self.ext_algo.get(self.algo, self.algo)
  399. return self.arch_name
  400. def get_base_name(self):
  401. """
  402. Returns the default name of the main directory in the archive, which is set to *appname-version*.
  403. Set the attribute *base_name* to change the default value::
  404. def dist(ctx):
  405. ctx.base_name = 'files'
  406. :rtype: string
  407. """
  408. try:
  409. self.base_name
  410. except AttributeError:
  411. appname = getattr(Context.g_module, Context.APPNAME, 'noname')
  412. version = getattr(Context.g_module, Context.VERSION, '1.0')
  413. self.base_name = appname + '-' + version
  414. return self.base_name
  415. def get_excl(self):
  416. """
  417. Returns the patterns to exclude for finding the files in the top-level directory.
  418. Set the attribute *excl* to change the default value::
  419. def dist(ctx):
  420. ctx.excl = 'build **/*.o **/*.class'
  421. :rtype: string
  422. """
  423. try:
  424. return self.excl
  425. except AttributeError:
  426. self.excl = Node.exclude_regs + ' **/waf-2.* **/.waf-2.* **/waf3-2.* **/.waf3-2.* **/*~ **/*.rej **/*.orig **/*.pyc **/*.pyo **/*.bak **/*.swp **/.lock-w*'
  427. if Context.out_dir:
  428. nd = self.root.find_node(Context.out_dir)
  429. if nd:
  430. self.excl += ' ' + nd.path_from(self.base_path)
  431. return self.excl
  432. def get_files(self):
  433. """
  434. Files to package are searched automatically by :py:func:`waflib.Node.Node.ant_glob`.
  435. Set *files* to prevent this behaviour::
  436. def dist(ctx):
  437. ctx.files = ctx.path.find_node('wscript')
  438. Files are also searched from the directory 'base_path', to change it, set::
  439. def dist(ctx):
  440. ctx.base_path = path
  441. :rtype: list of :py:class:`waflib.Node.Node`
  442. """
  443. try:
  444. files = self.files
  445. except AttributeError:
  446. files = self.base_path.ant_glob('**/*', excl=self.get_excl())
  447. return files
  448. def dist(ctx):
  449. '''makes a tarball for redistributing the sources'''
  450. pass
  451. class DistCheck(Dist):
  452. """creates an archive with dist, then tries to build it"""
  453. fun = 'distcheck'
  454. cmd = 'distcheck'
  455. def execute(self):
  456. """
  457. See :py:func:`waflib.Context.Context.execute`
  458. """
  459. self.recurse([os.path.dirname(Context.g_module.root_path)])
  460. self.archive()
  461. self.check()
  462. def make_distcheck_cmd(self, tmpdir):
  463. cfg = []
  464. if Options.options.distcheck_args:
  465. cfg = shlex.split(Options.options.distcheck_args)
  466. else:
  467. cfg = [x for x in sys.argv if x.startswith('-')]
  468. cmd = [sys.executable, sys.argv[0], 'configure', 'build', 'install', 'uninstall', '--destdir=' + tmpdir] + cfg
  469. return cmd
  470. def check(self):
  471. """
  472. Creates the archive, uncompresses it and tries to build the project
  473. """
  474. import tempfile, tarfile
  475. with tarfile.open(self.get_arch_name()) as t:
  476. for x in t:
  477. t.extract(x)
  478. instdir = tempfile.mkdtemp('.inst', self.get_base_name())
  479. cmd = self.make_distcheck_cmd(instdir)
  480. ret = Utils.subprocess.Popen(cmd, cwd=self.get_base_name()).wait()
  481. if ret:
  482. raise Errors.WafError('distcheck failed with code %r' % ret)
  483. if os.path.exists(instdir):
  484. raise Errors.WafError('distcheck succeeded, but files were left in %s' % instdir)
  485. shutil.rmtree(self.get_base_name())
  486. def distcheck(ctx):
  487. '''checks if the project compiles (tarball from 'dist')'''
  488. pass
  489. def autoconfigure(execute_method):
  490. """
  491. Decorator that enables context commands to run *configure* as needed.
  492. """
  493. def execute(self):
  494. """
  495. Wraps :py:func:`waflib.Context.Context.execute` on the context class
  496. """
  497. if not Configure.autoconfig:
  498. return execute_method(self)
  499. env = ConfigSet.ConfigSet()
  500. do_config = False
  501. try:
  502. env.load(os.path.join(Context.top_dir, Options.lockfile))
  503. except EnvironmentError:
  504. Logs.warn('Configuring the project')
  505. do_config = True
  506. else:
  507. if env.run_dir != Context.run_dir:
  508. do_config = True
  509. else:
  510. h = 0
  511. for f in env.files:
  512. try:
  513. h = Utils.h_list((h, Utils.readf(f, 'rb')))
  514. except EnvironmentError:
  515. do_config = True
  516. break
  517. else:
  518. do_config = h != env.hash
  519. if do_config:
  520. cmd = env.config_cmd or 'configure'
  521. if Configure.autoconfig == 'clobber':
  522. tmp = Options.options.__dict__
  523. launch_dir_tmp = Context.launch_dir
  524. if env.options:
  525. Options.options.__dict__ = env.options
  526. Context.launch_dir = env.launch_dir
  527. try:
  528. run_command(cmd)
  529. finally:
  530. Options.options.__dict__ = tmp
  531. Context.launch_dir = launch_dir_tmp
  532. else:
  533. run_command(cmd)
  534. run_command(self.cmd)
  535. else:
  536. return execute_method(self)
  537. return execute
  538. Build.BuildContext.execute = autoconfigure(Build.BuildContext.execute)