rash_core 2.17.7

Declarative shell scripting using Rust native bindings
Documentation
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
use crate::context::GlobalParams;
use crate::error::{Error, ErrorKind, Result};
use crate::modules::{MODULES, is_module};
use crate::task::Task;

use std::collections::HashSet;

use serde_norway::Value;

/// TaskValid is a ProtoTask with verified attrs: one module with valid attrs
#[derive(Debug)]
pub struct TaskValid {
    attrs: Value,
}

impl TaskValid {
    pub fn new(attrs: &Value) -> Self {
        TaskValid {
            attrs: attrs.clone(),
        }
    }

    fn get_possible_attrs(&self) -> HashSet<String> {
        self.attrs
            .clone()
            // safe unwrap: validated attr
            .as_mapping()
            .unwrap()
            .iter()
            // safe unwrap: validated attr
            .map(|(key, _)| key.as_str().unwrap().to_owned())
            .collect::<HashSet<String>>()
    }

    fn get_module_name(&'_ self) -> Result<String> {
        let module_names: HashSet<String> = self
            .get_possible_attrs()
            .iter()
            .filter(|&key| is_module(key))
            .map(String::clone)
            .collect();

        match module_names.len() {
            0 => Err(Error::new(
                ErrorKind::NotFound,
                format!("Not module found in task: {self:?}"),
            )),
            1 => Ok(module_names
                .iter()
                .map(String::clone)
                .next()
                //safe unwrap()
                .unwrap()),
            _ => Err(Error::new(
                ErrorKind::InvalidData,
                format!("Multiple modules found in task: {self:?}"),
            )),
        }
    }

    fn parse_array(&'_ self, attr: &Value) -> Option<String> {
        match attr.as_sequence() {
            Some(v) => Some(
                v.iter()
                    .map(|x| self.parse_bool_or_string(x))
                    .collect::<Option<Vec<String>>>()?
                    .iter()
                    .map(|s| format!("({s})"))
                    .collect::<Vec<String>>()
                    .join(" and "),
            ),
            None => self.parse_bool_or_string(attr),
        }
    }

    fn parse_bool_or_string(&'_ self, attr: &Value) -> Option<String> {
        match attr.as_bool() {
            Some(x) => match x {
                true => Some("true".to_owned()),
                false => Some("false".to_owned()),
            },
            None => attr.as_str().map(String::from),
        }
    }

    /// Validate rescue and always attributes (now allowed on any task)
    fn validate_block_only_attributes(&self) -> Result<()> {
        // Rescue and always attributes are now allowed on any task, not just blocks
        // This provides more flexible error handling and cleanup capabilities
        Ok(())
    }

