From 31bfe954465aed47d9391fa7bf0cc95ea186b1e9 Mon Sep 17 00:00:00 2001 From: Alberto Planas Date: Fri, 13 Dec 2019 10:58:00 +0100 Subject: [PATCH] inspector: find Cargo.toml from binary --- rust2rpm/inspector.py | 29 +++++++++++++++++++++++++++++ rust2rpm/metadata.py | 13 +++++++++---- 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/rust2rpm/inspector.py b/rust2rpm/inspector.py index 0c9b8a0..f34c75c 100644 --- a/rust2rpm/inspector.py +++ b/rust2rpm/inspector.py @@ -1,9 +1,36 @@ import argparse +import glob +import os import sys from . import Metadata from .metadata import normalize_deps + +def _get_binaries(cargo_toml): + manifest = Metadata.manifest(cargo_toml, check=False) + return [ + t['name'] for t in manifest.get('targets', []) if 'bin' in t['kind'] + ] + + +def _cargo_toml(source_path, path, exclude_vendor=True): + """Find a Cargo.toml related with a binary.""" + # If path is aready a Cargo.toml file, we are done + if path.endswith('Cargo.toml'): + return os.path.join(source_path, path) + + binary = os.path.basename(path) + cargo_tomls = glob.glob(os.path.join(source_path, '**/Cargo.toml'), + recursive=True) + for cargo_toml in cargo_tomls: + if exclude_vendor and 'vendor' in cargo_toml.split(os.sep): + continue + + if binary in _get_binaries(cargo_toml): + return cargo_toml + + def main(): parser = argparse.ArgumentParser() group = parser.add_mutually_exclusive_group(required=True) @@ -16,6 +43,7 @@ def main(): group.add_argument("-R", "--requires", action="store_true", help="Print Requires") group.add_argument("-BR", "--build-requires", action="store_true", help="Print BuildRequires") group.add_argument("-TR", "--test-requires", action="store_true", help="Print TestRequires") + group.add_argument("-p", "--path", default=os.getcwd(), help="Path where the source project is living") fgroup = parser.add_mutually_exclusive_group() fgroup.add_argument("-a", "--all-features", action="store_true", help="Activate all features") fgroup.add_argument("-f", "--features", default="default", help="Feature(s) to work on (comma-separated)") @@ -23,6 +51,7 @@ def main(): args = parser.parse_args() files = args.file or sys.stdin.readlines() + files = [_cargo_toml(args.path, f) for f in files] features = set() for f in args.features.split(","): diff --git a/rust2rpm/metadata.py b/rust2rpm/metadata.py index 95933ec..f0d7f3d 100644 --- a/rust2rpm/metadata.py +++ b/rust2rpm/metadata.py @@ -349,10 +349,15 @@ class Metadata: raise @staticmethod - def manifest(path): - return json.loads( - subprocess.check_output(["cargo", "read-manifest", - f"--manifest-path={path}"])) + def manifest(path, check=True): + manifest = {} + output = subprocess.run( + ["cargo", "read-manifest", f"--manifest-path={path}"], + check=check, capture_output=True + ) + if not output.returncode: + manifest = json.loads(output.stdout) + return manifest @staticmethod def metadata(path, deps=False):