1
Fork 0
mirror of https://github.com/RGBCube/nu_scripts synced 2025-08-01 06:37:46 +00:00

Update bar function (#589)

* fix indexing issue

* [bar] make default output without ansi codes

* [bar] use actual testing framework
This commit is contained in:
Maxim Uvarov 2023-09-01 20:18:21 +08:00 committed by GitHub
parent 4cbd678d78
commit 5ed3a961af
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -1,30 +1,32 @@
# construct bars based of a given percentage from a given width (5 is default) # construct bars based of a given percentage from a given width (5 is default)
# > bar 0.2 # > bar 0.2
# █ # █
# > bar 0.71 --width 10 # > bar 0.71
# ███████ # ███
def 'bar' [ def 'bar' [
percentage: float percentage: float
--background (-b): string = 'default' --background (-b): string = 'default'
--foreground (-f): string = 'default' --foreground (-f): string = 'default'
--progress (-p) # output the result using 'print -n' with '\r' at the end --progress (-p) # output the result using 'print -n'
--width (-w): int = 5 --width (-w): int = 5
] { ] {
let blocks = [null "▏" "▎" "▍" "▌" "▋" "▊" "▉" "█"] let blocks = [null "▏" "▎" "▍" "▌" "▋" "▊" "▉" "█"]
let $whole_part = (($blocks | last) * ($percentage * $width // 1)) let $whole_part = (($blocks | last) * ($percentage * $width // 1))
let $fraction = ( let $fraction = (
$blocks $blocks
| get ( | get (
($percentage * $width) mod 1 ($percentage * $width) mod 1
| $in * ($blocks | length) | $in * ($blocks | length | $in - 1)
| math floor | math round
) )
) )
let $result = ( let result = (
$"($whole_part)($fraction)" $"($whole_part)($fraction)"
| fill -c $' ' -w $width | fill -c $' ' -w $width
| $"(ansi -e {fg: ($foreground), bg: ($background)})($in)(ansi reset)" | if ($foreground == 'default') and ($background == 'default') {} else {
$"(ansi -e {fg: ($foreground), bg: ($background)})($in)(ansi reset)"
}
) )
if $progress { if $progress {
@ -34,28 +36,12 @@ def 'bar' [
} }
} }
def assert_eq [num: int, expected: string, input_1: float, input_2?] { use std assert equal
let actual = (
if ($input_2 == null) {bar $input_1} else {
bar $input_1 --width $input_2
}
)
let span = (metadata $expected).span;
if $actual != $expected {
error make {
msg: "Actual != Expected",
label: {
text: $"expected ($expected) but got ($actual)", start: $span.start, end: $span.end
}
}
} else {
print $"Test ($num) (ansi green)passed(ansi reset) ✓"
}
}
#[test]
def bar_tests [] { def bar_tests [] {
assert_eq 1 "▏ " 0.03 equal "█▌ " (bar 0.3)
assert_eq 2 "▎ " 0.03 10 equal "███ " (bar 0.3 --width 10)
assert_eq 3 "▊" 0.71 1 equal "▊" (bar 0.71 --width 1)
assert_eq 4 "███████ " 0.71 10 equal "███████▏ " (bar 0.71 --width 10)
} }