diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml new file mode 100644 index 000000000..00b36ac2f --- /dev/null +++ b/.github/workflows/CI.yml @@ -0,0 +1,24 @@ +on: + push: + branches: [master] + pull_request: + +name: Continuous integration + +jobs: + + fmt: + name: Rustfmt + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions-rs/toolchain@v1 + with: + toolchain: nightly + override: true + profile: minimal + components: rustfmt + - uses: actions-rs/cargo@v1 + with: + command: fmt + args: --all -- --check diff --git a/gtk/src/errors.rs b/gtk/src/errors.rs index e573ad94b..afcbf4a06 100644 --- a/gtk/src/errors.rs +++ b/gtk/src/errors.rs @@ -22,7 +22,7 @@ pub enum UiError { } impl UiError { - pub fn iter_sources(&self) -> ErrorIter<'_> { ErrorIter { current: self.source() } } + pub fn iter_sources(&self) -> ErrorIter { ErrorIter { current: self.source() } } } #[derive(Debug, Error)] diff --git a/gtk/src/events/background/mod.rs b/gtk/src/events/background/mod.rs index 725ce4c25..5c43af7d3 100644 --- a/gtk/src/events/background/mod.rs +++ b/gtk/src/events/background/mod.rs @@ -35,7 +35,7 @@ pub fn run( ) { let send: &dyn Fn(UiEvent) = &send; if let Ok(ref mut client) = Client::new() { - info!("Checking for updates to daemon"); + log::info!("Checking for updates to daemon"); if client.update_and_restart().unwrap_or(false) { send(UiEvent::Updating); let file = std::path::Path::new(pop_upgrade::RESTART_SCHEDULED); diff --git a/gtk/src/events/background/release.rs b/gtk/src/events/background/release.rs index f694b5fde..3e08f4319 100644 --- a/gtk/src/events/background/release.rs +++ b/gtk/src/events/background/release.rs @@ -9,7 +9,7 @@ use pop_upgrade::{ }; pub fn download(client: &Client, send: &dyn Fn(UiEvent), info: ReleaseInfo) { - info!("downloading updates for {}", info.next); + log::info!("downloading updates for {}", info.next); if !update(client, send) { return; } @@ -110,7 +110,7 @@ pub fn download(client: &Client, send: &dyn Fn(UiEvent), info: ReleaseInfo) { } pub fn update(client: &Client, send: &dyn Fn(UiEvent)) -> bool { - info!("checking if updates are required"); + log::info!("checking if updates are required"); let updates = match client.fetch_updates(Vec::new(), false) { Ok(updates) => updates, Err(why) => { diff --git a/gtk/src/events/background/scan.rs b/gtk/src/events/background/scan.rs index d9056fc47..6065cdcf0 100644 --- a/gtk/src/events/background/scan.rs +++ b/gtk/src/events/background/scan.rs @@ -33,7 +33,7 @@ pub fn scan(client: &Client, send: &dyn Fn(UiEvent)) { Ok(info) => { is_lts = info.is_lts; if devel || info.build >= 0 { - info!("upgrade from {} to {} is available", info.current, info.next); + log::info!("upgrade from {} to {} is available", info.current, info.next); let upgrade_text = Cow::Owned(if reboot_ready { format!("Pop!_OS is ready to upgrade to {}", info.next) @@ -54,7 +54,7 @@ pub fn scan(client: &Client, send: &dyn Fn(UiEvent)) { } Err(why) => { status_failed = true; - error!("failed to check for updates: {}", why); + log::error!("failed to check for updates: {}", why); Cow::Borrowed("Failed to check for updates") } } diff --git a/gtk/src/events/mod.rs b/gtk/src/events/mod.rs index 886f0bba5..a97bd7a8b 100644 --- a/gtk/src/events/mod.rs +++ b/gtk/src/events/mod.rs @@ -173,7 +173,7 @@ pub fn attach(gui_receiver: glib::Receiver, widgets: EventWidgets, mut } UiEvent::Completed(CompletedEvent::Recovery) => { - info!("successfully upgraded recovery partition"); + log::info!("successfully upgraded recovery partition"); } UiEvent::Completed(CompletedEvent::Refresh) => reboot(), @@ -201,14 +201,14 @@ pub fn attach(gui_receiver: glib::Receiver, widgets: EventWidgets, mut UiEvent::ReleaseUpgradeDialog => release_upgrade_dialog(&mut state, &widgets), UiEvent::Dismissed(dismissed) => { - info!("{} release", if dismissed { "dismissed" } else { "un-dismissed" }); + log::info!("{} release", if dismissed { "dismissed" } else { "un-dismissed" }); if let Some(dismisser) = state.dismisser.as_mut() { dismisser.set_dismissed(dismissed); } } UiEvent::StatusChanged(from, to, why) => { - warn!("status changed from {} to {}: {}", from, to, why); + log::warn!("status changed from {} to {}: {}", from, to, why); let _ = state.sender.send(BackgroundEvent::GetStatus(from)); } @@ -267,7 +267,7 @@ fn connect_upgrade(state: &mut State, widgets: &EventWidgets, is_lts: bool, rebo } } Err(why) => { - error!("failed to fetch EOL date: {}", why); + log::error!("failed to fetch EOL date: {}", why); None } }; @@ -375,7 +375,7 @@ fn error(state: &mut State, widgets: &EventWidgets, why: UiError) { .as_str(), ); - error!("{}", error_message); + log::error!("{}", error_message); if let UiError::Dismiss(dismissed, _) = why { if let Some(dismisser) = state.dismisser.as_mut() { diff --git a/rustfmt.toml b/rustfmt.toml index 44c3d2851..51fab0cd9 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -12,6 +12,6 @@ reorder_impl_items = true struct_field_align_threshold = 30 use_field_init_shorthand = true wrap_comments = true -merge_imports = true +imports_granularity = "Crate" force_multiline_blocks = false use_small_heuristics = "Max" diff --git a/src/checksum.rs b/src/checksum.rs index 2cad3dbfd..421719698 100644 --- a/src/checksum.rs +++ b/src/checksum.rs @@ -18,7 +18,7 @@ pub enum ValidateError { } pub async fn validate_checksum(file: &mut File, checksum: &str) -> Result<(), ValidateError> { - info!("validating checksum of downloaded ISO"); + log::info!("validating checksum of downloaded ISO"); let expected = <[u8; 32]>::from_hex(checksum) .map(GenericArray::from) .map_err(|_| ValidateError::InvalidInput)?; diff --git a/src/cli/mod.rs b/src/cli.rs similarity index 96% rename from src/cli/mod.rs rename to src/cli.rs index 7503c4bda..2ac66ac25 100644 --- a/src/cli/mod.rs +++ b/src/cli.rs @@ -2,10 +2,10 @@ mod colors; use self::colors::*; use crate::notify::notify; - use apt_cmd::AptUpgradeEvent; use chrono::{TimeZone, Utc}; use clap::ArgMatches; +use fomat_macros::{fomat, pintln}; use num_traits::FromPrimitive; use pop_upgrade::{ client, @@ -38,7 +38,7 @@ const UPGRADE_RESULT_STR: &str = "Release upgrade status"; const UPGRADE_RESULT_SUCCESS: &str = "systems are go for launch: reboot now"; const UPGRADE_RESULT_ERROR: &str = "release upgrade aborted"; -#[derive(Shrinkwrap)] +#[derive(shrinkwraprs::Shrinkwrap)] pub struct Client(client::Client); impl Client { @@ -235,7 +235,7 @@ impl Client { /// Check if the release has been dismissed by timestamp, or can be. fn dismiss_by_timestamp(&self, next: &str) -> Result { if !Path::new(INSTALL_DATE).exists() && installed_after_release(next) { - info!("dismissing notification for the latest release automatically"); + log::info!("dismissing notification for the latest release automatically"); let _ = self.dismiss_notification(DismissEvent::ByTimestamp)?; Ok(true) } else { @@ -294,7 +294,7 @@ impl Client { if let Ok(event) = AptUpgradeEvent::from_dbus_map(event.into_iter()) { write_apt_event(event); } else { - error!("failed to unpack the upgrade event"); + log::error!("failed to unpack the upgrade event"); } } _ => (), @@ -412,7 +412,9 @@ impl Client { client::Signal::PackageUpgrade(event) => { match AptUpgradeEvent::from_dbus_map(event.clone().into_iter()) { Ok(event) => write_apt_event(event), - Err(()) => error!("failed to unpack the upgrade event: {:?}", event), + Err(()) => { + log::error!("failed to unpack the upgrade event: {:?}", event) + } } } client::Signal::ReleaseResult(status) => { @@ -481,18 +483,19 @@ fn installed_after_release(next: &str) -> bool { Ok(codename) => { return codename.release_timestamp() < install_time as u64 } - Err(()) => error!("version {} is invalid", next), + Err(()) => log::error!("version {} is invalid", next), } } - _ => error!( + _ => log::error!( "major ({}) and minor({}) version failed to parse as u8", - major, minor + major, + minor ), } } - None => error!("version {} is invalid", next), + None => log::error!("version {} is invalid", next), }, - Err(why) => error!("failed to get install time: {}", why), + Err(why) => log::error!("failed to get install time: {}", why), } false @@ -525,7 +528,7 @@ fn notification_message(current: &str, next: &str) -> (String, String) { } EolStatus::Ok => (), }, - Err(why) => error!("failed to fetch EOL date: {}", why), + Err(why) => log::error!("failed to fetch EOL date: {}", why), } ("Upgrade Available".into(), fomat!("Pop!_OS " (next) " is available to download")) diff --git a/src/client/mod.rs b/src/client.rs similarity index 100% rename from src/client/mod.rs rename to src/client.rs diff --git a/src/daemon/mod.rs b/src/daemon.rs similarity index 90% rename from src/daemon/mod.rs rename to src/daemon.rs index c3ec1bae7..1774fbbbb 100644 --- a/src/daemon/mod.rs +++ b/src/daemon.rs @@ -33,7 +33,9 @@ use dbus::{ tree::{Factory, Signal}, BusType, Connection, Message, NameFlag, }; +use enclose::enclose; use flume::{bounded, Receiver, Sender}; +use fomat_macros::fomat; use futures::prelude::*; use logind_dbus::LoginManager; use num_traits::FromPrimitive; @@ -67,9 +69,9 @@ pub enum FgEvent { } pub struct LastKnown { - fetch: Result<(), ReleaseError>, + fetch: Result<(), ReleaseError>, recovery_upgrade: Result<(), RecoveryError>, - release_upgrade: Result<(), ReleaseError>, + release_upgrade: Result<(), ReleaseError>, } impl Default for LastKnown { @@ -80,20 +82,20 @@ impl Default for LastKnown { pub struct ReleaseUpgradeState { action: release::UpgradeMethod, - from: Box, - to: Box, + from: Box, + to: Box, } pub struct Daemon { - event_tx: Sender, - fg_rx: Receiver, - dbus_rx: Receiver, - connection: Arc, - status: Arc>, - sub_status: Arc>, - fetching_state: Arc>, - cancel: Arc, - last_known: LastKnown, + event_tx: Sender, + fg_rx: Receiver, + dbus_rx: Receiver, + connection: Arc, + status: Arc>, + sub_status: Arc>, + fetching_state: Arc>, + cancel: Arc, + last_known: LastKnown, release_upgrade: Option, perform_upgrade: bool, } @@ -138,7 +140,7 @@ impl Daemon { let mut logind = match LoginManager::new() { Ok(logind) => Some(logind), Err(why) => { - error!("failed to connect to logind: {}", why); + log::error!("failed to connect to logind: {}", why); None } }; @@ -174,7 +176,7 @@ impl Daemon { { Ok(lock) => Some(lock), Err(why) => { - error!("failed to inhibit suspension: {}", why); + log::error!("failed to inhibit suspension: {}", why); None } } @@ -189,12 +191,12 @@ impl Daemon { } Event::FetchUpdates { apt_uris, download_only } => { - info!("fetching packages for {:?}", apt_uris); + log::info!("fetching packages for {:?}", apt_uris); let npackages = apt_uris.len() as u32; prog_state.store((0, u64::from(npackages)), Ordering::SeqCst); let result = runtime.apt_fetch(apt_uris, fetch_closure.clone()).await; - info!("fetched"); + log::info!("fetched"); prog_state.store((0, 0), Ordering::SeqCst); @@ -205,7 +207,7 @@ impl Daemon { Ok(()) } else { (async { - info!("performing upgrade"); + log::info!("performing upgrade"); let (mut child, events) = AptGet::new() .noninteractive() .allow_downgrades() @@ -220,7 +222,7 @@ impl Daemon { let _ = dbus_tx.send(SignalEvent::Upgrade(event)); } - info!("completed apt upgrade"); + log::info!("completed apt upgrade"); child.status().await.map_result().map_err(ReleaseError::Upgrade) }).await @@ -233,7 +235,7 @@ impl Daemon { } Event::PackageUpgrade => { - info!("upgrading packages"); + log::info!("upgrading packages"); let _ = runtime.package_upgrade(|event| { let _ = dbus_tx.send(SignalEvent::Upgrade(event)); }); @@ -241,7 +243,7 @@ impl Daemon { Event::RecoveryUpgrade(action) => { processing = true; - info!("attempting recovery upgrade with {:?}", action); + log::info!("attempting recovery upgrade with {:?}", action); let result = recovery::recovery( &|| (*cancel_process)(), &action, @@ -262,7 +264,7 @@ impl Daemon { } Event::ReleaseUpgrade { how, from, to } => { - info!( + log::info!( "attempting release upgrade, using a {}", <&'static str>::from(how) ); @@ -296,7 +298,7 @@ impl Daemon { cancel.store(false, Ordering::SeqCst); status.store(DaemonStatus::Inactive, Ordering::SeqCst); - info!("event processed"); + log::info!("event processed"); } })), ); @@ -317,7 +319,7 @@ impl Daemon { } pub fn init() -> Result<(), DaemonError> { - info!("initializing daemon"); + log::info!("initializing daemon"); fs::create_dir_all(crate::VAR_LIB_DIR) .map_err(|why| DaemonError::VarLibDirectory(crate::VAR_LIB_DIR, why))?; @@ -438,7 +440,7 @@ impl Daemon { connection.add_handler(tree); - info!("daemon registered -- listening for new events"); + log::info!("daemon registered -- listening for new events"); async_io::block_on(async move { release::cleanup().await; @@ -463,17 +465,17 @@ impl Daemon { } if let Some(status) = sighandler::status() { - info!("received a '{}' signal", status); + log::info!("received a '{}' signal", status); use sighandler::Signal::*; match status { Terminate => { - info!("terminating daemon"); + log::info!("terminating daemon"); break Ok(()); } TermStop => { - info!("stopping daemon"); + log::info!("stopping daemon"); break Ok(()); } _ => (), @@ -484,7 +486,7 @@ impl Daemon { match fg_event { FgEvent::SetUpgradeState(result, action, from, to) => { if result.is_ok() { - info!("setting release upgrade state"); + log::info!("setting release upgrade state"); let state = ReleaseUpgradeState { action, from, to }; daemon.borrow_mut().release_upgrade = Some(state); } @@ -502,7 +504,7 @@ impl Daemon { | SignalEvent::RecoveryUpgradeEvent(_) | SignalEvent::RecoveryUpgradeResult(_) | SignalEvent::ReleaseUpgradeEvent(_) - | SignalEvent::Upgrade(_) => info!("{}", dbus_event), + | SignalEvent::Upgrade(_) => log::info!("{}", dbus_event), _ => (), } @@ -578,7 +580,7 @@ impl Daemon { additional_packages: &'a [String], download_only: bool, ) -> anyhow::Result<(bool, u32)> { - info!("fetching updates for the system, including {:?}", additional_packages); + log::info!("fetching updates for the system, including {:?}", additional_packages); let mut borrows = Vec::with_capacity(additional_packages.len()); borrows.extend(additional_packages.into_iter().map(String::as_str)); @@ -586,7 +588,7 @@ impl Daemon { let apt_uris = crate::fetch::apt::fetch_uris(Some(&borrows)).await?; if apt_uris.is_empty() { - info!("no updates available to fetch"); + log::info!("no updates available to fetch"); return Ok((false, 0)); } @@ -598,20 +600,20 @@ impl Daemon { } fn package_upgrade(&mut self) -> anyhow::Result<()> { - info!("upgrading packages for the release"); + log::info!("upgrading packages for the release"); self.submit_event(Event::PackageUpgrade)?; Ok(()) } fn cancel(&mut self) { - info!("cancelling a process which is in progress"); + log::info!("cancelling a process which is in progress"); self.cancel.store(true, Ordering::SeqCst); } fn recovery_upgrade_file(&mut self, path: &str) -> anyhow::Result<()> { - info!("using {} to upgrade the recovery partition", path); + log::info!("using {} to upgrade the recovery partition", path); let event = Event::RecoveryUpgrade(RecoveryUpgradeMethod::FromFile(PathBuf::from(path))); @@ -624,37 +626,37 @@ impl Daemon { arch: &str, flags: u8, ) -> anyhow::Result<()> { - info!("upgrading the recovery partition to {}-{}", version, arch); + log::info!("upgrading the recovery partition to {}-{}", version, arch); let event = Event::RecoveryUpgrade(RecoveryUpgradeMethod::FromRelease { version: if version.is_empty() { None } else { Some(version.into()) }, - arch: if arch.is_empty() { None } else { Some(arch.into()) }, - flags: RecoveryReleaseFlags::from_bits_truncate(flags), + arch: if arch.is_empty() { None } else { Some(arch.into()) }, + flags: RecoveryReleaseFlags::from_bits_truncate(flags), }); self.submit_event(event) } fn recovery_version(&mut self) -> Result { - info!("checking recovery version"); + log::info!("checking recovery version"); let version = crate::recovery::version().map_err(|ref why| format_error(why))?; - info!("{:?}", version); + log::info!("{:?}", version); Ok(version) } fn refresh_os(&mut self, flag: RefreshOp) -> Result { - info!("preparing to refresh OS"); + log::info!("preparing to refresh OS"); crate::release::refresh_os(flag).map_err(|ref why| format_error(why)) } fn release_check(&self, development: bool) -> Result { - info!("performing a release check"); + log::info!("performing a release check"); let status = release::check::next(development).map_err(|ref why| format_error(why))?; let mut buffer = String::new(); - info!( + log::info!( "Release {{ current: \"{}\", lts: \"{}\", next: \"{}\", available: {} }}", status.current, status.is_lts(), @@ -666,7 +668,7 @@ impl Daemon { } fn release_upgrade(&mut self, how: u8, from: &str, to: &str) -> anyhow::Result<()> { - info!("upgrading release from {} to {}, with {}", from, to, how); + log::info!("upgrading release from {} to {}, with {}", from, to, how); let how = ReleaseUpgradeMethod::from_u8(how) .context("provided upgrade `how` value is out of range")?; @@ -694,7 +696,7 @@ impl Daemon { } async fn reset(&mut self) -> Result<(), String> { - info!("resetting daemon"); + log::info!("resetting daemon"); self.status.store(DaemonStatus::Inactive, Ordering::SeqCst); self.sub_status.store(0, Ordering::SeqCst); @@ -708,7 +710,7 @@ impl Daemon { fn send_signal_message(connection: &Connection, message: Message) { if let Err(()) = connection.send(message) { - error!("failed to send dbus signal message"); + log::error!("failed to send dbus signal message"); } } @@ -734,7 +736,7 @@ impl Daemon { let desc = "too many requests sent -- refusing additional requests"; if self.event_tx.is_full() { - warn!("{}", desc); + log::warn!("{}", desc); return Err(anyhow::anyhow!("{}", desc)); } @@ -743,12 +745,14 @@ impl Daemon { } async fn update_and_restart(&mut self) -> u8 { - info!("updating apt sources"); + log::info!("updating apt sources"); let _ = AptGet::new().update().await; if let Ok(true) = upgrade_required().await { if async_fs::File::create(RESTART_SCHEDULED).await.is_ok() { - info!("installing latest version of `pop-upgrade`, which will restart the daemon"); + log::info!( + "installing latest version of `pop-upgrade`, which will restart the daemon" + ); self.perform_upgrade = true; return 1; } diff --git a/src/daemon/dbus_helper.rs b/src/daemon/dbus_helper.rs index c1273433a..82e98f5ed 100644 --- a/src/daemon/dbus_helper.rs +++ b/src/daemon/dbus_helper.rs @@ -26,7 +26,7 @@ impl<'a> DbusFactory<'a> { Ok(vec![mret]) } Err(why) => { - error!("{}", why); + log::error!("{}", why); Err(MethodErr::failed(&why)) } }); diff --git a/src/daemon/error.rs b/src/daemon/error.rs index 3b87a1f7b..89d4ff0e4 100644 --- a/src/daemon/error.rs +++ b/src/daemon/error.rs @@ -1,4 +1,3 @@ -use dbus; use std::io; use thiserror::Error; diff --git a/src/daemon/methods.rs b/src/daemon/methods.rs index cc11bcfdd..8b4f5bd03 100644 --- a/src/daemon/methods.rs +++ b/src/daemon/methods.rs @@ -9,6 +9,7 @@ use dbus::{ }; use crate::misc::format_error; +use num_derive::FromPrimitive; use num_traits::FromPrimitive; use std::{cell::RefCell, collections::HashMap, rc::Rc, sync::atomic::Ordering}; @@ -213,7 +214,7 @@ pub fn refresh_os(daemon: Rc>, dbus_factory: &DbusFactory) -> Me _ => RefreshOp::Status, })?; - info!("responding with value of {}", value); + log::info!("responding with value of {}", value); Ok(vec![value.into()]) }); diff --git a/src/daemon/status.rs b/src/daemon/status.rs index eb1c0f38a..1a7235d89 100644 --- a/src/daemon/status.rs +++ b/src/daemon/status.rs @@ -1,3 +1,4 @@ +use num_derive::FromPrimitive; use std::fmt::{self, Display}; #[repr(u8)] diff --git a/src/external.rs b/src/external.rs index 34309c221..0bebf4b2a 100644 --- a/src/external.rs +++ b/src/external.rs @@ -1,9 +1,10 @@ use async_process::{Command, Stdio}; +use cascade::cascade; use futures::{io::BufReader, prelude::*}; use std::{io, path::Path}; pub async fn findmnt_uuid>(path: P) -> io::Result { - let mut cmd = cascade::cascade! { + let mut cmd = cascade! { Command::new("findmnt"); ..stdout(Stdio::piped()); ..args(&["-n", "-o", "UUID"]); diff --git a/src/fetch.rs b/src/fetch.rs new file mode 100644 index 000000000..502f1b666 --- /dev/null +++ b/src/fetch.rs @@ -0,0 +1,35 @@ +pub mod apt { + use anyhow::Context; + use apt_cmd::{lock::apt_lock_wait, request::Request as AptRequest, AptGet}; + use std::collections::HashSet; + + pub async fn fetch_uris(packages: Option<&[&str]>) -> anyhow::Result> { + apt_lock_wait().await; + let mut uris = AptGet::new() + .noninteractive() + .fetch_uris(&["full-upgrade"]) + .await + .context("failed to exec `apt-get full-upgrade --print-uris`")? + .context("failed to fetch package URIs from apt-get full-upgrade")?; + + if let Some(packages) = packages { + apt_lock_wait().await; + let install_uris = AptGet::new() + .noninteractive() + .fetch_uris(&{ + let mut args = vec!["install"]; + args.extend_from_slice(packages); + args + }) + .await + .context("failed to exec `apt-get install --print-uris`")? + .context("failed to fetch package URIs from `apt-get install`")?; + + for uri in install_uris { + uris.insert(uri); + } + } + + Ok(uris) + } +} diff --git a/src/fetch/apt.rs b/src/fetch/apt.rs deleted file mode 100644 index a2fda5d42..000000000 --- a/src/fetch/apt.rs +++ /dev/null @@ -1,33 +0,0 @@ -use anyhow::Context; -use apt_cmd::{lock::apt_lock_wait, request::Request as AptRequest, AptGet}; -use std::collections::HashSet; - -pub async fn fetch_uris(packages: Option<&[&str]>) -> anyhow::Result> { - apt_lock_wait().await; - let mut uris = AptGet::new() - .noninteractive() - .fetch_uris(&["full-upgrade"]) - .await - .context("failed to exec `apt-get full-upgrade --print-uris`")? - .context("failed to fetch package URIs from apt-get full-upgrade")?; - - if let Some(packages) = packages { - apt_lock_wait().await; - let install_uris = AptGet::new() - .noninteractive() - .fetch_uris(&{ - let mut args = vec!["install"]; - args.extend_from_slice(packages); - args - }) - .await - .context("failed to exec `apt-get install --print-uris`")? - .context("failed to fetch package URIs from `apt-get install`")?; - - for uri in install_uris { - uris.insert(uri); - } - } - - Ok(uris) -} diff --git a/src/fetch/mod.rs b/src/fetch/mod.rs deleted file mode 100644 index 10b337665..000000000 --- a/src/fetch/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod apt; diff --git a/src/gnome_extensions.rs b/src/gnome_extensions.rs index 27bd335c7..0f629bdd4 100644 --- a/src/gnome_extensions.rs +++ b/src/gnome_extensions.rs @@ -8,7 +8,10 @@ pub fn disable() -> anyhow::Result<()> { if user.uid() > uid_min && user.uid() < uid_max { let name = user.name(); - info!("disabling gnome-shell extensions for {}", name.to_str().unwrap_or("")); + log::info!( + "disabling gnome-shell extensions for {}", + name.to_str().unwrap_or("") + ); disable_for(name); } @@ -26,7 +29,7 @@ fn disable_for(user: &std::ffi::OsStr) { .map_result(); if let Err(why) = result { - error!( + log::error!( "failed to disable gnome-shell extensions for {}: {}", user.to_str().unwrap_or(""), why diff --git a/src/lib.rs b/src/lib.rs index 48179a354..b629bd944 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2,27 +2,6 @@ #![allow(clippy::new_ret_no_self)] #![allow(clippy::useless_attribute)] -#[macro_use] -extern crate anyhow; - -#[macro_use] -extern crate bitflags; - -#[macro_use] -extern crate cascade; - -#[macro_use] -extern crate enclose; - -#[macro_use] -extern crate fomat_macros; - -#[macro_use] -extern crate log; - -#[macro_use] -extern crate num_derive; - /// Changelogs for each Pop!_OS release pub mod changelogs; diff --git a/src/main.rs b/src/main.rs index 78025681e..68cdfdca5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,15 +1,3 @@ -#[macro_use] -extern crate fomat_macros; - -#[macro_use] -extern crate log; - -#[macro_use] -extern crate shrinkwraprs; - -#[macro_use] -extern crate thiserror; - mod cli; mod logging; mod notify; @@ -24,7 +12,7 @@ pub mod error { }; use std::io; - #[derive(Debug, Error)] + #[derive(Debug, thiserror::Error)] pub enum Error { #[error("dbus client error")] Client(#[from] ClientError), @@ -42,7 +30,7 @@ pub mod error { Init(#[from] InitError), } - #[derive(Debug, Error)] + #[derive(Debug, thiserror::Error)] pub enum InitError { #[error("failure to create /var/cache/apt/archives/partial directories")] AptCacheDirectories(#[source] io::Error), diff --git a/src/misc.rs b/src/misc.rs index 970f4974e..265303f8d 100644 --- a/src/misc.rs +++ b/src/misc.rs @@ -1,5 +1,6 @@ use anyhow::Context; use async_fs::{copy, File}; +use fomat_macros::fomat; use std::{io, path::Path}; pub async fn create>(path: P) -> io::Result { diff --git a/src/recovery/mod.rs b/src/recovery.rs similarity index 96% rename from src/recovery/mod.rs rename to src/recovery.rs index d48d4da0a..60e6cc4d9 100644 --- a/src/recovery/mod.rs +++ b/src/recovery.rs @@ -1,9 +1,13 @@ mod errors; mod version; +use anyhow::anyhow; use as_result::*; use async_process::Command; +use bitflags::bitflags; +use cascade::cascade; use futures::prelude::*; +use num_derive::FromPrimitive; use std::{ io::SeekFrom, path::{Path, PathBuf}, @@ -124,7 +128,7 @@ async fn fetch_iso<'a, P: AsRef, F: Fn(u64, u64) + 'static + Send + Sync>( recovery_path: P, ) -> RecResult, u16)>> { let recovery_path = recovery_path.as_ref(); - info!("fetching ISO to upgrade recovery partition at {}", recovery_path.display()); + log::info!("fetching ISO to upgrade recovery partition at {}", recovery_path.display()); (*event)(RecoveryEvent::Fetching); if !recovery_path.exists() { @@ -156,7 +160,7 @@ async fn fetch_iso<'a, P: AsRef, F: Fn(u64, u64) + 'static + Send + Sync>( cancellation_check(&cancel)?; if verify(&version, build) { - info!("recovery partition is already upgraded to {}b{}", version, build); + log::info!("recovery partition is already upgraded to {}b{}", version, build); return Ok(None); } @@ -252,7 +256,7 @@ async fn from_remote<'a, F: Fn(u64, u64) + 'static + Send + Sync>( url: &'a str, checksum: &'a str, ) -> RecResult { - info!("downloading ISO from remote at {}", url); + log::info!("downloading ISO from remote at {}", url); let temp = tempdir().map_err(RecoveryError::TempDir)?; let path = temp.path().join("new.iso"); diff --git a/src/release/mod.rs b/src/release.rs similarity index 93% rename from src/release/mod.rs rename to src/release.rs index 923542f93..66aaee7bd 100644 --- a/src/release/mod.rs +++ b/src/release.rs @@ -21,6 +21,7 @@ use apt_cmd::{ }; use envfile::EnvFile; use futures::prelude::*; +use num_derive::FromPrimitive; use std::{ collections::HashSet, convert::TryFrom, @@ -200,9 +201,9 @@ impl DaemonRuntime { .context("failed to fetch package URIs from apt-get")?; for package in packages { - info!("sending package"); + log::info!("sending package"); let _ = fetch_tx.send_async(Arc::new(package)).await; - info!("sending package"); + log::info!("sending package"); } Ok::<(), anyhow::Error>(()) @@ -210,9 +211,9 @@ impl DaemonRuntime { // The system that handles events received from the package-fetcher let receiver = async move { - info!("receiving packages"); + log::info!("receiving packages"); while let Some(event) = events.next().await { - debug!("Package Fetch Event: {:#?}", event); + log::debug!("Package Fetch Event: {:#?}", event); match event.kind { EventKind::Fetching => { @@ -255,7 +256,7 @@ impl DaemonRuntime { let current = codename_from_version(current); let new = codename_from_version(new); - info!("checking if release can be upgraded from {} to {}", current, new); + log::info!("checking if release can be upgraded from {} to {}", current, new); // In case the system abruptly shuts down after this point, create a file to signal // that packages were being fetched for a new release. @@ -276,10 +277,10 @@ impl DaemonRuntime { }; if let Err(why) = update_sources.await { - error!("failed to update sources: {}", why); + log::error!("failed to update sources: {}", why); if let Err(why) = repos::restore(current) { - error!("failed to restore source lists: {:?}", why); + log::error!("failed to restore source lists: {:?}", why); } return Err(why).context("failed to update sources"); @@ -294,7 +295,7 @@ impl DaemonRuntime { let apt_upgrade = || async { apt_lock_wait().await; - info!("upgrading packages"); + log::info!("upgrading packages"); let (mut child, mut upgrade_events) = AptGet::new().noninteractive().allow_downgrades().force().stream_upgrade().await?; @@ -306,18 +307,18 @@ impl DaemonRuntime { }; apt_lock_wait().await; - info!("autoremoving packages"); + log::info!("autoremoving packages"); let _ = AptGet::new().noninteractive().allow_downgrades().force().autoremove().status().await; // If the first upgrade attempt fails, try to dpkg --configure -a and try again. if apt_upgrade().await.is_err() { apt_lock_wait().await; - info!("dpkg --configure -a"); + log::info!("dpkg --configure -a"); let dpkg_configure = Dpkg::new().configure_all().status().await.is_err(); apt_lock_wait().await; - info!("checking for broken packages"); + log::info!("checking for broken packages"); AptGet::new() .noninteractive() .fix_broken() @@ -329,7 +330,7 @@ impl DaemonRuntime { if dpkg_configure { apt_lock_wait().await; - info!("dpkg --configure -a"); + log::info!("dpkg --configure -a"); Dpkg::new().configure_all().status().await.map_err(ReleaseError::DpkgConfigure)? } @@ -337,7 +338,7 @@ impl DaemonRuntime { } apt_lock_wait().await; - info!("autoremoving packages"); + log::info!("autoremoving packages"); let _ = AptGet::new().noninteractive().force().allow_downgrades().autoremove().status().await; @@ -382,14 +383,14 @@ impl DaemonRuntime { let version = codename_from_version(from); - info!("creating backup of source lists"); + log::info!("creating backup of source lists"); repos::backup(version).map_err(ReleaseError::BackupPPAs)?; - info!("disabling third party sources"); + log::info!("disabling third party sources"); repos::disable_third_parties(version).map_err(ReleaseError::DisablePPAs)?; if repos::is_eol(from_codename) && repos::is_old_release(from_codename) { - info!("switching to old-releases repositories"); + log::info!("switching to old-releases repositories"); repos::replace_with_old_releases().map_err(ReleaseError::OldReleaseSwitch)?; } @@ -462,7 +463,7 @@ impl DaemonRuntime { let _ = self.fetch_new_release_packages(logger, fetch, from, to).await?; if let Err(why) = crate::gnome_extensions::disable() { - error!( + log::error!( "failed to disable gnome-shell extensions: {}", crate::misc::format_error(why.as_ref()) ) @@ -482,7 +483,7 @@ impl DaemonRuntime { let processes = match procfs::process::all_processes() { Ok(proc) => proc, Err(why) => { - warn!("failed to fetch running processes: {}", why); + log::warn!("failed to fetch running processes: {}", why); return; } }; @@ -533,7 +534,7 @@ impl DaemonRuntime { logger: &'a dyn Fn(UpgradeEvent), fetch: Arc, ) -> RelResult<()> { - info!("fetching packages for the new release"); + log::info!("fetching packages for the new release"); (*logger)(UpgradeEvent::FetchingPackagesForNewRelease); let uris = crate::fetch::apt::fetch_uris(None).await.map_err(ReleaseError::AptList)?; @@ -558,7 +559,7 @@ impl DaemonRuntime { // Use a closure to capture any early returns due to an error. let updated_list_ops = || async { - info!("updated the package lists for the new release"); + log::info!("updated the package lists for the new release"); apt_lock_wait().await; (logger)(UpgradeEvent::UpdatingPackageLists); AptGet::new().noninteractive().update().await.map_err(ReleaseError::ReleaseUpdate)?; @@ -567,7 +568,7 @@ impl DaemonRuntime { self.attempt_fetch(logger, fetch).await?; - info!("packages fetched successfully"); + log::info!("packages fetched successfully"); (*logger)(UpgradeEvent::Simulating); @@ -605,10 +606,10 @@ pub fn upgrade_finalize(action: UpgradeMethod, from: &str, to: &str) -> RelResul } fn rollback(release: &str, why: &(dyn std::error::Error + 'static)) { - error!("failed to fetch packages: {}", crate::misc::format_error(why)); - warn!("attempting to roll back apt release files"); + log::error!("failed to fetch packages: {}", crate::misc::format_error(why)); + log::warn!("attempting to roll back apt release files"); if let Err(why) = repos::restore(release) { - error!( + log::error!( "failed to revert release name changes to source lists in /etc/apt/: {}", crate::misc::format_error(why.as_ref()) ); @@ -679,13 +680,13 @@ fn unset_recovery_as_default_boot_option(option: &str) -> RelResult { } fn systemd_boot_loader_swap(loader: LoaderEntry, description: &str) -> RelResult<()> { - info!("gathering systemd-boot configuration information"); + log::info!("gathering systemd-boot configuration information"); let mut systemd_boot_conf = SystemdBootConf::new("/boot/efi").map_err(ReleaseError::SystemdBootConf)?; { - info!("found the systemd-boot config -- searching for the {}", description); + log::info!("found the systemd-boot config -- searching for the {}", description); let SystemdBootConf { ref entries, ref mut loader_conf, .. } = systemd_boot_conf; let recovery_entry = entries .iter() @@ -698,7 +699,7 @@ fn systemd_boot_loader_swap(loader: LoaderEntry, description: &str) -> RelResult loader_conf.default = Some(recovery_entry.id.to_owned()); } - info!("found the {} -- setting it as the default boot entry", description); + log::info!("found the {} -- setting it as the default boot entry", description); systemd_boot_conf.overwrite_loader_conf().map_err(ReleaseError::SystemdBootConfOverwrite) } @@ -716,7 +717,7 @@ pub async fn cleanup() { for &file in [RELEASE_FETCH_FILE, STARTUP_UPGRADE_FILE].iter() { if Path::new(file).exists() { - info!("cleaning up after failed upgrade"); + log::info!("cleaning up after failed upgrade"); match Version::detect() { Ok(version) => { @@ -728,7 +729,7 @@ pub async fn cleanup() { let _ = crate::release::repos::restore(codename); } Err(why) => { - error!("could not detect distro release version: {}", why); + log::error!("could not detect distro release version: {}", why); } } diff --git a/src/release/check.rs b/src/release/check.rs index 1303645ec..9826f4a4f 100644 --- a/src/release/check.rs +++ b/src/release/check.rs @@ -125,12 +125,12 @@ fn next_( next = "21.04"; ReleaseStatus { - build: if development { release_check(next) } else { BuildStatus::Blacklisted }, + build: if development { release_check(next) } else { BuildStatus::Blacklisted }, current: "20.10", - is_lts: false, + is_lts: false, next, } - }, + } (21, 4) => ReleaseStatus { build: BuildStatus::Blacklisted, diff --git a/src/release/eol.rs b/src/release/eol.rs index 6ae2100bb..fdf1dd4af 100644 --- a/src/release/eol.rs +++ b/src/release/eol.rs @@ -1,4 +1,4 @@ -use anyhow::Context; +use anyhow::{anyhow, Context}; use chrono::{Date, NaiveDate, Utc}; use std::convert::TryFrom; use ubuntu_version::{Codename, Version}; diff --git a/src/release/repos.rs b/src/release/repos.rs index 6dab77bf1..517b8931a 100644 --- a/src/release/repos.rs +++ b/src/release/repos.rs @@ -1,5 +1,6 @@ use super::eol::{EolDate, EolStatus}; use anyhow::Context; +use fomat_macros::fomat; use os_str_bytes::OsStrBytes; use std::{ ffi::OsStr, @@ -43,7 +44,7 @@ pub fn backup(release: &str) -> anyhow::Result<()> { iter_files(dir, |entry| { let path = entry.path(); if path.extension().map_or(false, |e| e == "save") { - info!("removing old backup at {}", path.display()); + log::info!("removing old backup at {}", path.display()); fs::remove_file(&path) .with_context(|| fomat!("failed to remove backup at "(path.display())))?; } @@ -60,7 +61,7 @@ pub fn backup(release: &str) -> anyhow::Result<()> { let dst_path_str = OsStr::from_bytes(&dst_path_buf).unwrap(); let dst_path = Path::new(&dst_path_str); - info!("creating backup of {} to {}", src_path.display(), dst_path.display()); + log::info!("creating backup of {} to {}", src_path.display(), dst_path.display()); fs::copy(&src_path, dst_path).with_context( || fomat!("failed to copy " (src_path.display()) " to " (dst_path.display())), )?; @@ -72,15 +73,15 @@ pub fn backup(release: &str) -> anyhow::Result<()> { if Path::new(MAIN_FILE).exists() { if Path::new(BACKUP_MAIN_FILE).exists() { - info!("removing old backup at {}", BACKUP_MAIN_FILE); + log::info!("removing old backup at {}", BACKUP_MAIN_FILE); fs::remove_file(BACKUP_MAIN_FILE).context("failed to remove backup of sources.list")?; } - info!("creating backup of {} to {}", MAIN_FILE, BACKUP_MAIN_FILE); + log::info!("creating backup of {} to {}", MAIN_FILE, BACKUP_MAIN_FILE); fs::copy(MAIN_FILE, BACKUP_MAIN_FILE) .context("failed to copy sources list to backup path") .map(|_| ()) } else { - info!("sources list was not found — creating a new one"); + log::info!("sources list was not found — creating a new one"); create_new_sources_list(release).context("failed to create new sources.list") } } @@ -99,7 +100,7 @@ pub fn disable_third_parties(release: &str) -> anyhow::Result<()> { } } - info!("disabling sources in {}", path.display()); + log::info!("disabling sources in {}", path.display()); let contents = fs::read_to_string(&path) .with_context(|| fomat!("failed to read "(&path.display())))?; @@ -162,7 +163,7 @@ pub fn replace_with_old_releases() -> io::Result<()> { /// Restore a previous backup of the sources lists pub fn restore(release: &str) -> anyhow::Result<()> { - info!("restoring release files for {}", release); + log::info!("restoring release files for {}", release); let dir = fs::read_dir(PPA_DIR).context("cannot read PPA directory")?; iter_files(dir, |entry| { @@ -173,7 +174,7 @@ pub fn restore(release: &str) -> anyhow::Result<()> { let dst_str = OsStr::from_bytes(dst_bytes).unwrap(); let dst = Path::new(&dst_str); - info!("restoring source list at {}", dst.display()); + log::info!("restoring source list at {}", dst.display()); if dst.exists() { fs::remove_file(dst).with_context(|| fomat!("failed to remove "(dst.display())))?; @@ -188,7 +189,7 @@ pub fn restore(release: &str) -> anyhow::Result<()> { })?; if Path::new(BACKUP_MAIN_FILE).exists() { - info!("restoring system sources list"); + log::info!("restoring system sources list"); if Path::new(MAIN_FILE).exists() { fs::remove_file(MAIN_FILE).context("failed to remove modified system sources.list")?; diff --git a/src/release_api.rs b/src/release_api.rs index 730ed4584..93cdb397e 100644 --- a/src/release_api.rs +++ b/src/release_api.rs @@ -49,7 +49,7 @@ pub struct Release { impl Release { pub fn get_release(version: &str, channel: &str) -> Result { - info!("checking for build {} in channel {}", version, channel); + log::info!("checking for build {} in channel {}", version, channel); let url = [BASE, "builds/", version, "/", channel].concat(); let response = isahc::get(&url).map_err(ApiError::Get)?; diff --git a/src/repair/mod.rs b/src/repair.rs similarity index 96% rename from src/repair/mod.rs rename to src/repair.rs index c13dc1f92..9327e9d23 100644 --- a/src/repair/mod.rs +++ b/src/repair.rs @@ -29,7 +29,7 @@ pub enum RepairError { } pub async fn repair() -> Result<(), RepairError> { - info!("performing release repair"); + log::info!("performing release repair"); crypttab::repair().map_err(RepairError::Crypttab)?; fstab::repair().map_err(RepairError::Fstab)?;