Skip to content

Commit

Permalink
format code
Browse files Browse the repository at this point in the history
  • Loading branch information
jreidinger committed Jun 16, 2023
1 parent 501fc0c commit f2027c7
Show file tree
Hide file tree
Showing 16 changed files with 96 additions and 88 deletions.
4 changes: 2 additions & 2 deletions rust/agama-cli/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use crate::error::CliError;
use crate::printers::{print, Format};
use clap::Subcommand;
use convert_case::{Case, Casing};
use agama_lib::connection;
use agama_lib::install_settings::{InstallSettings, Scope};
use agama_lib::settings::{SettingObject, SettingValue, Settings};
use agama_lib::Store as SettingsStore;
use clap::Subcommand;
use convert_case::{Case, Casing};
use std::str::FromStr;
use std::{collections::HashMap, error::Error, io};

Expand Down
13 changes: 8 additions & 5 deletions rust/agama-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,15 @@ mod profile;
mod progress;

use crate::error::CliError;
use async_std::task::{self, block_on};
use commands::Commands;
use config::run as run_config_cmd;
use agama_lib::error::ServiceError;
use agama_lib::manager::ManagerClient;
use agama_lib::progress::build_progress_monitor;
use async_std::task::{self, block_on};
use commands::Commands;
use config::run as run_config_cmd;
use printers::Format;
use progress::InstallerProgress;
use profile::run as run_profile_cmd;
use progress::InstallerProgress;
use std::error::Error;
use std::time::Duration;

Expand Down Expand Up @@ -58,7 +58,10 @@ async fn show_progress() -> Result<(), ServiceError> {
let conn = agama_lib::connection().await?;
let mut monitor = build_progress_monitor(conn).await.unwrap();
let presenter = InstallerProgress::new();
monitor.run(presenter).await.expect("failed to monitor the progress");
monitor
.run(presenter)
.await
.expect("failed to monitor the progress");
Ok(())
}

Expand Down
4 changes: 2 additions & 2 deletions rust/agama-cli/src/profile.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use clap::Subcommand;
use agama_lib::error::ProfileError;
use agama_lib::profile::{download, ProfileEvaluator, ProfileValidator, ValidationResult};
use std::{path::Path};
use clap::Subcommand;
use std::path::Path;

#[derive(Subcommand, Debug)]
pub enum ProfileCommands {
Expand Down
15 changes: 9 additions & 6 deletions rust/agama-dbus-server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,28 @@ pub mod locale;
pub mod questions;

use agama_network::NetworkService;
use std::future::pending;
use log::LevelFilter;
use std::future::pending;

const ADDRESS: &str = "unix:path=/run/agama/bus";

#[async_std::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// be smart with logging and log directly to journal if connected to it
if systemd_journal_logger::connected_to_journal(){
if systemd_journal_logger::connected_to_journal() {
// unwrap here is intentional as we are sure no other logger is active yet
systemd_journal_logger::JournalLog::default().install().unwrap();
systemd_journal_logger::JournalLog::default()
.install()
.unwrap();
log::set_max_level(LevelFilter::Info); // log only info for journal logger
} else {
simplelog::TermLogger::init(
LevelFilter::Info, // lets use info, trace provides too much output from libraries
LevelFilter::Info, // lets use info, trace provides too much output from libraries
simplelog::Config::default(),
simplelog::TerminalMode::Stderr, // only stderr output for easier filtering
simplelog::ColorChoice::Auto
).unwrap(); // unwrap here as we are sure no other logger active
simplelog::ColorChoice::Auto,
)
.unwrap(); // unwrap here as we are sure no other logger active
}
// When adding more services here, the order might be important.
crate::questions::start_service(ADDRESS).await?;
Expand Down
6 changes: 4 additions & 2 deletions rust/agama-lib/src/store/software.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,11 @@ impl<'a> SoftwareStore<'a> {
if ids.contains(&product) {
self.software_client.select_product(product).await?;
} else {
return Err(Box::new(WrongParameter::UnknownProduct(product.clone(), ids)));
return Err(Box::new(WrongParameter::UnknownProduct(
product.clone(),
ids,
)));
}

}
Ok(())
}
Expand Down
4 changes: 2 additions & 2 deletions rust/agama-lib/src/store/users.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::error::WrongParameter;
use crate::install_settings::{FirstUserSettings, RootUserSettings, UserSettings};
use crate::users::{FirstUser, UsersClient};
use crate::error::WrongParameter;
use std::error::Error;
use zbus::Connection;

