Android Library Dependency Management Script
I'll create a Python script to help manage dependencies across multiple Android library projects that use gradle/libs.versions.toml files. The script will handle the different ways dependencies can be declared and provide the requested functionality.
Solution
#!/usr/bin/env python3
import os
import toml
from pathlib import Path
from typing import Dict, List, Optional, Tuple, Union
import argparse
import sys
class DependencyManager:
def __init__(self, root_dir: str):
self.root_dir = Path(root_dir)
self.projects = self._find_projects()
def _find_projects(self) -> Dict[str, Path]:
"""Find all projects with libs.versions.toml files"""
projects = {}
for dirpath, _, filenames in os.walk(self.root_dir):
if "libs.versions.toml" in filenames:
project_name = Path(dirpath).name
projects[project_name] = Path(dirpath) / "gradle" / "libs.versions.toml"
return projects
def _parse_toml(self, toml_path: Path) -> dict:
"""Parse a TOML file"""
with open(toml_path, 'r') as f:
return toml.load(f)
def _get_version(self, versions: dict, version_ref: Union[str, dict]) -> str:
"""Get version string, handling both inline and reference versions"""
if isinstance(version_ref, str):
return version_ref
elif isinstance(version_ref, dict) and "ref" in version_ref:
return versions.get(version_ref["ref"], "UNKNOWN")
return "UNKNOWN"
def _get_module_coordinates(self, lib: dict) -> Optional[str]:
"""Get Maven coordinates from a library entry"""
if "module" in lib:
return lib["module"]
elif "group" in lib and "name" in lib:
return f"{lib['group']}:{lib['name']}"
return None
def list_all_dependencies(self) -> List[Dict]:
"""List all dependencies across all projects"""
results = []
for project_name, toml_path in self.projects.items():
data = self._parse_toml(toml_path)
versions = data.get("versions", {})
libraries = data.get("libraries", {})
for lib_name, lib_data in libraries.items():
if not isinstance(lib_data, dict):
continue
coordinates = self._get_module_coordinates(lib_data)
if not coordinates:
continue
version = self._get_version(versions, lib_data.get("version", "UNKNOWN"))
results.append({
"project": project_name,
"coordinates": coordinates,
"name": lib_name,
"version": version
})
return results
def find_dependency(self, coordinates: str) -> List[Dict]:
"""Find all projects that have a dependency with the given coordinates"""
dependencies = self.list_all_dependencies()
return [d for d in dependencies if d["coordinates"] == coordinates]
def change_dependency_version(self, coordinates: str, new_version: str) -> bool:
"""Change version of a dependency in all projects that have it"""
changed = False
for project_name, toml_path in self.projects.items():
data = self._parse_toml(toml_path)
versions = data.get("versions", {})
libraries = data.get("libraries", {})
modified = False
# Check libraries for the dependency
for lib_name, lib_data in libraries.items():
if not isinstance(lib_data, dict):
continue
current_coords = self._get_module_coordinates(lib_data)
if current_coords != coordinates:
continue
# Check if version is inline or reference
if "version" in lib_data:
if isinstance(lib_data["version"], str):
lib_data["version"] = new_version
modified = True
elif isinstance(lib_data["version"], dict) and "ref" in lib_data["version"]:
version_ref = lib_data["version"]["ref"]
if version_ref in versions:
versions[version_ref] = new_version
modified = True
if modified:
changed = True
# Write back the modified TOML
with open(toml_path, 'w') as f:
toml.dump(data, f)
print(f"Updated {coordinates} to version {new_version} in {project_name}")
return changed
def main():
parser = argparse.ArgumentParser(description="Manage Android library dependencies across multiple projects")
subparsers = parser.add_subparsers(dest="command", required=True)
# List command
list_parser = subparsers.add_parser("list", help="List all dependencies across all projects")
# Find command
find_parser = subparsers.add_parser("find", help="Find projects that have a specific dependency")
find_parser.add_argument("coordinates", help="Maven coordinates (groupId:artifactId) to search for")
# Change version command
change_parser = subparsers.add_parser("change", help="Change version of a dependency in all projects")
change_parser.add_argument("coordinates", help="Maven coordinates (groupId:artifactId) to update")
change_parser.add_argument("new_version", help="New version to set")
parser.add_argument("--root", default=".", help="Root directory to search for projects (default: current directory)")
args = parser.parse_args()
manager = DependencyManager(args.root)
if args.command == "list":
dependencies = manager.list_all_dependencies()
if not dependencies:
print("No dependencies found in any project.")
return
# Format output as a table
max_project = max(len(d["project"]) for d in dependencies) + 2
max_coords = max(len(d["coordinates"]) for d in dependencies) + 2
max_name = max(len(d["name"]) for d in dependencies) + 2
print(f"{'Project':<{max_project}}{'Coordinates':<{max_coords}}{'Name':<{max_name}}Version")
print("-" * (max_project + max_coords + max_name + 20))
for dep in sorted(dependencies, key=lambda x: (x["project"], x["coordinates"])):
print(f"{dep['project']:<{max_project}}{dep['coordinates']:<{max_coords}}{dep['name']:<{max_name}}{dep['version']}")
elif args.command == "find":
results = manager.find_dependency(args.coordinates)
if not results:
print(f"No projects found with dependency: {args.coordinates}")
return
print(f"Projects with dependency {args.coordinates}:")
for result in results:
print(f"- {result['project']}: version {result['version']} (declared as '{result['name']}')")
elif args.command == "change":
success = manager.change_dependency_version(args.coordinates, args.new_version)
if not success:
print(f"No projects found with dependency: {args.coordinates}")
else:
print(f"Successfully updated {args.coordinates} to version {args.new_version} in all projects")
if __name__ == "__main__":
main()