about summary refs log tree commit diff stats
path: root/crates/yt/src/commands
diff options
context:
space:
mode:
authorBenedikt Peetz <benedikt.peetz@b-peetz.de>2025-07-24 16:20:34 +0200
committerBenedikt Peetz <benedikt.peetz@b-peetz.de>2025-07-24 16:20:34 +0200
commita9fddbeebf428eb57c60afab96fbbd38629a636e (patch)
tree480d9c1ae6f43598bfff7e4a29a378691b0a7508 /crates/yt/src/commands
parentfix(crates/yt/{commands/playlist,videos/format_video}): Correctly calculate w... (diff)
downloadyt-a9fddbeebf428eb57c60afab96fbbd38629a636e.zip
fix(treewide): Use `json_try_get!` instead of `json.get(..).map(|| ..)`
`json.get` will return `Some(Value::Null)` if the json key exists but
has been set to `null`. This is obviously not what we want, and as such
we also need to check that the value is not null, before calling map.
The `json_try_get!` macro does exactly that.
Diffstat (limited to 'crates/yt/src/commands')
-rw-r--r--crates/yt/src/commands/select/implm/standalone/add.rs17
-rw-r--r--crates/yt/src/commands/subscriptions/implm.rs16
-rw-r--r--crates/yt/src/commands/update/implm/updater.rs7
-rw-r--r--crates/yt/src/commands/videos/implm.rs4
4 files changed, 18 insertions, 26 deletions
diff --git a/crates/yt/src/commands/select/implm/standalone/add.rs b/crates/yt/src/commands/select/implm/standalone/add.rs
index ec32039..dd11cb4 100644
--- a/crates/yt/src/commands/select/implm/standalone/add.rs
+++ b/crates/yt/src/commands/select/implm/standalone/add.rs
@@ -17,7 +17,7 @@ use crate::{
 use anyhow::{Context, Result, bail};
 use log::{error, warn};
 use url::Url;
-use yt_dlp::{YoutubeDL, info_json::InfoJson, json_cast, json_get};
+use yt_dlp::{YoutubeDL, info_json::InfoJson, json_cast, json_get, json_try_get};
 
 #[allow(clippy::too_many_lines)]
 pub(crate) async fn add(
@@ -55,14 +55,10 @@ pub(crate) async fn add(
                         .await
                         .with_context(|| format!(
                             "Failed to format hash of video '{}' as short hash",
-                            entry
-                                .get("url")
-                                .map_or("<Unknown video Url>".to_owned(), ToString::to_string)
+                            json_try_get!(entry, "url", as_str).unwrap_or("<Unknown video Url>")
                         ))?,
-                    entry.get("title").map_or(String::new(), |title| format!(
-                        " (\"{}\")",
-                        json_cast!(title, as_str)
-                    ))
+                    json_try_get!(entry, "title", as_str)
+                        .map_or(String::new(), |title| format!(" (\"{title}\")"))
                 );
                 return Ok(());
             }
@@ -82,7 +78,7 @@ pub(crate) async fn add(
             .extract_info(&url, false, true)
             .with_context(|| format!("Failed to fetch entry for url: '{url}'"))?;
 
-        match entry.get("_type").map(|val| json_cast!(val, as_str)) {
+        match json_try_get!(entry, "_type", as_str) {
             Some("video") => {
                 add_entry(app, entry).await?;
                 if start.is_some() || stop.is_some() {
@@ -92,8 +88,7 @@ pub(crate) async fn add(
                 }
             }
             Some("playlist") => {
-                if let Some(entries) = entry.get("entries") {
-                    let entries = json_cast!(entries, as_array);
+                if let Some(entries) = json_try_get!(entry, "entries", as_array) {
                     let start = start.unwrap_or(0);
                     let stop = stop.unwrap_or(entries.len() - 1);
 
diff --git a/crates/yt/src/commands/subscriptions/implm.rs b/crates/yt/src/commands/subscriptions/implm.rs
index 3051522..311ae2b 100644
--- a/crates/yt/src/commands/subscriptions/implm.rs
+++ b/crates/yt/src/commands/subscriptions/implm.rs
@@ -16,7 +16,7 @@ use tokio::{
     io::{AsyncBufRead, AsyncBufReadExt, BufReader, stdin},
 };
 use url::Url;
-use yt_dlp::{json_cast, json_get, options::YoutubeDLOptions};
+use yt_dlp::{json_cast, json_get, json_try_get, options::YoutubeDLOptions};
 
 impl SubscriptionCommand {
     pub(crate) async fn implm(self, app: &App) -> Result<()> {
@@ -27,10 +27,10 @@ impl SubscriptionCommand {
                 no_check,
             } => {
                 let mut ops = Operations::new("main: subscribe");
-                subscribe(&app, name, url, no_check, &mut ops)
+                subscribe(app, name, url, no_check, &mut ops)
                     .await
                     .context("Failed to add a subscription")?;
-                ops.commit(&app).await?;
+                ops.commit(app).await?;
             }
             SubscriptionCommand::Remove { name } => {
                 let mut present_subscriptions = Subscriptions::get(app).await?;
@@ -46,14 +46,14 @@ impl SubscriptionCommand {
                     .with_context(|| format!("Failed to unsubscribe from {name:?}"))?;
             }
             SubscriptionCommand::List {} => {
-                let all_subs = Subscriptions::get(&app).await?;
+                let all_subs = Subscriptions::get(app).await?;
 
                 for (key, val) in all_subs.0 {
                     println!("{}: '{}'", key, val.url);
                 }
             }
             SubscriptionCommand::Export {} => {
-                let all_subs = Subscriptions::get(&app).await?;
+                let all_subs = Subscriptions::get(app).await?;
                 for val in all_subs.0.values() {
                     println!("{}", val.url);
                 }
@@ -66,9 +66,9 @@ impl SubscriptionCommand {
                 if let Some(file) = file {
                     let f = File::open(file).await?;
 
-                    import(&app, BufReader::new(f), force, no_check).await?;
+                    import(app, BufReader::new(f), force, no_check).await?;
                 } else {
-                    import(&app, BufReader::new(stdin()), force, no_check).await?;
+                    import(app, BufReader::new(stdin()), force, no_check).await?;
                 }
             }
         }
@@ -215,7 +215,7 @@ async fn actual_subscribe(
 
         let info = yt_dlp.extract_info(&url, false, false)?;
 
-        if info.get("_type").map(|v| json_cast!(v, as_str)) == Some("playlist") {
+        if json_try_get!(info, "_type", as_str) == Some("playlist") {
             json_get!(info, "title", as_str).to_owned()
         } else {
             bail!("The url ('{}') does not represent a playlist!", &url)
diff --git a/crates/yt/src/commands/update/implm/updater.rs b/crates/yt/src/commands/update/implm/updater.rs
index 5969d54..3e4bc85 100644
--- a/crates/yt/src/commands/update/implm/updater.rs
+++ b/crates/yt/src/commands/update/implm/updater.rs
@@ -6,8 +6,7 @@ use log::{Level, debug, error, log_enabled};
 use tokio::io::{AsyncWriteExt, stderr};
 use tokio_util::task::LocalPoolHandle;
 use yt_dlp::{
-    info_json::InfoJson, json_cast, options::YoutubeDLOptions, process_ie_result,
-    python_error::PythonError,
+    info_json::InfoJson, json_cast, json_try_get, options::YoutubeDLOptions, process_ie_result, python_error::PythonError
 };
 
 use crate::{
@@ -93,9 +92,7 @@ impl Updater {
                         .with_context(|| format!("Failed to get playlist '{}'.", sub.name))?;
 
                     let empty = vec![];
-                    let entries = info
-                        .get("entries")
-                        .map_or(&empty, |val| json_cast!(val, as_array));
+                    let entries = json_try_get!(info, "entries", as_array).unwrap_or(&empty);
 
                     let valid_entries: Vec<(Subscription, InfoJson)> = entries
                         .iter()
diff --git a/crates/yt/src/commands/videos/implm.rs b/crates/yt/src/commands/videos/implm.rs
index 7d13ceb..7c2ec8a 100644
--- a/crates/yt/src/commands/videos/implm.rs
+++ b/crates/yt/src/commands/videos/implm.rs
@@ -42,12 +42,12 @@ impl VideosCommand {
                 }
             }
             VideosCommand::Info { hash, format } => {
-                let video = hash.realize(&app, None).await?.get_with_app(&app).await?;
+                let video = hash.realize(app, None).await?.get_with_app(app).await?;
 
                 print!(
                     "{}",
                     &video
-                        .to_info_display(&app, format)
+                        .to_info_display(app, format)
                         .await
                         .context("Failed to format video")?
                 );