Skip to content

Commit

Permalink
PowerShell changes for PowerCord
Browse files Browse the repository at this point in the history
  • Loading branch information
WamWooWam committed Mar 16, 2021
1 parent 2f7d7fd commit ccd7550
Show file tree
Hide file tree
Showing 17 changed files with 570 additions and 416 deletions.
2 changes: 1 addition & 1 deletion PowerShell.Common.props
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@

<TargetFramework>net5.0</TargetFramework>
<LangVersion>9.0</LangVersion>
<PublishReadyToRun Condition=" '$(Configuration)' != 'Debug' ">true</PublishReadyToRun>
<!--<PublishReadyToRun Condition=" '$(Configuration)' != 'Debug' ">true</PublishReadyToRun>-->

<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
Expand Down
4 changes: 4 additions & 0 deletions src/Microsoft.PowerShell.Commands.Management/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

[assembly:System.Runtime.CompilerServices.InternalsVisibleTo("PowerCord, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f99950a2fb958c40b1146e3561adab17f01a4d7849626dae998376b5f0d2024fdb5983d078a32011b3b3ad8a7aba6ea01bd3e2d864658267fe2e181e9b36c91e657512af726ead00df91a546b8838dad9a7eefa4190b8afebcdfa06714867ddf10fdd4151822eb3f51912443efc9b7b173f716cb3bfbb27d40c5441e5f8a6bba")]
Original file line number Diff line number Diff line change
Expand Up @@ -612,7 +612,8 @@ private static object ProcessValue(object obj, int currentDepth, in ConvertToJso
}
}

rv = AddPsProperties(pso, rv, currentDepth, isPurePSObj, isCustomObj, in context);
if (!isCustomObj)
rv = AddPsProperties(pso, rv, currentDepth, isPurePSObj, isCustomObj, in context);

return rv;
}
Expand Down Expand Up @@ -697,7 +698,7 @@ private static void AppendPsProperties(PSObject psObj, IDictionary receiver, int
{
}

if (!receiver.Contains(prop.Name))
if (!receiver.Contains(prop.Name) && isCustomObject)
{
receiver[prop.Name] = ProcessValue(value, depth + 1, in context);
}
Expand Down Expand Up @@ -784,7 +785,12 @@ private static object ProcessCustomObject<T>(object o, int depth, in ConvertToJs
value = null;
}

result.Add(info.Name, ProcessValue(value, depth + 1, in context));
string name = info.Name;
JsonPropertyAttribute attribute;
if ((attribute = info.GetCustomAttribute<JsonPropertyAttribute>()) != null)
name = attribute.PropertyName ?? name;

result.Add(name, ProcessValue(value, depth + 1, in context));
}
}

Expand All @@ -805,7 +811,13 @@ private static object ProcessCustomObject<T>(object o, int depth, in ConvertToJs
value = null;
}

result.Add(info2.Name, ProcessValue(value, depth + 1, in context));
string name = info2.Name;
JsonPropertyAttribute attribute;
if ((attribute = info2.GetCustomAttribute<JsonPropertyAttribute>()) != null)
name = attribute.PropertyName ?? name;


