Skip to content

Commit eb6dd3c

Browse files
feat(rust): if the command fails to load the state, it will throw a message and abort
1 parent aee5ff0 commit eb6dd3c

File tree

7 files changed

+59
-76
lines changed

7 files changed

+59
-76
lines changed

implementations/rust/ockam/ockam_app_lib/src/api/functions.rs

-1
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,6 @@ extern "C" fn initialize_application(
7575

7676
#[cfg(target_os = "macos")]
7777
crate::cli::add_homebrew_to_path();
78-
crate::cli::set_no_automatic_reset();
7978

8079
if let Err(err) = check_ockam_executable() {
8180
error!(?err, "Couldn't find the ockam executable");

implementations/rust/ockam/ockam_app_lib/src/cli/mod.rs

-7
Original file line numberDiff line numberDiff line change
@@ -43,13 +43,6 @@ pub(crate) fn add_homebrew_to_path() {
4343
}
4444
}
4545

46-
/// Set the OCKAM_NO_AUTOMATIC_RESET environment variable to avoid
47-
/// automatically resetting the node when the application find an incoherent state
48-
/// this may happen if a command is launched during a write operation
49-
pub(crate) fn set_no_automatic_reset() {
50-
std::env::set_var("OCKAM_NO_AUTOMATIC_RESET", "true");
51-
}
52-
5346
/// Check that the OCKAM environment variable defines an absolute path
5447
/// Otherwise we might fail to run the ockam command when starting the desktop application from an unexpected path
5548
/// Check that the ockam command can at least be called with the `--version` option and log

implementations/rust/ockam/ockam_command/Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ r3bl_rs_utils_core = "0.9.7"
8888
r3bl_tuify = "0.1.21"
8989
rand = "0.8"
9090
regex = "1.10.2"
91-
reqwest = { version = "0.11", default-features = false, features = ["json", "rustls-tls-native-roots"] }
91+
reqwest = { version = "0.11", default-features = false, features = ["json", "rustls-tls-native-roots", "blocking"] }
9292
rustls = "0.22.1"
9393
rustls-native-certs = "0.7.0"
9494
rustls-pki-types = "1.0.1"

implementations/rust/ockam/ockam_command/src/lib.rs

+15-34
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
//! cd implementations/rust/ockam/ockam_command && cargo install --path .
1818
//! ```
1919
20+
use std::process::exit;
2021
use std::{path::PathBuf, sync::Mutex};
2122

2223
use clap::{ArgAction, Args, Parser, Subcommand};
@@ -70,7 +71,7 @@ use crate::kafka::direct::KafkaDirectCommand;
7071
use crate::kafka::outlet::KafkaOutletCommand;
7172
use crate::logs::setup_logging;
7273
use crate::node::NodeSubcommand;
73-
use crate::output::{Output, OutputFormat};
74+
use crate::output::OutputFormat;
7475
use crate::run::RunCommand;
7576
use crate::sidecar::SidecarCommand;
7677
use crate::subscription::SubscriptionCommand;
@@ -242,30 +243,22 @@ pub struct CommandGlobalOpts {
242243

243244
impl CommandGlobalOpts {
244245
pub fn new(global_args: GlobalArgs) -> Self {
246+
let terminal = Terminal::from(&global_args);
245247
let state = match CliState::with_default_dir() {
246248
Ok(state) => state,
247-
Err(err) => {
248-
eprintln!("Failed to initialize state: {}", err);
249-
if std::env::var("OCKAM_NO_AUTOMATIC_RESET").is_ok() {
250-
std::process::exit(exitcode::CONFIG);
251-
}
252-
let state = CliState::backup_and_reset().expect(
253-
"Failed to initialize CliState. Try to manually remove the '~/.ockam' directory",
254-
);
255-
let dir = state.dir();
256-
let backup_dir = CliState::backup_default_dir().unwrap();
257-
eprintln!(
258-
"The {dir:?} directory has been reset and has been backed up to {backup_dir:?}"
259-
);
260-
state
249+
Err(_) => {
250+
terminal
251+
.write_line(fmt_err!("Failed to initialize local state"))
252+
.unwrap();
253+
terminal
254+
.write_line(fmt_log!(
255+
"Consider upgrading to the latest version of Ockam Command, \
256+
or try removing the local state directory at ~/.ockam"
257+
))
258+
.unwrap();
259+
exit(exitcode::SOFTWARE);
261260
}
262261
};
263-
let terminal = Terminal::new(
264-
global_args.quiet,
265-
global_args.no_color,
266-
global_args.no_input,
267-
global_args.output_format.clone(),
268-
);
269262
Self {
270263
global_args,
271264
state,
@@ -279,15 +272,6 @@ impl CommandGlobalOpts {
279272
clone.terminal = clone.terminal.set_quiet();
280273
clone
281274
}
282-
283-
/// Print a value on the console.
284-
/// TODO: replace this implementation with a call to the terminal instead
285-
pub fn println<T>(&self, t: &T) -> Result<()>
286-
where
287-
T: Output + serde::Serialize,
288-
{
289-
self.global_args.output_format.println_value(t)
290-
}
291275
}
292276

293277
#[cfg(test)]
@@ -374,10 +358,7 @@ pub fn run() {
374358

375359
match OckamCommand::try_parse_from(input) {
376360
Ok(command) => {
377-
if !command.global_args.test_argument_parser {
378-
check_if_an_upgrade_is_available();
379-
}
380-
361+
check_if_an_upgrade_is_available(&command.global_args);
381362
command.run();
382363
}
383364
Err(help) => pager::render_help(help),

implementations/rust/ockam/ockam_command/src/project/create.rs

+6-1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ use ockam_api::cloud::project::Projects;
66
use ockam_api::nodes::InMemoryNode;
77

88
use crate::operation::util::check_for_project_completion;
9+
use crate::output::Output;
910
use crate::project::util::check_project_readiness;
1011
use crate::util::api::CloudOpts;
1112
use crate::util::node_rpc;
@@ -56,6 +57,10 @@ async fn run_impl(
5657
.await?;
5758
let project = check_for_project_completion(&opts, ctx, &node, project).await?;
5859
let project = check_project_readiness(&opts, ctx, &node, project).await?;
59-
opts.println(&project)?;
60+
opts.terminal
61+
.stdout()
62+
.plain(project.output()?)
63+
.json(serde_json::json!(&project))
64+
.write_line()?;
6065
Ok(())
6166
}

implementations/rust/ockam/ockam_command/src/terminal/mod.rs

+10-4
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ use std::io::Write;
44
use std::time::Duration;
55

66
use colorful::Colorful;
7+
use console::Term;
78
use indicatif::{ProgressBar, ProgressDrawTarget, ProgressStyle};
89
use miette::Context as _;
910
use miette::{miette, IntoDiagnostic};
@@ -19,7 +20,7 @@ use r3bl_rs_utils_core::*;
1920
use r3bl_tuify::*;
2021

2122
use crate::error::Error;
22-
use crate::{fmt_list, fmt_log, fmt_warn, OutputFormat, Result};
23+
use crate::{fmt_list, fmt_log, fmt_warn, GlobalArgs, OutputFormat, Result};
2324

2425
pub mod colors;
2526
pub mod fmt;
@@ -45,9 +46,14 @@ impl<T: TerminalWriter, W> Terminal<T, W> {
4546
}
4647
}
4748

48-
impl<W: TerminalWriter> Default for Terminal<W> {
49-
fn default() -> Self {
50-
Terminal::new(false, false, false, OutputFormat::Plain)
49+
impl From<&GlobalArgs> for Terminal<TerminalStream<Term>> {
50+
fn from(global_args: &GlobalArgs) -> Self {
51+
Terminal::new(
52+
global_args.quiet,
53+
global_args.no_color,
54+
global_args.no_input,
55+
global_args.output_format.clone(),
56+
)
5157
}
5258
}
5359

implementations/rust/ockam/ockam_command/src/upgrade.rs

+27-28
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,45 @@
1+
use crate::{fmt_info, GlobalArgs, Terminal};
12
use clap::crate_version;
23
use colorful::Colorful;
34
use ockam_core::env::get_env_with_default;
45
use serde::Deserialize;
56
use std::env;
6-
use tokio::runtime::Builder;
77

88
#[derive(Deserialize)]
9-
struct UpgradeFile {
10-
upgrade_message: Option<String>,
11-
upgrade_message_macos: Option<String>,
9+
pub struct UpgradeFile {
10+
#[serde(default = "default_upgrade_message")]
11+
pub upgrade_message: String,
12+
#[serde(default = "default_upgrade_message_macos")]
13+
pub upgrade_message_macos: String,
1214
}
1315

14-
pub fn check_if_an_upgrade_is_available() {
15-
if !upgrade_check_is_disabled() {
16-
// check if a new version has been released
17-
Builder::new_current_thread()
18-
.enable_all()
19-
.build()
20-
.unwrap()
21-
.block_on(check());
22-
}
16+
fn default_upgrade_message() -> String {
17+
"Check out the latest release at https://github.com/build-trust/ockam/releases".to_string()
18+
}
19+
20+
fn default_upgrade_message_macos() -> String {
21+
"Run the following command to upgrade the Ockam Command: 'brew install build-trust/ockam/ockam'"
22+
.to_string()
2323
}
2424

25-
async fn check() {
25+
pub fn check_if_an_upgrade_is_available(global_args: &GlobalArgs) {
26+
if upgrade_check_is_disabled() || global_args.test_argument_parser {
27+
return;
28+
}
2629
let url = format!(
2730
"https://github.com/build-trust/ockam/releases/download/ockam_v{}/upgrade.json",
2831
crate_version!()
2932
);
30-
let resp = reqwest::get(url).await;
31-
32-
if let Ok(r) = resp {
33-
if let Ok(upgrade) = r.json::<UpgradeFile>().await {
34-
if let Some(message) = upgrade.upgrade_message {
35-
eprintln!("\n{}", message.yellow());
36-
37-
if cfg!(target_os = "macos") {
38-
if let Some(message) = upgrade.upgrade_message_macos {
39-
eprintln!("\n{}", message.yellow());
40-
}
41-
}
42-
43-
eprintln!();
33+
if let Ok(r) = reqwest::blocking::get(url) {
34+
if let Ok(f) = r.json::<UpgradeFile>() {
35+
let terminal = Terminal::from(global_args);
36+
terminal
37+
.write_line(fmt_info!("{}", f.upgrade_message))
38+
.unwrap();
39+
if cfg!(target_os = "macos") {
40+
terminal
41+
.write_line(fmt_info!("{}", f.upgrade_message_macos))
42+
.unwrap();
4443
}
4544
}
4645
}

0 commit comments

Comments
 (0)