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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
//! # condition
//!
//! Evaluates conditions based on task configuration and current env.
//!

#[cfg(test)]
#[path = "condition_test.rs"]
mod condition_test;

use crate::environment;
use crate::profile;
use crate::scriptengine;
use crate::types;
use crate::types::{
    ConditionScriptValue, FlowInfo, RustVersionCondition, ScriptValue, Step, TaskCondition,
};
use crate::version::{is_newer, is_same};
use envmnt;
use fsio;
use fsio::path::from_path::FromPath;
use glob::glob;
use indexmap::IndexMap;
use rust_info;
use rust_info::types::{RustChannel, RustInfo};
use std::path::Path;

fn validate_env_map(env: Option<IndexMap<String, String>>, equal: bool) -> bool {
    match env {
        Some(env_vars) => {
            let mut all_valid = true;

            for (key, current_value) in env_vars.iter() {
                if (equal && !envmnt::is_equal(key, current_value))
                    || (!equal && !envmnt::contains_ignore_case(key, current_value))
                {
                    all_valid = false;
                    break;
                }
            }

            all_valid
        }
        None => true,
    }
}

fn validate_env(condition: &TaskCondition) -> bool {
    validate_env_map(condition.env.clone(), true)
}

fn validate_env_contains(condition: &TaskCondition) -> bool {
    validate_env_map(condition.env_contains.clone(), false)
}

fn validate_env_set(condition: &TaskCondition) -> bool {
    let env = condition.env_set.clone();

    match env {
        Some(env_vars) => {
            let mut all_valid = true;

            for key in env_vars.iter() {
                if !envmnt::exists(key) {
                    all_valid = false;
                    break;
                }
            }

            all_valid
        }
        None => true,
    }
}

fn validate_env_not_set(condition: &TaskCondition) -> bool {
    let env = condition.env_not_set.clone();

    match env {
        Some(env_vars) => {
            let mut all_valid = true;

            for key in env_vars.iter() {
                if envmnt::exists(key) {
                    all_valid = false;
                    break;
                }
            }

            all_valid
        }
        None => true,
    }
}

fn validate_env_bool(condition: &TaskCondition, truthy: bool) -> bool {
    let env = if truthy {
        condition.env_true.clone()
    } else {
        condition.env_false.clone()
    };

    match env {
        Some(env_vars) => {
            let mut all_valid = true;

            for key in env_vars.iter() {
                let is_true = envmnt::is_or(key, !truthy);

                if is_true != truthy {
                    all_valid = false;
                    break;
                }
            }

            all_valid
        }
        None => true,
    }
}

fn validate_os(condition: &TaskCondition) -> bool {
    let os = condition.os.clone();
    match os {
        Some(os_names) => {
            let os_name = envmnt::get_or("CARGO_MAKE_RUST_TARGET_OS", "");
            let index = os_names.iter().position(|value| *value == os_name);

            match index {
                None => {
                    debug!("Failed OS condition, current OS: {}", &os_name);
                    false
                }
                _ => true,
            }
        }
        None => true,
    }
}

fn validate_platform(condition: &TaskCondition) -> bool {
    let platforms = condition.platforms.clone();
    match platforms {
        Some(platform_names) => {
            let platform_name = types::get_platform_name();

            let index = platform_names
                .iter()
                .position(|value| *value == platform_name);

            match index {
                None => {
                    debug!(
                        "Failed platform condition, current platform: {}",
                        &platform_name
                    );
                    false
                }
                _ => true,
            }
        }
        None => true,
    }
}

fn validate_profile(condition: &TaskCondition) -> bool {
    let profiles = condition.profiles.clone();
    match profiles {
        Some(profile_names) => {
            let profile_name = profile::get();

            let index = profile_names
                .iter()
                .position(|value| *value == profile_name);

            match index {
                None => {
                    debug!(
                        "Failed profile condition, current profile: {}",
                        &profile_name
                    );
                    false
                }
                _ => true,
            }
        }
        None => true,
    }
}

