Skip to content

Commit

Permalink
feat(module): Add pacman
Browse files Browse the repository at this point in the history
Resolves: #175
  • Loading branch information
pando85 committed Sep 20, 2023
1 parent f47bdb4 commit d8a3fc5
Show file tree
Hide file tree
Showing 16 changed files with 1,151 additions and 70 deletions.
5 changes: 3 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 15 additions & 0 deletions examples/pacman.rh
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#!/usr/bin/env rash
- name: test pacman module
pacman:
executable: "{{ rash.dir }}/../rash_core/tests/mocks/pacman.rh"
upgrade: true
force: true
name:
- rustup
- bpftrace
- linux61-zfs
state: sync
register: packages

- debug:
msg: "{{ packages.extra | json_encode }}"
2 changes: 1 addition & 1 deletion examples/task.rh
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
- debug:
var: "find_result.extra"

- name: "save password to multiple files"
- name: save password to multiple files
copy:
content: "{{ env.MY_PASSWORD }}"
dest: "/tmp/MY_PASSWORD_FILE_{{ file_name }}"
Expand Down
1 change: 1 addition & 0 deletions rash_core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ nix = { version = "0.27", features = ["process", "user"] }
serde = { version = "1.0", features = ["derive"] }
serde-error = "0.1"
serde_with = "3.3"
shlex = "1.2"
similar = { version = "2.2", features = ["inline"] }
strum = "0.25"
strum_macros = "0.25"
Expand Down
49 changes: 32 additions & 17 deletions rash_core/src/logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,36 @@ fn get_terminal_width() -> usize {
term_size::dimensions().map(|(w, _)| w).unwrap_or(80)
}

/// Print iterator.
fn print_diff<T>(iter: T, prefix: &str, style: &Style)
where
T: IntoIterator,
T::Item: fmt::Display,
{
if log_enabled!(target: "diff", log::Level::Info) {
iter.into_iter()
.for_each(|x| println!("{}{}", style.apply_to(prefix), style.apply_to(x)));
};
}

/// Print add iterator.
pub fn add<T>(iter: T)
where
T: IntoIterator,
T::Item: fmt::Display,
{
print_diff(iter, "+ ", &Style::new().green());
}

/// Print remove iterator.
pub fn remove<T>(iter: T)
where
T: IntoIterator,
T::Item: fmt::Display,
{
print_diff(iter, "- ", &Style::new().red());
}

/// Print formatted diff for files.
pub fn diff_files<T, U>(original: T, modified: U)
where
Expand Down Expand Up @@ -162,23 +192,8 @@ fn ansible_log_format(out: FormatCallback, message: &fmt::Arguments, record: &lo
))
}

