#!/usr/bin/env python3 """Generate Flatpak source entries for Cargo dependencies from Cargo.lock. Usage: python3 build-aux/flatpak-cargo-generator.py [Cargo.lock] \ -o build-aux/cargo-sources.json """ import json import sys try: import tomllib except ImportError: try: import tomli as tomllib # pip install tomli except ImportError: print("Error: requires Python 3.11+ or the 'tomli' package", file=sys.stderr) sys.exit(1) CRATES_IO_DL = "https://static.crates.io/crates" REGISTRY_SOURCE = "registry+https://github.com/rust-lang/crates.io-index" def main() -> None: # Parse arguments lockfile = "Cargo.lock" output_file = None args = sys.argv[1:] i = 0 while i < len(args): if args[i] == "-o" and i + 1 < len(args): output_file = args[i + 1] i += 2 else: lockfile = args[i] i += 1 with open(lockfile, "rb") as f: lock = tomllib.load(f) sources = [] checksums = {} for pkg in lock.get("package", []): name = pkg["name"] version = pkg["version"] source = pkg.get("source", "") checksum = pkg.get("checksum") # Only vendor packages from crates.io (they have a checksum) if source == REGISTRY_SOURCE and checksum: dest = f"cargo-vendor/{name}-{version}" sources.append( { "type": "archive", "archive-type": "tar-gzip", "url": f"{CRATES_IO_DL}/{name}/{version}/download", "sha256": checksum, "dest": dest, } ) checksums[f"{name}-{version}"] = checksum output = json.dumps(sources, indent=2) if output_file: with open(output_file, "w") as f: f.write(output) # Also write checksums file checksums_file = output_file.replace(".json", "-checksums.json") with open(checksums_file, "w") as f: json.dump(checksums, f) print(f"Generated {output_file} and {checksums_file}") else: print(output) if __name__ == "__main__": main()