fn validate_channel(condition: &TaskCondition, flow_info_option: Option<&FlowInfo>) -> bool {
    match flow_info_option {
        Some(flow_info) => {
            let channels = condition.channels.clone();
            match channels {
                Some(channel_names) => match flow_info.env_info.rust_info.channel {
                    Some(value) => {
                        let index = match value {
                            RustChannel::Stable => channel_names
                                .iter()
                                .position(|value| *value == "stable".to_string()),
                            RustChannel::Beta => channel_names
                                .iter()
                                .position(|value| *value == "beta".to_string()),
                            RustChannel::Nightly => channel_names
                                .iter()
                                .position(|value| *value == "nightly".to_string()),
                        };

                        match index {
                            None => {
                                debug!("Failed channel condition");
                                false
                            }
                            _ => true,
                        }
                    }
                    None => false,
                },
                None => true,
            }
        }
        None => true,
    }
}

fn validate_rust_version_condition(rustinfo: RustInfo, condition: RustVersionCondition) -> bool {
    if rustinfo.version.is_some() {
        let current_version = rustinfo.version.unwrap();

        let mut valid = match condition.min {
            Some(version) => {
                is_same(&version, &current_version, true, true)
                    || is_newer(&version, &current_version, true, true)
            }
            None => true,
        };

        if valid {
            valid = match condition.max {
                Some(version) => {
                    is_same(&version, &current_version, true, true)
                        || is_newer(&current_version, &version, true, true)
                }
                None => true,
            };
        }

        if valid {
            valid = match condition.equal {
                Some(version) => is_same(&version, &current_version, true, true),
                None => true,
            };
        }

        valid
    } else {
        true
    }
}

fn validate_rust_version(condition: &TaskCondition) -> bool {
    let rust_version = condition.rust_version.clone();
    match rust_version {
        Some(rust_version_condition) => {
            let rustinfo = rust_info::get();

            validate_rust_version_condition(rustinfo, rust_version_condition)
        }
        None => true,
    }
}

fn validate_files(file_paths: &Vec<String>, exist: bool) -> bool {
    for file_path in file_paths.iter() {
        let expanded_file_path = environment::expand_value(file_path);
        let path = Path::new(&expanded_file_path);

        if path.exists() != exist {
            return false;
        }
    }

    true
}

fn validate_files_exist(condition: &TaskCondition) -> bool {
    let files = condition.files_exist.clone();
    match files {
        Some(ref file_paths) => validate_files(file_paths, true),
        None => true,
    }
}

fn validate_files_not_exist(condition: &TaskCondition) -> bool {
    let files = condition.files_not_exist.clone();
    match files {
        Some(ref file_paths) => validate_files(file_paths, false),
        None => true,
    }
}

