ztheme 1.3.0

Fast asynchronous Zsh prompt
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
411
use std::io::{self, Write as _};
use std::path::PathBuf;

use clap::{Args, CommandFactory as _, Parser, Subcommand, error::ErrorKind};
use tokio::runtime::Builder;

use crate::{daemon, prompt, setup, theme};

#[derive(Parser)]
#[command(name = "ztheme", version, about = "Fast asynchronous Zsh prompt")]
struct Cli {
    #[command(subcommand)]
    command: Option<Command>,
}

#[derive(Subcommand)]
enum Command {
    /// Generate shell initialization code.
    Init(InitArgs),
    /// Install or repair prompt helpers.
    Setup(SetupArgs),
    /// List, edit, apply, or reload themes.
    Theme(ThemeArgs),
    /// Clear cached runtime values and reset Git status.
    Clear(InstanceArgs),

    #[command(name = "__daemon", hide = true)]
    Daemon(InstanceArgs),

    #[command(name = "__snapshot", hide = true)]
    Snapshot(SnapshotArgs),

    #[command(name = "__theme-apply-zsh", hide = true)]
    ThemeApplyZsh(InternalThemeArgs),

    #[command(name = "__theme-reload-zsh", hide = true)]
    ThemeReloadZsh(InternalThemeArgs),
}

#[derive(Args)]
struct InitArgs {
    #[command(subcommand)]
    shell: InitCommand,
}

#[derive(Subcommand)]
enum InitCommand {
    /// Generate Zsh initialization code.
    Zsh(InitZshArgs),
}

#[derive(Args)]
struct InitZshArgs {
    #[arg(long, value_name = "THEME")]
    theme: Option<String>,

    #[command(flatten)]
    instance: InstanceArgs,
}

#[derive(Args)]
struct SetupArgs {
    #[arg(long)]
    yes: bool,
}

#[derive(Args)]
struct ThemeArgs {
    #[command(subcommand)]
    command: ThemeCommand,
}

#[derive(Subcommand)]
enum ThemeCommand {
    /// Preview available themes.
    List,
    /// Open a theme in the configured editor.
    Edit(ThemeSelector),
    /// Select a theme for future shells.
    Apply(ThemeSelector),
    /// Reload the selected theme through the active shell wrapper.
    Reload,
}

#[derive(Args)]
struct ThemeSelector {
    #[arg(value_name = "THEME")]
    selector: String,
}

#[derive(Args, Default)]
struct InstanceArgs {
    #[arg(long, value_name = "NAME")]
    dev: Option<String>,
}

#[derive(Args)]
struct SnapshotArgs {
    #[arg(long)]
    generation: u64,

    #[arg(long, value_name = "PATH")]
    cwd: PathBuf,

    #[arg(long, value_name = "HEX")]
    theme: String,

    #[command(flatten)]
    instance: InstanceArgs,
}

#[derive(Args)]
struct InternalThemeArgs {
    #[arg(long, value_name = "THEME")]
    theme: String,

    #[command(flatten)]
    instance: InstanceArgs,
}

enum Request {
    InitZsh {
        instance: daemon::Instance,
        theme: Option<String>,
    },
    Setup {
        assume_yes: bool,
    },
    ThemeList,
    ThemeEdit {
        selector: String,
    },
    ThemeApply {
        selector: String,
    },
    ThemeReload,
    ThemeZsh {
        instance: daemon::Instance,
        selector: String,
        persist: bool,
    },
    Clear {
        instance: daemon::Instance,
    },
    Snapshot {
        generation: u64,
        cwd: PathBuf,
        instance: daemon::Instance,
        theme: Box<theme::AsyncTheme>,
    },
    Daemon {
        instance: daemon::Instance,
    },
}