    pub fn get_task<'a>(&self, global_params: &'a GlobalParams) -> Result<Task<'a>> {
        let module_name: &str = &self.get_module_name()?;

        // Validate that rescue and always attributes are only used with block modules
        self.validate_block_only_attributes()?;

        Ok(Task {
            r#become: match global_params.r#become {
                true => true,
                false => self.attrs["become"].as_bool().unwrap_or(false),
            },
            become_user: match self.attrs["become_user"].as_str() {
                Some(s) => s,
                None => global_params.become_user,
            }
            .to_owned(),
            changed_when: self.parse_array(&self.attrs["changed_when"]),
            check_mode: match global_params.check_mode {
                true => true,
                false => self.attrs["check_mode"].as_bool().unwrap_or(false),
            },
            // &dyn Module from &Box<dyn Module>
            module: &**MODULES.get::<str>(module_name).ok_or_else(|| {
                Error::new(
                    ErrorKind::NotFound,
                    format!("Module not found in modules: {:?}", MODULES.keys()),
                )
            })?,
            params: self.attrs[module_name].clone(),
            name: self.attrs["name"].as_str().map(String::from),
            ignore_errors: self.attrs["ignore_errors"].as_bool(),
            r#loop: self.attrs.get("loop").map(|_| self.attrs["loop"].clone()),
            register: self.attrs["register"].as_str().map(String::from),
            vars: self.attrs.get("vars").map(|_| self.attrs["vars"].clone()),
            when: self.parse_array(&self.attrs["when"]),
            rescue: self
                .attrs
                .get("rescue")
                .map(|_| self.attrs["rescue"].clone()),
            always: self
                .attrs
                .get("always")
                .map(|_| self.attrs["always"].clone()),
            environment: self
                .attrs
                .get("environment")
                .map(|_| self.attrs["environment"].clone()),
            global_params,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::context::GlobalParams;
    use serde_norway::Value as YamlValue;

    fn create_test_global_params() -> GlobalParams<'static> {
        GlobalParams::default()
    }

    #[test]
    fn test_rescue_with_debug_module_succeeds() {
        let yaml_str = r#"
        name: test task
        debug:
          msg: test
        rescue:
          - name: rescue task
            debug:
              msg: rescue
        "#;
        let yaml: YamlValue = serde_norway::from_str(yaml_str).unwrap();
        let task_valid = TaskValid::new(&yaml);
        let global_params = create_test_global_params();

        let result = task_valid.get_task(&global_params);
        assert!(result.is_ok());

        let task = result.unwrap();
        assert_eq!(task.name, Some("test task".to_string()));
        assert!(task.rescue.is_some());
        // Verify rescue is an array with one task
        if let Some(YamlValue::Sequence(rescue_tasks)) = &task.rescue {
            assert_eq!(rescue_tasks.len(), 1);
        } else {
            panic!("Expected rescue to be a sequence");
        }
    }

    #[test]
    fn test_always_with_command_module_succeeds() {
        let yaml_str = r#"
        name: test task
        command:
          cmd: echo test
        always:
          - name: always task
            debug:
              msg: always
        "#;
        let yaml: YamlValue = serde_norway::from_str(yaml_str).unwrap();
        let task_valid = TaskValid::new(&yaml);
        let global_params = create_test_global_params();

        let result = task_valid.get_task(&global_params);
        assert!(result.is_ok());

        let task = result.unwrap();
        assert_eq!(task.name, Some("test task".to_string()));
        assert!(task.always.is_some());
        // Verify always is an array with one task
        if let Some(YamlValue::Sequence(always_tasks)) = &task.always {
            assert_eq!(always_tasks.len(), 1);
        } else {
            panic!("Expected always to be a sequence");
        }
    }

    #[test]
    fn test_both_rescue_and_always_with_debug_module_succeeds() {
        let yaml_str = r#"
        name: test task
        debug:
          msg: test
        rescue:
          - name: rescue task
            debug:
              msg: rescue
        always:
          - name: always task
            debug:
              msg: always
        "#;
        let yaml: YamlValue = serde_norway::from_str(yaml_str).unwrap();
        let task_valid = TaskValid::new(&yaml);
        let global_params = create_test_global_params();

        let result = task_valid.get_task(&global_params);
        assert!(result.is_ok());

        let task = result.unwrap();
        assert_eq!(task.name, Some("test task".to_string()));

        // Verify both rescue and always are present
        assert!(task.rescue.is_some());
        assert!(task.always.is_some());

        // Verify rescue is an array with one task
        if let Some(YamlValue::Sequence(rescue_tasks)) = &task.rescue {
            assert_eq!(rescue_tasks.len(), 1);
        } else {
            panic!("Expected rescue to be a sequence");
        }

        // Verify always is an array with one task
        if let Some(YamlValue::Sequence(always_tasks)) = &task.always {
            assert_eq!(always_tasks.len(), 1);
        } else {
            panic!("Expected always to be a sequence");
        }
    }

    #[test]
    fn test_rescue_and_always_with_block_module_succeeds() {
        let yaml_str = r#"
        name: test block
        block:
          - name: main task
            debug:
              msg: main
        rescue:
          - name: rescue task
            debug:
              msg: rescue
        always:
          - name: always task
            debug:
              msg: always
        "#;
        let yaml: YamlValue = serde_norway::from_str(yaml_str).unwrap();
        let task_valid = TaskValid::new(&yaml);
        let global_params = create_test_global_params();

        let result = task_valid.get_task(&global_params);
        assert!(result.is_ok());

        let task = result.unwrap();
        assert_eq!(task.module.get_name(), "block");
        assert!(task.rescue.is_some());
        assert!(task.always.is_some());
    }

    #[test]
    fn test_block_without_rescue_and_always_succeeds() {
        let yaml_str = r#"
        name: test block
        block:
          - name: main task
            debug:
              msg: main
        "#;
        let yaml: YamlValue = serde_norway::from_str(yaml_str).unwrap();
        let task_valid = TaskValid::new(&yaml);
        let global_params = create_test_global_params();

        let result = task_valid.get_task(&global_params);
        assert!(result.is_ok());

        let task = result.unwrap();
        assert_eq!(task.module.get_name(), "block");
        assert!(task.rescue.is_none());
        assert!(task.always.is_none());
    }

    #[test]
    fn test_non_block_task_without_rescue_and_always_succeeds() {
        let yaml_str = r#"
        name: test task
        debug:
          msg: test
        "#;
        let yaml: YamlValue = serde_norway::from_str(yaml_str).unwrap();
        let task_valid = TaskValid::new(&yaml);
        let global_params = create_test_global_params();

        let result = task_valid.get_task(&global_params);
        assert!(result.is_ok());

        let task = result.unwrap();
        assert_eq!(task.module.get_name(), "debug");
        assert!(task.rescue.is_none());
        assert!(task.always.is_none());
    }

    #[test]
    fn test_rescue_with_copy_module_succeeds() {
        let yaml_str = r#"
        name: test copy task
        copy:
          content: "test content"
          dest: "/tmp/test.txt"
        rescue:
          - name: handle copy failure
            debug:
              msg: "Copy failed, cleaning up"
        "#;
        let yaml: YamlValue = serde_norway::from_str(yaml_str).unwrap();
        let task_valid = TaskValid::new(&yaml);
        let global_params = create_test_global_params();

        let result = task_valid.get_task(&global_params);
        assert!(result.is_ok());

        let task = result.unwrap();
        assert_eq!(task.name, Some("test copy task".to_string()));
        assert!(task.rescue.is_some());
        assert!(task.always.is_none());
    }

    #[test]
    fn test_always_with_file_module_succeeds() {
        let yaml_str = r#"
        name: test file task
        file:
          path: "/tmp/testfile"
          state: touch
        always:
          - name: cleanup
            debug:
              msg: "Always running cleanup"
        "#;
        let yaml: YamlValue = serde_norway::from_str(yaml_str).unwrap();
        let task_valid = TaskValid::new(&yaml);
        let global_params = create_test_global_params();

        let result = task_valid.get_task(&global_params);
        assert!(result.is_ok());

        let task = result.unwrap();
        assert_eq!(task.name, Some("test file task".to_string()));
        assert!(task.rescue.is_none());
        assert!(task.always.is_some());
    }

    #[test]
    fn test_rescue_and_always_with_loop_succeeds() {
        let yaml_str = r#"
        name: test loop with rescue/always
        debug:
          msg: "Item: {{ item }}"
        loop:
          - one
          - two
          - three
        rescue:
          - name: handle loop failure
            debug:
              msg: "Loop item failed: {{ item }}"
        always:
          - name: loop cleanup
            debug:
              msg: "Cleaning up after loop item: {{ item }}"
        "#;
        let yaml: YamlValue = serde_norway::from_str(yaml_str).unwrap();
        let task_valid = TaskValid::new(&yaml);
        let global_params = create_test_global_params();

        let result = task_valid.get_task(&global_params);
        assert!(result.is_ok());

        let task = result.unwrap();
        assert_eq!(task.name, Some("test loop with rescue/always".to_string()));
        assert!(task.rescue.is_some());
        assert!(task.always.is_some());
        assert!(task.r#loop.is_some());
    }

    #[test]
    fn test_rescue_and_always_empty_sequences_succeeds() {
        let yaml_str = r#"
        name: test empty rescue/always
        debug:
          msg: "test"
        rescue: []
        always: []
        "#;
        let yaml: YamlValue = serde_norway::from_str(yaml_str).unwrap();
        let task_valid = TaskValid::new(&yaml);
        let global_params = create_test_global_params();

        let result = task_valid.get_task(&global_params);
        assert!(result.is_ok());

        let task = result.unwrap();
        assert_eq!(task.name, Some("test empty rescue/always".to_string()));
        assert!(task.rescue.is_some());
        assert!(task.always.is_some());

        // Verify they are empty sequences
        if let Some(YamlValue::Sequence(rescue_tasks)) = &task.rescue {
            assert_eq!(rescue_tasks.len(), 0);
        } else {
            panic!("Expected rescue to be a sequence");
        }

        if let Some(YamlValue::Sequence(always_tasks)) = &task.always {
            assert_eq!(always_tasks.len(), 0);
        } else {
            panic!("Expected always to be a sequence");
        }
    }
}