Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

all: Port from chainerror to thiserror #114

Merged
merged 2 commits into from
Dec 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion varlink-certification/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ serde = "1.0.102"
serde_derive = "1.0.102"
serde_json = "1.0.41"
getopts = "0.2.21"
chainerror = "1"
thiserror = "2.0.3"

[build-dependencies]
varlink_generator = { path = "../varlink_generator" }
5 changes: 2 additions & 3 deletions varlink-certification/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ use std::time::Instant;

pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;

use chainerror::Context;
use varlink::{Connection, StringHashMap, StringHashSet, VarlinkService};

mod org_varlink_certification {
Expand Down Expand Up @@ -72,15 +71,15 @@ fn main() -> Result<()> {
let connection = match matches.opt_str("varlink") {
None => match matches.opt_str("bridge") {
Some(bridge) => Connection::with_bridge(&bridge)
.context(format!("Connection::with_bridge({})", bridge))?,
.map_err(|e| format!("Connection::with_bridge({bridge}): {e}"))?,
None => Connection::with_activate(&format!(
"{} \
--varlink=$VARLINK_ADDRESS",
program
))?,
},
Some(address) => Connection::with_address(&address)
.context(format!("Connection::with_address({})", address))?,
.map_err(|e| format!("Connection::with_address({address}): {e}"))?,
};
run_client(connection)?
} else if let Some(address) = matches.opt_str("varlink") {
Expand Down
4 changes: 2 additions & 2 deletions varlink-cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@ path = "src/main.rs"
[dependencies]
varlink = { version = "11", path = "../varlink" }
varlink_stdinterfaces = { version = "11", path = "../varlink_stdinterfaces" }
varlink_parser = { version = "4.3", path = "../varlink_parser" }
varlink_parser = { version = "5.0", path = "../varlink_parser" }
serde = "1.0.102"
serde_json = "1.0.41"
clap = "2.33.0"
colored_json = "2.1.0"
chainerror = "0.8.0"
anyhow = "1.0.93"
libc = { version = "0.2.126", default-features = false }
bitflags = "1.2.1"
97 changes: 48 additions & 49 deletions varlink-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ use std::io::prelude::*;
use std::path::Path;
use std::str;

use chainerror::prelude::v1::*;
use clap::{App, Arg, SubCommand};
use colored_json::{ColorMode, ColoredFormatter, Colour, Output, PrettyFormatter, Style, Styler};

Expand All @@ -26,14 +25,12 @@ pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error + 'static
fn varlink_format(filename: &str, line_len: Option<&str>, should_colorize: bool) -> Result<()> {
let mut buffer = String::new();
File::open(Path::new(filename))
.context(format!("Failed to open '{}'", filename))?
.map_err(|e| format!("Failed to open '{filename}': {e}"))?
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is fine, though I think using anyhow (and keeping .context) is more ergonomic than this map_err.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

True, in the apps we should use anyhow. I should have waited longer for your review. :)

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No big deal 😄

.read_to_string(&mut buffer)
.context(format!("Failed to read '{}'", filename))?;
.map_err(|e| format!("Failed to read '{filename}': {e}"))?;

let idl = IDL::try_from(buffer.as_str()).map_context(|e| {
let v: Vec<_> = e.iter().map(ToString::to_string).collect();
v.join("\n")
})?;
let idl =
IDL::try_from(buffer.as_str()).map_err(|e| format!("Failed to parse '{filename}': {e}"))?;

if should_colorize {
println!(
Expand Down Expand Up @@ -64,25 +61,26 @@ fn varlink_info(

let connection = match activate {
Some(activate) => Connection::with_activate(activate)
.context(format!("Failed to connect with activate '{}'", activate))?,
.map_err(|e| format!("Failed to connect with activate '{activate}': {e}"))?,
None => match bridge {
Some(bridge) => Connection::with_bridge(bridge)
.context(format!("Failed to connect with bridge '{}'", bridge))?,
.map_err(|e| format!("Failed to connect with bridge '{bridge}': {e}"))?,
None => {
let address = address.unwrap();
if address.rfind(':').is_none() {
let conn = Connection::new(resolver)
.context(format!("Failed to connect with resolver '{}'", resolver))?;
let conn = Connection::new(resolver).map_err(|e| {
format!("Failed to connect with resolver '{resolver}': {e}")
})?;
let mut resolver = VarlinkClient::new(conn);
let address = match resolver.resolve(address.into()).call() {
Ok(r) => r.address,
_ => return Err(format!("Interface '{}' not found", address).into()),
};
Connection::with_address(&address)
.context(format!("Failed to connect to '{}'", address))?
.map_err(|e| format!("Failed to connect to '{address}': {e}"))?
} else {
Connection::with_address(&address)
.context(format!("Failed to connect to '{}'", address))?
.map_err(|e| format!("Failed to connect to '{address}': {e}"))?
}
}
},
Expand All @@ -91,7 +89,7 @@ fn varlink_info(
let mut call = OrgVarlinkServiceClient::new(connection);
let info = call
.get_info()
.context("Cannot call GetInfo()".to_string())?;
.map_err(|e| format!("Cannot call GetInfo(): {e}"))?;

println!("{} {}", bold("Vendor:"), info.vendor);
println!("{} {}", bold("Product:"), info.product);
Expand Down Expand Up @@ -120,25 +118,27 @@ fn varlink_help(
let connection = if let Some(del) = url.rfind('/') {
address = &url[0..del];
interface = &url[(del + 1)..];
Connection::with_address(&address).context(format!("Cannot connect to '{}'", address))?
Connection::with_address(&address)
.map_err(|e| format!("Cannot connect to '{address}': {e}"))?
} else {
interface = url;
match activate {
Some(activate) => Connection::with_activate(activate)
.context(format!("Failed to connect with activate '{}'", activate))?,
.map_err(|e| format!("Failed to connect with activate '{activate}': {e}"))?,
None => match bridge {
Some(bridge) => Connection::with_bridge(bridge)
.context(format!("Failed to connect with bridge '{}'", bridge))?,
.map_err(|e| format!("Failed to connect with bridge '{bridge}': {e}"))?,
None => {
let conn = Connection::new(resolver)
.context(format!("Failed to connect with resolver '{}'", resolver))?;
let conn = Connection::new(resolver).map_err(|e| {
format!("Failed to connect with resolver '{resolver}': {e}")
})?;
let mut resolver = VarlinkClient::new(conn);
let address = match resolver.resolve(interface.into()).call() {
Ok(r) => r.address,
_ => return Err(format!("Interface '{}' not found", interface).into()),
_ => return Err(format!("Interface '{interface}' not found").into()),
};
Connection::with_address(&address)
.context(format!("Failed to connect to '{}'", address))?
.map_err(|e| format!("Failed to connect to '{address}': {e}"))?
}
},
}
Expand All @@ -151,18 +151,16 @@ fn varlink_help(
let mut call = OrgVarlinkServiceClient::new(connection);
match call
.get_interface_description(interface.to_string())
.context(format!(
"Can't get interface description for '{}'",
interface
))? {
.map_err(|e| format!("Can't get interface description for '{interface}': {e}"))?
{
GetInterfaceDescriptionReply {
description: Some(desc),
} => {
if should_colorize {
println!(
"{}",
IDL::try_from(desc.as_str())
.context(format!("Can't parse '{}'", desc))?
.map_err(|e| format!("Can't parse '{desc}': {e}"))?
.get_multiline_colored(
0,
columns.unwrap_or("80").parse::<usize>().unwrap_or(80),
Expand All @@ -172,7 +170,7 @@ fn varlink_help(
println!(
"{}",
IDL::try_from(desc.as_str())
.context(format!("Can't parse '{}'", desc))?
.map_err(|e| format!("Can't parse '{desc}': {e}"))?
.get_multiline(0, columns.unwrap_or("80").parse::<usize>().unwrap_or(80))
);
}
Expand Down Expand Up @@ -201,13 +199,13 @@ fn varlink_call(
Some(activate) => {
method = url;
Connection::with_activate(activate)
.context(format!("Failed to connect with activate '{}'", activate))?
.map_err(|e| format!("Failed to connect with activate '{activate}': {e}"))?
}
None => match bridge {
Some(bridge) => {
method = url;
Connection::with_bridge(bridge)
.context(format!("Failed to connect with bridge '{}'", bridge))?
.map_err(|e| format!("Failed to connect with bridge '{bridge}': {e}"))?
}
None => {
if let Some(del) = url.rfind('/') {
Expand All @@ -226,8 +224,9 @@ fn varlink_call(
} else {
return Err(format!("Invalid address {}", url).into());
}
let conn = Connection::new(resolver)
.context(format!("Failed to connect with resolver '{}'", resolver))?;
let conn = Connection::new(resolver).map_err(|e| {
format!("Failed to connect with resolver '{resolver}': {e}")
})?;
let mut resolver = VarlinkClient::new(conn);
address = match resolver.resolve(interface.into()).call() {
Ok(r) => {
Expand All @@ -238,15 +237,14 @@ fn varlink_call(
};
}
Connection::with_address(address)
.context(format!("Failed to connect to '{}'", address))?
.map_err(|e| format!("Failed to connect to '{address}': {e}"))?
}
},
};

let args = match args {
Some(args) => {
serde_json::from_str(args).context(format!("Failed to parse JSON for '{}'", args))?
}
Some(args) => serde_json::from_str(args)
.map_err(|e| format!("Failed to parse JSON for '{args}': {e}"))?,
None => serde_json::Value::Null,
};

Expand Down Expand Up @@ -283,7 +281,7 @@ fn varlink_call(
} else {
for ret in call
.more()
.context(format!("Failed to call method '{}({})'", method, args))?
.map_err(|e| format!("Failed to call method '{method}({args})': {e}"))?
{
print_call_ret(color_mode, cf.clone(), ret, should_colorize, method, &args)?
}
Expand All @@ -306,9 +304,9 @@ fn print_call_ret(
|w| w.to_string()
};

let reply = ret.map_context({
let reply = ret.map_err(|e| {
let cf = cf.clone();
|e| match e.kind() {
match e.kind() {
varlink::ErrorKind::InterfaceNotFound(s) => format!(
"Call failed with error: {}: {}",
red("InterfaceNotFound"),
Expand Down Expand Up @@ -346,7 +344,7 @@ fn print_call_ret(
println!(
"{}",
cf.to_colored_json(&reply, color_mode)
.context(format!("Failed to print json for '{}'", reply))?
.map_err(|e| format!("Failed to print json for '{reply}': {e}"))?
);

Ok(())
Expand All @@ -363,30 +361,31 @@ fn varlink_bridge(

let connection = match activate {
Some(activate) => Connection::with_activate_no_rw(activate)
.context(format!("Failed to connect with activate '{}'", activate))?,
.map_err(|e| format!("Failed to connect with activate '{activate}': {e}"))?,
None => match bridge {
Some(bridge) => Connection::with_bridge_no_rw(bridge)
.context(format!("Failed to connect with bridge '{}'", bridge))?,
.map_err(|e| format!("Failed to connect with bridge '{bridge}': {e}"))?,
None => {
if let Some(address) = address {
if address.rfind(':').is_none() {
let conn = Connection::new(resolver)
.context(format!("Failed to connect with resolver '{}'", resolver))?;
let conn = Connection::new(resolver).map_err(|e| {
format!("Failed to connect with resolver '{resolver}': {e}")
})?;
let mut resolver = VarlinkClient::new(conn);
let address = match resolver.resolve(address.into()).call() {
Ok(r) => r.address,
_ => return Err(format!("Interface '{}' not found", address).into()),
};
Connection::with_address_no_rw(&address)
.context(format!("Failed to connect to '{}'", address))?
.map_err(|e| format!("Failed to connect to '{address}': {e}"))?
} else {
Connection::with_address_no_rw(&address)
.context(format!("Failed to connect to '{}'", address))?
.map_err(|e| format!("Failed to connect to '{address}': {e}"))?
}
} else {
let stdin = ::std::io::stdin();
let stdout = ::std::io::stdout();
handle(resolver, stdin, stdout).context("Bridging".to_string())?;
handle(resolver, stdin, stdout).map_err(|e| format!("Bridging: {e}"))?;
return Ok(());
}
}
Expand All @@ -405,7 +404,7 @@ fn varlink_bridge(
}
}
}
r.context("Bridging".to_string())?;
r.map_err(|e| format!("Bridging: {e}"))?;

Ok(())
}
Expand Down Expand Up @@ -628,7 +627,7 @@ fn do_main(app: &mut App) -> Result<()> {
let address = sub_matches.value_of("ADDRESS");
if address.is_none() && activate.is_none() && bridge.is_none() {
app.print_help()
.context("Couldn't print help".to_string())?;
.map_err(|e| format!("Couldn't print help: {e}"))?;
println!();
return Err("No ADDRESS or activation or bridge".to_string().into());
}
Expand Down Expand Up @@ -661,7 +660,7 @@ fn do_main(app: &mut App) -> Result<()> {
}
(_, _) => {
app.print_help()
.context("Couldn't print help".to_string())?;
.map_err(|e| format!("Couldn't print help: {e}"))?;
println!();
}
}
Expand Down
6 changes: 3 additions & 3 deletions varlink-cli/src/proxy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use std::os::unix::io::{AsRawFd, FromRawFd};
use std::sync::{Arc, RwLock};
use std::thread;

use chainerror::prelude::v1::*;
use serde_json::{from_slice, from_value, to_string};

use varlink::{
Expand All @@ -21,7 +20,7 @@ where
W: Write + AsRawFd + Send + 'static,
{
let conn = Connection::new(resolver)
.context(format!("Failed to connect to resolver '{}'", resolver))?;
.map_err(|e| format!("Failed to connect to resolver '{resolver}': {e}"))?;

let mut client_bufreader = unsafe {
::std::io::BufReader::new(::std::fs::File::from_raw_fd(client_reader.as_raw_fd()))
Expand All @@ -46,7 +45,8 @@ where
// pop the last zero byte
buf.pop();

let mut req: Request = from_slice(&buf).context("Error from slice".to_string())?;
let mut req: Request =
from_slice(&buf).map_err(|e| format!("Error from slice: {e}"))?;

if req.method == "org.varlink.service.GetInfo" {
req.method = "org.varlink.resolver.GetInfo".into();
Expand Down
3 changes: 1 addition & 2 deletions varlink_derive/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,4 @@ name = "varlink_derive"
path = "src/lib.rs"

[dependencies]
varlink_generator = { version = "10.1", path = "../varlink_generator" }

varlink_generator = { version = "11.0", path = "../varlink_generator" }
12 changes: 1 addition & 11 deletions varlink_derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,17 +151,7 @@ fn parse_varlink_args(input: TokenStream) -> (String, String, Span) {
}

fn expand_varlink(name: String, source: String) -> TokenStream {
let code = match varlink_generator::compile(source) {
Ok(code) => code,
Err(e) => {
let mut s = String::new();
for i in e.iter() {
s += &i.to_string();
s += "\n";
}
panic!("{}", s)
}
};
let code = varlink_generator::compile(source).unwrap();

format!("mod {} {{ {} }}", name, code).parse().unwrap()
}
Loading
Loading