build.py 32 KB

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