Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / build / config / linux / pkg-config.py
blobfadcc0bbcf9dfbabd92e24475ecd2d7ed91b3ebd
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 parser.add_option('--libdir', action='store_true', dest='libdir')
116 (options, args) = parser.parse_args()
118 # Make a list of regular expressions to strip out.
119 strip_out = []
120 if options.strip_out != None:
121 for regexp in options.strip_out:
122 strip_out.append(re.compile(regexp))
124 SetConfigPath(options)
125 if options.sysroot:
126 prefix = GetPkgConfigPrefixToStrip(args)
127 else:
128 prefix = ''
130 if options.atleast_version:
131 # When asking for the return value, just run pkg-config and print the return
132 # value, no need to do other work.
133 if not subprocess.call([options.pkg_config,
134 "--atleast-version=" + options.atleast_version] +
135 args,
136 env=os.environ):
137 print "true"
138 else:
139 print "false"
140 sys.exit(0)
142 if options.libdir:
143 try:
144 libdir = subprocess.check_output([options.pkg_config,
145 "--variable=libdir"] +
146 args,
147 env=os.environ)
148 except:
149 print "Error from pkg-config."
150 sys.exit(1)
151 sys.stdout.write(libdir.strip())
152 sys.exit(0)
154 try:
155 flag_string = subprocess.check_output(
156 [ options.pkg_config, "--cflags", "--libs-only-l", "--libs-only-L" ] +
157 args, env=os.environ)
158 # For now just split on spaces to get the args out. This will break if
159 # pkgconfig returns quoted things with spaces in them, but that doesn't seem
160 # to happen in practice.
161 all_flags = flag_string.strip().split(' ')
162 except:
163 print "Could not run pkg-config."
164 sys.exit(1)
167 sysroot = options.sysroot
168 if not sysroot:
169 sysroot = ''
171 includes = []
172 cflags = []
173 libs = []
174 lib_dirs = []
175 ldflags = []
177 for flag in all_flags[:]:
178 if len(flag) == 0 or MatchesAnyRegexp(flag, strip_out):
179 continue;
181 if flag[:2] == '-l':
182 libs.append(RewritePath(flag[2:], prefix, sysroot))
183 elif flag[:2] == '-L':
184 lib_dirs.append(RewritePath(flag[2:], prefix, sysroot))
185 elif flag[:2] == '-I':
186 includes.append(RewritePath(flag[2:], prefix, sysroot))
187 elif flag[:3] == '-Wl':
188 ldflags.append(flag)
189 elif flag == '-pthread':
190 # Many libs specify "-pthread" which we don't need since we always include
191 # this anyway. Removing it here prevents a bunch of duplicate inclusions on
192 # the command line.
193 pass
194 else:
195 cflags.append(flag)
197 # Output a GN array, the first one is the cflags, the second are the libs. The
198 # JSON formatter prints GN compatible lists when everything is a list of
199 # strings.
200 print json.dumps([includes, cflags, libs, lib_dirs, ldflags])