1111from typing import Generator
1212from typing import Sequence
1313
14- import toml
15-
1614import pre_commit .constants as C
1715from pre_commit import parse_shebang
1816from pre_commit .envcontext import envcontext
@@ -82,18 +80,16 @@ def in_env(
8280
8381
8482def _add_dependencies (
85- cargo_toml_path : str ,
83+ prefix : Prefix ,
8684 additional_dependencies : set [str ],
8785) -> None :
88- with open (cargo_toml_path , 'r+' ) as f :
89- cargo_toml = toml .load (f )
90- cargo_toml .setdefault ('dependencies' , {})
91- for dep in additional_dependencies :
92- name , _ , spec = dep .partition (':' )
93- cargo_toml ['dependencies' ][name ] = spec or '*'
94- f .seek (0 )
95- toml .dump (cargo_toml , f )
96- f .truncate ()
86+ crates = []
87+ for dep in additional_dependencies :
88+ name , _ , spec = dep .partition (':' )
89+ crate = f'{ name } @{ spec or "*" } '
90+ crates .append (crate )
91+
92+ helpers .run_setup_cmd (prefix , ('cargo' , 'add' , * crates ))
9793
9894
9995def install_rust_with_toolchain (toolchain : str ) -> None :
@@ -151,9 +147,6 @@ def install_environment(
151147 }
152148 lib_deps = set (additional_dependencies ) - cli_deps
153149
154- if len (lib_deps ) > 0 :
155- _add_dependencies (prefix .path ('Cargo.toml' ), lib_deps )
156-
157150 with clean_path_on_failure (directory ):
158151 packages_to_install : set [tuple [str , ...]] = {('--path' , '.' )}
159152 for cli_dep in cli_deps :
@@ -168,6 +161,9 @@ def install_environment(
168161 if version != 'system' :
169162 install_rust_with_toolchain (_rust_toolchain (version ))
170163
164+ if len (lib_deps ) > 0 :
165+ _add_dependencies (prefix , lib_deps )
166+
171167 for args in packages_to_install :
172168 cmd_output_b (
173169 'cargo' , 'install' , '--bins' , '--root' , directory , * args ,
0 commit comments