Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/master' into adapt_quesstions_api
Browse files Browse the repository at this point in the history
  • Loading branch information
jreidinger committed Jul 13, 2023
2 parents 74462a0 + 2e11beb commit 5a1853b
Show file tree
Hide file tree
Showing 40 changed files with 244 additions and 199 deletions.
1 change: 1 addition & 0 deletions rust/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions rust/agama-cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ async-std = { version ="1.12.0", features = ["attributes"] }
thiserror = "1.0.39"
convert_case = "0.6.0"
console = "0.15.7"
anyhow = "1.0.71"

[[bin]]
name = "agama"
Expand Down
8 changes: 4 additions & 4 deletions rust/agama-cli/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ pub enum ConfigAction {
Load(String),
}

pub async fn run(subcommand: ConfigCommands, format: Format) -> Result<(), Box<dyn Error>> {
pub async fn run(subcommand: ConfigCommands, format: Format) -> anyhow::Result<()> {
let store = SettingsStore::new(connection().await?).await?;

match parse_config_command(subcommand) {
Expand All @@ -44,7 +44,7 @@ pub async fn run(subcommand: ConfigCommands, format: Format) -> Result<(), Box<d
for (key, value) in changes {
model.set(&key.to_case(Case::Snake), SettingValue(value))?;
}
store.store(&model).await
Ok(store.store(&model).await?)
}
ConfigAction::Show => {
let model = store.load(None).await?;
Expand All @@ -55,15 +55,15 @@ pub async fn run(subcommand: ConfigCommands, format: Format) -> Result<(), Box<d
let scope = key_to_scope(&key).unwrap();
let mut model = store.load(Some(vec![scope])).await?;
model.add(&key.to_case(Case::Snake), SettingObject::from(values))?;
store.store(&model).await
Ok(store.store(&model).await?)
}
ConfigAction::Load(path) => {
let contents = std::fs::read_to_string(path)?;
let result: InstallSettings = serde_json::from_str(&contents)?;
let scopes = result.defined_scopes();
let mut model = store.load(Some(scopes)).await?;
model.merge(&result);
store.store(&model).await
Ok(store.store(&model).await?)
}
}
}
Expand Down
44 changes: 30 additions & 14 deletions rust/agama-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,11 @@ use config::run as run_config_cmd;
use printers::Format;
use profile::run as run_profile_cmd;
use progress::InstallerProgress;
use std::error::Error;
use std::thread::sleep;
use std::time::Duration;
use std::{
process::{ExitCode, Termination},
thread::sleep,
time::Duration,
};

#[derive(Parser)]
#[command(name = "agama", version, about, long_about = None)]
Expand All @@ -32,7 +34,7 @@ struct Cli {
pub format: Format,
}

