Skip to content

Commit

Permalink
Merge pull request #175 from gerardog/Feature.LoadProfile
Browse files Browse the repository at this point in the history
Fix (technical debt): Unify `gsudo config PowerShellLoadProfile` and `$gsudoLoadProfile` into the first one.
  • Loading branch information
gerardog authored Sep 20, 2022
2 parents 5332cf3 + 6c5b9d8 commit 7d643ab
Show file tree
Hide file tree
Showing 5 changed files with 110 additions and 100 deletions.
4 changes: 2 additions & 2 deletions docs/docs/usage/powershell.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,8 +115,8 @@ For faster performance, elevation is called with the `-NoProfile` argument. If y

When using `gsudo`, infix `--loadProfile`:
- `PS C:\> gsudo --loadProfile echo (1+1)`
- Set as a permanent setting with `gsudo config PowerShellLoadProfile true`

When using `Invoke-gsudo`, add `-LoadProfile`:
- `PS C:\> Invoke-Gsudo { echo (1+1) } -LoadProfile`
- Set as a permanent setting adding `$gsudoLoadProfile=$true` in your `$PROFILE` after `Import-Module C:\FullPathTo\gsudoModule.psd1`

Set as a permanent setting with `gsudo config PowerShellLoadProfile true`
18 changes: 14 additions & 4 deletions src/gsudo.Wrappers/Invoke-gsudo.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,10 @@ param
[Parameter()]
[switch]
$LoadProfile = $false,

[Parameter()]
[switch]
$NoProfile = $false,

