youtube-legend-cli 0.4.0

Non-interactive Rust CLI that downloads YouTube subtitles through third-party providers, using a native Unix stdin/stdout interface.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
//! The `config` subcommand: inspect and edit the XDG configuration.
//!
//! Every action writes its payload to stdout and nothing else, so the
//! subcommand composes in a pipeline exactly like the extraction path.
//!
//! With `--json` each action emits one `config-envelope` object instead
//! of the plain-text form. The plain text is for humans and must never
//! be parsed: it carries no types, no set/unset distinction, and its
//! separators are chosen for reading rather than for splitting.

use crate::cli::{Cli, ConfigAction};
use crate::config::{spec, ConfigStore, KEYS};
use crate::error::{AppError, AppResult};
use crate::i18n::{t, Message};
use serde::Serialize;
use std::process::ExitCode;

/// One `config` action rendered for a machine.
///
/// `action` is the discriminator: which of the remaining fields are
/// present depends entirely on it. Every other field is optional and
/// skipped when absent, so the published schema can keep
/// `additionalProperties: false` while carrying six different shapes.
#[derive(Serialize)]
struct ConfigEnvelope<'a> {
    action: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    path: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    key: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    value: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    changed: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    entries: Option<Vec<ConfigEntry>>,
}

impl<'a> ConfigEnvelope<'a> {
    /// An envelope carrying nothing but its discriminator, to be filled
    /// in by the caller. Written as a constructor so that adding a field
    /// later does not mean editing six literal initialisers.
    fn new(action: &'a str) -> Self {
        Self {
            action,
            path: None,
            key: None,
            value: None,
            changed: None,
            entries: None,
        }
    }
}

/// One registry key rendered for a machine.
#[derive(Serialize)]
struct ConfigEntry {
    key: &'static str,
    #[serde(rename = "type")]
    kind: &'static str,
    #[serde(skip_serializing_if = "Option::is_none")]
    doc: Option<&'static str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    secret: Option<bool>,
    set: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    value: Option<String>,
}

/// Build the entry list for `show` and `list-keys`.
///
/// Both walk the registry rather than the parsed file, which is what
/// guarantees every entry carries a real declared type. Walking the file
/// instead would force a fallback type for any key the registry does not
/// know — and a fallback type is a lie the consumer cannot detect. A key
/// outside the registry cannot reach this point anyway, because loading
/// the configuration rejects it.
///
/// `only_set` selects between the two actions: `show` reports what the
/// operator persisted, `list-keys` reports the whole registry.
fn entries(store: &ConfigStore, only_set: bool, with_doc: bool) -> Vec<ConfigEntry> {
    KEYS.iter()
        .filter_map(|entry| {
            let stored = store.get(entry.key);
            if only_set && stored.is_none() {
                return None;
            }
            Some(ConfigEntry {
                key: entry.key,
                kind: entry.kind.as_str(),
                doc: with_doc.then_some(entry.doc),
                secret: entry.secret.then_some(true),
                set: stored.is_some(),
                // A secret never leaves the store through this surface,
                // in either direction: argv cannot put one in, and this
                // envelope does not take one out.
                value: stored.filter(|_| !entry.secret).map(render),
            })
        })
        .collect()
}

