1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::{env, fs};
use anyhow::{bail, format_err};
use semver::VersionReq;
use tempfile::Builder as TempFileBuilder;
use crate::core::compiler::{CompileKind, DefaultExecutor, Executor, Freshness, UnitOutput};
use crate::core::{Dependency, Edition, Package, PackageId, Source, SourceId, Workspace};
use crate::ops::common_for_install_and_uninstall::*;
use crate::sources::{GitSource, PathSource, SourceConfigMap};
use crate::util::errors::{CargoResult, CargoResultExt};
use crate::util::{paths, Config, Filesystem, Rustc, ToSemver};
use crate::{drop_println, ops};
struct Transaction {
bins: Vec<PathBuf>,
}
impl Transaction {
fn success(mut self) {
self.bins.clear();
}
}
impl Drop for Transaction {
fn drop(&mut self) {
for bin in self.bins.iter() {
let _ = paths::remove_file(bin);
}
}
}
pub fn install(
config: &Config,
root: Option<&str>,
krates: Vec<&str>,
source_id: SourceId,
from_cwd: bool,
vers: Option<&str>,
opts: &ops::CompileOptions,
force: bool,
no_track: bool,
) -> CargoResult<()> {
let root = resolve_root(root, config)?;
let map = SourceConfigMap::new(config)?;
let (installed_anything, scheduled_error) = if krates.len() <= 1 {
install_one(
config,
&root,
&map,
krates.into_iter().next(),
source_id,
from_cwd,
vers,
opts,
force,
no_track,
true,
)?;
(true, false)
} else {
let mut succeeded = vec![];
let mut failed = vec![];
let mut did_update = false;
for krate in krates {
let root = root.clone();
let map = map.clone();
match install_one(
config,
&root,
&map,
Some(krate),
source_id,
from_cwd,
vers,
opts,
force,
no_track,
!did_update,
) {
Ok(still_needs_update) => {
succeeded.push(krate);
did_update |= !still_needs_update;
}
Err(e) => {
crate::display_error(&e, &mut config.shell());
failed.push(krate);
did_update = true;
}
}
}
let mut summary = vec![];
if !succeeded.is_empty() {
summary.push(format!("Successfully installed {}!", succeeded.join(", ")));
}
if !failed.is_empty() {
summary.push(format!(
"Failed to install {} (see error(s) above).",
failed.join(", ")
));
}
if !succeeded.is_empty() || !failed.is_empty() {
config.shell().status("Summary", summary.join(" "))?;
}
(!succeeded.is_empty(), !failed.is_empty())
};
if installed_anything {
let dst = root.join("bin").into_path_unlocked();
let path = env::var_os("PATH").unwrap_or_default();
let dst_in_path = env::split_paths(&path).any(|path| path == dst);
if !dst_in_path {
config.shell().warn(&format!(
"be sure to add `{}` to your PATH to be \
able to run the installed binaries",
dst.display()
))?;
}
}
if scheduled_error {
bail!("some crates failed to install");
}
Ok(())
}
fn install_one(
config: &Config,
root: &Filesystem,
map: &SourceConfigMap<'_>,
krate: Option<&str>,
source_id: SourceId,
from_cwd: bool,
vers: Option<&str>,
opts: &ops::CompileOptions,
force: bool,
no_track: bool,
needs_update_if_source_is_index: bool,
) -> CargoResult<bool> {
if let Some(name) = krate {
if name == "." {
bail!(
"To install the binaries for the package in current working \
directory use `cargo install --path .`. \
Use `cargo build` if you want to simply build the package."
)
}
}
let dst = root.join("bin").into_path_unlocked();
let pkg = {
let dep = {
if let Some(krate) = krate {
let vers = if let Some(vers_flag) = vers {
Some(parse_semver_flag(vers_flag)?.to_string())
} else if source_id.is_registry() {
Some(String::from("*"))
} else {
None
};
Some(Dependency::parse_no_deprecated(
krate,
vers.as_deref(),
source_id,
)?)
} else {
None
}
};
if source_id.is_git() {
let mut source = GitSource::new(source_id, config)?;
select_pkg(
&mut source,
dep,
|git: &mut GitSource<'_>| git.read_packages(),
config,
)?
} else if source_id.is_path() {
let mut src = path_source(source_id, config)?;
if !src.path().is_dir() {
bail!(
"`{}` is not a directory. \
--path must point to a directory containing a Cargo.toml file.",
src.path().display()
)
}
if !src.path().join("Cargo.toml").exists() {
if from_cwd {
bail!(
"`{}` is not a crate root; specify a crate to \
install from crates.io, or use --path or --git to \
specify an alternate source",
src.path().display()
);
} else {
bail!(
"`{}` does not contain a Cargo.toml file. \
--path must point to a directory containing a Cargo.toml file.",
src.path().display()
)
}
}
select_pkg(
&mut src,
dep,
|path: &mut PathSource<'_>| path.read_packages(),
config,
)?
} else if let Some(dep) = dep {
let mut source = map.load(source_id, &HashSet::new())?;
if let Ok(Some(pkg)) =
installed_exact_package(dep.clone(), &mut source, config, opts, root, &dst, force)
{
let msg = format!(
"package `{}` is already installed, use --force to override",
pkg
);
config.shell().status("Ignored", &msg)?;
return Ok(true);
}
select_dep_pkg(&mut source, dep, config, needs_update_if_source_is_index)?
} else {
bail!(
"must specify a crate to install from \
crates.io, or use --path or --git to \
specify alternate source"
)
}
};
let (mut ws, rustc, target) = make_ws_rustc_target(config, opts, &source_id, pkg.clone())?;
if config.locked() && !ws.root().join("Cargo.lock").exists() {
config.shell().warn(format!(
"no Cargo.lock file published in {}",
pkg.to_string()
))?;
}
let pkg = if source_id.is_git() {
pkg
} else {
ws.current()?.clone()
};
let mut td_opt = None;
let mut needs_cleanup = false;
if !source_id.is_path() {
let target_dir = if let Some(dir) = config.target_dir()? {
dir
} else if let Ok(td) = TempFileBuilder::new().prefix("cargo-install").tempdir() {
let p = td.path().to_owned();
td_opt = Some(td);
Filesystem::new(p)
} else {
needs_cleanup = true;
Filesystem::new(config.cwd().join("target-install"))
};
ws.set_target_dir(target_dir);
}
if from_cwd {
if pkg.manifest().edition() == Edition::Edition2015 {
config.shell().warn(
"Using `cargo install` to install the binaries for the \
package in current working directory is deprecated, \
use `cargo install --path .` instead. \
Use `cargo build` if you want to simply build the package.",
)?
} else {
bail!(
"Using `cargo install` to install the binaries for the \
package in current working directory is no longer supported, \
use `cargo install --path .` instead. \
Use `cargo build` if you want to simply build the package."
)
}
};
if !opts.filter.is_specific() && !pkg.targets().iter().any(|t| t.is_bin()) {
bail!(
"there is nothing to install in `{}`, because it has no binaries\n\
`cargo install` is only for installing programs, and can't be used with libraries.\n\
To use a library crate, add it as a dependency in a Cargo project instead.",
pkg
);
}
let no_track_duplicates = || -> CargoResult<BTreeMap<String, Option<PackageId>>> {
let duplicates: BTreeMap<String, Option<PackageId>> = exe_names(&pkg, &opts.filter)
.into_iter()
.filter(|name| dst.join(name).exists())
.map(|name| (name, None))
.collect();
if !force && !duplicates.is_empty() {
let mut msg: Vec<String> = duplicates
.iter()
.map(|(name, _)| format!("binary `{}` already exists in destination", name))
.collect();
msg.push("Add --force to overwrite".to_string());
bail!("{}", msg.join("\n"));
}
Ok(duplicates)
};
if no_track {
no_track_duplicates()?;
} else if is_installed(&pkg, config, opts, &rustc, &target, root, &dst, force)? {
let msg = format!(
"package `{}` is already installed, use --force to override",
pkg
);
config.shell().status("Ignored", &msg)?;
return Ok(false);
}
config.shell().status("Installing", &pkg)?;
check_yanked_install(&ws)?;
let exec: Arc<dyn Executor> = Arc::new(DefaultExecutor);
let compile = ops::compile_ws(&ws, opts, &exec).chain_err(|| {
if let Some(td) = td_opt.take() {
td.into_path();
}
format_err!(
"failed to compile `{}`, intermediate artifacts can be \
found at `{}`",
pkg,
ws.target_dir().display()
)
})?;
let mut binaries: Vec<(&str, &Path)> = compile
.binaries
.iter()
.map(|UnitOutput { path, .. }| {
let name = path.file_name().unwrap();
if let Some(s) = name.to_str() {
Ok((s, path.as_ref()))
} else {
bail!("Binary `{:?}` name can't be serialized into string", name)
}
})
.collect::<CargoResult<_>>()?;
if binaries.is_empty() {
bail!("no binaries are available for install using the selected features");
}
binaries.sort_unstable();
let (tracker, duplicates) = if no_track {
(None, no_track_duplicates()?)
} else {
let tracker = InstallTracker::load(config, root)?;
let (_freshness, duplicates) =
tracker.check_upgrade(&dst, &pkg, force, opts, &target, &rustc.verbose_version)?;
(Some(tracker), duplicates)
};
paths::create_dir_all(&dst)?;
let staging_dir = TempFileBuilder::new()
.prefix("cargo-install")
.tempdir_in(&dst)?;
for &(bin, src) in binaries.iter() {
let dst = staging_dir.path().join(bin);
if !source_id.is_path() && fs::rename(src, &dst).is_ok() {
continue;
}
paths::copy(src, &dst)?;
}
let (to_replace, to_install): (Vec<&str>, Vec<&str>) = binaries
.iter()
.map(|&(bin, _)| bin)
.partition(|&bin| duplicates.contains_key(bin));
let mut installed = Transaction { bins: Vec::new() };
let mut successful_bins = BTreeSet::new();
for bin in to_install.iter() {
let src = staging_dir.path().join(bin);
let dst = dst.join(bin);
config.shell().status("Installing", dst.display())?;
fs::rename(&src, &dst).chain_err(|| {
format_err!("failed to move `{}` to `{}`", src.display(), dst.display())
})?;
installed.bins.push(dst);
successful_bins.insert(bin.to_string());
}
let replace_result = {
let mut try_install = || -> CargoResult<()> {
for &bin in to_replace.iter() {
let src = staging_dir.path().join(bin);
let dst = dst.join(bin);
config.shell().status("Replacing", dst.display())?;
fs::rename(&src, &dst).chain_err(|| {
format_err!("failed to move `{}` to `{}`", src.display(), dst.display())
})?;
successful_bins.insert(bin.to_string());
}
Ok(())
};
try_install()
};
if let Some(mut tracker) = tracker {
tracker.mark_installed(
&pkg,
&successful_bins,
vers.map(|s| s.to_string()),
opts,
&target,
&rustc.verbose_version,
);
if let Err(e) = remove_orphaned_bins(&ws, &mut tracker, &duplicates, &pkg, &dst) {
config
.shell()
.warn(format!("failed to remove orphan: {:?}", e))?;
}
match tracker.save() {
Err(err) => replace_result.chain_err(|| err)?,
Ok(_) => replace_result?,
}
}
installed.success();
if needs_cleanup {
let target_dir = ws.target_dir().into_path_unlocked();
paths::remove_dir_all(&target_dir)?;
}
fn executables<T: AsRef<str>>(mut names: impl Iterator<Item = T> + Clone) -> String {
if names.clone().count() == 1 {
format!("(executable `{}`)", names.next().unwrap().as_ref())
} else {
format!(
"(executables {})",
names
.map(|b| format!("`{}`", b.as_ref()))
.collect::<Vec<_>>()
.join(", ")
)
}
}
if duplicates.is_empty() {
config.shell().status(
"Installed",
format!("package `{}` {}", pkg, executables(successful_bins.iter())),
)?;
Ok(false)
} else {
if !to_install.is_empty() {
config.shell().status(
"Installed",
format!("package `{}` {}", pkg, executables(to_install.iter())),
)?;
}
let mut pkg_map = BTreeMap::new();
for (bin_name, opt_pkg_id) in &duplicates {
let key = opt_pkg_id.map_or_else(|| "unknown".to_string(), |pkg_id| pkg_id.to_string());
pkg_map.entry(key).or_insert_with(Vec::new).push(bin_name);
}
for (pkg_descr, bin_names) in &pkg_map {
config.shell().status(
"Replaced",
format!(
"package `{}` with `{}` {}",
pkg_descr,
pkg,
executables(bin_names.iter())
),
)?;
}
Ok(false)
}
}
fn is_installed(
pkg: &Package,
config: &Config,
opts: &ops::CompileOptions,
rustc: &Rustc,
target: &str,
root: &Filesystem,
dst: &Path,
force: bool,
) -> CargoResult<bool> {
let tracker = InstallTracker::load(config, root)?;
let (freshness, _duplicates) =
tracker.check_upgrade(dst, pkg, force, opts, target, &rustc.verbose_version)?;
Ok(freshness == Freshness::Fresh)
}
fn installed_exact_package<T>(
dep: Dependency,
source: &mut T,
config: &Config,
opts: &ops::CompileOptions,
root: &Filesystem,
dst: &Path,
force: bool,
) -> CargoResult<Option<Package>>
where
T: Source,
{
if !dep.is_locked() {
return Ok(None);
}
if let Ok(pkg) = select_dep_pkg(source, dep, config, false) {
let (_ws, rustc, target) =
make_ws_rustc_target(config, opts, &source.source_id(), pkg.clone())?;
if let Ok(true) = is_installed(&pkg, config, opts, &rustc, &target, root, dst, force) {
return Ok(Some(pkg));
}
}
Ok(None)
}
fn make_ws_rustc_target<'cfg>(
config: &'cfg Config,
opts: &ops::CompileOptions,
source_id: &SourceId,
pkg: Package,
) -> CargoResult<(Workspace<'cfg>, Rustc, String)> {
let mut ws = if source_id.is_git() || source_id.is_path() {
Workspace::new(pkg.manifest_path(), config)?
} else {
Workspace::ephemeral(pkg, config, None, false)?
};
ws.set_ignore_lock(config.lock_update_allowed());
ws.set_require_optional_deps(false);
let rustc = config.load_global_rustc(Some(&ws))?;
let target = match &opts.build_config.single_requested_kind()? {
CompileKind::Host => rustc.host.as_str().to_owned(),
CompileKind::Target(target) => target.short_name().to_owned(),
};
Ok((ws, rustc, target))
}
fn parse_semver_flag(v: &str) -> CargoResult<VersionReq> {
let first = v
.chars()
.next()
.ok_or_else(|| format_err!("no version provided for the `--vers` flag"))?;
let is_req = "<>=^~".contains(first) || v.contains('*');
if is_req {
match v.parse::<VersionReq>() {
Ok(v) => Ok(v),
Err(_) => bail!(
"the `--vers` provided, `{}`, is \
not a valid semver version requirement\n\n\
Please have a look at \
https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html \
for the correct format",
v
),
}
} else {
match v.to_semver() {
Ok(v) => Ok(VersionReq::exact(&v)),
Err(e) => {
let mut msg = format!(
"the `--vers` provided, `{}`, is \
not a valid semver version: {}\n",
v, e
);
if v.parse::<VersionReq>().is_ok() {
msg.push_str(&format!(
"\nif you want to specify semver range, \
add an explicit qualifier, like ^{}",
v
));
}
bail!(msg);
}
}
}
}
fn check_yanked_install(ws: &Workspace<'_>) -> CargoResult<()> {
if ws.ignore_lock() || !ws.root().join("Cargo.lock").exists() {
return Ok(());
}
let (pkg_set, resolve) = ops::resolve_ws(ws)?;
let mut sources = pkg_set.sources_mut();
let _lock = ws.config().acquire_package_cache_lock()?;
for pkg_id in resolve.iter() {
if let Some(source) = sources.get_mut(pkg_id.source_id()) {
if source.is_yanked(pkg_id)? {
ws.config().shell().warn(format!(
"package `{}` in Cargo.lock is yanked in registry `{}`, \
consider running without --locked",
pkg_id,
pkg_id.source_id().display_registry_name()
))?;
}
}
}
Ok(())
}
pub fn install_list(dst: Option<&str>, config: &Config) -> CargoResult<()> {
let root = resolve_root(dst, config)?;
let tracker = InstallTracker::load(config, &root)?;
for (k, v) in tracker.all_installed_bins() {
drop_println!(config, "{}:", k);
for bin in v {
drop_println!(config, " {}", bin);
}
}
Ok(())
}
fn remove_orphaned_bins(
ws: &Workspace<'_>,
tracker: &mut InstallTracker,
duplicates: &BTreeMap<String, Option<PackageId>>,
pkg: &Package,
dst: &Path,
) -> CargoResult<()> {
let filter = ops::CompileFilter::new_all_targets();
let all_self_names = exe_names(pkg, &filter);
let mut to_remove: HashMap<PackageId, BTreeSet<String>> = HashMap::new();
for other_pkg in duplicates.values() {
if let Some(other_pkg) = other_pkg {
if other_pkg.name() == pkg.name() {
if let Some(installed) = tracker.installed_bins(*other_pkg) {
for installed_name in installed {
if !all_self_names.contains(installed_name.as_str()) {
to_remove
.entry(*other_pkg)
.or_default()
.insert(installed_name.clone());
}
}
}
}
}
}
for (old_pkg, bins) in to_remove {
tracker.remove(old_pkg, &bins);
for bin in bins {
let full_path = dst.join(bin);
if full_path.exists() {
ws.config().shell().status(
"Removing",
format!(
"executable `{}` from previous version {}",
full_path.display(),
old_pkg
),
)?;
paths::remove_file(&full_path)
.chain_err(|| format!("failed to remove {:?}", full_path))?;
}
}
}
Ok(())
}