Skip to content

Commit

Permalink
Merge branch 'stable'
Browse files Browse the repository at this point in the history
* stable:
  (GH-1117) Get-ChocolateyWebFile - Url Overrides
  (maint) Do not error on missing SMA dll resources
  (GH-1126) Start-ChocolateyProcess no elevate when admin
  (GH-1013) PowerShell external - set debug/verbose false
  (maint) Fix: PackageResult Errors if DownloadUrl is Null
  (maint) formatting
  (GH-1121) API - Do not reset loggers
  (GH-1041) Fix: Skip loading synced dlls as extensions
  (GH-1013) PowerShell - Only import installer module
  (GH-1118) Feature to disable non-elevated warnings
  (maint)(log) Show Formatted Download Progress Only
  (GH-1035) Auto Uninstaller Skip if File Doesn't Exist
  (GH-1119) Auto Uninstaller - Allow remove directly
  (build) change message
  (doc) explain upgrading licensed version
  • Loading branch information
ferventcoder committed Jan 4, 2017
2 parents 7ff013f + 16fe0c8 commit 6031bb8
Show file tree
Hide file tree
Showing 17 changed files with 215 additions and 118 deletions.
2 changes: 1 addition & 1 deletion .build.custom/codeSign.step
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\signtool.exe sign /t http://timestamp.digicert.com /fd SHA1 /f %CHOCOLATEY_OFFICIAL_CERT% /p [INSERT] /a "code_drop\chocolatey\console\choco.exe"
-->

