Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add check updates command #577

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,13 @@ dirs = "5.0.1"
serde = { version = "1.0.210", features = ["derive"] }
serde_json = "1.0.128"
reqwest = { version = "0.12.8", default-features = false, features = [
"rustls-tls", "json"
"rustls-tls",
"json",
] }
chrono = { version = "0.4.38", features = ["serde"], default-features = false }
chrono = { version = "0.4.38", features = [
"serde",
"clock",
], default-features = false }
graphql_client = { version = "0.14.0", features = ["reqwest-rustls"] }
paste = "1.0.15"
tokio = { version = "1.40.0", features = ["full"] }
Expand Down
34 changes: 34 additions & 0 deletions src/commands/check_updates.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
use crate::check_update;

use super::*;
use serde_json::json;

/// Test the update check
coffee-cup marked this conversation as resolved.
Show resolved Hide resolved
#[derive(Parser)]
pub struct Args {}

pub async fn command(_args: Args, json: bool) -> Result<()> {
alexng353 marked this conversation as resolved.
Show resolved Hide resolved
let mut configs = Configs::new()?;

if json {
let result = configs.check_update(true).await;

let json = json!({
"latest_version": result.ok().flatten().as_ref(),
"current_version": env!("CARGO_PKG_VERSION"),
});

println!("{}", serde_json::to_string_pretty(&json)?);

return Ok(());
}

let is_latest = check_update!(configs, true);
if is_latest {
println!(
"You are on the latest version of the CLI, v{}",
env!("CARGO_PKG_VERSION")
);
}
Ok(())
}
5 changes: 4 additions & 1 deletion src/commands/init.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::fmt::Display;

use crate::util::prompt::prompt_select;
use crate::{check_update, util::prompt::prompt_select};

use super::{queries::user_projects::UserProjectsMeTeamsEdgesNode, *};

