Skip to content
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
53 changes: 53 additions & 0 deletions 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 Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ webbrowser = "1.0"

[dev-dependencies]
mockito = "1.5"
serial_test = "3.3"
tempfile = "3.8"
tokio-test = "0.4"

Expand Down
31 changes: 31 additions & 0 deletions docs/cli-commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ This document contains the help content for the `ricochet` command-line program.
* [`ricochet invoke`↴](#ricochet-invoke)
* [`ricochet config`↴](#ricochet-config)
* [`ricochet init`↴](#ricochet-init)
* [`ricochet item`↴](#ricochet-item)
* [`ricochet item toml`↴](#ricochet-item-toml)

## `ricochet`

Expand All @@ -30,6 +32,7 @@ Ricochet CLI
* `invoke` — Invoke a task
* `config` — Show configuration
* `init` — Initialize a new Ricochet deployment
* `item` — Manage deployed content items

###### **Options:**

Expand Down Expand Up @@ -157,6 +160,34 @@ Initialize a new Ricochet deployment



## `ricochet item`

Manage deployed content items

**Usage:** `ricochet item <COMMAND>`

###### **Subcommands:**

* `toml` — Fetch the remote _ricochet.toml for an item



## `ricochet item toml`

Fetch the remote _ricochet.toml for an item

**Usage:** `ricochet item toml [OPTIONS] [ID]`

###### **Arguments:**

* `<ID>` — Content item ID (ULID). If not provided, will read from local _ricochet.toml

###### **Options:**

* `-p`, `--path <PATH>` — Path to _ricochet.toml file



<hr/>

<small><i>
Expand Down
57 changes: 53 additions & 4 deletions src/client.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
use crate::config::{Config, parse_server_url};
use anyhow::{Context, Result};
use colored::Colorize;
use reqwest::{Client, Response, StatusCode};
use ricochet_core::content::ContentItem;
use serde::de::DeserializeOwned;
use std::fs::read_to_string;
use std::path::Path;
use std::pin::Pin;
use std::task::{Context as TaskContext, Poll};
use std::{
fs::read_to_string,
path::Path,
pin::Pin,
task::{Context as TaskContext, Poll},
};
use tokio::io::{AsyncRead, ReadBuf};
use url::Url;

Expand Down Expand Up @@ -110,6 +113,29 @@ impl RicochetClient {
Ok(response.status() == StatusCode::OK)
}

/// Check if a key is expired and report if so
/// Use this as a pre-flight check for all API calls where appropriate
pub async fn preflight_key_check(&self) -> Result<()> {
match self.validate_key().await {
Ok(v) => {
if !v {
anyhow::bail!(
"{} Existing credentials are invalid or expired.",
"⚠".yellow()
);
} else {
Ok(())
}
}
Err(e) => {
anyhow::bail!(
"{} Failed to validate credential with error {e}",
"!".bright_red()
);
}
}
}

pub async fn list_items(&self) -> Result<Vec<serde_json::Value>> {
let mut url = self.base_url.clone();
url.set_path("/api/v0/user/items");
Expand Down Expand Up @@ -382,4 +408,27 @@ impl RicochetClient {

Ok(())
}

pub async fn get_ricochet_toml(&self, id: &str) -> Result<String> {
let mut url = self.base_url.clone();
url.set_path(&format!("/api/v0/content/{}/toml", id));

let response = self
.client
.get(url)
.header("Authorization", format!("Key {}", self.api_key))
.send()
.await?;

if !response.status().is_success() {
let error_text = response
.text()
.await
.unwrap_or_else(|_| "Unknown error".to_string());
anyhow::bail!("Failed to fetch ricochet.toml: {}", error_text)
}

let toml_content = response.text().await?;
Ok(toml_content)
}
}
1 change: 1 addition & 0 deletions src/commands/item/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod toml;
36 changes: 36 additions & 0 deletions src/commands/item/toml.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
use crate::{client::RicochetClient, config::Config};
use colored::Colorize;
use ricochet_core::content::ContentItem;
use std::{fs::read_to_string, path::PathBuf};

pub async fn get_toml(
config: &Config,
id: Option<String>,
path: Option<PathBuf>,
) -> anyhow::Result<()> {
let client = RicochetClient::new(config)?;
client.preflight_key_check().await?;

let id = match id {
Some(id) => id,
None => {
let toml_path = path.unwrap_or(PathBuf::from("_ricochet.toml"));
if !toml_path.exists() {
anyhow::bail!(
"{} Provide either an item ID or a path to a `_ricochet.toml` file.",
"⚠".yellow()
);
}
let toml = read_to_string(toml_path)?;
let item = ContentItem::from_toml(&toml)?;
let Some(id) = item.content.id else {
anyhow::bail!("Provided _ricochet.toml does not have an item ID")
};

id
}
};

println!("{}", client.get_ricochet_toml(&id).await?);
Ok(())
}
1 change: 1 addition & 0 deletions src/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ pub mod delete;
pub mod deploy;
pub mod init;
pub mod invoke;
pub mod item;
pub mod list;
22 changes: 22 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,11 +109,28 @@ enum Commands {
#[arg(long)]
dry_run: bool,
},
/// Manage deployed content items
Item {
#[command(subcommand)]
command: ItemCommands,
},
/// Generate markdown documentation (hidden command)
#[command(hide = true)]
GenerateDocs,
}

#[derive(Subcommand)]
enum ItemCommands {
/// Fetch the remote _ricochet.toml for an item
Toml {
/// Content item ID (ULID). If not provided, will read from local _ricochet.toml
id: Option<String>,
/// Path to _ricochet.toml file
#[arg(short = 'p', long)]
path: Option<std::path::PathBuf>,
},
}

#[tokio::main]
async fn main() -> Result<()> {
let cli = Cli::parse();
Expand Down Expand Up @@ -181,6 +198,11 @@ async fn main() -> Result<()> {
}) => {
commands::init::init_rico_toml(&path, overwrite, dry_run)?;
}
Some(Commands::Item { command }) => match command {
ItemCommands::Toml { id, path } => {
commands::item::toml::get_toml(&config, id, path).await?;
}
},
Some(Commands::GenerateDocs) => {
let markdown = clap_markdown::help_markdown::<Cli>();
println!("{}", markdown);
Expand Down
Loading