1#!/usr/bin/env python3 2# Copyright (C) 2023 The Android Open Source Project 3# 4# Licensed under the Apache License, Version 2.0 (the "License"); 5# you may not use this file except in compliance with the License. 6# You may obtain a copy of the License at 7# 8# http://www.apache.org/licenses/LICENSE-2.0 9# 10# Unless required by applicable law or agreed to in writing, software 11# distributed under the License is distributed on an "AS IS" BASIS, 12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13# See the License for the specific language governing permissions and 14# limitations under the License. 15 16"""Wrapper of pkg-config command line to format output for gn. 17 18Parses the pkg-config output and format it into json, 19so that it can be used in GN files easily. 20 21Usage: 22 pkg-config_wrapper.py pkg-config pkg1 pkg2 ... 23 24Specifically, this script does not expect any additional flags. 25""" 26 27import json 28import shlex 29import subprocess 30import sys 31 32 33def get_shell_output(cmd): 34 """Run |cmd| and return output as a list.""" 35 result = subprocess.run( 36 cmd, encoding="utf-8", stdout=subprocess.PIPE, check=False 37 ) 38 if result.returncode: 39 sys.exit(result.returncode) 40 return shlex.split(result.stdout) 41 42 43def main(argv): 44 if len(argv) < 2: 45 sys.exit(f"Usage: {sys.argv[0]} <pkg-config> <modules>") 46 47 cflags = get_shell_output(argv + ["--cflags"]) 48 libs = [] 49 lib_dirs = [] 50 ldflags = [] 51 for ldflag in get_shell_output(argv + ["--libs"]): 52 if ldflag.startswith("-l"): 53 # Strip -l. 54 libs.append(ldflag[2:]) 55 elif ldflag.startswith("-L"): 56 # Strip -L. 57 lib_dirs.append(ldflag[2:]) 58 else: 59 ldflags.append(ldflag) 60 61 # Set sort_keys=True for stabilization. 62 result = { 63 "cflags": cflags, 64 "libs": libs, 65 "lib_dirs": lib_dirs, 66 "ldflags": ldflags, 67 } 68 json.dump(result, sys.stdout, sort_keys=True) 69 70 71if __name__ == "__main__": 72 sys.exit(main(sys.argv[1:])) 73