summaryrefslogtreecommitdiffstats
path: root/src/commands/util.rs
blob: 3b63c1d58f25e88ae5c468a1441f317a9faf5c57 (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
//
// Copyright (c) 2020-2021 science+computing ag and other contributors
//
// This program and the accompanying materials are made
// available under the terms of the Eclipse Public License 2.0
// which is available at https://www.eclipse.org/legal/epl-2.0/
//
// SPDX-License-Identifier: EPL-2.0
//

use std::io::Write;
use std::fmt::Display;
use std::path::Path;

use anyhow::Context;
use anyhow::Error;
use anyhow::Result;
use anyhow::anyhow;
use clap::ArgMatches;
use itertools::Itertools;
use log::{error, info, trace};
use regex::Regex;
use tokio_stream::StreamExt;

use crate::config::*;
use crate::package::Package;
use crate::package::PhaseName;
use crate::package::ScriptBuilder;
use crate::package::Shebang;

/// Helper for getting a boolean value by name form the argument object
pub fn getbool(m: &ArgMatches, name: &str, cmp: &str) -> bool {
    // unwrap is safe here because clap is configured with default values
    m.values_of(name).unwrap().any(|v| v == cmp)
}

/// Helper function to lint all packages in an interator
pub async fn lint_packages<'a, I>(
    iter: I,
    linter: &Path,
    config: &Configuration,
    bar: indicatif::ProgressBar,
) -> Result<()>
where
    I: Iterator<Item = &'a Package> + 'a,
{
    let shebang = Shebang::from(config.shebang().clone());
    let lint_results = iter
        .map(|pkg| {
            let shebang = shebang.clone();
            let bar = bar.clone();
            async move {
                trace!("Linting script of {} {} with '{}'", pkg.name(), pkg.version(), linter.display());
                let _ = all_phases_available(pkg, config.available_phases())?;

                let cmd = tokio::process::Command::new(linter);
                let script = ScriptBuilder::new(&shebang)
                    .build(pkg, config.available_phases(), *config.strict_script_interpolation())?;

                let (status, stdout, stderr) = script.lint(cmd).await?;
                bar.inc(1);
                Ok((pkg.name().clone(), pkg.version().clone(), status, stdout, stderr))
            }
        })
        .collect::<futures::stream::FuturesUnordered<_>>()
        .collect::<Result<Vec<_>>>()
        .await?
        .into_iter()
        .map(|tpl| {
            let pkg_name = tpl.0;
            let pkg_vers = tpl.1;
            let status = tpl.2;
            let stdout = tpl.3;
            let stderr = tpl.4;

            if status.success() {
                info!("Linting {pkg_name} {pkg_vers} script ({status}):\nstdout:\n{stdout}\n\nstderr:\n\n{stderr}",
                    pkg_name = pkg_name,
                    pkg_vers = pkg_vers,
                    status = status,
                    stdout = stdout,
                    stderr = stderr
                );
                true
            } else {
                error!("Linting {pkg_name} {pkg_vers} errored ({status}):\n\nstdout:\n{stdout}\n\nstderr:\n{stderr}\n\n",
                    pkg_name = pkg_name,
                    pkg_vers = pkg_vers,
                    status = status,
                    stdout = stdout,
                    stderr = stderr
                );
                false
            }
        })
        .collect::<Vec<_>>();

    let lint_ok = lint_results.iter().all(|b| *b);

    if !lint_ok {
        bar.finish_with_message("Linting errored");
        return Err(anyhow!("Linting was not successful"));
    } else {
        bar.finish_with_message(&format!(
            "Finished linting {} package scripts",
            lint_results.len()
        ));
        Ok(())
    }
}

fn all_phases_available(pkg: &Package, available_phases: &[PhaseName]) -> Result<()> {
    let package_phasenames = pkg.phases().keys().collect::<Vec<_>>();

    if let Some(phase) = package_phasenames
        .iter()
        .find(|name| !available_phases.contains(name))
    {
        return Err(anyhow!(
            "Phase '{}' available in {} {}, but not in config",
            phase.as_str(),
            pkg.name(),
            pkg.version()
        ));
    }

    if let Some(phase) = available_phases
        .iter()
        .find(|name| !package_phasenames.contains(name))
    {
        return Err(anyhow!(
            "Phase '{}' not configured in {} {}",
            phase.as_str(),
            pkg.name(),
            pkg.version()
        ));
    }

    Ok(())
}

pub fn mk_package_name_regex(regex: &str) -> Result<Regex> {
    let mut builder = regex::RegexBuilder::new(regex);

    #[allow(clippy::identity_op)]
    builder.size_limit(1 * 1024 * 1024); // max size for the regex is 1MB. Should be enough for everyone

    builder
        .build()
        .with_context(|| anyhow!("Failed to build regex from '{}'", regex))
        .map_err(Error::from)
}


pub fn mk_header(vec: Vec<&str>) -> Vec<ascii_table::Column> {
    vec.into_iter()
        .map(|name| ascii_table::Column {
            header: name.into(),
            align: ascii_table::Align::Left,
            ..Default::default()
        })
        .collect()
}

/// Display the passed data as nice ascii table,
/// or, if stdout is a pipe, print it nicely parseable
pub fn display_data<D: Display>(
    headers: Vec<ascii_table::Column>,
    data: Vec<Vec<D>>,
    csv: bool,
) -> Result<()> {
    if csv {
        use csv::WriterBuilder;
        let mut wtr = WriterBuilder::new().from_writer(vec![]);
        for record in data.into_iter() {
            let r: Vec<String> = record.into_iter().map(|e| e.to_string()).collect();

            wtr.write_record(&r)?;
        }

        let out = std::io::stdout();
        let mut lock = out.lock();

        wtr.into_inner()
            .map_err(Error::from)
            .and_then(|t| String::from_utf8(t).map_err(Error::from))
            .and_then(|text| writeln!(lock, "{}", text).map_err(Error::from))
    } else if atty::is(atty::Stream::Stdout) {
        let mut ascii_table = ascii_table::AsciiTable {
            columns: Default::default(),
            max_width: terminal_size::terminal_size()
                .map(|tpl| tpl.0 .0 as usize) // an ugly interface indeed!
                .unwrap_or(80),
        };

        headers.into_iter().enumerate().for_each(|(i, c)| {
            ascii_table.columns.insert(i, c);
        });

        ascii_table.print(data);
        Ok(())
    } else {
        let out = std::io::stdout();
        let mut lock = out.lock();
        for list in data {
            writeln!(lock, "{}", list.iter().map(|d| d.to_string()).join(" "))?;
        }
        Ok(())
    }
}