-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPSAliasFinder.psm1
More file actions
364 lines (294 loc) · 10.4 KB
/
PSAliasFinder.psm1
File metadata and controls
364 lines (294 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
# ============================================
# PSAliasFinder - PowerShell Alias Discovery Module
# Based on the oh-my-zsh alias-finder plugin
# ============================================
# ----------------------------
# Function: CountActualPipes
# ----------------------------
function CountActualPipes {
<#
.SYNOPSIS
Counts the actual number of pipes in a PowerShell command.
.DESCRIPTION
Uses the PowerShell Abstract Syntax Tree (AST) to accurately count
pipes in a command, ignoring pipes within strings.
.PARAMETER Command
The command string to analyze.
.EXAMPLE
CountActualPipes "Get-Process | Where-Object Name -eq 'pwsh'"
Returns: 1
#>
[CmdletBinding()]
param([string]$Command)
try {
$ast = [System.Management.Automation.Language.Parser]::ParseInput($Command, [ref]$null, [ref]$null)
$pipelineAsts = $ast.FindAll({
param($node)
$node -is [System.Management.Automation.Language.PipelineAst]
}, $true)
if ($pipelineAsts.Count -gt 0) {
return ($pipelineAsts[0].PipelineElements.Count - 1)
}
return 0
}
catch {
return 0
}
}
# ----------------------------
# Function: ShouldShowAliasSuggestion
# ----------------------------
function ShouldShowAliasSuggestion {
<#
.SYNOPSIS
Determines if an alias suggestion should be shown.
.DESCRIPTION
Applies intelligent filtering to avoid showing suggestions for:
- Short commands (less than 8 characters)
- Complex commands (multiple pipes or many arguments)
- Aliases that don't save enough characters
.PARAMETER OriginalCommand
The original command entered by the user.
.PARAMETER Alias
The alias object to evaluate.
.EXAMPLE
ShouldShowAliasSuggestion "Get-Process" $aliasObject
#>
[CmdletBinding()]
param(
[string]$OriginalCommand,
[PSCustomObject]$Alias
)
$firstCommand = ($OriginalCommand -split '\|')[0].Trim()
# Selective criteria
if ($firstCommand.Length -lt 8) { return $false }
$pipeCount = CountActualPipes $OriginalCommand
$argumentCount = ($OriginalCommand -split '\s+').Count
if ($pipeCount -gt 1 -or $argumentCount -gt 10) { return $false }
$absoluteSaving = $firstCommand.Length - $Alias.Name.Length
if ($absoluteSaving -lt 4) { return $false }
return $true
}
# ----------------------------
# Function: Find-Alias
# ----------------------------
function Find-Alias {
<#
.SYNOPSIS
Finds aliases for a given PowerShell command.
.DESCRIPTION
Searches for existing aliases that match the specified command.
Supports multiple search modes and filtering options.
.PARAMETER Command
The command to search aliases for. Accepts multiple words.
.PARAMETER Exact
Find only exact matches for the command.
.PARAMETER Longer
Include aliases that are longer than the original command.
.PARAMETER Cheaper
Only show aliases that are shorter than the original command.
.PARAMETER Quiet
Suppress console output, only return results.
.PARAMETER Force
Bypass intelligent filtering and show all matches.
.EXAMPLE
Find-Alias Get-ChildItem
Finds aliases for Get-ChildItem (e.g., gci, ls, dir)
.EXAMPLE
Find-Alias "Get-Process" -Exact
Finds only exact matches for Get-Process
.EXAMPLE
Find-Alias "docker ps" -Force
Shows all aliases for docker ps, bypassing filters
#>
[CmdletBinding()]
param (
[Parameter(Mandatory=$true, ValueFromRemainingArguments=$true)]
[string[]]$Command,
[switch]$Exact,
[switch]$Longer,
[switch]$Cheaper,
[switch]$Quiet,
[switch]$Force
)
$fullCommand = ($Command -join ' ').Trim()
if ([string]::IsNullOrWhiteSpace($fullCommand)) { return @() }
$foundAliases = @()
$currentCmd = $fullCommand
while (-not [string]::IsNullOrWhiteSpace($currentCmd)) {
# Search for matching aliases
$matchingAliases = Get-Alias | Where-Object {
if ($Exact) {
$_.Definition -eq $currentCmd
} elseif ($Longer) {
$_.Definition -like "*$currentCmd*"
} else {
$_.Definition -eq $currentCmd -or
($currentCmd.StartsWith($_.Definition) -and
$currentCmd.Length -gt $_.Definition.Length -and
$currentCmd[$_.Definition.Length] -match '\s')
}
} | ForEach-Object {
[PSCustomObject]@{
Name = $_.Name
Definition = $_.Definition
}
}
if ($Cheaper) {
$matchingAliases = $matchingAliases | Where-Object {
$_.Name.Length -lt $fullCommand.Length
}
}
foreach ($alias in $matchingAliases) {
if ($foundAliases.Name -notcontains $alias.Name) {
$foundAliases += $alias
}
}
if ($Exact -or $Longer) { break }
$words = $currentCmd.Trim() -split '\s+'
if ($words.Count -le 1) { break }
$currentCmd = ($words[0..($words.Count-2)] -join ' ').Trim()
}
# Apply selective criteria
if (-not $Force) {
$foundAliases = $foundAliases | Where-Object { ShouldShowAliasSuggestion $fullCommand $_ }
}
# Display results
if (-not $Quiet -and $foundAliases.Count -gt 0) {
$foundAliases | ForEach-Object {
Write-Host "$($_.Name) -> $($_.Definition)" -ForegroundColor Green
}
}
return $foundAliases
}
# ----------------------------
# Function: Test-CommandAlias
# ----------------------------
function Test-CommandAlias {
<#
.SYNOPSIS
Tests if a command has an available alias and suggests it.
.DESCRIPTION
Internal function used by the Enter key hook to automatically
suggest aliases when commands are entered.
.PARAMETER Command
The command to test for available aliases.
.EXAMPLE
Test-CommandAlias "Get-ChildItem"
#>
[CmdletBinding()]
param([Parameter(Mandatory=$true)][string]$Command)
try {
$cleanCommand = $Command.Trim() -replace '\s+', ' '
if ([string]::IsNullOrWhiteSpace($cleanCommand)) { return }
$firstToken = ($cleanCommand -split '\s+')[0]
# Count real pipes (not inside strings)
$pipeCount = CountActualPipes $cleanCommand
# Criteria: long command, max 1 pipe, not already an alias
if ($firstToken.Length -ge 8 -and
$pipeCount -le 1 -and
-not (Get-Alias -Name $firstToken -ErrorAction SilentlyContinue)) {
$aliasMatches = Get-Alias | Where-Object { $_.Definition -eq $firstToken }
if ($aliasMatches -and ($firstToken.Length - $aliasMatches[0].Name.Length) -ge 4) {
Write-Host "`nFound existing alias for `"$firstToken`". You should use: " -NoNewline -ForegroundColor Yellow
$aliasNames = $aliasMatches | ForEach-Object { "`"$($_.Name)`"" }
Write-Host ($aliasNames -join ", ") -ForegroundColor Magenta
}
}
}
catch {
Write-Debug "Error in Test-CommandAlias: $_"
}
}
# ----------------------------
# Function: Set-AliasFinderHook
# ----------------------------
function Set-AliasFinderHook {
<#
.SYNOPSIS
Enables or disables the automatic alias detection hook.
.DESCRIPTION
Configures PSReadLine to automatically detect and suggest aliases
when the Enter key is pressed.
.PARAMETER Enable
Explicitly enable the hook and show confirmation message.
.PARAMETER Disable
Disable the hook and restore default Enter key behavior.
.EXAMPLE
Set-AliasFinderHook -Enable
Enables automatic alias detection
.EXAMPLE
Set-AliasFinderHook -Disable
Disables automatic alias detection
#>
[CmdletBinding()]
param(
[switch]$Enable,
[switch]$Disable
)
if ($Disable) {
Set-PSReadLineKeyHandler -Key Enter -Function AcceptLine
Write-Host "Alias finder disabled." -ForegroundColor Yellow
return
}
if (Get-Module PSReadLine -ErrorAction SilentlyContinue) {
Set-PSReadLineKeyHandler -Key Enter -BriefDescription "AliasFinder" -ScriptBlock {
$line = $null
$cursor = $null
[Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor)
if (-not [string]::IsNullOrWhiteSpace($line)) {
Test-CommandAlias -Command $line
}
[Microsoft.PowerShell.PSConsoleReadLine]::AcceptLine()
}
if ($Enable) {
Write-Host "Alias finder enabled." -ForegroundColor Green
}
} else {
Write-Warning "PSReadLine module not found. Alias finder hook requires PSReadLine."
}
}
# ----------------------------
# Function: Set-AliasFinderConfig
# ----------------------------
function Set-AliasFinderConfig {
<#
.SYNOPSIS
Configures the PSAliasFinder module behavior.
.DESCRIPTION
Sets global configuration for automatic alias detection.
.PARAMETER AutoLoad
Enable automatic alias detection on module load.
.EXAMPLE
Set-AliasFinderConfig -AutoLoad
Enables automatic alias detection
.EXAMPLE
Set-AliasFinderConfig
Disables automatic alias detection
#>
[CmdletBinding()]
param([switch]$AutoLoad)
$global:PSAliasFinderConfig = @{ AutoLoad = $AutoLoad.IsPresent }
if ($AutoLoad) {
Set-AliasFinderHook -Enable
} else {
Set-AliasFinderHook -Disable
}
}
# ----------------------------
# Module Initialization
# ----------------------------
# Create aliases for Find-Alias function
Set-Alias -Name af -Value Find-Alias -ErrorAction SilentlyContinue
Set-Alias -Name alias-finder -Value Find-Alias -ErrorAction SilentlyContinue
# Initialize configuration
if (-not $global:PSAliasFinderConfig) {
$global:PSAliasFinderConfig = @{ AutoLoad = $false }
}
# Auto-enable hook if configured
if ($global:PSAliasFinderConfig.AutoLoad -and (Get-Module PSReadLine -ErrorAction SilentlyContinue)) {
Set-AliasFinderHook
}
# Export module members
Export-ModuleMember -Function Find-Alias, Test-CommandAlias, Set-AliasFinderHook, Set-AliasFinderConfig
Export-ModuleMember -Alias af, alias-finder