Expand Down Expand Up @@ -57,7 +57,7 @@ impl<'a> UsersStore<'a> {
};
let (success, issues) = self.users_client.set_first_user(&first_user).await?;
if !success {
return Err(Box::new(WrongParameter::WrongUser(issues)));
return Err(Box::new(WrongParameter::WrongUser(issues)));
}
Ok(())
}
Expand Down
5 changes: 1 addition & 4 deletions rust/agama-lib/src/users.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,10 +78,7 @@ impl<'a> UsersClient<'a> {
value: &str,
encrypted: bool,
) -> Result<u32, ServiceError> {
Ok(self
.users_proxy
.set_root_password(value, encrypted)
.await?)
Ok(self.users_proxy.set_root_password(value, encrypted).await?)
}

/// Whether the root password is set or not
Expand Down
22 changes: 11 additions & 11 deletions rust/agama-locale-data/src/deprecated_timezones.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
/// List of timezones which are deprecated and langtables missing translations for it
///
///
/// Filtering it out also helps with returning smaller list of real timezones.
/// Sadly many libraries facing issues with deprecated timezones, see e.g.
///
pub(crate) const DEPRECATED_TIMEZONES : &[&str]= &[
"Africa/Asmera", // replaced by Africa/Asmara
"Africa/Timbuktu", // replaced by Africa/Bamako
///
pub(crate) const DEPRECATED_TIMEZONES: &[&str] = &[
"Africa/Asmera", // replaced by Africa/Asmara
"Africa/Timbuktu", // replaced by Africa/Bamako
"America/Argentina/ComodRivadavia", // replaced by America/Argentina/Catamarca
"America/Atka", // replaced by America/Adak
"America/Ciudad_Juarez", // failed to find replacement
"America/Coral_Harbour", // replaced by America/Atikokan
"America/Ensenada", // replaced by America/Tijuana
"America/Atka", // replaced by America/Adak
"America/Ciudad_Juarez", // failed to find replacement
"America/Coral_Harbour", // replaced by America/Atikokan
"America/Ensenada", // replaced by America/Tijuana
"America/Fort_Nelson",
"America/Fort_Wayne", // replaced by America/Indiana/Indianapolis
"America/Knox_IN", // replaced by America/Indiana/Knox
"America/Knox_IN", // replaced by America/Indiana/Knox
"America/Nuuk",
"America/Porto_Acre", // replaced by America/Rio_Branco
"America/Punta_Arenas",
Expand Down Expand Up @@ -170,4 +170,4 @@ pub(crate) const DEPRECATED_TIMEZONES : &[&str]= &[
"W-SU",
"WET",
"Zulu",
];
];
8 changes: 4 additions & 4 deletions rust/agama-locale-data/src/language.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
use serde::Deserialize;

use crate::ranked::{RankedTerritories, RankedLocales};
use crate::ranked::{RankedLocales, RankedTerritories};

#[derive(Debug, Deserialize)]
pub struct Language {
#[serde(rename(deserialize = "languageId"))]
pub id: String,
pub territories: RankedTerritories,
pub locales: RankedLocales,
pub names: crate::localization::Localization
pub names: crate::localization::Localization,
}

#[derive(Debug, Deserialize)]
pub struct Languages {
pub language: Vec<Language>
pub language: Vec<Language>,
}

impl Languages {
pub fn find_by_id(&self, id: &str) -> Option<&Language> {
self.language.iter().find(|t| t.id == id)
}
}
}
57 changes: 34 additions & 23 deletions rust/agama-locale-data/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
use anyhow::Context;
use flate2::bufread::GzDecoder;
use quick_xml::de::Deserializer;
use regex::Regex;
use serde::Deserialize;
use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
use std::process::Command;
use quick_xml::de::Deserializer;
use flate2::bufread::GzDecoder;
use regex::Regex;

pub mod xkeyboard;
pub mod deprecated_timezones;
pub mod language;
pub mod localization;
pub mod ranked;
pub mod territory;
pub mod timezone_part;
pub mod ranked;
pub mod deprecated_timezones;
pub mod xkeyboard;