/// Execute one configuration action.
///
/// # Errors
///
/// - [`AppError::InvalidUsage`] when a key is absent from the registry,
///   when a value does not parse as its declared type, when `get` is
///   asked for an unset key, or when a secret key is passed on argv.
/// - [`AppError::Config`] when the file cannot be read, parsed or
///   serialised.
/// - [`AppError::Io`] when the file cannot be written or stdout fails.
/// - [`AppError::Serde`] when the JSON envelope cannot be serialised.
pub async fn run(cli: &Cli, action: &ConfigAction) -> AppResult<ExitCode> {
    match action {
        ConfigAction::Path => {
            let path = crate::config::config_file_path()?;
            if cli.json {
                let mut env = ConfigEnvelope::new("path");
                env.path = Some(path.display().to_string());
                super::emit_envelope(cli, &env).await?;
            } else {
                emit(&format!("{}\n", path.display())).await?;
            }
        }
        ConfigAction::Show => {
            let store = ConfigStore::load()?;
            if cli.json {
                let mut env = ConfigEnvelope::new("show");
                env.entries = Some(entries(&store, true, false));
                super::emit_envelope(cli, &env).await?;
            } else {
                let mut out = String::new();
                for (key, value) in store.flattened() {
                    out.push_str(&format!("{key} = {value}\n"));
                }
                emit(&out).await?;
            }
        }
        ConfigAction::Get { key } => {
            if spec(key).is_none() {
                return Err(unknown(key));
            }
            let store = ConfigStore::load()?;
            let value = store.get(key).ok_or_else(|| {
                AppError::InvalidUsage(format!("`{key}` {}", t(Message::ConfigKeyNotSet)))
            })?;
            if cli.json {
                let mut env = ConfigEnvelope::new("get");
                env.key = Some(key);
                env.value = Some(render(value));
                super::emit_envelope(cli, &env).await?;
            } else {
                emit(&format!("{}\n", render(value))).await?;
            }
        }
        ConfigAction::Set {
            key,
            value,
            from_stdin,
        } => {
            let entry = spec(key).ok_or_else(|| unknown(key))?;
            if entry.secret && !*from_stdin {
                return Err(AppError::InvalidUsage(format!(
                    "`{key}` {}",
                    t(Message::ConfigKeyIsSecret)
                )));
            }
            let raw = if *from_stdin {
                read_secret_from_stdin().await?
            } else {
                value.clone().ok_or_else(|| {
                    AppError::InvalidUsage(format!(
                        "`config set {key}` {}",
                        t(Message::ConfigSetNeedsValue)
                    ))
                })?
            };
            let mut store = ConfigStore::load()?;
            let before = store.get(key).map(render);
            store.set(key, &raw)?;
            let after = store.get(key).map(render);
            store.save()?;
            if cli.json {
                let mut env = ConfigEnvelope::new("set");
                env.key = Some(key);
                env.changed = Some(before != after);
                super::emit_envelope(cli, &env).await?;
            } else {
                emit(&format!("{key} set\n")).await?;
            }
        }
        ConfigAction::Unset { key } => {
            let mut store = ConfigStore::load()?;
            // Removing a value the operator persisted is destructive and
            // cannot be undone from the file itself, so it demands an
            // explicit `--yes`. Removing a key that was never set is
            // harmless and needs no confirmation, which keeps a script
            // from having to know the previous state.
            let was_set = store.get(key).is_some();
            if was_set && !cli.yes {
                return Err(AppError::InvalidUsage(format!(
                    "`{key}` {}",
                    t(Message::ConfigKeySetNeedsYes)
                )));
            }
            store.unset(key)?;
            store.save()?;
            if cli.json {
                let mut env = ConfigEnvelope::new("unset");
                env.key = Some(key);
                // False means the key was already absent. Reporting it
                // lets a script tell a real removal from a no-op without
                // having to read the file beforehand.
                env.changed = Some(was_set);
                super::emit_envelope(cli, &env).await?;
            } else {
                emit(&format!("{key} unset\n")).await?;
            }
        }
        ConfigAction::ListKeys => {
            if cli.json {
                let store = ConfigStore::load()?;
                let mut env = ConfigEnvelope::new("list-keys");
                env.entries = Some(entries(&store, false, true));
                super::emit_envelope(cli, &env).await?;
            } else {
                let mut out = String::new();
                for entry in KEYS {
                    out.push_str(&format!(
                        "{}\t{}\t{}\n",
                        entry.key,
                        entry.kind.as_str(),
                        entry.doc
                    ));
                }
                emit(&out).await?;
            }
        }
    }
    Ok(ExitCode::SUCCESS)
}

/// Read one line from stdin, trimmed of its trailing newline.
///
/// This is the only path by which a credential enters the store: argv is
/// world-readable through the process table, stdin is not.
async fn read_secret_from_stdin() -> AppResult<String> {
    use tokio::io::{AsyncBufReadExt, BufReader};
    let mut line = String::new();
    let read = BufReader::new(tokio::io::stdin())
        .read_line(&mut line)
        .await
        .map_err(|e| AppError::InvalidInput(format!("reading stdin: {e}")))?;
    if read == 0 {
        return Err(AppError::StdinEmpty);
    }
    Ok(line.trim_end_matches(['\r', '\n']).to_string())
}

/// Render a scalar or array TOML value for stdout.
fn render(value: &toml::Value) -> String {
    match value {
        toml::Value::String(s) => s.clone(),
        toml::Value::Array(items) => items.iter().map(render).collect::<Vec<_>>().join(","),
        other => other.to_string(),
    }
}

/// Build the error for a key absent from the registry.
///
/// The wording lives in [`crate::config::unknown_key`]; this is the
/// local name the subcommand reads better with.
fn unknown(key: &str) -> AppError {
    crate::config::unknown_key(key)
}

