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
6"""Compiler version checking tool for gcc
7
8Print gcc version as XY if you are running gcc X.Y.*.
9This is used to tweak build flags for gcc 4.4.
10"""
11
12import os
13import re
14import subprocess
15import sys
16
17def GetVersion(compiler):
18  try:
19    # Note that compiler could be something tricky like "distcc g++".
20    compiler = compiler + " -dumpversion"
21    pipe = subprocess.Popen(compiler, shell=True,
22                            stdout=subprocess.PIPE, stderr=subprocess.PIPE)
23    gcc_output, gcc_error = pipe.communicate()
24    if pipe.returncode:
25      raise subprocess.CalledProcessError(pipe.returncode, compiler)
26
27    result = re.match(r"(\d+)\.(\d+)", gcc_output)
28    return result.group(1) + result.group(2)
29  except Exception, e:
30    if gcc_error:
31      sys.stderr.write(gcc_error)
32    print >> sys.stderr, "compiler_version.py failed to execute:", compiler
33    print >> sys.stderr, e
34    return ""
35
36def main():
37  # Check if CXX environment variable exists and
38  # if it does use that compiler.
39  cxx = os.getenv("CXX", None)
40  if cxx:
41    cxxversion = GetVersion(cxx)
42    if cxxversion != "":
43      print cxxversion
44      return 0
45  else:
46    # Otherwise we check the g++ version.
47    gccversion = GetVersion("g++")
48    if gccversion != "":
49      print gccversion
50      return 0
51
52  return 1
53
54if __name__ == "__main__":
55  sys.exit(main())
56