build.py 37 KB

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