/// Write `text` to stdout.
async fn emit(text: &str) -> AppResult<()> {
    crate::io::write_subtitle_to_stdout(text.as_bytes()).await
}

#[cfg(test)]
mod tests {
    use super::*;

    /// `--yes` had no confirmation to answer anywhere in the binary.
    /// Removing a persisted value is the one destructive action this
    /// CLI performs, so that is where the flag now binds.
    /// Build a `Cli` for the tests. Going through the real parser is
    /// deliberate: a hand-rolled struct literal would drift from the
    /// parser the binary actually uses, and the defaults under test are
    /// exactly what the parser fills in.
    fn test_cli(json: bool) -> Cli {
        use clap::Parser;
        let mut argv = vec!["youtube-legend-cli"];
        if json {
            argv.push("--json");
        }
        argv.extend_from_slice(&["config", "path"]);
        Cli::parse_from(argv)
    }

    /// `--yes` had no confirmation to answer anywhere in the binary.
    /// Removing a persisted value is the one destructive action this
    /// CLI performs, so that is where the flag now binds.
    #[tokio::test]
    async fn unsetting_an_unset_key_needs_no_confirmation() {
        let action = ConfigAction::Unset {
            key: "cli.max_url_chars".to_string(),
        };
        // The key is absent from a pristine store, so the guard must not
        // fire even without `--yes`.
        let store = ConfigStore::load().expect("store loads");
        if store.get("cli.max_url_chars").is_none() {
            assert!(run(&test_cli(false), &action).await.is_ok());
        }
    }

    #[test]
    fn list_keys_entries_cover_the_whole_registry() {
        let store = ConfigStore::load().expect("store loads");
        let all = entries(&store, false, true);
        assert_eq!(
            all.len(),
            KEYS.len(),
            "list-keys must report every registry key, set or not"
        );
        assert!(
            all.iter().all(|e| e.doc.is_some()),
            "list-keys carries the registry doc for every key"
        );
    }

    #[test]
    fn show_entries_are_a_subset_that_is_actually_set() {
        let store = ConfigStore::load().expect("store loads");
        let shown = entries(&store, true, false);
        assert!(shown.len() <= KEYS.len());
        assert!(
            shown.iter().all(|e| e.set),
            "show reports only keys the operator persisted"
        );
        assert!(
            shown.iter().all(|e| e.doc.is_none()),
            "show reports stored values, not registry metadata"
        );
    }

    #[test]
    fn a_secret_key_never_carries_its_value_in_the_envelope() {
        // The registry has no secret key today, so this asserts the
        // filter itself rather than an instance of it: the day a
        // credential key is added, the value must still not leave here.
        let store = ConfigStore::load().expect("store loads");
        for entry in entries(&store, false, true) {
            if entry.secret == Some(true) {
                assert!(
                    entry.value.is_none(),
                    "`{}` is secret and must not publish its value",
                    entry.key
                );
            }
        }
    }

    #[test]
    fn envelope_omits_every_field_the_action_does_not_use() {
        // `additionalProperties: false` in the published schema only
        // holds if absent fields are skipped rather than serialised as
        // null. A null is a present field with an empty value, which is
        // not the same thing to a consumer.
        let env = ConfigEnvelope::new("path");
        let json = serde_json::to_string(&env).expect("serialises");
        assert_eq!(json, r#"{"action":"path"}"#);
    }

    #[test]
    fn render_joins_a_string_list_with_commas() {
        let value = toml::Value::Array(vec![
            toml::Value::String("a".to_string()),
            toml::Value::String("b".to_string()),
        ]);
        assert_eq!(render(&value), "a,b");
    }

    #[test]
    fn render_strips_quotes_from_a_plain_string() {
        assert_eq!(render(&toml::Value::String("auto".to_string())), "auto");
    }

    #[test]
    fn unknown_key_maps_to_a_usage_error() {
        let err = unknown("nope");
        assert!(matches!(err, AppError::InvalidUsage(_)));
        assert_eq!(err.exit_code(), 64);
    }

    #[test]
    fn no_registry_key_is_secret_today_so_none_needs_stdin() {
        // The guard exists so that adding a credential key later cannot
        // be done without also forcing it through stdin. This test is
        // the tripwire: adding a secret key makes it fail, and the fix
        // is to add its coverage rather than to delete the assertion.
        assert!(
            KEYS.iter().all(|k| !k.secret),
            "a secret key was added; cover its --from-stdin path"
        );
    }
}