Skip to content

Commit

Permalink
Merge branch 'stable'
Browse files Browse the repository at this point in the history
* stable:
  (GH-412)(GH-664) PoSh tab completion / refreshenv
  (GH-295) Do not replace PSModulePath
  (GH-664) RefreshEnv Should also work in PowerShell
  (GH-412) update parameter name for skip scripts
  (GH-663) Search just by id
  (doc) update how to pass args
  • Loading branch information
ferventcoder committed Mar 20, 2016
2 parents 63225b7 + b480d6b commit 231cd93
Show file tree
Hide file tree
Showing 12 changed files with 197 additions and 13 deletions.
6 changes: 6 additions & 0 deletions src/chocolatey.resources/chocolatey.resources.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,12 @@
<ItemGroup>
<EmbeddedResource Include="tools\die.zip" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="helpers\chocolateyProfile.psm1" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="helpers\ChocolateyTabExpansion.ps1" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
Expand Down
129 changes: 129 additions & 0 deletions src/chocolatey.resources/helpers/ChocolateyTabExpansion.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
$Global:ChocolateyTabSettings = New-Object PSObject -Property @{
AllCommands = $false
}

function script:chocoCmdOperations($commands, $command, $filter) {
$commands.$command -split ' ' |
where { $_ -like "$filter*" }
}

$script:someCommands = @('-?', '-h', '--help','search','list','install','pin','outdated','upgrade','uninstall','pack','push','new','source','config','feature','apikey')

$allcommands = " -? --help --debug --verbose --accept-license -y --confirm --force --noop -whatif --limit-output --execution-timeout= --cache-location='' --fail-on-error-output --use-system-powershell"

$proInstallUpgradeOptions = " --skip-download-cache --use-download-cache --skip-virus-check --virus-check --virus-positives-minimum="

$subcommands = @{
search = '--source= --lo --local-only--pre --prerelease --include-programs --all-versions --user= --password= --page= --page-size= --exact --id-only' + $allcommands
list = '--source= --lo --local-only--pre --prerelease --include-programs --all-versions --user= --password= --page= --page-size= --exact --id-only' + $allcommands
install = "--source='' --version= --pre --prerelease --forcex86 --install-arguments='' --override-arguments --not-silent --params='' --package-parameters='' --allow-downgrade --allow-multiple-versions --ignore-dependencies --force-dependencies --skip-automation-scripts --user= --password= --ignore-checksums" + $allcommands + $proInstallUpgradeOptions
upgrade = "--source='' --version= --pre --prerelease --forcex86 --install-arguments='' --override-arguments --not-silent --params='' --package-parameters='' --allow-downgrade --allow-multiple-versions --ignore-dependencies --skip-automation-scripts --fail-on-unfound --fail-on-not-installed --user= --password= --ignore-checksums --except=''" + $allcommands + $proInstallUpgradeOptions
uninstall = "--source='' --version= --all-versions --uninstall-arguments='' --override-arguments --not-silent --params='' --package-parameters='' --force-dependencies --remove-dependencies --skip-automation-scripts" + $allcommands
pin = "list add remove --name= --version=" + $allcommands
outdated = "--source='' --user= --password=" + $allcommands
pack = "<PathtoNuspec> --version=" + $allcommands
push = "<PathToNupkg> --source='' --api-key= --timeout=" + $allcommands
new = "<name> --automaticpackage --template-name= --name= --version= --maintainer='' packageversion= maintainername='' maintainerrepo='' installertype= url='' url64='' silentargs=''" + $allcommands
source = "list add remove disable enable --name= --source='' --user= --password= --priority=" + $allcommands
config = 'list get set unset --name= --value=' + $allcommands
feature = 'list disable enable --name=' + $allcommands
apikey = "--source='' --api-key=" + $allcommands
}

try {
# if license exists
# add in pro/biz switches
}
catch {
}

function script:chocoCommands($filter) {
$cmdList = @()
if (-not $global:ChocolateyTabSettings.AllCommands) {
$cmdList += $someCommands -like "$filter*"
} else {
$cmdList += choco -h |
where { $_ -match '^ \S.*' } |
foreach { $_.Split(' ', [StringSplitOptions]::RemoveEmptyEntries) } |
where { $_ -like "$filter*" }
}

$cmdList | sort
}

function script:chocoLocalPackages($filter) {
@('all|') + (choco list -lo -r) | where { $_.Split('|')[0] -like "$filter*" } | %{ $_.Split('|')[0] }
}

function script:chocoRemotePackages($filter) {
@('packages.config|') + (choco search $filter --page=0 --page-size=5 -r --id-only) | where { $_.Split('|')[0] -like "$filter*" } | %{ $_.Split('|')[0] }
}

function Get-AliasPattern($exe) {
$aliases = @($exe) + @(Get-Alias | where { $_.Definition -eq $exe } | select -Exp Name)

"($($aliases -join '|'))"
}