async fn probe() -> Result<(), Box<dyn Error>> {
async fn probe() -> anyhow::Result<()> {
let another_manager = build_manager().await?;
let probe = task::spawn(async move { another_manager.probe().await });
show_progress().await?;
Expand All @@ -45,13 +47,13 @@ async fn probe() -> Result<(), Box<dyn Error>> {
/// Before starting, it makes sure that the manager is idle.
///
/// * `manager`: the manager client.
async fn install(manager: &ManagerClient<'_>, max_attempts: u8) -> Result<(), Box<dyn Error>> {
async fn install(manager: &ManagerClient<'_>, max_attempts: u8) -> anyhow::Result<()> {
if manager.is_busy().await {
println!("Agama's manager is busy. Waiting until it is ready...");
}

if !manager.can_install().await? {
return Err(Box::new(CliError::ValidationError));
return Err(CliError::ValidationError)?;
}

// Display the progress (if needed) and makes sure that the manager is ready
Expand All @@ -72,7 +74,7 @@ async fn install(manager: &ManagerClient<'_>, max_attempts: u8) -> Result<(), Bo
}
if attempts == max_attempts {
eprintln!("Giving up.");
return Err(Box::new(CliError::InstallationError));
return Err(CliError::InstallationError)?;
}
attempts += 1;
sleep(Duration::from_secs(1));
Expand All @@ -94,7 +96,7 @@ async fn show_progress() -> Result<(), ServiceError> {
Ok(())
}

async fn wait_for_services(manager: &ManagerClient<'_>) -> Result<(), Box<dyn Error>> {
async fn wait_for_services(manager: &ManagerClient<'_>) -> Result<(), ServiceError> {
let services = manager.busy_services().await?;
// TODO: having it optional
if !services.is_empty() {
Expand All @@ -104,12 +106,12 @@ async fn wait_for_services(manager: &ManagerClient<'_>) -> Result<(), Box<dyn Er
Ok(())
}

async fn build_manager<'a>() -> Result<ManagerClient<'a>, Box<dyn Error>> {
async fn build_manager<'a>() -> anyhow::Result<ManagerClient<'a>> {
let conn = agama_lib::connection().await?;
Ok(ManagerClient::new(conn).await?)
}

async fn run_command(cli: Cli) -> Result<(), Box<dyn Error>> {
async fn run_command(cli: Cli) -> anyhow::Result<()> {
match cli.command {
Commands::Config(subcommand) => {
let manager = build_manager().await?;
Expand All @@ -130,13 +132,27 @@ async fn run_command(cli: Cli) -> Result<(), Box<dyn Error>> {
}
}

/// Represents the result of execution.
pub enum CliResult {
/// Successful execution.
Ok = 0,
/// Something went wrong.
Error = 1,
}

impl Termination for CliResult {
fn report(self) -> ExitCode {
ExitCode::from(self as u8)
}
}

#[async_std::main]
async fn main() -> Result<(), Box<dyn Error>> {
async fn main() -> CliResult {
let cli = Cli::parse();

if let Err(error) = run_command(cli).await {
eprintln!("{}", error);
return Err(error);
eprintln!("{:?}", error);
return CliResult::Error;
}
Ok(())
CliResult::Ok
}
22 changes: 11 additions & 11 deletions rust/agama-cli/src/printers.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use serde::Serialize;
use std::error;
use std::fmt::Debug;
use std::io::Write;

Expand All @@ -16,7 +15,7 @@ use std::io::Write;
/// print(user, io::stdout(), Some(Format::Json))
/// .expect("Something went wrong!")
/// ```
pub fn print<T, W>(content: T, writer: W, format: Format) -> Result<(), Box<dyn error::Error>>
pub fn print<T, W>(content: T, writer: W, format: Format) -> anyhow::Result<()>
where
T: serde::Serialize + Debug,
W: Write,
Expand All @@ -38,27 +37,28 @@ pub enum Format {
}

pub trait Printer<T, W> {
fn print(self: Box<Self>) -> Result<(), Box<dyn error::Error>>;
fn print(self: Box<Self>) -> anyhow::Result<()>;
}

pub struct JsonPrinter<T, W> {
content: T,
writer: W,
}

impl<T: Serialize + Debug, W: Write> Printer<T, W> for JsonPrinter<T, W> {
fn print(self: Box<Self>) -> Result<(), Box<dyn error::Error>> {
Ok(serde_json::to_writer(self.writer, &self.content)?)
impl<T: Serialize, W: Write> Printer<T, W> for JsonPrinter<T, W> {
fn print(mut self: Box<Self>) -> anyhow::Result<()> {
let json = serde_json::to_string(&self.content)?;
Ok(writeln!(self.writer, "{}", json)?)
}
}
pub struct TextPrinter<T, W> {
content: T,
writer: W,
}

impl<T: Serialize + Debug, W: Write> Printer<T, W> for TextPrinter<T, W> {
fn print(mut self: Box<Self>) -> Result<(), Box<dyn error::Error>> {
Ok(write!(self.writer, "{:?}", &self.content)?)
impl<T: Debug, W: Write> Printer<T, W> for TextPrinter<T, W> {
fn print(mut self: Box<Self>) -> anyhow::Result<()> {
Ok(writeln!(self.writer, "{:?}", &self.content)?)
}
}

Expand All @@ -67,8 +67,8 @@ pub struct YamlPrinter<T, W> {
writer: W,
}

impl<T: Serialize + Debug, W: Write> Printer<T, W> for YamlPrinter<T, W> {
fn print(self: Box<Self>) -> Result<(), Box<dyn error::Error>> {
impl<T: Serialize, W: Write> Printer<T, W> for YamlPrinter<T, W> {
fn print(self: Box<Self>) -> anyhow::Result<()> {
Ok(serde_yaml::to_writer(self.writer, &self.content)?)
}
}
21 changes: 13 additions & 8 deletions rust/agama-cli/src/profile.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use agama_lib::error::ProfileError;
use agama_lib::profile::{download, ProfileEvaluator, ProfileValidator, ValidationResult};
use anyhow::Context;
use clap::Subcommand;
use std::path::Path;

Expand All @@ -15,16 +15,18 @@ pub enum ProfileCommands {
Evaluate { path: String },
}

fn validate(path: String) -> Result<(), ProfileError> {
fn validate(path: String) -> anyhow::Result<()> {
let validator = ProfileValidator::default_schema()?;
let path = Path::new(&path);
let result = validator.validate_file(path)?;
let result = validator
.validate_file(path)
.context("Could not validate the profile")?;
match result {
ValidationResult::Valid => {
println!("The profile is valid")
}
ValidationResult::NotValid(errors) => {
println!("The profile is not valid. Please, check the following errors:\n");
eprintln!("The profile is not valid. Please, check the following errors:\n");
for error in errors {
println!("* {error}")
}
Expand All @@ -33,14 +35,17 @@ fn validate(path: String) -> Result<(), ProfileError> {
Ok(())
}

fn evaluate(path: String) -> Result<(), ProfileError> {
fn evaluate(path: String) -> anyhow::Result<()> {
let evaluator = ProfileEvaluator {};
evaluator.evaluate(Path::new(&path))
evaluator
.evaluate(Path::new(&path))
.context("Could not evaluate the profile".to_string())?;
Ok(())
}

pub fn run(subcommand: ProfileCommands) -> Result<(), ProfileError> {
pub fn run(subcommand: ProfileCommands) -> anyhow::Result<()> {
match subcommand {
ProfileCommands::Download { url } => download(&url),
ProfileCommands::Download { url } => Ok(download(&url)?),
ProfileCommands::Validate { path } => validate(path),
ProfileCommands::Evaluate { path } => evaluate(path),
}
Expand Down
4 changes: 2 additions & 2 deletions rust/agama-cli/src/progress.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ impl InstallerProgress {
impl ProgressPresenter for InstallerProgress {
fn start(&mut self, progress: &Progress) {
if !progress.finished {
self.update_main(&progress);
self.update_main(progress);
}
}

Expand All @@ -49,7 +49,7 @@ impl ProgressPresenter for InstallerProgress {
bar.finish_and_clear();
}
} else {
self.update_bar(&progress);
self.update_bar(progress);
}
}

Expand Down
9 changes: 4 additions & 5 deletions rust/agama-dbus-server/src/locale.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ impl Locale {

#[dbus_interface(property)]
fn locales(&self) -> Vec<String> {
return self.locales.to_owned();
self.locales.to_owned()
}

#[dbus_interface(property)]
Expand Down Expand Up @@ -112,16 +112,15 @@ impl Locale {

#[dbus_interface(property, name = "VConsoleKeyboard")]
fn keymap(&self) -> &str {
return &self.keymap.as_str();
self.keymap.as_str()
}

#[dbus_interface(property, name = "VConsoleKeyboard")]
fn set_keymap(&mut self, keyboard: &str) -> Result<(), zbus::fdo::Error> {
let exist = agama_locale_data::get_key_maps()
.unwrap()
.iter()
.find(|&k| k == keyboard)
.is_some();
.any(|k| k == keyboard);
if !exist {
return Err(zbus::fdo::Error::Failed(
"Invalid keyboard value".to_string(),
Expand All @@ -141,7 +140,7 @@ impl Locale {

#[dbus_interface(property)]
fn timezone(&self) -> &str {
return &self.timezone_id.as_str();
self.timezone_id.as_str()
}

#[dbus_interface(property)]
Expand Down
10 changes: 4 additions & 6 deletions rust/agama-dbus-server/src/network/dbus/interfaces.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ impl Connections {
/// * `id`: connection ID.
pub async fn get_connection(&self, id: &str) -> zbus::fdo::Result<OwnedObjectPath> {
let objects = self.objects.lock();
match objects.connection_path(&id) {
match objects.connection_path(id) {
Some(path) => Ok(path.into()),
None => Err(NetworkStateError::UnknownConnection(id.to_string()).into()),
}
Expand Down Expand Up @@ -308,8 +308,8 @@ impl Ipv4 {
.iter()
.map(|addr| addr.parse::<Ipv4Addr>())
.collect::<Result<Vec<Ipv4Addr>, AddrParseError>>()
.and_then(|parsed| Ok(ipv4.nameservers = parsed))
.map_err(|err| NetworkStateError::from(err))?;
.map(|parsed| ipv4.nameservers = parsed)
.map_err(NetworkStateError::from)?;
self.update_connection(connection)
}

Expand All @@ -333,9 +333,7 @@ impl Ipv4 {
if gateway.is_empty() {
ipv4.gateway = None;
} else {
let parsed: Ipv4Addr = gateway
.parse()
.map_err(|err| NetworkStateError::from(err))?;
let parsed: Ipv4Addr = gateway.parse().map_err(NetworkStateError::from)?;
ipv4.gateway = Some(parsed);
}
self.update_connection(connection)
Expand Down
2 changes: 1 addition & 1 deletion rust/agama-dbus-server/src/network/dbus/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ impl NetworkService {
connection
.request_name(SERVICE_NAME)
.await
.expect(&format!("Could not request name {SERVICE_NAME}"));
.unwrap_or_else(|_| panic!("Could not request name {SERVICE_NAME}"));

network.listen().await;
})
Expand Down
Loading

0 comments on commit 5a1853b

Please sign in to comment.