Skip to content

Commit c34a6f0

Browse files
committed
(#3344) Convert Get-PackageScriptParameter to helper cmdlet
It was pointed out that this PR should be targeted at including new helper functions into the C# conversion efforts. This converts Get-PackageParameter to use a helper class (shared between this and the new cmdlet) and adds Get-PackageScriptParameters to the Chocolatey.PowerShell compiled module.
1 parent 9865bc9 commit c34a6f0

File tree

7 files changed

+208
-461
lines changed

7 files changed

+208
-461
lines changed

src/Chocolatey.PowerShell/Chocolatey.PowerShell.csproj

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,13 +60,16 @@
6060
<ItemGroup>
6161
<Compile Include="Commands\GetEnvironmentVariableCommand.cs" />
6262
<Compile Include="Commands\GetEnvironmentVariableNamesCommand.cs" />
63+
<Compile Include="Commands\GetPackageParameterCommand.cs" />
64+
<Compile Include="Commands\GetPackageScriptParametersCommand.cs" />
6365
<Compile Include="Commands\InstallChocolateyPathCommand.cs" />
6466
<Compile Include="Commands\SetEnvironmentVariableCommand.cs" />
6567
<Compile Include="Commands\TestProcessAdminRightsCommand.cs" />
6668
<Compile Include="Commands\UninstallChocolateyPathCommand.cs" />
6769
<Compile Include="Commands\UpdateSessionEnvironmentCommand.cs" />
6870
<Compile Include="Helpers\Elevation.cs" />
6971
<Compile Include="Helpers\EnvironmentHelper.cs" />
72+
<Compile Include="Helpers\PackageParameter.cs" />
7073
<Compile Include="Helpers\Paths.cs" />
7174
<Compile Include="Helpers\ProcessInformation.cs" />
7275
<Compile Include="Helpers\PSHelper.cs" />
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// Copyright © 2017 - 2025 Chocolatey Software, Inc
2+
// Copyright © 2011 - 2017 RealDimensions Software, LLC
3+
//
4+
// Licensed under the Apache License, Version 2.0 (the "License");
5+
// you may not use this file except in compliance with the License.
6+
//
7+
// You may obtain a copy of the License at
8+
//
9+
// http://www.apache.org/licenses/LICENSE-2.0
10+
//
11+
// Unless required by applicable law or agreed to in writing, software
12+
// distributed under the License is distributed on an "AS IS" BASIS,
13+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
// See the License for the specific language governing permissions and
15+
// limitations under the License.
16+
17+
using Chocolatey.PowerShell.Shared;
18+
using System.Collections;
19+
using System.Management.Automation;
20+
using Chocolatey.PowerShell.Helpers;
21+
22+
namespace Chocolatey.PowerShell.Commands
23+
{
24+
/// <summary>
25+
/// Parses a string and returns a hash table array of those values for use in package scripts.
26+
/// </summary>
27+
/// <param name="Parameters">A string containing parameters to be parsed.</param>
28+
/// <returns>A hashtable of parameters that have been passed to <paramref name="Parameters"> and parsed.</returns>
29+
[Cmdlet(VerbsCommon.Get, "PackageParameter")]
30+
[Alias("Get-PackageParameters")]
31+
[OutputType(typeof(Hashtable))]
32+
public class GetPackageParameterCommand : ChocolateyCmdlet
33+
{
34+
[Parameter(Position = 0)]
35+
[Alias("Params")]
36+
public string Parameters { get; set; } = string.Empty;
37+
38+
protected override void End()
39+
{
40+
WriteObject(PackageParameter.GetParameters(this, Parameters));
41+
}
42+
}
43+
}
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
// Copyright © 2017 - 2024 Chocolatey Software, Inc
2+
// Copyright © 2011 - 2017 RealDimensions Software, LLC
3+
//
4+
// Licensed under the Apache License, Version 2.0 (the "License");
5+
// you may not use this file except in compliance with the License.
6+
//
7+
// You may obtain a copy of the License at
8+
//
9+
// http://www.apache.org/licenses/LICENSE-2.0
10+
//
11+
// Unless required by applicable law or agreed to in writing, software
12+
// distributed under the License is distributed on an "AS IS" BASIS,
13+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
// See the License for the specific language governing permissions and
15+
// limitations under the License.
16+
17+
using System;
18+
using System.Collections;
19+
using System.Collections.Generic;
20+
using System.Linq;
21+
using System.Management.Automation;
22+
using System.Management.Automation.Language;
23+
using Chocolatey.PowerShell.Helpers;
24+
using Chocolatey.PowerShell.Shared;
25+
26+
namespace Chocolatey.PowerShell.Commands
27+
{
28+
/// <summary>
29+
/// Parses a script and returns a hash table of parameters that are present in the package params, along with their values.
30+
/// </summary>
31+
/// <param name="ScriptPath">A path to a script to parse parameters from.</param>
32+
/// <param name="Parameters">A string containing parameters to be parsed.</param>
33+
/// <returns>A hashtable of parameters present in <paramref name="ScriptPath"> and also in <paramref name="Parameters"> (or the envvar).</returns>
34+
[Cmdlet(VerbsCommon.Get, "PackageScriptParameters")]
35+
[OutputType(typeof(Hashtable))]
36+
public class GetScriptParametersCommand : ChocolateyCmdlet
37+
{
38+
[Parameter(Mandatory = true, Position = 0)]
39+
public string ScriptPath { get; set; }
40+
41+
[Parameter(Mandatory = false, Position = 1)]
42+
public string Parameters { get; set; } = string.Empty;
43+
44+
protected override void End()
45+
{
46+
var packageParameters = PackageParameter.GetParameters(this, Parameters);
47+
var splatHash = new Hashtable(StringComparer.OrdinalIgnoreCase);
48+
49+
// Check what parameters the script has
50+
Token[] tokensRef = null;
51+
ParseError[] errorsRef = null;
52+
var parsedAst = Parser.ParseFile(ScriptPath, out tokensRef, out errorsRef);
53+
var scriptParameters = parsedAst.ParamBlock != null ? parsedAst.ParamBlock.Parameters.Select(p => p.Name.VariablePath.UserPath.ToString()).ToList() : new List<string>();
54+
WriteVerbose($"Found {scriptParameters.Count()} parameter(s) in '{ScriptPath}'");
55+
56+
// For each of those in PackageParameters, add it to the splat
57+
foreach (var parameter in scriptParameters)
58+
{
59+
if (packageParameters.ContainsKey(parameter))
60+
{
61+
splatHash.Add(parameter, packageParameters[parameter]);
62+
}
63+
}
64+
65+
// Return the splat
66+
WriteObject(splatHash);
67+
}
68+
}
69+
}
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
// Copyright © 2017 - 2024 Chocolatey Software, Inc
2+
// Copyright © 2011 - 2017 RealDimensions Software, LLC
3+
//
4+
// Licensed under the Apache License, Version 2.0 (the "License");
5+
// you may not use this file except in compliance with the License.
6+
//
7+
// You may obtain a copy of the License at
8+
//
9+
// http://www.apache.org/licenses/LICENSE-2.0
10+
//
11+
// Unless required by applicable law or agreed to in writing, software
12+
// distributed under the License is distributed on an "AS IS" BASIS,
13+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
// See the License for the specific language governing permissions and
15+
// limitations under the License.
16+
17+
using System;
18+
using System.Collections;
19+
using System.Collections.Generic;
20+
using System.Management.Automation;
21+
using System.Text.RegularExpressions;
22+
23+
namespace Chocolatey.PowerShell.Helpers
24+
{
25+
public static class PackageParameter
26+
{
27+
private const string PackageParameterPattern = @"(?:^|\s+)\/(?<ItemKey>[^\:\=\s)]+)(?:(?:\:|=){1}(?:\'|\""){0,1}(?<ItemValue>.*?)(?:\'|\""){0,1}(?:(?=\s+\/)|$))?";
28+
private static readonly Regex _packageParameterRegex = new Regex(PackageParameterPattern, RegexOptions.Compiled);
29+
30+
public static Hashtable GetParameters(PSCmdlet cmdlet, string parameters)
31+
{
32+
var paramStrings = new List<string>();
33+
var logParams = true;
34+
35+
if (!string.IsNullOrEmpty(parameters))
36+
{
37+
paramStrings.Add(parameters);
38+
}
39+
else
40+
{
41+
var packageParameters = EnvironmentHelper.GetVariable(
42+
cmdlet,
43+
"ChocolateyPackageParameters",
44+
EnvironmentVariableTarget.Process);
45+
if (!string.IsNullOrEmpty(packageParameters))
46+
{
47+
paramStrings.Add(packageParameters);
48+
}
49+
50+
// This should possibly only be implemented in the CLE codebase
51+
var sensitivePackageParameters = EnvironmentHelper.GetVariable(
52+
cmdlet,
53+
"ChocolateyPackageParametersSensitive",
54+
EnvironmentVariableTarget.Process);
55+
if (!string.IsNullOrEmpty(sensitivePackageParameters))
56+
{
57+
logParams = false;
58+
paramStrings.Add(sensitivePackageParameters);
59+
}
60+
}
61+
62+
var paramHash = new Hashtable(StringComparer.OrdinalIgnoreCase);
63+
64+
foreach (var param in paramStrings)
65+
{
66+
foreach (Match match in _packageParameterRegex.Matches(param))
67+
{
68+
var name = match.Groups["ItemKey"].Value.Trim();
69+
var valueGroup = match.Groups["ItemValue"];
70+
71+
object value;
72+
if (valueGroup.Success)
73+
{
74+
value = valueGroup.Value.Trim();
75+
}
76+
else
77+
{
78+
value = (object)true;
79+
}
80+
81+
if (logParams)
82+
{
83+
cmdlet.WriteDebug($"Adding package param '{name}'='{value}'");
84+
}
85+
86+
paramHash[name] = value;
87+
}
88+
}
89+
90+
return paramHash;
91+
}
92+
}
93+
}

src/chocolatey.resources/chocolatey.resources.csproj

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -260,11 +260,6 @@
260260
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
261261
</EmbeddedResource>
262262
</ItemGroup>
263-
<ItemGroup>
264-
<EmbeddedResource Include="helpers\functions\Get-PackageParameters.ps1">
265-
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
266-
</EmbeddedResource>
267-
</ItemGroup>
268263
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
269264
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
270265
Other similar extension points exist, see Microsoft.Common.targets.

0 commit comments

Comments
 (0)