pub(crate) fn run() {
    let cli = match Cli::try_parse() {
        Ok(cli) => cli,
        Err(error) => {
            print_parser_result(&error);
            return;
        }
    };
    let Some(command) = cli.command else {
        let mut help = Cli::command().render_long_help().to_string();
        help.push('\n');
        finish(write_stdout(&help));
        return;
    };
    let request = match request(command) {
        Ok(request) => request,
        Err(message) => {
            eprintln!("ztheme: {message}\nTry `ztheme --help` for usage.");
            std::process::exit(2);
        }
    };

    let result = match request {
        Request::InitZsh { instance, theme } => {
            prompt::init_zsh(&instance, theme.as_deref()).and_then(|script| write_stdout(&script))
        }
        Request::Setup { assume_yes } => setup::run(assume_yes),
        Request::ThemeList => theme::list().and_then(|output| write_stdout(&output)),
        Request::ThemeEdit { selector } => {
            theme::edit(&selector).and_then(|output| write_stdout(&output))
        }
        Request::ThemeApply { selector } => theme::apply(&selector).and_then(|path| {
            write_stdout(&format!(
                "Saved the theme selection to {}.\n\
                 The current shell was not changed because the ztheme shell wrapper was bypassed.\n",
                path.display()
            ))
        }),
        Request::ThemeReload => Err(io::Error::other(
            "theme reload requires the active Zsh integration",
        )),
        Request::ThemeZsh {
            instance,
            selector,
            persist,
        } => prompt::theme_zsh(&instance, &selector, persist)
            .and_then(|script| write_stdout(&script)),
        Request::Clear { instance } => run_async(daemon::reset(&instance)),
        Request::Snapshot {
            generation,
            cwd,
            instance,
            theme,
        } => run_async(prompt::snapshot(generation, cwd, instance, theme)),
        Request::Daemon { instance } => run_async(daemon::serve(&instance)),
    };
    finish(result);
}

fn request(command: Command) -> Result<Request, &'static str> {
    match command {
        Command::Init(InitArgs {
            shell: InitCommand::Zsh(arguments),
        }) => Ok(Request::InitZsh {
            instance: instance(arguments.instance)?,
            theme: arguments.theme,
        }),
        Command::Setup(arguments) => Ok(Request::Setup {
            assume_yes: arguments.yes,
        }),
        Command::Theme(ThemeArgs { command }) => match command {
            ThemeCommand::List => Ok(Request::ThemeList),
            ThemeCommand::Edit(arguments) => Ok(Request::ThemeEdit {
                selector: arguments.selector,
            }),
            ThemeCommand::Apply(arguments) => Ok(Request::ThemeApply {
                selector: arguments.selector,
            }),
            ThemeCommand::Reload => Ok(Request::ThemeReload),
        },
        Command::Clear(arguments) => Ok(Request::Clear {
            instance: instance(arguments)?,
        }),
        Command::Daemon(arguments) => Ok(Request::Daemon {
            instance: instance(arguments)?,
        }),
        Command::Snapshot(arguments) => {
            if !arguments.cwd.is_absolute() || !arguments.cwd.is_dir() {
                return Err("cwd must be an existing absolute directory");
            }
            let theme = theme::AsyncTheme::decode_hex(&arguments.theme)
                .map_err(|_| "invalid compiled theme")?;
            Ok(Request::Snapshot {
                generation: arguments.generation,
                cwd: arguments.cwd,
                instance: instance(arguments.instance)?,
                theme: Box::new(theme),
            })
        }
        Command::ThemeApplyZsh(arguments) => Ok(Request::ThemeZsh {
            instance: instance(arguments.instance)?,
            selector: arguments.theme,
            persist: true,
        }),
        Command::ThemeReloadZsh(arguments) => Ok(Request::ThemeZsh {
            instance: instance(arguments.instance)?,
            selector: arguments.theme,
            persist: false,
        }),
    }
}

fn instance(arguments: InstanceArgs) -> Result<daemon::Instance, &'static str> {
    arguments
        .dev
        .map_or(Ok(daemon::Instance::Production), |name| {
            daemon::Instance::development(name)
        })
}

