diff options
author | Pascal Hertleif <[email protected]> | 2019-11-13 19:51:57 +0000 |
---|---|---|
committer | Pascal Hertleif <[email protected]> | 2019-11-13 19:51:57 +0000 |
commit | 5075c77957e127be51e1b5271567f906abeb50c6 (patch) | |
tree | c8e8d8f29011ad2b2472a201561f3f3dc1627d8f /xtask | |
parent | 5e3c1c2b5f63e57f98a7d02f75a559d225341b1c (diff) |
Use anyhow::Result in xtask, add contexts
This builds on #2231 but was actually done before that. You see, the
cause for #2231 was that I got this error message:
Error: Error { kind: Io(Os { code: 2, kind: NotFound, message: "No such file or directory" }) }
Just switching to `anyhow::Result` got me stack traces (when setting
`RUST_LIB_BACKTRACE=1`) that at least showed
stack backtrace:
0: std::backtrace::Backtrace::create
1: std::backtrace::Backtrace::capture
2: anyhow::error::<impl core::convert::From<E> for anyhow::Error>::from
3: xtask::install_server
4: xtask::install
5: xtask::main
6: std::rt::lang_start::{{closure}}
7: std::panicking::try::do_call
8: __rust_maybe_catch_panic
9: std::rt::lang_start_internal
10: std::rt::lang_start
11: main
With the added contexts (not at all exhaustive), the error became
Error: install server
Caused by:
0: build AutoCfg with target directory
1: No such file or directory (os error 2)
Since anyhow is such a small thing (no new transitive dependencies!),
and in general gives you `Result<T, Box<dyn Error>>` on steroids, I
think this a nice small change. The only slightly annoying thing was to
replace all the `Err(format!(…))?` calls (haven't even looked at whether
we can make it support wrapping strings though), but the `bail!` macro
is shorter anyway :)
Diffstat (limited to 'xtask')
-rw-r--r-- | xtask/Cargo.toml | 1 | ||||
-rw-r--r-- | xtask/src/bin/pre-commit.rs | 4 | ||||
-rw-r--r-- | xtask/src/codegen.rs | 8 | ||||
-rw-r--r-- | xtask/src/codegen/gen_parser_tests.rs | 4 | ||||
-rw-r--r-- | xtask/src/lib.rs | 16 | ||||
-rw-r--r-- | xtask/src/main.rs | 25 |
6 files changed, 29 insertions, 29 deletions
diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index 72b39c3b4..bba4be192 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml | |||
@@ -13,3 +13,4 @@ quote = "1.0.2" | |||
13 | proc-macro2 = "1.0.1" | 13 | proc-macro2 = "1.0.1" |
14 | ron = "0.5.1" | 14 | ron = "0.5.1" |
15 | serde = { version = "1.0.0", features = ["derive"] } | 15 | serde = { version = "1.0.0", features = ["derive"] } |
16 | anyhow = "1.0.19" | ||
diff --git a/xtask/src/bin/pre-commit.rs b/xtask/src/bin/pre-commit.rs index cc6ccb25e..44507fb74 100644 --- a/xtask/src/bin/pre-commit.rs +++ b/xtask/src/bin/pre-commit.rs | |||
@@ -19,10 +19,10 @@ fn update_staged() -> Result<()> { | |||
19 | .current_dir(&root) | 19 | .current_dir(&root) |
20 | .output()?; | 20 | .output()?; |
21 | if !output.status.success() { | 21 | if !output.status.success() { |
22 | Err(format!( | 22 | anyhow::bail!( |
23 | "`git diff --diff-filter=MAR --name-only --cached` exited with {}", | 23 | "`git diff --diff-filter=MAR --name-only --cached` exited with {}", |
24 | output.status | 24 | output.status |
25 | ))?; | 25 | ); |
26 | } | 26 | } |
27 | for line in String::from_utf8(output.stdout)?.lines() { | 27 | for line in String::from_utf8(output.stdout)?.lines() { |
28 | run(&format!("git update-index --add {}", root.join(line).to_string_lossy()), ".")?; | 28 | run(&format!("git update-index --add {}", root.join(line).to_string_lossy()), ".")?; |
diff --git a/xtask/src/codegen.rs b/xtask/src/codegen.rs index 770b55a9a..53f524f42 100644 --- a/xtask/src/codegen.rs +++ b/xtask/src/codegen.rs | |||
@@ -52,7 +52,7 @@ fn update(path: &Path, contents: &str, mode: Mode) -> Result<()> { | |||
52 | _ => (), | 52 | _ => (), |
53 | } | 53 | } |
54 | if mode == Mode::Verify { | 54 | if mode == Mode::Verify { |
55 | Err(format!("`{}` is not up-to-date", path.display()))?; | 55 | anyhow::bail!("`{}` is not up-to-date", path.display()); |
56 | } | 56 | } |
57 | eprintln!("updating {}", path.display()); | 57 | eprintln!("updating {}", path.display()); |
58 | fs::write(path, contents)?; | 58 | fs::write(path, contents)?; |
@@ -101,10 +101,8 @@ fn do_extract_comment_blocks(text: &str, allow_blocks_with_empty_lins: bool) -> | |||
101 | let is_comment = line.starts_with(prefix); | 101 | let is_comment = line.starts_with(prefix); |
102 | if is_comment { | 102 | if is_comment { |
103 | block.push(line[prefix.len()..].to_string()); | 103 | block.push(line[prefix.len()..].to_string()); |
104 | } else { | 104 | } else if !block.is_empty() { |
105 | if !block.is_empty() { | 105 | res.push(mem::replace(&mut block, Vec::new())); |
106 | res.push(mem::replace(&mut block, Vec::new())) | ||
107 | } | ||
108 | } | 106 | } |
109 | } | 107 | } |
110 | if !block.is_empty() { | 108 | if !block.is_empty() { |
diff --git a/xtask/src/codegen/gen_parser_tests.rs b/xtask/src/codegen/gen_parser_tests.rs index d0f0f683b..2977da2fa 100644 --- a/xtask/src/codegen/gen_parser_tests.rs +++ b/xtask/src/codegen/gen_parser_tests.rs | |||
@@ -102,10 +102,10 @@ fn tests_from_dir(dir: &Path) -> Result<Tests> { | |||
102 | for test in collect_tests(&text) { | 102 | for test in collect_tests(&text) { |
103 | if test.ok { | 103 | if test.ok { |
104 | if let Some(old_test) = res.ok.insert(test.name.clone(), test) { | 104 | if let Some(old_test) = res.ok.insert(test.name.clone(), test) { |
105 | return Err(format!("Duplicate test: {}", old_test.name).into()); | 105 | anyhow::bail!("Duplicate test: {}", old_test.name); |
106 | } | 106 | } |
107 | } else if let Some(old_test) = res.err.insert(test.name.clone(), test) { | 107 | } else if let Some(old_test) = res.err.insert(test.name.clone(), test) { |
108 | return Err(format!("Duplicate test: {}", old_test.name).into()); | 108 | anyhow::bail!("Duplicate test: {}", old_test.name); |
109 | } | 109 | } |
110 | } | 110 | } |
111 | Ok(()) | 111 | Ok(()) |
diff --git a/xtask/src/lib.rs b/xtask/src/lib.rs index bae4c4650..bfee2f9c8 100644 --- a/xtask/src/lib.rs +++ b/xtask/src/lib.rs | |||
@@ -2,10 +2,10 @@ | |||
2 | 2 | ||
3 | pub mod codegen; | 3 | pub mod codegen; |
4 | 4 | ||
5 | use anyhow::Context; | ||
6 | pub use anyhow::Result; | ||
5 | use std::{ | 7 | use std::{ |
6 | env, | 8 | env, fs, |
7 | error::Error, | ||
8 | fs, | ||
9 | io::{Error as IoError, ErrorKind}, | 9 | io::{Error as IoError, ErrorKind}, |
10 | path::{Path, PathBuf}, | 10 | path::{Path, PathBuf}, |
11 | process::{Command, Output, Stdio}, | 11 | process::{Command, Output, Stdio}, |
@@ -13,8 +13,6 @@ use std::{ | |||
13 | 13 | ||
14 | use crate::codegen::Mode; | 14 | use crate::codegen::Mode; |
15 | 15 | ||
16 | pub type Result<T> = std::result::Result<T, Box<dyn Error>>; | ||
17 | |||
18 | const TOOLCHAIN: &str = "stable"; | 16 | const TOOLCHAIN: &str = "stable"; |
19 | 17 | ||
20 | pub fn project_root() -> PathBuf { | 18 | pub fn project_root() -> PathBuf { |
@@ -69,7 +67,7 @@ pub fn run_rustfmt(mode: Mode) -> Result<()> { | |||
69 | .status() | 67 | .status() |
70 | { | 68 | { |
71 | Ok(status) if status.success() => (), | 69 | Ok(status) if status.success() => (), |
72 | _ => install_rustfmt()?, | 70 | _ => install_rustfmt().context("install rustfmt")?, |
73 | }; | 71 | }; |
74 | 72 | ||
75 | if mode == Mode::Verify { | 73 | if mode == Mode::Verify { |
@@ -112,7 +110,7 @@ pub fn run_clippy() -> Result<()> { | |||
112 | .status() | 110 | .status() |
113 | { | 111 | { |
114 | Ok(status) if status.success() => (), | 112 | Ok(status) if status.success() => (), |
115 | _ => install_clippy()?, | 113 | _ => install_clippy().context("install clippy")?, |
116 | }; | 114 | }; |
117 | 115 | ||
118 | let allowed_lints = [ | 116 | let allowed_lints = [ |
@@ -162,9 +160,9 @@ where | |||
162 | let exec = args.next().unwrap(); | 160 | let exec = args.next().unwrap(); |
163 | let mut cmd = Command::new(exec); | 161 | let mut cmd = Command::new(exec); |
164 | f(cmd.args(args).current_dir(proj_dir).stderr(Stdio::inherit())); | 162 | f(cmd.args(args).current_dir(proj_dir).stderr(Stdio::inherit())); |
165 | let output = cmd.output()?; | 163 | let output = cmd.output().with_context(|| format!("running `{}`", cmdline))?; |
166 | if !output.status.success() { | 164 | if !output.status.success() { |
167 | Err(format!("`{}` exited with {}", cmdline, output.status))?; | 165 | anyhow::bail!("`{}` exited with {}", cmdline, output.status); |
168 | } | 166 | } |
169 | Ok(output) | 167 | Ok(output) |
170 | } | 168 | } |
diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 84842b428..7eab1c949 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs | |||
@@ -9,6 +9,7 @@ | |||
9 | //! `.cargo/config`. | 9 | //! `.cargo/config`. |
10 | mod help; | 10 | mod help; |
11 | 11 | ||
12 | use anyhow::Context; | ||
12 | use autocfg; | 13 | use autocfg; |
13 | use core::fmt::Write; | 14 | use core::fmt::Write; |
14 | use core::str; | 15 | use core::str; |
@@ -114,21 +115,21 @@ fn handle_extra_flags(e: pico_args::Error) -> Result<()> { | |||
114 | write!(&mut invalid_flags, "{}, ", flag)?; | 115 | write!(&mut invalid_flags, "{}, ", flag)?; |
115 | } | 116 | } |
116 | let (invalid_flags, _) = invalid_flags.split_at(invalid_flags.len() - 2); | 117 | let (invalid_flags, _) = invalid_flags.split_at(invalid_flags.len() - 2); |
117 | Err(format!("Invalid flags: {}", invalid_flags).into()) | 118 | anyhow::bail!("Invalid flags: {}", invalid_flags) |
118 | } else { | 119 | } else { |
119 | Err(e.to_string().into()) | 120 | anyhow::bail!(e.to_string()) |
120 | } | 121 | } |
121 | } | 122 | } |
122 | 123 | ||
123 | fn install(opts: InstallOpt) -> Result<()> { | 124 | fn install(opts: InstallOpt) -> Result<()> { |
124 | if cfg!(target_os = "macos") { | 125 | if cfg!(target_os = "macos") { |
125 | fix_path_for_mac()? | 126 | fix_path_for_mac().context("Fix path for mac")? |
126 | } | 127 | } |
127 | if let Some(server) = opts.server { | 128 | if let Some(server) = opts.server { |
128 | install_server(server)?; | 129 | install_server(server).context("install server")?; |
129 | } | 130 | } |
130 | if let Some(client) = opts.client { | 131 | if let Some(client) = opts.client { |
131 | install_client(client)?; | 132 | install_client(client).context("install client")?; |
132 | } | 133 | } |
133 | Ok(()) | 134 | Ok(()) |
134 | } | 135 | } |
@@ -140,7 +141,7 @@ fn fix_path_for_mac() -> Result<()> { | |||
140 | const ROOT_DIR: &str = ""; | 141 | const ROOT_DIR: &str = ""; |
141 | let home_dir = match env::var("HOME") { | 142 | let home_dir = match env::var("HOME") { |
142 | Ok(home) => home, | 143 | Ok(home) => home, |
143 | Err(e) => Err(format!("Failed getting HOME from environment with error: {}.", e))?, | 144 | Err(e) => anyhow::bail!("Failed getting HOME from environment with error: {}.", e), |
144 | }; | 145 | }; |
145 | 146 | ||
146 | [ROOT_DIR, &home_dir] | 147 | [ROOT_DIR, &home_dir] |
@@ -154,12 +155,12 @@ fn fix_path_for_mac() -> Result<()> { | |||
154 | if !vscode_path.is_empty() { | 155 | if !vscode_path.is_empty() { |
155 | let vars = match env::var_os("PATH") { | 156 | let vars = match env::var_os("PATH") { |
156 | Some(path) => path, | 157 | Some(path) => path, |
157 | None => Err("Could not get PATH variable from env.")?, | 158 | None => anyhow::bail!("Could not get PATH variable from env."), |
158 | }; | 159 | }; |
159 | 160 | ||
160 | let mut paths = env::split_paths(&vars).collect::<Vec<_>>(); | 161 | let mut paths = env::split_paths(&vars).collect::<Vec<_>>(); |
161 | paths.append(&mut vscode_path); | 162 | paths.append(&mut vscode_path); |
162 | let new_paths = env::join_paths(paths)?; | 163 | let new_paths = env::join_paths(paths).context("build env PATH")?; |
163 | env::set_var("PATH", &new_paths); | 164 | env::set_var("PATH", &new_paths); |
164 | } | 165 | } |
165 | 166 | ||
@@ -198,7 +199,7 @@ fn install_client(ClientOpt::VsCode: ClientOpt) -> Result<()> { | |||
198 | 199 | ||
199 | let code_binary = match code_binary { | 200 | let code_binary = match code_binary { |
200 | Some(it) => it, | 201 | Some(it) => it, |
201 | None => Err("Can't execute `code --version`. Perhaps it is not in $PATH?")?, | 202 | None => anyhow::bail!("Can't execute `code --version`. Perhaps it is not in $PATH?"), |
202 | }; | 203 | }; |
203 | 204 | ||
204 | Cmd { | 205 | Cmd { |
@@ -219,8 +220,10 @@ fn install_client(ClientOpt::VsCode: ClientOpt) -> Result<()> { | |||
219 | .run_with_output()?; | 220 | .run_with_output()?; |
220 | 221 | ||
221 | if !str::from_utf8(&output.stdout)?.contains("ra-lsp") { | 222 | if !str::from_utf8(&output.stdout)?.contains("ra-lsp") { |
222 | Err("Could not install the Visual Studio Code extension. \ | 223 | anyhow::bail!( |
223 | Please make sure you have at least NodeJS 10.x installed and try again.")?; | 224 | "Could not install the Visual Studio Code extension. \ |
225 | Please make sure you have at least NodeJS 10.x installed and try again." | ||
226 | ); | ||
224 | } | 227 | } |
225 | 228 | ||
226 | Ok(()) | 229 | Ok(()) |