Skip to content

Commit

Permalink
Merge branch 'master' into develop
Browse files Browse the repository at this point in the history
* master:
  (maint) If statement formatting change
  (#3224) Add Assembly Loaded configuration option
  (maint) Resave without BOM
  (#3224) Update version check tests
  (#3174) Store non-normalized package version
  (maint) Add required whitespace
  (#3225) Add Pester Tests to ensure environment
  (#3201 #3225) Re-instate setting of config values
  (maint) Remove env variable for release version
  (maint) Fix encoding of file
  (#3194) Add tab completion for cache command
  (#2854) Re-save file with UTF-8 with BOM
  (#3218) Update Tab Expansion to use Test-Path
  (#3218) Remove try catch block for tab completion
  • Loading branch information
gep13 committed Jun 29, 2023
2 parents f96f014 + 46976cf commit 0a7efcf
Show file tree
Hide file tree
Showing 13 changed files with 209 additions and 56 deletions.
85 changes: 41 additions & 44 deletions src/chocolatey.resources/helpers/ChocolateyTabExpansion.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ function script:chocoCmdOperations($commands, $command, $filter, $currentArgumen
Where-Object { $_ -like "$filter*" }
}

$script:chocoCommands = @('-?','search','list','info','install','outdated','upgrade','uninstall','new','pack','push','-h','--help','pin','source','config','feature','apikey','export','help','template','--version')
$script:chocoCommands = @('-?','search','list','info','install','outdated','upgrade','uninstall','new','pack','push','-h','--help','pin','source','config','feature','apikey','export','help','template','cache','--version')

# ensure these all have a space to start, or they will cause issues
$allcommands = " --debug --verbose --trace --noop --help -? --online --accept-license --confirm --limit-output --no-progress --log-file='' --execution-timeout='' --cache-location='' --proxy='' --proxy-user='' --proxy-password='' --proxy-bypass-list='' --proxy-bypass-on-local --force --no-color --skip-compatibility-checks --ignore-http-cache"
Expand All @@ -58,65 +58,57 @@ $commandOptions = @{
apikey = "--source='' --api-key='' --remove"
export = "--include-version-numbers --output-file-path=''"
template = "--name=''"
cache = "--expired"
}

$commandOptions['find'] = $commandOptions['search']

try {
$licenseFile = Get-Item -Path "$env:ChocolateyInstall\license\chocolatey.license.xml" -ErrorAction Stop
$licenseFile = "$env:ChocolateyInstall\license\chocolatey.license.xml"

if ($licenseFile) {
# Add pro-only commands
$script:chocoCommands = @(
$script:chocoCommands
'download'
'optimize'
)
if (Test-Path $licenseFile) {
# Add pro-only commands
$script:chocoCommands = @(
$script:chocoCommands
'download'
'optimize'
)

$commandOptions.download = "--internalize --internalize-all-urls --ignore-dependencies --installed-packages --ignore-unfound-packages --resources-location='' --download-location='' --outputdirectory='' --source='' --version='' --prerelease --user='' --password='' --cert='' --certpassword='' --append-use-original-location --recompile --disable-package-repository-optimizations"
$commandOptions.sync = "--output-directory='' --id='' --package-id=''"
$commandOptions.optimize = "--deflate-nupkg-only --id=''"
$commandOptions.download = "--internalize --internalize-all-urls --ignore-dependencies --installed-packages --ignore-unfound-packages --resources-location='' --download-location='' --outputdirectory='' --source='' --version='' --prerelease --user='' --password='' --cert='' --certpassword='' --append-use-original-location --recompile --disable-package-repository-optimizations"
$commandOptions.sync = "--output-directory='' --id='' --package-id=''"
$commandOptions.optimize = "--deflate-nupkg-only --id=''"

# Add pro switches to commands that have additional switches on Pro
$proInstallUpgradeOptions = " --install-directory='' --package-parameters-sensitive='' --max-download-rate='' --install-arguments-sensitive='' --skip-download-cache --use-download-cache --skip-virus-check --virus-check --virus-positives-minimum='' --deflate-package-size --no-deflate-package-size --deflate-nupkg-only"
# Add pro switches to commands that have additional switches on Pro
$proInstallUpgradeOptions = " --install-directory='' --package-parameters-sensitive='' --max-download-rate='' --install-arguments-sensitive='' --skip-download-cache --use-download-cache --skip-virus-check --virus-check --virus-positives-minimum='' --deflate-package-size --no-deflate-package-size --deflate-nupkg-only"

$commandOptions.install += $proInstallUpgradeOptions
$commandOptions.upgrade += $proInstallUpgradeOptions + " --exclude-chocolatey-packages-during-upgrade-all --include-chocolatey-packages-during-upgrade-all"
$commandOptions.new += " --build-package --use-original-location --keep-remote --url='' --url64='' --checksum='' --checksum64='' --checksumtype='' --pause-on-error"
$commandOptions.pin += " --note=''"
$commandOptions.install += $proInstallUpgradeOptions
$commandOptions.upgrade += $proInstallUpgradeOptions + " --exclude-chocolatey-packages-during-upgrade-all --include-chocolatey-packages-during-upgrade-all"
$commandOptions.new += " --build-package --use-original-location --keep-remote --url='' --url64='' --checksum='' --checksum64='' --checksumtype='' --pause-on-error"
$commandOptions.pin += " --note=''"

# Add Business-only commands and options if the license is a Business or Trial license
[xml]$xml = Get-Content -Path $licenseFile.FullName -ErrorAction Stop
$licenseType = $xml.license.type
# Add Business-only commands and options if the license is a Business or Trial license
[xml]$xml = Get-Content -Path $licenseFile -ErrorAction Stop
$licenseType = $xml.license.type

if ('Business', 'BusinessTrial' -contains $licenseType) {
if ('Business', 'BusinessTrial' -contains $licenseType) {

# Add business-only commands
$script:chocoCommands = @(
$script:chocoCommands
'support'
'sync'
)
# Add business-only commands
$script:chocoCommands = @(
$script:chocoCommands
'support'
'sync'
)

$commandOptions.list += " --audit"
$commandOptions.uninstall += " --from-programs-and-features"
$commandOptions.new += " --file='' --file64='' --from-programs-and-features --remove-architecture-from-name --include-architecture-in-name"
$commandOptions.list += " --audit"
$commandOptions.uninstall += " --from-programs-and-features"
$commandOptions.new += " --file='' --file64='' --from-programs-and-features --remove-architecture-from-name --include-architecture-in-name"

# Add --use-self-service to commands that support it
$selfServiceCommands = 'list', 'find', 'search', 'info', 'install', 'upgrade', 'uninstall', 'pin', 'outdated', 'push', 'download', 'sync', 'optimize'
foreach ($command in $selfServiceCommands) {
$commandOptions.$command += ' --use-self-service'
}
# Add --use-self-service to commands that support it
$selfServiceCommands = 'list', 'find', 'search', 'info', 'install', 'upgrade', 'uninstall', 'pin', 'outdated', 'push', 'download', 'sync', 'optimize'
foreach ($command in $selfServiceCommands) {
$commandOptions.$command += ' --use-self-service'
}
}
}
catch {
# Remove the error that last occurred from $error so it doesn't cause any
# issues for users, as we're deliberately ignoring it.
if ($error.Count -gt 0) {
$error.RemoveAt(0)
}
}

foreach ($key in @($commandOptions.Keys)) {
$commandOptions.$key += $allcommands
Expand Down Expand Up @@ -233,6 +225,11 @@ function ChocolateyTabExpansion($lastBlock) {
@('list', 'info', '-?') | Where-Object { $_ -like "$($matches['subcommand'])*" }
}

# Handles cache first tab
"^(cache)\s+(?<subcommand>[^-\s]*)$" {
@('list', 'remove', '-?') | Where-Object { $_ -like "$($matches['subcommand'])*" }
}

# Handles more options after others
"^(?<cmd>$($commandOptions.Keys -join '|'))(?<currentArguments>.*)\s+(?<op>\S*)$" {
chocoCmdOperations $commandOptions $matches['cmd'] $matches['op'] $matches['currentArguments']
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Copyright © 2022 Chocolatey Software, Inc.
# Copyright © 2022 Chocolatey Software, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
Expand Down
60 changes: 60 additions & 0 deletions src/chocolatey/StringResources.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// Copyright © 2023-Present Chocolatey Software, Inc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
//
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

namespace chocolatey
{
using System.ComponentModel;

public static class StringResources
{
/// <summary>
/// Resources for the names of available environment variables
/// that will be created or used as part of executing
/// Chocolatey CLI.
/// </summary>
/// <remarks>
/// DEV NOTICE: Mark anything that is not meant for public consumption as
/// internal constants and not browsable, even if used in other projects.
/// </remarks>
public static class EnvironmentVariables
{
/// <summary>
/// The version of the package that is being handled as it is defined in the embedded
/// nuspec file.
/// </summary>
/// <remarks>
/// Will be sets during package installs, upgrades and uninstalls.
/// Environment variable is only for internal uses.
/// </remarks>
/// <seealso cref="PackageNuspecVersion" />
[EditorBrowsable(EditorBrowsableState.Never)]
[Browsable(false)]
internal const string ChocolateyPackageNuspecVersion = "chocolateyPackageNuspecVersion";

/// <summary>
/// The version of the package that is being handled as it is defined in the embedded
/// nuspec file.
/// </summary>
/// <remarks>
/// Will be sets during package installs, upgrades and uninstalls.
/// Environment variable is only for internal uses.
/// </remarks>
/// <seealso cref="ChocolateyPackageNuspecVersion" />
[EditorBrowsable(EditorBrowsableState.Never)]
[Browsable(false)]
internal const string PackageNuspecVersion = "packageNuspecVersion";
}
}
}
1 change: 1 addition & 0 deletions src/chocolatey/chocolatey.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -475,6 +475,7 @@
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="RuleResultExtensions.cs" />
<Compile Include="StringExtensions.cs" />
<Compile Include="StringResources.cs" />
<Compile Include="TypeExtensions.cs" />
</ItemGroup>
<ItemGroup>
Expand Down
20 changes: 16 additions & 4 deletions src/chocolatey/infrastructure.app/builders/ConfigurationBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,15 @@ private static void SetMachineSources(ChocolateyConfiguration config, ConfigFile

private static void SetAllConfigItems(ChocolateyConfiguration config, ConfigFileSettings configFileSettings, IFileSystem fileSystem)
{
config.CacheLocation = Environment.ExpandEnvironmentVariables(
SetConfigItem(
ApplicationParameters.ConfigSettings.CacheLocation,
configFileSettings,
string.Empty,
"Cache location if not TEMP folder. Replaces `$env:TEMP` value for choco.exe process. It is highly recommended this be set to make Chocolatey more deterministic in cleanup."
)
);

if (string.IsNullOrWhiteSpace(config.CacheLocation))
{
config.CacheLocation = fileSystem.GetTempPath(); // System.Environment.GetEnvironmentVariable("TEMP");
Expand All @@ -233,10 +242,12 @@ private static void SetAllConfigItems(ChocolateyConfiguration config, ConfigFile
if (string.IsNullOrWhiteSpace(config.CacheLocation)) config.CacheLocation = fileSystem.CombinePaths(ApplicationParameters.InstallLocation, "temp");

var commandExecutionTimeoutSeconds = 0;
var commandExecutionTimeout = configFileSettings.ConfigSettings
.Where(f => f.Key.IsEqualTo(ApplicationParameters.ConfigSettings.CommandExecutionTimeoutSeconds))
.Select(c => c.Value)
.FirstOrDefault();
var commandExecutionTimeout = SetConfigItem(
ApplicationParameters.ConfigSettings.CommandExecutionTimeoutSeconds,
configFileSettings,
ApplicationParameters.DefaultWaitForExitInSeconds.ToStringSafe(),
"Default timeout for command execution. '0' for infinite."
);

int.TryParse(commandExecutionTimeout, out commandExecutionTimeoutSeconds);
config.CommandExecutionTimeoutSeconds = commandExecutionTimeoutSeconds;
Expand Down Expand Up @@ -511,6 +522,7 @@ private static void SetEnvironmentOptions(ChocolateyConfiguration config)
private static void SetLicensedOptions(ChocolateyConfiguration config, ChocolateyLicense license, ConfigFileSettings configFileSettings)
{
config.Information.IsLicensedVersion = license.IsLicensedVersion();
config.Information.IsLicensedAssemblyLoaded = license.AssemblyLoaded;
config.Information.LicenseType = license.LicenseType.DescriptionOrValue();

if (license.AssemblyLoaded)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -527,6 +527,7 @@ public sealed class InformationCommandConfiguration
public bool IsUserRemote { get; set; }
public bool IsProcessElevated { get; set; }
public bool IsLicensedVersion { get; set; }
public bool IsLicensedAssemblyLoaded { get; set; }
public string LicenseType { get; set; }
public string CurrentDirectory { get; set; }
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright © 2017 - 2021 Chocolatey Software, Inc
// Copyright © 2017 - 2021 Chocolatey Software, Inc
// Copyright © 2011 - 2017 RealDimensions Software, LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
Expand Down Expand Up @@ -134,10 +134,13 @@ public static void SetEnvironmentVariables(ChocolateyConfiguration config)

private static void SetLicensedEnvironment(ChocolateyConfiguration config)
{
if (!config.Information.IsLicensedVersion) return;

Environment.SetEnvironmentVariable("ChocolateyLicenseType", config.Information.LicenseType);

if (!(config.Information.IsLicensedVersion && config.Information.IsLicensedAssemblyLoaded))
{
return;
}

var licenseAssembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.GetName().Name.IsEqualTo("chocolatey.licensed"));

if (licenseAssembly != null)
Expand Down
2 changes: 1 addition & 1 deletion src/chocolatey/infrastructure.app/nuget/NugetCommon.cs
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ public static IEnumerable<SourceRepository> GetRemoteRepositories(ChocolateyConf
var updatedSources = new StringBuilder();
foreach (var sourceValue in sources.OrEmpty())
{
var source = sourceValue;
var source = sourceValue;
var bypassProxy = false;

var sourceClientCertificates = new List<X509Certificate>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -446,8 +446,11 @@ public void PreparePowerShellEnvironment(IPackageSearchMetadata package, Chocola
Environment.SetEnvironmentVariable("packageTitle", package.Title);
Environment.SetEnvironmentVariable("chocolateyPackageVersion", package.Identity.Version.ToNormalizedStringChecked());
Environment.SetEnvironmentVariable("packageVersion", package.Identity.Version.ToNormalizedStringChecked());
// We use ToStringSafe on purpose here. There is a need for the version
// the package specified, not the normalized version we want users to use.
Environment.SetEnvironmentVariable(StringResources.EnvironmentVariables.ChocolateyPackageNuspecVersion, package.Identity.Version.ToStringSafe());
Environment.SetEnvironmentVariable(StringResources.EnvironmentVariables.PackageNuspecVersion, package.Identity.Version.ToStringSafe());
Environment.SetEnvironmentVariable("chocolateyPackageVersionPrerelease", package.Identity.Version.Release.ToStringSafe());
Environment.SetEnvironmentVariable("chocolateyPackageVersionPackageRelease", package.Identity.Version.Version.ToStringSafe());

Environment.SetEnvironmentVariable("chocolateyPackageFolder", packageDirectory);
Environment.SetEnvironmentVariable("packageFolder", packageDirectory);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ Chocolatey makes a number of environment variables available (You can access any
* ChocolateyInstall - Top level folder where Chocolatey is installed
* ChocolateyPackageName - The name of the package, equivalent to the `<id />` field in the nuspec
* ChocolateyPackageTitle - The title of the package, equivalent to the `<title />` field in the nuspec
* ChocolateyPackageVersion - The version of the package, equivalent to the `<version />` field in the nuspec
* ChocolateyPackageVersion - The normalized version of the package, equivalent to a normalized edition of the `<version />` field in the nuspec
* ChocolateyPackageFolder - The top level location of the package folder - the folder where Chocolatey has downloaded and extracted the NuGet package, typically `C:\ProgramData\chocolatey\lib\packageName`.
#### Advanced Environment Variables
Expand Down
33 changes: 33 additions & 0 deletions tests/chocolatey-tests/commands/choco-install.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -1863,6 +1863,39 @@ To install a local, or remote file, you may use:
}
}

# Tagged as Internal as this package needs to be packaged by an older version of Chocolatey CLI to have the nuspec version
# not be normalized.
Context 'Installing non-normalized package outputting all environment variables' -Tag Internal {
BeforeAll {
Restore-ChocolateyInstallSnapshot

$Output = Invoke-Choco install test-environment --version 0.9 --confirm
}

It 'Exits with Success (0)' {
$Output.ExitCode | Should -Be 0 -Because $Output.String
}

It 'Outputs <Name> as <Value>' -ForEach @(@{
Name = 'chocolateyPackageVersion'
Value= '0.9.0'
}
@{
Name = 'packageVersion'
Value= '0.9.0'
}
@{
Name = 'chocolateyPackageNuspecVersion'
Value= '0.9'
}
@{
Name = 'packageNuspecVersion'
Value= '0.9'
}) {
$Output.Lines | Should -Contain "$Name=$Value"
}
}

# This needs to be the last test in this block, to ensure NuGet configurations aren't being created.
# Any tests after this block are expected to generate the configuration as they're explicitly using the NuGet CLI
Test-NuGetPaths
Expand Down
Loading

0 comments on commit 0a7efcf

Please sign in to comment.