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
use std::env;
use std::path::Path;
use bstr::ByteSlice;
use crate::config;
use crate::error::CargoResult;
use crate::ops::cmd::call;
#[derive(Clone, Debug)]
pub enum Features {
None,
Selective(Vec<String>),
All,
}
fn cargo() -> String {
env::var("CARGO").unwrap_or_else(|_| "cargo".to_owned())
}
pub fn package_content(manifest_path: &Path) -> CargoResult<Vec<std::path::PathBuf>> {
let mut cmd = std::process::Command::new(cargo());
cmd.arg("package");
cmd.arg("--manifest-path");
cmd.arg(manifest_path);
cmd.arg("--list");
cmd.arg("--allow-dirty");
let output = cmd.output()?;
let parent = manifest_path
.parent()
.unwrap_or_else(|| std::path::Path::new(""));
if output.status.success() {
let paths = ByteSlice::lines(output.stdout.as_slice())
.map(|l| parent.join(l.to_path_lossy()))
.collect();
Ok(paths)
} else {
let error = String::from_utf8_lossy(&output.stderr);
Err(anyhow::format_err!(
"failed to get package content for {}: {}",
manifest_path.display(),
error
))
}
}
#[allow(clippy::too_many_arguments)]
pub fn publish(
dry_run: bool,
verify: bool,
manifest_path: &Path,
pkgid: Option<&str>,
features: &Features,
registry: Option<&str>,
target: Option<&str>,
) -> CargoResult<bool> {
let cargo = cargo();
let mut command: Vec<&str> = vec![
&cargo,
"publish",
"--manifest-path",
manifest_path.to_str().unwrap(),
];
if let Some(pkgid) = pkgid {
command.push("--package");
command.push(pkgid);
}
if let Some(registry) = registry {
command.push("--registry");
command.push(registry);
}
if dry_run {
command.push("--dry-run");
command.push("--allow-dirty");
}
if !verify {
command.push("--no-verify");
}
if let Some(target) = target {
command.push("--target");
command.push(target);
}
let feature_arg;
match features {
Features::None => (),
Features::Selective(vec) => {
feature_arg = vec.join(" ");
command.push("--features");
command.push(&feature_arg);
}
Features::All => {
command.push("--all-features");
}
};
call(command, false)
}
pub fn wait_for_publish(
index: &mut crates_index::Index,
name: &str,
version: &str,
timeout: std::time::Duration,
dry_run: bool,
) -> CargoResult<()> {
if !dry_run {
let now = std::time::Instant::now();
let sleep_time = std::time::Duration::from_secs(1);
let mut logged = false;
loop {
if let Err(e) = index.update() {
log::debug!("crate index update failed with {}", e);
}
if is_published(index, name, version) {
break;
} else if timeout < now.elapsed() {
anyhow::bail!("timeout waiting for crate to be published");
}
if !logged {
let _ = crate::ops::shell::status(
"Waiting",
format!("on {name} to propagate to index"),
);
logged = true;
}
std::thread::sleep(sleep_time);
}
}
Ok(())
}
pub fn is_published(index: &crates_index::Index, name: &str, version: &str) -> bool {
let crate_data = index.crate_(name);
crate_data
.iter()
.flat_map(|c| c.versions().iter())
.any(|v| v.version() == version)
}
pub fn set_workspace_version(
manifest_path: &Path,
version: &str,
dry_run: bool,
) -> CargoResult<()> {
let original_manifest = std::fs::read_to_string(manifest_path)?;
let mut manifest: toml_edit::Document = original_manifest.parse()?;
manifest["workspace"]["package"]["version"] = toml_edit::value(version);
let manifest = manifest.to_string();
if dry_run {
if manifest != original_manifest {
let display_path = manifest_path.display().to_string();
let old_lines: Vec<_> = original_manifest
.lines()
.map(|s| format!("{}\n", s))
.collect();
let new_lines: Vec<_> = manifest.lines().map(|s| format!("{}\n", s)).collect();
let diff = difflib::unified_diff(
&old_lines,
&new_lines,
display_path.as_str(),
display_path.as_str(),
"original",
"updated",
0,
);
log::debug!("change:\n{}", itertools::join(diff.into_iter(), ""));
}
} else {
atomic_write(manifest_path, &manifest)?;
}
Ok(())
}
pub fn ensure_owners(
name: &str,
logins: &[String],
registry: Option<&str>,
dry_run: bool,
) -> CargoResult<()> {
let cargo = cargo();
let mut cmd = std::process::Command::new(&cargo);
cmd.arg("owner").arg(name).arg("--color=never");
cmd.arg("--list");
if let Some(registry) = registry {
cmd.arg("--registry");
cmd.arg(registry);
}
let output = cmd.output()?;
if !output.status.success() {
anyhow::bail!(
"failed talking to registry about crate owners: {}",
String::from_utf8_lossy(&output.stderr)
);
}
let raw = String::from_utf8(output.stdout)
.map_err(|_| anyhow::format_err!("unrecognized response from registry"))?;
let mut current = std::collections::BTreeSet::new();
for line in raw.lines() {
if let Some((owner, _)) = line.split_once(' ') {
if !owner.is_empty() {
current.insert(owner);
}
}
}
let expected = logins
.iter()
.map(|s| s.as_str())
.collect::<std::collections::BTreeSet<_>>();
let missing = expected.difference(¤t).copied().collect::<Vec<_>>();
if !missing.is_empty() {
let _ = crate::ops::shell::status(
"Adding",
format!("owners for {}: {}", name, missing.join(", ")),
);
if !dry_run {
let mut cmd = std::process::Command::new(&cargo);
cmd.arg("owner").arg(name).arg("--color=never");
for missing in missing {
cmd.arg("--add").arg(missing);
}
if let Some(registry) = registry {
cmd.arg("--registry");
cmd.arg(registry);
}
let output = cmd.output()?;
if !output.status.success() {
let _ = crate::ops::shell::warn(format!(
"failed to set owners for {}: {}",
name,
String::from_utf8_lossy(&output.stderr)
));
}
}
}
let extra = current.difference(&expected).copied().collect::<Vec<_>>();
if !extra.is_empty() {
log::debug!("extra owners for {}: {}", name, extra.join(", "));
}
Ok(())
}
pub fn set_package_version(manifest_path: &Path, version: &str, dry_run: bool) -> CargoResult<()> {
let original_manifest = std::fs::read_to_string(manifest_path)?;
let mut manifest: toml_edit::Document = original_manifest.parse()?;
manifest["package"]["version"] = toml_edit::value(version);
let manifest = manifest.to_string();
if dry_run {
if manifest != original_manifest {
let display_path = manifest_path.display().to_string();
let old_lines: Vec<_> = original_manifest
.lines()
.map(|s| format!("{}\n", s))
.collect();
let new_lines: Vec<_> = manifest.lines().map(|s| format!("{}\n", s)).collect();
let diff = difflib::unified_diff(
&old_lines,
&new_lines,
display_path.as_str(),
display_path.as_str(),
"original",
"updated",
0,
);
log::debug!("change:\n{}", itertools::join(diff.into_iter(), ""));
}
} else {
atomic_write(manifest_path, &manifest)?;
}
Ok(())
}
pub fn upgrade_dependency_req(
manifest_name: &str,
manifest_path: &Path,
root: &Path,
name: &str,
version: &semver::Version,
upgrade: config::DependentVersion,
dry_run: bool,
) -> CargoResult<()> {
let manifest_root = manifest_path
.parent()
.expect("always at least a parent dir");
let original_manifest = std::fs::read_to_string(manifest_path)?;
let mut manifest: toml_edit::Document = original_manifest.parse()?;
for dep_item in find_dependency_tables(manifest.as_table_mut())
.flat_map(|t| t.iter_mut().filter_map(|(_, d)| d.as_table_like_mut()))
.filter(|d| is_relevant(*d, manifest_root, root))
{
upgrade_req(manifest_name, dep_item, name, version, upgrade);
}
let manifest = manifest.to_string();
if manifest != original_manifest {
if dry_run {
let display_path = manifest_path.display().to_string();
let old_lines: Vec<_> = original_manifest
.lines()
.map(|s| format!("{}\n", s))
.collect();
let new_lines: Vec<_> = manifest.lines().map(|s| format!("{}\n", s)).collect();
let diff = difflib::unified_diff(
&old_lines,
&new_lines,
display_path.as_str(),
display_path.as_str(),
"original",
"updated",
0,
);
log::debug!("change:\n{}", itertools::join(diff.into_iter(), ""));
} else {
atomic_write(manifest_path, &manifest)?;
}
}
Ok(())
}
fn find_dependency_tables(
root: &mut toml_edit::Table,
) -> impl Iterator<Item = &mut dyn toml_edit::TableLike> + '_ {
const DEP_TABLES: &[&str] = &["dependencies", "dev-dependencies", "build-dependencies"];
root.iter_mut().flat_map(|(k, v)| {
if DEP_TABLES.contains(&k.get()) {
v.as_table_like_mut().into_iter().collect::<Vec<_>>()
} else if k == "workspace" {
v.as_table_like_mut()
.unwrap()
.iter_mut()
.filter_map(|(k, v)| {
if k.get() == "dependencies" {
v.as_table_like_mut()
} else {
None
}
})
.collect::<Vec<_>>()
} else if k == "target" {
v.as_table_like_mut()
.unwrap()
.iter_mut()
.flat_map(|(_, v)| {
v.as_table_like_mut().into_iter().flat_map(|v| {
v.iter_mut().filter_map(|(k, v)| {
if DEP_TABLES.contains(&k.get()) {
v.as_table_like_mut()
} else {
None
}
})
})
})
.collect::<Vec<_>>()
} else {
Vec::new()
}
})
}
fn is_relevant(d: &dyn toml_edit::TableLike, dep_crate_root: &Path, crate_root: &Path) -> bool {
if !d.contains_key("version") {
return false;
}
match d
.get("path")
.and_then(|i| i.as_str())
.and_then(|relpath| dunce::canonicalize(dep_crate_root.join(relpath)).ok())
{
Some(dep_path) => dep_path == crate_root,
None => false,
}
}
fn upgrade_req(
manifest_name: &str,
dep_item: &mut dyn toml_edit::TableLike,
name: &str,
version: &semver::Version,
upgrade: config::DependentVersion,
) -> bool {
let version_value = if let Some(version_value) = dep_item.get_mut("version") {
version_value
} else {
log::debug!("not updating path-only dependency on {}", name);
return false;
};
let existing_req_str = if let Some(existing_req) = version_value.as_str() {
existing_req
} else {
log::debug!("unsupported dependency {}", name);
return false;
};
let existing_req = if let Ok(existing_req) = semver::VersionReq::parse(existing_req_str) {
existing_req
} else {
log::debug!("unsupported dependency req {}={}", name, existing_req_str);
return false;
};
let new_req = match upgrade {
config::DependentVersion::Fix => {
if !existing_req.matches(version) {
let new_req = crate::ops::version::upgrade_requirement(existing_req_str, version)
.ok()
.flatten();
if let Some(new_req) = new_req {
new_req
} else {
return false;
}
} else {
return false;
}
}
config::DependentVersion::Upgrade => {
let new_req = crate::ops::version::upgrade_requirement(existing_req_str, version)
.ok()
.flatten();
if let Some(new_req) = new_req {
new_req
} else {
return false;
}
}
};
let _ = crate::ops::shell::status(
"Updating",
format!(
"{}'s dependency from {} to {}",
manifest_name, existing_req_str, new_req
),
);
*version_value = toml_edit::value(new_req);
true
}
pub fn update_lock(manifest_path: &Path) -> CargoResult<()> {
cargo_metadata::MetadataCommand::new()
.manifest_path(manifest_path)
.exec()?;
Ok(())
}
pub fn sort_workspace(ws_meta: &cargo_metadata::Metadata) -> Vec<&cargo_metadata::PackageId> {
let members: std::collections::HashSet<_> = ws_meta.workspace_members.iter().collect();
let dep_tree: std::collections::HashMap<_, _> = ws_meta
.resolve
.as_ref()
.expect("cargo-metadata resolved deps")
.nodes
.iter()
.filter_map(|n| {
if members.contains(&n.id) {
let non_dev_pkgs = n.deps.iter().filter_map(|dep| {
let dev_only = dep
.dep_kinds
.iter()
.all(|info| info.kind == cargo_metadata::DependencyKind::Development);
if dev_only {
None
} else {
Some(&dep.pkg)
}
});
Some((&n.id, non_dev_pkgs.collect()))
} else {
None
}
})
.collect();
let mut sorted = Vec::new();
let mut processed = std::collections::HashSet::new();
for pkg_id in ws_meta.workspace_members.iter() {
sort_workspace_inner(ws_meta, pkg_id, &dep_tree, &mut processed, &mut sorted);
}
sorted
}
fn sort_workspace_inner<'m>(
ws_meta: &'m cargo_metadata::Metadata,
pkg_id: &'m cargo_metadata::PackageId,
dep_tree: &std::collections::HashMap<
&'m cargo_metadata::PackageId,
Vec<&'m cargo_metadata::PackageId>,
>,
processed: &mut std::collections::HashSet<&'m cargo_metadata::PackageId>,
sorted: &mut Vec<&'m cargo_metadata::PackageId>,
) {
if !processed.insert(pkg_id) {
return;
}
for dep_id in dep_tree[pkg_id]
.iter()
.filter(|dep_id| dep_tree.contains_key(*dep_id))
{
sort_workspace_inner(ws_meta, dep_id, dep_tree, processed, sorted);
}
sorted.push(pkg_id);
}
fn atomic_write(path: &Path, data: &str) -> std::io::Result<()> {
let temp_path = path
.parent()
.unwrap_or_else(|| Path::new("."))
.join("Cargo.toml.work");
std::fs::write(&temp_path, &data)?;
std::fs::rename(&temp_path, path)?;
Ok(())
}
#[cfg(test)]
mod test {
use super::*;
#[allow(unused_imports)] use assert_fs::prelude::*;
use predicates::prelude::*;
mod set_package_version {
use super::*;
#[test]
fn succeeds() {
let temp = assert_fs::TempDir::new().unwrap();
temp.copy_from("tests/fixtures/simple", &["**"]).unwrap();
let manifest_path = temp.child("Cargo.toml");
let meta = cargo_metadata::MetadataCommand::new()
.manifest_path(manifest_path.path())
.exec()
.unwrap();
assert_eq!(meta.packages[0].version.to_string(), "0.1.0");
set_package_version(manifest_path.path(), "2.0.0", false).unwrap();
let meta = cargo_metadata::MetadataCommand::new()
.manifest_path(manifest_path.path())
.exec()
.unwrap();
assert_eq!(meta.packages[0].version.to_string(), "2.0.0");
temp.close().unwrap();
}
}
mod update_lock {
use super::*;
#[test]
fn in_pkg() {
let temp = assert_fs::TempDir::new().unwrap();
temp.copy_from("tests/fixtures/simple", &["**"]).unwrap();
let manifest_path = temp.child("Cargo.toml");
let lock_path = temp.child("Cargo.lock");
set_package_version(manifest_path.path(), "2.0.0", false).unwrap();
lock_path.assert(predicate::path::eq_file(Path::new(
"tests/fixtures/simple/Cargo.lock",
)));
update_lock(manifest_path.path()).unwrap();
lock_path.assert(
predicate::path::eq_file(Path::new("tests/fixtures/simple/Cargo.lock")).not(),
);
temp.close().unwrap();
}
#[test]
fn in_pure_workspace() {
let temp = assert_fs::TempDir::new().unwrap();
temp.copy_from("tests/fixtures/pure_ws", &["**"]).unwrap();
let manifest_path = temp.child("b/Cargo.toml");
let lock_path = temp.child("Cargo.lock");
set_package_version(manifest_path.path(), "2.0.0", false).unwrap();
lock_path.assert(predicate::path::eq_file(Path::new(
"tests/fixtures/pure_ws/Cargo.lock",
)));
update_lock(manifest_path.path()).unwrap();
lock_path.assert(
predicate::path::eq_file(Path::new("tests/fixtures/pure_ws/Cargo.lock")).not(),
);
temp.close().unwrap();
}
#[test]
fn in_mixed_workspace() {
let temp = assert_fs::TempDir::new().unwrap();
temp.copy_from("tests/fixtures/mixed_ws", &["**"]).unwrap();
let manifest_path = temp.child("Cargo.toml");
let lock_path = temp.child("Cargo.lock");
set_package_version(manifest_path.path(), "2.0.0", false).unwrap();
lock_path.assert(predicate::path::eq_file(Path::new(
"tests/fixtures/mixed_ws/Cargo.lock",
)));
update_lock(manifest_path.path()).unwrap();
lock_path.assert(
predicate::path::eq_file(Path::new("tests/fixtures/mixed_ws/Cargo.lock")).not(),
);
temp.close().unwrap();
}
}
mod sort_workspace {
use super::*;
#[test]
fn circular_dev_dependency() {
let temp = assert_fs::TempDir::new().unwrap();
temp.copy_from("tests/fixtures/mixed_ws", &["**"]).unwrap();
let manifest_path = temp.child("a/Cargo.toml");
manifest_path
.write_str(
r#"
[package]
name = "a"
version = "0.1.0"
authors = []
[dev-dependencies]
b = { path = "../" }
"#,
)
.unwrap();
let root_manifest_path = temp.child("Cargo.toml");
let meta = cargo_metadata::MetadataCommand::new()
.manifest_path(root_manifest_path.path())
.exec()
.unwrap();
let sorted = sort_workspace(&meta);
let root_package = meta.resolve.as_ref().unwrap().root.as_ref().unwrap();
assert_ne!(
sorted[0], root_package,
"The root package must not be the first one to be published."
);
temp.close().unwrap();
}
}
}