|
1 | 1 | @('npm', 'npm.cmd') | ForEach-Object {
|
2 |
| - Register-ArgumentCompleter -Native -CommandName $_ -ScriptBlock { |
| 2 | + Register-ArgumentCompleter -Native -CommandName $_ -ScriptBlock { |
3 | 3 | param($wordToComplete, $commandAst, $cursorPosition)
|
4 | 4 |
|
| 5 | + # Search for a file "package.json" in the current directory or parent directories |
| 6 | + function Get-PackageJsonPath { |
| 7 | + [string]$packageJsonPath=$pwd; |
| 8 | + while ($packageJsonPath.Length -gt 0 -and -not (Test-Path "$packageJsonPath\package.json")) { |
| 9 | + # No package.json found. Look in parent directory next |
| 10 | + $packageJsonPath=Split-Path $packageJsonPath -Parent |
| 11 | + } |
| 12 | + |
| 13 | + return $packageJsonPath |
| 14 | + } |
| 15 | + |
| 16 | + function Get-PackageJsonScripts { |
| 17 | + param ( |
| 18 | + [Parameter(Mandatory=$true, ValueFromPipeline=$true)] |
| 19 | + [string] $packageJsonPath, |
| 20 | + [string] $scriptFilter |
| 21 | + ) |
| 22 | + if ($packageJsonPath.Length -gt 0) { |
| 23 | + $packageJson="$packageJsonPath/package.json" |
| 24 | + $packageJsonContent = Get-Content $packageJson | ConvertFrom-Json |
| 25 | + # Do we have a "script" section? |
| 26 | + if ($packageJsonContent.scripts -ne $null) { |
| 27 | + $allScripts=$packageJsonContent.scripts | Get-Member -MemberType NoteProperty | where Name -like "$scriptFilter" | select -ExpandProperty Name |
| 28 | + $result=$allScripts | ForEach-Object { |
| 29 | + # return the script name and the script text. The script text is passed as tooltip later. |
| 30 | + [tuple]::Create($_, $packageJsonContent.scripts.$_) |
| 31 | + } |
| 32 | + |
| 33 | + return $result |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + return @(); |
| 38 | + } |
| 39 | + |
| 40 | + if ($commandAst.ToString() -match "npm(.cmd)?\s+run(-script)?\s*") { |
| 41 | + $allScripts = Get-PackageJsonPath | Get-PackageJsonScripts -scriptFilter "$wordToComplete*" |
| 42 | + $result=$allScripts | ForEach-Object { |
| 43 | + # item1 is the script name, item2 is the script text (passed as tooltip) |
| 44 | + [System.Management.Automation.CompletionResult]::new($_.item1, $_.item1, 'ParameterValue', $_.item2) |
| 45 | + } |
| 46 | + |
| 47 | + return $result; |
| 48 | + } |
| 49 | + |
5 | 50 | . $PSScriptRoot\commands.ps1
|
6 | 51 | $cmds |
|
7 | 52 | Where-Object { $_ -like "$wordToComplete*" } |
|
|
0 commit comments