fn print_parser_result(error: &clap::Error) {
    let code = error.exit_code();
    if matches!(
        error.kind(),
        ErrorKind::DisplayHelp | ErrorKind::DisplayVersion
    ) {
        if let Err(write_error) = write_stdout(&error.to_string())
            && write_error.kind() != io::ErrorKind::BrokenPipe
        {
            eprintln!("ztheme: {write_error}");
            std::process::exit(1);
        }
        return;
    }
    eprint!("{error}");
    std::process::exit(code);
}

fn finish(result: io::Result<()>) {
    if let Err(error) = result
        && error.kind() != io::ErrorKind::BrokenPipe
    {
        eprintln!("ztheme: {error}");
        std::process::exit(1);
    }
}

fn write_stdout(value: &str) -> io::Result<()> {
    let mut output = io::stdout().lock();
    output.write_all(value.as_bytes())?;
    output.flush()
}

fn run_async(future: impl Future<Output = io::Result<()>>) -> io::Result<()> {
    Builder::new_current_thread()
        .enable_all()
        .build()
        .map_err(io::Error::other)?
        .block_on(future)
}

#[cfg(test)]
mod tests {
    use clap::{CommandFactory as _, Parser as _};

    use super::{Cli, Command, InitCommand, ThemeCommand};

    #[test]
    fn public_and_internal_commands_parse() {
        let cases = [
            vec![
                "ztheme", "init", "zsh", "--theme", "vesper", "--dev", "test",
            ],
            vec!["ztheme", "setup", "--yes"],
            vec!["ztheme", "theme", "list"],
            vec!["ztheme", "theme", "edit", "vesper"],
            vec!["ztheme", "theme", "apply", "vesper"],
            vec!["ztheme", "theme", "reload"],
            vec!["ztheme", "clear", "--dev", "test"],
            vec!["ztheme", "__daemon", "--dev", "test"],
            vec![
                "ztheme",
                "__snapshot",
                "--generation",
                "4",
                "--cwd",
                "/",
                "--theme",
                "0000",
                "--dev",
                "test",
            ],
            vec![
                "ztheme",
                "__theme-apply-zsh",
                "--theme",
                "vesper",
                "--dev",
                "test",
            ],
            vec![
                "ztheme",
                "__theme-reload-zsh",
                "--theme",
                "vesper",
                "--dev",
                "test",
            ],
        ];

        for arguments in cases {
            assert!(Cli::try_parse_from(&arguments).is_ok(), "{arguments:?}");
        }
    }

    #[test]
    fn command_shapes_are_nested_as_expected() {
        let cli = Cli::try_parse_from(["ztheme", "init", "zsh"]).unwrap();
        assert!(matches!(
            cli.command,
            Some(Command::Init(super::InitArgs {
                shell: InitCommand::Zsh(_)
            }))
        ));
        let cli = Cli::try_parse_from(["ztheme", "theme", "reload"]).unwrap();
        assert!(matches!(
            cli.command,
            Some(Command::Theme(super::ThemeArgs {
                command: ThemeCommand::Reload
            }))
        ));
    }

    #[test]
    fn invalid_commands_and_duplicate_flags_are_rejected() {
        for arguments in [
            &["ztheme", "unknown"][..],
            &["ztheme", "theme", "unknown"],
            &["ztheme", "clear", "--dev"],
            &["ztheme", "clear", "--dev", "one", "--dev", "two"],
            &["ztheme", "__snapshot", "--generation", "x"],
        ] {
            assert!(Cli::try_parse_from(arguments).is_err(), "{arguments:?}");
        }
    }

    #[test]
    fn internal_commands_are_hidden_from_public_help() {
        let help = Cli::command().render_long_help().to_string();
        assert!(help.contains("init"));
        assert!(help.contains("theme"));
        assert!(!help.contains("__daemon"));
        assert!(!help.contains("__snapshot"));
        assert!(!help.contains("__theme-apply-zsh"));
    }
}