1# This script implements the workspace inheritance mechanism described
2# here: https://doc.rust-lang.org/cargo/reference/workspaces.html#the-package-table
3#
4# Please run `mypy --strict`, `black`, and `isort --profile black` on this after editing, thanks!
5
6import sys
7from typing import Any
8
9import tomli
10import tomli_w
11
12
13def load_file(path: str) -> dict[str, Any]:
14 with open(path, "rb") as f:
15 return tomli.load(f)
16
17
18# This replicates the dependency merging logic from Cargo.
19# See `inner_dependency_inherit_with`:
20# https://github.com/rust-lang/cargo/blob/4de0094ac78743d2c8ff682489e35c8a7cafe8e4/src/cargo/util/toml/mod.rs#L982
21def replace_key(
22 workspace_manifest: dict[str, Any], table: dict[str, Any], section: str, key: str
23) -> bool:
24 if (
25 isinstance(table[key], dict)
26 and "workspace" in table[key]
27 and table[key]["workspace"] is True
28 ):
29 print("replacing " + key)
30
31 local_dep = table[key]
32 del local_dep["workspace"]
33
34 workspace_dep = workspace_manifest[section][key]
35
36 if section == "dependencies":
37 if isinstance(workspace_dep, str):
38 workspace_dep = {"version": workspace_dep}
39
40 final: dict[str, Any] = workspace_dep.copy()
41
42 merged_features = local_dep.pop("features", []) + workspace_dep.get("features", [])
43 if merged_features:
44 final["features"] = merged_features
45
46 local_default_features = local_dep.pop("default-features", None)
47 workspace_default_features = workspace_dep.get("default-features")
48
49 if not workspace_default_features and local_default_features:
50 final["default-features"] = True
51
52 optional = local_dep.pop("optional", False)
53 if optional:
54 final["optional"] = True
55
56 if "package" in local_dep:
57 final["package"] = local_dep.pop("package")
58
59 if local_dep:
60 raise Exception(f"Unhandled keys in inherited dependency {key}: {local_dep}")
61
62 table[key] = final
63 elif section == "package":
64 table[key] = workspace_dep
65
66 return True
67
68 return False
69
70
71def replace_dependencies(
72 workspace_manifest: dict[str, Any], root: dict[str, Any]
73) -> bool:
74 changed = False
75
76 for key in ["dependencies", "dev-dependencies", "build-dependencies"]:
77 if key in root:
78 for k in root[key].keys():
79 changed |= replace_key(workspace_manifest, root[key], "dependencies", k)
80
81 return changed
82
83
84def main() -> None:
85 top_cargo_toml = load_file(sys.argv[2])
86
87 if "workspace" not in top_cargo_toml:
88 # If top_cargo_toml is not a workspace manifest, then this script was probably
89 # ran on something that does not actually use workspace dependencies
90 print(f"{sys.argv[2]} is not a workspace manifest, doing nothing.")
91 return
92
93 crate_manifest = load_file(sys.argv[1])
94 workspace_manifest = top_cargo_toml["workspace"]
95
96 if "workspace" in crate_manifest:
97 return
98
99 changed = False
100
101 for key in crate_manifest["package"].keys():
102 changed |= replace_key(
103 workspace_manifest, crate_manifest["package"], "package", key
104 )
105
106 changed |= replace_dependencies(workspace_manifest, crate_manifest)
107
108 if "target" in crate_manifest:
109 for key in crate_manifest["target"].keys():
110 changed |= replace_dependencies(
111 workspace_manifest, crate_manifest["target"][key]
112 )
113
114 if (
115 "lints" in crate_manifest
116 and "workspace" in crate_manifest["lints"]
117 and crate_manifest["lints"]["workspace"] is True
118 ):
119 crate_manifest["lints"] = workspace_manifest["lints"]
120
121 if not changed:
122 return
123
124 with open(sys.argv[1], "wb") as f:
125 tomli_w.dump(crate_manifest, f)
126
127
128if __name__ == "__main__":
129 main()