1
mod log_file;
2

            
3
use clap::Parser;
4
use cli_core::start_server;
5
use sqlx::types::Uuid;
6
use std::sync::Mutex;
7
use tracing::level_filters::LevelFilter;
8
use tui::{
9
    App, CliConfig, ConsoleEval, Keys, LocalTransport, install_panic_hook, parse_colors, run_loop,
10
};
11
use tvui::{ColorDepth, Theme};
12

            
13
#[derive(Parser, Debug)]
14
#[command(name = "nomisync-tui", about = "Nomisync interactive TUI")]
15
struct Cli {
16
    #[arg(short = 'u', long)]
17
    userid: Uuid,
18

            
19
    #[arg(short = 'd', long)]
20
    database: Option<String>,
21

            
22
    #[arg(long)]
23
    loglevel: Option<LevelFilter>,
24

            
25
    /// Key bindings preset: cua (the default), emacs or vim. Overrides the `tui-keymap` config key.
26
    #[arg(long, value_parser = parse_keymap)]
27
    keymap: Option<String>,
28

            
29
    /// Colour depth: auto, rgb, 256 or 16. Overrides the `tui-colors` config key.
30
    #[arg(long, default_value = "auto")]
31
    colors: Colors,
32

            
33
    /// Theme preset: dn or turbo. Overrides the `tui-theme` config key.
34
    #[arg(long, value_parser = parse_theme)]
35
    theme: Option<String>,
36
}
37

            
38
/// The `--colors` value: `None` is `auto`.
39
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40
struct Colors(Option<ColorDepth>);
41

            
42
impl std::str::FromStr for Colors {
43
    type Err = String;
44

            
45
11
    fn from_str(s: &str) -> Result<Colors, String> {
46
11
        parse_colors(s).map(Colors)
47
11
    }
48
}
49

            
50
3
fn parse_theme(s: &str) -> Result<String, String> {
51
3
    Theme::preset(s)
52
2
        .map(|_| s.to_string())
53
1
        .map_err(|err| err.message)
54
3
}
55

            
56
impl Cli {
57
6
    fn cli_config(&self) -> CliConfig {
58
6
        CliConfig {
59
6
            preset: self.theme.clone(),
60
6
            depth: self.colors.0,
61
6
            keymap: self.keymap.clone(),
62
6
        }
63
6
    }
64
}
65

            
66
fn detected_depth() -> ColorDepth {
67
    let term = std::env::var("TERM").ok();
68
    let colorterm = std::env::var("COLORTERM").ok();
69
    ColorDepth::detect(term.as_deref(), colorterm.as_deref())
70
}
71

            
72
4
fn parse_keymap(s: &str) -> Result<String, String> {
73
4
    Keys::preset(s).map(|_| s.to_string())
74
4
}
75

            
76
#[tokio::main]
77
async fn main() -> anyhow::Result<()> {
78
    let cli = Cli::parse();
79

            
80
    let log = log_file::open_from_env().map_err(std::io::Error::other)?;
81
    server::telemetry::init_logging_to(cli.loglevel, LevelFilter::WARN, Mutex::new(log), false)?;
82

            
83
    let mut app =
84
        App::new(cli.userid, cli.cli_config(), detected_depth()).map_err(std::io::Error::other)?;
85

            
86
    start_server(cli.database, None).await?;
87

            
88
    install_panic_hook();
89
    let handle = tokio::runtime::Handle::current();
90
    match ConsoleEval::connect(&handle, rpc::ScriptCtx::new(cli.userid), rpc::Session::new) {
91
        Ok(eval) => app.attach_console(eval),
92
        Err(err) => tracing::warn!("console eval unavailable: {err}"),
93
    }
94

            
95
    // The transport is dropped, and the terminal restored, before an error is printed.
96
    let loop_result = {
97
        let mut transport = LocalTransport::new()?;
98
        run_loop(&mut transport, &mut app)
99
    };
100
    loop_result?;
101
    Ok(())
102
}
103

            
104
#[cfg(test)]
105
mod tests {
106
    use super::*;
107

            
108
    const USER: &str = "00000000-0000-0000-0000-000000000000";
109

            
110
14
    fn parse(extra: &[&str]) -> Result<Cli, clap::Error> {
111
14
        let args = ["nomisync-tui", "-u", USER]
112
14
            .into_iter()
113
14
            .chain(extra.iter().copied());
114
14
        Cli::try_parse_from(args)
115
14
    }
116

            
117
    #[test]
118
1
    fn the_cli_parses_with_and_without_colors() {
119
1
        let default = parse(&[]).expect("parses");
120
1
        assert_eq!(default.colors, Colors(None));
121
1
        assert_eq!(default.cli_config().depth, None);
122
1
        let forced = parse(&["--colors", "16"]).expect("parses");
123
1
        assert_eq!(forced.colors, Colors(Some(ColorDepth::Ansi16)));
124
1
        assert_eq!(
125
1
            parse(&["--colors", "auto"]).expect("parses").colors,
126
1
            Colors(None)
127
        );
128
1
        assert_eq!(forced.cli_config().depth, Some(ColorDepth::Ansi16));
129
1
        assert!(parse(&["--colors", "8"]).is_err());
130
1
    }
131

            
132
    #[test]
133
1
    fn the_cli_parses_the_theme_flag() {
134
1
        assert_eq!(parse(&[]).expect("parses").theme, None);
135
1
        let turbo = parse(&["--theme", "turbo"]).expect("parses");
136
1
        assert_eq!(turbo.cli_config().preset.as_deref(), Some("turbo"));
137
1
        assert!(parse(&["--theme", "dn"]).is_ok());
138
1
        assert!(parse(&["--theme", "bogus"]).is_err());
139
1
    }
140

            
141
    #[test]
142
1
    fn the_cli_parses_the_keymap_flag() {
143
1
        assert_eq!(parse(&[]).expect("parses").keymap, None);
144
1
        for name in ["cua", "emacs", "vim"] {
145
3
            let cli = parse(&["--keymap", name]).expect("parses");
146
3
            assert_eq!(cli.keymap.as_deref(), Some(name));
147
3
            assert_eq!(cli.cli_config().keymap.as_deref(), Some(name));
148
        }
149
1
        assert!(parse(&["--keymap", "bogus"]).is_err());
150
1
        assert!(parse(&["--edit-mode", "vim"]).is_err());
151
1
    }
152
}