fn validate_files_modified(condition: &TaskCondition) -> bool {
    match &condition.files_modified {
        Some(files_modified) => {
            if files_modified.input.len() == 0 {
                return true;
            }

            let mut latest_binary = 0;
            for glob_pattern in &files_modified.output {
                let glob_pattern = environment::expand_value(glob_pattern);
                match glob(&glob_pattern) {
                    Ok(paths) => {
                        for entry in paths {
                            match entry {
                                Ok(path_value) => {
                                    if path_value.is_file() {
                                        let value_string: String = FromPath::from_path(&path_value);
                                        match fsio::path::get_last_modified_time(&value_string) {
                                            Ok(last_modified_time) => {
                                                if last_modified_time > latest_binary {
                                                    latest_binary = last_modified_time;
                                                }
                                            }
                                            Err(error) => {
                                                error!(
                                            "Unable to extract last modified time for path: {} {:#?}",
                                            &value_string, &error
                                        )
                                            }
                                        }
                                    }
                                }
                                Err(error) => {
                                    error!(
                                        "Unable to process paths for glob: {} {:#?}",
                                        &glob_pattern, &error
                                    )
                                }
                            }
                        }
                    }
                    Err(error) => {
                        error!(
                            "Unable to fetch paths for glob: {} {:#?}",
                            &glob_pattern, &error
                        )
                    }
                }
            }

            if latest_binary == 0 {
                true
            } else {
                for glob_pattern in &files_modified.input {
                    let glob_pattern = environment::expand_value(glob_pattern);
                    match glob(&glob_pattern) {
                        Ok(paths) => {
                            let mut paths_found = false;
                            for entry in paths {
                                paths_found = true;

                                match entry {
                                    Ok(path_value) => {
                                        if path_value.is_file() {
                                            let value_string: String =
                                                FromPath::from_path(&path_value);
                                            match fsio::path::get_last_modified_time(&value_string)
                                            {
                                                Ok(last_modified_time) => {
                                                    if last_modified_time > latest_binary {
                                                        return true;
                                                    }
                                                }
                                                Err(error) => {
                                                    error!(
                                            "Unable to extract last modified time for path: {} {:#?}",
                                            &value_string, &error
                                        )
                                                }
                                            }
                                        }
                                    }
                                    Err(error) => {
                                        error!(
                                            "Unable to process paths for glob: {} {:#?}",
                                            &glob_pattern, &error
                                        )
                                    }
                                }
                            }

                            if !paths_found {
                                error!("Unable to find input files for pattern: {}", &glob_pattern);
                            }
                        }
                        Err(error) => {
                            error!(
                                "Unable to fetch paths for glob: {} {:#?}",
                                &glob_pattern, &error
                            )
                        }
                    }
                }

                // all sources (input) are older than binaries (output)
                false
            }
        }
        None => true,
    }
}

fn validate_criteria(flow_info: Option<&FlowInfo>, condition: &Option<TaskCondition>) -> bool {
    match condition {
        Some(ref condition_struct) => {
            debug!("Checking task condition structure.");

            validate_os(&condition_struct)
                && validate_platform(&condition_struct)
                && validate_profile(&condition_struct)
                && validate_channel(&condition_struct, flow_info)
                && validate_env(&condition_struct)
                && validate_env_set(&condition_struct)
                && validate_env_not_set(&condition_struct)
                && validate_env_bool(&condition_struct, true)
                && validate_env_bool(&condition_struct, false)
                && validate_env_contains(&condition_struct)
                && validate_rust_version(&condition_struct)
                && validate_files_exist(&condition_struct)
                && validate_files_not_exist(&condition_struct)
                && validate_files_modified(&condition_struct)
        }
        None => true,
    }
}

pub(crate) fn get_script_text(script: &ConditionScriptValue) -> Vec<String> {
    match script {
        ConditionScriptValue::SingleLine(text) => vec![text.clone()],
        ConditionScriptValue::Text(text) => text.clone(),
    }
}

fn validate_script(
    condition_script: &Option<ConditionScriptValue>,
    script_runner: Option<String>,
) -> bool {
    match condition_script {
        Some(ref script) => {
            debug!("Checking task condition script.");

            let script_text = get_script_text(script);
            return scriptengine::invoke_script_pre_flow(
                &ScriptValue::Text(script_text),
                script_runner,
                None,
                None,
                false,
                &vec![],
            );
        }
        None => true,
    }
}

pub(crate) fn validate_conditions_without_context(condition: TaskCondition) -> bool {
    validate_criteria(None, &Some(condition))
}

pub(crate) fn validate_conditions(
    flow_info: &FlowInfo,
    condition: &Option<TaskCondition>,
    condition_script: &Option<ConditionScriptValue>,
    script_runner: Option<String>,
) -> bool {
    validate_criteria(Some(&flow_info), &condition)
        && validate_script(&condition_script, script_runner)
}

pub(crate) fn validate_condition_for_step(flow_info: &FlowInfo, step: &Step) -> bool {
    validate_conditions(
        &flow_info,
        &step.config.condition,
        &step.config.condition_script,
        step.config.script_runner.clone(),
    )
}