From 6e3979fdbbe9adcb11ed69380b493f8362f3b911 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Iv=C3=A1n=20L=C3=B3pez=20Gonz=C3=A1lez?= Date: Fri, 17 May 2024 10:47:36 +0100 Subject: [PATCH 1/2] rust: Fix clippy warnings --- rust/agama-cli/src/auth.rs | 2 +- rust/agama-lib/src/dbus.rs | 12 ++- rust/agama-lib/src/software/client.rs | 2 +- rust/agama-lib/src/storage/client/iscsi.rs | 2 +- rust/agama-lib/src/storage/model.rs | 88 +++++++++---------- rust/agama-server/src/agama-web-server.rs | 1 + rust/agama-server/src/dbus.rs | 10 +-- rust/agama-server/src/l10n/dbus.rs | 6 +- rust/agama-server/src/l10n/l10n.rs | 6 +- rust/agama-server/src/l10n/locale.rs | 4 +- rust/agama-server/src/l10n/web.rs | 10 +-- rust/agama-server/src/network/model.rs | 2 +- rust/agama-server/src/network/nm/dbus.rs | 52 ++++------- rust/agama-server/src/network/nm/watcher.rs | 19 ++-- .../src/storage/web/iscsi/stream.rs | 12 +-- rust/agama-server/src/web/auth.rs | 9 +- rust/agama-server/tests/network_service.rs | 2 +- 17 files changed, 108 insertions(+), 131 deletions(-) diff --git a/rust/agama-cli/src/auth.rs b/rust/agama-cli/src/auth.rs index 80823d96a6..cbc6407eb9 100644 --- a/rust/agama-cli/src/auth.rs +++ b/rust/agama-cli/src/auth.rs @@ -199,7 +199,7 @@ async fn get_jwt(url: String, password: String) -> anyhow::Result { let body = response .json::>() .await?; - let value = body.get(&"token".to_string()); + let value = body.get("token"); if let Some(token) = value { return Ok(token.clone()); diff --git a/rust/agama-lib/src/dbus.rs b/rust/agama-lib/src/dbus.rs index fa9c8e2ec2..145f412c78 100644 --- a/rust/agama-lib/src/dbus.rs +++ b/rust/agama-lib/src/dbus.rs @@ -62,9 +62,7 @@ macro_rules! property_from_dbus { pub fn to_owned_hash(source: &HashMap<&str, Value<'_>>) -> HashMap { let mut owned = HashMap::new(); for (key, value) in source.iter() { - if let Ok(owned_value) = value.try_into() { - owned.insert(key.to_string(), owned_value); - } + owned.insert(key.to_string(), value.into()); } owned } @@ -74,7 +72,7 @@ pub fn to_owned_hash(source: &HashMap<&str, Value<'_>>) -> HashMap Result { path.as_str() - .rsplit_once("/") + .rsplit_once('/') .and_then(|(_, id)| id.parse::().ok()) .ok_or_else(|| { zvariant::Error::Message(format!("Could not extract the ID from {}", path.as_str())) @@ -92,7 +90,7 @@ mod tests { #[test] fn test_get_property() { let data: HashMap = HashMap::from([ - ("Id".to_string(), (1 as u8).into()), + ("Id".to_string(), 1_u8.into()), ("Device".to_string(), Str::from_static("/dev/sda").into()), ]); let id: u8 = get_property(&data, "Id").unwrap(); @@ -105,7 +103,7 @@ mod tests { #[test] fn test_get_property_wrong_type() { let data: HashMap = - HashMap::from([("Id".to_string(), (1 as u8).into())]); + HashMap::from([("Id".to_string(), 1_u8.into())]); let result: Result = get_property(&data, "Id"); assert_eq!(result, Err(zvariant::Error::IncorrectType)); } @@ -113,7 +111,7 @@ mod tests { #[test] fn test_get_optional_property() { let data: HashMap = - HashMap::from([("Id".to_string(), (1 as u8).into())]); + HashMap::from([("Id".to_string(), 1_u8.into())]); let id: Option = get_optional_property(&data, "Id").unwrap(); assert_eq!(id, Some(1)); diff --git a/rust/agama-lib/src/software/client.rs b/rust/agama-lib/src/software/client.rs index 1364956196..d7f8757141 100644 --- a/rust/agama-lib/src/software/client.rs +++ b/rust/agama-lib/src/software/client.rs @@ -92,7 +92,7 @@ impl<'a> SoftwareClient<'a> { .await? .into_iter() .filter_map(|(id, reason)| match SelectedBy::try_from(reason) { - Ok(reason) if reason == SelectedBy::User => Some(id), + Ok(SelectedBy::User) => Some(id), Ok(_reason) => None, Err(e) => { log::warn!("Ignoring pattern {}. Error: {}", &id, e); diff --git a/rust/agama-lib/src/storage/client/iscsi.rs b/rust/agama-lib/src/storage/client/iscsi.rs index 2a02588c2a..105143ed82 100644 --- a/rust/agama-lib/src/storage/client/iscsi.rs +++ b/rust/agama-lib/src/storage/client/iscsi.rs @@ -163,7 +163,7 @@ impl<'a> ISCSIClient<'a> { let result = self .initiator_proxy - .discover(address, port as u32, options_ref) + .discover(address, port, options_ref) .await?; Ok(result == 0) } diff --git a/rust/agama-lib/src/storage/model.rs b/rust/agama-lib/src/storage/model.rs index f2c30b2b22..423f71753c 100644 --- a/rust/agama-lib/src/storage/model.rs +++ b/rust/agama-lib/src/storage/model.rs @@ -18,12 +18,10 @@ impl TryFrom for DeviceSid { type Error = zbus::zvariant::Error; fn try_from(value: i32) -> Result { - u32::try_from(value).map(|v| v.into()).or_else(|_| { - Err(Self::Error::Message(format!( + u32::try_from(value).map(|v| v.into()).map_err(|_| Self::Error::Message(format!( "Cannot convert sid from {}", value ))) - }) } } @@ -48,7 +46,7 @@ impl TryFrom> for DeviceSid { fn try_from(path: zbus::zvariant::ObjectPath) -> Result { path.as_str() - .rsplit_once("/") + .rsplit_once('/') .and_then(|(_, sid)| sid.parse::().ok()) .ok_or_else(|| Self::Error::Message(format!("Cannot parse sid from {}", path))) .map(DeviceSid) @@ -68,12 +66,10 @@ impl TryFrom for DeviceSize { type Error = zbus::zvariant::Error; fn try_from(value: i64) -> Result { - u64::try_from(value).map(|v| v.into()).or_else(|_| { - Err(Self::Error::Message(format!( + u64::try_from(value).map(|v| v.into()).map_err(|_| Self::Error::Message(format!( "Cannot convert size from {}", value ))) - }) } } @@ -94,9 +90,9 @@ impl TryFrom> for DeviceSize { } } -impl<'a> Into> for DeviceSize { - fn into(self) -> Value<'a> { - Value::new(self.0) +impl<'a> From for zbus::zvariant::Value<'a> { + fn from(val: DeviceSize) -> Self { + Value::new(val.0) } } @@ -188,11 +184,11 @@ impl TryFrom> for SpaceActionSettings { } } -impl<'a> Into> for SpaceActionSettings { - fn into(self) -> zbus::zvariant::Value<'a> { +impl<'a> From for zbus::zvariant::Value<'a> { + fn from(val: SpaceActionSettings) -> Self { let result: HashMap<&str, Value> = HashMap::from([ - ("Device", Value::new(self.device)), - ("Action", Value::new(self.action.as_dbus_string())), + ("Device", Value::new(val.device)), + ("Action", Value::new(val.action.as_dbus_string())), ]); Value::new(result) @@ -218,41 +214,41 @@ pub struct ProposalSettingsPatch { pub volumes: Option>, } -impl<'a> Into>> for ProposalSettingsPatch { - fn into(self) -> HashMap<&'static str, Value<'a>> { +impl<'a> From for HashMap<&'static str, Value<'a>> { + fn from(val: ProposalSettingsPatch) -> Self { let mut result = HashMap::new(); - if let Some(target) = self.target { + if let Some(target) = val.target { result.insert("Target", Value::new(target.as_dbus_string())); } - if let Some(dev) = self.target_device { + if let Some(dev) = val.target_device { result.insert("TargetDevice", Value::new(dev)); } - if let Some(devs) = self.target_pv_devices { + if let Some(devs) = val.target_pv_devices { result.insert("TargetPVDevices", Value::new(devs)); } - if let Some(value) = self.configure_boot { + if let Some(value) = val.configure_boot { result.insert("ConfigureBoot", Value::new(value)); } - if let Some(value) = self.boot_device { + if let Some(value) = val.boot_device { result.insert("BootDevice", Value::new(value)); } - if let Some(value) = self.encryption_password { + if let Some(value) = val.encryption_password { result.insert("EncryptionPassword", Value::new(value)); } - if let Some(value) = self.encryption_method { + if let Some(value) = val.encryption_method { result.insert("EncryptionMethod", Value::new(value)); } - if let Some(value) = self.encryption_pbkd_function { + if let Some(value) = val.encryption_pbkd_function { result.insert("EncryptionPBKDFunction", Value::new(value)); } - if let Some(value) = self.space_policy { + if let Some(value) = val.space_policy { result.insert("SpacePolicy", Value::new(value)); } - if let Some(value) = self.space_actions { + if let Some(value) = val.space_actions { let list: Vec = value.into_iter().map(|a| a.into()).collect(); result.insert("SpaceActions", Value::new(list)); } - if let Some(value) = self.volumes { + if let Some(value) = val.volumes { let list: Vec = value.into_iter().map(|a| a.into()).collect(); result.insert("Volumes", Value::new(list)); } @@ -338,14 +334,14 @@ pub enum VolumeTarget { Filesystem, } -impl<'a> Into> for VolumeTarget { - fn into(self) -> zbus::zvariant::Value<'a> { - let str = match self { - Self::Default => "default", - Self::NewPartition => "new_partition", - Self::NewVg => "new_vg", - Self::Device => "device", - Self::Filesystem => "filesystem", +impl<'a> From for zbus::zvariant::Value<'a> { + fn from(val: VolumeTarget) -> Self { + let str = match val { + VolumeTarget::Default => "default", + VolumeTarget::NewPartition => "new_partition", + VolumeTarget::NewVg => "new_vg", + VolumeTarget::Device => "device", + VolumeTarget::Filesystem => "filesystem", }; Value::new(str) @@ -419,23 +415,23 @@ pub struct Volume { outline: Option, } -impl<'a> Into> for Volume { - fn into(self) -> zbus::zvariant::Value<'a> { +impl<'a> From for zbus::zvariant::Value<'a> { + fn from(val: Volume) -> Self { let mut result: HashMap<&str, Value> = HashMap::from([ - ("MountPath", Value::new(self.mount_path)), - ("MountOptions", Value::new(self.mount_options)), - ("Target", self.target.into()), - ("FsType", Value::new(self.fs_type)), - ("AutoSize", Value::new(self.auto_size)), - ("Snapshots", Value::new(self.snapshots)), + ("MountPath", Value::new(val.mount_path)), + ("MountOptions", Value::new(val.mount_options)), + ("Target", val.target.into()), + ("FsType", Value::new(val.fs_type)), + ("AutoSize", Value::new(val.auto_size)), + ("Snapshots", Value::new(val.snapshots)), ]); - if let Some(dev) = self.target_device { + if let Some(dev) = val.target_device { result.insert("TargetDevice", Value::new(dev)); } - if let Some(value) = self.min_size { + if let Some(value) = val.min_size { result.insert("MinSize", value.into()); } - if let Some(value) = self.max_size { + if let Some(value) = val.max_size { result.insert("MaxSize", value.into()); } // intentionally skip outline as it is not send to dbus and act as read only parameter diff --git a/rust/agama-server/src/agama-web-server.rs b/rust/agama-server/src/agama-web-server.rs index 117ec800fa..e49b06ff88 100644 --- a/rust/agama-server/src/agama-web-server.rs +++ b/rust/agama-server/src/agama-web-server.rs @@ -351,6 +351,7 @@ fn write_token(path: &str, secret: &str) -> io::Result<()> { let token = generate_token(secret); let mut file = fs::OpenOptions::new() .create(true) + .truncate(true) .write(true) .mode(0o400) .open(path)?; diff --git a/rust/agama-server/src/dbus.rs b/rust/agama-server/src/dbus.rs index 2fcafa8f9a..1f6e98bb1b 100644 --- a/rust/agama-server/src/dbus.rs +++ b/rust/agama-server/src/dbus.rs @@ -150,7 +150,7 @@ impl DBusObjectChangesStream { .path(manager_path.clone())? .interface("org.freedesktop.DBus.ObjectManager")? .build(); - let stream = MessageStream::for_match_rule(rule, &connection, None).await?; + let stream = MessageStream::for_match_rule(rule, connection, None).await?; Ok(stream) } @@ -168,7 +168,7 @@ impl DBusObjectChangesStream { .interface("org.freedesktop.DBus.Properties")? .member("PropertiesChanged")? .build(); - let stream = MessageStream::for_match_rule(rule, &connection, None).await?; + let stream = MessageStream::for_match_rule(rule, connection, None).await?; Ok(stream) } } @@ -182,10 +182,10 @@ impl Stream for DBusObjectChangesStream { let item = ready!(pinned.inner.as_mut().poll_next(cx)); let next_value = match item { Some((PROPERTIES_CHANGED, message)) => { - Self::handle_properties_changed(message, &pinned.interface) + Self::handle_properties_changed(message, pinned.interface) } Some((OBJECTS_MANAGER, message)) => { - Self::handle_added_or_removed(message, &pinned.interface) + Self::handle_added_or_removed(message, pinned.interface) } _ => None, }; @@ -216,7 +216,7 @@ where } pub fn remove(&mut self, path: &OwnedObjectPath) -> Option { - self.objects.remove(&path) + self.objects.remove(path) } } diff --git a/rust/agama-server/src/l10n/dbus.rs b/rust/agama-server/src/l10n/dbus.rs index 67b2bcf78a..8ed49fd7c6 100644 --- a/rust/agama-server/src/l10n/dbus.rs +++ b/rust/agama-server/src/l10n/dbus.rs @@ -26,7 +26,7 @@ impl L10nInterface { )); } backend.set_locales(&locales).map_err(|e| { - zbus::fdo::Error::Failed(format!("Could not set the locales: {}", e.to_string())) + zbus::fdo::Error::Failed(format!("Could not set the locales: {}", e)) })?; Ok(()) } @@ -60,7 +60,7 @@ impl L10nInterface { .map_err(|_e| zbus::fdo::Error::InvalidArgs("Cannot parse keymap ID".to_string()))?; backend.set_keymap(keymap_id).map_err(|e| { - zbus::fdo::Error::Failed(format!("Could not set the keymap: {}", e.to_string())) + zbus::fdo::Error::Failed(format!("Could not set the keymap: {}", e)) })?; Ok(()) @@ -77,7 +77,7 @@ impl L10nInterface { let mut backend = self.backend.write().unwrap(); backend.set_timezone(timezone).map_err(|e| { - zbus::fdo::Error::Failed(format!("Could not set the timezone: {}", e.to_string())) + zbus::fdo::Error::Failed(format!("Could not set the timezone: {}", e)) })?; Ok(()) } diff --git a/rust/agama-server/src/l10n/l10n.rs b/rust/agama-server/src/l10n/l10n.rs index 5c70cce1df..987329aab8 100644 --- a/rust/agama-server/src/l10n/l10n.rs +++ b/rust/agama-server/src/l10n/l10n.rs @@ -68,7 +68,7 @@ impl L10n { return Err(LocaleError::UnknownLocale(loc.to_string()))?; } } - self.locales = locales.clone(); + self.locales.clone_from(locales); Ok(()) } @@ -77,7 +77,7 @@ impl L10n { if !self.timezones_db.exists(&timezone.to_string()) { return Err(LocaleError::UnknownTimezone(timezone.to_string()))?; } - self.timezone = timezone.to_owned(); + timezone.clone_into(&mut self.timezone); Ok(()) } @@ -92,7 +92,7 @@ impl L10n { // TODO: use LocaleError pub fn translate(&mut self, locale: &LocaleId) -> Result<(), Error> { - helpers::set_service_locale(&locale); + helpers::set_service_locale(locale); self.timezones_db.read(&locale.language)?; self.locales_db.read(&locale.language)?; self.ui_locale = locale.clone(); diff --git a/rust/agama-server/src/l10n/locale.rs b/rust/agama-server/src/l10n/locale.rs index 04def8b22f..e29fc23dcb 100644 --- a/rust/agama-server/src/l10n/locale.rs +++ b/rust/agama-server/src/l10n/locale.rs @@ -109,7 +109,7 @@ impl LocalesDatabase { const LOCALES_LIST_PATH: &str = "/etc/agama.d/locales"; let locales = fs::read_to_string(LOCALES_LIST_PATH) - .map(|content| Self::get_locales_from_string(content)); + .map(Self::get_locales_from_string); if let Ok(locales) = locales { if !locales.is_empty() { @@ -123,7 +123,7 @@ impl LocalesDatabase { .context("Failed to get the list of locales")?; let locales = String::from_utf8(result.stdout) - .map(|content| Self::get_locales_from_string(content)) + .map(Self::get_locales_from_string) .context("Invalid UTF-8 sequence from list-locales")?; Ok(locales) diff --git a/rust/agama-server/src/l10n/web.rs b/rust/agama-server/src/l10n/web.rs index 4ec36694cb..1647a50a1d 100644 --- a/rust/agama-server/src/l10n/web.rs +++ b/rust/agama-server/src/l10n/web.rs @@ -123,19 +123,19 @@ async fn set_config( let mut changes = LocaleConfig::default(); if let Some(locales) = &value.locales { - data.set_locales(&locales)?; - changes.locales = value.locales.clone(); + data.set_locales(locales)?; + changes.locales.clone_from(&value.locales); } if let Some(timezone) = &value.timezone { data.set_timezone(timezone)?; - changes.timezone = value.timezone.clone(); + changes.timezone.clone_from(&value.timezone); } if let Some(keymap_id) = &value.keymap { let keymap_id = keymap_id.parse().map_err(LocaleError::InvalidKeymap)?; data.set_keymap(keymap_id)?; - changes.keymap = value.keymap.clone(); + changes.keymap.clone_from(&value.keymap); } if let Some(ui_locale) = &value.ui_locale { @@ -198,7 +198,7 @@ pub async fn update_dbus( } if let Some(timezone) = &config.timezone { - client.set_timezone(&timezone).await?; + client.set_timezone(timezone).await?; } if let Some(ui_locale) = &config.ui_locale { diff --git a/rust/agama-server/src/network/model.rs b/rust/agama-server/src/network/model.rs index cba18b0612..3199f21860 100644 --- a/rust/agama-server/src/network/model.rs +++ b/rust/agama-server/src/network/model.rs @@ -180,7 +180,7 @@ impl NetworkState { } pub fn remove_device(&mut self, name: &str) -> Result<(), NetworkStateError> { - let Some(position) = self.devices.iter().position(|d| &d.name == name) else { + let Some(position) = self.devices.iter().position(|d| d.name == name) else { return Err(NetworkStateError::UnknownDevice(name.to_string())); }; diff --git a/rust/agama-server/src/network/nm/dbus.rs b/rust/agama-server/src/network/nm/dbus.rs index 86a47e2061..99454c76d3 100644 --- a/rust/agama-server/src/network/nm/dbus.rs +++ b/rust/agama-server/src/network/nm/dbus.rs @@ -155,17 +155,17 @@ pub fn connection_from_dbus(conn: OwnedNestedHash) -> Option { return Some(connection); } - if conn.get(DUMMY_KEY).is_some() { + if conn.contains_key(DUMMY_KEY) { connection.config = ConnectionConfig::Dummy; return Some(connection); }; - if conn.get(LOOPBACK_KEY).is_some() { + if conn.contains_key(LOOPBACK_KEY) { connection.config = ConnectionConfig::Loopback; return Some(connection); }; - if conn.get(ETHERNET_KEY).is_some() { + if conn.contains_key(ETHERNET_KEY) { return Some(connection); }; @@ -240,9 +240,7 @@ pub fn cleanup_dbus_connection(conn: &mut NestedHash) { /// Ancillary function to get the controller for a given interface. pub fn controller_from_dbus(conn: &OwnedNestedHash) -> Option { - let Some(connection) = conn.get("connection") else { - return None; - }; + let connection = conn.get("connection")?; let master: &str = connection.get("master")?.downcast_ref()?; Some(master.to_string()) @@ -424,13 +422,9 @@ fn bridge_config_to_dbus(bridge: &BridgeConfig) -> HashMap<&str, zvariant::Value } fn bridge_config_from_dbus(conn: &OwnedNestedHash) -> Option { - let Some(bridge) = conn.get(BRIDGE_KEY) else { - return None; - }; + let bridge = conn.get(BRIDGE_KEY)?; - let Some(stp) = bridge.get("stp") else { - return None; - }; + let stp = bridge.get("stp")?; let mut bc = BridgeConfig { stp: *stp.downcast_ref::()?, @@ -474,9 +468,7 @@ fn bridge_port_config_to_dbus(bridge_port: &BridgePortConfig) -> HashMap<&str, z } fn bridge_port_config_from_dbus(conn: &OwnedNestedHash) -> Option { - let Some(bridge_port) = conn.get(BRIDGE_PORT_KEY) else { - return None; - }; + let bridge_port = conn.get(BRIDGE_PORT_KEY)?; let mut bpc = BridgePortConfig::default(); @@ -508,9 +500,7 @@ fn infiniband_config_to_dbus(config: &InfinibandConfig) -> HashMap<&str, zvarian } fn infiniband_config_from_dbus(conn: &OwnedNestedHash) -> Option { - let Some(infiniband) = conn.get(INFINIBAND_KEY) else { - return None; - }; + let infiniband = conn.get(INFINIBAND_KEY)?; let mut infiniband_config = InfinibandConfig::default(); @@ -551,9 +541,7 @@ fn match_config_to_dbus(match_config: &MatchConfig) -> HashMap<&str, zvariant::V } fn base_connection_from_dbus(conn: &OwnedNestedHash) -> Option { - let Some(connection) = conn.get("connection") else { - return None; - }; + let connection = conn.get("connection")?; let id: &str = connection.get("id")?.downcast_ref()?; let uuid: &str = connection.get("uuid")?.downcast_ref()?; @@ -751,9 +739,7 @@ fn nameservers_from_dbus(dns_data: &OwnedValue) -> Option> { } fn wireless_config_from_dbus(conn: &OwnedNestedHash) -> Option { - let Some(wireless) = conn.get(WIRELESS_KEY) else { - return None; - }; + let wireless = conn.get(WIRELESS_KEY)?; let mode: &str = wireless.get("mode")?.downcast_ref()?; let ssid = wireless.get("ssid")?; @@ -832,9 +818,7 @@ fn wireless_config_from_dbus(conn: &OwnedNestedHash) -> Option { } fn bond_config_from_dbus(conn: &OwnedNestedHash) -> Option { - let Some(bond) = conn.get(BOND_KEY) else { - return None; - }; + let bond = conn.get(BOND_KEY)?; let dict: &zvariant::Dict = bond.get("options")?.downcast_ref()?; @@ -864,18 +848,12 @@ fn vlan_config_to_dbus(cfg: &VlanConfig) -> NestedHash { } fn vlan_config_from_dbus(conn: &OwnedNestedHash) -> Option { - let Some(vlan) = conn.get(VLAN_KEY) else { - return None; - }; + let vlan = conn.get(VLAN_KEY)?; - let Some(id) = vlan.get("id") else { - return None; - }; + let id = vlan.get("id")?; let id = id.downcast_ref::()?; - let Some(parent) = vlan.get("parent") else { - return None; - }; + let parent = vlan.get("parent")?; let parent: &str = parent.downcast_ref()?; let protocol = match vlan.get("protocol") { @@ -1152,7 +1130,7 @@ mod test { ]); let infiniband_section = HashMap::from([ - ("p-key".to_string(), Value::new(0x8001 as i32).to_owned()), + ("p-key".to_string(), Value::new(0x8001_i32).to_owned()), ("parent".to_string(), Value::new("ib0").to_owned()), ( "transport-mode".to_string(), diff --git a/rust/agama-server/src/network/nm/watcher.rs b/rust/agama-server/src/network/nm/watcher.rs index df7222bdd2..2b24aade5c 100644 --- a/rust/agama-server/src/network/nm/watcher.rs +++ b/rust/agama-server/src/network/nm/watcher.rs @@ -214,8 +214,8 @@ impl<'a> ActionDispatcher<'a> { connection: &zbus::Connection, proxy: DeviceProxy<'_>, ) -> Result { - let builder = DeviceFromProxyBuilder::new(&connection, &proxy); - Ok(builder.build().await?) + let builder = DeviceFromProxyBuilder::new(connection, &proxy); + builder.build().await } } @@ -255,7 +255,6 @@ impl DeviceChangedStream { let interfaces: Vec = args .interfaces_and_properties() .keys() - .into_iter() .map(|i| i.to_string()) .collect(); @@ -364,7 +363,7 @@ async fn build_added_and_removed_stream( .path("/org/freedesktop")? .interface("org.freedesktop.DBus.ObjectManager")? .build(); - let stream = MessageStream::for_match_rule(rule, &connection, Some(1)).await?; + let stream = MessageStream::for_match_rule(rule, connection, Some(1)).await?; Ok(stream) } @@ -379,7 +378,7 @@ async fn build_properties_changed_stream( .interface("org.freedesktop.DBus.Properties")? .member("PropertiesChanged")? .build(); - let stream = MessageStream::for_match_rule(rule, &connection, Some(1)).await?; + let stream = MessageStream::for_match_rule(rule, connection, Some(1)).await?; Ok(stream) } @@ -433,7 +432,7 @@ impl<'a> ProxiesRegistry<'a> { /// /// * `path`: D-Bus object path. pub fn remove_device(&mut self, path: &OwnedObjectPath) -> Option<(String, DeviceProxy)> { - self.devices.remove(&path) + self.devices.remove(path) } //// Updates a device name. @@ -453,10 +452,10 @@ impl<'a> ProxiesRegistry<'a> { &self, ip4_config_path: &OwnedObjectPath, ) -> Option<&(String, DeviceProxy<'_>)> { - for (_, device) in &self.devices { + for device in self.devices.values() { if let Ok(path) = device.1.ip4_config().await { if path == *ip4_config_path { - return Some(&device); + return Some(device); } } } @@ -470,10 +469,10 @@ impl<'a> ProxiesRegistry<'a> { &self, ip4_config_path: &OwnedObjectPath, ) -> Option<&(String, DeviceProxy<'_>)> { - for (_, device) in &self.devices { + for device in self.devices.values() { if let Ok(path) = device.1.ip4_config().await { if path == *ip4_config_path { - return Some(&device); + return Some(device); } } } diff --git a/rust/agama-server/src/storage/web/iscsi/stream.rs b/rust/agama-server/src/storage/web/iscsi/stream.rs index 4a235590aa..29e2c579db 100644 --- a/rust/agama-server/src/storage/web/iscsi/stream.rs +++ b/rust/agama-server/src/storage/web/iscsi/stream.rs @@ -50,7 +50,7 @@ impl ISCSINodeStream { let (tx, rx) = unbounded_channel(); let mut stream = DBusObjectChangesStream::new( - &dbus, + dbus, &ObjectPath::from_str_unchecked(MANAGER_PATH), &ObjectPath::from_str_unchecked(NAMESPACE), "org.opensuse.Agama.Storage1.ISCSI.Node", @@ -84,8 +84,8 @@ impl ISCSINodeStream { path: &OwnedObjectPath, values: &HashMap, ) -> Result<&'a ISCSINode, ServiceError> { - let node = cache.find_or_create(&path); - node.id = extract_id_from_path(&path)?; + let node = cache.find_or_create(path); + node.id = extract_id_from_path(path)?; property_from_dbus!(node, target, "Target", values, str); property_from_dbus!(node, address, "Address", values, str); property_from_dbus!(node, interface, "Interface", values, str); @@ -100,7 +100,7 @@ impl ISCSINodeStream { path: &OwnedObjectPath, ) -> Result { cache - .remove(&path) + .remove(path) .ok_or_else(|| ISCSINodeStreamError::UnknownNode(path.clone())) } @@ -110,11 +110,11 @@ impl ISCSINodeStream { ) -> Result { match change { DBusObjectChange::Added(path, values) => { - let node = Self::update_node(cache, path, &values)?; + let node = Self::update_node(cache, path, values)?; Ok(Event::ISCSINodeAdded { node: node.clone() }) } DBusObjectChange::Changed(path, updated) => { - let node = Self::update_node(cache, path, &updated)?; + let node = Self::update_node(cache, path, updated)?; Ok(Event::ISCSINodeChanged { node: node.clone() }) } DBusObjectChange::Removed(path) => { diff --git a/rust/agama-server/src/web/auth.rs b/rust/agama-server/src/web/auth.rs index 36fad9a04e..06f807e883 100644 --- a/rust/agama-server/src/web/auth.rs +++ b/rust/agama-server/src/web/auth.rs @@ -57,14 +57,19 @@ impl TokenClaims { /// * `secret`: secret to decode the token. pub fn from_token(token: &str, secret: &str) -> Result { let decoding = DecodingKey::from_secret(secret.as_ref()); - let token_data = jsonwebtoken::decode(&token, &decoding, &Validation::default())?; + let token_data = jsonwebtoken::decode(token, &decoding, &Validation::default())?; Ok(token_data.claims) } } impl Default for TokenClaims { fn default() -> Self { - let exp = Utc::now() + Duration::days(1); + let mut exp = Utc::now(); + + if let Some(days) = Duration::try_days(1) { + exp += days; + } + Self { exp: exp.timestamp(), } diff --git a/rust/agama-server/tests/network_service.rs b/rust/agama-server/tests/network_service.rs index 26860de626..7507bef1f8 100644 --- a/rust/agama-server/tests/network_service.rs +++ b/rust/agama-server/tests/network_service.rs @@ -38,7 +38,7 @@ async fn build_state() -> NetworkState { async fn build_service(state: NetworkState) -> Result { let adapter = NetworkTestAdapter(state); let (tx, _rx) = broadcast::channel(16); - Ok(network_service(adapter, tx).await?) + network_service(adapter, tx).await } #[derive(Default)] From d7202e826fc88e5c4be334ff37140320bc7a9c58 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Iv=C3=A1n=20L=C3=B3pez=20Gonz=C3=A1lez?= Date: Fri, 17 May 2024 10:57:46 +0100 Subject: [PATCH 2/2] rust: Fix format (cargo fmt) --- rust/agama-lib/src/dbus.rs | 6 ++---- rust/agama-lib/src/storage/model.rs | 14 ++++++-------- rust/agama-server/src/l10n/dbus.rs | 18 +++++++++--------- rust/agama-server/src/l10n/locale.rs | 3 +-- 4 files changed, 18 insertions(+), 23 deletions(-) diff --git a/rust/agama-lib/src/dbus.rs b/rust/agama-lib/src/dbus.rs index 145f412c78..6ff2e6eab4 100644 --- a/rust/agama-lib/src/dbus.rs +++ b/rust/agama-lib/src/dbus.rs @@ -102,16 +102,14 @@ mod tests { #[test] fn test_get_property_wrong_type() { - let data: HashMap = - HashMap::from([("Id".to_string(), 1_u8.into())]); + let data: HashMap = HashMap::from([("Id".to_string(), 1_u8.into())]); let result: Result = get_property(&data, "Id"); assert_eq!(result, Err(zvariant::Error::IncorrectType)); } #[test] fn test_get_optional_property() { - let data: HashMap = - HashMap::from([("Id".to_string(), 1_u8.into())]); + let data: HashMap = HashMap::from([("Id".to_string(), 1_u8.into())]); let id: Option = get_optional_property(&data, "Id").unwrap(); assert_eq!(id, Some(1)); diff --git a/rust/agama-lib/src/storage/model.rs b/rust/agama-lib/src/storage/model.rs index 423f71753c..67e586bc54 100644 --- a/rust/agama-lib/src/storage/model.rs +++ b/rust/agama-lib/src/storage/model.rs @@ -18,10 +18,9 @@ impl TryFrom for DeviceSid { type Error = zbus::zvariant::Error; fn try_from(value: i32) -> Result { - u32::try_from(value).map(|v| v.into()).map_err(|_| Self::Error::Message(format!( - "Cannot convert sid from {}", - value - ))) + u32::try_from(value) + .map(|v| v.into()) + .map_err(|_| Self::Error::Message(format!("Cannot convert sid from {}", value))) } } @@ -66,10 +65,9 @@ impl TryFrom for DeviceSize { type Error = zbus::zvariant::Error; fn try_from(value: i64) -> Result { - u64::try_from(value).map(|v| v.into()).map_err(|_| Self::Error::Message(format!( - "Cannot convert size from {}", - value - ))) + u64::try_from(value) + .map(|v| v.into()) + .map_err(|_| Self::Error::Message(format!("Cannot convert size from {}", value))) } } diff --git a/rust/agama-server/src/l10n/dbus.rs b/rust/agama-server/src/l10n/dbus.rs index 8ed49fd7c6..0c14145d06 100644 --- a/rust/agama-server/src/l10n/dbus.rs +++ b/rust/agama-server/src/l10n/dbus.rs @@ -25,9 +25,9 @@ impl L10nInterface { "The locales list cannot be empty".to_string(), )); } - backend.set_locales(&locales).map_err(|e| { - zbus::fdo::Error::Failed(format!("Could not set the locales: {}", e)) - })?; + backend + .set_locales(&locales) + .map_err(|e| zbus::fdo::Error::Failed(format!("Could not set the locales: {}", e)))?; Ok(()) } @@ -59,9 +59,9 @@ impl L10nInterface { .parse() .map_err(|_e| zbus::fdo::Error::InvalidArgs("Cannot parse keymap ID".to_string()))?; - backend.set_keymap(keymap_id).map_err(|e| { - zbus::fdo::Error::Failed(format!("Could not set the keymap: {}", e)) - })?; + backend + .set_keymap(keymap_id) + .map_err(|e| zbus::fdo::Error::Failed(format!("Could not set the keymap: {}", e)))?; Ok(()) } @@ -76,9 +76,9 @@ impl L10nInterface { pub fn set_timezone(&mut self, timezone: &str) -> Result<(), zbus::fdo::Error> { let mut backend = self.backend.write().unwrap(); - backend.set_timezone(timezone).map_err(|e| { - zbus::fdo::Error::Failed(format!("Could not set the timezone: {}", e)) - })?; + backend + .set_timezone(timezone) + .map_err(|e| zbus::fdo::Error::Failed(format!("Could not set the timezone: {}", e)))?; Ok(()) } diff --git a/rust/agama-server/src/l10n/locale.rs b/rust/agama-server/src/l10n/locale.rs index e29fc23dcb..4ea85bc03d 100644 --- a/rust/agama-server/src/l10n/locale.rs +++ b/rust/agama-server/src/l10n/locale.rs @@ -108,8 +108,7 @@ impl LocalesDatabase { fn get_locales_list() -> Result, Error> { const LOCALES_LIST_PATH: &str = "/etc/agama.d/locales"; - let locales = fs::read_to_string(LOCALES_LIST_PATH) - .map(Self::get_locales_from_string); + let locales = fs::read_to_string(LOCALES_LIST_PATH).map(Self::get_locales_from_string); if let Ok(locales) = locales { if !locales.is_empty() {