fn file_reader(file_path: &str) -> anyhow::Result<impl BufRead> {
let file = File::open(file_path)
Expand All @@ -34,37 +34,45 @@ pub fn get_xkeyboards() -> anyhow::Result<xkeyboard::XKeyboards> {
}

/// Gets list of available keymaps
///
///
/// ## Examples
/// Requires working localectl.
///
///
/// ```no_run
/// let key_maps = agama_locale_data::get_key_maps().unwrap();
/// assert!(key_maps.contains(&"us".to_string()))
/// ```
pub fn get_key_maps() -> anyhow::Result<Vec<String>> {
const BINARY: &str = "/usr/bin/localectl";
let output = Command::new(BINARY).arg("list-keymaps")
.output().context("failed to execute localectl list-maps")?.stdout;
let output = Command::new(BINARY)
.arg("list-keymaps")
.output()
.context("failed to execute localectl list-maps")?
.stdout;
let output = String::from_utf8(output).context("Strange localectl output formatting")?;
let ret = output.split('\n').map(|l| l.trim().to_string()).collect();

Ok(ret)
}

/// Parses given locale to language and territory part
///
///
/// /// ## Examples
///
///
/// ```
/// let result = agama_locale_data::parse_locale("en_US.UTF-8").unwrap();
/// assert_eq!(result.0, "en");
/// assert_eq!(result.1, "US")
/// ```
pub fn parse_locale(locale: &str) -> anyhow::Result<(&str, &str)> {
let locale_regexp : Regex = Regex::new(r"^([[:alpha:]]+)_([[:alpha:]]+)").unwrap();
let captures = locale_regexp.captures(locale).context("Failed to parse locale")?;
Ok((captures.get(1).unwrap().as_str(), captures.get(2).unwrap().as_str()))
let locale_regexp: Regex = Regex::new(r"^([[:alpha:]]+)_([[:alpha:]]+)").unwrap();
let captures = locale_regexp
.captures(locale)
.context("Failed to parse locale")?;
Ok((
captures.get(1).unwrap().as_str(),
captures.get(2).unwrap().as_str(),
))
}

/// Returns struct which contain list of known languages
Expand Down Expand Up @@ -97,13 +105,13 @@ pub fn get_timezone_parts() -> anyhow::Result<timezone_part::TimezoneIdParts> {
Ok(ret)
}


/// Gets list of non-deprecated timezones
pub fn get_timezones() -> Vec<String> {
chrono_tz::TZ_VARIANTS.iter()
.filter(|&tz| !crate::deprecated_timezones::DEPRECATED_TIMEZONES.contains(&tz.name())) // Filter out deprecated asmera
.map(|e| e.name().to_string())
.collect()
chrono_tz::TZ_VARIANTS
.iter()
.filter(|&tz| !crate::deprecated_timezones::DEPRECATED_TIMEZONES.contains(&tz.name())) // Filter out deprecated asmera
.map(|e| e.name().to_string())
.collect()
}

#[cfg(test)]
Expand Down Expand Up @@ -152,7 +160,10 @@ mod tests {
// here test that timezones from timezones matches ones in langtable ( as timezones can contain deprecated ones)
// so this test catch if there is new zone that is not translated or if a zone is become deprecated
let timezones = get_timezones();
let localized = get_timezone_parts().unwrap().localize_timezones("de", &timezones);
let _res : Vec<(String, String)> = timezones.into_iter().zip(localized.into_iter()).collect();
let localized = get_timezone_parts()
.unwrap()
.localize_timezones("de", &timezones);
let _res: Vec<(String, String)> =
timezones.into_iter().zip(localized.into_iter()).collect();
}
}
9 changes: 4 additions & 5 deletions rust/agama-locale-data/src/localization.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,12 @@ use serde::Deserialize;

#[derive(Debug, Deserialize)]
pub struct Localization {
pub name: Vec<LocalizationEntry>
pub name: Vec<LocalizationEntry>,
}

impl Localization {
pub fn name_for(&self, language: &str) -> Option<String> {
let entry = self.name.iter()
.find(|n| n.language == language)?;
let entry = self.name.iter().find(|n| n.language == language)?;
Some(entry.value.clone())
}
}
Expand All @@ -18,5 +17,5 @@ pub struct LocalizationEntry {
#[serde(rename(deserialize = "languageId"))]
pub language: String,
#[serde(rename(deserialize = "trName"))]
pub value: String
}
pub value: String,
}
12 changes: 6 additions & 6 deletions rust/agama-locale-data/src/ranked.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,38 +6,38 @@ pub struct RankedLanguage {
#[serde(rename(deserialize = "languageId"))]
pub id: String,
/// Bigger rank means it is more important
pub rank: u16
pub rank: u16,
}

#[derive(Debug, Deserialize)]
pub struct RankedLanguages {
#[serde(default)]
pub language: Vec<RankedLanguage>
pub language: Vec<RankedLanguage>,
}

#[derive(Debug, Deserialize)]
pub struct RankedTerritory {
#[serde(rename(deserialize = "territoryId"))]
pub id: String,
/// Bigger rank means it is more important
pub rank: u16
pub rank: u16,
}

#[derive(Debug, Deserialize)]
pub struct RankedTerritories {
#[serde(default)]
pub territory: Vec<RankedTerritory>
pub territory: Vec<RankedTerritory>,
}

#[derive(Debug, Deserialize)]
pub struct RankedLocale {
#[serde(rename(deserialize = "localeId"))]
pub id: String,
pub rank: u16
pub rank: u16,
}

#[derive(Debug, Deserialize)]
pub struct RankedLocales {
#[serde(default)]
pub locale: Vec<RankedLocale>
pub locale: Vec<RankedLocale>,
}
Loading

0 comments on commit f2027c7

Please sign in to comment.