summaryrefslogtreecommitdiffstats
path: root/src/modules/pijul_channel.rs
blob: c5af4814b486b2a5dec02d4280db41818e3f76f2 (plain)
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
use super::utils::truncate::truncate_text;
use super::{Context, Module, ModuleConfig};

use crate::configs::pijul_channel::PijulConfig;
use crate::formatter::StringFormatter;

/// Creates a module with the Pijul channel in the current directory
///
/// Will display the channel lame if the current directory is a pijul repo
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
    let is_repo = context
        .try_begin_scan()?
        .set_folders(&[".pijul"])
        .is_match();

    if !is_repo {
        return None;
    }

    let mut module = context.new_module("pijul_channel");
    let config: PijulConfig = PijulConfig::try_load(module.config);

    // We default to disabled=true, so we have to check after loading our config module.
    if config.disabled {
        return None;
    };

    let channel_name = get_pijul_current_channel(context)?;

    let truncated_text = truncate_text(
        &channel_name,
        config.truncation_length as usize,
        config.truncation_symbol,
    );

    let parsed = StringFormatter::new(config.format).and_then(|formatter| {
        formatter
            .map_meta(|variable, _| match variable {
                "symbol" => Some(config.symbol),
                _ => None,
            })
            .map_style(|variable| match variable {
                "style" => Some(Ok(config.style)),
                _ => None,
            })
            .map(|variable| match variable {
                "channel" => Some(Ok(&truncated_text)),
                _ => None,
            })
            .parse(None, Some(context))
    });

    module.set_segments(match parsed {
        Ok(segments) => segments,
        Err(error) => {
            log::warn!("Error in module `pijul_channel`:\n{}", error);
            return None;
        }
    });

    Some(module)
}

fn get_pijul_current_channel(ctx: &Context) -> Option<String> {
    let output = ctx.exec_cmd("pijul", &["channel"])?.stdout;

    output
        .lines()
        .find_map(|l| l.strip_prefix("* "))
        .map(str::to_owned)
}

#[cfg(test)]
mod tests {
    use nu_ansi_term::{Color, Style};
    use std::io;
    use std::path::Path;

    use crate::test::{fixture_repo, FixtureProvider, ModuleRenderer};

    enum Expect<'a> {
        ChannelName(&'a str),
        Empty,
        NoTruncation,
        Symbol(&'a str),
        Style(Style),
        TruncationSymbol(&'a str),
    }

    #[test]
    fn show_nothing_on_empty_dir() -> io::Result<()> {
        let repo_dir = tempfile::tempdir()?;

        let actual = ModuleRenderer::new("pijul_channel")
            .path(repo_dir.path())
            .collect();

        let expected = None;
        assert_eq!(expected, actual);
        repo_dir.close()
    }

    #[test]
    fn test_pijul_disabled_per_default() -> io::Result<()> {
        let tempdir = fixture_repo(FixtureProvider::Pijul)?;
        let repo_dir = tempdir.path();
        expect_pijul_with_config(
            repo_dir,
            Some(toml::toml! {
                [pijul_channel]
                truncation_length = 14
            }),
            &[Expect::Empty],
        );
        tempdir.close()
    }

    #[test]
    fn test_pijul_autodisabled() -> io::Result<()> {
        let tempdir = tempfile::tempdir()?;
        expect_pijul_with_config(tempdir.path(), None, &[Expect::Empty]);
        tempdir.close()
    }

    #[test]
    fn test_pijul_channel() -> io::Result<()> {
        let tempdir = fixture_repo(FixtureProvider::Pijul)?;
        let repo_dir = tempdir.path();
        run_pijul(&["channel", "new", "tributary-48198"], repo_dir)?;
        run_pijul(&["channel", "switch", "tributary-48198"], repo_dir)?;
        expect_pijul_with_config(
            repo_dir,
            None,
            &[Expect::ChannelName("tributary-48198"), Expect::NoTruncation],
        );
        tempdir.close()
    }

    #[test]
    fn test_pijul_configured() -> io::Result<()> {
        let tempdir = fixture_repo(FixtureProvider::Pijul)?;
        let repo_dir = tempdir.path();
        run_pijul(&["channel", "new", "tributary-48198"], repo_dir)?;
        run_pijul(&["channel", "switch", "tributary-48198"], repo_dir)?;
        expect_pijul_with_config(
            repo_dir,
            Some(toml::toml! {
                [pijul_channel]
                style = "underline blue"
                symbol = "P "
                truncation_length = 14
                truncation_symbol = "%"
                disabled = false
            }),
            &[
                Expect::ChannelName("tributary-4819"),
                Expect::Style(Color::Blue.underline()),
                Expect::Symbol("P"),
                Expect::TruncationSymbol("%"),
            ],
        );
        tempdir.close()
    }

    fn expect_pijul_with_config(
        repo_dir: &Path,
        config: Option<toml::Value>,
        expectations: &[Expect],
    ) {
        let actual = ModuleRenderer::new("pijul_channel")
            .path(repo_dir.to_str().unwrap())
            .config(config.unwrap_or_else(|| {
                toml::toml! {
                    [pijul_channel]
                    disabled = false
                }
            }))
            .collect();

        let mut expect_channel_name = "main";
        let mut expect_style = Color::Purple.bold();
        let mut expect_symbol = "\u{e0a0}";
        let mut expect_truncation_symbol = "…";

        for expect in expectations {
            match expect {
                Expect::Empty => {
                    assert_eq!(None, actual);
                    return;
                }
                Expect::Symbol(symbol) => {
                    expect_symbol = symbol;
                }
                Expect::TruncationSymbol(truncation_symbol) => {
                    expect_truncation_symbol = truncation_symbol;
                }
                Expect::NoTruncation => {
                    expect_truncation_symbol = "";
                }
                Expect::ChannelName(channel_name) => {
                    expect_channel_name = channel_name;
                }
                Expect::Style(style) => expect_style = *style,
            }
        }

        let expected = Some(format!(
            "on {} ",
            expect_style.paint(format!(
                "{expect_symbol} {expect_channel_name}{expect_truncation_symbol}"
            )),
        ));
        assert_eq!(expected, actual);
    }

    fn run_pijul(args: &[&str], _repo_dir: &Path) -> io::Result<()> {
        crate::utils::mock_cmd("pijul", args).ok_or(io::ErrorKind::Unsupported)?;
        Ok(())
    }
}