Skip to content

Fix parameter completion when script requirements fail #17687

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

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -1198,7 +1198,7 @@ private bool PrepareCommandElements(ExecutionContext context, CommandParameterAs
string commandName = null;
try
{
processor = PrepareFromAst(context, out commandName) ?? context.CreateCommand(commandName, dotSource);
processor = PrepareFromAst(context, out commandName) ?? context.CreateCommand(commandName, dotSource, forCompletion:true);
}
catch (RuntimeException)
{
Expand Down
39 changes: 26 additions & 13 deletions src/System.Management.Automation/engine/CommandDiscovery.cs
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,9 @@ internal void AddSessionStateCmdletEntryToCache(SessionStateCmdletEntry entry, b
/// False if not. Null if command discovery should default to something reasonable
/// for the command discovered.
/// </param>
/// <param name="forCompletion">
/// True if this for parameter completion and script requirements should be ignored.
/// </param>
/// <returns>
/// </returns>
/// <exception cref="CommandNotFoundException">
Expand All @@ -271,22 +274,23 @@ internal void AddSessionStateCmdletEntryToCache(SessionStateCmdletEntry entry, b
/// If the security manager is preventing the command from running.
/// </exception>
internal CommandProcessorBase LookupCommandProcessor(string commandName,
CommandOrigin commandOrigin, bool? useLocalScope)
CommandOrigin commandOrigin, bool? useLocalScope, bool forCompletion = false)
{
CommandProcessorBase processor = null;
CommandInfo commandInfo = LookupCommandInfo(commandName, commandOrigin);

if (commandInfo != null)
{
processor = LookupCommandProcessor(commandInfo, commandOrigin, useLocalScope, null);
processor = LookupCommandProcessor(commandInfo, commandOrigin, useLocalScope, null, forCompletion);

// commandInfo.Name might be different than commandName - restore the original invocation name
processor.Command.MyInvocation.InvocationName = commandName;
}

return processor;
}

internal static void VerifyRequiredModules(ExternalScriptInfo scriptInfo, ExecutionContext context)
internal static void VerifyRequiredModules(ExternalScriptInfo scriptInfo, ExecutionContext context, bool forCompletion = false)
{
// Check Required Modules
if (scriptInfo.RequiresModules != null)
Expand All @@ -301,7 +305,7 @@ internal static void VerifyRequiredModules(ExternalScriptInfo scriptInfo, Execut
moduleManifestPath: null,
manifestProcessingFlags: ModuleCmdletBase.ManifestProcessingFlags.LoadElements | ModuleCmdletBase.ManifestProcessingFlags.WriteErrors,
error: out error);
if (error != null)
if (!forCompletion && error is not null)
{
ScriptRequiresException scriptRequiresException =
new ScriptRequiresException(
Expand All @@ -316,9 +320,9 @@ internal static void VerifyRequiredModules(ExternalScriptInfo scriptInfo, Execut
}
}

private CommandProcessorBase CreateScriptProcessorForSingleShell(ExternalScriptInfo scriptInfo, ExecutionContext context, bool useLocalScope, SessionStateInternal sessionState)
private CommandProcessorBase CreateScriptProcessorForSingleShell(ExternalScriptInfo scriptInfo, ExecutionContext context, bool useLocalScope, SessionStateInternal sessionState, bool forCompletion = false)
{
VerifyScriptRequirements(scriptInfo, Context);
VerifyScriptRequirements(scriptInfo, Context, forCompletion);

if (!string.IsNullOrEmpty(scriptInfo.RequiresApplicationID))
{
Expand All @@ -340,12 +344,18 @@ private CommandProcessorBase CreateScriptProcessorForSingleShell(ExternalScriptI
// #Requires -PSVersion
// #Requires -PSEdition
// #Requires -Module
internal static void VerifyScriptRequirements(ExternalScriptInfo scriptInfo, ExecutionContext context)
internal static void VerifyScriptRequirements(ExternalScriptInfo scriptInfo, ExecutionContext context, bool forCompletion = false)
{
VerifyElevatedPrivileges(scriptInfo);
VerifyPSVersion(scriptInfo);
VerifyPSEdition(scriptInfo);
VerifyRequiredModules(scriptInfo, context);
// When completing script parameters we don't care if these requirements are met.
// VerifyRequiredModules will attempt to load the required modules which is useful for completion (so the correct types are loaded).
if (!forCompletion)
{
VerifyElevatedPrivileges(scriptInfo);
VerifyPSVersion(scriptInfo);
VerifyPSEdition(scriptInfo);
}

VerifyRequiredModules(scriptInfo, context, forCompletion);
}

internal static void VerifyPSVersion(ExternalScriptInfo scriptInfo)
Expand Down Expand Up @@ -426,6 +436,9 @@ internal static void VerifyElevatedPrivileges(ExternalScriptInfo scriptInfo)
/// False if not. Null if command discovery should default to something reasonable
/// for the command discovered.
/// </param>
/// <param name="forCompletion">
/// True if this for parameter completion and script requirements should be ignored.
/// </param>
/// <param name="sessionState">The session state the commandInfo should be run in.</param>
/// <returns>
/// </returns>
Expand All @@ -436,7 +449,7 @@ internal static void VerifyElevatedPrivileges(ExternalScriptInfo scriptInfo)
/// If the security manager is preventing the command from running.
/// </exception>
internal CommandProcessorBase LookupCommandProcessor(CommandInfo commandInfo,
CommandOrigin commandOrigin, bool? useLocalScope, SessionStateInternal sessionState)
CommandOrigin commandOrigin, bool? useLocalScope, SessionStateInternal sessionState, bool forCompletion = false)
{
CommandProcessorBase processor = null;

Expand Down Expand Up @@ -482,7 +495,7 @@ internal CommandProcessorBase LookupCommandProcessor(CommandInfo commandInfo,
scriptInfo.SignatureChecked = true;
try
{
processor = CreateScriptProcessorForSingleShell(scriptInfo, Context, useLocalScope ?? true, sessionState);
processor = CreateScriptProcessorForSingleShell(scriptInfo, Context, useLocalScope ?? true, sessionState, forCompletion);
}
catch (ScriptRequiresSyntaxException reqSyntaxException)
{
Expand Down
6 changes: 3 additions & 3 deletions src/System.Management.Automation/engine/ExecutionContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -477,7 +477,6 @@ internal LocationGlobber LocationGlobber
/// The assemblies that have been loaded for this runspace.
/// </summary>
internal Dictionary<string, Assembly> AssemblyCache { get; private set; }

#endregion Properties

#region Engine State
Expand Down Expand Up @@ -634,12 +633,13 @@ internal HelpSystem HelpSystem
/// </summary>
/// <param name="command">The name of the command to lookup.</param>
/// <param name="dotSource"></param>
/// <param name="forCompletion"></param>
/// <returns>The command processor object.</returns>
internal CommandProcessorBase CreateCommand(string command, bool dotSource)
internal CommandProcessorBase CreateCommand(string command, bool dotSource, bool forCompletion = false)
{
CommandOrigin commandOrigin = this.EngineSessionState.CurrentScope.ScopeOrigin;
CommandProcessorBase commandProcessor =
CommandDiscovery.LookupCommandProcessor(command, commandOrigin, !dotSource);
CommandDiscovery.LookupCommandProcessor(command, commandOrigin, !dotSource, forCompletion);
// Reset the command origin for script commands... // BUGBUG - dotting can get around command origin checks???
if (commandProcessor != null && commandProcessor is ScriptCommandProcessorBase)
{
Expand Down
30 changes: 30 additions & 0 deletions test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -1659,6 +1659,36 @@ class InheritedClassTest : System.Attribute
}
}

Context "Script parameter completion" {
BeforeAll {
Setup -File -Path 'ModuleReqTest.ps1' -Content @'
#requires -Modules ThisModuleDoesNotExist
param ($Param1)
'@
Setup -File -Path 'AdminReqTest.ps1' -Content @'
#requires -RunAsAdministrator
param ($Param1)
'@
Push-Location ${TestDrive}\
}

AfterAll {
Pop-Location
}

It "Input should successfully complete script parameter for script with failed script requirements" {
$res = TabExpansion2 -inputScript '.\ModuleReqTest.ps1 -'
$res.CompletionMatches.Count | Should -BeGreaterThan 0
$res.CompletionMatches[0].CompletionText | Should -BeExactly '-Param1'
}

It "Input should successfully complete script parameter for admin script while not elevated" {
$res = TabExpansion2 -inputScript '.\AdminReqTest.ps1 -'
$res.CompletionMatches.Count | Should -BeGreaterThan 0
$res.CompletionMatches[0].CompletionText | Should -BeExactly '-Param1'
}
}

Context "File name completion" {
BeforeAll {
$tempDir = Join-Path -Path $TestDrive -ChildPath "baseDir"
Expand Down
Loading