fn raw_log_format(out: FormatCallback, message: &fmt::Arguments, record: &log::Record) {
out.finish(format_args!(
"{color_line}{message}\x1B[0m",
color_line = format_args!(
"\x1B[{}m",
match (record.level(), record.target()) {
(log::Level::Error, _) => Color::Red,
(log::Level::Warn, _) => Color::Magenta,
(log::Level::Info, _) => Color::White,
(log::Level::Debug, _) => Color::BrightBlue,
(log::Level::Trace, "error") => Color::Red,
(log::Level::Trace, _) => Color::BrightBlack,
}
.to_fg_str()
),
message = &message,
))
fn raw_log_format(out: FormatCallback, message: &fmt::Arguments, _record: &log::Record) {
out.finish(format_args!("{message}"))
}

/// Setup logging according to the specified verbosity.
Expand Down
8 changes: 3 additions & 5 deletions rash_core/src/modules/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,19 +157,17 @@ impl Module for Command {
.map_err(|e| Error::new(ErrorKind::SubprocessFail, e))?;

trace!("exec - output: {:?}", output);
let stderr = String::from_utf8(output.stderr)
.map_err(|e| Error::new(ErrorKind::InvalidData, e))?;
let stderr = String::from_utf8_lossy(&output.stderr);

if !output.status.success() {
return Err(Error::new(ErrorKind::InvalidData, stderr));
}
let output_string = String::from_utf8(output.stdout)
.map_err(|e| Error::new(ErrorKind::InvalidData, e))?;
let output_string = String::from_utf8_lossy(&output.stdout);

let module_output = if output_string.is_empty() {
None
} else {
Some(output_string)
Some(output_string.into_owned())
};

let extra = Some(value::to_value(json!({
Expand Down
3 changes: 1 addition & 2 deletions rash_core/src/modules/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
///
/// - file:
/// path: /yea
/// state: present
/// mode: 0644
/// ```
/// ANCHOR_END: examples
Expand Down Expand Up @@ -63,7 +62,7 @@ pub struct Params {
/// If _file_, even with other options (such as mode), the file will be modified if it exists but
/// will NOT be created if it does not exist.
/// If _touch_, an empty file will be created if the file does not exist.
/// **[default: file]**
/// **[default: `"file"`]**
state: Option<State>,
}

Expand Down
22 changes: 9 additions & 13 deletions rash_core/src/modules/find.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
/// ```
/// ANCHOR_END: examples
use crate::error::{Error, ErrorKind, Result};
use crate::modules::utils::default_false;
use crate::modules::{parse_if_json, parse_params, Module, ModuleResult};
use crate::vars::Vars;

Expand All @@ -47,12 +48,11 @@ use schemars::schema::RootSchema;
use schemars::JsonSchema;
use serde::Deserialize;
use serde_with::{serde_as, OneOrMany};
use serde_yaml::value;
use serde_yaml::Value;
use serde_yaml::{value, Value};
#[cfg(feature = "docs")]
use strum_macros::{Display, EnumString};

#[derive(Debug, Default, PartialEq, Deserialize)]
#[derive(Default, Debug, PartialEq, Deserialize)]
#[cfg_attr(feature = "docs", derive(EnumString, Display, JsonSchema))]
#[serde(rename_all = "lowercase")]
enum FileType {
Expand All @@ -67,10 +67,6 @@ fn default_file_type() -> Option<FileType> {
Some(FileType::default())
}

fn default_false() -> Option<bool> {
Some(false)
}

#[serde_as]
#[derive(Debug, PartialEq, Deserialize)]
#[cfg_attr(feature = "docs", derive(JsonSchema, DocJsonSchema))]
Expand All @@ -84,15 +80,15 @@ pub struct Params {
#[serde(default)]
excludes: Option<Vec<String>>,
/// Type of file to select.
/// **[default: file]**
/// **[default: `"file"`]**
#[serde(default = "default_file_type")]
file_type: Option<FileType>,
/// Set this to true to follow symlinks
/// **[default: false]**
/// **[default: `false`]**
#[serde(default = "default_false")]
follow: Option<bool>,
/// Set this to yes to include hidden files, otherwise they will be ignored.
/// **[default: false]**
/// **[default: `false`]**
#[serde(default = "default_false")]
hidden: Option<bool>,
/// The patterns restrict the list of files to be returned to those whose basenames
Expand All @@ -102,7 +98,7 @@ pub struct Params {
#[serde(default)]
patterns: Option<Vec<String>>,
/// If target is a directory, recursively descend into the directory looking for files.
/// **[default: false]**
/// **[default: `false`]**
#[serde(default = "default_false")]
recurse: Option<bool>,
/// Select files whose size is less than the specified size.
Expand All @@ -112,11 +108,11 @@ pub struct Params {
size: Option<String>,
}

#[cfg(test)]
impl Default for Params {
fn default() -> Self {
let paths: Vec<String> = Vec::new();
Params {
paths,
paths: Vec::new(),
excludes: None,
file_type: Some(FileType::default()),
follow: Some(false),
Expand Down
4 changes: 4 additions & 0 deletions rash_core/src/modules/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@ mod copy;
mod debug;
mod file;
mod find;
mod pacman;
mod set_vars;
mod template;
mod utils;

use crate::error::{Error, ErrorKind, Result};
use crate::modules::assert::Assert;
Expand All @@ -14,6 +16,7 @@ use crate::modules::copy::Copy;
use crate::modules::debug::Debug;
use crate::modules::file::File;
use crate::modules::find::Find;
use crate::modules::pacman::Pacman;
use crate::modules::set_vars::SetVars;
use crate::modules::template::Template;
use crate::vars::Vars;
Expand Down Expand Up @@ -85,6 +88,7 @@ lazy_static! {
(Debug.get_name(), Box::new(Debug) as Box<dyn Module>),
(File.get_name(), Box::new(File) as Box<dyn Module>),
(Find.get_name(), Box::new(Find) as Box<dyn Module>),
(Pacman.get_name(), Box::new(Pacman) as Box<dyn Module>),
(SetVars.get_name(), Box::new(SetVars) as Box<dyn Module>),
(Template.get_name(), Box::new(Template) as Box<dyn Module>),
]
Expand Down
Loading

0 comments on commit d8a3fc5

Please sign in to comment.