#test mode
[Parameter()]
Expand Down Expand Up @@ -153,9 +157,14 @@ if($NoElevate) {
$windowTitle = $host.ui.RawUI.WindowTitle;

$dbg = if ($debug) {"--debug "} else {" "}
$NoProfile = if ($gsudoLoadProfile -or $LoadProfile) {""} else {"-NoProfile "}

$arguments = "-d $dbg--LogLevel Error $pwsh -nologo $NoProfile-NonInteractive -OutputFormat Xml -InputFormat Text -encodedCommand IAAoACQAaQBuAHAAdQB0ACAAfAAgAE8AdQB0AC0AUwB0AHIAaQBuAGcAKQAgAHwAIABpAGUAeAAgAA==".Split(" ")
if ($LoadProfile -or ((gsudo.exe --loglevel None config Powershellloadprofile).Split(" = ")[1] -like "*true*" -and -not $NoProfile)) {
$sNoProfile = ""
} else {
$sNoProfile = "-NoProfile "
}

$arguments = "-d --LogLevel Error $dbg$pwsh -nologo $sNoProfile-NonInteractive -OutputFormat Xml -InputFormat Text -encodedCommand IAAoACQAaQBuAHAAdQB0ACAAfAAgAE8AdQB0AC0AUwB0AHIAaQBuAGcAKQAgAHwAIABpAGUAeAAgAA==".Split(" ")

# Must Read: https://stackoverflow.com/questions/68136128/how-do-i-call-the-powershell-cli-robustly-with-respect-to-character-encoding-i?noredirect=1&lq=1
$result = $remoteCmd | & gsudo.exe $arguments *>&1
Expand All @@ -166,8 +175,9 @@ if($NoElevate) {
ForEach ($item in $result)
{
if (
$item.Exception.SerializedRemoteException.WasThrownFromThrowStatement -or
$item.Exception.WasThrownFromThrowStatement
$item.psobject.Properties['Exception'] -and
($item.Exception.SerializedRemoteException.WasThrownFromThrowStatement -or
$item.Exception.WasThrownFromThrowStatement)
)
{
throw $item
Expand Down
2 changes: 1 addition & 1 deletion src/gsudo.Wrappers/gsudoModule.psd1
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ FunctionsToExport = 'gsudo', 'invoke-gsudo'
CmdletsToExport = @()

# Variables to export from this module
VariablesToExport = 'gsudoVerbose', 'gsudoLoadProfile'
VariablesToExport = 'gsudoVerbose'

# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
AliasesToExport = @()
Expand Down
6 changes: 1 addition & 5 deletions src/gsudo.Wrappers/gsudoModule.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,4 @@ function gsudo {

$gsudoVerbose=$true;

# On your $PROFILE set $gsudoLoadProfile=$true to make invoke-gsudo load your profile.
# Warning: If you do, then do not write to console/Out on your $profile or else that lines will appear in your Invoke-gsudo result.
$gsudoLoadProfile=$false;

Export-ModuleMember -function Invoke-Gsudo, gsudo -Variable gsudoVerbose, gsudoLoadProfile
Export-ModuleMember -function Invoke-Gsudo, gsudo -Variable gsudoVerbose
180 changes: 92 additions & 88 deletions src/gsudo/Commands/ConfigCommand.cs
Original file line number Diff line number Diff line change
@@ -1,88 +1,92 @@
using gsudo.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace gsudo.Commands
{
class ConfigCommand : ICommand
{
public string key { get; set; }

public IEnumerable<string> value { get; set; }

public Task<int> Execute()
{
RegistrySetting setting = null;

if (key == null)
{
// print all configs
foreach (var k in Settings.AllKeys)
Console.WriteLine($"{k.Value.Name} = \"{ k.Value.GetStringValue().ToString()}\"".PadRight(50) + (k.Value.HasGlobalValue() ? "(global)" : (k.Value.HasLocalValue() ? "(user)" : string.Empty)));

return Task.FromResult(0);
}

Settings.AllKeys.TryGetValue(key, out setting);

if (setting == null)
{
Logger.Instance.Log($"Invalid Setting '{key}'.", LogLevel.Error);
return Task.FromResult(Constants.GSUDO_ERROR_EXITCODE);
}

if (value != null && value.Any())
{
if (value.Any(v => v.In("--global")))
{
InputArguments.Global = true;
value = value.Where(v => !v.In("--global"));
}

bool reset = value.Any(v => v.In("--reset"));
value = value.Where(v => !v.In("--reset"));

string unescapedValue =
(value.Count() == 1)
? ArgumentsHelper.UnQuote(value.FirstOrDefault()).Replace("\\%", "%")
: string.Join(" ", value.ToArray());

if (!reset) _ = setting.Parse(unescapedValue);

if (!InputArguments.Global && setting.Scope == RegistrySettingScope.GlobalOnly)
{
Logger.Instance.Log($"Config Setting for '{setting.Name}' will be set as global system setting.", LogLevel.Info);
InputArguments.Global = true;
}

if (InputArguments.Global && !ProcessHelper.IsAdministrator())
{
Logger.Instance.Log($"Global system settings requires elevation. Elevating...", LogLevel.Info);
InputArguments.Direct = true;
return new RunCommand()
{
CommandToRun = new string[]
{ $"\"{ProcessHelper.GetOwnExeName()}\"", "--global", "config", key, reset ? "--reset" : $"\"{unescapedValue}\""}
}.Execute();
}

if (reset)
setting.Reset(InputArguments.Global); // reset to default value
else
setting.Save(unescapedValue, InputArguments.Global);

if (setting.Name == Settings.CacheMode.Name && unescapedValue.In(Enums.CacheMode.Disabled.ToString()))
new KillCacheCommand().Execute();
if (setting.Name.In (Settings.CacheDuration.Name, Settings.SecurityEnforceUacIsolation.Name))
new KillCacheCommand().Execute();
}

// READ
setting.ClearRunningValue();
Console.WriteLine($"{setting.Name} = \"{ setting.GetStringValue().ToString()}\" {(setting.HasGlobalValue() ? "(global)" : (setting.HasLocalValue() ? "(user)" : "(default)"))}");
return Task.FromResult(0);
}
}
}
using gsudo.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace gsudo.Commands
{
class ConfigCommand : ICommand
{
public string key { get; set; }

public IEnumerable<string> value { get; set; }

public Task<int> Execute()
{
RegistrySetting setting = null;

if (key == null)
{
// print all configs
foreach (var k in Settings.AllKeys)
{
var scope = k.Value.HasGlobalValue() ? "(global)" :
(k.Value.HasLocalValue() ? "(user)" : "(default)");
Console.WriteLine($"{k.Value.Name} = \"{ k.Value.GetStringValue().ToString()}\" ".PadRight(50) + scope);
}

return Task.FromResult(0);
}

Settings.AllKeys.TryGetValue(key, out setting);

if (setting == null)
{
Logger.Instance.Log($"Invalid Setting '{key}'.", LogLevel.Error);
return Task.FromResult(Constants.GSUDO_ERROR_EXITCODE);
}

if (value != null && value.Any()) // Write Setting
{
if (value.Any(v => v.In("--global")))
{
InputArguments.Global = true;
value = value.Where(v => !v.In("--global"));
}

bool reset = value.Any(v => v.In("--reset"));
value = value.Where(v => !v.In("--reset"));

string unescapedValue =
(value.Count() == 1)
? ArgumentsHelper.UnQuote(value.FirstOrDefault()).Replace("\\%", "%")
: string.Join(" ", value.ToArray());

if (!reset) _ = setting.Parse(unescapedValue);

if (!InputArguments.Global && setting.Scope == RegistrySettingScope.GlobalOnly)
{
Logger.Instance.Log($"Config Setting for '{setting.Name}' will be set as global system setting.", LogLevel.Info);
InputArguments.Global = true;
}

if (InputArguments.Global && !ProcessHelper.IsAdministrator())
{
Logger.Instance.Log($"Global system settings requires elevation. Elevating...", LogLevel.Info);
InputArguments.Direct = true;
return new RunCommand()
{
CommandToRun = new string[]
{ $"\"{ProcessHelper.GetOwnExeName()}\"", "--global", "config", key, reset ? "--reset" : $"\"{unescapedValue}\""}
}.Execute();
}

if (reset)
setting.Reset(InputArguments.Global); // reset to default value
else
setting.Save(unescapedValue, InputArguments.Global);

if (setting.Name == Settings.CacheMode.Name && unescapedValue.In(Enums.CacheMode.Disabled.ToString()))
new KillCacheCommand().Execute();
if (setting.Name.In (Settings.CacheDuration.Name, Settings.SecurityEnforceUacIsolation.Name))
new KillCacheCommand().Execute();
}

// READ
setting.ClearRunningValue();
Console.WriteLine($"{setting.Name} = \"{ setting.GetStringValue().ToString()}\"");
return Task.FromResult(0);
}
}
}

0 comments on commit 7d643ab

Please sign in to comment.