-
Notifications
You must be signed in to change notification settings - Fork 162
Expand file tree
/
Copy pathmain.rs
More file actions
200 lines (181 loc) · 6.23 KB
/
main.rs
File metadata and controls
200 lines (181 loc) · 6.23 KB
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
//! `cargo add`
#![warn(
missing_docs,
missing_debug_implementations,
missing_copy_implementations,
trivial_casts,
trivial_numeric_casts,
unsafe_code,
unstable_features,
unused_import_braces,
unused_qualifications
)]
#[macro_use]
extern crate error_chain;
use crate::args::{Args, Command};
use cargo_edit::{
find, manifest_from_pkgid, registry_url, update_registry_index, Dependency, LocalManifest,
};
use std::borrow::Cow;
use std::io::Write;
use std::path::Path;
use std::process;
use structopt::StructOpt;
use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor};
use toml_edit::Item as TomlItem;
mod args;
mod errors {
error_chain! {
errors {
/// Specified a dependency with both a git URL and a version.
GitUrlWithVersion(git: String, version: String) {
description("Specified git URL with version")
display("Cannot specify a git URL (`{}`) with a version (`{}`).", git, version)
}
/// Specified multiple crates with path or git or vers
MultipleCratesWithGitOrPathOrVers {
description("Specified multiple crates with path or git or vers")
display("Cannot specify multiple crates with path or git or vers")
}
/// Specified multiple crates with renaming.
MultipleCratesWithRename {
description("Specified multiple crates with rename")
display("Cannot specify multiple crates with rename")
}
/// Specified multiple crates with features.
MultipleCratesWithFeatures {
description("Specified multiple crates with features")
display("Cannot specify multiple crates with features")
}
AddingSelf(crate_: String) {
description("Adding crate to itself")
display("Cannot add `{}` as a dependency to itself", crate_)
}
}
links {
CargoEditLib(::cargo_edit::Error, ::cargo_edit::ErrorKind);
}
foreign_links {
CargoMetadata(::cargo_metadata::Error)#[doc = "An error from the cargo_metadata crate"];
Io(::std::io::Error);
}
}
}
use crate::errors::*;
fn print_msg(dep: &Dependency, section: &[String], optional: bool) -> Result<()> {
let colorchoice = if atty::is(atty::Stream::Stdout) {
ColorChoice::Auto
} else {
ColorChoice::Never
};
let mut output = StandardStream::stderr(colorchoice);
output.set_color(ColorSpec::new().set_fg(Some(Color::Green)).set_bold(true))?;
write!(output, "{:>12}", "Adding")?;
output.reset()?;
write!(output, " {}", dep.name)?;
if let Some(version) = dep.version() {
write!(output, " v{}", version)?;
} else {
write!(output, " (unknown version)")?;
}
write!(output, " to")?;
if optional {
write!(output, " optional")?;
}
let section = if section.len() == 1 {
section[0].clone()
} else {
format!("{} for target `{}`", §ion[2], §ion[1])
};
write!(output, " {}", section)?;
if let Some(f) = &dep.features {
writeln!(output, " with features: {:?}", f)?
} else {
writeln!(output)?
}
Ok(())
}
// Based on Iterator::is_sorted from nightly std; remove in favor of that when stabilized.
fn is_sorted(mut it: impl Iterator<Item = impl PartialOrd>) -> bool {
let mut last = match it.next() {
Some(e) => e,
None => return true,
};
for curr in it {
if curr < last {
return false;
}
last = curr;
}
true
}
fn handle_add(args: &Args) -> Result<()> {
let manifest_path = if let Some(pkgid) = args.workspace.package.get(0) {
let pkg = manifest_from_pkgid(args.manifest.manifest_path.as_deref(), pkgid)?;
Cow::Owned(Some(pkg.manifest_path.into_std_path_buf()))
} else {
Cow::Borrowed(&args.manifest.manifest_path)
};
let mut manifest = LocalManifest::find(&manifest_path)?;
if !args.offline && std::env::var("CARGO_IS_TEST").is_err() {
let url = registry_url(
&find(&manifest_path)?,
args.registry.as_ref().map(String::as_ref),
)?;
update_registry_index(&url, args.quiet)?;
}
let deps = &args.parse_dependencies()?;
let was_sorted = manifest
.get_table(&args.get_section())
.map(TomlItem::as_table_mut)
.map_or(true, |table_option| {
table_option.map_or(true, |table| is_sorted(table.iter().map(|(name, _)| name)))
});
deps.iter()
.map(|dep| {
if !args.quiet {
print_msg(dep, &args.get_section(), args.optional)?;
}
if let Some(path) = dep.path() {
if path == manifest.path.parent().unwrap_or_else(|| Path::new("")) {
return Err(ErrorKind::AddingSelf(manifest.package_name()?.to_owned()).into());
}
}
manifest
.insert_into_table(&args.get_section(), dep)
.map(|_| {
manifest
.get_table(&args.get_section())
.map(TomlItem::as_table_mut)
.map(|table_option| {
table_option.map(|table| {
if was_sorted || args.sort {
table.sort_values();
}
})
})
})
.map_err(Into::into)
})
.collect::<Result<Vec<_>>>()
.map_err(|err| {
eprintln!("Could not edit `Cargo.toml`.\n\nERROR: {}", err);
err
})?;
manifest.write()?;
Ok(())
}
fn main() {
let args: Command = Command::from_args();
let Command::Add(args) = args;
if let Err(err) = handle_add(&args) {
eprintln!("Command failed due to unhandled error: {}\n", err);
for e in err.iter().skip(1) {
eprintln!("Caused by: {}", e);
}
if let Some(backtrace) = err.backtrace() {
eprintln!("Backtrace: {:?}", backtrace);
}
process::exit(1);
}
}