1use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
2use std::path::{Path, PathBuf};
3use std::sync::Arc;
4use std::{env, fs};
5
6use crate::core::compiler::{CompileKind, DefaultExecutor, Executor, UnitOutput};
7use crate::core::{Dependency, Edition, Package, PackageId, SourceId, Target, Workspace};
8use crate::ops::{common_for_install_and_uninstall::*, FilterRule};
9use crate::ops::{CompileFilter, Packages};
10use crate::sources::source::Source;
11use crate::sources::{GitSource, PathSource, SourceConfigMap};
12use crate::util::context::FeatureUnification;
13use crate::util::errors::CargoResult;
14use crate::util::{Filesystem, GlobalContext, Rustc};
15use crate::{drop_println, ops};
16
17use anyhow::{bail, Context as _};
18use cargo_util::paths;
19use cargo_util_schemas::core::PartialVersion;
20use itertools::Itertools;
21use semver::VersionReq;
22use tempfile::Builder as TempFileBuilder;
23
24struct Transaction {
25 bins: Vec<PathBuf>,
26}
27
28impl Transaction {
29 fn success(mut self) {
30 self.bins.clear();
31 }
32}
33
34impl Drop for Transaction {
35 fn drop(&mut self) {
36 for bin in self.bins.iter() {
37 let _ = paths::remove_file(bin);
38 }
39 }
40}
41
42struct InstallablePackage<'gctx> {
43 gctx: &'gctx GlobalContext,
44 opts: ops::CompileOptions,
45 root: Filesystem,
46 source_id: SourceId,
47 vers: Option<VersionReq>,
48 force: bool,
49 no_track: bool,
50 pkg: Package,
51 ws: Workspace<'gctx>,
52 rustc: Rustc,
53 target: String,
54}
55
56impl<'gctx> InstallablePackage<'gctx> {
57 pub fn new(
59 gctx: &'gctx GlobalContext,
60 root: Filesystem,
61 map: SourceConfigMap<'_>,
62 krate: Option<&str>,
63 source_id: SourceId,
64 from_cwd: bool,
65 vers: Option<&VersionReq>,
66 original_opts: &ops::CompileOptions,
67 force: bool,
68 no_track: bool,
69 needs_update_if_source_is_index: bool,
70 current_rust_version: Option<&PartialVersion>,
71 lockfile_path: Option<&Path>,
72 ) -> CargoResult<Option<Self>> {
73 if let Some(name) = krate {
74 if name == "." {
75 bail!(
76 "To install the binaries for the package in current working \
77 directory use `cargo install --path .`. \n\
78 Use `cargo build` if you want to simply build the package."
79 )
80 }
81 }
82
83 let dst = root.join("bin").into_path_unlocked();
84 let pkg = {
85 let dep = {
86 if let Some(krate) = krate {
87 let vers = if let Some(vers) = vers {
88 Some(vers.to_string())
89 } else if source_id.is_registry() {
90 Some(String::from("*"))
93 } else {
94 None
95 };
96 Some(Dependency::parse(krate, vers.as_deref(), source_id)?)
97 } else {
98 None
99 }
100 };
101
102 if source_id.is_git() {
103 let mut source = GitSource::new(source_id, gctx)?;
104 select_pkg(
105 &mut source,
106 dep,
107 |git: &mut GitSource<'_>| git.read_packages(),
108 gctx,
109 current_rust_version,
110 )?
111 } else if source_id.is_path() {
112 let mut src = path_source(source_id, gctx)?;
113 if !src.path().is_dir() {
114 bail!(
115 "`{}` is not a directory. \
116 --path must point to a directory containing a Cargo.toml file.",
117 src.path().display()
118 )
119 }
120 if !src.path().join("Cargo.toml").exists() {
121 if from_cwd {
122 bail!(
123 "`{}` is not a crate root; specify a crate to \
124 install from crates.io, or use --path or --git to \
125 specify an alternate source",
126 src.path().display()
127 );
128 } else if src.path().join("cargo.toml").exists() {
129 bail!(
130 "`{}` does not contain a Cargo.toml file, but found cargo.toml please try to rename it to Cargo.toml. \
131 --path must point to a directory containing a Cargo.toml file.",
132 src.path().display()
133 )
134 } else {
135 bail!(
136 "`{}` does not contain a Cargo.toml file. \
137 --path must point to a directory containing a Cargo.toml file.",
138 src.path().display()
139 )
140 }
141 }
142 select_pkg(
143 &mut src,
144 dep,
145 |path: &mut PathSource<'_>| path.root_package().map(|p| vec![p]),
146 gctx,
147 current_rust_version,
148 )?
149 } else if let Some(dep) = dep {
150 let mut source = map.load(source_id, &HashSet::new())?;
151 if let Ok(Some(pkg)) = installed_exact_package(
152 dep.clone(),
153 &mut source,
154 gctx,
155 original_opts,
156 &root,
157 &dst,
158 force,
159 lockfile_path,
160 ) {
161 let msg = format!(
162 "package `{}` is already installed, use --force to override",
163 pkg
164 );
165 gctx.shell().status("Ignored", &msg)?;
166 return Ok(None);
167 }
168 select_dep_pkg(
169 &mut source,
170 dep,
171 gctx,
172 needs_update_if_source_is_index,
173 current_rust_version,
174 )?
175 } else {
176 bail!(
177 "must specify a crate to install from \
178 crates.io, or use --path or --git to \
179 specify alternate source"
180 )
181 }
182 };
183
184 let (ws, rustc, target) = make_ws_rustc_target(
185 gctx,
186 &original_opts,
187 &source_id,
188 pkg.clone(),
189 lockfile_path.clone(),
190 )?;
191
192 if !gctx.lock_update_allowed() {
193 if let Some(requested_lockfile_path) = ws.requested_lockfile_path() {
196 if !requested_lockfile_path.is_file() {
197 bail!(
198 "no Cargo.lock file found in the requested path {}",
199 requested_lockfile_path.display()
200 );
201 }
202 } else if !ws.root().join("Cargo.lock").exists() {
205 gctx.shell()
206 .warn(format!("no Cargo.lock file published in {}", pkg))?;
207 }
208 }
209 let pkg = if source_id.is_git() {
210 pkg
213 } else {
214 ws.current()?.clone()
215 };
216
217 let mut opts = original_opts.clone();
222 let pkgidspec = ws.current()?.package_id().to_spec();
226 opts.spec = Packages::Packages(vec![pkgidspec.to_string()]);
227
228 if from_cwd {
229 if pkg.manifest().edition() == Edition::Edition2015 {
230 gctx.shell().warn(
231 "Using `cargo install` to install the binaries from the \
232 package in current working directory is deprecated, \
233 use `cargo install --path .` instead. \
234 Use `cargo build` if you want to simply build the package.",
235 )?
236 } else {
237 bail!(
238 "Using `cargo install` to install the binaries from the \
239 package in current working directory is no longer supported, \
240 use `cargo install --path .` instead. \
241 Use `cargo build` if you want to simply build the package."
242 )
243 }
244 };
245
246 if !opts.filter.is_specific() && !pkg.targets().iter().any(|t| t.is_bin()) {
250 bail!(
251 "there is nothing to install in `{}`, because it has no binaries\n\
252 `cargo install` is only for installing programs, and can't be used with libraries.\n\
253 To use a library crate, add it as a dependency to a Cargo project with `cargo add`.",
254 pkg,
255 );
256 }
257
258 let ip = InstallablePackage {
259 gctx,
260 opts,
261 root,
262 source_id,
263 vers: vers.cloned(),
264 force,
265 no_track,
266 pkg,
267 ws,
268 rustc,
269 target,
270 };
271
272 if no_track {
275 ip.no_track_duplicates(&dst)?;
277 } else if is_installed(
278 &ip.pkg, gctx, &ip.opts, &ip.rustc, &ip.target, &ip.root, &dst, force,
279 )? {
280 let msg = format!(
281 "package `{}` is already installed, use --force to override",
282 ip.pkg
283 );
284 gctx.shell().status("Ignored", &msg)?;
285 return Ok(None);
286 }
287
288 Ok(Some(ip))
289 }
290
291 fn no_track_duplicates(&self, dst: &Path) -> CargoResult<BTreeMap<String, Option<PackageId>>> {
292 let duplicates: BTreeMap<String, Option<PackageId>> =
294 exe_names(&self.pkg, &self.opts.filter)
295 .into_iter()
296 .filter(|name| dst.join(name).exists())
297 .map(|name| (name, None))
298 .collect();
299 if !self.force && !duplicates.is_empty() {
300 let mut msg: Vec<String> = duplicates
301 .iter()
302 .map(|(name, _)| {
303 format!(
304 "binary `{}` already exists in destination `{}`",
305 name,
306 dst.join(name).to_string_lossy()
307 )
308 })
309 .collect();
310 msg.push("Add --force to overwrite".to_string());
311 bail!("{}", msg.join("\n"));
312 }
313 Ok(duplicates)
314 }
315
316 fn install_one(mut self, dry_run: bool) -> CargoResult<bool> {
317 self.gctx.shell().status("Installing", &self.pkg)?;
318
319 let dst = self.root.join("bin").into_path_unlocked();
320
321 let mut td_opt = None;
322 let mut needs_cleanup = false;
323 if !self.source_id.is_path() {
324 let target_dir = if let Some(dir) = self.gctx.target_dir()? {
325 dir
326 } else if let Ok(td) = TempFileBuilder::new().prefix("cargo-install").tempdir() {
327 let p = td.path().to_owned();
328 td_opt = Some(td);
329 Filesystem::new(p)
330 } else {
331 needs_cleanup = true;
332 Filesystem::new(self.gctx.cwd().join("target-install"))
333 };
334 self.ws.set_target_dir(target_dir);
335 }
336
337 self.check_yanked_install()?;
338
339 let exec: Arc<dyn Executor> = Arc::new(DefaultExecutor);
340 self.opts.build_config.dry_run = dry_run;
341 let compile = ops::compile_ws(&self.ws, &self.opts, &exec).with_context(|| {
342 if let Some(td) = td_opt.take() {
343 drop(td.keep());
345 }
346
347 format!(
348 "failed to compile `{}`, intermediate artifacts can be \
349 found at `{}`.\nTo reuse those artifacts with a future \
350 compilation, set the environment variable \
351 `CARGO_TARGET_DIR` to that path.",
352 self.pkg,
353 self.ws.target_dir().display()
354 )
355 })?;
356 let mut binaries: Vec<(&str, &Path)> = compile
357 .binaries
358 .iter()
359 .map(|UnitOutput { path, .. }| {
360 let name = path.file_name().unwrap();
361 if let Some(s) = name.to_str() {
362 Ok((s, path.as_ref()))
363 } else {
364 bail!("Binary `{:?}` name can't be serialized into string", name)
365 }
366 })
367 .collect::<CargoResult<_>>()?;
368 if binaries.is_empty() {
369 if let CompileFilter::Only { bins, examples, .. } = &self.opts.filter {
378 let mut any_specific = false;
379 if let FilterRule::Just(ref v) = bins {
380 if !v.is_empty() {
381 any_specific = true;
382 }
383 }
384 if let FilterRule::Just(ref v) = examples {
385 if !v.is_empty() {
386 any_specific = true;
387 }
388 }
389 if any_specific {
390 bail!("no binaries are available for install using the selected features");
391 }
392 }
393
394 let binaries: Vec<_> = self
400 .pkg
401 .targets()
402 .iter()
403 .filter(|t| t.is_executable())
404 .collect();
405 if !binaries.is_empty() {
406 self.gctx
407 .shell()
408 .warn(make_warning_about_missing_features(&binaries))?;
409 }
410
411 return Ok(false);
412 }
413 binaries.sort_unstable();
415
416 let (tracker, duplicates) = if self.no_track {
417 (None, self.no_track_duplicates(&dst)?)
418 } else {
419 let tracker = InstallTracker::load(self.gctx, &self.root)?;
420 let (_freshness, duplicates) = tracker.check_upgrade(
421 &dst,
422 &self.pkg,
423 self.force,
424 &self.opts,
425 &self.target,
426 &self.rustc.verbose_version,
427 )?;
428 (Some(tracker), duplicates)
429 };
430
431 paths::create_dir_all(&dst)?;
432
433 let staging_dir = TempFileBuilder::new()
437 .prefix("cargo-install")
438 .tempdir_in(&dst)?;
439 if !dry_run {
440 for &(bin, src) in binaries.iter() {
441 let dst = staging_dir.path().join(bin);
442 if !self.source_id.is_path() && fs::rename(src, &dst).is_ok() {
444 continue;
445 }
446 paths::copy(src, &dst)?;
447 }
448 }
449
450 let (to_replace, to_install): (Vec<&str>, Vec<&str>) = binaries
451 .iter()
452 .map(|&(bin, _)| bin)
453 .partition(|&bin| duplicates.contains_key(bin));
454
455 let mut installed = Transaction { bins: Vec::new() };
456 let mut successful_bins = BTreeSet::new();
457
458 for bin in to_install.iter() {
460 let src = staging_dir.path().join(bin);
461 let dst = dst.join(bin);
462 self.gctx.shell().status("Installing", dst.display())?;
463 if !dry_run {
464 fs::rename(&src, &dst).with_context(|| {
465 format!("failed to move `{}` to `{}`", src.display(), dst.display())
466 })?;
467 installed.bins.push(dst);
468 successful_bins.insert(bin.to_string());
469 }
470 }
471
472 let replace_result = {
475 let mut try_install = || -> CargoResult<()> {
476 for &bin in to_replace.iter() {
477 let src = staging_dir.path().join(bin);
478 let dst = dst.join(bin);
479 self.gctx.shell().status("Replacing", dst.display())?;
480 if !dry_run {
481 fs::rename(&src, &dst).with_context(|| {
482 format!("failed to move `{}` to `{}`", src.display(), dst.display())
483 })?;
484 successful_bins.insert(bin.to_string());
485 }
486 }
487 Ok(())
488 };
489 try_install()
490 };
491
492 if let Some(mut tracker) = tracker {
493 tracker.mark_installed(
494 &self.pkg,
495 &successful_bins,
496 self.vers.map(|s| s.to_string()),
497 &self.opts,
498 &self.target,
499 &self.rustc.verbose_version,
500 );
501
502 if let Err(e) = remove_orphaned_bins(
503 &self.ws,
504 &mut tracker,
505 &duplicates,
506 &self.pkg,
507 &dst,
508 dry_run,
509 ) {
510 self.gctx
512 .shell()
513 .warn(format!("failed to remove orphan: {:?}", e))?;
514 }
515
516 match tracker.save() {
517 Err(err) => replace_result.with_context(|| err)?,
518 Ok(_) => replace_result?,
519 }
520 }
521
522 installed.success();
524 if needs_cleanup {
525 let target_dir = self.ws.target_dir().into_path_unlocked();
528 paths::remove_dir_all(&target_dir)?;
529 }
530
531 fn executables<T: AsRef<str>>(mut names: impl Iterator<Item = T> + Clone) -> String {
533 if names.clone().count() == 1 {
534 format!("(executable `{}`)", names.next().unwrap().as_ref())
535 } else {
536 format!(
537 "(executables {})",
538 names
539 .map(|b| format!("`{}`", b.as_ref()))
540 .collect::<Vec<_>>()
541 .join(", ")
542 )
543 }
544 }
545
546 if dry_run {
547 self.gctx.shell().warn("aborting install due to dry run")?;
548 Ok(true)
549 } else if duplicates.is_empty() {
550 self.gctx.shell().status(
551 "Installed",
552 format!(
553 "package `{}` {}",
554 self.pkg,
555 executables(successful_bins.iter())
556 ),
557 )?;
558 Ok(true)
559 } else {
560 if !to_install.is_empty() {
561 self.gctx.shell().status(
562 "Installed",
563 format!("package `{}` {}", self.pkg, executables(to_install.iter())),
564 )?;
565 }
566 let mut pkg_map = BTreeMap::new();
568 for (bin_name, opt_pkg_id) in &duplicates {
569 let key =
570 opt_pkg_id.map_or_else(|| "unknown".to_string(), |pkg_id| pkg_id.to_string());
571 pkg_map.entry(key).or_insert_with(Vec::new).push(bin_name);
572 }
573 for (pkg_descr, bin_names) in &pkg_map {
574 self.gctx.shell().status(
575 "Replaced",
576 format!(
577 "package `{}` with `{}` {}",
578 pkg_descr,
579 self.pkg,
580 executables(bin_names.iter())
581 ),
582 )?;
583 }
584 Ok(true)
585 }
586 }
587
588 fn check_yanked_install(&self) -> CargoResult<()> {
589 if self.ws.ignore_lock() || !self.ws.root().join("Cargo.lock").exists() {
590 return Ok(());
591 }
592 let dry_run = false;
596 let (pkg_set, resolve) = ops::resolve_ws(&self.ws, dry_run)?;
597 ops::check_yanked(
598 self.ws.gctx(),
599 &pkg_set,
600 &resolve,
601 "consider running without --locked",
602 )
603 }
604}
605
606fn make_warning_about_missing_features(binaries: &[&Target]) -> String {
607 let max_targets_listed = 7;
608 let target_features_message = binaries
609 .iter()
610 .take(max_targets_listed)
611 .map(|b| {
612 let name = b.description_named();
613 let features = b
614 .required_features()
615 .unwrap_or(&Vec::new())
616 .iter()
617 .map(|f| format!("`{f}`"))
618 .join(", ");
619 format!(" {name} requires the features: {features}")
620 })
621 .join("\n");
622
623 let additional_bins_message = if binaries.len() > max_targets_listed {
624 format!(
625 "\n{} more targets also requires features not enabled. See them in the Cargo.toml file.",
626 binaries.len() - max_targets_listed
627 )
628 } else {
629 "".into()
630 };
631
632 let example_features = binaries[0]
633 .required_features()
634 .map(|f| f.join(" "))
635 .unwrap_or_default();
636
637 format!(
638 "\
639none of the package's binaries are available for install using the selected features
640{target_features_message}{additional_bins_message}
641Consider enabling some of the needed features by passing, e.g., `--features=\"{example_features}\"`"
642 )
643}
644
645pub fn install(
646 gctx: &GlobalContext,
647 root: Option<&str>,
648 krates: Vec<(String, Option<VersionReq>)>,
649 source_id: SourceId,
650 from_cwd: bool,
651 opts: &ops::CompileOptions,
652 force: bool,
653 no_track: bool,
654 dry_run: bool,
655 lockfile_path: Option<&Path>,
656) -> CargoResult<()> {
657 let root = resolve_root(root, gctx)?;
658 let dst = root.join("bin").into_path_unlocked();
659 let map = SourceConfigMap::new(gctx)?;
660
661 let current_rust_version = if opts.honor_rust_version.unwrap_or(true) {
662 let rustc = gctx.load_global_rustc(None)?;
663 Some(rustc.version.clone().into())
664 } else {
665 None
666 };
667
668 let (installed_anything, scheduled_error) = if krates.len() <= 1 {
669 let (krate, vers) = krates
670 .iter()
671 .next()
672 .map(|(k, v)| (Some(k.as_str()), v.as_ref()))
673 .unwrap_or((None, None));
674 let installable_pkg = InstallablePackage::new(
675 gctx,
676 root,
677 map,
678 krate,
679 source_id,
680 from_cwd,
681 vers,
682 opts,
683 force,
684 no_track,
685 true,
686 current_rust_version.as_ref(),
687 lockfile_path,
688 )?;
689 let mut installed_anything = true;
690 if let Some(installable_pkg) = installable_pkg {
691 installed_anything = installable_pkg.install_one(dry_run)?;
692 }
693 (installed_anything, false)
694 } else {
695 let mut succeeded = vec![];
696 let mut failed = vec![];
697 let mut did_update = false;
700
701 let pkgs_to_install: Vec<_> = krates
702 .iter()
703 .filter_map(|(krate, vers)| {
704 let root = root.clone();
705 let map = map.clone();
706 match InstallablePackage::new(
707 gctx,
708 root,
709 map,
710 Some(krate.as_str()),
711 source_id,
712 from_cwd,
713 vers.as_ref(),
714 opts,
715 force,
716 no_track,
717 !did_update,
718 current_rust_version.as_ref(),
719 lockfile_path,
720 ) {
721 Ok(Some(installable_pkg)) => {
722 did_update = true;
723 Some((krate, installable_pkg))
724 }
725 Ok(None) => {
726 succeeded.push(krate.as_str());
728 None
729 }
730 Err(e) => {
731 crate::display_error(&e, &mut gctx.shell());
732 failed.push(krate.as_str());
733 did_update = true;
735 None
736 }
737 }
738 })
739 .collect();
740
741 let install_results: Vec<_> = pkgs_to_install
742 .into_iter()
743 .map(|(krate, installable_pkg)| (krate, installable_pkg.install_one(dry_run)))
744 .collect();
745
746 for (krate, result) in install_results {
747 match result {
748 Ok(installed) => {
749 if installed {
750 succeeded.push(krate);
751 }
752 }
753 Err(e) => {
754 crate::display_error(&e, &mut gctx.shell());
755 failed.push(krate);
756 }
757 }
758 }
759
760 let mut summary = vec![];
761 if !succeeded.is_empty() {
762 summary.push(format!("Successfully installed {}!", succeeded.join(", ")));
763 }
764 if !failed.is_empty() {
765 summary.push(format!(
766 "Failed to install {} (see error(s) above).",
767 failed.join(", ")
768 ));
769 }
770 if !succeeded.is_empty() || !failed.is_empty() {
771 gctx.shell().status("Summary", summary.join(" "))?;
772 }
773
774 (!succeeded.is_empty(), !failed.is_empty())
775 };
776
777 if installed_anything {
778 let path = gctx.get_env_os("PATH").unwrap_or_default();
781 let dst_in_path = env::split_paths(&path).any(|path| path == dst);
782
783 if !dst_in_path {
784 gctx.shell().warn(&format!(
785 "be sure to add `{}` to your PATH to be \
786 able to run the installed binaries",
787 dst.display()
788 ))?;
789 }
790 }
791
792 if scheduled_error {
793 bail!("some crates failed to install");
794 }
795
796 Ok(())
797}
798
799fn is_installed(
800 pkg: &Package,
801 gctx: &GlobalContext,
802 opts: &ops::CompileOptions,
803 rustc: &Rustc,
804 target: &str,
805 root: &Filesystem,
806 dst: &Path,
807 force: bool,
808) -> CargoResult<bool> {
809 let tracker = InstallTracker::load(gctx, root)?;
810 let (freshness, _duplicates) =
811 tracker.check_upgrade(dst, pkg, force, opts, target, &rustc.verbose_version)?;
812 Ok(freshness.is_fresh())
813}
814
815fn installed_exact_package<T>(
819 dep: Dependency,
820 source: &mut T,
821 gctx: &GlobalContext,
822 opts: &ops::CompileOptions,
823 root: &Filesystem,
824 dst: &Path,
825 force: bool,
826 lockfile_path: Option<&Path>,
827) -> CargoResult<Option<Package>>
828where
829 T: Source,
830{
831 if !dep.version_req().is_exact() {
832 return Ok(None);
835 }
836 if let Ok(pkg) = select_dep_pkg(source, dep, gctx, false, None) {
841 let (_ws, rustc, target) =
842 make_ws_rustc_target(gctx, opts, &source.source_id(), pkg.clone(), lockfile_path)?;
843 if let Ok(true) = is_installed(&pkg, gctx, opts, &rustc, &target, root, dst, force) {
844 return Ok(Some(pkg));
845 }
846 }
847 Ok(None)
848}
849
850fn make_ws_rustc_target<'gctx>(
851 gctx: &'gctx GlobalContext,
852 opts: &ops::CompileOptions,
853 source_id: &SourceId,
854 pkg: Package,
855 lockfile_path: Option<&Path>,
856) -> CargoResult<(Workspace<'gctx>, Rustc, String)> {
857 let mut ws = if source_id.is_git() || source_id.is_path() {
858 Workspace::new(pkg.manifest_path(), gctx)?
859 } else {
860 let mut ws = Workspace::ephemeral(pkg, gctx, None, false)?;
861 ws.set_resolve_honors_rust_version(Some(false));
862 ws
863 };
864 ws.set_resolve_feature_unification(FeatureUnification::Selected);
865 ws.set_ignore_lock(gctx.lock_update_allowed());
866 ws.set_requested_lockfile_path(lockfile_path.map(|p| p.to_path_buf()));
867 if ws.requested_lockfile_path().is_some() {
869 ws.set_ignore_lock(false);
870 }
871 ws.set_require_optional_deps(false);
872
873 let rustc = gctx.load_global_rustc(Some(&ws))?;
874 let target = match &opts.build_config.single_requested_kind()? {
875 CompileKind::Host => rustc.host.as_str().to_owned(),
876 CompileKind::Target(target) => target.short_name().to_owned(),
877 };
878
879 Ok((ws, rustc, target))
880}
881
882pub fn install_list(dst: Option<&str>, gctx: &GlobalContext) -> CargoResult<()> {
884 let root = resolve_root(dst, gctx)?;
885 let tracker = InstallTracker::load(gctx, &root)?;
886 for (k, v) in tracker.all_installed_bins() {
887 drop_println!(gctx, "{}:", k);
888 for bin in v {
889 drop_println!(gctx, " {}", bin);
890 }
891 }
892 Ok(())
893}
894
895fn remove_orphaned_bins(
898 ws: &Workspace<'_>,
899 tracker: &mut InstallTracker,
900 duplicates: &BTreeMap<String, Option<PackageId>>,
901 pkg: &Package,
902 dst: &Path,
903 dry_run: bool,
904) -> CargoResult<()> {
905 let filter = ops::CompileFilter::new_all_targets();
906 let all_self_names = exe_names(pkg, &filter);
907 let mut to_remove: HashMap<PackageId, BTreeSet<String>> = HashMap::new();
908 for other_pkg in duplicates.values().flatten() {
910 if other_pkg.name() == pkg.name() {
912 if let Some(installed) = tracker.installed_bins(*other_pkg) {
914 for installed_name in installed {
917 if !all_self_names.contains(installed_name.as_str()) {
918 to_remove
919 .entry(*other_pkg)
920 .or_default()
921 .insert(installed_name.clone());
922 }
923 }
924 }
925 }
926 }
927
928 for (old_pkg, bins) in to_remove {
929 tracker.remove(old_pkg, &bins);
930 for bin in bins {
931 let full_path = dst.join(bin);
932 if full_path.exists() {
933 ws.gctx().shell().status(
934 "Removing",
935 format!(
936 "executable `{}` from previous version {}",
937 full_path.display(),
938 old_pkg
939 ),
940 )?;
941 if !dry_run {
942 paths::remove_file(&full_path)
943 .with_context(|| format!("failed to remove {:?}", full_path))?;
944 }
945 }
946 }
947 }
948 Ok(())
949}