result.Add(name, ProcessValue(value, depth + 1, in context));
}
}
}
Expand Down
1 change: 1 addition & 0 deletions src/System.Management.Automation/AssemblyInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
[assembly: InternalsVisibleTo(@"Microsoft.PowerShell.Security" + @",PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly: InternalsVisibleTo(@"System.Management.Automation.Remoting" + @",PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly: InternalsVisibleTo(@"Microsoft.PowerShell.ConsoleHost" + @",PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly: InternalsVisibleTo("PowerCord, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f99950a2fb958c40b1146e3561adab17f01a4d7849626dae998376b5f0d2024fdb5983d078a32011b3b3ad8a7aba6ea01bd3e2d864658267fe2e181e9b36c91e657512af726ead00df91a546b8838dad9a7eefa4190b8afebcdfa06714867ddf10fdd4151822eb3f51912443efc9b7b173f716cb3bfbb27d40c5441e5f8a6bba")]
#endif

namespace System.Management.Automation
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -792,7 +792,7 @@ private static IEnumerable<FormatViewDefinition> ViewsOf_System_Management_Autom
)
}
function Get-VT100Color([ConsoleColor] $color) {
function Get-VT100Color([Nullable[ConsoleColor]] $color) {
if (!$Host.UI.SupportsVirtualTerminal -or !([string]::IsNullOrEmpty($env:__SuppressAnsiEscapeSequences))) {
return ''
}
Expand Down Expand Up @@ -1074,10 +1074,10 @@ private static IEnumerable<FormatViewDefinition> ViewsOf_System_Management_Autom
$errorColor = ''
$accentColor = ''
if ($null -ne $Host.PrivateData) {
$errorColor = Get-VT100Color $Host.PrivateData.ErrorForegroundColor
$accentColor = Get-VT100Color ($Host.PrivateData.ErrorAccentColor ?? $errorColor)
}
# if ($null -ne $Host.PrivateData) {
# $errorColor = Get-VT100Color $Host.PrivateData.ErrorForegroundColor
# $accentColor = Get-VT100Color ($Host.PrivateData.ErrorAccentColor ?? $errorColor)
# }
$posmsg = ''
$headerWhitespace = ''
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,9 +106,7 @@ private void DelayedInternalInitialize()
_pp = new PipelineProcessor();

CmdletInfo cmdletInfo = new CmdletInfo(_commandName, _commandType, null, null, _context);

CommandProcessor cp = new CommandProcessor(cmdletInfo, _context);

foreach (CommandParameterInternal par in _commandParameterList)
{
cp.AddParameter(par);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
Expand Down
112 changes: 106 additions & 6 deletions src/System.Management.Automation/engine/InitialSessionState.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1457,6 +1457,11 @@ private static void IncludePowerShellCoreFormats(InitialSessionState iss)

#endregion

/// <summary>
/// Path to the global drive
/// </summary>
public string GlobalDrivePath { get; internal set; }

/// <summary>
/// Ctor for Custom-Shell - Do we need this?
/// </summary>
Expand Down Expand Up @@ -1611,6 +1616,7 @@ public InitialSessionState Clone()
{
InitialSessionState ss = new InitialSessionState();

ss.GlobalDrivePath = this.GlobalDrivePath;
ss.Variables.Add(this.Variables.Clone());
ss.EnvironmentVariables.Add(this.EnvironmentVariables.Clone());
ss.Commands.Add(this.Commands.Clone());
Expand All @@ -1624,6 +1630,11 @@ public InitialSessionState Clone()
ss.StartupScripts.Add(startupScript);
}

foreach (string startupScript in this.StartupBlocks)
{
ss.StartupBlocks.Add(startupScript);
}

foreach (string unresolvedCommandsToExpose in this.UnresolvedCommandsToExpose)
{
ss.UnresolvedCommandsToExpose.Add(unresolvedCommandsToExpose);
Expand Down Expand Up @@ -2118,6 +2129,23 @@ public virtual HashSet<string> StartupScripts

private HashSet<string> _startupScripts = new HashSet<string>();

/// <summary>
/// </summary>
public virtual HashSet<string> StartupBlocks
{
get
{
if (_startupBlocks == null)
{
Interlocked.CompareExchange(ref _startupBlocks, new HashSet<string>(), null);
}

return _startupBlocks;
}
}

private HashSet<string> _startupBlocks = new HashSet<string>();

private object _syncObject = new object();

internal void Bind(ExecutionContext context, bool updateOnly, PSModuleInfo module, bool noClobber, bool local, bool setLocation)
Expand Down Expand Up @@ -2416,7 +2444,8 @@ private void Bind_LoadAssemblies(ExecutionContext context)
// Load the assemblies and initialize the assembly cache...
foreach (SessionStateAssemblyEntry ssae in Assemblies)
{
if (etwEnabled) RunspaceEventSource.Log.LoadAssemblyStart(ssae.Name, ssae.FileName);
if (etwEnabled)
RunspaceEventSource.Log.LoadAssemblyStart(ssae.Name, ssae.FileName);
Exception error = null;
Assembly asm = context.AddAssembly(ssae.Name, ssae.FileName, out error);

Expand Down Expand Up @@ -2554,6 +2583,21 @@ HashSet<CommandInfo> GetPublicCommands()
}
}

if (!string.IsNullOrWhiteSpace(GlobalDrivePath))
{
Exception userDriveException = ProcessGlobalDrive(initializedRunspace);
if (userDriveException != null)
{
runspaceInitTracer.WriteLine(
"Runspace open failed while processing global drive with error {1}",
userDriveException);

Exception result = PSTraceSource.NewInvalidOperationException(userDriveException, RemotingErrorIdStrings.UserDriveProcessingThrewTerminatingError, userDriveException.Message);
return result;
}
}


// Process startup scripts
if (StartupScripts.Count > 0)
{
Expand All @@ -2569,6 +2613,11 @@ HashSet<CommandInfo> GetPublicCommands()
}
}

if (StartupBlocks.Count > 0)
{
ProcessStartupBlocks(initializedRunspace);
}

// Start transcribing
if (!string.IsNullOrEmpty(TranscriptDirectory))
{
Expand Down Expand Up @@ -2831,6 +2880,44 @@ private Exception ProcessUserDrive(Runspace initializedRunspace)
return ex;
}

private Exception ProcessGlobalDrive(Runspace initializedRunspace)
{
Exception ex = null;
try
{
List<ProviderInfo> fileSystemProviders = initializedRunspace.ExecutionContext.EngineSessionState.Providers["FileSystem"];
if (fileSystemProviders.Count == 0)
{
throw new PSInvalidOperationException(RemotingErrorIdStrings.UserDriveCannotGetFileSystemProvider);
}

// Create directory if it doesn't exist.
if (!Directory.Exists(GlobalDrivePath))
{
Directory.CreateDirectory(GlobalDrivePath);
}

// Create the PSDrive.
var newDriveInfo = new PSDriveInfo(
"Global",
fileSystemProviders[0],
GlobalDrivePath.TrimEnd('\\', '/'),
null,
null);
var userDriveInfo = initializedRunspace.ExecutionContext.SessionState.Drive.New(newDriveInfo, null);
}
catch (ArgumentNullException e) { ex = e; }
catch (ArgumentException e) { ex = e; }
catch (NotSupportedException e) { ex = e; }
catch (ProviderNotFoundException e) { ex = e; }
catch (ProviderInvocationException e) { ex = e; }
catch (KeyNotFoundException e) { ex = e; }
catch (IOException e) { ex = e; }
catch (UnauthorizedAccessException e) { ex = e; }

return ex;
}

private string MakeUserNamePath()
{
// Use the user name passed to initial session state if available, or
Expand Down Expand Up @@ -2875,6 +2962,18 @@ private Exception ProcessStartupScripts(Runspace initializedRunspace)
return null;
}

private void ProcessStartupBlocks(Runspace initializedRunspace)
{
foreach (string startupScript in StartupBlocks)
{
using (PowerShell psToInvoke = PowerShell.Create())
{
psToInvoke.AddCommand(new Command(startupScript, true, true));
ProcessPowerShellCommand(psToInvoke, initializedRunspace);
}
}
}

private Exception ProcessPowerShellCommand(PowerShell psToInvoke, Runspace initializedRunspace)
{
PSLanguageMode originalLanguageMode = initializedRunspace.SessionStateProxy.LanguageMode;
Expand Down Expand Up @@ -4552,25 +4651,25 @@ .ForwardHelpCategory Cmdlet
SpecialVariables.IsLinux,
Platform.IsLinux,
string.Empty,
ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope),
ScopedItemOptions.ReadOnly),

new SessionStateVariableEntry(
SpecialVariables.IsMacOS,
Platform.IsMacOS,
string.Empty,
ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope),
ScopedItemOptions.ReadOnly),

new SessionStateVariableEntry(
SpecialVariables.IsWindows,
Platform.IsWindows,
string.Empty,
ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope),
ScopedItemOptions.ReadOnly),

