summaryrefslogtreecommitdiffstats
path: root/src/modules/kotlin.rs
blob: 74de1ae0c094fb3707c1e9509ad1c8e37e5d3ff2 (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
use super::{Context, Module, RootModuleConfig};

use crate::configs::kotlin::KotlinConfig;
use crate::formatter::StringFormatter;
use crate::formatter::VersionFormatter;

use regex::Regex;
const KOTLIN_VERSION_PATTERN: &str = "(?P<version>[\\d\\.]+[\\d\\.]+[\\d\\.]+)";

/// Creates a module with the current Kotlin version
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
    let mut module = context.new_module("kotlin");
    let config = KotlinConfig::try_load(module.config);

    let is_kotlin_project = context
        .try_begin_scan()?
        .set_files(&config.detect_files)
        .set_extensions(&config.detect_extensions)
        .set_folders(&config.detect_folders)
        .is_match();

    if !is_kotlin_project {
        return None;
    }

    let parsed = StringFormatter::new(config.format).and_then(|formatter| {
        formatter
            .map_meta(|var, _| match var {
                "symbol" => Some(config.symbol),
                _ => None,
            })
            .map_style(|variable| match variable {
                "style" => Some(Ok(config.style)),
                _ => None,
            })
            .map(|variable| match variable {
                "version" => {
                    let kotlin_version = get_kotlin_version(context, &config.kotlin_binary)?;
                    VersionFormatter::format_module_version(
                        module.get_name(),
                        &kotlin_version,
                        config.version_format,
                    )
                    .map(Ok)
                }
                _ => None,
            })
            .parse(None)
    });

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

    Some(module)
}

fn get_kotlin_version(context: &Context, kotlin_binary: &str) -> Option<String> {
    match context.exec_cmd(kotlin_binary, &["-version"]) {
        Some(output) => {
            let kotlin_output = if output.stdout.is_empty() {
                output.stderr
            } else {
                output.stdout
            };
            parse_kotlin_version(&kotlin_output)
        }
        None => None,
    }
}

fn parse_kotlin_version(kotlin_stdout: &str) -> Option<String> {
    // kotlin -version output looks like this:
    // Kotlin version 1.4.21-release-411 (JRE 14.0.1+7)
    // kotlinc -version output looks like this:
    // info: kotlinc-jvm 1.4.21 (JRE 14.0.1+7)
    let re = Regex::new(KOTLIN_VERSION_PATTERN).ok()?;
    let captures = re.captures(kotlin_stdout)?;
    let version = &captures["version"];
    Some(version.to_string())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test::ModuleRenderer;
    use ansi_term::Color;
    use std::fs::File;
    use std::io;

    #[test]
    fn folder_without_kotlin_files() -> io::Result<()> {
        let dir = tempfile::tempdir()?;
        let actual = ModuleRenderer::new("kotlin").path(dir.path()).collect();
        let expected = None;
        assert_eq!(expected, actual);
        dir.close()
    }

    #[test]
    fn folder_with_kotlin_file() -> io::Result<()> {
        let dir = tempfile::tempdir()?;
        File::create(dir.path().join("main.kt"))?.sync_all()?;
        let actual = ModuleRenderer::new("kotlin").path(dir.path()).collect();
        let expected = Some(format!("via {}", Color::Blue.bold().paint("🅺 v1.4.21 ")));
        assert_eq!(expected, actual);
        dir.close()
    }

    #[test]
    fn folder_with_kotlin_script_file() -> io::Result<()> {
        let dir = tempfile::tempdir()?;
        File::create(dir.path().join("main.kts"))?.sync_all()?;
        let actual = ModuleRenderer::new("kotlin").path(dir.path()).collect();
        let expected = Some(format!("via {}", Color::Blue.bold().paint("🅺 v1.4.21 ")));
        assert_eq!(expected, actual);
        dir.close()
    }

    #[test]
    fn kotlin_binary_is_kotlin_runtime() -> io::Result<()> {
        let dir = tempfile::tempdir()?;
        File::create(dir.path().join("main.kt"))?.sync_all()?;

        let config = toml::toml! {
             [kotlin]
             kotlin_binary = "kotlin"
        };

        let actual = ModuleRenderer::new("kotlin")
            .path(dir.path())
            .config(config)
            .collect();

        let expected = Some(format!("via {}", Color::Blue.bold().paint("🅺 v1.4.21 ")));
        assert_eq!(expected, actual);
        dir.close()
    }

    #[test]
    fn kotlin_binary_is_kotlin_compiler() -> io::Result<()> {
        let dir = tempfile::tempdir()?;
        File::create(dir.path().join("main.kt"))?.sync_all()?;

        let config = toml::toml! {
             [kotlin]
             kotlin_binary = "kotlinc"
        };

        let actual = ModuleRenderer::new("kotlin")
            .path(dir.path())
            .config(config)
            .collect();

        let expected = Some(format!("via {}", Color::Blue.bold().paint("🅺 v1.4.21 ")));
        assert_eq!(expected, actual);
        dir.close()
    }

    #[test]
    fn test_parse_kotlin_version_from_runtime() {
        let kotlin_input = "Kotlin version 1.4.21-release-411 (JRE 14.0.1+7)";
        assert_eq!(
            parse_kotlin_version(kotlin_input),
            Some("1.4.21".to_string())
        );
    }

    #[test]
    fn test_parse_kotlin_version_from_compiler() {
        let kotlin_input = "info: kotlinc-jvm 1.4.21 (JRE 14.0.1+7)";
        assert_eq!(
            parse_kotlin_version(kotlin_input),
            Some("1.4.21".to_string())
        );
    }
}