Expand All @@ -15,6 +15,9 @@ pub struct Args {

pub async fn command(args: Args, _json: bool) -> Result<()> {
let mut configs = Configs::new()?;

check_update!(configs);

let client = GQLClient::new_authorized(&configs)?;

let vars = queries::user_projects::Variables {};
Expand Down
4 changes: 4 additions & 0 deletions src/commands/link.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use colored::*;
use std::fmt::Display;

use crate::{
check_update,
errors::RailwayError,
util::prompt::{fake_select, prompt_options, prompt_options_skippable},
};
Expand Down Expand Up @@ -37,6 +38,9 @@ pub struct Args {

pub async fn command(args: Args, _json: bool) -> Result<()> {
let mut configs = Configs::new()?;

check_update!(configs);

let client = GQLClient::new_authorized(&configs)?;
let me = post_graphql::<queries::UserProjects, _>(
&client,
Expand Down
2 changes: 2 additions & 0 deletions src/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,5 @@ pub mod up;
pub mod variables;
pub mod volume;
pub mod whoami;

pub mod check_updates;
7 changes: 6 additions & 1 deletion src/commands/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use anyhow::bail;
use is_terminal::IsTerminal;

use crate::{
check_update,
controllers::{
environment::get_matched_environment,
project::{ensure_project_and_environment_exist, get_project},
Expand Down Expand Up @@ -73,7 +74,11 @@ async fn get_service(
}

pub async fn command(args: Args, _json: bool) -> Result<()> {
let configs = Configs::new()?;
// only needs to be mutable for the update check
let mut configs = Configs::new()?;
check_update!(configs);
let configs = configs; // so we make it immutable again

let client = GQLClient::new_authorized(&configs)?;
let linked_project = configs.get_linked_project().await?;

Expand Down
52 changes: 52 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@ use std::{
};

use anyhow::{Context, Result};
use chrono::{DateTime, Utc};
use colored::Colorize;
use inquire::ui::{Attributes, RenderConfig, StyleSheet, Styled};
use is_terminal::IsTerminal;
use serde::{Deserialize, Serialize};

use crate::{
Expand Down Expand Up @@ -42,6 +44,7 @@ pub struct RailwayUser {
pub struct RailwayConfig {
pub projects: BTreeMap<String, LinkedProject>,
pub user: RailwayUser,
pub last_update_check: Option<DateTime<Utc>>,
}

#[derive(Debug)]
Expand All @@ -57,6 +60,13 @@ pub enum Environment {
Dev,
}

#[derive(Deserialize)]
struct GithubApiRelease {
tag_name: String,
}

const GITHUB_API_RELEASE_URL: &str = "https://api.github.com/repos/railwayapp/cli/releases/latest";

impl Configs {
pub fn new() -> Result<Self> {
let environment = Self::get_environment_id();
Expand All @@ -79,6 +89,7 @@ impl Configs {
RailwayConfig {
projects: BTreeMap::new(),
user: RailwayUser { token: None },
last_update_check: None,
}
});

Expand All @@ -95,6 +106,7 @@ impl Configs {
root_config: RailwayConfig {
projects: BTreeMap::new(),
user: RailwayUser { token: None },
last_update_check: None,
},
})
}
Expand All @@ -103,6 +115,7 @@ impl Configs {
self.root_config = RailwayConfig {
projects: BTreeMap::new(),
user: RailwayUser { token: None },
last_update_check: None,
};
Ok(())
}
Expand Down Expand Up @@ -313,4 +326,43 @@ impl Configs {

Ok(())
}

pub async fn check_update(&mut self, force: bool) -> anyhow::Result<Option<String>> {
// outputting would break json output on CI
if !std::io::stdout().is_terminal() && !force {
return Ok(None);
}

let should_update = if let Some(last_update_check) = self.root_config.last_update_check {
Utc::now().date_naive() != last_update_check.date_naive() || force
} else {
true
};

if !should_update {
return Ok(None);
}

let client = reqwest::Client::new();
let response = client
.get(GITHUB_API_RELEASE_URL)
.header("User-Agent", "railwayapp")
.send()
.await?;

self.root_config.last_update_check = Some(Utc::now());
self.write()
.context("Failed to save time since last update check")?;

let response = response.json::<GithubApiRelease>().await?;
let latest_version = response.tag_name.trim_start_matches('v');

let current_version = env!("CARGO_PKG_VERSION");

if latest_version == current_version {
return Ok(None);
}

Ok(Some(latest_version.to_owned()))
}
}
22 changes: 22 additions & 0 deletions src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,25 @@ macro_rules! interact_or {
}
};
}

#[macro_export]
macro_rules! check_update {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why does this have to be a macro instead of just a function? In general I'd prefer to avoid macros unless absolutely necessary.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's a macro because I can overload the call signature of it to default the second parameter to false, but I can make it into a function if you want.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think a function is preferred here for simplicity. If you want to avoid having to provided false as the second parameter, we can have a check_update_command function that passed false

($obj:expr, $force:expr) => {{
let result = $obj.check_update($force).await;

if let Ok(Some(latest_version)) = result {
println!(
"{} v{} visit {} for more info",
"New version available:".green().bold(),
latest_version.yellow(),
"https://docs.railway.com/guides/cli".purple(),
);
false
} else {
true
}
}};
($configs:expr) => {{
check_update!($configs, false);
}};
}
21 changes: 20 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ mod macros;
#[derive(Parser)]
#[clap(author, version, about, long_about = None)]
#[clap(propagate_version = true)]
// #[clap(author, about, long_about = None)]
pub struct Args {
#[clap(subcommand)]
command: Commands,
Expand Down Expand Up @@ -58,11 +59,29 @@ commands_enum!(
variables,
whoami,
volume,
redeploy
redeploy,
check_updates
);

#[tokio::main]
async fn main() -> Result<()> {
// intercept the args
{
let args: Vec<String> = std::env::args().collect();

let flags: Vec<String> = vec!["--version", "-V", "-h", "--help", "help"]
.into_iter()
.map(|s| s.to_string())
.collect();

let check_version = args.into_iter().any(|arg| flags.contains(&arg));

if check_version {
let mut configs = Configs::new()?;
check_update!(configs, false);
}
}

let cli = Args::parse();

match Commands::exec(cli).await {
Expand Down
Loading