<target name="sign_assemblies" description="Signs the final choco.exe assembly prior to packaging it up." if="${file::exists(app.signtool) and property::exists('path.code.cert')}">
<target name="sign_assemblies" description="Signs the final assembly prior to packaging it up." if="${file::exists(app.signtool) and property::exists('path.code.cert')}">
<echo level="Warning" message="Signing the assemblies using ${app.signtool}." />
<property name="app.choco" value="${dirs.drop}${path.separator}chocolatey${path.separator}console${path.separator}choco.exe" />
<property name="lib.choco" value="${dirs.drop}${path.separator}chocolatey${path.separator}lib${path.separator}chocolatey.dll" />
Expand Down
2 changes: 2 additions & 0 deletions src/chocolatey.resources/helpers/chocolateyInstaller.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ if (Test-Path($extensionsPath)) {
Get-ChildItem $extensionsPath -recurse -filter "*.psm1" | Select -ExpandProperty FullName | % { Write-Debug "Importing `'$_`'"; Import-Module $_; }
Get-ChildItem $extensionsPath -recurse -filter "*.dll" | Select -ExpandProperty FullName | % {
$path = $_;
if ($path.Contains("extensions\chocolatey\lib-synced") { continue }

try {
Write-Debug "Importing '$path'";
Write-Debug "Loading '$([System.IO.Path]::GetFileNameWithoutExtension($path))' extension.";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,12 @@ param(

Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters

# url overrides
$urlOverride = $env:ChocolateyUrlOverride
$url64bitOverride = $env:ChocolateyUrl64bitOverride
if ($urlOverride -ne $null -and $urlOverride -ne '') { $url = $urlOverride }
if ($url64bitOverride -ne $null -and $url64bitOverride -ne '') { $url64bit = $url64bitOverride }

if ($url -ne $null) { $url = $url.Replace("//","/").Replace(":/","://") }
if ($url64bit -ne $null) { $url64bit = $url64bit.Replace("//","/").Replace(":/","://") }

Expand Down
2 changes: 1 addition & 1 deletion src/chocolatey.resources/helpers/functions/Get-WebFile.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,7 @@ param(
$totalFormatted = Format-FileSize $total
if($goal -gt 0 -and ++$iterLoop%10 -eq 0) {
$percentComplete = [Math]::Truncate(($total/$goal)*100)
Write-Progress "Downloading $url to $fileName" "Saving $totalFormatted of $goalFormatted ($total/$goal)" -id 0 -percentComplete $percentComplete
Write-Progress "Downloading $url to $fileName" "Saving $totalFormatted of $goalFormatted" -id 0 -percentComplete $percentComplete
}

if ($total -eq $goal -and $count -eq 0) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,17 @@ param(

Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters

try{
$alreadyElevated = $false
if (Test-ProcessAdminRights) {
$alreadyElevated = $true
}

$dbMessagePrepend = "Elevating permissions and running"
if (!$elevated) {
$dbMessagePrepend = "Running"
}

try {
if ($exeToRun -ne $null) { $exeToRun = $exeToRun -replace "`0", "" }
if ($statements -ne $null) { $statements = $statements -replace "`0", "" }
} catch {
Expand All @@ -126,11 +136,30 @@ param(
if ($wrappedStatements -eq $null) { $wrappedStatements = ''}

if ($exeToRun -eq 'powershell') {
if ($alreadyElevated) {
$block = @"
try {
$statements
} catch {
throw
}
"@

& $block
$scriptSuccess = $?
if (-not $scriptSuccess) {
return 1
}

return 0
}

$exeToRun = "$($env:SystemRoot)\System32\WindowsPowerShell\v1.0\powershell.exe"
$importChocolateyHelpers = ""
Get-ChildItem "$helpersPath" -Filter *.psm1 | ForEach-Object { $importChocolateyHelpers = "& import-module -name `'$($_.FullName)`' | Out-Null; $importChocolateyHelpers" };
$importChocolateyHelpers = "& import-module -name '$helpersPath\chocolateyInstaller.psm1' -Verbose:`$false | Out-Null;"
$block = @"
`$noSleep = `$$noSleep
#`$env:ChocolateyEnvironmentDebug='false'
#`$env:ChocolateyEnvironmentVerbose='false'
$importChocolateyHelpers
try{
`$progressPreference="SilentlyContinue"
Expand All @@ -143,23 +172,18 @@ param(
}
"@
$encoded = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($block))
$wrappedStatements = "-NoProfile -ExecutionPolicy bypass -EncodedCommand $encoded"
$wrappedStatements = "-NoLogo -NonInteractive -NoProfile -ExecutionPolicy Bypass -InputFormat Text -OutputFormat Text -EncodedCommand $encoded"
$dbgMessage = @"
Elevating Permissions and running powershell block:
$dbMessagePrepend powershell block:
$block
This may take a while, depending on the statements.
"@

}
else
{
$dbgMessage = @"
Elevating Permissions and running [`"$exeToRun`" $wrappedStatements]. This may take a while, depending on the statements.
"@
}

if (!$elevated) {
$dbgMessage = @"
Running [`"$exeToRun`" $wrappedStatements]. This may take a while, depending on the statements.
$dbMessagePrepend [`"$exeToRun`" $wrappedStatements]. This may take a while, depending on the statements.
"@
}

Expand Down Expand Up @@ -224,7 +248,7 @@ Running [`"$exeToRun`" $wrappedStatements]. This may take a while, depending on
$process.StartInfo.UseShellExecute = $false
$process.StartInfo.WorkingDirectory = $workingDirectory

if ($elevated -and [Environment]::OSVersion.Version -ge (New-Object 'Version' 6,0)){
if ($elevated -and -not $alreadyElevated -and [Environment]::OSVersion.Version -ge (New-Object 'Version' 6,0)){
# this doesn't actually currently work - because we are not running under shell execute
Write-Debug "Setting RunAs for elevation"
$process.StartInfo.Verb = "RunAs"
Expand Down Expand Up @@ -265,7 +289,7 @@ Running [`"$exeToRun`" $wrappedStatements]. This may take a while, depending on
}
}

Write-Debug "Finishing 'Start-ChocolateyProcessAsAdmin'"
Write-Debug "Finishing '$($MyInvocation.InvocationName)'"

return $exitCode
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ public override void Context()
fileSystem.Setup(f => f.directory_exists(registryKeys.FirstOrDefault().InstallLocation)).Returns(true);
registryService.Setup(r => r.installer_value_exists(registryKeys.FirstOrDefault().KeyPath, ApplicationParameters.RegistryValueInstallLocation)).Returns(true);
fileSystem.Setup(f => f.get_full_path(expectedUninstallString)).Returns(expectedUninstallString);
fileSystem.Setup(x => x.file_exists(expectedUninstallString)).Returns(true);

var field = typeof(ApplicationParameters).GetField("AllowPrompts");
field.SetValue(null, false);
Expand Down Expand Up @@ -177,6 +178,7 @@ public override void Context()
base.Context();
fileSystem.ResetCalls();
fileSystem.Setup(f => f.directory_exists(registryKeys.FirstOrDefault().InstallLocation)).Returns(false);
fileSystem.Setup(x => x.file_exists(expectedUninstallString)).Returns(true);
}

public override void Because()
Expand Down Expand Up @@ -212,6 +214,7 @@ public override void Context()
KeyPath = @"HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\WinDirStat"
});
packageInformation.RegistrySnapshot = new Registry("123", registryKeys);
fileSystem.Setup(x => x.file_exists(expectedUninstallString)).Returns(true);
}

public override void Because()
Expand Down Expand Up @@ -267,6 +270,7 @@ public override void Context()
base.Context();
fileSystem.ResetCalls();
fileSystem.Setup(f => f.directory_exists(registryKeys.FirstOrDefault().InstallLocation)).Returns(false);
fileSystem.Setup(x => x.file_exists(expectedUninstallString)).Returns(true);
registryService.ResetCalls();
registryService.Setup(r => r.installer_value_exists(registryKeys.FirstOrDefault().KeyPath, ApplicationParameters.RegistryValueInstallLocation)).Returns(false);
}
Expand All @@ -289,6 +293,36 @@ public void should_not_call_command_executor()
}
}

public class when_uninstall_exe_does_not_exist : AutomaticUninstallerServiceSpecsBase
{
public override void Context()
{
base.Context();
fileSystem.ResetCalls();
fileSystem.Setup(f => f.directory_exists(registryKeys.FirstOrDefault().InstallLocation)).Returns(true);
fileSystem.Setup(f => f.get_full_path(expectedUninstallString)).Returns(expectedUninstallString);
fileSystem.Setup(x => x.file_exists(expectedUninstallString)).Returns(false);
}

public override void Because()
{
MockLogger.LogMessagesToConsole = true;
service.run(packageResult, config);
}

[Fact]
public void should_log_why_it_skips_auto_uninstaller()
{
MockLogger.Verify(l => l.Info(" Skipping auto uninstaller - The uninstaller file no longer exists. \"" + expectedUninstallString +"\""), Times.Once);
}

[Fact]
public void should_not_call_command_executor()
{
commandExecutor.Verify(c => c.execute(It.IsAny<String>(), It.IsAny<String>(), It.IsAny<int>(), It.IsAny<Action<object, DataReceivedEventArgs>>(), It.IsAny<Action<object, DataReceivedEventArgs>>(), It.IsAny<bool>()), Times.Never);
}
}

public class when_AutomaticUninstallerService_is_run_normally : AutomaticUninstallerServiceSpecsBase
{
public override void Because()
Expand Down
10 changes: 4 additions & 6 deletions src/chocolatey/GetChocolatey.cs
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ public GetChocolatey()
/// <returns>This <see cref="GetChocolatey"/> instance</returns>
public GetChocolatey SetCustomLogging(ILog logger)
{
Log.InitializeWith(logger);
Log.InitializeWith(logger, resetLoggers: false);
return this;
}

Expand All @@ -118,9 +118,9 @@ public GetChocolatey SetCustomLogging(ILog logger)
public GetChocolatey Set(Action<ChocolateyConfiguration> propConfig)
{
_propConfig = propConfig;
return this;
return this;
}

/// <summary>
/// Registers a container component. Does not require a dependency on Simple Injector.
/// Will override existing component if registered.
Expand All @@ -131,7 +131,6 @@ public GetChocolatey Set(Action<ChocolateyConfiguration> propConfig)
public GetChocolatey RegisterContainerComponent(Type service, Type implementation)
{
_container.Register(service,implementation,Lifestyle.Singleton);

return this;
}

Expand Down Expand Up @@ -163,7 +162,6 @@ public GetChocolatey RegisterContainerComponent<Service,Implementation>(Lifestyl
where Implementation : class, Service
{
_container.Register<Service,Implementation>(lifestyle);

return this;
}

Expand All @@ -178,7 +176,6 @@ public GetChocolatey RegisterContainerComponent<Service>(Func<Service> implement
where Service : class
{
_container.Register(implementationCreator,Lifestyle.Singleton);

return this;
}

Expand Down Expand Up @@ -270,6 +267,7 @@ private ChocolateyConfiguration create_configuration(IList<string> args)
{
_propConfig.Invoke(configuration);
}

return configuration;
}

Expand Down
1 change: 1 addition & 0 deletions src/chocolatey/infrastructure.app/ApplicationParameters.cs
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,7 @@ public static class Features
public static readonly string UsePackageExitCodes = "usePackageExitCodes";
public static readonly string UseFipsCompliantChecksums = "useFipsCompliantChecksums";
public static readonly string ScriptsCheckLastExitCode = "scriptsCheckLastExitCode";
public static readonly string ShowNonElevatedWarnings = "showNonElevatedWarnings";
}

public static class Messages
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,7 @@ private static void set_feature_flags(ChocolateyConfiguration config, ConfigFile
config.Features.IgnoreInvalidOptionsSwitches = set_feature_flag(ApplicationParameters.Features.IgnoreInvalidOptionsSwitches, configFileSettings, defaultEnabled: true, description: "Ignore Invalid Options/Switches - If a switch or option is passed that is not recognized, should choco fail? Available in 0.9.10+.");
config.Features.UsePackageExitCodes = set_feature_flag(ApplicationParameters.Features.UsePackageExitCodes, configFileSettings, defaultEnabled: true, description: "Use Package Exit Codes - Package scripts can provide exit codes. With this on, package exit codes will be what choco uses for exit when non-zero (this value can come from a dependency package). Chocolatey defines valid exit codes as 0, 1605, 1614, 1641, 3010. With this feature off, choco will exit with a 0 or a 1 (matching previous behavior). Available in 0.9.10+.");
config.Features.UseFipsCompliantChecksums = set_feature_flag(ApplicationParameters.Features.UseFipsCompliantChecksums, configFileSettings, defaultEnabled: false, description: "Use FIPS Compliant Checksums - Ensure checksumming done by choco uses FIPS compliant algorithms. Not recommended unless required by FIPS Mode. Enabling on an existing installation could have unintended consequences related to upgrades/uninstalls. Available in 0.9.10+.");
config.Features.ShowNonElevatedWarnings = set_feature_flag(ApplicationParameters.Features.ShowNonElevatedWarnings, configFileSettings, defaultEnabled: true, description: "Show Non-Elevated Warnings - Display non-elevated warnings. Available in 0.10.4+.");
config.Features.ScriptsCheckLastExitCode = set_feature_flag(ApplicationParameters.Features.ScriptsCheckLastExitCode, configFileSettings, defaultEnabled: false, description: "Scripts Check $LastExitCode (external commands) - Leave this off unless you absolutely need it while you fix your package scripts to use `throw 'error message'` or `Set-PowerShellExitCode #` instead of `exit #`. This behavior started in 0.9.10 and produced hard to find bugs. If the last external process exits successfully but with an exit code of not zero, this could cause hard to detect package failures. Available in 0.10.3+. Will be removed in 0.11.0.");
config.PromptForConfirmation = !set_feature_flag(ApplicationParameters.Features.AllowGlobalConfirmation, configFileSettings, defaultEnabled: false, description: "Prompt for confirmation in scripts or bypass.");
}
Expand Down Expand Up @@ -459,7 +460,7 @@ private static void set_licensed_options(ChocolateyConfiguration config, Chocola
{
if (config.RegularOutput) "chocolatey".Log().Warn(ChocolateyLoggers.Important,
@"Unable to set licensed configuration. Please upgrade to a newer
licensed version.");
licensed version (choco upgrade chocolatey.extension).");
return;
}
try
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,6 @@ private void append_output(StringBuilder propertyValues, string append)
public bool AcceptLicense { get; set; }
public bool AllowUnofficialBuild { get; set; }


/// <summary>
/// Usually related to unparsed arguments.
/// </summary>
Expand Down Expand Up @@ -262,7 +261,6 @@ private void append_output(StringBuilder propertyValues, string append)
/// </remarks>
public SourcesCommandConfiguration SourceCommand { get; set; }


/// <summary>
/// Default Machine Sources Configuration
/// </summary>
Expand Down Expand Up @@ -354,6 +352,7 @@ public sealed class FeaturesConfiguration
public bool IgnoreInvalidOptionsSwitches { get; set; }
public bool UsePackageExitCodes { get; set; }
public bool UseFipsCompliantChecksums { get; set; }
public bool ShowNonElevatedWarnings { get; set; }
//todo remove in 0.11.0
public bool ScriptsCheckLastExitCode { get; set; }
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ private static void set_licensed_environment(ChocolateyConfiguration config)
{
if (config.RegularOutput) "chocolatey".Log().Warn(
ChocolateyLoggers.Important, @"Unable to set licensed environment settings. Please upgrade to a newer
licensed version.");
licensed version (choco upgrade chocolatey.extension).");
return;
}
try
Expand Down
3 changes: 3 additions & 0 deletions src/chocolatey/infrastructure.app/runners/GenericRunner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,9 @@ public int count(ChocolateyConfiguration config, Container container, bool isCon
public void warn_when_admin_needs_elevation(ChocolateyConfiguration config)
{
if (config.HelpRequested) return;

// skip when commands will set or for background mode
if (!config.Features.ShowNonElevatedWarnings) return;

var shouldWarn = (!config.Information.IsProcessElevated && config.Information.IsUserAdministrator)
|| (!config.Information.IsUserAdministrator && ApplicationParameters.InstallLocation.is_equal_to(ApplicationParameters.CommonAppDataChocolatey));
Expand Down
Loading

0 comments on commit 6031bb8

Please sign in to comment.