Debian Codegraph @

acprep

raw symbols SCIP
1 #!/usr/bin/env python3
2
3 # acprep, version 3.1
4 #
5 # This script simply sets up the compiler and linker flags for all the various
6 # build permutations I use for testing and profiling.
7
8 import inspect
9 import logging
10 import logging.handlers
11 import optparse
12 import os
13 import re
14 import shutil
15 import sys
16 import locale
17
18 try:
19 import hashlib
20 except:
21 import md5
22
23 from os.path import *
24 from stat import *
25 from subprocess import Popen, PIPE, call
26
27 LEVELS = {'DEBUG': logging.DEBUG,
28 'INFO': logging.INFO,
29 'WARNING': logging.WARNING,
30 'ERROR': logging.ERROR,
31 'CRITICAL': logging.CRITICAL}
32
33 def which(program):
34 def is_exe(fpath):
35 return os.path.exists(fpath) and os.access(fpath, os.X_OK)
36
37 def ext_candidates(fpath):
38 yield fpath
39 for ext in os.environ.get("PATHEXT", "").split(os.pathsep):
40 yield fpath + ext
41
42 fpath, fname = os.path.split(program)
43 if fpath:
44 if is_exe(program):
45 return program
46 else:
47 for path in os.environ["PATH"].split(os.pathsep):
48 exe_file = os.path.join(path, program)
49 for candidate in ext_candidates(exe_file):
50 if is_exe(candidate):
51 return candidate
52
53 return None
54
55 class BoostInfo(object):
56 def dependencies(self, system, python):
57 if system in ['darwin-homebrew']:
58 return [ 'boost' ] + ([ 'boost-python3' ] if python else [])
59
60 if system in ['darwin-macports']:
61 return [ 'boost-jam', 'boost' ] + ([ '+python310' ] if python else [])
62
63 if system in ['centos']:
64 return [ 'boost-devel' ]
65
66 elif system in ['ubuntu-noble', 'ubuntu-jammy', 'ubuntu-focal', 'ubuntu-bionic',
67 'ubuntu-xenial', 'ubuntu-eoan', 'ubuntu-trusty', 'ubuntu-cosmic']:
68 return [ 'libboost-dev',
69 'libboost-date-time-dev',
70 'libboost-filesystem-dev',
71 'libboost-iostreams-dev',
72 'libboost-regex-dev',
73 'libboost-system-dev',
74 'libboost-test-dev',
75 'tzdata' ] + ([ 'libboost-python-dev' ] if python else [])
76
77 elif system in [ 'ubuntu-saucy', 'ubuntu-precise']:
78 return [ 'autopoint',
79 'libboost-dev',
80 'libboost-test-dev',
81 'libboost-regex-dev',
82 'libboost-date-time-dev',
83 'libboost-filesystem-dev',
84 'libboost-iostreams-dev',
85 ] + ([ 'libboost-python-dev' ] if withPython else [])
86
87 elif system in ['ubuntu-lucid']:
88 return [ 'bjam', 'autopoint',
89 'libboost-dev',
90 'libboost-regex-dev',
91 'libboost-date-time-dev',
92 'libboost-filesystem-dev',
93 'libboost-iostreams-dev',
94 ] + ([ 'libboost-python-dev' ] if withPython else [])
95
96
97 class CommandLineApp(object):
98 "Base class for building command line applications."
99
100 force_exit = True # If true, always ends run() with sys.exit()
101 log_handler = None
102
103 def __init__(self):
104 "Initialize CommandLineApp."
105 # Create the logger
106 self.log = logging.getLogger(os.path.basename(sys.argv[0]))
107 ch = logging.StreamHandler()
108 formatter = logging.Formatter("%(name)s: %(levelname)s: %(message)s")
109 ch.setFormatter(formatter)
110 self.log.addHandler(ch)
111 self.log_handler = ch
112
113 # Setup the options parser
114 usage = 'usage: %prog [OPTIONS...] [ARGS...]'
115 op = self.option_parser = optparse.OptionParser(usage = usage,
116 conflict_handler = 'resolve')
117 op.add_option('', '--debug',
118 action='store_true', dest='debug',
119 default=False, help='show debug messages and pass exceptions')
120 op.add_option('-v', '--verbose',
121 action='store_true', dest='verbose',
122 default=False, help='show informational messages')
123 op.add_option('-q', '--quiet',
124 action='store_true', dest='quiet',
125 default=False, help='do not show log messages on console')
126 op.add_option('', '--log', metavar='FILE',
127 type='string', action='store', dest='logfile',
128 default=False, help='append logging data to FILE')
129 op.add_option('', '--loglevel', metavar='LEVEL',
130 type='string', action='store', dest='loglevel',
131 default=False, help='set log level: DEBUG, INFO, WARNING, ERROR, CRITICAL')
132
133 self.options = op.get_default_values()
134
135 def main(self, *args):
136 """Main body of your application.
137
138 This is the main portion of the app, and is run after all of the
139 arguments are processed. Override this method to implement the primary
140 processing section of your application."""
141 pass
142
143 def handleInterrupt(self):
144 """Called when the program is interrupted via Control-C or SIGINT.
145 Returns exit code."""
146 self.log.error('Canceled by user.')
147 return 1
148
149 def handleMainException(self):
150 "Invoked when there is an error in the main() method."
151 if not self.options.debug:
152 self.log.exception('Caught exception')
153 return 1
154
155 ## INTERNALS (Subclasses should not need to override these methods)
156
157 def run(self):
158 """Entry point.
159
160 Process options and execute callback functions as needed. This method
161 should not need to be overridden, if the main() method is defined."""
162 # Process the options supported and given
163 self.options, main_args = self.option_parser.parse_args(values=self.options)
164
165 if self.options.logfile:
166 fh = logging.handlers.RotatingFileHandler(self.options.logfile,
167 maxBytes = (1024 * 1024),
168 backupCount = 5)
169 formatter = logging.Formatter("%(asctime)s - %(levelname)s: %(message)s")
170 fh.setFormatter(formatter)
171 self.log.addHandler(fh)
172
173 if self.options.quiet:
174 self.log.removeHandler(self.log_handler)
175 ch = logging.handlers.SysLogHandler()
176 formatter = logging.Formatter("%(name)s: %(levelname)s: %(message)s")
177 ch.setFormatter(formatter)
178 self.log.addHandler(ch)
179 self.log_handler = ch
180
181 if self.options.loglevel:
182 self.log.setLevel(LEVELS[self.options.loglevel])
183 elif self.options.debug:
184 self.log.setLevel(logging.DEBUG)
185 elif self.options.verbose:
186 self.log.setLevel(logging.INFO)
187
188 exit_code = 0
189 try:
190 # We could just call main() and catch a TypeError, but that would
191 # not let us differentiate between application errors and a case
192 # where the user has not passed us enough arguments. So, we check
193 # the argument count ourself.
194 argspec = inspect.getfullargspec(self.main)
195 expected_arg_count = len(argspec[0]) - 1
196
197 if len(main_args) >= expected_arg_count:
198 exit_code = self.main(*main_args)
199 else:
200 self.log.debug('Incorrect argument count (expected %d, got %d)' %
201 (expected_arg_count, len(main_args)))
202 self.option_parser.print_help()
203 exit_code = 1
204
205 except KeyboardInterrupt:
206 exit_code = self.handleInterrupt()
207
208 except SystemExit as msg:
209 exit_code = msg.args[0]
210
211 except Exception:
212 exit_code = self.handleMainException()
213 if self.options.debug:
214 raise
215
216 if self.force_exit:
217 sys.exit(exit_code)
218 return exit_code
219
220
221 class PrepareBuild(CommandLineApp):
222 #########################################################################
223 # Initialization routines #
224 #########################################################################
225
226 def initialize(self):
227 self.log.debug('Initializing all state variables')
228
229 self.should_clean = False
230 self.configured = False
231 self.current_ver = None
232 #self.current_flavor = 'default'
233 self.current_flavor = 'debug'
234 self.products_dir = None
235 self.configure_args = []
236 self.CXXFLAGS = []
237 self.LDFLAGS = []
238
239 self.envvars = {
240 'CXX': '',
241 'CXXFLAGS': '',
242 'LDFLAGS': '',
243 }
244
245 for varname in self.envvars.keys():
246 if varname in os.environ:
247 self.envvars[varname] = os.environ[varname]
248
249 if varname.endswith('FLAGS'):
250 self.__dict__[varname] = str.split(os.environ[varname])
251 self.envvars[varname] = ''
252
253 # If ~/Products/ or build/ exists, use them instead of the source tree
254 # for building
255 products = self.default_products_directory()
256 if (exists(products) and isdir(products)) or \
257 (exists('build') and isdir('build')):
258 self.options.build_dir = None
259
260 def __init__(self):
261 CommandLineApp.__init__(self)
262 self.log.setLevel(logging.INFO)
263
264 self.source_dir = os.getcwd()
265
266 op = self.option_parser
267
268 op.add_option('', '--help', action="callback",
269 callback=self.option_help,
270 help='Show this help text')
271 op.add_option('-j', '--jobs', metavar='N',
272 type='int', action='store', dest='jobs',
273 default=1, help='Allow N make jobs at once')
274
275 op.add_option('', '--boost', metavar='BOOST_ROOT',
276 action="store", dest="boost_root",
277 help='Set Boost library root (ex: "--boost=/usr/local")')
278 op.add_option('', '--boost-suffix', metavar='BOOST_SUFFIX',
279 action="store", dest="boost_suffix",
280 help='Set Boost library suffix (ex: "--boost-suffix=-mt")')
281 op.add_option('', '--boost-include', metavar='BOOST_INCLUDE',
282 action="store", dest="boost_include",
283 help='Set Boost include path (ex: "--boost-include=DIR")')
284
285 op.add_option('', '--compiler', metavar='COMPILER',
286 action="store", dest="compiler",
287 help='Use the Clang C++ compiler')
288 op.add_option('', '--cxx', metavar='COMPILER',
289 action="store", dest="compiler",
290 help='Use the Clang C++ compiler')
291
292 op.add_option('-N', '--ninja', action='store_true', dest='use_ninja',
293 default=False,
294 help='Use ninja to build, rather than make')
295 op.add_option('', '--no-git', action='store_true', dest='no_git',
296 default=False,
297 help='Do not call out to Git; useful for offline builds')
298 op.add_option('', '--doxygen', action='store_true',
299 dest='enable_doxygen', default=False,
300 help='Enable use of Doxygen to build ref manual ("make docs")')
301 op.add_option('', '--python', action='store_true', dest='python',
302 default=False,
303 help='Enable Python support')
304 op.add_option('', '--no-python', action='store_false', dest='python',
305 help='Disable python support (default)')
306 op.add_option('', '--prefix', metavar='DIR', action="store",
307 dest="prefix_dir", help='Use custom installation prefix')
308 op.add_option('', '--products', metavar='DIR', action="store",
309 dest="option_products",
310 help='Collect all build products in this directory')
311 op.add_option('', '--output', metavar='DIR', action="store",
312 default=self.source_dir,
313 dest="build_dir", help='Build in the specified directory')
314 op.add_option('', '--local', action="callback",
315 callback=self.option_local,
316 help='Build directly within the source tree (default)')
317
318 self.options = op.get_default_values()
319
320 self.initialize()
321
322 def main(self, *args):
323 if args and args[0] in ['default', 'debug', 'opt', 'gcov', 'gprof']:
324 self.current_flavor = args[0]
325 args = args[1:]
326
327 if args:
328 cmd = args[0]
329 if 'phase_' + cmd not in PrepareBuild.__dict__:
330 self.log.error("Unknown build phase: " + cmd + "\n")
331 sys.exit(1)
332 else:
333 args = args[1:]
334 else:
335 cmd = 'config'
336
337 self.log.info('Invoking primary phase: ' + cmd)
338 PrepareBuild.__dict__['phase_' + cmd](self, *args)
339
340 #########################################################################
341 # General utility code #
342 #########################################################################
343
344 def execute(self, *args):
345 try:
346 self.log.debug('Executing command: ' + ' '.join(args))
347
348 retcode = call(args, shell=False)
349 if retcode < 0:
350 self.log.error("Child was terminated by signal", -retcode)
351 sys.exit(1)
352 elif retcode != 0:
353 self.log.error("Execution failed: " + ' '.join(args))
354 sys.exit(1)
355 except OSError as e:
356 self.log.error("Execution failed: " + e)
357 sys.exit(1)
358
359 def isnewer(self, file1, file2):
360 "Check if file1 is newer than file2."
361 if not exists(file2):
362 return True
363 return os.stat(file1)[ST_MTIME] > os.stat(file2)[ST_MTIME]
364
365 #########################################################################
366 # Determine information about the surroundings #
367 #########################################################################
368
369 def prefix_directory(self):
370 if self.options.prefix_dir:
371 return self.options.prefix_dir
372 else:
373 return None
374
375 def default_products_directory(self):
376 return join(os.environ['HOME'], "Products")
377
378 def products_directory(self):
379 if not self.products_dir:
380 products = self.default_products_directory()
381
382 if not exists(products) or not isdir(products):
383 products = join(self.source_dir, 'build')
384
385 products = join(products, basename(self.source_dir))
386
387 self.products_dir = products
388
389 return self.products_dir
390
391 def build_directory(self):
392 if not self.options.build_dir:
393 self.options.build_dir = join(self.products_directory(),
394 self.current_flavor)
395 return self.options.build_dir
396
397 def ensure(self, dirname):
398 if not exists(dirname):
399 self.log.info('Making directory: ' + dirname)
400 os.makedirs(dirname)
401 elif not isdir(dirname):
402 self.log.error('Directory is not a directory: ' + dirname)
403 sys.exit(1)
404 return dirname
405
406 def git_working_tree(self):
407 return exists('.git') and isdir('.git') and not self.options.no_git
408
409 def current_version(self):
410 if not self.current_ver:
411 major, minor, patch, date = None, None, None, None
412
413 version_m4 = open('CMakeLists.txt', 'r')
414 for line in version_m4.readlines():
415 match = re.match(r'^set\(Ledger_VERSION_MAJOR ([0-9]+)\)', line)
416 if match:
417 major = match.group(1)
418 match = re.match(r'^set\(Ledger_VERSION_MINOR ([0-9]+)\)', line)
419 if match:
420 minor = match.group(1)
421 match = re.match(r'^set\(Ledger_VERSION_PATCH ([0-9]+)\)', line)
422 if match:
423 patch = match.group(1)
424 match = re.match(r'^set\(Ledger_VERSION_DATE ([0-9]+)\)', line)
425 if match:
426 date = match.group(1)
427 break
428 self.current_ver = "%s.%s.%s%s" % (major, minor, patch,
429 "-%s" % date if date else "")
430 version_m4.close()
431 return self.current_ver
432
433 def phase_products(self, *args):
434 self.log.info('Executing phase: products')
435 print(self.products_directory())
436
437 def phase_info(self, *args):
438 self.log.info('Executing phase: info')
439
440 environ, conf_args = self.configure_environment()
441
442 self.log.info("Current version => " + self.current_version())
443 self.log.info("Current flavor => " + self.current_flavor)
444 self.log.info("Source directory => " + self.source_dir)
445 if self.prefix_directory():
446 self.log.info("Installation prefix => " + self.prefix_directory())
447 self.log.info("Products directory => " + self.products_directory())
448 self.log.info("Build directory => " + self.build_directory())
449
450 self.log.debug('CMake environment =>')
451
452 keys = environ.keys()
453 for key in sorted(keys):
454 if key in ['PATH', 'CXX'] or key.endswith('FLAGS'):
455 self.log.debug(' %s=%s' % (key, environ[key]))
456
457 self.log.debug('CMake arguments =>')
458
459 for arg in conf_args + list(args):
460 self.log.debug(' %s' % arg)
461
462 def phase_sloc(self, *args):
463 self.log.info('Executing phase: sloc')
464 self.execute('sloccount', 'src', 'python', 'test')
465
466 #########################################################################
467 # Update local files with the latest information #
468 #########################################################################
469
470 def phase_pull(self, *args):
471 self.log.info('Executing phase: pull')
472 if self.git_working_tree():
473 self.execute('git', 'pull')
474
475 #########################################################################
476 # Automatic installation of build dependencies #
477 #########################################################################
478
479 def phase_dependencies(self, *args):
480 self.log.info('Executing phase: dependencies')
481
482 self.log.info("Installing Ledger's build dependencies ...")
483
484 system = os.uname().sysname
485
486 if system == 'Darwin':
487 if shutil.which('port'):
488 self.log.info('Looks like you are using MacPorts on macOS')
489 packages = [
490 'sudo', 'port', 'install', '-f',
491 'automake', 'autoconf', 'libtool',
492 'python310',
493 'libiconv',
494 'zlib',
495 'gmp', 'mpfr',
496 'ncurses',
497 'gettext',
498 'libedit',
499 'texlive-xetex', 'doxygen', 'graphviz', 'texinfo',
500 'lcov', 'sloccount'
501 ] + BoostInfo().dependencies('darwin-macports', self.options.python)
502 self.log.info('Executing: ' + ' '.join(packages))
503 self.execute(*packages)
504 elif shutil.which('brew'):
505 self.log.info('Looks like you are using Homebrew on macOS')
506 packages = [
507 'brew', 'install',
508 'cmake', 'ninja',
509 'mpfr', 'gmp',
510 'gpgme', 'gpgmepp',
511 ] + BoostInfo().dependencies('darwin-homebrew', self.options.python)
512 self.log.info('Executing: ' + ' '.join(packages))
513 self.execute(*packages)
514 elif shutil.which('fink'):
515 self.log.info('Looks like you are using Fink on macOS')
516 self.log.error("I don't know the package names for Fink yet!")
517 sys.exit(1)
518 elif shutil.which('nix'):
519 self.log.info('Looks like you are using Nixpkgs on macOS')
520 packages = [
521 'nix', 'develop',
522 ]
523 self.log.info('Executing: ' + ' '.join(packages))
524 self.execute(*packages)
525
526 elif system == 'Linux':
527 is_ubuntu = False
528 if exists('/etc/issue'):
529 issue_name = open('/etc/issue').readline()
530 if issue_name.startswith('Ubuntu'):
531 info = dict([line.strip().split('=', 1)
532 for line in open('/etc/lsb-release')])
533 release = info['DISTRIB_CODENAME']
534 is_ubuntu = True
535 self.log.info('Looks like you are using APT on Ubuntu ' + release)
536 packages = [
537 'sudo', 'apt-get', 'install',
538 'build-essential',
539 'libgpgme-dev',
540 'libgpgmepp-dev',
541 'libgpg-error-dev',
542 ]
543 release_list = [
544 "noble", # 24.04
545 "jammy", # 22.04
546 "focal", # 20.04
547 "eoan", # 19.10
548 "bionic", # 18.04
549 "xenial", # 16.04
550 "trusty", # 14.04
551 "saucy", # 13.10
552 "precise", # 12.04
553 ]
554 if release in release_list:
555 # Common Ubuntu packages
556 packages.extend(
557 [
558 "cmake",
559 "libgmp-dev",
560 "libmpfr-dev",
561 "libgpgmepp-dev",
562 "gettext",
563 "zlib1g-dev",
564 "libbz2-dev",
565 "libedit-dev",
566 "texinfo",
567 "lcov",
568 "sloccount",
569 (
570 "python3-dev"
571 if release in ["noble", "jammy"]
572 else "python-dev"
573 ),
574 ]
575 )
576 # doxygen & ninja build
577 if release != 'precise':
578 packages.extend(['doxygen','ninja-build'])
579 # libutfcpp-dev
580 if release != 'saucy':
581 packages.extend(['libutfcpp-dev'])
582 # Precise (Ubuntu 12.04) need GNU libtool
583 if release == 'precise':
584 packages.extend(['libtool'])
585 else:
586 self.log.info('I do not recognize your version of Ubuntu!')
587 packages = None
588 if packages:
589 packages.extend(
590 BoostInfo().dependencies('ubuntu-' + release, self.options.python)
591 )
592 self.log.info('Executing: ' + ' '.join(packages))
593 self.execute(*packages)
594 elif issue_name.startswith('Arch Linux'):
595 self.log.info('Looks like you are using Pacman on Arch Linux')
596 packages = [
597 'sudo', 'pacman', '-S', '--noconfirm',
598 'base-devel',
599 'boost',
600 'doxygen',
601 'gmp',
602 'graphviz',
603 'lcov',
604 'libedit',
605 'mpfr',
606 'sloccount',
607 'utf8cpp'
608 ]
609 self.log.info('Executing: ' + ' '.join(packages))
610 self.execute(*packages)
611
612 # Since Ubuntu also contains '/etc/debian_version', Ubuntu should skip it
613 if not is_ubuntu and exists('/etc/debian_version'):
614 release = open('/etc/debian_version').readline()
615 if release.startswith('trixie'):
616 self.log.info(f'Looks like you are using APT on Debian {release}')
617 packages = [
618 'sudo', 'apt', 'install', '-y', '--no-install-recommends',
619 'clang',
620 'cmake',
621 'ninja',
622 'libboost-dev',
623 'libmpfr-dev',
624 'libgmp-dev',
625 'libicu-dev',
626 'libedit-dev',
627 'libutfcpp-dev',
628 'gettext',
629 'texinfo',
630 'doxygen',
631 'graphviz',
632 'lcov',
633 'sloccount',
634 ]
635 self.log.info('Executing: ' + ' '.join(packages))
636 self.execute(*packages)
637 else:
638 self.log.info(f"I do not recognize your version '{release}' of Debian!")
639
640 if exists('/etc/redhat-release'):
641 release = open('/etc/redhat-release').readline()
642 if release.startswith('CentOS'):
643 self.log.info('Looks like you are using YUM on CentOS')
644 packages = [
645 'sudo', 'yum', 'install',
646 'gcc',
647 'gcc-c++',
648 'compat-gcc-*',
649 'make',
650 'libtool',
651 'autoconf',
652 'automake',
653 'zlib-devel',
654 'bzip2-devel',
655 'python-devel',
656 'gmp-devel',
657 'gettext-devel',
658 #'mpfr-devel'
659 'libedit-devel',
660 #'texlive-full',
661 #'doxygen',
662 #'graphviz',
663 'texinfo',
664 #'lcov',
665 #'sloccount'
666 ]
667 self.log.info('Executing: ' + ' '.join(packages))
668 self.execute(*packages)
669 elif release.startswith('Fedora release 20'):
670 self.log.info('Looks like you are using YUM on Fedora 20')
671 packages = [
672 'sudo', 'yum', 'install',
673 'boost-devel',
674 'bzip2-devel',
675 'cmake',
676 'doxygen',
677 'gcc',
678 'gcc-c++',
679 'gettext',
680 'gettext-devel',
681 'gmp-devel',
682 'lcov',
683 'libedit-devel',
684 'mpfr-devel',
685 'ninja-build',
686 'python-devel',
687 'sloccount',
688 'texinfo',
689 'zlib-devel'
690 ]
691 self.log.info('Executing: ' + ' '.join(packages))
692 self.execute(*packages)
693
694 elif system.startswith('CYGWIN'):
695 self.log.info('Looks like you are using Cygwin')
696 self.log.info('Please install the dependencies manually.')
697
698 #########################################################################
699 # Determine the system's basic configuration #
700 #########################################################################
701
702 def setup_for_johnw(self):
703 self.configure_args.append('-DCMAKE_EXPORT_COMPILE_COMMANDS:BOOL=ON')
704
705 if not self.options.compiler:
706 self.configure_args.append('-DCMAKE_CXX_COMPILER:PATH=/usr/local/bin/clang++')
707
708 if self.current_flavor == 'opt':
709 self.configure_args.append('-DCMAKE_CXX_FLAGS_RELEASE:STRING=-O3')
710 self.configure_args.append('-DCMAKE_EXE_LINKER_FLAGS:STRING=-O3')
711 self.configure_args.append('-DCMAKE_SHARED_LINKER_FLAGS:STRING=-O3')
712 self.configure_args.append('-DCMAKE_MODULE_LINKER_FLAGS:STRING=-O3')
713 #else:
714 # self.CXXFLAGS.append('-g -O1 -faddress-sanitizer')
715 # self.LDFLAGS.append('-g -O1 -faddress-sanitizer')
716
717 self.configure_args.append(self.source_dir)
718
719 else:
720 self.configure_args.append('-DCMAKE_CXX_COMPILER:PATH=' + self.options.compiler)
721 self.configure_args.append('-DCMAKE_INCLUDE_PATH:STRING=/usr/local/include')
722 self.configure_args.append('-DCMAKE_LIBRARY_PATH:STRING=/usr/local/lib')
723 self.configure_args.append('-DBOOST_ROOT=/usr/local')
724 self.configure_args.append(self.source_dir)
725
726 def setup_for_system(self):
727 system = os.uname().sysname
728 self.log.info('System type is => ' + system)
729
730 if self.options.enable_doxygen:
731 self.configure_args.append('-DUSE_DOXYGEN=1')
732 if self.options.python:
733 self.configure_args.append('-DUSE_PYTHON=1')
734
735 if system.startswith('CYGWIN'):
736 self.configure_args.append('-G')
737 self.configure_args.append('Unix Makefiles')
738 elif system.startswith('MINGW'):
739 self.configure_args.append('-G')
740 self.configure_args.append('MSYS Makefiles')
741 elif self.options.use_ninja:
742 self.configure_args.append('-GNinja')
743
744 if exists('/Users/johnw/Projects/ledger/plan/TODO'):
745 self.setup_for_johnw()
746
747 def setup_flavor(self):
748 self.setup_for_system()
749
750 if 'setup_flavor_' + self.current_flavor not in PrepareBuild.__dict__:
751 self.log.error('Unknown build flavor "%s"' % self.current_flavor)
752 sys.exit(1)
753
754 self.log.info('Setting up build flavor => ' + self.current_flavor)
755 PrepareBuild.__dict__['setup_flavor_' + self.current_flavor](self)
756
757 def escape_string(self, data):
758 return re.sub(r'(["\\\\])', '\\\\\\1', data)
759
760 def finalize_config(self):
761 self.setup_flavor()
762
763 for var in ('CXXFLAGS', 'LDFLAGS'):
764 value = self.__dict__[var]
765 if value:
766 first = not self.envvars[var]
767 for member in value:
768 #escaped = self.escape_string(member)
769 #if member != escaped:
770 # member = escaped
771 if first:
772 first = False
773 else:
774 self.envvars[var] += ' '
775 self.envvars[var] += member
776 self.log.debug('Final value of %s: %s' %
777 (var, self.envvars[var]))
778
779 elif var in self.envvars:
780 del self.envvars[var]
781
782 #########################################################################
783 # Options that can modify any build flavor #
784 #########################################################################
785
786 def option_local(self, option=None, opt_str=None, value=None, parser=None):
787 self.log.debug('Saw option --local')
788 self.options.build_dir = self.source_dir
789
790 def option_help(self, option=None, opt_str=None, value=None, parser=None):
791 self.phase_help()
792
793 #########################################################################
794 # The various build flavors #
795 #########################################################################
796
797 def setup_flavor_default(self):
798 pass
799
800 def setup_flavor_debug(self):
801 self.configure_args.append('-DCMAKE_BUILD_TYPE=Debug')
802
803 def setup_flavor_opt(self):
804 self.configure_args.append('-DCMAKE_BUILD_TYPE=Release')
805 self.configure_args.append('-DNO_ASSERTS=1')
806
807 def setup_flavor_gcov(self):
808 # NO_ASSERTS is set so that branch coverage ignores the never-taken
809 # else branch inside assert statements.
810 self.configure_args.append('-DCMAKE_BUILD_TYPE=Debug')
811 self.configure_args.append('-DNO_ASSERTS=1')
812 self.configure_args.append('-DCLANG_GCOV=1')
813
814 self.CXXFLAGS.append('-fprofile-arcs')
815 self.CXXFLAGS.append('-ftest-coverage')
816 self.LDFLAGS.append('-fprofile-arcs')
817 self.LDFLAGS.append('-ftest-coverage')
818
819 if not self.options.compiler or self.options.compiler == "clang-3.1":
820 self.LDFLAGS.append('-lgcov')
821
822 def setup_flavor_gprof(self):
823 self.configure_args.append('-DCMAKE_BUILD_TYPE=Debug')
824
825 self.CXXFLAGS.append('-pg')
826 self.LDFLAGS.append('-pg')
827
828 #########################################################################
829 # Configure build tree using CMake #
830 #########################################################################
831
832 def configure_environment(self):
833 self.finalize_config()
834
835 environ = dict(os.environ)
836 for key, value in self.envvars.items():
837 if value:
838 environ[key] = value
839
840 if self.build_directory() == self.source_dir:
841 conf_args = ['cmake']
842 else:
843 conf_args = ['cmake', self.source_dir]
844
845 if not which('cmake'):
846 self.log.error("Cannot find CMake, please check your PATH")
847 sys.exit(1)
848
849 for var in ('CXX', 'CXXFLAGS', 'LDFLAGS'):
850 if self.envvars.get(var) and (var.endswith('FLAGS')
851 or exists(self.envvars[var])):
852 if var == 'CXX':
853 conf_args.append('-DCMAKE_CXX_COMPILER=%s' %
854 self.envvars[var])
855 elif var == 'CXXFLAGS':
856 conf_args.append('-DCMAKE_CXX_FLAGS=%s' %
857 self.envvars[var])
858 elif var == 'LDFLAGS':
859 conf_args.append('-DCMAKE_EXE_LINKER_FLAGS=%s' %
860 self.envvars[var])
861
862 if self.options.boost_root:
863 conf_args.append('-DBOOST_ROOT=%s' %
864 self.options.boost_root)
865 conf_args.append('-DBoost_NO_SYSTEM_PATHS=TRUE')
866 if self.options.boost_suffix:
867 conf_args.append('-DBoost_COMPILER=%s' %
868 self.options.boost_suffix)
869 if self.options.boost_include:
870 conf_args.append('-DBOOST_INCLUDEDIR=%s' %
871 self.options.boost_include)
872
873 if self.prefix_directory():
874 conf_args.append('-DCMAKE_INSTALL_PREFIX=%s' % self.prefix_directory())
875
876 return (environ, conf_args + self.configure_args)
877
878 def phase_configure(self, *args):
879 self.log.info('Executing phase: configure')
880
881 self.configured = True
882
883 environ, conf_args = self.configure_environment()
884 for arg in args:
885 if arg: conf_args.append(arg)
886
887 build_dir = self.ensure(self.build_directory())
888 try:
889 os.chdir(build_dir)
890
891 need_to_config = not isfile('rules.ninja' if self.options.use_ninja else 'Makefile')
892 if need_to_config:
893 self.log.debug('Source => ' + self.source_dir)
894 self.log.debug('Build => ' + build_dir)
895 self.log.debug('configure env => ' + str(environ))
896 self.log.debug('configure args => ' + str(conf_args))
897
898 configure = Popen(conf_args, shell=False, env=environ)
899 retcode = configure.wait()
900 if retcode < 0:
901 self.log.error("Child was terminated by signal", -retcode)
902 sys.exit(1)
903 elif retcode != 0:
904 self.log.error("Execution failed: " + ' '.join(conf_args))
905 sys.exit(1)
906 else:
907 self.log.debug('configure does not need to be run')
908
909 finally:
910 os.chdir(self.source_dir)
911
912 def phase_config(self, *args):
913 self.log.info('Executing phase: config')
914 self.phase_configure(*args)
915 if self.should_clean:
916 self.phase_clean()
917
918 #########################################################################
919 # Builds products from the sources #
920 #########################################################################
921
922 def phase_make(self, *args):
923 self.log.info('Executing phase: make')
924
925 config_args = []
926 make_args = []
927
928 for arg in args:
929 if arg.startswith('--') or arg.startswith('-D'):
930 config_args.append(arg)
931 else:
932 make_args.append(arg)
933
934 if self.options.jobs > 1 and self.current_flavor != 'gcov':
935 make_args.append('-j%d' % self.options.jobs)
936
937 if self.options.verbose:
938 make_args.append('-v' if self.options.use_ninja else 'VERBOSE=1')
939
940 self.log.debug('Configure arguments => ' + str(config_args))
941 self.log.debug('Makefile arguments => ' + str(make_args))
942
943 if not self.configured:
944 self.phase_config(*config_args)
945
946 build_dir = self.ensure(self.build_directory())
947 try:
948 self.log.debug('Changing directory to ' + build_dir)
949 os.chdir(build_dir)
950
951 self.execute(*(['ninja' if self.options.use_ninja else 'make'] +
952 make_args))
953 finally:
954 os.chdir(self.source_dir)
955
956 def phase_check(self, *args):
957 self.log.info('Executing phase: check')
958 build_dir = self.ensure(self.build_directory())
959 try:
960 self.log.debug('Changing directory to ' + build_dir)
961 os.chdir(build_dir)
962
963 make_args = list(args)
964 if self.options.jobs > 1:
965 make_args.append('-j%d' % self.options.jobs)
966
967 self.execute(*(['ctest'] + list(make_args)))
968 finally:
969 os.chdir(self.source_dir)
970
971 def phase_update(self, *args):
972 self.log.info('Executing phase: update')
973 self.phase_pull()
974 self.phase_make(*args)
975
976 #########################################################################
977 # Build directory cleaning phases #
978 #########################################################################
979
980 def phase_clean(self, *args):
981 self.log.info('Executing phase: clean')
982 self.phase_make('clean')
983
984 def phase_gitclean(self, *args):
985 self.log.info('Executing phase: gitclean')
986 if self.git_working_tree():
987 self.execute('git', 'clean', '-dfx')
988
989 #########################################################################
990 # Other build phases #
991 #########################################################################
992
993 def configure_flavor(self, flavor, reset=True):
994 self.initialize() # reset everything
995 self.current_flavor = flavor
996 self.options.build_dir = None # use the build/ tree
997 self.options.prefix_dir = None
998
999 if reset and exists(self.build_directory()) and \
1000 isdir(self.build_directory()):
1001 self.log.info('=== Wiping build directory %s ===' %
1002 self.build_directory())
1003 try:
1004 shutil.rmtree(self.build_directory())
1005 except:
1006 self.execute('chmod', '-R', 'u+w', self.build_directory())
1007 self.execute('rm', '-fr', self.build_directory())
1008
1009 def phase_rsync(self, *args):
1010 self.log.info('Executing phase: rsync')
1011
1012 proof_dir = 'ledger-proof'
1013
1014 if self.options.python:
1015 proof_dir += "-python"
1016 if self.options.compiler:
1017 proof_dir += "-" + basename(self.options.compiler)
1018
1019 source_copy_dir = join(self.ensure(self.products_directory()), proof_dir)
1020
1021 self.execute('rsync', '-a', '--delete', '--exclude=/dist/',
1022 '--exclude=.git/', '--exclude=b/',
1023 '--exclude=/lib/boost-release/',
1024 '--exclude=/archive/', '--exclude=/build/',
1025 '%s/' % self.source_dir, '%s/' % source_copy_dir)
1026
1027 self.source_dir = source_copy_dir
1028
1029 def phase_proof(self, *args):
1030 self.log.info('Executing phase: proof')
1031
1032 self.log.info('=== Copying source tree ===')
1033 self.phase_rsync()
1034
1035 self.phase_makeall(reset=True, *args)
1036
1037 self.configure_flavor('opt', reset=False)
1038 self.log.info('=== Testing opt ===')
1039 # jww (2012-05-20): Can't use fullcheck yet
1040 #self.phase_make('fullcheck')
1041 self.phase_make('test')
1042
1043 self.configure_flavor('gcov', reset=False)
1044 self.log.info('=== Testing gcov ===')
1045 #self.phase_make('check')
1046 self.phase_make('test')
1047
1048 self.configure_flavor('default', reset=False)
1049 self.log.info('=== Testing default ===')
1050 #self.phase_make('fullcheck')
1051 self.phase_make('test')
1052 # jww (2012-05-20): docs are not working yet
1053 #self.phase_make('docs')
1054
1055 self.configure_flavor('debug', reset=False)
1056 self.log.info('=== Testing debug ===')
1057 #self.phase_make('fullcheck')
1058 self.phase_make('test')
1059
1060 def phase_makeall(self, reset=False, *args):
1061 self.log.info('Executing phase: makeall')
1062
1063 self.configure_flavor('opt', reset)
1064 self.log.info('=== Building opt ===')
1065 self.phase_make(*args)
1066
1067 self.configure_flavor('gcov', reset)
1068 self.log.info('=== Building gcov ===')
1069 self.phase_make(*args)
1070
1071 self.configure_flavor('default', reset)
1072 self.log.info('=== Building default ===')
1073 self.phase_make(*args)
1074
1075 self.configure_flavor('debug', reset)
1076 self.log.info('=== Building debug ===')
1077 self.phase_make(*args)
1078
1079 #########################################################################
1080 # Help #
1081 #########################################################################
1082
1083 def phase_help(self, *args):
1084 self.option_parser.print_help()
1085
1086 print("""
1087 Of the optional ARGS, the first is an optional build FLAVOR, with the default
1088 being 'debug':
1089
1090 default Regular autoconf settings
1091 debug Debugging and --verify support (default)
1092 opt Full optimizations
1093 gcov Coverage analysis
1094 gprof Code profiling (for macOS, just use: 'shark -i ledger ...')
1095
1096 Next is the optional build PHASE, with 'config' being the default:
1097
1098 clean Runs 'make clean' in the build directory
1099 config Configure the environment for building
1100 dependencies Automatically install all necessary build dependencies
1101 gitclean Runs 'git clean -dfx', which *really* cleans things
1102 help Displays this help text
1103 info Show information about the build environment
1104 make Do a make in the build directory
1105 proof Proves Ledger by building and testing every flavor
1106 pull Pulls the latest, and updates local config if need be
1107 update Does it all, updates your environment and re-make's
1108
1109 There are many other build phases, though most are not of interest to the
1110 typical user:
1111
1112 configure Runs just cmake
1113 do_all Runs makeall followed by proof
1114 gettext Initialize gettext support
1115 makeall Build every flavor there is
1116 products Report the products directory path
1117 rsync Rsync a copy of the source tree into Products
1118 sloc Report total Source Lines Of Code
1119 version Output current HEAD version to version.m4
1120
1121 NOTE: If you wish to pass options to CMake or make, add "--" followed by
1122 your options. Those starting with "-D" or "--" will be passed on to CMake,
1123 positional arguments and other options will be passed to make.
1124 For the 'config' and 'configure' phase everything will be passed to CMake.
1125
1126 Here are some real-world examples:
1127
1128 ./acprep
1129 ./acprep --python
1130 ./acprep opt make
1131 ./acprep make doc -- -DBUILD_WEB_DOCS=1""")
1132 sys.exit(0)
1133
1134 PrepareBuild().run()