Skip to content

Commit

Permalink
feat(rust): add tasks using the xtask pattern (#1650)
Browse files Browse the repository at this point in the history
While working on [Agama's website](https://agama-project.github.io/) we
wanted to include some documentation about the CLI. Fortunately,
[clap](https://crates.io/crates/clap) includes support for generating
markdown documentation, man pages, shell completions, etc.

After some research, we found out that the Rust community is adopting
the [xtask pattern](https://github.com/matklad/cargo-xtask), where you
write those tasks using Rust code. And it plays really well with clap,
as we can generate those artifcats from the sources.

However, we needed to do some refactoring to expose the CLI as a `lib`
crate so we can use it in our tasks.

This pull request includes the following tasks: `manpages`,
`completions` and `markdown`. The first step should be to take advantage
of them and generate the artifacts at runtime. It is open for discussion
whether we should do the same with the OpenAPI docs.

<details>
<summary>Generating the man pages</summary>

```shell
$ cargo xtask manpages                                                                                                                                                              at 15:05:46 
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.27s
     Running `target/debug/xtask manpages`
Generate manpages documentation at out/man

$ ls out/man/                                                                                                                                                                       agama-auth-login.1
agama-auth-logout.1
agama-auth-show.1
agama-auth.1
agama-config-edit.1
agama-config-load.1
agama-config-show.1
agama-config.1
agama-download.1
agama-install.1
agama-logs-list.1
agama-logs-store.1
agama-logs.1
agama-probe.1
agama-profile-autoyast.1
agama-profile-evaluate.1
agama-profile-import.1
agama-profile-validate.1
agama-profile.1
agama-questions-answers.1
agama-questions-ask.1
agama-questions-list.1
agama-questions-mode.1
agama-questions.1
agama.1
```
</details>
  • Loading branch information
imobachgs authored Oct 4, 2024
2 parents d57f8e6 + d883048 commit d29a167
Show file tree
Hide file tree
Showing 12 changed files with 421 additions and 168 deletions.
2 changes: 2 additions & 0 deletions rust/.cargo/config.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[alias]
xtask = "run --package xtask --"
57 changes: 51 additions & 6 deletions rust/Cargo.lock

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

8 changes: 7 additions & 1 deletion rust/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
[workspace]
members = ["agama-cli", "agama-server", "agama-lib", "agama-locale-data"]
members = [
"agama-cli",
"agama-server",
"agama-lib",
"agama-locale-data",
"xtask",
]
resolver = "2"

[workspace.package]
Expand Down
179 changes: 179 additions & 0 deletions rust/agama-cli/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
// Copyright (c) [2024] SUSE LLC
//
// All Rights Reserved.
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 2 of the License, or (at your option)
// any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, contact SUSE LLC.
//
// To contact SUSE LLC about this file by physical or electronic mail, you may
// find current contact information at www.suse.com.

use clap::Parser;

mod auth;
mod commands;
mod config;
mod error;
mod logs;
mod profile;
mod progress;
mod questions;

use crate::error::CliError;
use agama_lib::error::ServiceError;
use agama_lib::manager::ManagerClient;
use agama_lib::progress::ProgressMonitor;
use auth::run as run_auth_cmd;
use commands::Commands;
use config::run as run_config_cmd;
use logs::run as run_logs_cmd;
use profile::run as run_profile_cmd;
use progress::InstallerProgress;
use questions::run as run_questions_cmd;
use std::{
process::{ExitCode, Termination},
thread::sleep,
time::Duration,
};

/// Agama's command-line interface
///
/// This program allows inspecting or changing Agama's configuration, handling installation
/// profiles, starting the installation, monitoring the process, etc.
///
/// Please, use the "help" command to learn more.
#[derive(Parser)]
#[command(name = "agama", about, long_about, max_term_width = 100)]
pub struct Cli {
#[command(subcommand)]
pub command: Commands,
}

async fn probe() -> anyhow::Result<()> {
let another_manager = build_manager().await?;
let probe = tokio::spawn(async move {
let _ = another_manager.probe().await;
});
show_progress().await?;

Ok(probe.await?)
}

/// Starts the installation process
///
/// Before starting, it makes sure that the manager is idle.
///
/// * `manager`: the manager client.
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...");
}

// Make sure that the manager is ready
manager.wait().await?;

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

let progress = tokio::spawn(async { show_progress().await });
// Try to start the installation up to max_attempts times.
let mut attempts = 1;
loop {
match manager.install().await {
Ok(()) => break,
Err(e) => {
eprintln!(
"Could not start the installation process: {e}. Attempt {}/{}.",
attempts, max_attempts
);
}
}
if attempts == max_attempts {
eprintln!("Giving up.");
return Err(CliError::Installation)?;
}
attempts += 1;
sleep(Duration::from_secs(1));
}
let _ = progress.await;
Ok(())
}

async fn show_progress() -> Result<(), ServiceError> {
// wait 1 second to give other task chance to start, so progress can display something
tokio::time::sleep(Duration::from_secs(1)).await;
let conn = agama_lib::connection().await?;
let mut monitor = ProgressMonitor::new(conn).await.unwrap();
let presenter = InstallerProgress::new();
monitor
.run(presenter)
.await
.expect("failed to monitor the progress");
Ok(())
}

async fn wait_for_services(manager: &ManagerClient<'_>) -> Result<(), ServiceError> {
let services = manager.busy_services().await?;
// TODO: having it optional
if !services.is_empty() {
eprintln!("The Agama service is busy. Waiting for it to be available...");
show_progress().await?
}
Ok(())
}

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

pub async fn run_command(cli: Cli) -> Result<(), ServiceError> {
match cli.command {
Commands::Config(subcommand) => {
let manager = build_manager().await?;
wait_for_services(&manager).await?;
run_config_cmd(subcommand).await?
}
Commands::Probe => {
let manager = build_manager().await?;
wait_for_services(&manager).await?;
probe().await?
}
Commands::Profile(subcommand) => run_profile_cmd(subcommand).await?,
Commands::Install => {
let manager = build_manager().await?;
install(&manager, 3).await?
}
Commands::Questions(subcommand) => run_questions_cmd(subcommand).await?,
Commands::Logs(subcommand) => run_logs_cmd(subcommand).await?,
Commands::Auth(subcommand) => run_auth_cmd(subcommand).await?,
Commands::Download { url } => crate::profile::download(&url, std::io::stdout())?,
};

Ok(())
}

/// 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)
}
}
Loading

0 comments on commit d29a167

Please sign in to comment.