inspector: find Cargo.toml from binary

This commit is contained in:
Alberto Planas 2019-12-13 10:58:00 +01:00
parent b746a2ec5c
commit 31bfe95446
2 changed files with 38 additions and 4 deletions

View file

@ -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(","):

View file

@ -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):