new SessionStateVariableEntry(
SpecialVariables.IsCoreCLR,
Platform.IsCoreCLR,
string.Empty,
ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope),
ScopedItemOptions.ReadOnly),
#endregion
};

Expand Down Expand Up @@ -5258,7 +5357,8 @@ internal static Assembly LoadPSSnapInAssembly(PSSnapInInfo psSnapInInfo)
// the users of the cmdlet, instead of the author, should have control of what options applied to an alias
// ('ScopedItemOptions.ReadOnly' and/or 'ScopedItemOptions.AllScopes').
var aliasEntry = new SessionStateAliasEntry(alias, cmdletName, description: string.Empty, ScopedItemOptions.None);
if (psSnapInInfo != null) { aliasEntry.SetPSSnapIn(psSnapInInfo); }
if (psSnapInInfo != null)
{ aliasEntry.SetPSSnapIn(psSnapInInfo); }

if (moduleInfo != null)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3989,7 +3989,7 @@ internal ConvertViaNoArgumentConstructor(ConstructorInfo constructor, Type type)
// - It's in FullLanguage but not because it's part of a parameter binding that is transitioning from ConstrainedLanguage to FullLanguage
// When this is invoked from a parameter binding in transition from ConstrainedLanguage environment to FullLanguage command, we disallow
// the property conversion because it's dangerous.
if (ecFromTLS == null || (ecFromTLS.LanguageMode == PSLanguageMode.FullLanguage && !ecFromTLS.LanguageModeTransitionInParameterBinding))
if (ecFromTLS == null || (ecFromTLS.LanguageMode == PSLanguageMode.FullLanguage && !ecFromTLS.LanguageModeTransitionInParameterBinding) || resultType == typeof(InternalPSCustomObject))
{
result = _constructor();
var psobject = valueToConvert as PSObject;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -644,8 +644,16 @@ private PSModuleInfo ImportModule_LocallyViaName(ImportModuleOptions importModul

if (rootedPath == null)
{
// Check for full-qualified paths - either absolute or relative
rootedPath = ResolveRootedFilePath(name, this.Context);
try
{
// Check for full-qualified paths - either absolute or relative
rootedPath = ResolveRootedFilePath(name, this.Context);
}
catch
{
if (File.Exists(name))
rootedPath = name;
}
}

bool alreadyLoaded = false;
Expand Down Expand Up @@ -2024,15 +2032,15 @@ internal override IList<PSModuleInfo> ImportModulesUsingWinCompat(IEnumerable<st
// perform necessary preparations if module has to be imported with NoClobber mode
if (filteredModuleNames != null)
{
foreach(string moduleName in filteredModuleNames)
foreach (string moduleName in filteredModuleNames)
{
PrepareNoClobberWinCompatModuleImport(moduleName, null, ref importModuleOptions);
}
}

if (filteredModuleFullyQualifiedNames != null)
{
foreach(var moduleSpec in filteredModuleFullyQualifiedNames)
foreach (var moduleSpec in filteredModuleFullyQualifiedNames)
{
PrepareNoClobberWinCompatModuleImport(null, moduleSpec, ref importModuleOptions);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,8 @@ internal static IEnumerable<string> GetDefaultAvailableModuleFiles(string topDir
if (File.Exists(moduleFile))
{
isModuleDirectory = true;

PSModuleInfo.AddToAppDomainLevelModuleCache(moduleFile, moduleFile, true);
yield return moduleFile;

// when finding the default modules we stop when the first
Expand Down
Loading

0 comments on commit ccd7550

Please sign in to comment.