Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add --system-root parameter, systemRoot() and path() functions to dsc #589

Merged
merged 17 commits into from
Nov 17, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions dsc/src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ pub enum SubCommand {
parameters: Option<String>,
#[clap(short = 'f', long, help = "Parameters to pass to the configuration as a JSON or YAML file", conflicts_with = "parameters")]
parameters_file: Option<String>,
#[clap(short = 'm', long, help = "Mounted path to use for supported resources")]
mounted_path: Option<String>,
// Used to inform when DSC is used as a group resource to modify it's output
#[clap(long, hide = true)]
as_group: bool,
Expand Down
6 changes: 3 additions & 3 deletions dsc/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,19 +68,19 @@ fn main() {
let mut cmd = Args::command();
generate(shell, &mut cmd, "dsc", &mut io::stdout());
},
SubCommand::Config { subcommand, parameters, parameters_file, as_group, as_include } => {
SubCommand::Config { subcommand, parameters, parameters_file, mounted_path, as_group, as_include } => {
if let Some(file_name) = parameters_file {
info!("Reading parameters from file {file_name}");
match std::fs::read_to_string(&file_name) {
Ok(parameters) => subcommand::config(&subcommand, &Some(parameters), &input, &as_group, &as_include),
Ok(parameters) => subcommand::config(&subcommand, &Some(parameters), &mounted_path, &input, &as_group, &as_include),
Err(err) => {
error!("Error: Failed to read parameters file '{file_name}': {err}");
exit(util::EXIT_INVALID_INPUT);
}
}
}
else {
subcommand::config(&subcommand, &parameters, &input, &as_group, &as_include);
subcommand::config(&subcommand, &parameters, &mounted_path, &input, &as_group, &as_include);
}
},
SubCommand::Resource { subcommand } => {
Expand Down
6 changes: 5 additions & 1 deletion dsc/src/subcommand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ fn initialize_config_root(path: &Option<String>) -> Option<String> {
}

#[allow(clippy::too_many_lines)]
pub fn config(subcommand: &ConfigSubCommand, parameters: &Option<String>, stdin: &Option<String>, as_group: &bool, as_include: &bool) {
pub fn config(subcommand: &ConfigSubCommand, parameters: &Option<String>, mounted_path: &Option<String>, stdin: &Option<String>, as_group: &bool, as_include: &bool) {
let (new_parameters, json_string) = match subcommand {
ConfigSubCommand::Get { document, path, .. } |
ConfigSubCommand::Set { document, path, .. } |
Expand Down Expand Up @@ -270,6 +270,10 @@ pub fn config(subcommand: &ConfigSubCommand, parameters: &Option<String>, stdin:
}
};

if let Some(path) = mounted_path {
configurator.set_mounted_path(path);
}

if let Err(err) = configurator.set_context(&parameters) {
error!("Error: Parameter input failure: {err}");
exit(EXIT_INVALID_INPUT);
Expand Down
27 changes: 27 additions & 0 deletions dsc/tests/dsc_functions.tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,31 @@ Describe 'tests for function expressions' {
$out = $config_yaml | dsc config get | ConvertFrom-Json
$out.results[0].result.actualState.output | Should -Be $expected
}

It 'mountedpath(<path>) works' -TestCases @(
@{ path = '' }
@{ path = "hello$([System.IO.Path]::DirectorySeparatorChar)world" }
) {
param($path)

$testPath = if ($path.Length -gt 0) {
$expected = "$PSHOME$([System.IO.Path]::DirectorySeparatorChar)$path"
"'$($path.replace('\', '\\'))'"
}
else {
$expected = $PSHOME
$path
}

$config_yaml = @"
`$schema: https://raw.githubusercontent.com/PowerShell/DSC/main/schemas/2024/04/config/document.json
resources:
- name: Echo
type: Microsoft.DSC.Debug/Echo
properties:
output: "[mountedpath($testPath)]"
"@
$out = $config_yaml | dsc config --mounted-path $PSHOME get | ConvertFrom-Json
$out.results[0].result.actualState.output | Should -BeExactly $expected
}
}
2 changes: 2 additions & 0 deletions dsc_lib/src/configure/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use super::config_doc::{DataType, SecurityContextKind};
pub struct Context {
pub execution_type: ExecutionKind,
pub outputs: HashMap<String, Value>, // this is used by the `reference()` function to retrieve output
pub mounted_path: String,
SteveL-MSFT marked this conversation as resolved.
Show resolved Hide resolved
pub parameters: HashMap<String, (Value, DataType)>,
pub security_context: SecurityContextKind,
pub variables: HashMap<String, Value>,
Expand All @@ -24,6 +25,7 @@ impl Context {
Self {
execution_type: ExecutionKind::Actual,
outputs: HashMap::new(),
mounted_path: String::new(),
parameters: HashMap::new(),
security_context: match get_security_context() {
SecurityContext::Admin => SecurityContextKind::Elevated,
Expand Down
9 changes: 9 additions & 0 deletions dsc_lib/src/configure/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -479,6 +479,15 @@ impl Configurator {
Ok(result)
}

/// Set the mounted path for the configuration.
///
/// # Arguments
///
/// * `mounted_path` - The mounted path to set.
SteveL-MSFT marked this conversation as resolved.
Show resolved Hide resolved
pub fn set_mounted_path(&mut self, mounted_path: &str) {
self.context.mounted_path = mounted_path.to_string();
}

/// Set the parameters and variables context for the configuration.
///
/// # Arguments
Expand Down
2 changes: 2 additions & 0 deletions dsc_lib/src/functions/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ pub mod int;
pub mod max;
pub mod min;
pub mod mod_function;
pub mod mounted_path;
pub mod mul;
pub mod parameters;
pub mod reference;
Expand Down Expand Up @@ -74,6 +75,7 @@ impl FunctionDispatcher {
functions.insert("max".to_string(), Box::new(max::Max{}));
functions.insert("min".to_string(), Box::new(min::Min{}));
functions.insert("mod".to_string(), Box::new(mod_function::Mod{}));
functions.insert("mountedpath".to_string(), Box::new(mounted_path::MountedPath{}));
SteveL-MSFT marked this conversation as resolved.
Show resolved Hide resolved
functions.insert("mul".to_string(), Box::new(mul::Mul{}));
functions.insert("parameters".to_string(), Box::new(parameters::Parameters{}));
functions.insert("reference".to_string(), Box::new(reference::Reference{}));
Expand Down
66 changes: 66 additions & 0 deletions dsc_lib/src/functions/mounted_path.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

use crate::DscError;
use crate::configure::context::Context;
use crate::functions::{AcceptedArgKind, Function};
use serde_json::Value;
use tracing::debug;

#[derive(Debug, Default)]
pub struct MountedPath {}

/// Implements the 'mountedpath' function.
/// This function returns the value of the mounted path.
/// The optional parameter is a path appended to the mounted path.
/// Path is not validated as it might be used for creation.
impl Function for MountedPath {
fn min_args(&self) -> usize {
0
}

fn max_args(&self) -> usize {
1
}

fn accepted_arg_types(&self) -> Vec<AcceptedArgKind> {
vec![AcceptedArgKind::String]
}

fn invoke(&self, args: &[Value], context: &Context) -> Result<Value, DscError> {
debug!("Executing mountedpath function with args: {:?}", args);

if args.len() == 1 {
let path = args[0].as_str().ok_or(DscError::Parser("Invalid argument".to_string()))?;
Ok(Value::String(format!("{}{}{path}", context.mounted_path, std::path::MAIN_SEPARATOR)))
} else {
Ok(Value::String(context.mounted_path.clone()))
}
}
}

#[cfg(test)]
mod tests {
use crate::configure::context::Context;
use crate::parser::Statement;

#[test]
fn no_arg() {
let mut parser = Statement::new().unwrap();
let mut context = Context::new();
let separator = std::path::MAIN_SEPARATOR;
context.mounted_path = format!("{separator}mnt");
let result = parser.parse_and_execute("[mountedpath()]", &context).unwrap();
assert_eq!(result, format!("{separator}mnt"));
}

#[test]
fn with_arg() {
let mut parser = Statement::new().unwrap();
let mut context = Context::new();
let separator = std::path::MAIN_SEPARATOR;
context.mounted_path = format!("{separator}mnt");
let result = parser.parse_and_execute("[mountedpath('foo')]", &context).unwrap();
assert_eq!(result, format!("{separator}mnt{separator}foo"));
}
}
Loading