build.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  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. root_dir = '/opt/wkhtmltopdf-build/%s-%s' % (chroot, arch)
  388. rmdir(root_dir)
  389. mkdir_p(root_dir)
  390. for command in CHROOT_SETUP[chroot]:
  391. # handle architecture-specific commands
  392. name = command[0]
  393. if ':' in name:
  394. if name[1+name.rindex(':'):] != arch:
  395. continue
  396. else:
  397. name = name[:name.rindex(':')]
  398. # handle commands
  399. if name == 'debootstrap':
  400. shell('debootstrap --arch=%(arch)s --variant=buildd %(distro)s %(dir)s %(url)s' % {
  401. 'arch': arch, 'dir': root_dir, 'distro': command[1], 'url': command[2] })
  402. elif name == 'rinse':
  403. cmd = (arch == 'i386' and 'linux32 rinse' or 'rinse')
  404. shell('%s --arch %s --distribution %s --directory %s' % (cmd, arch, command[1], root_dir))
  405. elif name == 'shell':
  406. cmd = (arch == 'i386' and 'linux32 chroot' or 'chroot')
  407. shell('%s %s %s' % (cmd, root_dir, command[1]))
  408. elif name == 'write_file':
  409. open(os.path.join(root_dir, command[1]), 'w').write(command[2].strip())
  410. elif name == 'append_file':
  411. open(os.path.join(root_dir, command[1]), 'a').write(command[2].strip())
  412. elif name == 'schroot_conf':
  413. cfg = open('/etc/schroot/chroot.d/wkhtmltopdf-%s-%s' % (chroot, arch), 'w')
  414. cfg.write('[wkhtmltopdf-%s-%s]\n' % (chroot, arch))
  415. cfg.write('type=directory\ndirectory=%s/\n' % root_dir)
  416. cfg.write('description=%s %s for wkhtmltopdf\n' % (command[1], arch))
  417. cfg.write('users=%s\nroot-users=root\n' % login)
  418. if arch == 'i386' and 'amd64' in ARCH:
  419. cfg.write('personality=linux32\n')
  420. cfg.close()
  421. def check_update_schroot(config):
  422. check_running_on_debian()
  423. if not get_output('schroot', '--list'):
  424. error('Unable to determine the list of available schroots.')
  425. def build_update_schroot(config, basedir):
  426. for name in get_output('schroot', '--list').split('\n'):
  427. print '******************* %s' % name[name.index('wkhtmltopdf-'):]
  428. shell('schroot -c %s -- /bin/bash /update.sh' % name[name.index('wkhtmltopdf-'):])
  429. def check_setup_mingw64(config):
  430. check_running_on_debian()
  431. def build_setup_mingw64(config, basedir):
  432. install_packages('build-essential', 'mingw-w64', 'nsis')
  433. # --------------------------------------------------------------- MSVC (2008-2013)
  434. MSVC_LOCATION = {
  435. 'msvc2008': 'VS90COMNTOOLS',
  436. 'msvc2010': 'VS100COMNTOOLS',
  437. 'msvc2012': 'VS110COMNTOOLS',
  438. 'msvc2013': 'VS120COMNTOOLS'
  439. }
  440. def check_msvc(config):
  441. version, arch = rchop(config, '-dbg').split('-')
  442. env_var = MSVC_LOCATION[version]
  443. if not env_var in os.environ:
  444. error("%s does not seem to be installed." % version)
  445. vcdir = os.path.join(os.environ[env_var], '..', '..', 'VC')
  446. if not exists(os.path.join(vcdir, 'vcvarsall.bat')):
  447. error("%s: unable to find vcvarsall.bat" % version)
  448. if arch == 'win32' and not exists(os.path.join(vcdir, 'bin', 'cl.exe')):
  449. error("%s: unable to find the x86 compiler" % version)
  450. if arch == 'win64' and not exists(os.path.join(vcdir, 'bin', 'amd64', 'cl.exe')) \
  451. and not exists(os.path.join(vcdir, 'bin', 'x86_amd64', 'cl.exe')):
  452. error("%s: unable to find the amd64 compiler" % version)
  453. def build_msvc(config, basedir):
  454. msvc, arch = rchop(config, '-dbg').split('-')
  455. vcdir = os.path.join(os.environ[MSVC_LOCATION[msvc]], '..', '..', 'VC')
  456. vcarg = 'x86'
  457. if arch == 'win64':
  458. if exists(os.path.join(vcdir, 'bin', 'amd64', 'cl.exe')):
  459. vcarg = 'amd64'
  460. else:
  461. vcarg = 'x86_amd64'
  462. python = sys.executable
  463. process = subprocess.Popen('("%s" %s>nul)&&"%s" -c "import os; print repr(os.environ)"' % (
  464. os.path.join(vcdir, 'vcvarsall.bat'), vcarg, python), stdout=subprocess.PIPE, shell=True)
  465. stdout, _ = process.communicate()
  466. exitcode = process.wait()
  467. if exitcode != 0:
  468. error("%s: unable to initialize the environment" % msvc)
  469. os.environ.update(eval(stdout.strip()))
  470. build_msvc_common(config, basedir)
  471. # --------------------------------------------------------------- MSVC via Windows SDK 7.1
  472. def check_msvc_winsdk71(config):
  473. for pfile in ['ProgramFiles(x86)', 'ProgramFiles']:
  474. if pfile in os.environ and exists(os.path.join(os.environ[pfile], 'Microsoft SDKs', 'Windows', 'v7.1', 'Bin', 'SetEnv.cmd')):
  475. return
  476. error("Unable to detect the location of Windows SDK 7.1")
  477. def build_msvc_winsdk71(config, basedir):
  478. arch = config[config.rindex('-'):]
  479. setenv = None
  480. for pfile in ['ProgramFiles(x86)', 'ProgramFiles']:
  481. if not pfile in os.environ:
  482. continue
  483. setenv = os.path.join(os.environ[pfile], 'Microsoft SDKs', 'Windows', 'v7.1', 'Bin', 'SetEnv.cmd')
  484. mode = debug and '/Debug' or '/Release'
  485. if arch == 'win64':
  486. args = '/2008 /x64 %s' % mode
  487. else:
  488. args = '/2008 /x86 %s' % mode
  489. python = sys.executable
  490. process = subprocess.Popen('("%s" %s>nul)&&"%s" -c "import os; print repr(os.environ)"' % (
  491. setenv, args, python), stdout=subprocess.PIPE, shell=True)
  492. stdout, _ = process.communicate()
  493. exitcode = process.wait()
  494. if exitcode != 0:
  495. error("unable to initialize the environment for Windows SDK 7.1")
  496. os.environ.update(eval(stdout.strip()))
  497. build_msvc_common(config, basedir)
  498. def build_msvc_common(config, basedir):
  499. version, simple_version = get_version(basedir)
  500. ssl_libs = build_openssl(config, basedir)
  501. ssldir = os.path.join(basedir, config, 'openssl')
  502. qtdir = os.path.join(basedir, config, 'qt')
  503. mkdir_p(qtdir)
  504. configure_args = qt_config('msvc',
  505. '-I %s\\include' % ssldir,
  506. '-L %s\\lib' % ssldir,
  507. 'OPENSSL_LIBS="-L%s -lssleay32 -llibeay32 %s"' % (ssldir.replace('\\', '\\\\'), ssl_libs))
  508. os.chdir(qtdir)
  509. if not exists('is_configured'):
  510. shell('%s\\..\\qt\\configure.exe %s' % (basedir, configure_args))
  511. open('is_configured', 'w').write('')
  512. shell('nmake')
  513. appdir = os.path.join(basedir, config, 'app')
  514. mkdir_p(appdir)
  515. os.chdir(appdir)
  516. rmdir('bin')
  517. mkdir_p('bin')
  518. os.environ['WKHTMLTOX_VERSION'] = version
  519. shell('%s\\bin\\qmake %s\\..\\wkhtmltopdf.pro' % (qtdir, basedir))
  520. shell('nmake')
  521. found = False
  522. for pfile in ['ProgramFiles(x86)', 'ProgramFiles']:
  523. if not pfile in os.environ or not exists(os.path.join(os.environ[pfile], 'NSIS', 'makensis.exe')):
  524. continue
  525. found = True
  526. makensis = os.path.join(os.environ[pfile], 'NSIS', 'makensis.exe')
  527. os.chdir(os.path.join(basedir, '..'))
  528. shell('"%s" /DVERSION=%s /DSIMPLE_VERSION=%s /DTARGET=%s wkhtmltox.nsi' % \
  529. (makensis, version, simple_version, config))
  530. if not found:
  531. print "\n\nCould not build installer as NSIS was not found."
  532. # ------------------------------------------------ MinGW-W64 Cross Environment
  533. MINGW_W64_PREFIX = {
  534. 'mingw-w64-cross-win32' : 'i686-w64-mingw32',
  535. 'mingw-w64-cross-win64' : 'x86_64-w64-mingw32',
  536. }
  537. def check_mingw64_cross(config):
  538. shell('%s-gcc --version' % MINGW_W64_PREFIX[rchop(config, '-dbg')])
  539. def build_mingw64_cross(config, basedir):
  540. version, simple_version = get_version(basedir)
  541. ssl_libs = build_openssl(config, basedir)
  542. ssldir = os.path.join(basedir, config, 'openssl')
  543. qtdir = os.path.join(basedir, config, 'qt')
  544. configure_args = qt_config('mingw-w64-cross',
  545. '--prefix=%s' % qtdir,
  546. '-I %s/include' % ssldir,
  547. '-L %s/lib' % ssldir,
  548. '-device-option CROSS_COMPILE=%s-' % MINGW_W64_PREFIX[rchop(config, '-dbg')])
  549. os.environ['OPENSSL_LIBS'] = '-lssl -lcrypto -L %s/lib %s' % (ssldir, ssl_libs)
  550. mkdir_p(qtdir)
  551. os.chdir(qtdir)
  552. if not exists('is_configured'):
  553. for var in ['CFLAGS', 'CXXFLAGS']:
  554. os.environ[var] = '-w'
  555. shell('%s/../qt/configure %s' % (basedir, configure_args))
  556. shell('touch is_configured')
  557. shell('make -j%d' % CPU_COUNT)
  558. appdir = os.path.join(basedir, config, 'app')
  559. mkdir_p(appdir)
  560. os.chdir(appdir)
  561. shell('rm -f bin/*')
  562. # set up cross compiling prefix correctly
  563. os.environ['WKHTMLTOX_VERSION'] = version
  564. shell('%s/bin/qmake -set CROSS_COMPILE %s-' % (qtdir, MINGW_W64_PREFIX[rchop(config, '-dbg')]))
  565. shell('%s/bin/qmake -spec win32-g++-4.6 %s/../wkhtmltopdf.pro' % (qtdir, basedir))
  566. shell('make')
  567. shutil.copy('bin/libwkhtmltox0.a', 'bin/wkhtmltox.lib')
  568. os.chdir(os.path.join(basedir, '..'))
  569. shell('makensis -DVERSION=%s -DSIMPLE_VERSION=%s -DTARGET=%s wkhtmltox.nsi' % \
  570. (version, simple_version, config))
  571. # -------------------------------------------------- Linux schroot environment
  572. def check_linux_schroot(config):
  573. shell('schroot -c wkhtmltopdf-%s -- gcc --version' % rchop(config, '-dbg'))
  574. def build_linux_schroot(config, basedir):
  575. version, simple_version = get_version(basedir)
  576. dir = os.path.join(basedir, config)
  577. script = os.path.join(dir, 'build.sh')
  578. dist = os.path.join(dir, 'wkhtmltox-%s' % version)
  579. rmdir(dist)
  580. mkdir_p(os.path.join(dist, 'bin'))
  581. mkdir_p(os.path.join(dist, 'include', 'wkhtmltox'))
  582. mkdir_p(os.path.join(dist, 'lib'))
  583. configure_args = qt_config('posix', '--prefix=%s' % os.path.join(dir, 'qt'))
  584. lines = ['#!/bin/bash']
  585. lines.append('# start of autogenerated build script')
  586. lines.append('mkdir -p app qt')
  587. lines.append('cd qt')
  588. if config == 'centos5-i386':
  589. lines.append('export CFLAGS="-march=i486 -w"')
  590. lines.append('export CXXFLAGS="-march=i486 -w"')
  591. else:
  592. for var in ['CFLAGS', 'CXXFLAGS']:
  593. lines.append('export %s="-w"' % var)
  594. lines.append('if [ ! -f is_configured ]; then')
  595. lines.append(' ../../../qt/configure %s || exit 1' % configure_args)
  596. lines.append(' touch is_configured')
  597. lines.append('fi')
  598. lines.append('if ! make -j%d -q; then\n make -j%d || exit 1\nfi' % (CPU_COUNT, CPU_COUNT))
  599. lines.append('cd ../app')
  600. lines.append('rm -f bin/*')
  601. lines.append('export WKHTMLTOX_VERSION=%s' % version)
  602. lines.append('../qt/bin/qmake ../../../wkhtmltopdf.pro')
  603. lines.append('make -j%d || exit 1' % CPU_COUNT)
  604. lines.append('strip bin/wkhtmltopdf bin/wkhtmltoimage')
  605. lines.append('cp bin/wkhtmlto* ../wkhtmltox-%s/bin' % version)
  606. lines.append('cp -P bin/libwkhtmltox*.so.* ../wkhtmltox-%s/lib' % version)
  607. lines.append('cp ../../../include/wkhtmltox/*.h ../wkhtmltox-%s/include/wkhtmltox' % version)
  608. lines.append('cp ../../../include/wkhtmltox/dll*.inc ../wkhtmltox-%s/include/wkhtmltox' % version)
  609. lines.append('cd ..')
  610. lines.append('tar -c -v -f ../wkhtmltox-%s_linux-%s.tar wkhtmltox-%s/' % (version, config, version))
  611. lines.append('xz --compress --force --verbose -9 ../wkhtmltox-%s_linux-%s.tar' % (version, config))
  612. lines.append('# end of build script')
  613. open(script, 'w').write('\n'.join(lines))
  614. os.chdir(dir)
  615. shell('chmod +x build.sh')
  616. shell('schroot -c wkhtmltopdf-%s -- ./build.sh' % rchop(config, '-dbg'))
  617. # -------------------------------------------------- POSIX local environment
  618. def check_posix_local(config):
  619. pass
  620. def build_posix_local(config, basedir):
  621. version, simple_version = get_version(basedir)
  622. app = os.path.join(basedir, config, 'app')
  623. qtdir = os.path.join(basedir, config, 'qt')
  624. dist = os.path.join(basedir, config, 'wkhtmltox-%s' % version)
  625. mkdir_p(qt)
  626. mkdir_p(app)
  627. rmdir(dist)
  628. mkdir_p(os.path.join(dist, 'bin'))
  629. mkdir_p(os.path.join(dist, 'include', 'wkhtmltox'))
  630. mkdir_p(os.path.join(dist, 'lib'))
  631. os.chdir(qt)
  632. if not exists('is_configured'):
  633. shell('../../../qt/configure %s' % qt_config('posix', '--prefix=%s' % qtdir))
  634. shell('touch is_configured')
  635. if subprocess.call(['make', '-j%d' % CPU_COUNT]):
  636. shell('make -j%d' % CPU_COUNT)
  637. os.chdir(app)
  638. shell('rm -f bin/*')
  639. os.environ['WKHTMLTOX_VERSION'] = version
  640. shell('../qt/bin/qmake ../../../wkhtmltopdf.pro')
  641. shell('make -j%d' % CPU_COUNT)
  642. shell('cp bin/wkhtmlto* ../wkhtmltox-%s/bin' % version)
  643. shell('cp -P bin/libwkhtmltox*.so.* ../wkhtmltox-%s/lib' % version)
  644. shell('cp ../../../include/wkhtmltox/*.h ../wkhtmltox-%s/include/wkhtmltox' % version)
  645. shell('cp ../../../include/wkhtmltox/dll*.inc ../wkhtmltox-%s/include/wkhtmltox' % version)
  646. os.chdir(basedir)
  647. shell('tar -c -v -f ../wkhtmltox-%s_local-%s.tar wkhtmltox-%s/' % (version, platform.node(), version))
  648. shell('xz --compress --force --verbose -9 ../wkhtmltox-%s_local-%s.tar' % (version, platform.node()))
  649. # --------------------------------------------------------------- OS X
  650. OSX_CONFIG = {
  651. 'osx-10.6-carbon-i386': '-carbon -platform macx-g++42',
  652. 'osx-10.7-carbon-i386': '-carbon -platform unsupported/macx-clang -reduce-exports',
  653. 'osx-10.8-carbon-i386': '-carbon -platform unsupported/macx-clang -reduce-exports',
  654. 'osx-10.9-carbon-i386': '-carbon -platform unsupported/macx-clang -reduce-exports',
  655. 'osx-10.7-cocoa-x86-64': '-cocoa -platform unsupported/macx-clang',
  656. 'osx-10.8-cocoa-x86-64': '-cocoa -platform unsupported/macx-clang',
  657. 'osx-10.9-cocoa-x86-64': '-cocoa -platform unsupported/macx-clang-libc++'
  658. }
  659. def check_osx(config):
  660. if not platform.system() == 'Darwin' or not platform.mac_ver()[0]:
  661. error('This can only be run on a OS X system!')
  662. osxver = platform.mac_ver()[0][:platform.mac_ver()[0].rindex('.')]
  663. osxcfg = config.replace('osx-', 'osx-%s-' % osxver)
  664. if not osxcfg in OSX_CONFIG:
  665. error('This target is not supported: %s' % osxcfg)
  666. if 'carbon' in osxcfg and osxver != '10.6':
  667. sdk_dir = get_output('xcodebuild', '-sdk', 'macosx10.6', '-version', 'Path')
  668. if not sdk_dir:
  669. error('Unable to find OS X 10.6 SDK for the carbon build, aborting.')
  670. if not os.path.isfile('%s/usr/lib/libstdc++.dylib' % sdk_dir):
  671. error('Symlink for libstdc++.dylib has not been created, aborting.')
  672. def build_osx(config, basedir):
  673. version, simple_version = get_version(basedir)
  674. osxver = platform.mac_ver()[0][:platform.mac_ver()[0].rindex('.')]
  675. osxcfg = config.replace('osx-', 'osx-%s-' % osxver)
  676. args = OSX_CONFIG[osxcfg]
  677. flags = ''
  678. if 'carbon' in osxcfg and osxver != '10.6':
  679. args += ' -sdk %s' % get_output('xcodebuild', '-sdk', 'macosx10.6', '-version', 'Path')
  680. for item in ['CFLAGS', 'CXXFLAGS']:
  681. flags += '"QMAKE_%s += %s" ' % (item, '-fvisibility=hidden -fvisibility-inlines-hidden')
  682. qt = os.path.join(basedir, config, 'qt')
  683. app = os.path.join(basedir, config, 'app')
  684. dist = os.path.join(basedir, config, 'wkhtmltox-%s' % version)
  685. mkdir_p(qt)
  686. mkdir_p(app)
  687. rmdir(dist)
  688. mkdir_p(os.path.join(dist, 'bin'))
  689. mkdir_p(os.path.join(dist, 'include', 'wkhtmltox'))
  690. mkdir_p(os.path.join(dist, 'lib'))
  691. os.chdir(qt)
  692. if not exists('is_configured'):
  693. shell('../../../qt/configure %s' % qt_config('osx', '--prefix=%s' % qt, args))
  694. shell('touch is_configured')
  695. shell('make -j%d' % CPU_COUNT)
  696. os.chdir(app)
  697. shell('rm -f bin/*')
  698. os.environ['WKHTMLTOX_VERSION'] = version
  699. shell('../qt/bin/qmake %s ../../../wkhtmltopdf.pro' % flags)
  700. shell('make -j%d' % CPU_COUNT)
  701. shell('cp bin/wkhtmlto* ../wkhtmltox-%s/bin' % version)
  702. shell('cp -P bin/libwkhtmltox*.dylib* ../wkhtmltox-%s/lib' % version)
  703. shell('cp ../../../include/wkhtmltox/*.h ../wkhtmltox-%s/include/wkhtmltox' % version)
  704. shell('cp ../../../include/wkhtmltox/dll*.inc ../wkhtmltox-%s/include/wkhtmltox' % version)
  705. os.chdir(os.path.join(basedir, config))
  706. shell('tar -c -v -f ../wkhtmltox-%s_%s.tar wkhtmltox-%s/' % (version, osxcfg, version))
  707. shell('xz --compress --force --verbose -9 ../wkhtmltox-%s_%s.tar' % (version, osxcfg))
  708. # --------------------------------------------------------------- command line
  709. def usage(exit_code=2):
  710. print "Usage: scripts/build.py <target> [-clean] [-debug]\n\nThe supported targets are:\n",
  711. opts = list(BUILDERS.keys())
  712. opts.sort()
  713. for opt in opts:
  714. print '* %s' % opt
  715. sys.exit(exit_code)
  716. def main():
  717. basedir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'static-build')
  718. mkdir_p(basedir)
  719. if len(sys.argv) == 1:
  720. usage(0)
  721. config = sys.argv[1]
  722. if config not in BUILDERS:
  723. usage()
  724. for arg in sys.argv[2:]:
  725. if not arg in ['-clean', '-debug']:
  726. usage()
  727. final_config = config
  728. if '-debug' in sys.argv[2:]:
  729. # use the debug OpenSSL configuration if possible
  730. ssl = OPENSSL['build']
  731. for key in ssl:
  732. if fnmatch.fnmatch(config, key) and 'debug' in ssl[key]:
  733. ssl[key]['configure'] = ssl[key]['debug']
  734. # use a debug build of QT and WebKit
  735. cfg = QT_CONFIG['common']
  736. cfg[cfg.index('-release')] = '-debug'
  737. cfg[cfg.index('-webkit')] = '-webkit-debug'
  738. final_config += '-dbg'
  739. if '-clean' in sys.argv[2:]:
  740. rmdir(os.path.join(basedir, config))
  741. globals()['check_%s' % BUILDERS[config]](final_config)
  742. globals()['build_%s' % BUILDERS[config]](final_config, os.path.realpath(basedir))
  743. if __name__ == '__main__':
  744. main()