-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathPoShWarp.psm1
657 lines (498 loc) · 17.6 KB
/
PoShWarp.psm1
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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
##
## PoShWarp: a PowerShell port of the `wd` zshell script.
## URL: https://github.com/DuFace/PoShWarp
## Copyright (c) 2014 Kier Dugan
##
## Utility functions -----------------------------------------------------------
function GetWarpMapFilename() {
if (-not ($env:POSHWARP_MAPFILE -eq $null)) {
return $env:POSHWARP_MAPFILE
} else {
return "$((Get-Item $profile).Directory.FullName)\WarpMap.xml"
}
}
function WarpMapExists() {
return Test-Path (GetWarpMapFilename) -PathType Leaf
}
function OpenWarpMap() {
$xml = New-Object XML
if (WarpMapExists) {
$fn = GetWarpMapFilename
$xml.Load($fn)
} else {
# Initialise the empty document
$decl = $xml.CreateXmlDeclaration("1.0", $null, $null)
$root = $xml.CreateElement("WarpMap")
$xml.InsertBefore($decl, $xml.DocumentElement) | Out-Null
$xml.InsertBefore($root, $xml.DocumentElement) | Out-Null
}
return $xml
}
function CloseWarpMap($xml) {
$fn = GetWarpMapFilename
$xml.Save($fn)
}
function FindWarpLocations($xml, $name) {
return $xml.WarpMap.Location | where { $_.Name -eq $name }
}
function ConvertElementsToObjects($elems) {
if ($elems) {
return $elems | foreach {
$obj = New-Object System.Object
$obj | Add-Member -Type NoteProperty -Name "Name" -Value $_.Name
$obj | Add-Member -Type NoteProperty -Name "Path" -Value $_.Path
$obj
}
}
}
function SelectFirstNonNull() {
return $args | where { $_ } | Select-Object -First 1
}
## Commands --------------------------------------------------------------------
<#
.SYNOPSIS
Searches the warp-map for the specified entry and sets the location accordingly.
.DESCRIPTION
Select-WarpLocation will search the active warp-map file for the entry with the
given name and attempt to `Set-Location` to the corresponding path. An error
will be raised if no entry with the given name is found, of if the named entry
exists but points to a non-existent directory.
.PARAMETER WarpName
Entry name to search for in the warp-map.
.PARAMETER PassThru
Return the new directory object after changing into it.
.LINK
https://github.com/DuFace/PoShWarp#warpmap
https://github.com/DuFace/PoShWarp#Select-WarpLocation
#>
function Select-WarpLocation {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true)]
[String]
$WarpName,
[Parameter(Mandatory=$false)]
[Switch]
$PassThru = $false
)
process {
# Open the XML warp-map
Write-Verbose "Opening warp-map file: $(GetWarpMapFilename)"
$xml = OpenWarpMap
# Find all warp entries with the given name
$entry = FindWarpLocations $xml $WarpName | Select-Object -First 1
if (-not $entry) {
Write-Error "No entry for $WarpName exists in warp-map!"
return
}
# Verify the directory exists
$name, $path = $entry.Name, $entry.Path
if (-not (Test-Path -Path $path -PathType Container)) {
Write-Error ("Entry '$name' points to directory '$path' which " +
"does not exist!")
return
}
# Attempt to go to the warp location
return Set-Location -Path $path -PassThru:$PassThru
}
}
<#
.SYNOPSIS
Creates a new entry in the current warp-map.
.DESCRIPTION
A new entry will be added to the warp-map currently active using either the
current or specific directory path. If the does not exist, no entry will be
created. A warp-map XML file with be created if one does not already exist.
.PARAMETER WarpName
Name for the new warp-map entry.
.PARAMETER Path
Path to assign to WarpName. Defaults to the current directory.
.LINK
https://github.com/DuFace/PoShWarp#warpmap
https://github.com/DuFace/PoShWarp#New-WarpLocation
#>
function New-WarpLocation {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, ValueFromPipeline=$false)]
[String]
$WarpName,
[Parameter(Mandatory=$false, ValueFromPipeline=$false)]
[String]
$Path = '.'
)
begin {
# Open the XML warp-map
Write-Verbose "Opening warp-map file: $(GetWarpMapFilename)"
$xml = OpenWarpMap
$warpMapElem = $xml.SelectSingleNode("WarpMap")
}
process {
# Target path *must* exist
if (-not (Test-Path -Path $Path -PathType Container)) {
Write-Error "Target path must exist."
return
}
# Expand the path
$Path = (Get-Item $Path).FullName
# Find the first reference to the wapr name so that this can be added
# before it, thereby overriding it.
$exstingEntry = $xml.WarpMap.Location |
where { $_.Name -eq $WarpName} | Select-Object -First 1
# Construct a new XML element to hold the mapping
$newElem = $xml.CreateElement("Location")
$newElem.SetAttribute("Name", $WarpName)
$newElem.SetAttribute("Path", $Path)
# If this warp name has not been used before, add the element to the end
# of the document
if (-not $exstingEntry) {
$dirElem = $warpMapElem.AppendChild($newElem)
} else {
# Prevent duplication
if (-not ($exstingEntry.Path -eq $Path)) {
$dirElem = $warpMapElem.InsertBefore($newElem, $exstingEntry)
}
}
return ConvertElementsToObjects $dirElem
}
end {
# Save the changes to the warp-map
Write-Verbose "Saving warp-map file: $(GetWarpMapFilename)"
CloseWarpMap $xml
}
}
<#
.SYNOPSIS
Removes the specified entry from the active warp-map.
.DESCRIPTION
Searches the active warp-map for the named entry and then removes it. The
current directory will be used as a search term if no name is given. All
entries that meet the criterion will be removed. An empty warp-map file will
not be created if one does not already exist.
.PARAMETER WarpName
Warp-map entry name to search for.
.LINK
https://github.com/DuFace/PoShWarp#Remove-WarpLocation
#>
function Remove-WarpLocation {
[CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="Low")]
param(
[Parameter(Mandatory=$false, ValueFromPipeline=$true)]
[String]
$WarpName
)
begin {
# Open the XML warp-map
Write-Verbose "Opening warp-map file: $(GetWarpMapFilename)"
$xml = OpenWarpMap
$warpMapElem = $xml.SelectSingleNode("WarpMap")
}
process {
# Find all elements to delete
if ($WarpName) {
$elemsToRemove = $warpMapElem.Location |
where { $_.Name -eq $WarpName }
} else {
$curPath = (Get-Location).Path
$elemsToRemove = $warpMapElem.Location |
where { $_.Path -eq $curPath }
}
# Bail if there's no work to do
if (-not $elemsToRemove) {
if ($WarpName) {
Write-Error "$WarpName does not exist in warp-map."
} else {
Write-Error "There is no entry for this directory in warp-map."
}
return
}
# Get confirmation from user
if ($elemsToRemove.Length) {
$prompt = "Remove $($elemsToRemove.Count) entries from warp-map."
} else {
$prompt = "Remove 1 entry from warp-map."
}
if ($PSCmdlet.ShouldProcess($prompt)) {
# Remove the elements from the WarpMap tag
foreach ($elem in $elemsToRemove) {
$warpMapElem.RemoveChild($elem) | Out-Null
}
# Save the changes to the warp-map
Write-Verbose "Saving warp-map file: $(GetWarpMapFilename)"
CloseWarpMap $xml
}
}
}
<#
.SYNOPSIS
Gets the entries from the warp-map, optionally filtering by name or path.
.DESCRIPTION
Get-WarpLocation will return all the entries from the warp-map that meet the
given search criteria. Zero or more entries will be returned. Both a warp-name
and a path may be specified, and both must match to return any results. No
error will be raised if the query results in no matches.
.PARAMETER WarpName
Name to search for in the warp-map.
.PARAMETER Path
Path to search for in the warp-map.
.LINK
https://github.com/DuFace/PoShWarp#Get-WarpLocation
#>
function Get-WarpLocation {
[CmdletBinding()]
param(
[Parameter(Mandatory=$false)]
[String]
$WarpName,
[Parameter(Mandatory=$false)]
[String]
$Path
)
process {
# Actually check the warp-map even exists first
if (WarpMapExists) {
# Open the warp-map
Write-Verbose "Opening warp-map file: $(GetWarpMapFilename)"
$xml = OpenWarpMap
# Build the warp name filter
if ($WarpName) {
$nameFilter = { $_.Name -eq $WarpName }
} else {
$nameFilter = { $true }
}
# Build the path filter
if ($Path) {
# Expand out to full path if, and only if, it exists
if (Test-Path -Path $Path -PathType Container) {
$Path = (Get-Item $Path).FullName
Write-Verbose "Path expanded to $Path."
}
# Make the actual filter block
$pathFilter = { $_.Path -eq $Path }
} else {
$pathFilter = { $true }
}
# Apply the filters to the Location elements
$entries = $xml.WarpMap.Location | where {
(&$nameFilter) -and (&$pathFilter)
}
# Return all the locations in the map
return ConvertElementsToObjects $entries
}
}
}
<#
.SYNOPSIS
Removes all invalid directory references from the warp-map.
.DESCRIPTION
Over time, a living warp-map can retain entries pointing to directories that no
longer exist. Repair-WarpMap checks every entry in the warp-map and removes any
that reference a directory that has been deleted. Multiple entries pointing to
the same directory will remain unchanged provided that they point to a directory
that still exists.
.LINK
https://github.com/DuFace/PoShWarp#Repair-WarpMap
#>
function Repair-WarpMap {
[CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="Low")]
param()
process {
# Open the warp-map
Write-Verbose "Opening warp-map file: $(GetWarpMapFilename)"
$xml = OpenWarpMap
$warpMapElem = $xml.SelectSingleNode("WarpMap")
# Find all entries that point to missing directories
if ($warpMapElem.Location) {
$danglers = $warpMapElem.Location | where {
-not (Test-Path -Path $_.Path -PathType Container)
}
}
# Bail early if there's nothing to remove
if (-not $danglers) {
Write-Verbose "No bad entries in warp-map."
} else {
# Build the message to confirm with user
if ($danglers.Length) {
$prompt = "Remove $($danglers.Count) entries from warp-map."
} else {
$prompt = "Remove 1 entry from warp-map."
}
# Actually do it...
if ($PSCmdlet.ShouldProcess($prompt)) {
# Remove the elements from the WarpMap tag
foreach ($dangler in $danglers) {
$warpMapElem.RemoveChild($dangler) | Out-Null
}
# Save the changes to the warp-map
Write-Verbose "Saving warp-map file: $(GetWarpMapFilename)"
CloseWarpMap $xml
}
}
}
}
<#
.SYNOPSIS
Provides all warp-map functionality under a single utility command.
.DESCRIPTION
`wd` is a clone of the command offered in the eponymous zsh package. It
provides an interface to all of the other commands in PoShWarp:
wd add, wd new -> New-WarpLocation
wd rm, wd del -> Remove-WarpLocation
wd ls, wd list -> Get-WarpLocation
wd clean, wd repair -> Repair-WarpMap
wd help -> Get-Help wd
`wd` also supports `wd show <WarpName>` which lists all entries that share the
given name. This has been provided as a convenience as it simply maps onto
`Get-WarpLocation`, and also for compatibility with the original `wd` command.
`wd` treats the first argument as a warp-map entry name if it does not match one
of the sub-commands. In this instance `wd <WarpName>` maps onto
`Select-WarpLocation -WarpName <WarpName>`.
As `wd` exists for compatibility with the zsh package, it primarily relies on
positional arguments as follows: `wd <sub-command> <WarpName> <Path>`. However,
named parameters are also supported to make good use of PowerShell.
.PARAMETER WarpName
Name for the warp-map entry.
.PARAMETER Path
Path for the warp-map entry.
.PARAMETER PassThru
Only used when selecting a warp location: flag propagates directory to
`Select-WarpLocation`.
.LINK
https://github.com/DuFace/PoShWarp#wd
#>
function wd {
[CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="Low")]
param(
[Parameter(Mandatory=$false)]
[String]
$WarpName,
[Parameter(Mandatory=$false)]
[String]
$Path,
[Parameter(Mandatory=$false)]
[Switch]
$PassThru,
[Parameter(Position=0, ValueFromRemainingArguments=$true)]
$argv
)
process {
# Make sure arguments have been specified
if ($argv.Length -eq 0) {
Write-Error "No sub-command or warp-name specified."
return
}
# Unpack the arguments
$warpName = SelectFirstNonNull $WarpName $argv[1]
$path = SelectFirstNonNull $Path $argv[2] '.'
# Redirect to appropriate command
switch -regex ($argv[0]) {
"^(add|new)$" {
return New-WarpLocation -WarpName $warpName -Path $path
}
"^(rm|del)$" {
return Remove-WarpLocation -WarpName $warpName
}
"^(ls|list)$" {
return Get-WarpLocation
}
"^show$" {
return Get-WarpLocation -WarpName $warpName
}
"^(clean|repair)$" {
return Repair-WarpMap
}
"^help$" {
return Get-Help wd
}
default {
$warpName = SelectFirstNonNull $WarpName $argv[0]
return Select-WarpLocation -WarpName $warpName `
-PassThru:$PassThru
}
}
}
}
## Simple tab expansion for the wd utility function ----------------------------
$script:wdSubCommands = @("add", "new", "rm", "del", "ls", "list", "show",
"clean", "repair", "help") # sub-commands of wd
if (Test-Path Function:\TabExpansion) {
Rename-Item Function:\TabExpansion TabExpansionOld
}
function TabExpansion([string] $line, [string] $lastWord) {
if ($line -match "^wd\s+($($script:wdSubCommands -join '|'))\s+(.*)") {
$command = $Matches[1]
$param = $Matches[2]
if ($command -match "rm|del|show") {
$options = Get-WarpLocation | foreach { $_.Name } | Sort-Object
return $options | where { $_ -like "$param*" }
}
} elseif ($line -match "^wd\s+(.*)") {
$params = $Matches[1]
$options = ($script:wdSubCommands | Sort-Object) + `
(Get-WarpLocation | foreach { $_.Name } | Sort-Object)
if ($params -match "([a-zA-Z_]\w*)\s*(.*)") {
$subCommand = $Matches[1]
$options = $options | where { $_ -like "$subCommand*" }
}
return $options
}
if (Test-Path Function:\TabExpansionOld) {
return TabExpansionOld $line $lastWord
}
}
## Advanced tab expansion for WarpName -----------------------------------------
if (-not $global:KJDCompleteOptions) {
$global:KJDCompleteOptions = @{
CustomArgumentCompleters = @{};
NativeArgumentCompleters = @{}
}
}
# Hook into the global completion function
$LookupCode = @'
End
{
# KJDCompletionLookup
if ($options -eq $null)
{
$options = $global:KJDCompleteOptions
}
else
{
$options += $global:KJDCompleteOptions
}
'@
if (-not ($function:TabExpansion2 -match 'KJDCompletionLookup')) {
$function:TabExpansion2 = $function:TabExpansion2 `
-replace 'End\r\n{', $LookupCode
}
# Register the actual completion function
$global:KJDCompleteOptions['CustomArgumentCompleters']['WarpName'] = {
param(
$commandName,
$parameterName,
$wordToComplete,
$commandAst,
$fakeBoundParameter
)
# Correctly resolve the command name
if ((Get-Command $commandName).CommandType -eq 'Alias') {
$commandName = (Get-Command $commandName).ResolvedCommandName
}
# Make sure it's a PoShWarp command
if ($commandName -match "(Remove|Get|Select)-WarpLocation|wd") {
# Return a list of warp locations filtered appropriately
$options = Get-WarpLocation | foreach { $_.Name }
if ($wordToComplete) {
$options = $options | where { $_ -like "$wordToComplete*" }
}
return $options | Sort-Object
}
}
## Modules Exports -------------------------------------------------------------
Export-ModuleMember -Function Select-WarpLocation
Export-ModuleMember -Function New-WarpLocation
Export-ModuleMember -Function Remove-WarpLocation
Export-ModuleMember -Function Get-WarpLocation
Export-ModuleMember -Function Repair-WarpMap
Export-ModuleMember -Function wd
Export-ModuleMember -Function TabExpansion