summaryrefslogtreecommitdiff
path: root/rules/CC/prebuilt/read_pkgconfig.py
blob: cb4154f6339c11c27252005015d8720617b2ee28 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#!/usr/bin/env python3
# Copyright 2023 Huawei Cloud Computing Technology Co., Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import subprocess
import sys
from pathlib import Path


def run_pkgconfig(args: list[str], env: dict[str, str]) -> str:
    result = subprocess.run(["pkg-config"] + args, env=env, capture_output=True)
    if result.returncode != 0:
        print(result.stderr.decode("utf-8"), file=sys.stderr)
        exit(1)
    return result.stdout.decode("utf-8").strip()


def read_ldflags(pkg: str, env: dict[str, str]) -> str:
    def libname(filename: str) -> str:
        return filename.split(".")[0]

    local_libs = {
        libname(f)
        for it in os.walk(".") for f in it[2] if f.startswith("lib")
    }

    link_flags = run_pkgconfig(["--libs-only-l", pkg], env).split(" ")

    # deduplicate, keep right-most
    seen: set[str] = set()
    link_flags = [
        f for f in link_flags[::-1] if f not in seen and not seen.add(f)
    ][::-1]

    def is_local(flag: str) -> bool:
        if not flag.startswith("-l"):
            return False
        lib = libname(flag[3:]) if flag.startswith("-l:") else f"lib{flag[2:]}"
        return lib in local_libs

    return " ".join([f for f in link_flags if not is_local(f)])


def read_pkgconfig():
    if len(sys.argv) < 3:
        print(f"usage: read_pkgconfig OUT_NAME PC_FILE")
        exit(1)

    name = sys.argv[1]
    pkg = Path(sys.argv[2]).stem
    env = dict(os.environ, PKG_CONFIG_PATH="./lib/pkgconfig")

    if name.endswith(".cflags"):
        data = run_pkgconfig(["--cflags-only-other", pkg], env)
    else:
        data = read_ldflags(pkg, env)

    with open(f"{name}", 'w') as f:
        f.write(data)


if __name__ == "__main__":
    read_pkgconfig()