build.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875
  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2014 wkhtmltopdf authors
  4. #
  5. # This file is part of wkhtmltopdf.
  6. #
  7. # wkhtmltopdf is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU Lesser General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # wkhtmltopdf is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU Lesser General Public License
  18. # along with wkhtmltopdf. If not, see <http:#www.gnu.org/licenses/>.
  19. # --------------------------------------------------------------- CONFIGURATION
  20. OPENSSL = {
  21. 'url' : 'http://www.openssl.org/source/openssl-1.0.1g.tar.gz',
  22. 'sha1' : 'b28b3bcb1dc3ee7b55024c9f795be60eb3183e3c',
  23. 'build' : {
  24. 'msvc*-win32*': {
  25. 'configure' : 'VC-WIN32 no-asm',
  26. 'debug' : 'debug-VC-WIN32 no-asm',
  27. 'build' : ['ms\\do_ms.bat', 'nmake /f ms\\nt.mak install'],
  28. 'libs' : ['ssleay32.lib', 'libeay32.lib'],
  29. 'os_libs' : '-lUser32 -lAdvapi32 -lGdi32 -lCrypt32'
  30. },
  31. 'msvc*-win64*': {
  32. 'configure' : 'VC-WIN64A',
  33. 'debug' : 'debug-VC-WIN64A',
  34. 'build' : ['ms\\do_win64a.bat', 'nmake /f ms\\nt.mak install'],
  35. 'libs' : ['ssleay32.lib', 'libeay32.lib'],
  36. 'os_libs' : '-lUser32 -lAdvapi32 -lGdi32 -lCrypt32'
  37. },
  38. 'mingw-w64-cross-win32': {
  39. 'configure' : '--cross-compile-prefix=i686-w64-mingw32- no-shared no-asm mingw64',
  40. 'build' : ['make', 'make install_sw'],
  41. 'libs' : ['libssl.a', 'libcrypto.a'],
  42. 'os_libs' : '-lws2_32 -lgdi32 -lcrypt32'
  43. },
  44. 'mingw-w64-cross-win64': {
  45. 'configure' : '--cross-compile-prefix=x86_64-w64-mingw32- no-shared no-asm mingw64',
  46. 'build' : ['make', 'make install_sw'],
  47. 'libs' : ['libssl.a', 'libcrypto.a'],
  48. 'os_libs' : '-lws2_32 -lgdi32 -lcrypt32'
  49. }
  50. }
  51. }
  52. QT_CONFIG = {
  53. 'common' : [
  54. '-opensource',
  55. '-confirm-license',
  56. '-fast',
  57. '-release',
  58. '-static',
  59. '-graphicssystem raster',
  60. '-webkit',
  61. '-exceptions', # required by XmlPatterns
  62. '-xmlpatterns', # required for TOC support
  63. '-qt-zlib', # use bundled versions of libraries
  64. '-qt-libpng',
  65. '-qt-libjpeg',
  66. '-no-libmng',
  67. '-no-libtiff',
  68. '-no-accessibility',
  69. '-no-stl',
  70. '-no-qt3support',
  71. '-no-phonon',
  72. '-no-phonon-backend',
  73. '-no-opengl',
  74. '-no-declarative',
  75. '-no-script',
  76. '-no-scripttools',
  77. '-no-sql-ibase',
  78. '-no-sql-mysql',
  79. '-no-sql-odbc',
  80. '-no-sql-psql',
  81. '-no-sql-sqlite',
  82. '-no-sql-sqlite2',
  83. '-no-mmx',
  84. '-no-3dnow',
  85. '-no-sse',
  86. '-no-sse2',
  87. '-no-multimedia',
  88. '-nomake demos',
  89. '-nomake docs',
  90. '-nomake examples',
  91. '-nomake tools',
  92. '-nomake tests',
  93. '-nomake translations'
  94. ],
  95. 'msvc': [
  96. '-mp',
  97. '-qt-style-windows',
  98. '-qt-style-cleanlooks',
  99. '-no-style-windowsxp',
  100. '-no-style-windowsvista',
  101. '-no-style-plastique',
  102. '-no-style-motif',
  103. '-no-style-cde',
  104. '-openssl-linked' # static linkage for OpenSSL
  105. ],
  106. 'posix': [
  107. '-silent', # perform a silent build
  108. '-xrender', # xrender support is required
  109. '-largefile',
  110. '-rpath',
  111. '-openssl', # load OpenSSL binaries at runtime
  112. '-no-dbus',
  113. '-no-nis',
  114. '-no-cups',
  115. '-no-iconv',
  116. '-no-pch',
  117. '-no-gtkstyle',
  118. '-no-nas-sound',
  119. '-no-sm',
  120. '-no-xshape',
  121. '-no-xinerama',
  122. '-no-xcursor',
  123. '-no-xfixes',
  124. '-no-xrandr',
  125. '-no-mitshm',
  126. '-no-xinput',
  127. '-no-xkb',
  128. '-no-glib',
  129. '-no-gstreamer',
  130. '-D ENABLE_VIDEO=0', # required as otherwise gstreamer gets linked in
  131. '-no-openvg',
  132. '-no-xsync',
  133. '-no-audio-backend',
  134. '-no-sse3',
  135. '-no-ssse3',
  136. '-no-sse4.1',
  137. '-no-sse4.2',
  138. '-no-avx',
  139. '-no-neon'
  140. ],
  141. 'mingw-w64-cross' : [
  142. '-silent', # perform a silent build
  143. '-openssl-linked', # static linkage for OpenSSL
  144. '-no-reduce-exports',
  145. '-no-rpath',
  146. '-xplatform win32-g++-4.6'
  147. ],
  148. 'osx': [
  149. '-no-framework',
  150. '-no-dwarf2',
  151. '-xrender', # xrender support is required
  152. '-openssl', # load OpenSSL binaries at runtime
  153. '-largefile',
  154. '-rpath'
  155. ]
  156. }
  157. BUILDERS = {
  158. 'msvc2008-win32': 'msvc',
  159. 'msvc2008-win64': 'msvc',
  160. 'msvc2010-win32': 'msvc',
  161. 'msvc2010-win64': 'msvc',
  162. 'msvc2012-win32': 'msvc',
  163. 'msvc2012-win64': 'msvc',
  164. 'msvc2013-win32': 'msvc',
  165. 'msvc2013-win64': 'msvc',
  166. 'msvc-winsdk71-win32': 'msvc_winsdk71',
  167. 'msvc-winsdk71-win64': 'msvc_winsdk71',
  168. 'setup-mingw-w64': 'setup_mingw64',
  169. 'setup-schroot-centos5': 'setup_schroot',
  170. 'setup-schroot-centos6': 'setup_schroot',
  171. 'setup-schroot-wheezy': 'setup_schroot',
  172. 'setup-schroot-trusty': 'setup_schroot',
  173. 'setup-schroot-precise': 'setup_schroot',
  174. 'update-all-schroots': 'update_schroot',
  175. 'centos5-i386': 'linux_schroot',
  176. 'centos5-amd64': 'linux_schroot',
  177. 'centos6-i386': 'linux_schroot',
  178. 'centos6-amd64': 'linux_schroot',
  179. 'wheezy-i386': 'linux_schroot',
  180. 'wheezy-amd64': 'linux_schroot',
  181. 'trusty-i386': 'linux_schroot',
  182. 'trusty-amd64': 'linux_schroot',
  183. 'precise-i386': 'linux_schroot',
  184. 'precise-amd64': 'linux_schroot',
  185. 'mingw-w64-cross-win32': 'mingw64_cross',
  186. 'mingw-w64-cross-win64': 'mingw64_cross',
  187. 'posix-local': 'posix_local',
  188. 'osx-cocoa-x86-64': 'osx',
  189. 'osx-carbon-i386': 'osx'
  190. }
  191. CHROOT_SETUP = {
  192. 'wheezy': [
  193. ('debootstrap', 'wheezy', 'http://ftp.us.debian.org/debian/'),
  194. ('write_file', 'etc/apt/sources.list', """
  195. deb http://ftp.debian.org/debian/ wheezy main contrib non-free
  196. deb http://ftp.debian.org/debian/ wheezy-updates main contrib non-free
  197. deb http://security.debian.org/ wheezy/updates main contrib non-free
  198. deb-src http://ftp.debian.org/debian/ wheezy main contrib non-free
  199. deb-src http://ftp.debian.org/debian/ wheezy-updates main contrib non-free
  200. deb-src http://security.debian.org/ wheezy/updates main contrib non-free"""),
  201. ('shell', 'apt-get update'),
  202. ('shell', 'apt-get dist-upgrade --assume-yes'),
  203. ('shell', 'apt-get install --assume-yes xz-utils'),
  204. ('shell', 'apt-get build-dep --assume-yes libqt4-core'),
  205. ('write_file', 'update.sh', 'apt-get update\napt-get dist-upgrade --assume-yes\n'),
  206. ('schroot_conf', 'Debian Wheezy')
  207. ],
  208. 'trusty': [
  209. ('debootstrap', 'trusty', 'http://archive.ubuntu.com/ubuntu/'),
  210. ('write_file', 'etc/apt/sources.list', """
  211. deb http://archive.ubuntu.com/ubuntu/ trusty main restricted universe multiverse
  212. deb http://archive.ubuntu.com/ubuntu/ trusty-updates main restricted universe multiverse
  213. deb http://archive.ubuntu.com/ubuntu/ trusty-security main restricted universe multiverse
  214. deb-src http://archive.ubuntu.com/ubuntu/ trusty main restricted universe multiverse
  215. deb-src http://archive.ubuntu.com/ubuntu/ trusty-updates main restricted universe multiverse
  216. deb-src http://archive.ubuntu.com/ubuntu/ trusty-security main restricted universe multiverse"""),
  217. ('shell', 'apt-get update'),
  218. ('shell', 'apt-get dist-upgrade --assume-yes'),
  219. ('shell', 'apt-get install --assume-yes xz-utils'),
  220. ('shell', 'apt-get build-dep --assume-yes libqt4-core'),
  221. ('write_file', 'update.sh', 'apt-get update\napt-get dist-upgrade --assume-yes\n'),
  222. ('schroot_conf', 'Ubuntu Trusty')
  223. ],
  224. 'precise': [
  225. ('debootstrap', 'precise', 'http://archive.ubuntu.com/ubuntu/'),
  226. ('write_file', 'etc/apt/sources.list', """
  227. deb http://archive.ubuntu.com/ubuntu/ precise main restricted universe multiverse
  228. deb http://archive.ubuntu.com/ubuntu/ precise-updates main restricted universe multiverse
  229. deb http://archive.ubuntu.com/ubuntu/ precise-security main restricted universe multiverse
  230. deb-src http://archive.ubuntu.com/ubuntu/ precise main restricted universe multiverse
  231. deb-src http://archive.ubuntu.com/ubuntu/ precise-updates main restricted universe multiverse
  232. deb-src http://archive.ubuntu.com/ubuntu/ precise-security main restricted universe multiverse"""),
  233. ('shell', 'apt-get update'),
  234. ('shell', 'apt-get dist-upgrade --assume-yes'),
  235. ('shell', 'apt-get install --assume-yes xz-utils'),
  236. ('shell', 'apt-get build-dep --assume-yes libqt4-core'),
  237. ('write_file', 'update.sh', 'apt-get update\napt-get dist-upgrade --assume-yes\n'),
  238. ('schroot_conf', 'Ubuntu Precise')
  239. ],
  240. 'centos5': [
  241. ('rinse', 'centos-5'),
  242. ('shell', 'yum update -y'),
  243. ('append_file:amd64', 'etc/yum.conf', 'exclude = *.i?86\n'),
  244. ('shell', 'yum install -y gcc gcc-c++ make qt4-devel openssl-devel diffutils perl xz'),
  245. ('write_file', 'update.sh', 'yum update -y\n'),
  246. ('schroot_conf', 'CentOS 5')
  247. ],
  248. 'centos6': [
  249. ('rinse', 'centos-6'),
  250. ('shell', 'yum update -y'),
  251. ('append_file:amd64', 'etc/yum.conf', 'exclude = *.i?86\n'),
  252. ('shell', 'yum install -y gcc gcc-c++ make qt4-devel openssl-devel diffutils perl tar xz'),
  253. ('write_file', 'update.sh', 'yum update -y\n'),
  254. ('schroot_conf', 'CentOS 6')
  255. ]
  256. }
  257. # --------------------------------------------------------------- HELPERS
  258. import os, sys, platform, subprocess, shutil, re, fnmatch, multiprocessing, urllib, hashlib, tarfile
  259. from os.path import exists
  260. CPU_COUNT = max(2, multiprocessing.cpu_count()-1) # leave one CPU free
  261. def rchop(s, e):
  262. if s.endswith(e):
  263. return s[:-len(e)]
  264. return s
  265. def error(msg):
  266. print msg
  267. sys.exit(1)
  268. def shell(cmd):
  269. ret = os.system(cmd)
  270. if ret != 0:
  271. error("command failed: exit code %d" % ret)
  272. def get_output(*cmd):
  273. try:
  274. return subprocess.check_output(cmd, stderr=subprocess.STDOUT).strip()
  275. except subprocess.CalledProcessError:
  276. return None
  277. def rmdir(path):
  278. if exists(path):
  279. shutil.rmtree(path)
  280. def mkdir_p(path):
  281. if not exists(path):
  282. os.makedirs(path)
  283. def get_version(basedir):
  284. text = open(os.path.join(basedir, '..', 'VERSION'), 'r').read()
  285. if '-' not in text:
  286. return (text, text)
  287. version = text[:text.index('-')]
  288. os.chdir(os.path.join(basedir, '..'))
  289. hash = get_output('git', 'rev-parse', '--short', 'HEAD')
  290. if not hash:
  291. return (text, version)
  292. return ('%s-%s' % (version, hash), version)
  293. def qt_config(key, *opts):
  294. input, output = [], []
  295. input.extend(QT_CONFIG['common'])
  296. input.extend(QT_CONFIG[key])
  297. input.extend(opts)
  298. cfg = os.environ.get('WKHTMLTOX_QT_CONFIG')
  299. if cfg:
  300. input.extend(cfg.split())
  301. for arg in input:
  302. if not arg.startswith('remove:-'):
  303. output.append(arg)
  304. elif arg[1+arg.index(':'):] in output:
  305. output.remove(arg[1+arg.index(':'):])
  306. return ' '.join(output)
  307. def download_file(url, dir, sha1):
  308. name = url.split('/')[-1]
  309. loc = os.path.join(dir, name)
  310. if os.path.exists(loc):
  311. hash = hashlib.sha1(open(loc, 'rb').read()).hexdigest()
  312. if hash != sha1:
  313. error('Checksum mismatch for %s' % name)
  314. os.remove(loc)
  315. return loc
  316. def hook(cnt, bs, total):
  317. pct = int(cnt*bs*100/total)
  318. sys.stdout.write("\rDownloading: %s [%d%%]" % (name, pct))
  319. sys.stdout.flush()
  320. urllib.urlretrieve(url, loc, reporthook=hook)
  321. sys.stdout.write("\r")
  322. sys.stdout.flush()
  323. hash = hashlib.sha1(open(loc, 'rb').read()).hexdigest()
  324. if hash != sha1:
  325. error('Checksum mismatch for %s' % name)
  326. os.remove(loc)
  327. sys.stdout.write("\rDownloaded: %s [checksum OK]\n" % name)
  328. sys.stdout.flush()
  329. return loc
  330. def build_openssl(config, basedir):
  331. cfg = None
  332. for key in OPENSSL['build']:
  333. if fnmatch.fnmatch(config, key):
  334. cfg = key
  335. if not cfg:
  336. return
  337. dstdir = os.path.join(basedir, config, 'openssl')
  338. location = download_file(OPENSSL['url'], basedir, OPENSSL['sha1'])
  339. relname = os.path.basename(location)[:os.path.basename(location).index('.tar')]
  340. srcdir = os.path.join(basedir, relname)
  341. def is_compiled():
  342. compiled = exists(os.path.join(dstdir, 'include', 'openssl', 'ssl.h'))
  343. for lib in OPENSSL['build'][cfg]['libs']:
  344. compiled = compiled and exists(os.path.join(dstdir, 'lib', lib))
  345. return compiled
  346. if not is_compiled():
  347. rmdir(srcdir)
  348. tarfile.open(location).extractall(basedir)
  349. os.chdir(srcdir)
  350. opts = OPENSSL['build'][cfg]
  351. shell('perl Configure --openssldir=%s %s' % (dstdir, opts['configure']))
  352. for cmd in opts['build']:
  353. shell(cmd)
  354. if not is_compiled():
  355. error("Unable to compile OpenSSL for your system, aborting.")
  356. return OPENSSL['build'][cfg]['os_libs']
  357. def check_running_on_debian():
  358. if not sys.platform.startswith('linux') or not exists('/etc/apt/sources.list'):
  359. error('This can only be run on a Debian/Ubuntu distribution, aborting.')
  360. if os.geteuid() != 0:
  361. error('This script must be run as root.')
  362. if platform.architecture()[0] == '64bit' and 'amd64' not in ARCH:
  363. ARCH.insert(0, 'amd64')
  364. PACKAGE_NAME = re.compile(r'ii\s+(.+?)\s+.*')
  365. def install_packages(*names):
  366. lines = get_output('dpkg-query', '--list').split('\n')
  367. avail = [PACKAGE_NAME.match(line).group(1) for line in lines if PACKAGE_NAME.match(line)]
  368. inst = [name for name in names if name in avail]
  369. if len(inst) != len(names):
  370. shell('apt-get update')
  371. shell('apt-get install --assume-yes %s' % (' '.join(names)))
  372. # --------------------------------------------------------------- Linux chroot
  373. ARCH = ['i386']
  374. def check_setup_schroot(config):
  375. check_running_on_debian()
  376. login = get_output('logname') or os.environ.get('SUDO_USER')
  377. if not login:
  378. error('Unable to determine the login for which schroot access is to be given.')
  379. if login == 'root':
  380. error('Please run via sudo to determine login for which schroot access is to be given.')
  381. def build_setup_schroot(config, basedir):
  382. install_packages('git', 'debootstrap', 'schroot', 'rinse')
  383. login = get_output('logname') or os.environ.get('SUDO_USER')
  384. chroot = config[1+config.rindex('-'):]
  385. for arch in ARCH:
  386. print '******************* %s-%s' % (chroot, arch)
  387. base_dir = os.environ.get('WKHTMLTOX_CHROOT') or '/opt/wkhtmltopdf-build'
  388. root_dir = os.path.join(base_dir, '%s-%s' % (chroot, arch))
  389. rmdir(root_dir)
  390. mkdir_p(root_dir)
  391. for command in CHROOT_SETUP[chroot]:
  392. # handle architecture-specific commands
  393. name = command[0]
  394. if ':' in name:
  395. if name[1+name.rindex(':'):] != arch:
  396. continue
  397. else:
  398. name = name[:name.rindex(':')]
  399. # handle commands
  400. if name == 'debootstrap':
  401. shell('debootstrap --arch=%(arch)s --variant=buildd %(distro)s %(dir)s %(url)s' % {
  402. 'arch': arch, 'dir': root_dir, 'distro': command[1], 'url': command[2] })
  403. elif name == 'rinse':
  404. cmd = (arch == 'i386' and 'linux32 rinse' or 'rinse')
  405. shell('%s --arch %s --distribution %s --directory %s' % (cmd, arch, command[1], root_dir))
  406. elif name == 'shell':
  407. cmd = (arch == 'i386' and 'linux32 chroot' or 'chroot')
  408. shell('%s %s %s' % (cmd, root_dir, command[1]))
  409. elif name == 'write_file':
  410. open(os.path.join(root_dir, command[1]), 'w').write(command[2].strip())
  411. elif name == 'append_file':
  412. open(os.path.join(root_dir, command[1]), 'a').write(command[2].strip())
  413. elif name == 'schroot_conf':
  414. cfg = open('/etc/schroot/chroot.d/wkhtmltopdf-%s-%s' % (chroot, arch), 'w')
  415. cfg.write('[wkhtmltopdf-%s-%s]\n' % (chroot, arch))
  416. cfg.write('type=directory\ndirectory=%s/\n' % root_dir)
  417. cfg.write('description=%s %s for wkhtmltopdf\n' % (command[1], arch))
  418. cfg.write('users=%s\nroot-users=root\n' % login)
  419. if arch == 'i386' and 'amd64' in ARCH:
  420. cfg.write('personality=linux32\n')
  421. cfg.close()
  422. def check_update_schroot(config):
  423. check_running_on_debian()
  424. if not get_output('schroot', '--list'):
  425. error('Unable to determine the list of available schroots.')
  426. def build_update_schroot(config, basedir):
  427. for name in get_output('schroot', '--list').split('\n'):
  428. print '******************* %s' % name[name.index('wkhtmltopdf-'):]
  429. shell('schroot -c %s -- /bin/bash /update.sh' % name[name.index('wkhtmltopdf-'):])
  430. def check_setup_mingw64(config):
  431. check_running_on_debian()
  432. def build_setup_mingw64(config, basedir):
  433. install_packages('build-essential', 'mingw-w64', 'nsis')
  434. # --------------------------------------------------------------- MSVC (2008-2013)
  435. MSVC_LOCATION = {
  436. 'msvc2008': 'VS90COMNTOOLS',
  437. 'msvc2010': 'VS100COMNTOOLS',
  438. 'msvc2012': 'VS110COMNTOOLS',
  439. 'msvc2013': 'VS120COMNTOOLS'
  440. }
  441. def check_msvc(config):
  442. version, arch = rchop(config, '-dbg').split('-')
  443. env_var = MSVC_LOCATION[version]
  444. if not env_var in os.environ:
  445. error("%s does not seem to be installed." % version)
  446. vcdir = os.path.join(os.environ[env_var], '..', '..', 'VC')
  447. if not exists(os.path.join(vcdir, 'vcvarsall.bat')):
  448. error("%s: unable to find vcvarsall.bat" % version)
  449. if arch == 'win32' and not exists(os.path.join(vcdir, 'bin', 'cl.exe')):
  450. error("%s: unable to find the x86 compiler" % version)
  451. if arch == 'win64' and not exists(os.path.join(vcdir, 'bin', 'amd64', 'cl.exe')) \
  452. and not exists(os.path.join(vcdir, 'bin', 'x86_amd64', 'cl.exe')):
  453. error("%s: unable to find the amd64 compiler" % version)
  454. def build_msvc(config, basedir):
  455. msvc, arch = rchop(config, '-dbg').split('-')
  456. vcdir = os.path.join(os.environ[MSVC_LOCATION[msvc]], '..', '..', 'VC')
  457. vcarg = 'x86'
  458. if arch == 'win64':
  459. if exists(os.path.join(vcdir, 'bin', 'amd64', 'cl.exe')):
  460. vcarg = 'amd64'
  461. else:
  462. vcarg = 'x86_amd64'
  463. python = sys.executable
  464. process = subprocess.Popen('("%s" %s>nul)&&"%s" -c "import os; print repr(os.environ)"' % (
  465. os.path.join(vcdir, 'vcvarsall.bat'), vcarg, python), stdout=subprocess.PIPE, shell=True)
  466. stdout, _ = process.communicate()
  467. exitcode = process.wait()
  468. if exitcode != 0:
  469. error("%s: unable to initialize the environment" % msvc)
  470. os.environ.update(eval(stdout.strip()))
  471. build_msvc_common(config, basedir)
  472. # --------------------------------------------------------------- MSVC via Windows SDK 7.1
  473. def check_msvc_winsdk71(config):
  474. for pfile in ['ProgramFiles(x86)', 'ProgramFiles']:
  475. if pfile in os.environ and exists(os.path.join(os.environ[pfile], 'Microsoft SDKs', 'Windows', 'v7.1', 'Bin', 'SetEnv.cmd')):
  476. return
  477. error("Unable to detect the location of Windows SDK 7.1")
  478. def build_msvc_winsdk71(config, basedir):
  479. arch = config[config.rindex('-'):]
  480. setenv = None
  481. for pfile in ['ProgramFiles(x86)', 'ProgramFiles']:
  482. if not pfile in os.environ:
  483. continue
  484. setenv = os.path.join(os.environ[pfile], 'Microsoft SDKs', 'Windows', 'v7.1', 'Bin', 'SetEnv.cmd')
  485. mode = debug and '/Debug' or '/Release'
  486. if arch == 'win64':
  487. args = '/2008 /x64 %s' % mode
  488. else:
  489. args = '/2008 /x86 %s' % mode
  490. python = sys.executable
  491. process = subprocess.Popen('("%s" %s>nul)&&"%s" -c "import os; print repr(os.environ)"' % (
  492. setenv, args, python), stdout=subprocess.PIPE, shell=True)
  493. stdout, _ = process.communicate()
  494. exitcode = process.wait()
  495. if exitcode != 0:
  496. error("unable to initialize the environment for Windows SDK 7.1")
  497. os.environ.update(eval(stdout.strip()))
  498. build_msvc_common(config, basedir)
  499. def build_msvc_common(config, basedir):
  500. version, simple_version = get_version(basedir)
  501. ssl_libs = build_openssl(config, basedir)
  502. ssldir = os.path.join(basedir, config, 'openssl')
  503. qtdir = os.path.join(basedir, config, 'qt')
  504. mkdir_p(qtdir)
  505. configure_args = qt_config('msvc',
  506. '-I %s\\include' % ssldir,
  507. '-L %s\\lib' % ssldir,
  508. 'OPENSSL_LIBS="-L%s -lssleay32 -llibeay32 %s"' % (ssldir.replace('\\', '\\\\'), ssl_libs))
  509. os.chdir(qtdir)
  510. if not exists('is_configured'):
  511. shell('%s\\..\\qt\\configure.exe %s' % (basedir, configure_args))
  512. open('is_configured', 'w').write('')
  513. shell('nmake')
  514. appdir = os.path.join(basedir, config, 'app')
  515. mkdir_p(appdir)
  516. os.chdir(appdir)
  517. rmdir('bin')
  518. mkdir_p('bin')
  519. os.environ['WKHTMLTOX_VERSION'] = version
  520. shell('%s\\bin\\qmake %s\\..\\wkhtmltopdf.pro' % (qtdir, basedir))
  521. shell('nmake')
  522. found = False
  523. for pfile in ['ProgramFiles(x86)', 'ProgramFiles']:
  524. if not pfile in os.environ or not exists(os.path.join(os.environ[pfile], 'NSIS', 'makensis.exe')):
  525. continue
  526. found = True
  527. makensis = os.path.join(os.environ[pfile], 'NSIS', 'makensis.exe')
  528. os.chdir(os.path.join(basedir, '..'))
  529. shell('"%s" /DVERSION=%s /DSIMPLE_VERSION=%s /DTARGET=%s wkhtmltox.nsi' % \
  530. (makensis, version, simple_version, config))
  531. if not found:
  532. print "\n\nCould not build installer as NSIS was not found."
  533. # ------------------------------------------------ MinGW-W64 Cross Environment
  534. MINGW_W64_PREFIX = {
  535. 'mingw-w64-cross-win32' : 'i686-w64-mingw32',
  536. 'mingw-w64-cross-win64' : 'x86_64-w64-mingw32',
  537. }
  538. def check_mingw64_cross(config):
  539. shell('%s-gcc --version' % MINGW_W64_PREFIX[rchop(config, '-dbg')])
  540. def build_mingw64_cross(config, basedir):
  541. version, simple_version = get_version(basedir)
  542. ssl_libs = build_openssl(config, basedir)
  543. ssldir = os.path.join(basedir, config, 'openssl')
  544. qtdir = os.path.join(basedir, config, 'qt')
  545. configure_args = qt_config('mingw-w64-cross',
  546. '--prefix=%s' % qtdir,
  547. '-I %s/include' % ssldir,
  548. '-L %s/lib' % ssldir,
  549. '-device-option CROSS_COMPILE=%s-' % MINGW_W64_PREFIX[rchop(config, '-dbg')])
  550. os.environ['OPENSSL_LIBS'] = '-lssl -lcrypto -L %s/lib %s' % (ssldir, ssl_libs)
  551. mkdir_p(qtdir)
  552. os.chdir(qtdir)
  553. if not exists('is_configured'):
  554. for var in ['CFLAGS', 'CXXFLAGS']:
  555. os.environ[var] = '-w'
  556. shell('%s/../qt/configure %s' % (basedir, configure_args))
  557. shell('touch is_configured')
  558. shell('make -j%d' % CPU_COUNT)
  559. appdir = os.path.join(basedir, config, 'app')
  560. mkdir_p(appdir)
  561. os.chdir(appdir)
  562. shell('rm -f bin/*')
  563. # set up cross compiling prefix correctly
  564. os.environ['WKHTMLTOX_VERSION'] = version
  565. shell('%s/bin/qmake -set CROSS_COMPILE %s-' % (qtdir, MINGW_W64_PREFIX[rchop(config, '-dbg')]))
  566. shell('%s/bin/qmake -spec win32-g++-4.6 %s/../wkhtmltopdf.pro' % (qtdir, basedir))
  567. shell('make')
  568. shutil.copy('bin/libwkhtmltox0.a', 'bin/wkhtmltox.lib')
  569. os.chdir(os.path.join(basedir, '..'))
  570. shell('makensis -DVERSION=%s -DSIMPLE_VERSION=%s -DTARGET=%s wkhtmltox.nsi' % \
  571. (version, simple_version, config))
  572. # -------------------------------------------------- Linux schroot environment
  573. def check_linux_schroot(config):
  574. shell('schroot -c wkhtmltopdf-%s -- gcc --version' % rchop(config, '-dbg'))
  575. def build_linux_schroot(config, basedir):
  576. version, simple_version = get_version(basedir)
  577. dir = os.path.join(basedir, config)
  578. script = os.path.join(dir, 'build.sh')
  579. dist = os.path.join(dir, 'wkhtmltox-%s' % version)
  580. rmdir(dist)
  581. mkdir_p(os.path.join(dist, 'bin'))
  582. mkdir_p(os.path.join(dist, 'include', 'wkhtmltox'))
  583. mkdir_p(os.path.join(dist, 'lib'))
  584. configure_args = qt_config('posix', '--prefix=%s' % os.path.join(dir, 'qt'))
  585. lines = ['#!/bin/bash']
  586. lines.append('# start of autogenerated build script')
  587. lines.append('mkdir -p app qt')
  588. lines.append('cd qt')
  589. if config == 'centos5-i386':
  590. lines.append('export CFLAGS="-march=i486 -w"')
  591. lines.append('export CXXFLAGS="-march=i486 -w"')
  592. else:
  593. for var in ['CFLAGS', 'CXXFLAGS']:
  594. lines.append('export %s="-w"' % var)
  595. lines.append('if [ ! -f is_configured ]; then')
  596. lines.append(' ../../../qt/configure %s || exit 1' % configure_args)
  597. lines.append(' touch is_configured')
  598. lines.append('fi')
  599. lines.append('if ! make -j%d -q; then\n make -j%d || exit 1\nfi' % (CPU_COUNT, CPU_COUNT))
  600. lines.append('cd ../app')
  601. lines.append('rm -f bin/*')
  602. lines.append('export WKHTMLTOX_VERSION=%s' % version)
  603. lines.append('../qt/bin/qmake ../../../wkhtmltopdf.pro')
  604. lines.append('make -j%d || exit 1' % CPU_COUNT)
  605. lines.append('strip bin/wkhtmltopdf bin/wkhtmltoimage')
  606. lines.append('cp bin/wkhtmlto* ../wkhtmltox-%s/bin' % version)
  607. lines.append('cp -P bin/libwkhtmltox*.so.* ../wkhtmltox-%s/lib' % version)
  608. lines.append('cp ../../../include/wkhtmltox/*.h ../wkhtmltox-%s/include/wkhtmltox' % version)
  609. lines.append('cp ../../../include/wkhtmltox/dll*.inc ../wkhtmltox-%s/include/wkhtmltox' % version)
  610. lines.append('cd ..')
  611. lines.append('tar -c -v -f ../wkhtmltox-%s_linux-%s.tar wkhtmltox-%s/' % (version, config, version))
  612. lines.append('xz --compress --force --verbose -9 ../wkhtmltox-%s_linux-%s.tar' % (version, config))
  613. lines.append('# end of build script')
  614. open(script, 'w').write('\n'.join(lines))
  615. os.chdir(dir)
  616. shell('chmod +x build.sh')
  617. shell('schroot -c wkhtmltopdf-%s -- ./build.sh' % rchop(config, '-dbg'))
  618. # -------------------------------------------------- POSIX local environment
  619. def check_posix_local(config):
  620. pass
  621. def build_posix_local(config, basedir):
  622. version, simple_version = get_version(basedir)
  623. app = os.path.join(basedir, config, 'app')
  624. qtdir = os.path.join(basedir, config, 'qt')
  625. dist = os.path.join(basedir, config, 'wkhtmltox-%s' % version)
  626. mkdir_p(qt)
  627. mkdir_p(app)
  628. rmdir(dist)
  629. mkdir_p(os.path.join(dist, 'bin'))
  630. mkdir_p(os.path.join(dist, 'include', 'wkhtmltox'))
  631. mkdir_p(os.path.join(dist, 'lib'))
  632. os.chdir(qt)
  633. if not exists('is_configured'):
  634. shell('../../../qt/configure %s' % qt_config('posix', '--prefix=%s' % qtdir))
  635. shell('touch is_configured')
  636. if subprocess.call(['make', '-j%d' % CPU_COUNT]):
  637. shell('make -j%d' % CPU_COUNT)
  638. os.chdir(app)
  639. shell('rm -f bin/*')
  640. os.environ['WKHTMLTOX_VERSION'] = version
  641. shell('../qt/bin/qmake ../../../wkhtmltopdf.pro')
  642. shell('make -j%d' % CPU_COUNT)
  643. shell('cp bin/wkhtmlto* ../wkhtmltox-%s/bin' % version)
  644. shell('cp -P bin/libwkhtmltox*.so.* ../wkhtmltox-%s/lib' % version)
  645. shell('cp ../../../include/wkhtmltox/*.h ../wkhtmltox-%s/include/wkhtmltox' % version)
  646. shell('cp ../../../include/wkhtmltox/dll*.inc ../wkhtmltox-%s/include/wkhtmltox' % version)
  647. os.chdir(basedir)
  648. shell('tar -c -v -f ../wkhtmltox-%s_local-%s.tar wkhtmltox-%s/' % (version, platform.node(), version))
  649. shell('xz --compress --force --verbose -9 ../wkhtmltox-%s_local-%s.tar' % (version, platform.node()))
  650. # --------------------------------------------------------------- OS X
  651. OSX_CONFIG = {
  652. 'osx-10.6-carbon-i386': '-carbon -platform macx-g++42',
  653. 'osx-10.7-carbon-i386': '-carbon -platform unsupported/macx-clang -reduce-exports',
  654. 'osx-10.8-carbon-i386': '-carbon -platform unsupported/macx-clang -reduce-exports',
  655. 'osx-10.9-carbon-i386': '-carbon -platform unsupported/macx-clang -reduce-exports',
  656. 'osx-10.7-cocoa-x86-64': '-cocoa -platform unsupported/macx-clang',
  657. 'osx-10.8-cocoa-x86-64': '-cocoa -platform unsupported/macx-clang',
  658. 'osx-10.9-cocoa-x86-64': '-cocoa -platform unsupported/macx-clang-libc++'
  659. }
  660. def check_osx(config):
  661. if not platform.system() == 'Darwin' or not platform.mac_ver()[0]:
  662. error('This can only be run on a OS X system!')
  663. osxver = platform.mac_ver()[0][:platform.mac_ver()[0].rindex('.')]
  664. osxcfg = config.replace('osx-', 'osx-%s-' % osxver)
  665. if not osxcfg in OSX_CONFIG:
  666. error('This target is not supported: %s' % osxcfg)
  667. if 'carbon' in osxcfg and osxver != '10.6':
  668. sdk_dir = get_output('xcodebuild', '-sdk', 'macosx10.6', '-version', 'Path')
  669. if not sdk_dir:
  670. error('Unable to find OS X 10.6 SDK for the carbon build, aborting.')
  671. if not os.path.isfile('%s/usr/lib/libstdc++.dylib' % sdk_dir):
  672. error('Symlink for libstdc++.dylib has not been created, aborting.')
  673. def build_osx(config, basedir):
  674. version, simple_version = get_version(basedir)
  675. osxver = platform.mac_ver()[0][:platform.mac_ver()[0].rindex('.')]
  676. osxcfg = config.replace('osx-', 'osx-%s-' % osxver)
  677. args = OSX_CONFIG[osxcfg]
  678. flags = ''
  679. if 'carbon' in osxcfg and osxver != '10.6':
  680. args += ' -sdk %s' % get_output('xcodebuild', '-sdk', 'macosx10.6', '-version', 'Path')
  681. for item in ['CFLAGS', 'CXXFLAGS']:
  682. flags += '"QMAKE_%s += %s" ' % (item, '-fvisibility=hidden -fvisibility-inlines-hidden')
  683. qt = os.path.join(basedir, config, 'qt')
  684. app = os.path.join(basedir, config, 'app')
  685. dist = os.path.join(basedir, config, 'wkhtmltox-%s' % version)
  686. mkdir_p(qt)
  687. mkdir_p(app)
  688. rmdir(dist)
  689. mkdir_p(os.path.join(dist, 'bin'))
  690. mkdir_p(os.path.join(dist, 'include', 'wkhtmltox'))
  691. mkdir_p(os.path.join(dist, 'lib'))
  692. os.chdir(qt)
  693. if not exists('is_configured'):
  694. shell('../../../qt/configure %s' % qt_config('osx', '--prefix=%s' % qt, args))
  695. shell('touch is_configured')
  696. shell('make -j%d' % CPU_COUNT)
  697. os.chdir(app)
  698. shell('rm -f bin/*')
  699. os.environ['WKHTMLTOX_VERSION'] = version
  700. shell('../qt/bin/qmake %s ../../../wkhtmltopdf.pro' % flags)
  701. shell('make -j%d' % CPU_COUNT)
  702. shell('cp bin/wkhtmlto* ../wkhtmltox-%s/bin' % version)
  703. shell('cp -P bin/libwkhtmltox*.dylib* ../wkhtmltox-%s/lib' % version)
  704. shell('cp ../../../include/wkhtmltox/*.h ../wkhtmltox-%s/include/wkhtmltox' % version)
  705. shell('cp ../../../include/wkhtmltox/dll*.inc ../wkhtmltox-%s/include/wkhtmltox' % version)
  706. os.chdir(os.path.join(basedir, config))
  707. shell('tar -c -v -f ../wkhtmltox-%s_%s.tar wkhtmltox-%s/' % (version, osxcfg, version))
  708. shell('xz --compress --force --verbose -9 ../wkhtmltox-%s_%s.tar' % (version, osxcfg))
  709. # --------------------------------------------------------------- command line
  710. def usage(exit_code=2):
  711. print "Usage: scripts/build.py <target> [-clean] [-debug]\n\nThe supported targets are:\n",
  712. opts = list(BUILDERS.keys())
  713. opts.sort()
  714. for opt in opts:
  715. print '* %s' % opt
  716. sys.exit(exit_code)
  717. def main():
  718. basedir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'static-build')
  719. mkdir_p(basedir)
  720. if len(sys.argv) == 1:
  721. usage(0)
  722. config = sys.argv[1]
  723. if config not in BUILDERS:
  724. usage()
  725. for arg in sys.argv[2:]:
  726. if not arg in ['-clean', '-debug']:
  727. usage()
  728. final_config = config
  729. if '-debug' in sys.argv[2:]:
  730. # use the debug OpenSSL configuration if possible
  731. ssl = OPENSSL['build']
  732. for key in ssl:
  733. if fnmatch.fnmatch(config, key) and 'debug' in ssl[key]:
  734. ssl[key]['configure'] = ssl[key]['debug']
  735. # use a debug build of QT and WebKit
  736. cfg = QT_CONFIG['common']
  737. cfg[cfg.index('-release')] = '-debug'
  738. cfg[cfg.index('-webkit')] = '-webkit-debug'
  739. final_config += '-dbg'
  740. if '-clean' in sys.argv[2:]:
  741. rmdir(os.path.join(basedir, config))
  742. globals()['check_%s' % BUILDERS[config]](final_config)
  743. globals()['build_%s' % BUILDERS[config]](final_config, os.path.realpath(basedir))
  744. if __name__ == '__main__':
  745. main()