function ChocolateyTabExpansion($lastBlock) {
switch -regex ($lastBlock -replace "^$(Get-AliasPattern choco) ","") {

# Handles install package names
"^(install)\s+(?<package>[^-\s]*)$" {
chocoRemotePackages $matches['package']
}

# Handles upgrade / uninstall package names
"^(upgrade|uninstall)\s+(?<package>[^-\s]*)$" {
chocoLocalPackages $matches['package']
}

# Handles more options after others
"^(?<cmd>$($subcommands.Keys -join '|'))(.*)\s+(?<op>\S*)$" {
chocoCmdOperations $subcommands $matches['cmd'] $matches['op']
}

# Handles choco <cmd> <op>
"^(?<cmd>$($subcommands.Keys -join '|'))\s+(?<op>\S*)$" {
chocoCmdOperations $subcommands $matches['cmd'] $matches['op']
}

# Handles choco <cmd>
"^(?<cmd>\S*)$" {
chocoCommands $matches['cmd']
}
}
}

$PowerTab_RegisterTabExpansion = if (Get-Module -Name powertab) { Get-Command Register-TabExpansion -Module powertab -ErrorAction SilentlyContinue }
if ($PowerTab_RegisterTabExpansion)
{
& $PowerTab_RegisterTabExpansion "choco" -Type Command {
param($Context, [ref]$TabExpansionHasOutput, [ref]$QuoteSpaces) # 1:

$line = $Context.Line
$lastBlock = [regex]::Split($line, '[|;]')[-1].TrimStart()
$TabExpansionHasOutput.Value = $true
ChocolateyTabExpansion $lastBlock
}

return
}

if (Test-Path Function:\TabExpansion) {
Rename-Item Function:\TabExpansion TabExpansionBackup
}

function TabExpansion($line, $lastWord) {
$lastBlock = [regex]::Split($line, '[|;]')[-1].TrimStart()

switch -regex ($lastBlock) {
# Execute Chocolatey tab completion for all choco-related commands
"^$(Get-AliasPattern choco) (.*)" { ChocolateyTabExpansion $lastBlock }
"^$(Get-AliasPattern choco.exe) (.*)" { ChocolateyTabExpansion $lastBlock }
"^$(Get-AliasPattern chocolatey) (.*)" { ChocolateyTabExpansion $lastBlock }

# Fall back on existing tab expansion
default { if (Test-Path Function:\TabExpansionBackup) { TabExpansionBackup $line $lastWord } }
}
}
9 changes: 9 additions & 0 deletions src/chocolatey.resources/helpers/chocolateyProfile.psm1
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# ensure module loading preference is on
$PSModuleAutoLoadingPreference = "All";

$thisDirectory = (Split-Path -parent $MyInvocation.MyCommand.Definition);
. $thisDirectory\functions\Get-EnvironmentVariable.ps1
. $thisDirectory\functions\Get-EnvironmentVariableNames.ps1
. $thisDirectory\functions\Update-SessionEnvironment.ps1
. $thisDirectory\ChocolateyTabExpansion.ps1
Export-ModuleMember -Alias refreshenv -Function 'Update-SessionEnvironment', 'TabExpansion'
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,23 @@ powershell session with all environment settings possibly performed by
chocolatey package installs.
#>
Write-Debug "Running 'Update-SessionEnvironment' - Updating the environment variables for the session."
Write-Debug "Running 'Update-SessionEnvironment'"
$refreshEnv = $false
$invocation = $MyInvocation
if ($invocation.InvocationName -eq 'refreshenv') {
$refreshEnv = $true
}

if ($refreshEnv) {
Write-Output "Refreshing environment variables from the registry..."
} else {
Write-Verbose "Refreshing environment variables from the registry."
}

$psModulePath = $env:PSModulePath

#ordering is important here, $user comes after so we can override $machine
'Machine', 'User' |
'Process', 'Machine', 'User' |
% {
$scope = $_
Get-EnvironmentVariableNames -Scope $scope |
Expand All @@ -51,4 +64,13 @@ chocolatey package installs.
} |
Select -Unique
$Env:PATH = $paths -join ';'

# PSModulePath is almost always updated by process, so we want to preserve it.
$env:PSModulePath = $psModulePath

if ($refreshEnv) {
Write-Output "Finished"
}
}

