Skip to content

Commit 0f8c7bb

Browse files
committed
add test and fix typos
1 parent 9319b66 commit 0f8c7bb

File tree

10 files changed

+89
-33
lines changed

10 files changed

+89
-33
lines changed

dsc/locales/en-us.toml

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ foundProcesses = "Found processes"
4242
failedToGetPid = "Could not get current process id"
4343
currentPid = "Current process id"
4444
failedToGetProcess = "Could not get current process"
45-
terminatingSubprocess ="Terminating subprocesses of process"
45+
terminatingSubprocess = "Terminating subprocesses of process"
4646
terminatingProcess = "Terminating process"
4747
failedTerminatingProcess = "Failed to terminate process"
4848
storeMessage = """DSC.exe is a command-line tool and cannot be run directly from the Windows Store or Explorer.
@@ -58,11 +58,11 @@ failedToOpenFile = "Failed to open included file"
5858
invalidFileContent = "Invalid UTF-8 sequence in included file"
5959
invalidFile = "Failed to read the configuration file as YAML or JSON"
6060
resolvingParameters = "Resolving parameters from file"
61-
failedParseParametersFile = "Failed to parse parameters file to JSON"
62-
failedResolveParametersFile = "Failed to resolve parameters file"
63-
noParametersFile = "No parameters file found"
61+
failedParseParametersFile = "Failed to parse parameters file or conetnt to JSON"
62+
couldNotReadParametersFile = "Could not read parameters file"
6463
invalidPath = "Include path must not contain '..'"
6564
failedGetCurrentDirectory = "Failed to get current directory"
65+
noParameters = "No parameters specified"
6666

6767
[resource_command]
6868
implementedAs = "implemented as"

dsc/src/main.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ fn main() {
4242
debug!("{}: {}", t!("main.usingDscVersion"), env!("CARGO_PKG_VERSION"));
4343

4444
let progress_format = args.progress_format.unwrap_or( ProgressFormat::Default );
45-
45+
4646
match args.subcommand {
4747
SubCommand::Completer { shell } => {
4848
info!("{} {:?}", t!("main.generatingCompleter"), shell);
@@ -55,7 +55,7 @@ fn main() {
5555
match std::fs::read_to_string(&file_name) {
5656
Ok(parameters) => subcommand::config(&subcommand, &Some(parameters), system_root.as_ref(), &as_group, &as_include, progress_format),
5757
Err(err) => {
58-
error!("{} '{file_name}': {err}", t!("main.failedToReadParametersFile"));
58+
error!("{} '{file_name}': {err}", t!("main.failedReadingParametersFile"));
5959
exit(util::EXIT_INVALID_INPUT);
6060
}
6161
}
@@ -111,7 +111,7 @@ fn terminate_subprocesses(sys: &System, process: &Process) {
111111

112112
info!("{}: {:?} {}", t!("main.terminatingProcess"), process.name(), process.pid());
113113
if !process.kill() {
114-
error!("{}: {:?} {}", t!("main.failedTerminateProcess"), process.name(), process.pid());
114+
error!("{}: {:?} {}", t!("main.failedTerminatingProcess"), process.name(), process.pid());
115115
}
116116
}
117117

dsc/src/resolve.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -126,15 +126,15 @@ pub fn get_contents(input: &str) -> Result<(Option<String>, String), String> {
126126
Some(parameters_json)
127127
},
128128
Err(err) => {
129-
return Err(format!("{} '{parameters_file:?}': {err}", t!("resolve.failedResolveParametersFile")));
129+
return Err(format!("{} '{parameters_file:?}': {err}", t!("resolve.couldNotReadParametersFile")));
130130
}
131131
}
132132
},
133133
Some(IncludeParametersKind::ParametersContent(text)) => {
134134
let parameters_json = match parse_input_to_json(&text) {
135135
Ok(json) => json,
136136
Err(err) => {
137-
return Err(format!("{}: {err}", t!("resolve.invalidParametersContent")));
137+
return Err(format!("{}: {err}", t!("resolve.failedParseParametersFile")));
138138
}
139139
};
140140
Some(parameters_json)

dsc/tests/dsc_i18n.tests.ps1

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
# Copyright (c) Microsoft Corporation.
2+
# Licensed under the MIT License.
3+
4+
BeforeDiscovery {
5+
$tomls = Get-ChildItem $PSScriptRoot/../../en-us.toml -Recurse -File
6+
$projects = @()
7+
$tomls | ForEach-Object {
8+
$projectName = (Split-Path $_ -Parent | Split-Path -Parent)
9+
$projects += @{ project = $projectName; toml = $_ }
10+
}
11+
}
12+
13+
Describe 'Internationalization tests' {
14+
It 'Project <project> uses i18n strings from <toml>' -TestCases $projects {
15+
param($project, $toml)
16+
17+
$i18n = [System.Collections.Hashtable]::new([System.StringComparer]::Ordinal)
18+
$prefix = ''
19+
Get-Content -Path $toml | ForEach-Object {
20+
if ($_ -match '\[(?<prefix>.*?)\]') {
21+
$prefix = $Matches['prefix']
22+
}
23+
elseif ($_ -match '^(?<key>\w+)\s?=\s?"(?<value>.*?)"') {
24+
$key = $prefix + '.' + $Matches['key']
25+
$i18n[$key] = 0
26+
}
27+
}
28+
29+
$missing = @()
30+
Get-ChildItem -Recurse -Path $project -Include *.rs -File | ForEach-Object {
31+
# Write-Verbose -Verbose "File: $_"
32+
$line = 0
33+
Get-Content -Path $_ | ForEach-Object {
34+
$line++
35+
($_ | Select-String -Pattern '[^\w]t\!\("(?<key>.*?)".*?\)' -AllMatches).Matches | ForEach-Object {
36+
# write-verbose -verbose "Line: $_"
37+
if ($null -ne $_) {
38+
$key = $_.Groups['key'].Value
39+
if ($i18n.ContainsKey($key)) {
40+
$i18n[$key] = 1
41+
# write-verbose -verbose "Found on line $line : $key"
42+
}
43+
else {
44+
$missing += $key
45+
# write-verbose -verbose "Missing: $key"
46+
}
47+
}
48+
}
49+
}
50+
}
51+
52+
$missing | Should -BeNullOrEmpty -Because "The following i18n keys are missing from $toml :`n$($missing | Out-String)"
53+
$unused = $i18n.GetEnumerator() | Where-Object { $_.Value -eq 0 } | ForEach-Object { $_.Key }
54+
$unused | Should -BeNullOrEmpty -Because "The following i18n keys are unused in the project:`n$($unused | Out-String)"
55+
}
56+
}

dsc_lib/locales/en-us.toml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ testNoActualState = "No actual state returned"
102102
testNoDiff = "No diff properties returned"
103103
invokeDeleteUsing = "Invoking delete on '%{resource}' using '%{executable}'"
104104
invokeValidateConfig = "Invoking validate on '%{resource}' using '%{config}'"
105-
invokeVaalidateUsing = "Invoking validate on '%{resource}' using '%{executable}'"
105+
invokeValidateUsing = "Invoking validate on '%{resource}' using '%{executable}'"
106106
exportNotSupported = "Export is not supported by resource '%{resource}'"
107107
exportVerifyOutput = "Verifying output of export on '%{resource}' using '%{executable}'"
108108
resolveNotSupported = "Resolve is not supported by resource '%{resource}'"
@@ -310,7 +310,7 @@ schema = "Schema"
310310
schemaNotAvailable = "No Schema found and `validate` is not supported"
311311
securityContext = "Security context"
312312
utf8Conversion = "UTF-8 conversion"
313-
unkonwn = "Unknown"
313+
unknown = "Unknown"
314314
validation = "Validation"
315315
setting = "Setting"
316316

dsc_lib/src/configure/mod.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,7 @@ fn escape_property_values(properties: &Map<String, Value>) -> Result<Option<Map<
139139

140140
fn get_progress_bar_span(len: u64, progress_format: ProgressFormat) -> Result<ProgressBar, DscError> {
141141
let mut pb_span = ProgressBar::new(progress_format == ProgressFormat::Json);
142-
142+
143143
pb_span.pb_set_style(&ProgressStyle::with_template(
144144
"{spinner:.green} [{elapsed_precise:.cyan}] [{bar:40.cyan/blue}] {pos:>7}/{len:7} {msg:.yellow}"
145145
)?);
@@ -184,7 +184,7 @@ fn check_security_context(metadata: Option<&Metadata>) -> Result<(), DscError> {
184184
},
185185
SecurityContextKind::Restricted => {
186186
if get_security_context() != SecurityContext::User {
187-
return Err(DscError::SecurityContext(t!("configure.mid.restrictedRequired").to_string()));
187+
return Err(DscError::SecurityContext(t!("configure.mod.restrictedRequired").to_string()));
188188
}
189189
},
190190
}

dsc_lib/src/dscresources/command_resource.rs

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -249,9 +249,9 @@ pub fn invoke_set(resource: &ResourceManifest, cwd: &str, desired: &str, skip_te
249249
///
250250
/// Error is returned if the underlying command returns a non-zero exit code.
251251
pub fn invoke_test(resource: &ResourceManifest, cwd: &str, expected: &str) -> Result<TestResult, DscError> {
252-
debug!("{}", t!("dscresource.commandResource.invokeTest", resource = &resource.resource_type));
252+
debug!("{}", t!("dscresources.commandResource.invokeTest", resource = &resource.resource_type));
253253
let Some(test) = &resource.test else {
254-
info!("{}", t!("dscresource.commandResource.testSyntheticTest", resource = &resource.resource_type));
254+
info!("{}", t!("dscresources.commandResource.testSyntheticTest", resource = &resource.resource_type));
255255
return invoke_synthetic_test(resource, cwd, expected);
256256
};
257257

@@ -411,7 +411,7 @@ pub fn invoke_validate(resource: &ResourceManifest, cwd: &str, config: &str) ->
411411
let args = process_args(validate.args.as_ref(), config);
412412
let command_input = get_command_input(validate.input.as_ref(), config)?;
413413

414-
info!("{}", t!("dscreources.commandResource.invokeValidateUsing", resource = &resource.resource_type, executable = &validate.executable));
414+
info!("{}", t!("dscresources.commandResource.invokeValidateUsing", resource = &resource.resource_type, executable = &validate.executable));
415415
let (_exit_code, stdout, _stderr) = invoke_command(&validate.executable, args, command_input.stdin.as_deref(), Some(cwd), command_input.env, resource.exit_codes.as_ref())?;
416416
let result: ValidateResult = serde_json::from_str(&stdout)?;
417417
Ok(result)
@@ -516,7 +516,7 @@ pub fn invoke_export(resource: &ResourceManifest, cwd: &str, input: Option<&str>
516516
/// Error returned if the resource does not successfully resolve the input
517517
pub fn invoke_resolve(resource: &ResourceManifest, cwd: &str, input: &str) -> Result<ResolveResult, DscError> {
518518
let Some(resolve) = &resource.resolve else {
519-
return Err(DscError::Operation(t!("dscreources.commandResource.resolveNotSupported", resource = &resource.resource_type).to_string()));
519+
return Err(DscError::Operation(t!("dscresources.commandResource.resolveNotSupported", resource = &resource.resource_type).to_string()));
520520
};
521521

522522
let args = process_args(resolve.args.as_ref(), input);
@@ -577,21 +577,21 @@ async fn run_process_async(executable: &str, args: Option<Vec<String>>, input: O
577577
};
578578

579579
let Some(stdout) = child.stdout.take() else {
580-
return Err(DscError::CommandOperation(t!("dscreousrces.commandResource.processChildStdout").to_string(), executable.to_string()));
580+
return Err(DscError::CommandOperation(t!("dscresources.commandResource.processChildStdout").to_string(), executable.to_string()));
581581
};
582582
let Some(stderr) = child.stderr.take() else {
583-
return Err(DscError::CommandOperation(t!("dscreousrces.commandResource.processChildStderr").to_string(), executable.to_string()));
583+
return Err(DscError::CommandOperation(t!("dscresources.commandResource.processChildStderr").to_string(), executable.to_string()));
584584
};
585585
let mut stdout_reader = BufReader::new(stdout).lines();
586586
let mut stderr_reader = BufReader::new(stderr).lines();
587587

588588
if let Some(input) = input {
589589
trace!("Writing to command STDIN: {input}");
590590
let Some(mut stdin) = child.stdin.take() else {
591-
return Err(DscError::CommandOperation(t!("dscreousrces.commandResource.processChildStdin").to_string(), executable.to_string()));
591+
return Err(DscError::CommandOperation(t!("dscresources.commandResource.processChildStdin").to_string(), executable.to_string()));
592592
};
593593
if stdin.write_all(input.as_bytes()).await.is_err() {
594-
return Err(DscError::CommandOperation(t!("dscreousrces.commandResource.processWriteStdin").to_string(), executable.to_string()));
594+
return Err(DscError::CommandOperation(t!("dscresources.commandResource.processWriteStdin").to_string(), executable.to_string()));
595595
}
596596
drop(stdin);
597597
}
@@ -714,11 +714,11 @@ fn get_command_input(input_kind: Option<&InputKind>, input: &str) -> Result<Comm
714714
let mut stdin: Option<String> = None;
715715
match input_kind {
716716
Some(InputKind::Env) => {
717-
debug!("{}", t!("dscresources.commandResource.parsingAsEnvVars"));
717+
debug!("{}", t!("dscresources.commandResource.parseAsEnvVars"));
718718
env = Some(json_to_hashmap(input)?);
719719
},
720720
Some(InputKind::Stdin) => {
721-
debug!("{}", t!("dscresources.commandResource.parsingAsStdin"));
721+
debug!("{}", t!("dscresources.commandResource.parseAsStdin"));
722722
stdin = Some(input.to_string());
723723
},
724724
None => {

dsc_lib/src/functions/resource_id.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ impl Function for ResourceId {
3030
if let Some(value) = resource_type.as_str() {
3131
let slash_count = value.chars().filter(|c| *c == '/').count();
3232
if slash_count != 1 {
33-
return Err(DscError::Function("resourceId".to_string(), t!("functions.resourceid.incorrectTypeFormat").to_string()));
33+
return Err(DscError::Function("resourceId".to_string(), t!("functions.resourceId.incorrectTypeFormat").to_string()));
3434
}
3535
result.push_str(value);
3636
} else {

dsc_lib/src/parser/functions.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ fn convert_args_node(statement_bytes: &[u8], args: Option<&Node>) -> Result<Opti
115115
result.push(FunctionArg::Expression(expression));
116116
},
117117
_ => {
118-
return Err(DscError::Parser(t!("parser.function.unknownArgType", kind = arg.kind()).to_string()));
118+
return Err(DscError::Parser(t!("parser.functions.unknownArgType", kind = arg.kind()).to_string()));
119119
}
120120
}
121121
}

dsc_lib/src/parser/mod.rs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -45,43 +45,43 @@ impl Statement {
4545
///
4646
/// This function will return an error if the statement fails to parse or execute.
4747
pub fn parse_and_execute(&mut self, statement: &str, context: &Context) -> Result<Value, DscError> {
48-
debug!("{}", t!("parser.statement.parsingStatement", statement = statement));
48+
debug!("{}", t!("parser.parsingStatement", statement = statement));
4949
let Some(tree) = &mut self.parser.parse(statement, None) else {
50-
return Err(DscError::Parser(t!("parser.statement.failedToParse", statement = statement).to_string()));
50+
return Err(DscError::Parser(t!("parser.failedToParse", statement = statement).to_string()));
5151
};
5252
let root_node = tree.root_node();
5353
if root_node.is_error() {
54-
return Err(DscError::Parser(t!("parser.statement.failedToParseRoot", statement = statement).to_string()));
54+
return Err(DscError::Parser(t!("parser.failedToParseRoot", statement = statement).to_string()));
5555
}
5656
if root_node.kind() != "statement" {
57-
return Err(DscError::Parser(t!("parser.statement.invalidStatement", statement = statement).to_string()));
57+
return Err(DscError::Parser(t!("parser.invalidStatement", statement = statement).to_string()));
5858
}
5959
let statement_bytes = statement.as_bytes();
6060
let mut cursor = root_node.walk();
6161
let mut return_value = Value::Null;
6262
for child_node in root_node.named_children(&mut cursor) {
6363
if child_node.is_error() {
64-
return Err(DscError::Parser(t!("parser.statement.failedToParse", statement = statement).to_string()));
64+
return Err(DscError::Parser(t!("parser.failedToParse", statement = statement).to_string()));
6565
}
6666

6767
match child_node.kind() {
6868
"stringLiteral" => {
6969
let Ok(value) = child_node.utf8_text(statement_bytes) else {
7070
return Err(DscError::Parser(t!("parser.failedToParseStringLiteral").to_string()));
7171
};
72-
debug!("{}", t!("parser.statement.parsingStringLiteral", value = value.to_string()));
72+
debug!("{}", t!("parser.parsingStringLiteral", value = value.to_string()));
7373
return_value = Value::String(value.to_string());
7474
},
7575
"escapedStringLiteral" => {
7676
// need to remove the first character: [[ => [
7777
let Ok(value) = child_node.utf8_text(statement_bytes) else {
7878
return Err(DscError::Parser(t!("parser.failedToParseEscapedStringLiteral").to_string()));
7979
};
80-
debug!("{}", t!("parser.statement.parsingEscapedStringLiteral", value = value[1..].to_string()));
80+
debug!("{}", t!("parser.parsingEscapedStringLiteral", value = value[1..].to_string()));
8181
return_value = Value::String(value[1..].to_string());
8282
},
8383
"expression" => {
84-
debug!("{}", t!("parser.statement.parsingExpression"));
84+
debug!("{}", t!("parser.parsingExpression"));
8585
let expression = Expression::new(statement_bytes, &child_node)?;
8686
return_value = expression.invoke(&self.function_dispatcher, context)?;
8787
},

0 commit comments

Comments
 (0)