-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPSparklines.psm1
644 lines (521 loc) · 16.4 KB
/
PSparklines.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
using namespace System.Collections;
using namespace System.Collections.Generic;
<#
____ ____ _ _ _
| _ \/ ___| _ __ __ _ _ __| | _| (_)_ __ ___ ___
| |_) \___ \| '_ \ / _` | '__| |/ / | | '_ \ / _ \/ __|
| __/ ___) | |_) | (_| | | | <| | | | | | __/\__ \
|_| |____/| .__/ \__,_|_| |_|\_\_|_|_| |_|\___||___/
|_|
#>
<#
.Synopsis
This module is a very simple way to show text sparklines in the console.
.Description
This module is a very simple way to show text sparklines in the console.
It was ported to PowerShell from Python. The original package is sparklines.py.
It is hosted on github.com at github.com/deeplook/sparklines.
This module does implement emphasis in a manner similar to the original.
However, instead of a simple string pattern, it uses Emphasis objects.
Objects are added to a dictionary with functions that support auto-completion.
This module does not implement the batching (array splitting) that sparklines used.
Use the `Ansi` switch parameter with `Show-Sparkline` to take advantage of Ansi colors.
This module also outputs Sparklines as objects and uses two different functions to write them.
`Show-Sparkline` will write the sparkline to the host and STDINFO (6) and colorize based on an emphasis table.
`Write-Sparkline` will write the sparkline to STDOUT (1) as a string for further parsing or use.
Because `Get-Sparkline` will write objects, the user can write a custom function to write the sparkline
how they need if the default functions are inadequate.
Cmdlets/Functions for Sparklines:
Get-Sparkline
Write-Sparkline
Show-Sparkline
Cmdlets/Functions for Emphasis:
New-Emphasis
.Example
PS> Get-Sparkline 25, 50, 75, 100, 25 -Emphasis @(
New-Emphasis -Color 'Red' -Predicate { param($x) $x -gt 50 }
) | Show-Sparkline
Display a sparkline in the host of line height 1 with every bar representing a number greater than 50
as ConsoleColor.Red
#>
param()
# Idea: PowerShell 7 is so much easier to work with more 'programmatic' PS -- consider requiring it
<#
___ _
/ __| ___| |_ _ _ _ __
\__ \/ -_) _| || | '_ \
|___/\___|\__|\_,_| .__/
|_|
#>
#region Setup ------------------------------------------------------------------
# Module variables go here
Set-Variable PSparklines -Option ReadOnly -Value @{
DefaultForegroundColor = [Console]::ForegroundColor
ModuleName = 'PSparklines'
Esc = [char] 0x1b
}
$ErrorActionPreference = 'Stop'
$ResourceFile = @{
BindingVariable = 'Resources'
BaseDirectory = $PSScriptRoot
FileName = $PSparklines.ModuleName + '.Resources.psd1'
}
$ConfigFile = @{
BindingVariable = 'Config'
BaseDirectory = $PSScriptRoot
FileName = $PSparklines.ModuleName + '.Config.psd1'
}
# Try to import the resource file
try {
Import-LocalizedData @ResourceFile
} catch {
# Uh-oh. The module is likely broken if this file cannot be found.
Import-LocalizedData @ResourceFile -UICulture en-US
}
# Try to import the config file.
try {
Import-LocalizedData @ConfigFile
} catch {
# The config file is missing. Not a big deal! Here's a default Config.
$Config = @{
Blocks = @'
▁▂▃▄▅▆▇█
'@
}
}
#endregion
<#
___ _
/ __| |__ _ ______ ___ ___
| (__| / _` (_-<_-</ -_|_-<
\___|_\__,_/__/__/\___/__/
#>
#region Module Classes ---------------------------------------------------------
class Color {
[byte] $R
[byte] $G
[byte] $B
[byte] $Value
[ConsoleColor] $ConsoleColor
Color($n) {
$x = $n -as [int]
if ($x -is [int]) {
$this.Value = $n
} else {
$this.Value =
switch ($n) {
Black { 0 }
DarkRed { 1 }
DarkGreen { 2 }
DarkYellow { 3 }
DarkBlue { 4 }
DarkMagenta { 5 }
DarkCyan { 6 }
Gray { 7 }
DarkGray { 8 }
Red { 9 }
Green { 10 }
Yellow { 11 }
Blue { 12 }
Magenta { 13 }
Cyan { 14 }
White { 15 }
default { 0 } # Todo: Drawing.Color -> rgb -> ansi
}
}
$this.R, $this.G, $this.B = [Color]::RgbFromAnsi256($this.Value)
$this.ConsoleColor = [Color]::ConsoleColorFromAnsi($this.Value)
}
static [int] CubeValue($n) {
return @(
0
95
135
175
215
255
)[$n]
}
static [int[]] RgbFromAnsi256($n) {
$x =
switch ($n) {
{ $n -lt 232 } {
$idx = $n - 16
[Color]::CubeValue($idx / 36),
[Color]::CubeValue($idx / 6 % 6),
[Color]::CubeValue($idx % 6)
}
default {
$gr = ($n - 232) * 10 + 8
$gr, $gr, $gr
}
}
return $x
}
static [ConsoleColor] ClosestConsoleColorFromRgb($r, $g, $b) {
$color =
if ($r -eq $g -and $g -eq $b) {
switch ($r) {
{ $r -gt 192 } { 0xf } # 0b1111
{ $r -gt 128 } { 7 } # 0b0111
{ $r -gt 64 } { 8 } # 0b1000
default { 0 }
}
} else {
$br =
if ($r -gt 128 -or $g -gt 128 -or $b -gt 128) {
7
} else {
0
}
$rb = if ($r -gt 64) { 4 } else { 0 } # 0b0100
$gb = if ($g -gt 64) { 2 } else { 0 } # 0b0010
$bb = if ($b -gt 64) { 1 } else { 0 } # 0b0001
$br -bor $rb -bor $gb -bor $bb
}
return $color
}
static [ConsoleColor] ConsoleColorFromAnsi($n) {
$colorMap = @(
[ConsoleColor]::Black
[ConsoleColor]::DarkRed
[ConsoleColor]::DarkGreen
[ConsoleColor]::DarkYellow
[ConsoleColor]::DarkBlue
[ConsoleColor]::DarkMagenta
[ConsoleColor]::DarkCyan
[ConsoleColor]::Gray
[ConsoleColor]::DarkGray
[ConsoleColor]::Red
[ConsoleColor]::Green
[ConsoleColor]::Yellow
[ConsoleColor]::Blue
[ConsoleColor]::Magenta
[ConsoleColor]::Cyan
[ConsoleColor]::White
)
$color =
switch ($n) {
{ $n -lt 16 } { $colorMap[$n] }
default {
$x, $y, $z = [Color]::RgbFromAnsi256($n)
[Color]::ClosestConsoleColorFromRgb($x, $y, $z)
}
}
return $color
}
[string] ToString() {
return $this.ConsoleColor.ToString()
}
}
class Emphasis {
[Color] $Color
[scriptblock] $Predicate
}
class Spark {
[int] $Row
[int] $Col
[int] $Val
[string] $Block
[AllowNull()]
[Color] $Color
}
#endregion
<#
_ _ _
| || |___| |_ __ ___ _ _ ___
| __ / -_) | '_ \/ -_) '_(_-<
|_||_\___|_| .__/\___|_| /__/
|_|
#>
#region Class Helpers ----------------------------------------------------------
function Get-Max ($a, $b) { [Math]::Max($a, $b) }
function Get-Min ($a, $b) { [Math]::Min($a, $b) }
function Get-RoundUp ($n) { [Math]::Round($n) }
function Get-ScaledValues {
# .Synopsis
# Scale input numbers to appropriate range.
# double[] -> int -> double? -> double? -> double[]
# .Notes
# Replaces scale_values(numbers, num_lines=1, minium=None, maximum=None)
param(
[double[]] $Numbers
,
[int] $NumLines = 1
,
[double] $Minimum
,
[double] $Maximum
)
$Numbers |
Measure-Object -Minimum -Maximum |
Set-Variable mo
$min = ($Minimum, $mo.Minimum)[!$Minimum]
$max = ($Maximum, $mo.Maximum)[!$Maximum]
$dv = $max - $min
$nums = $Numbers.ForEach{ Max (Min $_ $max) $min }
$getValue = {
$maxIndex = $NumLines * ($Config.Blocks.Length - 1)
(($maxIndex - 1) * ($_ - $min)) / $dv + 1
}
$roundValue = {
$v = RoundUp $_
(1, $v)[$v -gt 0]
}
switch ($dv) {
{ $dv -eq 0 } { $nums.ForEach{ 4 * $NumLines } }
{ $dv -gt 0 } { $nums.ForEach($getValue).ForEach($roundValue) }
default { }
}
}
function Get-ColorArray ($ns, $xs) {
# .Synopsis
# Get the colors mapped from a double array when passed through an array of predicates
# double[] -> Emphasis[]? -> Color[]
foreach ($n in $ns) {
$color = [Console]::ForegroundColor -as [Color]
foreach ($x in $xs) {
if ($x.Predicate.Invoke($n)) {
$color = $x.Color
break;
}
}
$color
}
}
#endregion
<#
___ _ _ _
| _ \_ _| |__| (_)__
| _/ || | '_ \ | / _|
|_| \_,_|_.__/_|_\__|
#>
#region Public Commands --------------------------------------------------------
function New-Emphasis ($Color, $Predicate) {
<#
.Synopsis
Creates a new Emphasis object.
.Description
A public helper function that creates a new Emphasis object.
Emphasis objects allow for the colorization of sparks in a sparkline.
The predicate parameter
.Parameter Color
The color parameter capitalizes on PowerShell's powerful casting.
Pass it either a ConsoleColor name, e.g. 'Red' or an Ansi 256 color.
If an Ansi 256 color is passed above 16, the Color class will smartly select the closest ConsoleColor.
.Parameter Predicate
The predicate parameter must be a scriptblock.
The scriptblock should accept 1 parameter and evaluate to a boolean.
.Example
New-Emphasis -Color 'Red' -Predicate { param($x) $x -gt 50 }
.Example
New-Emphasis -Color 55 -Predicate { $x, $rest = $args; $x -in (6..13) }
.Example
New-Emphasis -Color 231 -Predicate { $args[0] -like '6*' }
.Link
Get-Sparkline
.Notes
Replaces the emph pattern used in sparklines.py
#>
[Emphasis] @{
Color = $Color
Predicate = $Predicate
}
}
function Get-Sparkline {
<#
.Synopsis
Return an array of sparkline objects for a given list of input numbers.
.Description
Return an array of sparkline objects for a given list of input numbers.
.Example
PS> Get-Sparkline -Numbers 20, 80, 60, 100
Returns sparkline objects representing the numbers 20, 80, 60, 100.
.Example
PS> Get-Sparkline -Numbers 20, 80, 60, 100 | Write-Sparkline
▁▆▄█
.Example
PS> Get-Sparkline -Numbers 20, 80, 60, 100 -NumLines 3 | Write-Sparkline
▂ █
█▄█
▁███
.Example
PS> Get-Sparkline -Numbers 20, 80, 60, 100 -Emphasis (New-Emphasis -Color Red -Predicate { param($x) $x -gt 70 } | Show-Sparkline
This will display a sparkline in the host with the second and fourth bar colored red,
if the host is capable.
.Example
PS> -join (Get-Sparkline 1,2,3,4 | Show-Sparkline 6>&1)
One possible way to capture the output of `Show-Sparkline`.
.Link
New-Emphasis
.Link
Write-Sparkline
.Link
Show-Sparkline
.Inputs
double[]
.Outputs
Sparks[]
.Notes
Replaces sparklines(numbers=[], num_lines=1, emph=None, verboe=False,
minimum=None, maximum=None, wrap=None). Wrap is not
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')]
param(
# An array of numbers to turn into a sparkline.
[Parameter(ValueFromPipeline)]
[double[]] $Numbers
,
# The number of lines to write or show the sparkline on. Must be positive.
[ValidateScript({ Assert-Positive $_ })]
[int] $NumLines = 1
,
# An array of Emphasis objects that will color certain sparks based on simple logical tests.
$Emphasis # For some reason cannot be [Emphasis[]]?
,
# The lowest number to display on the sparkline--a high-pass filter.
[double] $Minimum
,
# The highest number to display on the sparkline--a low-pass filter.
[double] $Maximum
)
begin {
$ls = [System.Collections.ArrayList] @()
}
process {
[void] $Numbers.ForEach{ $ls.Add($_) }
}
end {
$PSBoundParameters.Numbers = $ls.ToArray()
$xs = $Emphasis
# Remove params from the hashtable to allow for easy-reuse
[void] $PSBoundParameters.Remove('Emphasis')
Test-NegativeNumber $ls.ToArray()
$x = Get-ColorArray $ls.ToArray() $xs
Get-ScaledValues @PSBoundParameters | ForEach-Object { $c = 0 } {
$v = $_
1..$NumLines | ForEach-Object { $r = 0 } {
$vs = Min $v 8
$v = Max 0 ($v - 8)
[Spark] @{
Row = $r
Col = $c
Val = $vs
Block = $Config.Blocks[$vs]
Color = $x[$c]
}
$r++
}
$c++
}
}
}
function Show-Sparkline {
<#
.Synopsis
Format the pipelined Sparkline and send it to the information stream and write it to the host.
.Description
Format the pipelined Sparkline and send it to the information stream and write it to the host.
Allows for in host formatting and colorization if the Sparkline array was defined with an Emphasis.
If the console host support virtual terminal codes and 24 bit color, use the ansi switch to get enhanced colors defined by Emphasis objects.
.Example
PS> Get-Sparkline 1,2,3,4 | Show-Sparkline
.Example
PS> Get-Sparkline 1,2,3,4 -Emphasis (New-Emphasis -Color 55 -Predicate { param($x) $x -eq 2 }) | Show-Sparkline -Ansi
#>
param(
# Do not terminate the sparkline with a newline.
[switch] $NoNewline
,
# Use the 256 Ansi Colors
[switch] $Ansi
)
$input |
Sort-Object @{ Expression = 'Row'; Descending = $true }, Col -OutVariable sparks |
Measure-Object -Property Row -Maximum |
Set-Variable mo
$r = $mo.Maximum
foreach ($x in $sparks) {
if ($x.Row -ne $r) {
Write-Host
$r--
}
if ($Ansi.IsPresent) {
Write-Host ('{2}[38;5;{0}m{1}{2}[0m' -f $x.Color.Value, $x.Block, $PSparklines.Esc) -NoNewline
} else {
Write-Host $x.Block -ForegroundColor $x.Color.ConsoleColor -NoNewline
}
}
Write-Host -NoNewline:$NoNewline.IsPresent
}
function Write-Sparkline {
<#
.Synopsis
Format the pipelines Sparkline and send it the standard output stream and write it as a string.
.Example
PS> Get-Sparkline 1,2,3,4 | Write-Sparkline
#>
$input |
Group-Object Row |
Sort-Object Name -Descending |
ForEach-Object { -join $_.Group.Block }
}
#endregion
<#
__ ,
,-| ~ , ,,
('||/__, _ || || ' _
(( ||| | < \, =||= _-_ ||/\ _-_ _-_ -_-_ \\ \\/\\ / \\
(( |||==| /-|| || || \\ ||_< || \\ || \\ || \\ || || || || ||
( / | , (( || || ||/ || | ||/ ||/ || || || || || || ||
-____/ \/\\ \\, \\,/ \\,\ \\,/ \\,/ ||-' \\ \\ \\ \\_-|
|/ / \
' '----`
#>
#region Gatekeeping ------------------------------------------------------------
function Assert-Positive ($n) {
# .Synopsis
# Returns true if the number is greater than zero.
# Otherwise, throws an exception.
# double -> bool
$isNumeric = [double]::TryParse($n, [ref] $null)
if (!$isNumeric) {
throw $Resources.InvalidNumeric -f $n
}
if ($n -le 0) {
throw $Resources.InvalidNegative -f $n
}
$true
}
filter Get-NegativeNumbers {
# .Synopsis
# Passes numbers less than zero.
# double[] -> double
if ($_ -lt 0) {
$_
}
}
function Write-Scolding {
# .Synopsis
# Writes a warning for every negative number caught.
# Writes a general warning if any negative number is caught.
# double[] -> ()
process {
Write-Warning ($Resources.FoundNegativeNum -f $_)
$b = $null -ne $_
}
end {
if ($b) {
Write-Warning $Resources.UnexpectedOutput
}
}
}
function Test-NegativeNumber ($a) {
# .Synopsis
# Raise warning for negative numbers.
# double[] -> ()
$a |
Get-NegativeNumbers |
Write-Scolding
}
#endregion