aboutsummaryrefslogtreecommitdiffstats
path: root/crates
diff options
context:
space:
mode:
Diffstat (limited to 'crates')
-rw-r--r--crates/mk_config/Cargo.toml33
-rw-r--r--crates/mk_config/src/generate.rs727
-rw-r--r--crates/mk_config/src/lib.rs19
-rw-r--r--crates/mk_config/src/parse.rs145
-rw-r--r--crates/yt/src/cli.rs60
-rw-r--r--crates/yt/src/config/def.rs127
-rw-r--r--crates/yt/src/config/mod.rs134
-rw-r--r--crates/yt/src/config/paths.rs2
-rw-r--r--crates/yt/src/config/support.rs161
-rw-r--r--crates/yt/src/main.rs45
10 files changed, 1136 insertions, 317 deletions
diff --git a/crates/mk_config/Cargo.toml b/crates/mk_config/Cargo.toml
new file mode 100644
index 0000000..b75c16c
--- /dev/null
+++ b/crates/mk_config/Cargo.toml
@@ -0,0 +1,33 @@
+# yt - A fully featured command line YouTube client
+#
+# Copyright (C) 2025 Benedikt Peetz <benedikt.peetz@b-peetz.de>
+# Copyright (C) 2025 uutils developers
+# SPDX-License-Identifier: MIT
+#
+# This file is part of Yt.
+#
+# You should have received a copy of the License along with this program.
+# If not, see <https://www.gnu.org/licenses/gpl-3.0.txt>.
+
+[package]
+name = "mk_config"
+authors.workspace = true
+license.workspace = true
+description = "config proc macro"
+version.workspace = true
+edition.workspace = true
+repository.workspace = true
+rust-version.workspace = true
+publish = false
+
+[lib]
+proc-macro = true
+
+[dependencies]
+prettyplease = "0.3.0"
+proc-macro2 = "1.0.107"
+quote = "1.0.47"
+syn = { version = "3.0.9", features = ["full"] }
+
+[lints]
+workspace = true
diff --git a/crates/mk_config/src/generate.rs b/crates/mk_config/src/generate.rs
new file mode 100644
index 0000000..30b560d
--- /dev/null
+++ b/crates/mk_config/src/generate.rs
@@ -0,0 +1,727 @@
+use std::iter;
+
+use proc_macro2::TokenStream as TokenStream2;
+use quote::{ToTokens, TokenStreamExt, format_ident, quote};
+use syn::{Attribute, Expr, Ident, Type};
+
+use crate::parse;
+
+#[derive(Debug)]
+pub(crate) struct Config {
+ name: Ident,
+ sections: Vec<ConfigSection>,
+ fields: Vec<ConfigField>,
+ imports: Vec<syn::Path>,
+}
+
+#[derive(Debug)]
+pub(crate) struct ConfigSection {
+ name: Vec<Ident>,
+ fields: Vec<ConfigField>,
+ is_public: bool,
+ documentation: Vec<Attribute>,
+}
+
+#[derive(Debug)]
+pub(crate) struct ConfigField {
+ name: Vec<Ident>,
+ default: Option<ConfigFieldDefault>,
+ ty: Type,
+ documentation: Vec<Attribute>,
+
+ /// Whether this config field was create to include the parent-child relation ships between
+ /// config sections.
+ is_section: bool,
+ is_public: bool,
+ finalizer: Option<Ident>,
+}
+
+#[derive(Debug)]
+pub(crate) struct ConfigFieldDefault {
+ default: Expr,
+ may_error: bool,
+}
+
+impl From<parse::FieldDefault> for ConfigFieldDefault {
+ fn from(value: parse::FieldDefault) -> Self {
+ Self {
+ default: value.default,
+ may_error: value.may_error,
+ }
+ }
+}
+
+impl ToTokens for ConfigFieldDefault {
+ fn to_tokens(&self, tokens: &mut TokenStream2) {
+ let Self { default, may_error } = self;
+ if *may_error {
+ tokens.extend(quote! {
+ #default?
+ });
+ } else {
+ tokens.extend(quote! {
+ #default
+ });
+ }
+ }
+}
+
+impl From<parse::ParseBase> for Config {
+ fn from(value: parse::ParseBase) -> Self {
+ let mut sections = vec![];
+ let mut new_fields = vec![];
+
+ value.fields.into_iter().for_each(|field| match field {
+ parse::ParsePart::Section { .. } => {
+ sections.extend(ConfigSection::from_parse_part(vec![], field.clone()));
+ new_fields.push(ConfigField::spawn_from_section(vec![], field));
+ }
+ parse::ParsePart::Field { .. } => {
+ new_fields.push(ConfigField::from_parse_part(vec![], field));
+ }
+ });
+
+ Self {
+ name: value.name,
+ sections,
+ fields: new_fields,
+ imports: value.imports,
+ }
+ }
+}
+
+impl ConfigSection {
+ fn from_parse_part(prefix: Vec<Ident>, value: parse::ParsePart) -> Vec<Self> {
+ if let parse::ParsePart::Section {
+ name,
+ fields,
+ documentation,
+ } = value
+ {
+ let new_name: Vec<_> = prefix.into_iter().chain(iter::once(name)).collect();
+
+ let mut sections = vec![];
+ let mut new_fields = vec![];
+
+ for field in fields {
+ match field {
+ parse::ParsePart::Section { .. } => {
+ sections.extend(Self::from_parse_part(new_name.clone(), field.clone()));
+ new_fields.push(ConfigField::spawn_from_section(new_name.clone(), field));
+ }
+ parse::ParsePart::Field { .. } => {
+ new_fields.push(ConfigField::from_parse_part(new_name.clone(), field));
+ }
+ }
+ }
+
+ sections.push(Self {
+ name: new_name,
+ fields: new_fields,
+ is_public: true,
+ documentation,
+ });
+
+ sections
+ } else {
+ unreachable!("Only called on sections")
+ }
+ }
+}
+
+impl ConfigField {
+ fn from_parse_part(prefix: Vec<Ident>, value: parse::ParsePart) -> Self {
+ if let parse::ParsePart::Field {
+ name,
+ ty,
+ default,
+ documentation,
+ finalizer,
+ } = value
+ {
+ let new_name = prefix.into_iter().chain(iter::once(name)).collect();
+
+ Self {
+ name: new_name,
+ default: default.map(Into::into),
+ ty,
+ is_section: false,
+ is_public: true,
+ documentation,
+ finalizer,
+ }
+ } else {
+ unreachable!("Only called on fields")
+ }
+ }
+
+ fn spawn_from_section(prefix: Vec<Ident>, field: parse::ParsePart) -> ConfigField {
+ if let parse::ParsePart::Section {
+ name,
+ documentation,
+ ..
+ } = field
+ {
+ let config_name = name_ident(&name);
+ let new_name = prefix.into_iter().chain(iter::once(name)).collect();
+
+ Self {
+ name: new_name,
+ default: None,
+ ty: syn::parse_quote!(#config_name),
+ is_section: true,
+ is_public: true,
+ documentation,
+ finalizer: None,
+ }
+ } else {
+ unreachable!("Should only be called, on Sections")
+ }
+ }
+}
+
+struct ConfDeser {
+ sections: Vec<ConfigSection>,
+ fields: Vec<ConfigField>,
+}
+
+impl From<&Config> for ConfDeser {
+ fn from(value: &Config) -> Self {
+ fn field_to_deser(field: &ConfigField) -> ConfigField {
+ let field_ty = field.ty.clone();
+
+ ConfigField {
+ name: field.name.clone(),
+ default: None,
+ documentation: field.documentation.clone(),
+ ty: if field.default.is_some() || field.is_section {
+ syn::parse_quote!(Option<#field_ty>)
+ } else {
+ // TODO: We could also accept this value here, and then throw an error later.
+ // But right now, we just use serde to complain to the user <2026-08-20>
+ field_ty
+ },
+ is_section: field.is_section,
+ is_public: false,
+ finalizer: None,
+ }
+ }
+
+ Self {
+ sections: value
+ .sections
+ .iter()
+ .map(|section| ConfigSection {
+ name: section.name.clone(),
+ fields: section.fields.iter().map(field_to_deser).collect(),
+ is_public: false,
+ documentation: section.documentation.clone(),
+ })
+ .collect(),
+ fields: value.fields.iter().map(field_to_deser).collect(),
+ }
+ }
+}
+
+impl ToTokens for ConfDeser {
+ fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
+ let Self { sections, fields } = self;
+
+ let serde = serde(false);
+ tokens.extend(quote! {
+ #serde
+ #[derive(Clone, Debug)]
+ pub(super) struct ConfDeser {
+ #(
+ #fields
+ )*
+ }
+ #(
+ #sections
+ )*
+ });
+ }
+}
+
+impl ToTokens for Config {
+ fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
+ let Self {
+ name,
+ sections,
+ fields,
+ imports,
+ } = self;
+
+ let serde = serde(true);
+ tokens.extend(quote! {
+ #(
+ use #imports;
+ )*
+
+ #[derive(Debug)]
+ #serde
+ pub(crate) struct #name {
+ #(
+ #fields
+ )*
+ }
+ });
+ tokens.append_all(sections.iter());
+
+ let default_config = generate_default_config(fields, sections);
+ let option_assign = generate_option_assign(fields, sections);
+ let option_finalizer = generate_option_finalizer(fields, sections);
+ let field_deser_assign: Vec<_> = fields
+ .iter()
+ .map(|field| field.field_assign_deser(&[]))
+ .collect();
+ let conf_deser = ConfDeser::from(self);
+ tokens.extend(quote! {
+ mod __inner {
+ #(
+ use #imports;
+ )*
+
+ #conf_deser
+ }
+
+ impl #name {
+ /// Parse the configuration from a config file at `config_file_path`.
+ ///
+ /// This will then also take the config overrides via `options` into consideration,
+ /// and finally run the finalizers, defined via the macro.
+ pub(crate) fn from_config_file(
+ config_file_path: &std::path::Path,
+ options: Vec<(Vec<String>, toml::Value)>
+ ) -> anyhow::Result<Self> {
+ use anyhow::Context;
+
+ let config: __inner::ConfDeser = toml::from_str(
+ &std::fs::read_to_string(config_file_path).unwrap_or(String::new()),
+ ).context("Failed to parse the config file as toml")?;
+
+ let mut base = Self {
+ #(
+ #field_deser_assign
+ )*
+ };
+
+ for (name, value) in options {
+ let name = name.join(".");
+
+ match name.as_str() {
+ #option_assign
+ other => anyhow::bail!("Option name '{other}' is not known")
+ }
+ }
+
+ // Run the finalizers
+ {
+ #option_finalizer
+ }
+
+ Ok(base)
+ }
+
+ /// Return the default configuration in semi TOML format, with it's doc comments appended
+ /// to the document.
+ ///
+ /// The default values, will be the pretty-printed rust defaults, so it's not
+ /// actually possible to parse it as TOML.
+ pub(crate) const fn config_doc() -> &'static str {
+ #default_config
+ }
+ }
+ });
+ }
+}
+
+impl ToTokens for ConfigSection {
+ fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
+ fn field_to_default(field: &ConfigField) -> TokenStream2 {
+ let ConfigField {
+ name,
+ default,
+ is_section,
+ ty,
+ ..
+ } = field;
+
+ let last_name = name.last().expect("Exists");
+ if let Some(default) = default {
+ quote! {
+ #last_name: #default,
+ }
+ } else if *is_section {
+ quote! {
+ #last_name: #ty::default()?,
+ }
+ } else {
+ let msg = format!(
+ "No default value for field '{last_name}'. Auto defaults are not yet implemented."
+ );
+ quote! {
+ #last_name: {compile_error!(#msg)},
+ }
+ }
+ }
+
+ let Self {
+ name,
+ fields,
+ is_public,
+ documentation,
+ } = self;
+ let last_name = name_ident(name.last().expect("Exists"));
+
+ let default_fields: Vec<_> = fields.iter().map(field_to_default).collect();
+ let from_deser_fields: Vec<_> = fields
+ .iter()
+ .map(|field| field.field_assign_deser(name))
+ .collect();
+
+ let vis = vis(*is_public);
+ let serde = serde(*is_public);
+ tokens.extend(quote! {
+ #serde
+ #[derive(Clone, Debug)]
+ #(#documentation)*
+ #vis struct #last_name {
+ #(
+ #fields
+ )*
+ }
+ });
+ if *is_public {
+ tokens.extend(quote! {
+ impl #last_name {
+ fn default() -> anyhow::Result<Self> {
+ Ok(Self {
+ #(
+ #default_fields
+ )*
+ })
+ }
+ fn from_inner(from: Option<__inner::#last_name>, config: __inner::ConfDeser) -> anyhow::Result<Self> {
+ if let Some(from) = from {
+ Ok(Self {
+ #(
+ #from_deser_fields
+ )*
+ })
+ } else {
+ Self::default()
+ }
+ }
+ }
+ });
+ }
+ }
+}
+
+impl ConfigField {
+ fn field_assign_deser(&self, prefix: &[Ident]) -> TokenStream2 {
+ let ConfigField {
+ name,
+ is_section,
+ default,
+ ty,
+ ..
+ } = self;
+
+ let base = if prefix.is_empty() {
+ quote! {
+ config.#(#name).*
+ }
+ } else {
+ let mut new = name.clone();
+ for p in prefix {
+ let next = new.remove(0);
+ assert_eq!(p, &next);
+ }
+ quote! {
+ from.#(#new).*
+ }
+ };
+
+ let last_name = name.last().expect("Exists");
+
+ if *is_section {
+ quote! {
+ #last_name: #ty::from_inner(#base.clone(), config.clone())?,
+ }
+ } else {
+ match default {
+ Some(default) => {
+ quote! {
+ #last_name: {
+ match #base {
+ Some(val) => val,
+ None => #default,
+ }
+ },
+ }
+ }
+ None => {
+ // NOTE: When there is no default value, we also don't accept one in the __inner
+ // part. <2026-08-20>
+ quote! {
+ #last_name: #base,
+ }
+ }
+ }
+ }
+ }
+}
+impl ToTokens for ConfigField {
+ fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
+ let Self {
+ name,
+ ty,
+ is_public,
+ documentation,
+ ..
+ } = self;
+ let last_name = name.last().expect("Exists");
+
+ let vis = vis(*is_public);
+ tokens.extend(quote! {
+ #(#documentation)*
+ #vis #last_name: #ty,
+ });
+ }
+}
+
+fn name_ident(name: &Ident) -> Ident {
+ let mut name: Vec<_> = name.to_string().chars().collect();
+ name[0] = name[0].to_ascii_uppercase();
+
+ format_ident!("{}Config", name.into_iter().collect::<String>())
+}
+fn vis(is_public: bool) -> TokenStream2 {
+ if is_public {
+ quote! {pub(crate)}
+ } else {
+ quote! {pub(super)}
+ }
+}
+fn serde(is_public: bool) -> TokenStream2 {
+ if is_public {
+ quote! {
+ #[derive(serde::Serialize, serde::Deserialize)]
+ }
+ } else {
+ quote! {
+ #[derive(serde::Deserialize)]
+ }
+ }
+ // quote! {}
+}
+
+fn generate_option_assign(fields: &[ConfigField], sections: &[ConfigSection]) -> TokenStream2 {
+ fn name_str(name: &[Ident]) -> String {
+ name.iter()
+ .map(ToString::to_string)
+ .collect::<Vec<_>>()
+ .join(".")
+ }
+ fn value(ty: &Type) -> TokenStream2 {
+ let ty_str = ty.to_token_stream().to_string();
+
+ quote! {
+ {
+ use serde::Deserialize;
+
+ let value_str = value.to_string();
+ let deserializer = toml::de::ValueDeserializer::parse(&value_str)
+ .with_context(|| format!("Failed to parse value for option override '{name}' as '{}'", #ty_str))?;
+ <#ty>::deserialize(deserializer).context("Failed to deserialize default value for '{name}'")?
+ }
+ }
+ }
+
+ fn mk_field(field: &ConfigField) -> TokenStream2 {
+ let ConfigField { name, ty, .. } = field;
+
+ let name_str = name_str(name);
+ let value = value(ty);
+
+ quote! {
+ #name_str => base.#(#name).* = #value,
+ }
+ }
+ fn mk_section(section: &ConfigSection) -> TokenStream2 {
+ let ConfigSection { name, fields, .. } = section;
+
+ let name_str = name_str(name);
+ let fields: Vec<_> = fields.iter().map(mk_field).collect();
+ let value = {
+ let last_name = name.last().expect("to exist");
+ let ty = name_ident(last_name);
+ let ty: Type = syn::parse_quote! {#ty};
+
+ value(&ty)
+ };
+
+ quote! {
+ #name_str => base.#(#name).* = #value,
+ #(
+ #fields
+ )*
+ }
+ }
+
+ let fields: Vec<_> = fields.iter().map(mk_field).collect();
+ let sections: Vec<_> = sections.iter().map(mk_section).collect();
+
+ quote! {
+ #(
+ #fields
+ )*
+ #(
+ #sections
+ )*
+ }
+}
+fn generate_option_finalizer(fields: &[ConfigField], sections: &[ConfigSection]) -> TokenStream2 {
+ fn mk_field(field: &ConfigField) -> TokenStream2 {
+ let ConfigField {
+ name, finalizer, ..
+ } = field;
+
+ match finalizer {
+ Some(finalizer) => {
+ let context_msg = format!(
+ "While running the finalizer for config value '{}'",
+ name.iter()
+ .map(ToString::to_string)
+ .collect::<Vec<_>>()
+ .join(".")
+ );
+
+ quote! {
+ #finalizer(&base.#(#name).*).context(#context_msg)?;
+ }
+ }
+ None => quote! {},
+ }
+ }
+ fn mk_section(section: &ConfigSection) -> TokenStream2 {
+ let ConfigSection { fields, .. } = section;
+
+ let fields: Vec<_> = fields.iter().map(mk_field).collect();
+ quote! {
+ #(
+ #fields
+ )*
+ }
+ }
+ let fields: Vec<_> = fields.iter().map(mk_field).collect();
+ let sections: Vec<_> = sections.iter().map(mk_section).collect();
+
+ quote! {
+ #(
+ #fields
+ )*
+ #(
+ #sections
+ )*
+ }
+}
+
+fn generate_default_config(fields: &[ConfigField], sections: &[ConfigSection]) -> String {
+ fn mk_doc_comment(attr: &Attribute) -> String {
+ let comment = match &attr.meta {
+ syn::Meta::Path(_) => todo!(),
+ syn::Meta::List(_) => todo!(),
+ syn::Meta::NameValue(meta_name_value) => &meta_name_value.value,
+ };
+
+ let comment = comment.to_token_stream().to_string();
+ let comment = comment.trim_matches('\"').trim();
+ format!("# {comment}")
+ }
+
+ fn mk_field(field: &ConfigField) -> Option<String> {
+ let ConfigField {
+ name,
+ default,
+ documentation,
+ is_section,
+ ..
+ } = field;
+
+ let documentation = documentation.iter().map(mk_doc_comment).collect::<Vec<_>>();
+
+ let last_name = name.last().expect("to exist");
+ if let Some(default) = default {
+ let default = {
+ let file = syn::parse2::<syn::File>(quote::quote! {
+ fn deleteme(){
+ #default
+ }
+ })
+ .expect("The default value is valid rust code, and should be parsable");
+
+ {
+ let mut str = prettyplease::unparse(&file);
+
+ // remove the outer function
+ str = str.replace("fn deleteme() {\n", "");
+
+ if let Some(pos) = str.rfind("\n}\n") {
+ str.replace_range(pos..pos + 3, "");
+ }
+
+ // remove the function indent
+ str = str
+ .lines()
+ .map(|line| if line.len() >= 4 { &line[4..] } else { line })
+ .collect::<Vec<_>>()
+ .join("\n");
+
+ str
+ }
+ };
+
+ Some(format!(
+ "{}{}{} = {}\n",
+ documentation.join("\n"),
+ if documentation.is_empty() { "" } else { "\n" },
+ last_name,
+ default
+ ))
+ } else if *is_section {
+ None
+ } else {
+ todo!("no default fields, to yet supported")
+ }
+ }
+ fn mk_section(section: &ConfigSection) -> String {
+ let ConfigSection {
+ fields,
+ name,
+ documentation,
+ ..
+ } = section;
+
+ let documentation = documentation.iter().map(mk_doc_comment).collect::<Vec<_>>();
+ let fields: Vec<_> = fields.iter().filter_map(mk_field).collect();
+ let name = name.iter().map(ToString::to_string).collect::<Vec<_>>();
+
+ format!(
+ "{}{}[{}]\n{}\n",
+ documentation.join("\n"),
+ if documentation.is_empty() { "" } else { "\n" },
+ name.join("."),
+ fields.join("\n")
+ )
+ }
+ let fields: Vec<_> = fields.iter().filter_map(mk_field).collect();
+ let sections: Vec<_> = sections.iter().map(mk_section).collect();
+
+ format!(
+ "{}\n",
+ format!("{}{}", fields.join("\n"), sections.join("\n")).trim()
+ )
+}
diff --git a/crates/mk_config/src/lib.rs b/crates/mk_config/src/lib.rs
new file mode 100644
index 0000000..0686b27
--- /dev/null
+++ b/crates/mk_config/src/lib.rs
@@ -0,0 +1,19 @@
+use proc_macro::TokenStream;
+use quote::quote;
+use syn::parse_macro_input;
+
+use crate::parse::ParseBase;
+
+mod generate;
+mod parse;
+
+#[proc_macro]
+pub fn mk_config(input: TokenStream) -> TokenStream {
+ // eprintln!("{}", input);
+ let parsed = parse_macro_input!(input as ParseBase);
+
+ let config = generate::Config::from(parsed);
+ let expanded = quote! {#config};
+
+ TokenStream::from(expanded)
+}
diff --git a/crates/mk_config/src/parse.rs b/crates/mk_config/src/parse.rs
new file mode 100644
index 0000000..c48aef6
--- /dev/null
+++ b/crates/mk_config/src/parse.rs
@@ -0,0 +1,145 @@
+use syn::parse::{Parse, ParseStream, Result};
+use syn::token::Brace;
+use syn::{Attribute, Expr, Ident, Token, Type, braced, bracketed};
+
+#[derive(Debug)]
+pub(crate) struct ParseBase {
+ pub(crate) name: Ident,
+ pub(crate) fields: Vec<ParsePart>,
+ pub(crate) imports: Vec<syn::Path>,
+}
+
+#[derive(Clone, Debug)]
+#[expect(clippy::large_enum_variant)]
+pub(crate) enum ParsePart {
+ Section {
+ name: Ident,
+ fields: Vec<ParsePart>,
+ documentation: Vec<Attribute>,
+ },
+ Field {
+ name: Ident,
+ ty: Type,
+ default: Option<FieldDefault>,
+ documentation: Vec<Attribute>,
+ finalizer: Option<Ident>,
+ },
+}
+
+#[derive(Clone, Debug)]
+pub(crate) struct FieldDefault {
+ pub(crate) default: Expr,
+ pub(crate) may_error: bool,
+}
+
+impl Parse for FieldDefault {
+ fn parse(input: ParseStream<'_>) -> Result<Self> {
+ let lookahead = input.lookahead1();
+ let (may_error, expr) = if lookahead.peek(Token![try]) {
+ input.parse::<Token![try]>()?;
+ (true, input.parse()?)
+ } else {
+ (false, input.parse()?)
+ };
+
+ Ok(Self {
+ default: expr,
+ may_error,
+ })
+ }
+}
+
+impl Parse for ParsePart {
+ fn parse(input: ParseStream<'_>) -> Result<Self> {
+ let documentation = input.call(Attribute::parse_outer)?;
+
+ let name = input.parse()?;
+ input.parse::<Token![:]>()?;
+
+ let lookahead = input.lookahead1();
+ if lookahead.peek(Brace) {
+ let content;
+ braced!(content in input);
+ let fields = content
+ .parse_terminated(ParsePart::parse, Token![,])?
+ .into_iter()
+ .collect();
+
+ Ok(Self::Section {
+ name,
+ fields,
+ documentation,
+ })
+ } else {
+ let ty = input.parse()?;
+
+ let lookahead = input.lookahead1();
+ let mut default = None;
+ let mut finalizer = None;
+
+ if lookahead.peek(Token![=>]) {
+ input.parse::<Token![=>]>()?;
+ finalizer = Some(input.parse::<Ident>()?);
+
+ let lookahead = input.lookahead1();
+ if !lookahead.peek(Token![,]) {
+ return Err(lookahead.error());
+ }
+ } else if lookahead.peek(Token![=]) {
+ input.parse::<Token![=]>()?;
+ default = Some(input.parse()?);
+
+ let lookahead = input.lookahead1();
+ if lookahead.peek(Token![=>]) {
+ input.parse::<Token![=>]>()?;
+ finalizer = Some(input.parse::<Ident>()?);
+
+ let lookahead = input.lookahead1();
+ if !lookahead.peek(Token![,]) {
+ return Err(lookahead.error());
+ }
+ }
+ } else if lookahead.peek(Token![,]) {
+ // leave the `,` so that the `parse_terminated` can remove it
+ } else {
+ return Err(lookahead.error());
+ }
+
+ Ok(Self::Field {
+ name,
+ ty,
+ default,
+ documentation,
+ finalizer,
+ })
+ }
+ }
+}
+
+impl Parse for ParseBase {
+ fn parse(input: ParseStream<'_>) -> Result<Self> {
+ input.parse::<Token![use]>()?;
+ let content;
+ bracketed!(content in input);
+ let imports = content
+ .parse_terminated(syn::Path::parse, Token![;])?
+ .into_iter()
+ .collect();
+
+ input.parse::<Token![struct]>()?;
+ let name: Ident = input.parse()?;
+
+ let content;
+ braced!(content in input);
+ let fields = content
+ .parse_terminated(ParsePart::parse, Token![,])?
+ .into_iter()
+ .collect();
+
+ Ok(ParseBase {
+ name,
+ fields,
+ imports,
+ })
+ }
+}
diff --git a/crates/yt/src/cli.rs b/crates/yt/src/cli.rs
index dbdcdd1..45783bf 100644
--- a/crates/yt/src/cli.rs
+++ b/crates/yt/src/cli.rs
@@ -9,8 +9,9 @@
// You should have received a copy of the License along with this program.
// If not, see <https://www.gnu.org/licenses/gpl-3.0.txt>.
-use std::path::PathBuf;
+use std::{path::PathBuf, str::FromStr};
+use anyhow::bail;
use clap::{ArgAction, Parser};
use crate::commands::Command;
@@ -33,19 +34,6 @@ pub(crate) struct CliArgs {
#[arg(long, short, action=ArgAction::SetTrue, default_value_t = false)]
pub(crate) no_migrate_db: bool,
- /// Display colors [defaults to true, if the config file has no value]
- #[arg(long, short = 'C')]
- pub(crate) color: Option<bool>,
-
- /// Set the path to the videos.db. This overrides the default and the config file.
- #[arg(long, short)]
- pub(crate) db_path: Option<PathBuf>,
-
- /// Set the cookie file to be passed to `yt_dlp`. This overrides the default and the value from
- /// the config file.
- #[arg(long, short = 'P')]
- pub(crate) cookies: Option<PathBuf>,
-
/// Set the path to the config.toml.
/// This overrides the default.
#[arg(long, short)]
@@ -58,6 +46,50 @@ pub(crate) struct CliArgs {
/// Silence all output
#[arg(long, short = 'q')]
pub(crate) quiet: bool,
+
+ /// Temporarily set config option <NAME> to <VALUE>
+ ///
+ /// See `yt config default` for a documented list of all available options.
+ /// Options are addressed with a `.` separator (so download > max_cache_size becomes
+ /// `download.max_cache_size`).
+ ///
+ /// Can be specified more than once.
+ #[arg(
+ long = "option",
+ short = 'o',
+ num_args = 2,
+ value_names = &["NAME", "VALUE"],
+ global = true,
+ )]
+ pub(crate) options: Vec<String>,
+}
+
+#[derive(Clone, Debug)]
+pub(crate) struct ConfigOverride {
+ pub(crate) name: Vec<String>,
+ pub(crate) value: toml::Value,
+}
+
+impl ConfigOverride {
+ pub(crate) fn from_name_and_value(name: &str, value: &str) -> Result<Self, anyhow::Error> {
+ let value = {
+ let mut naive = toml::Table::from_str(format!("a = {value}").as_str());
+ if let Ok(value) = &mut naive {
+ value.remove("a").expect("Was just added")
+ } else if let Ok(mut value) = toml::Table::from_str(format!("a = \"{value}\"").as_str())
+ {
+ value.remove("a").expect("Was just added")
+ } else {
+ let err = naive.expect_err("Was not Ok above");
+ bail!("Failed to parse option value '{value}' as toml value: {err}");
+ }
+ };
+
+ Ok(Self {
+ name: name.split('.').map(ToOwned::to_owned).collect(),
+ value,
+ })
+ }
}
#[cfg(test)]
diff --git a/crates/yt/src/config/def.rs b/crates/yt/src/config/def.rs
new file mode 100644
index 0000000..70456ea
--- /dev/null
+++ b/crates/yt/src/config/def.rs
@@ -0,0 +1,127 @@
+#![expect(unused_imports)]
+
+mk_config::mk_config! {
+ use [
+ std::collections::HashMap;
+ std::io::IsTerminal;
+ std::path::PathBuf;
+ std::time::Duration;
+
+ crate::shared::bytes::Bytes;
+
+ crate::config::set_static_should_display_color;
+
+ crate::config::non_empty_vec::NonEmptyVec;
+ crate::config::non_empty_vec::non_empty_vec;
+
+ crate::config::paths::PREFIX;
+ crate::config::paths::ensure_dir;
+ crate::config::paths::ensure_parent_dir;
+ crate::config::paths::get_config_path;
+ crate::config::paths::get_data_path;
+ crate::config::paths::get_runtime_path;
+ ]
+
+ struct Config {
+ global: {
+ /// Whether to display colors.
+ display_colors: bool = { std::io::stderr().is_terminal() } => set_static_should_display_color,
+ },
+ select: {
+ /// The playback speed to use, when it is not overridden.
+ playback_speed: f64 = 2.7,
+
+ /// The subtitle langs to download, when it is not overridden.
+ subtitle_langs: String = String::new(),
+ },
+ watch: {
+ /// How many chars to display at most, when displaying information on mpv's local on screen
+ /// display.
+ local_displays_length: usize = 1000,
+
+ /// How long to wait between saving the video watch progress.
+ progress_save_intervall: Duration = Duration::from_secs(10),
+ },
+ commands: {
+ /// Which command to execute, when showing the thumbnail.
+ ///
+ /// This command will be executed with the one argument, being the path to the image file to display.
+ image_show: NonEmptyVec<String> = non_empty_vec!["imv".to_owned()],
+
+ /// Which command to use, when spawing one of the external commands (e.g.
+ /// `yt-comments-external` from mpv).
+ ///
+ /// The command will be called with a series of args that should be executed.
+ /// For example,
+ /// `<your_specified_command> <path_to_yt_binary> --db-path <path_to_current_db_path> comments`
+ external_spawn: NonEmptyVec<String> = non_empty_vec!["alacritty".to_owned(), "-e".to_owned()],
+
+ /// Which command to use, when opening video urls (like in the `yt select url` case).
+ ///
+ /// This command will be called with one argument, being the url of the video to open.
+ url_opener: NonEmptyVec<String> = non_empty_vec!["firefox".to_owned()],
+ },
+ paths: {
+ /// Where to store downloaded files.
+ download_dir: PathBuf = {
+ // We download to the temp dir to avoid taxing the disk
+ let temp_dir = std::env::temp_dir();
+
+ temp_dir.join(PREFIX)
+ } => ensure_dir,
+
+ /// Path to the mpv configuration file.
+ mpv_config_path: PathBuf = try get_config_path("mpv.conf") => ensure_parent_dir,
+
+ /// Path to the mpv input configuration file.
+ mpv_input_path: PathBuf = try get_config_path("mpv.input.conf") => ensure_parent_dir,
+
+ /// Which path to use for mpv ipc socket creation.
+ mpv_ipc_socket_path: PathBuf = try get_runtime_path("mpv.ipc.socket") => ensure_parent_dir,
+
+ /// Path to the video database.
+ database_path: PathBuf = try get_data_path("videos.sqlite") => ensure_parent_dir,
+
+ /// Where to store the selection file before applying it.
+ last_selection_path: PathBuf = try get_runtime_path("selected.yts") => ensure_parent_dir,
+ },
+ download: {
+ /// The maximum cache size.
+ max_cache_size: Bytes = try "3 GiB".parse(),
+
+ /// The cookie file to pass to `yt_dlp`.
+ ///
+ /// If set takes priority over `cookies_from_browser`
+ cookies: Option<PathBuf> = None,
+
+ /// Pass `cookies_from_browser` to `yt_dlp`
+ ///
+ /// If `cookies` is set, that setting takes priority.
+ cookies_from_browser: Option<String> = None,
+
+ /// Additional options to pass to `yt-dlp`, when updating (or select adding).
+ ///
+ /// These are added _after_ the ones `yt` adds, so you can override hardcoded
+ /// options.
+ yt_dlp_options: HashMap<String, serde_json::Value> = HashMap::new(),
+ },
+ update: {
+ /// How many videos to download, when checking for new ones.
+ max_backlog: usize = 20,
+
+ /// How many threads to use in the thread pool for fetching new videos.
+ pool_size: usize = 16,
+
+ /// How many subscriptions to fetch at once.
+ ///
+ /// For example, 16 means, that we will fetch 16 subscriptions at the same time.
+ futures: usize = 16 * 4,
+
+ /// Additional options to pass to `yt-dlp`, when updating (or select adding).
+ ///
+ /// These are added _after_ the ones `yt` adds, so you can override hardcoded
+ /// options.
+ yt_dlp_options: HashMap<String, serde_json::Value> = HashMap::new(),
+ },
+ }
+}
diff --git a/crates/yt/src/config/mod.rs b/crates/yt/src/config/mod.rs
index 6e596de..208fcf8 100644
--- a/crates/yt/src/config/mod.rs
+++ b/crates/yt/src/config/mod.rs
@@ -10,11 +10,10 @@
use std::sync::atomic::{AtomicBool, Ordering};
-use crate::config::support::mk_config;
-
mod non_empty_vec;
-mod paths;
-mod support;
+
+pub(crate) mod def;
+pub(crate) mod paths;
pub(crate) static SHOULD_DISPLAY_COLOR: AtomicBool = AtomicBool::new(false);
@@ -25,130 +24,3 @@ fn set_static_should_display_color(value: &bool) -> anyhow::Result<()> {
Ok(())
}
-
-mk_config! {
- use std::path::PathBuf;
- use std::io::IsTerminal;
- use std::time::Duration;
-
- use crate::shared::bytes::Bytes;
-
- use super::set_static_should_display_color;
-
- use super::paths::get_config_path;
- use super::paths::get_runtime_path;
- use super::paths::get_data_path;
- use super::paths::ensure_parent_dir;
- use super::paths::ensure_dir;
- use super::paths::PREFIX;
-
- use super::non_empty_vec::NonEmptyVec;
- use super::non_empty_vec::non_empty_vec;
-
- struct Config {
- global: GlobalConfig = {
- /// Whether to display colors.
- display_colors: bool where display_color: Option<bool> =! {
- |config_value: Option<bool>|
- Ok::<_, anyhow::Error>(
- display_color
- .unwrap_or(
- config_value
- .unwrap_or_else(|| std::io::stderr().is_terminal())
- )
- )
- } => set_static_should_display_color,
-
- /// The cookie file to pass to `yt_dlp`.
- cookies: Option<PathBuf> where cookies_path: Option<PathBuf> =! {
- |config_value: Option<Option<PathBuf>>|
- if let Some(co) = cookies_path {
- Ok::<_, anyhow::Error>(Some(co))
- } else {
- Ok(config_value.unwrap_or(None))
- }
- },
- },
- select: SelectConfig = {
- /// The playback speed to use, when it is not overridden.
- playback_speed: f64 =: 2.7,
-
- /// The subtitle langs to download, when it is not overridden.
- subtitle_langs: String =: String::new(),
- },
- watch: WatchConfig = {
- /// How many chars to display at most, when displaying information on mpv's local on screen
- /// display.
- local_displays_length: usize =: 1000,
-
- /// How long to wait between saving the video watch progress.
- progress_save_intervall: Duration =: Duration::from_secs(10),
- },
- commands: CommandsConfig = {
- /// Which command to execute, when showing the thumbnail.
- ///
- /// This command will be executed with the one argument, being the path to the image file to display.
- image_show: NonEmptyVec<String> =: non_empty_vec!["imv".to_owned()],
-
- /// Which command to use, when spawing one of the external commands (e.g.
- /// `yt-comments-external` from mpv).
- ///
- /// The command will be called with a series of args that should be executed.
- /// For example,
- /// `<your_specified_command> <path_to_yt_binary> --db-path <path_to_current_db_path> comments`
- external_spawn: NonEmptyVec<String> =: non_empty_vec!["alacritty".to_owned(), "-e".to_owned()],
-
- /// Which command to use, when opening video urls (like in the `yt select url` case).
- ///
- /// This command will be called with one argument, being the url of the video to open.
- url_opener: NonEmptyVec<String> =: non_empty_vec!["firefox".to_owned()],
- },
- paths: PathsConfig = {
- /// Where to store downloaded files.
- download_dir: PathBuf =: {
- // We download to the temp dir to avoid taxing the disk
- let temp_dir = std::env::temp_dir();
-
- temp_dir.join(PREFIX)
- } => ensure_dir,
-
- /// Path to the mpv configuration file.
- mpv_config_path: PathBuf =? get_config_path("mpv.conf") => ensure_parent_dir,
-
- /// Path to the mpv input configuration file.
- mpv_input_path: PathBuf =? get_config_path("mpv.input.conf") => ensure_parent_dir,
-
- /// Which path to use for mpv ipc socket creation.
- mpv_ipc_socket_path: PathBuf =? get_runtime_path("mpv.ipc.socket") => ensure_parent_dir,
-
- /// Path to the video database.
- database_path: PathBuf where db_path: Option<PathBuf> =! {
- |config_value: Option<PathBuf>| {
- db_path
- .map_or_else(
- || config_value.map_or_else(|| get_data_path("videos.sqlite"), Ok),
- Ok
- )
- }} => ensure_parent_dir,
-
- /// Where to store the selection file before applying it.
- last_selection_path: PathBuf =? get_runtime_path("selected.yts") => ensure_parent_dir,
- },
- download: DownloadConfig = {
- /// The maximum cache size.
- max_cache_size: Bytes =? "3 GiB".parse(),
- },
- update: UpdateConfig = {
- /// How many videos to download, when checking for new ones.
- max_backlog: usize =: 20,
-
- /// How many threads to use in the thread pool for fetching new videos.
- pool_size: usize =: 16,
-
- /// How many subscriptions to fetch at once.
- ///
- /// For example, 16 means, that we will fetch 16 subscriptions at the same time.
- futures: usize =: 16 * 4,
- },
- }
-}
diff --git a/crates/yt/src/config/paths.rs b/crates/yt/src/config/paths.rs
index 66975dd..dc219cb 100644
--- a/crates/yt/src/config/paths.rs
+++ b/crates/yt/src/config/paths.rs
@@ -51,7 +51,7 @@ pub(super) fn ensure_dir(path: &Path) -> Result<()> {
Ok(())
}
-pub(super) fn config_path() -> Result<PathBuf> {
+pub(crate) fn config_path() -> Result<PathBuf> {
get_config_path("config.toml")
}
diff --git a/crates/yt/src/config/support.rs b/crates/yt/src/config/support.rs
deleted file mode 100644
index 96e7ba4..0000000
--- a/crates/yt/src/config/support.rs
+++ /dev/null
@@ -1,161 +0,0 @@
-// yt - A fully featured command line YouTube client
-//
-// Copyright (C) 2025 Benedikt Peetz <benedikt.peetz@b-peetz.de>
-// SPDX-License-Identifier: GPL-3.0-or-later
-//
-// This file is part of Yt.
-//
-// You should have received a copy of the License along with this program.
-// If not, see <https://www.gnu.org/licenses/gpl-3.0.txt>.
-
-macro_rules! mk_config {
- (
- $(use $usage_path:path;)*
-
- struct $name:ident {
- $(
- $(#[$attr0:meta])*
- $subconfig_name:ident : $subconfig_type:ident = {
- $(
- $(#[$attr1:meta])*
- $field_name:ident : $field_type:ty $(
- where $extra_input:ident: $extra_input_type:ty
- ),* = $errors:tt $default:expr $(=> $finalizer:ident)?
- ),*
- $(,)?
- }
- ),*
- $(,)?
- }
- ) => {
- mod _inner {
- #![allow(non_snake_case)]
-
- $(use $usage_path;)*
-
- #[derive(serde::Serialize, Debug)]
- pub(crate) struct $name {
- $(
- $(#[$attr0])*
- pub(crate) $subconfig_name: $subconfig_type
- ),*
- }
-
- #[derive(Debug, serde::Deserialize, PartialEq)]
- #[serde(deny_unknown_fields)]
- #[allow(non_camel_case_types)]
- struct config {
- $(
- $subconfig_name: Option<$subconfig_name>
- ),*
- }
-
- impl $name {
- pub(crate) fn from_config_file(
- config_file_path: Option<std::path::PathBuf>,
- $(
- $(
- $(
- $extra_input: $extra_input_type,
- )*
- )*
- )*
- ) -> anyhow::Result<Self> {
- use anyhow::Context;
-
- let config_file_path =
- config_file_path.map_or_else(|| -> anyhow::Result<_> { super::paths::config_path() }, Ok)?;
-
- let config: config =
- toml::from_str(&std::fs::read_to_string(config_file_path).unwrap_or(String::new()))
- .context("Failed to parse the config file as toml")?;
-
- Ok(Self {
- $(
- $subconfig_name: {
- let toplevel = config.$subconfig_name.unwrap_or_default();
- $subconfig_type {
- $(
- $field_name: $field_name(toplevel.$field_name, $($extra_input),*)?
- ),*
- }
- }
- ),*
- })
- }
-
- pub(crate) fn run_finalizers(&self) -> anyhow::Result<()> {
- #[allow(unused_imports)]
- use anyhow::Context;
-
- $(
- $(
- $(
- $finalizer(&self.$subconfig_name.$field_name)
- .context(
- concat!(
- "While running the finalizer for config value '",
- stringify!($subconfig_name),
- ".",
- stringify!($field_name),
- "'"
- )
- )?;
- )?
- )*
- )*
-
- Ok(())
- }
- }
-
- $(
- #[derive(serde::Serialize, Debug)]
- pub(crate) struct $subconfig_type {
- $(
- $(#[$attr1])*
- pub(crate) $field_name: $field_type
- ),*
- }
-
- #[derive(Debug, Default, serde::Deserialize, PartialEq)]
- #[serde(deny_unknown_fields)]
- #[allow(non_camel_case_types)]
- struct $subconfig_name {
- $(
- $field_name: Option<$field_type>
- ),*
- }
-
- $(
- fn $field_name(
- config_value: Option<$field_type>,
- $($extra_input: $extra_input_type),*
- ) -> anyhow::Result<$field_type> {
- use anyhow::Context;
-
- let expr = $crate::config::support::maybe_wrap_type!($field_type =$errors $default)(config_value);
-
- expr.context(concat!("Failed to generate default config value for '", stringify!($field_name),"'"))
- }
- )*
- )*
- }
- pub(crate) use self::_inner::*;
- };
-}
-
-macro_rules! maybe_wrap_type {
- ($ty:ty =! $val:expr) => {
- (|config_value: Option<$ty>| $val(config_value))
- };
- ($ty:ty =? $val:expr) => {
- (|config_value: Option<$ty>| config_value.map_or_else(|| $val, Ok))
- };
- ($ty:ty =: $val:expr) => {
- (|config_value: Option<$ty>| Ok::<_, anyhow::Error>(config_value.unwrap_or_else(|| $val)))
- };
-}
-
-pub(crate) use maybe_wrap_type;
-pub(crate) use mk_config;
diff --git a/crates/yt/src/main.rs b/crates/yt/src/main.rs
index 50e4a09..8c67e95 100644
--- a/crates/yt/src/main.rs
+++ b/crates/yt/src/main.rs
@@ -16,10 +16,9 @@
use anyhow::{Context, Result};
use app::App;
use clap::{CommandFactory, Parser};
-use config::Config;
use log::info;
-use crate::commands::Command;
+use crate::{app::App, cli::ConfigOverride, commands::Command};
pub(crate) mod output;
pub(crate) mod yt_dlp;
@@ -42,6 +41,32 @@ async fn main() -> Result<()> {
let args = cli::CliArgs::parse();
+ let arg_options = {
+ if args.options.is_empty() {
+ vec![]
+ } else {
+ let mut output = vec![];
+
+ let mut name = None;
+ for name_or_value in args.options {
+ if name.is_none() {
+ name = Some(name_or_value);
+ } else {
+ assert!(name.is_some());
+
+ let name = name.take().expect("is some");
+ let value = name_or_value;
+ output.push(ConfigOverride::from_name_and_value(&name, &value)?);
+ }
+ }
+
+ output
+ .into_iter()
+ .map(|ovr| (ovr.name, ovr.value))
+ .collect()
+ }
+ };
+
// The default verbosity is 1 (Warn)
let verbosity: u8 = args.verbosity + 1;
@@ -66,20 +91,20 @@ async fn main() -> Result<()> {
}
});
- let config =
- Config::from_config_file(args.config_path, args.color, args.cookies, args.db_path)?;
+ let config_path = if let Some(path) = args.config_path {
+ path
+ } else {
+ config::paths::config_path()?
+ };
+ let config = config::def::Config::from_config_file(&config_path, arg_options)?;
+ // Config finalization happens _before_ this, so checking for the version
+ // might fail :/
if args.version {
version::show(&config).await?;
return Ok(());
}
- // Perform config finalization _after_ checking for the version
- // so that version always works.
- config
- .run_finalizers()
- .context("Failed to finalize config for usage")?;
-
let app = App::new(config, !args.no_migrate_db).await?;
args.command