I'll help you create a Python script to manage Android library dependencies across multiple projects. This script will parse TOML files and handle both inline and reference-based version declarations.
#!/usr/bin/env python3
"""
Android Library Dependency Manager
Manages dependencies across multiple Android library projects using gradle/libs.versions.toml files.
"""
import os
import sys
import argparse
from pathlib import Path
from typing import Dict, List, Tuple, Optional, Set
import toml
from dataclasses import dataclass
from collections import defaultdict
@dataclass
class Dependency:
"""Represents a dependency with its details."""
project_name: str
toml_key: str
group_id: str
artifact_id: str
version: str
version_ref: Optional[str] = None
@property
def maven_coordinate(self) -> str:
"""Returns the Maven coordinate in format groupId:artifactId."""
return f"{self.group_id}:{self.artifact_id}"
class DependencyManager:
"""Manages dependencies across multiple Android projects."""
def __init__(self, root_dirs: List[str]):
"""
Initialize the dependency manager.
Args:
root_dirs: List of root directories to search for Android projects
"""
self.root_dirs = root_dirs
self.projects: Dict[str, Path] = {}
self.dependencies: List[Dependency] = []
self._scan_projects()
self._load_dependencies()
def _scan_projects(self):
"""Scan for Android projects containing gradle/libs.versions.toml."""
for root_dir in self.root_dirs:
root_path = Path(root_dir).resolve()
if not root_path.exists():
print(f"Warning: Directory {root_dir} does not exist")
continue
# Check if the root directory itself is a project
toml_path = root_path / "gradle" / "libs.versions.toml"
if toml_path.exists():
self.projects[root_path.name] = root_path
# Also check subdirectories
for item in root_path.iterdir():
if item.is_dir():
toml_path = item / "gradle" / "libs.versions.toml"
if toml_path.exists():
self.projects[item.name] = item
def _load_dependencies(self):
"""Load all dependencies from discovered projects."""
self.dependencies.clear()
for project_name, project_path in self.projects.items():
toml_path = project_path / "gradle" / "libs.versions.toml"
try:
data = toml.load(toml_path)
self._parse_toml(project_name, data)
except Exception as e:
print(f"Error loading {toml_path}: {e}")
def _parse_toml(self, project_name: str, data: dict):
"""Parse a TOML file and extract dependencies."""
versions = data.get('versions', {})
libraries = data.get('libraries', {})
for lib_key, lib_data in libraries.items():
if isinstance(lib_data, dict):
# Extract group and artifact
if 'module' in lib_data:
# Format: module = "groupId:artifactId"
parts = lib_data['module'].split(':')
if len(parts) == 2:
group_id, artifact_id = parts
else:
continue
elif 'group' in lib_data and 'name' in lib_data:
# Format: group = "groupId", name = "artifactId"
group_id = lib_data['group']
artifact_id = lib_data['name']
else:
continue
# Extract version
version = None
version_ref = None
if 'version' in lib_data:
version_data = lib_data['version']
if isinstance(version_data, str):
# Inline version
version = version_data
elif isinstance(version_data, dict) and 'ref' in version_data:
# Version reference
version_ref = version_data['ref']
version = versions.get(version_ref, "UNKNOWN")
if version:
dep = Dependency(
project_name=project_name,
toml_key=lib_key,
group_id=group_id,
artifact_id=artifact_id,
version=version,
version_ref=version_ref
)
self.dependencies.append(dep)
def list_all_dependencies(self):
"""List all dependencies across all projects."""
if not self.dependencies:
print("No dependencies found.")
return
# Group by project
by_project = defaultdict(list)
for dep in self.dependencies:
by_project[dep.project_name].append(dep)
# Sort and display
for project in sorted(by_project.keys()):
print(f"\n{project}:")
print("-" * (len(project) + 1))
deps = sorted(by_project[project], key=lambda d: d.maven_coordinate)
for dep in deps:
version_info = f"v{dep.version}"
if dep.version_ref:
version_info += f" (ref: {dep.version_ref})"
print(f" {dep.toml_key}: {dep.maven_coordinate} @ {version_info}")
def find_by_coordinate(self, coordinate: str):
"""Find all projects that have a specific dependency."""
matching_deps = [d for d in self.dependencies if d.maven_coordinate == coordinate]
if not matching_deps:
print(f"No projects found with dependency: {coordinate}")
return
print(f"\nProjects with dependency {coordinate}:")
print("-" * (len(coordinate) + 25))
for dep in sorted(matching_deps, key=lambda d: d.project_name):
version_info = f"v{dep.version}"
if dep.version_ref:
version_info += f" (ref: {dep.version_ref})"
print(f" {dep.project_name}: {version_info} (key: {dep.toml_key})")
def update_version(self, coordinate: str, new_version: str):
"""Update the version of a dependency across all projects."""
matching_deps = [d for d in self.dependencies if d.maven_coordinate == coordinate]
if not matching_deps:
print(f"No projects found with dependency: {coordinate}")
return
print(f"\nUpdating {coordinate} to version {new_version}...")
# Group by project to handle each TOML file once
by_project = defaultdict(list)
for dep in matching_deps:
by_project[dep.project_name].append(dep)
for project_name, deps in by_project.items():
project_path = self.projects[project_name]
toml_path = project_path / "gradle" / "libs.versions.toml"
try:
# Load the TOML file
data = toml.load(toml_path)
# Update versions
for dep in deps:
if dep.version_ref:
# Update in versions section
if 'versions' in data and dep.version_ref in data['versions']:
data['versions'][dep.version_ref] = new_version
print(f" Updated {project_name}: {dep.toml_key} (via ref: {dep.version_ref})")
else:
# Update inline version
if 'libraries' in data and dep.toml_key in data['libraries']:
data['libraries'][dep.toml_key]['version'] = new_version
print(f" Updated {project_name}: {dep.toml_key} (inline)")
# Write back the TOML file
with open(toml_path, 'w') as f:
toml.dump(data, f)
except Exception as e:
print(f" Error updating {project_name}: {e}")
# Reload dependencies to reflect changes
self._load_dependencies()
print("\nUpdate complete!")
def main():
"""Main entry point for the script."""
parser = argparse.ArgumentParser(
description="Manage Android library dependencies across multiple projects",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# List all dependencies in current directory and subdirectories
%(prog)s list
# List all dependencies in specific directories
%(prog)s list /path/to/libs /path/to/more/libs
# Find which projects use a specific dependency
%(prog)s find com.google.android.material:material
# Update version of a dependency across all projects
%(prog)s update com.google.android.material:material 1.9.0
"""
)
subparsers = parser.add_subparsers(dest='command', help='Available commands')
# List command
list_parser = subparsers.add_parser('list', help='List all dependencies')
list_parser.add_argument('directories', nargs='*', default=['.'],
help='Directories to scan (default: current directory)')
# Find command
find_parser = subparsers.add_parser('find', help='Find projects with a specific dependency')
find_parser.add_argument('coordinate', help='Maven coordinate (groupId:artifactId)')
find_parser.add_argument('directories', nargs='*', default=['.'],
help='Directories to scan (default: current directory)')
# Update command
update_parser = subparsers.add_parser('update', help='Update dependency version')
update_parser.add_argument('coordinate', help='Maven coordinate (groupId:artifactId)')
update_parser.add_argument('version', help='New version')
update_parser.add_argument('directories', nargs='*', default=['.'],
help='Directories to scan (default: current directory)')
args = parser.parse_args()
if not args.command:
parser.print_help()
return
# Get directories based on command
if args.command == 'list':
directories = args.directories
elif args.command == 'find':
directories = args.directories
elif args.command == 'update':
directories = args.directories
else:
directories = ['.']
# Create manager and execute command
manager = DependencyManager(directories)
if not manager.projects:
print("No Android projects found with gradle/libs.versions.toml files.")
return
print(f"Found {len(manager.projects)} project(s): {', '.join(sorted(manager.projects.keys()))}")
if args.command == 'list':
manager.list_all_dependencies()
elif args.command == 'find':
manager.find_by_coordinate(args.coordinate)
elif args.command == 'update':
manager.update_version(args.coordinate, args.version)
if __name__ == '__main__':
main()