ozone: evdev: Sync caps lock LED state to evdev
[chromium-blink-merge.git] / build / config / linux / pkg-config.py
bloba4f4703bd3814ed971845042c5eda0e8917f5913
1 # Copyright (c) 2013 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file.
5 import json
6 import os
7 import subprocess
8 import sys
9 import re
10 from optparse import OptionParser
12 # This script runs pkg-config, optionally filtering out some results, and
13 # returns the result.
15 # The result will be [ <includes>, <cflags>, <libs>, <lib_dirs>, <ldflags> ]
16 # where each member is itself a list of strings.
18 # You can filter out matches using "-v <regexp>" where all results from
19 # pkgconfig matching the given regular expression will be ignored. You can
20 # specify more than one regular expression my specifying "-v" more than once.
22 # You can specify a sysroot using "-s <sysroot>" where sysroot is the absolute
23 # system path to the sysroot used for compiling. This script will attempt to
24 # generate correct paths for the sysroot.
26 # When using a sysroot, you must also specify the architecture via
27 # "-a <arch>" where arch is either "x86" or "x64".
29 # Additionally, you can specify the option --atleast-version. This will skip
30 # the normal outputting of a dictionary and instead print true or false,
31 # depending on the return value of pkg-config for the given package.
33 # If this is run on non-Linux platforms, just return nothing and indicate
34 # success. This allows us to "kind of emulate" a Linux build from other
35 # platforms.
36 if sys.platform.find("linux") == -1:
37 print "[[],[],[],[],[]]"
38 sys.exit(0)
41 def SetConfigPath(options):
42 """Set the PKG_CONFIG_PATH environment variable.
43 This takes into account any sysroot and architecture specification from the
44 options on the given command line."""
46 sysroot = options.sysroot
47 if not sysroot:
48 sysroot = ""
50 # Compute the library path name based on the architecture.
51 arch = options.arch
52 if sysroot and not arch:
53 print "You must specify an architecture via -a if using a sysroot."
54 sys.exit(1)
55 if arch == 'x64':
56 libpath = 'lib64'
57 else:
58 libpath = 'lib'
60 # Add the sysroot path to the environment's PKG_CONFIG_PATH
61 config_path = sysroot + '/usr/' + libpath + '/pkgconfig'
62 config_path += ':' + sysroot + '/usr/share/pkgconfig'
63 if 'PKG_CONFIG_PATH' in os.environ:
64 os.environ['PKG_CONFIG_PATH'] += ':' + config_path
65 else:
66 os.environ['PKG_CONFIG_PATH'] = config_path
69 def GetPkgConfigPrefixToStrip(args):
70 """Returns the prefix from pkg-config where packages are installed.
71 This returned prefix is the one that should be stripped from the beginning of
72 directory names to take into account sysroots."""
73 # Some sysroots, like the Chromium OS ones, may generate paths that are not
74 # relative to the sysroot. For example,
75 # /path/to/chroot/build/x86-generic/usr/lib/pkgconfig/pkg.pc may have all
76 # paths relative to /path/to/chroot (i.e. prefix=/build/x86-generic/usr)
77 # instead of relative to /path/to/chroot/build/x86-generic (i.e prefix=/usr).
78 # To support this correctly, it's necessary to extract the prefix to strip
79 # from pkg-config's |prefix| variable.
80 prefix = subprocess.check_output(["pkg-config", "--variable=prefix"] + args,
81 env=os.environ)
82 if prefix[-4] == '/usr':
83 return prefix[4:]
84 return prefix
87 def MatchesAnyRegexp(flag, list_of_regexps):
88 """Returns true if the first argument matches any regular expression in the
89 given list."""
90 for regexp in list_of_regexps:
91 if regexp.search(flag) != None:
92 return True
93 return False
96 def RewritePath(path, strip_prefix, sysroot):
97 """Rewrites a path by stripping the prefix and prepending the sysroot."""
98 if os.path.isabs(path) and not path.startswith(sysroot):
99 if path.startswith(strip_prefix):
100 path = path[len(strip_prefix):]
101 path = path.lstrip('/')
102 return os.path.join(sysroot, path)
103 else:
104 return path
107 parser = OptionParser()
108 parser.add_option('-p', action='store', dest='pkg_config', type='string',
109 default='pkg-config')
110 parser.add_option('-v', action='append', dest='strip_out', type='string')
111 parser.add_option('-s', action='store', dest='sysroot', type='string')
112 parser.add_option('-a', action='store', dest='arch', type='string')
113 parser.add_option('--atleast-version', action='store',
114 dest='atleast_version', type='string')
115 (options, args) = parser.parse_args()
117 # Make a list of regular expressions to strip out.
118 strip_out = []
119 if options.strip_out != None:
120 for regexp in options.strip_out:
121 strip_out.append(re.compile(regexp))
123 SetConfigPath(options)
124 if options.sysroot:
125 prefix = GetPkgConfigPrefixToStrip(args)
126 else:
127 prefix = ''
129 if options.atleast_version:
130 # When asking for the return value, just run pkg-config and print the return
131 # value, no need to do other work.
132 if not subprocess.call([options.pkg_config,
133 "--atleast-version=" + options.atleast_version] +
134 args,
135 env=os.environ):
136 print "true"
137 else:
138 print "false"
139 sys.exit(0)
141 try:
142 flag_string = subprocess.check_output(
143 [ options.pkg_config, "--cflags", "--libs-only-l", "--libs-only-L" ] +
144 args, env=os.environ)
145 # For now just split on spaces to get the args out. This will break if
146 # pkgconfig returns quoted things with spaces in them, but that doesn't seem
147 # to happen in practice.
148 all_flags = flag_string.strip().split(' ')
149 except:
150 print "Could not run pkg-config."
151 sys.exit(1)
154 sysroot = options.sysroot
155 if not sysroot:
156 sysroot = ''
158 includes = []
159 cflags = []
160 libs = []
161 lib_dirs = []
162 ldflags = []
164 for flag in all_flags[:]:
165 if len(flag) == 0 or MatchesAnyRegexp(flag, strip_out):
166 continue;
168 if flag[:2] == '-l':
169 libs.append(RewritePath(flag[2:], prefix, sysroot))
170 elif flag[:2] == '-L':
171 lib_dirs.append(RewritePath(flag[2:], prefix, sysroot))
172 elif flag[:2] == '-I':
173 includes.append(RewritePath(flag[2:], prefix, sysroot))
174 elif flag[:3] == '-Wl':
175 ldflags.append(flag)
176 elif flag == '-pthread':
177 # Many libs specify "-pthread" which we don't need since we always include
178 # this anyway. Removing it here prevents a bunch of duplicate inclusions on
179 # the command line.
180 pass
181 else:
182 cflags.append(flag)
184 # Output a GN array, the first one is the cflags, the second are the libs. The
185 # JSON formatter prints GN compatible lists when everything is a list of
186 # strings.
187 print json.dumps([includes, cflags, libs, lib_dirs, ldflags])