1#!/usr/bin/env python
2# Copyright (c) 2012 The Chromium Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6import glob
7import os
8import shutil
9import subprocess
10import sys
11import tempfile
12
13BUILD_DIR = 'build'
14
15
16def run_with_vsvars(cmd, tmpdir=None):
17  fd, filename = tempfile.mkstemp('.bat', text=True)
18  with os.fdopen(fd, 'w') as f:
19    print >> f, '@echo off'
20    print >> f, r'call "%VS100COMNTOOLS%\vsvars32.bat"'
21    if tmpdir:
22      print >> f, r'cd %s' % tmpdir
23    print >> f, cmd
24  try:
25    p = subprocess.Popen([filename], shell=True, stdout=subprocess.PIPE,
26        universal_newlines=True)
27    out, _ = p.communicate()
28    return p.returncode, out
29  finally:
30    os.unlink(filename)
31
32
33def get_vc_dir():
34  _, out = run_with_vsvars('echo VCINSTALLDIR=%VCINSTALLDIR%')
35  for line in out.splitlines():  # pylint: disable-msg=E1103
36    if line.startswith('VCINSTALLDIR='):
37      return line[len('VCINSTALLDIR='):]
38  return None
39
40
41def build(infile):
42  if not os.path.exists(BUILD_DIR):
43    os.makedirs(BUILD_DIR)
44  outfile = 'limiter.exe'
45  outpath = os.path.join(BUILD_DIR, outfile)
46  cpptime = os.path.getmtime(infile)
47  if not os.path.exists(outpath) or cpptime > os.path.getmtime(outpath):
48    print 'Building %s...' % outfile
49    rc, out = run_with_vsvars(
50        'cl /nologo /Ox /Zi /W4 /WX /D_UNICODE /DUNICODE'
51        ' /D_CRT_SECURE_NO_WARNINGS /EHsc %s /link /out:%s'
52        % (os.path.join('..', infile), outfile), BUILD_DIR)
53    if rc:
54      print out
55      print 'Failed to build %s' % outfile
56      sys.exit(1)
57  else:
58    print '%s already built' % outfile
59  return outpath
60
61
62def main():
63  # Switch to our own dir.
64  os.chdir(os.path.dirname(os.path.abspath(__file__)))
65
66  if sys.argv[-1] == 'clean':
67    if os.path.exists(BUILD_DIR):
68      shutil.rmtree(BUILD_DIR)
69    for exe in glob.glob('*.exe'):
70      os.unlink(exe)
71    return 0
72
73  vcdir = os.environ.get('VCINSTALLDIR')
74  if not vcdir:
75    vcdir = get_vc_dir()
76    if not vcdir:
77      print 'Could not get VCINSTALLDIR. Run vsvars32.bat?'
78      return 1
79    os.environ['PATH'] += (';' + os.path.join(vcdir, 'bin') +
80                           ';' + os.path.join(vcdir, r'..\Common7\IDE'))
81
82  # Verify that we can find link.exe.
83  link = os.path.join(vcdir, 'bin', 'link.exe')
84  if not os.path.exists(link):
85    print 'link.exe not found at %s' % link
86    return 1
87
88  exe_name = build('limiter.cc')
89  for shim_exe in ('lib.exe', 'link.exe'):
90    newpath = '%s__LIMITER.exe' % shim_exe
91    shutil.copyfile(exe_name, newpath)
92    print '%s shim built. Use with msbuild like: "/p:LinkToolExe=%s"' \
93        % (shim_exe, os.path.abspath(newpath))
94
95  return 0
96
97
98if __name__ == '__main__':
99  sys.exit(main())
100