Set-Alias refreshenv Update-SessionEnvironment
Expand Down
23 changes: 16 additions & 7 deletions src/chocolatey/infrastructure.app/builders/ConfigurationBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,8 @@ each command.
"chocolatey".Log().Info(@"
You can pass options and switches in the following ways:
* Unless stated otherwise, an option/switch should only be passed one
time. Otherwise you may find weird/non-supported behavior.
* `-`, `/`, or `--` (one character switches should not use `--`)
* **Option Bundling / Bundled Options**: One character switches can be
bundled. e.g. `-d` (debug), `-f` (force), `-v` (verbose), and `-y`
Expand All @@ -369,13 +371,20 @@ each command.
the local options are parsed.
* **Use Equals**: You can also include or not include an equals sign
`=` between options and values.
* **Quote Values**: When you need to quote things, such as when using
spaces, please use apostrophes (`'value'`). In cmd.exe you may be
able to use just double quotes (`""value""`) but in powershell.exe
you may need to either escape the quotes with backticks
(`` `""value`"" ``) or use a combination of double quotes and
apostrophes (`""'value'""`). This is due to the hand off to
PowerShell - it seems to strip off the outer set of quotes.
* **Quote Values**: When you need to quote an entire argument, such as
when using spaces, please use a combination of double quotes and
apostrophes (`""'value'""`). In cmd.exe you can just use double quotes
(`""value""`) but in powershell.exe you should use backticks
(`` `""value`"" ``) or apostrophes (`'value'`). Using the combination
allows for both shells to work without issue, except for when the next
section applies.
* **Pass quotes in arguments**: When you need to pass quoted values to
to something like a native installer, you are in for a world of fun. In
cmd.exe you must pass it like this: `-ia ""/yo=""""Spaces spaces""""""`. In
PowerShell.exe, you must pass it like this: `-ia '/yo=""""Spaces spaces""""'`.
No other combination will work. In PowerShell.exe if you are on version
v3+, you can try `--%` before `-ia` to just pass the args through as is,
which means it should not require any special workarounds.
* Options and switches apply to all items passed, so if you are
installing multiple packages, and you use `--version=1.0.0`, choco
is going to look for and try to install version 1.0.0 of every
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyCon
.Add("x|forcedependencies|force-dependencies",
"ForceDependencies - Force dependencies to be reinstalled when force installing package(s). Must be used in conjunction with --force. Defaults to false.",
option => configuration.ForceDependencies = option != null)
.Add("n|skippowershell|skip-powershell",
.Add("n|skippowershell|skip-powershell|skipscripts|skip-scripts|skip-automation-scripts",
"Skip Powershell - Do not run chocolateyInstall.ps1. Defaults to false.",
option => configuration.SkipPackageInstallProvider = option != null)
.Add("u=|user=",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,9 @@ public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyCon
.Add("e|exact",
"Exact - Only return packages with this exact name.",
option => configuration.ListCommand.Exact = option != null)
.Add("id|idonly|id-only",
"ByIdOnly - Only return packages with the filter being part of the id.",
option => configuration.ListCommand.ByIdOnly = option != null)
;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyCon
.Add("x|forcedependencies|force-dependencies|removedependencies|remove-dependencies",
"RemoveDependencies - Uninstall dependencies when uninstalling package(s). Defaults to false.",
option => configuration.ForceDependencies = option != null)
.Add("n|skippowershell|skip-powershell",
.Add("n|skippowershell|skip-powershell|skipscripts|skip-scripts|skip-automation-scripts",
"Skip Powershell - Do not run chocolateyUninstall.ps1. Defaults to false.",
option => configuration.SkipPackageInstallProvider = option != null)
;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyCon
.Add("i|ignoredependencies|ignore-dependencies",
"IgnoreDependencies - Ignore dependencies when upgrading package(s). Defaults to false.",
option => configuration.IgnoreDependencies = option != null)
.Add("n|skippowershell|skip-powershell",
.Add("n|skippowershell|skip-powershell|skipscripts|skip-scripts|skip-automation-scripts",
"Skip Powershell - Do not run chocolateyInstall.ps1. Defaults to false.",
option => configuration.SkipPackageInstallProvider = option != null)
.Add("failonunfound|fail-on-unfound",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,7 @@ public ListCommandConfiguration()
public int? Page { get; set; }
public int PageSize { get; set; }
public bool Exact { get; set; }
public bool ByIdOnly { get; set; }
}

[Serializable]
Expand Down
5 changes: 5 additions & 0 deletions src/chocolatey/infrastructure.app/nuget/NugetList.cs
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,11 @@ private static IQueryable<IPackage> execute_package_search(ChocolateyConfigurati
results = results.Where(p => p.Id == configuration.Input);
}

if (configuration.ListCommand.ByIdOnly)
{
results = results.Where(p => p.Id.Contains(configuration.Input));
}

return results.OrderBy(p => p.Id);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -979,7 +979,7 @@ private void get_environment_after(ChocolateyConfiguration config, IEnumerable<G
if (hasEnvironmentChanges || hasEnvironmentRemovals)
{
this.Log().Info(ChocolateyLoggers.Important,@"Environment Vars (like PATH) have changed. Close/reopen your shell to
see the changes (or in cmd.exe just type `refreshenv`).");
see the changes (or in powershell/cmd.exe just type `refreshenv`).");

if (!config.Features.LogEnvironmentValues)
{
Expand Down

0 comments on commit 231cd93

Please sign in to comment.