-
Notifications
You must be signed in to change notification settings - Fork 162
Expand file tree
/
Copy pathmain.rs
More file actions
281 lines (251 loc) · 9.67 KB
/
main.rs
File metadata and controls
281 lines (251 loc) · 9.67 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
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
//! `cargo version`
#![warn(
missing_docs,
missing_debug_implementations,
missing_copy_implementations,
trivial_casts,
trivial_numeric_casts,
unsafe_code,
unstable_features,
unused_import_braces,
unused_qualifications
)]
#![allow(clippy::comparison_chain)]
#[macro_use]
extern crate error_chain;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process;
use cargo_edit::{
find, manifest_from_pkgid, upgrade_requirement, workspace_members, LocalManifest,
};
use structopt::StructOpt;
use termcolor::{BufferWriter, Color, ColorChoice, ColorSpec, WriteColor};
mod args;
mod errors;
mod version;
use crate::args::*;
use crate::errors::*;
fn main() {
let args = Command::from_args();
let Command::Version(args) = args;
if let Err(err) = process(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);
}
}
/// Main processing function. Allows us to return a `Result` so that `main` can print pretty error
/// messages.
fn process(args: Args) -> Result<()> {
let Args {
target,
bump,
metadata,
manifest: clap_cargo::Manifest { manifest_path, .. },
workspace:
clap_cargo::Workspace {
package: pkgid,
workspace,
all,
exclude,
..
},
dry_run,
} = args;
let target = match (target, bump) {
(None, None) => version::TargetVersion::Relative(version::BumpLevel::Release),
(None, Some(level)) => version::TargetVersion::Relative(level),
(Some(version), None) => version::TargetVersion::Absolute(version),
(Some(_), Some(_)) => unreachable!("clap groups should prevent this"),
};
if all {
deprecated_message("The flag `--all` has been deprecated in favor of `--workspace`")?;
}
let all = workspace || all || LocalManifest::find(&None)?.is_virtual();
let manifests = if all {
Manifests::get_all(&manifest_path)
} else if let Some(id) = pkgid.get(0) {
Manifests::get_pkgid(manifest_path.as_deref(), id)
} else {
Manifests::get_local_one(&manifest_path)
}?;
if dry_run {
dry_run_message()?;
}
let workspace_members = workspace_members(manifest_path.as_deref())?;
for (mut manifest, package) in manifests.0 {
if exclude.contains(&package.name) {
continue;
}
let current = &package.version;
let next = target.bump(current, metadata.as_deref())?;
if let Some(next) = next {
manifest.set_package_version(&next);
upgrade_message(package.name.as_str(), current, &next)?;
if !dry_run {
manifest.write()?;
}
let crate_root = manifest.path.parent().expect("at least a parent");
for member in workspace_members.iter() {
let mut dep_manifest = LocalManifest::try_new(member.manifest_path.as_std_path())?;
let dep_crate_root = dep_manifest
.path
.parent()
.expect("at least a parent")
.to_owned();
for dep in dep_manifest
.get_dependency_tables_mut()
.flat_map(|t| t.iter_mut().filter_map(|(_, d)| d.as_table_like_mut()))
.filter(|d| {
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,
}
})
{
let old_req = dep
.get("version")
.expect("filter ensures this")
.as_str()
.unwrap_or("*");
if let Some(new_req) = upgrade_requirement(old_req, &next)? {
upgrade_dependent_message(member.name.as_str(), old_req, &new_req)?;
dep.insert("version", toml_edit::value(new_req));
}
}
if !dry_run {
dep_manifest.write()?;
}
}
}
}
Ok(())
}
/// A collection of manifests.
struct Manifests(Vec<(LocalManifest, cargo_metadata::Package)>);
impl Manifests {
/// Get all manifests in the workspace.
fn get_all(manifest_path: &Option<PathBuf>) -> Result<Self> {
let mut cmd = cargo_metadata::MetadataCommand::new();
cmd.no_deps();
if let Some(path) = manifest_path {
cmd.manifest_path(path);
}
let result = cmd
.exec()
.chain_err(|| "Failed to get workspace metadata")?;
result
.packages
.into_iter()
.map(|package| {
Ok((
LocalManifest::try_new(Path::new(&package.manifest_path))?,
package,
))
})
.collect::<Result<Vec<_>>>()
.map(Manifests)
}
fn get_pkgid(manifest_path: Option<&Path>, pkgid: &str) -> Result<Self> {
let package = manifest_from_pkgid(manifest_path, pkgid)?;
let manifest = LocalManifest::try_new(Path::new(&package.manifest_path))?;
Ok(Manifests(vec![(manifest, package)]))
}
/// Get the manifest specified by the manifest path. Try to make an educated guess if no path is
/// provided.
fn get_local_one(manifest_path: &Option<PathBuf>) -> Result<Self> {
let resolved_manifest_path: String = find(manifest_path)?.to_string_lossy().into();
let manifest = LocalManifest::find(manifest_path)?;
let mut cmd = cargo_metadata::MetadataCommand::new();
cmd.no_deps();
if let Some(path) = manifest_path {
cmd.manifest_path(path);
}
let result = cmd.exec().chain_err(|| "Invalid manifest")?;
let packages = result.packages;
let package = packages
.iter()
.find(|p| p.manifest_path == resolved_manifest_path)
// If we have successfully got metadata, but our manifest path does not correspond to a
// package, we must have been called against a virtual manifest.
.chain_err(|| {
"Found virtual manifest, but this command requires running against an \
actual package in this workspace. Try adding `--workspace`."
})?;
Ok(Manifests(vec![(manifest, package.to_owned())]))
}
}
fn dry_run_message() -> Result<()> {
let bufwtr = BufferWriter::stderr(ColorChoice::Always);
let mut buffer = bufwtr.buffer();
buffer
.set_color(ColorSpec::new().set_fg(Some(Color::Cyan)).set_bold(true))
.chain_err(|| "Failed to set output colour")?;
write!(&mut buffer, "Starting dry run. ").chain_err(|| "Failed to write dry run message")?;
buffer
.set_color(&ColorSpec::new())
.chain_err(|| "Failed to clear output colour")?;
writeln!(&mut buffer, "Changes will not be saved.")
.chain_err(|| "Failed to write dry run message")?;
bufwtr
.print(&buffer)
.chain_err(|| "Failed to print dry run message")
}
fn deprecated_message(message: &str) -> Result<()> {
let bufwtr = BufferWriter::stderr(ColorChoice::Always);
let mut buffer = bufwtr.buffer();
buffer
.set_color(ColorSpec::new().set_fg(Some(Color::Red)).set_bold(true))
.chain_err(|| "Failed to set output colour")?;
writeln!(&mut buffer, "{}", message).chain_err(|| "Failed to write dry run message")?;
buffer
.set_color(&ColorSpec::new())
.chain_err(|| "Failed to clear output colour")?;
bufwtr
.print(&buffer)
.chain_err(|| "Failed to print dry run message")
}
fn upgrade_message(name: &str, from: &semver::Version, to: &semver::Version) -> Result<()> {
let bufwtr = BufferWriter::stderr(ColorChoice::Always);
let mut buffer = bufwtr.buffer();
buffer
.set_color(ColorSpec::new().set_fg(Some(Color::Green)).set_bold(true))
.chain_err(|| "Failed to print dry run message")?;
write!(&mut buffer, "{:>12}", "Upgraded").chain_err(|| "Failed to print dry run message")?;
buffer
.reset()
.chain_err(|| "Failed to print dry run message")?;
writeln!(&mut buffer, " {} from {} to {}", name, from, to)
.chain_err(|| "Failed to print dry run message")?;
bufwtr
.print(&buffer)
.chain_err(|| "Failed to print dry run message")
}
fn upgrade_dependent_message(name: &str, old_req: &str, new_req: &str) -> Result<()> {
let bufwtr = BufferWriter::stderr(ColorChoice::Always);
let mut buffer = bufwtr.buffer();
buffer
.set_color(ColorSpec::new().set_fg(Some(Color::Green)).set_bold(true))
.chain_err(|| "Failed to print dry run message")?;
write!(&mut buffer, "{:>16}", "Updated dependency")
.chain_err(|| "Failed to print dry run message")?;
buffer
.reset()
.chain_err(|| "Failed to print dry run message")?;
writeln!(&mut buffer, " {} from {} to {}", name, old_req, new_req)
.chain_err(|| "Failed to print dry run message")?;
bufwtr
.print(&buffer)
.chain_err(|| "Failed to print dry run message")
}