Changed . token to _dot

This change allows the dotfiles to work with chezmoi (e.g: on windows)
and improves grepability with neovim/telescope
This commit is contained in:
2024-11-07 13:52:17 +00:00
parent 83b02bd753
commit 896af887ca
2351 changed files with 0 additions and 0 deletions

View File

@@ -0,0 +1,63 @@
let dictionary = [
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4',
'5', '6', '7', '8', '9', '+', '/'
]
let padding_char = '='
def base64_encode [input: string] {
mut result = ""
mut counter = 0
mut left_carry = 0
if ($input | is-empty) {
error make {msg: "input is empty"}
}
for char in ($input | split chars) {
let char_bin = ($char | into binary)
let char_int = ($char_bin | into int)
if $counter mod 3 == 0 {
let index = ($char_int bit-shr 2)
$result += ($dictionary | get $index)
$left_carry = ($char_int bit-and 0x3)
} else if $counter mod 3 == 1 {
let index = (($left_carry bit-shl 4) bit-or ($char_int bit-shr 4))
$result += ($dictionary | get $index)
$left_carry = ($char_int bit-and 0xF)
} else if $counter mod 3 == 2 {
mut index = (($left_carry bit-shl 2) bit-or ($char_int bit-shr 6))
$result += ($dictionary | get $index)
$index = ($char_int bit-and 0x3F)
$result += ($dictionary | get $index)
}
$counter += 1
}
if $counter != 0 {
if $counter mod 3 == 1 {
$result += ($dictionary | get ($left_carry bit-shl 4))
$result += $padding_char
$result += $padding_char
} else if $counter mod 3 == 2 {
$result += ($dictionary | get ($left_carry bit-shl 2))
$result += $padding_char
}
}
$result
}
# Test Cases
# base64_encode "nushell", "bnVzaGVsbA=="
# base64_encode "hello", "aGVsbG8="
# base64_encode "world", "d29ybGQ="
# base64_encode "now is the time for all good mean to come to the aid of their country", "bm93IGlzIHRoZSB0aW1lIGZvciBhbGwgZ29vZCBtZWFuIHRvIGNvbWUgdG8gdGhlIGFpZCBvZiB0aGVpciBjb3VudHJ5
# base64_encode "crab", "Y3JhYg=="
# base64_encode "the brown fox jump over the lazy dog!"), "dGhlIGJyb3duIGZveCBqdW1wIG92ZXIgdGhlIGxhenkgZG9nIQ=="
# base64_encode "", error
# base64_encode "a", "YQ=="

View File

@@ -0,0 +1,18 @@
export def main [] {
let builtin = (scope commands | where type == "built-in" | length)
let external = (scope commands | where type == "external" | length)
let custom = (scope commands | where type == "custom" | length)
let keyword = (scope commands | where type == "keyword" | length)
let plugin = (scope commands | where type == "plugin" | length)
let total = (scope commands | length)
[
[command_type count];
[builtin $builtin]
[external $external]
[custom $custom]
[keyword $keyword]
[plugin $plugin]
[total_cmds $total]
]
}

View File

@@ -0,0 +1,513 @@
#copy current dir
def cpwd [] {pwd | tr "\n" " " | sed "s/ //g" | xclip -sel clip}
#update-upgrade system (ubuntu)
def supgrade [] {
echo "updating..."
sudo aptitude update -y
echo "upgrading..."
sudo aptitude safe-upgrade -y
echo "autoremoving..."
sudo apt autoremove -y
}
#open mcomix
def mcx [file] {
bash -c $'mcomix "($file)" 2>/dev/null &'
}
#open file
def openf [file?] {
let file = if ($file | is-empty) {$in} else {$file}
bash -c $'xdg-open "($file)" 2>/dev/null &'
}
#search for specific process
def psn [name: string] {
ps | find $name
}
#kill specified process in name
def killn [name: string] {
ps | find $name | each {|| kill -f $in.pid}
}
#jdownloader downloads info (requires a jdown python script)
def nujd [] {
jdown | lines | each { |line| $line | from nuon } | flatten | flatten
}
# Switch-case like instruction
def switch [
var #input var to test
cases: record #record with all cases
#
# Example:
# let x = 3
# switch $x {
# 1: { echo "you chose one" },
# 2: { echo "you chose two" },
# 3: { echo "you chose three" }
# }
] {
echo $cases | get $var | do $in
}
#post to discord
def post_to_discord [message] {
let content = $"{\"content\": \"($message)\"}"
let weburl = "webhook_url"
post $weburl $content --content-type "application/json"
}
#select column of a table (to table)
def column [n] {
transpose | select $n | transpose | select column1 | headers
}
#get column of a table (to list)
def column2 [n] {
transpose | get $n | transpose | get column1 | skip 1
}
#short pwd
def pwd-short [] {
$env.PWD | str replace $nu.home-path '~'
}
#string repeat
def "str repeat" [count: int] {
each {|it| let str = $it; echo 1..$count | each {|| echo $str } }
}
#join 2 lists
def union [a: list, b: list] {
$a | append $b | uniq
}
#nushell source files info
def 'nu-sloc' [] {
let stats = (
ls **/*.nu
| select name
| insert lines { |it| open $it.name | str stats | get lines }
| insert blank {|s| $s.lines - (open $s.name | lines | find --regex '\S' | length) }
| insert comments {|s| open $s.name | lines | find --regex '^\s*#' | length }
| sort-by lines -r
)
let lines = ($stats | reduce -f 0 {|it, acc| $it.lines + $acc })
let blank = ($stats | reduce -f 0 {|it, acc| $it.blank + $acc })
let comments = ($stats | reduce -f 0 {|it, acc| $it.comments + $acc })
let total = ($stats | length)
let avg = ($lines / $total | math round)
$'(char nl)(ansi pr) SLOC Summary for Nushell (ansi reset)(char nl)'
print { 'Total Lines': $lines, 'Blank Lines': $blank, Comments: $comments, 'Total Nu Scripts': $total, 'Avg Lines/Script': $avg }
$'(char nl)Source file stat detail:'
print $stats
}
#go to dir (via pipe)
def --env goto [] {
let input = $in
cd (
if ($input | path type) == file {
($input | path dirname)
} else {
$input
}
)
}
#go to custom bash bin path, must be added last in config.nu
def --env goto-bash [] {
cd ($env.PATH | last)
}
#cd to the folder where a binary is located
def --env which-cd [program] {
let dir = (which $program | get path | path dirname | str trim)
cd $dir.0
}
#push to git
def git-push [m: string] {
git add -A
git status
git commit -a -m $"($m)"
git push origin main
}
#get help for custom commands
def "help my-commands" [] {
help commands | where is_custom == true
}
#web search in terminal (requires ddgr)
def gg [...search: string] {
ddgr -n 5 ($search | str join ' ')
}
#habitipy dailies done all (requires habitipy)
def hab-dailies-done [] {
let to_do = (habitipy dailies | grep | awk {print $1} | tr '.\n' ' ' | split row ' ' | into int)
habitipy dailies done $to_do
}
#update aliases backup file from config.nu
def update-aliases [] {
let nlines = (open $nu.config-path | lines | length)
let from = ((grep "## aliases" $nu.config-path -n | split row ':').0 | into int)
open $nu.config-path | lines | last ($nlines - $from + 1) | save /path/to/backup/file.nu
}
#update config.nu from aliases backup
def update-config [] {
let from = ((grep "## aliases" $nu.config-path -n | split row ':').0 | into int)
let aliases = "/path/to/backup/file.nu"
open $nu.config-path | lines | first ($from - 1) | append (open $aliases | lines) | save temp.nu
mv temp.nu $nu.config-path
}
#countdown alarm (requires termdown y mpv)
def countdown [
n: int # time in seconds
] {
let BEEP = "/path/to/sound/file"
let muted = (pacmd list-sinks | awk '/muted/ { print $2 }' | tr '\n' ' ' | split row ' ' | last)
if $muted == 'no' {
termdown $n;mpv --no-terminal $BEEP
} else {
termdown $n
unmute
mpv --no-terminal $BEEP
mute
}
}
#get aliases
def get-aliases [] {
open $nu.config-path | lines | find alias | find -v aliases | split column '=' | select column1 column2 | rename Alias Command | update Alias {|f| $f.Alias | split row ' ' | last} | sort-by Alias
}
#compress every subfolder into separate files and delete them
def `7zfolders` [] {
^find . -maxdepth 1 -mindepth 1 -type d -print0 | parallel -0 --eta 7z a -t7z -sdel -bso0 -bsp0 -m0=lzma2 -mx=9 -ms=on -mmt=on {}.7z {}
}
#compress to 7z using max compression
def `7zmax` [
filename: string #filename without extension
...rest: string #files to compress and extra flags for 7z (add flags between quotes)
#
# Example:
# compress all files in current directory and delete them
# 7zmax * "-sdel"
] {
if ($rest | is-empty) {
echo "no files to compress specified"
} else {
7z a -t7z -m0=lzma2 -mx=9 -ms=on -mmt=on $"($filename).7z" $rest
}
}
#add event to google calendar, also usable without arguments (requires gcalcli)
def addtogcal [
calendar? #to which calendar add event
title? #event title
when? #date: yyyy.MM.dd hh:mm
where? #location
duration? #duration in minutes
] {
let calendar = if $calendar == null {echo $"calendar: ";input } else {$calendar}
let title = if $title == null {echo $"\ntitle: ";input } else {$title}
let when = if $when == null {echo $"\nwhen: ";input } else {$when}
let where = if $where == null {echo $"\nwhere: ";input } else {$where}
let duration = if $duration == null {echo $"\nduration: ";input } else {$duration}
gcalcli --calendar $"($calendar)" add --title $"($title)" --when $"($when)" --where $"($where)" --duration $"($duration)" --default-reminders
}
#show gcal agenda in selected calendars
def agenda [
--full: int #show all calendars (default: 0)
...rest #extra flags for gcalcli between quotes (specified full needed)
#
# Examples
# agenda
# agenda --full true
# agenda "--details=all"
# agenda --full true "--details=all"
] {
let calendars = "your_selected_calendars"
let calendars_full = "most_calendars"
if ($full | is-empty) or ($full == 0) {
gcalcli --calendar $"($calendars)" agenda --military $rest
} else {
gcalcli --calendar $"($calendars_full)" agenda --military $rest
}
}
#show gcal week in selected calendards
def semana [
--full: int #show all calendars (default: 0)
...rest #extra flags for gcalcli between quotes (specified full needed)
#
# Examples
# semana
# semana --full true
# semana "--details=all"
# semana --full true "--details=all"
] {
let calendars = "your_selected_calendars"
let calendars_full = "most_calendars"
if ($full | is-empty) or ($full == 0) {
gcalcli --calendar $"($calendars)" calw $rest --military --monday
} else {
gcalcli --calendar $"($calendars_full)" calw $rest --military --monday
}
}
#show gcal month in selected calendards
def mes [
--full: int #show all calendars (default: 0)
...rest #extra flags for gcalcli between quotes (specified full needed)
#
# Examples
# mes
# mes --full true
# mes "--details=all"
# mes --full true "--details=all"
] {
let calendars = "your_selected_calendars"
let calendars_full = "most_calendars"
if ($full | is-empty) or ($full == 0) {
gcalcli --calendar $"($calendars)" calm $rest --military --monday
} else {
gcalcli --calendar $"($calendars_full)" calm $rest --military --monday
}
}
#get bitly short link (requires xclip)
def mbitly [longurl] {
if ($longurl | is-empty) {
echo "no url provided"
} else {
let Accesstoken = "Token"
let username = "user"
let url = $"https://api-ssl.bitly.com/v3/shorten?access_token=($Accesstoken)&login=($username)&longUrl=($longurl)"
let shorturl = (http get $url | get data | get url)
$shorturl
$shorturl | xclip -sel clip
}
}
#translate text using mymemmory api
def trans [
...search:string #search query]
--from:string #from which language you are translating (default english)
--to:string #to which language you are translating (default spanish)
#
#Use ISO standard names for the languages, for example:
#english: en-US
#spanish: es-ES
#italian: it-IT
#swedish: sv-SV
#
#More in: https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes
] {
if ($search | is-empty) {
echo "no search query provided"
} else {
let key = "api_kei"
let user = "user_email"
let from = if ($from | is-empty) {"en-US"} else {$from}
let to = if ($to | is-empty) {"es-ES"} else {$to}
let to_translate = ($search | str join "%20")
let url = $"https://api.mymemory.translated.net/get?q=($to_translate)&langpair=($from)%7C($to)&of=json&key=($key)&de=($user)"
http get $url | get responseData | get translatedText
}
}
#check if drive is mounted
def is-mounted [drive:string] {
let count = (ls "~/media" | find $"($drive)" | length)
if $count == 0 {
false
} else {
true
}
}
#get phone number from google contacts (requires goobook)
def get-phone-number [search:string] {
goobook dquery $search | from ssv | rename results | where results =~ '(?P<plus>\+)(?P<nums>\d+)'
}
#ping with plot (requires ttyplot)
def nu-png-plot [] {
bash -c "ping 1.1.1.1 | sed -u 's/^.*time=//g; s/ ms//g' | ttyplot -t \'ping to 1.1.1.1\' -u ms"
}
#plot download-upload speed (requires ttyplot and fast-cli)
def nu-downup-plot [] {
bash -c "fast --single-line --upload | stdbuf -o0 awk '{print $2 \" \" $6}' | ttyplot -2 -t 'Download/Upload speed' -u Mbps"
}
#plot data table using gnuplot
def gnu-plot [
data? #1 or 2 column table
--title:string #title
#
#Example: If $x is a table with 2 columns
#$x | gnu-plot
#($x | column 0) | gnu-plot
#($x | column 1) | gnu-plot
#($x | column 0) | gnu-plot --title "My Title"
#gnu-plot $x --title "My Title"
] {
let x = if ($data | is-empty) {$in} else {$data}
let n_cols = ($x | transpose | length)
let name_cols = ($x | transpose | column2 0)
let ylabel = if $n_cols == 1 {$name_cols | get 0} else {$name_cols | get 1}
let xlabel = if $n_cols == 1 {""} else {$name_cols | get 0}
let title = if ($title | is-empty) {if $n_cols == 1 {$ylabel | str upcase} else {$"($ylabel) vs ($xlabel)"}} else {$title}
$x | to tsv | save data0.txt
sed 1d data0.txt | save data.txt
gnuplot -e $"set terminal dumb; unset key;set title '($title)';plot 'data.txt' w l lt 0;"
rm data*.txt | ignore
}
# date string YYYY-MM-DD
def ymd [] {
(date now | format date %Y-%m-%d)
}
# date string DD-MM-YYYY
def dmy [] {
(date now | format date %d-%m-%Y)
}
# create directory and cd into it.
def --env md [dir] {
mkdir $dir
cd $dir
}
# Fuzzy finds a value in a newline-separated-string or a list, using an
# optional preview. If the string or the list contains only one item,
# it is returned immediately.
# Requires the external binary 'skim'.
#
# Examples:
# > "a\nb\n" | skim
# > ls | get name | skim --preview 'ls --color {}'
def skim [
--preview (-p) = '' # command to use for the sk preview
] {
let lst = $in
let type = ($lst | describe)
let s = (if ($type | str starts-with 'list<') {
$lst | str join (char nl)
} else if ($type == 'string') {
$lst
})
if ($s | is-empty) {
null
} else {
if ($preview | is-empty ) {
($s
| sk
--layout reverse
--preview-window down:65%
--select-1
| str trim)
} else {
($s
| sk
--layout reverse
--preview-window down:65%
--select-1
--preview $preview
| str trim)
}
}
}
# Group list values that match the next-group regex.
# This function is a useful helper to quick and dirty parse data
# that contains line-wise a 'header', followed by a variable number
# of data entries. The return value is a table of header-keys with
# a list of values in the second column. Values before a header-key
# and header-keys without values are ignored.
#
# Example:
# [id_a 1 2 id_b 3] | group-list '^id_'
def group-list [
regex # on match, a new group is created
] {
let lst = $in
def make-group [v, buf, ret, key] {
let new_group = ($'($v)' =~ $regex)
if $new_group {
let is_key = (not ($key | is-empty))
let is_buf = (not ($buf | is-empty))
if ($is_buf and $is_key) {
let ret = ($ret | append {key: $key, values: $buf})
{buf: [], ret: $ret, key: $v}
} else {
{buf: [], ret: $ret, key: $v}
}
} else {
let buf = ($buf | append $v)
{buf: $buf, ret: $ret, key: $key}
}
}
def loop [lst, buf=[], ret=[], key=''] {
if ($lst | is-empty) {
{ret: $ret, buf: $buf, key: $key}
} else {
let v = ($lst | first)
let obj = (make-group $v $buf $ret $key)
let rest = ($lst | skip)
loop $rest $obj.buf $obj.ret $obj.key
}
}
let obj = (loop $lst)
let ret = $obj.ret
let buf = $obj.buf
let key = $obj.key
let is_key = (not ($key | is-empty))
let is_buf = (not ($buf | is-empty))
if ($is_buf and $is_key) {
$ret | append {key: $key, values: $buf}
} else {
$ret
}
}

View File

@@ -0,0 +1,92 @@
# Nushell Password Generator "nupass"
This nushell command randomly retrieves a specified number of words from a dictionary file (English with Japanese words added by @rickcogley) less than or equal to a given parameter's length, formats the words randomly with capitalization, then separates the words with some random symbols and numbers to return a password.
To use:
1. Get the dictionary file to your system using nushell's `http`:
```
http get https://raw.githubusercontent.com/RickCogley/jpassgen/master/genpass-dict-jp.txt | save genpass-dict-jp
```
...which has also been included in this folder for convenience.
2. Confirm your `$env.NU_LIB_DIRS` location, and copy the below script `2. nupass.nu` there as `nupass.nu`.
3. Set the script as executable like `chmod +x nupass.nu`
4. Specify the dictionary file's location in the script:
```
let dictfile = $"/path/to/my/genpass-dict-jp"
```
5. In the main function's flags section, confirm and edit the default symbols list, diceware delimiter and threads for par-each (double the number of your CPU cores seems to be a good sweet spot):
```
--symbols (-s): string = "!@#$%^&()_-+[]{}" # Symbols to use in password
--delimiter (-m): string = "-" # Delimiter for diceware
--threads (-t): int = 16 # Number of threads to use in par-each
```
6. Load the script with `use` in your `config.nu`, something like:
```
use nupass.nu
```
(you can specify the path as `use /path/to/nupass.nu` if you're not taking advantage of `$env.NU_LIB_DIRS`)
Reload nu, then run it to test:
```
nupass -h
nupass 5
nupass 6 --debug
nupass 8 -v diceware
nupass 8 -v diceware -m _
nupass 4 -v mixnmatch
nupass 6 -v alphanum
nupass 5 -l 8
```
### Testing
If you're making changes to the script while testing, you can just re-source the script by doing:
`use nupass.nu`
... which will reload the latest you have saved.
From `nu` version 0.79.1, you can use the standard library, and use its bench command to do a benchmark. Load the standard library by adding `use std` in your `env.nu`, reload, then assuming `nupass.nu` is in your path, you can benchmark like so:
```
std bench --rounds 10 --verbose {nupass 10}
std bench --rounds 10 --verbose {nupass 100 -v diceware}
std bench --rounds 10 --verbose {nupass 1000 -v mixnmatch}
```
If you change the `par-each` to `each` in the main list builders for instance, you'll see a significant performance hit. When I benchmarked `nupass 100`, using just `each` took 7 sec per round, whereas changing to `par-each` dropped that to about 1 sec per round.
You can tweak it a little further by setting the threads for par-each.
```
std bench --rounds 10 --verbose {nupass 100 -v diceware -t 8}
std bench --rounds 10 --verbose {nupass 100 -v diceware -t 16}
std bench --rounds 10 --verbose {nupass 100 -v diceware -t 32}
```
<img width="736" alt="image" src="https://user-images.githubusercontent.com/512328/235553238-48b48f37-0eae-48d3-8afe-e17515cd8325.png">
### Caveats
I've been scripting for quite a long time, but not in nu. Input appreciated to make this more nu-esque! The script is in a decent place as of the 20230501 version.
Obviously you can just use the `random chars` or `random integers` commands but I like to have words I can read in my passwords, and I think those generated by this script have sufficient entropy.
This command doesn't let you specify a precise length.
### Acknowledgements
Thanks everyone on Discord for putting up with and answering my nubie questions @amtoine, @fdncred, @jelle, @sygmei, @kubouch and for the feedback after try number 1.
<img width="576" alt="image" src="https://user-images.githubusercontent.com/512328/235383307-d3f3d65d-c184-4dfa-9fe9-677b677d8531.png">

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,120 @@
# Script to generate a password from a dictionary file
# Author: @rickcogley
# Thanks: @amtoine, @fdncred, @jelle, @sygmei, @kubouch
# Updates: 20230415 - initial version
# 20230416 - add @amtoine's slick probabilistic "random decimal" char capitalization
# 20230417 - add script duration output in debug block
# 20230421 - add length of symbol chars to get-random-symbol function
# 20230422 - add variant flag to generate different styles of passwords
# 20230501 - refactor to allow number of words to be specified, use list manipulation and reduce to string
# 20230502 - improve performance on list builders with par-each
# 20230503 - add threads flag for fine tuning par-each
#======= NUPASS PASSWORD GENERATOR =======
# Generate password of 3 dictionary file words, numbers and symbols
export def main [
words: int = 3 # Number of words in password
--word_length (-l): int = 5 # Max length of words in password
--symbols (-s): string = "!@#$%^&()_-+[]{}" # Symbols to use in password
--variant (-v): string = "regular" # Password style to generate in regular, mixnmatch, alphanum, alpha, diceware
--delimiter (-m): string = "-" # Delimiter for diceware
--threads (-t): int = 16 # Number of threads to use in par-each
--debug (-d) # Include debug info
] {
##### Main function #####
# Get dictionary file:
# http get https://raw.githubusercontent.com/RickCogley/jpassgen/master/genpass-dict-jp.txt | save genpass-dict-jp
# Set the path:
let dictfile = $"/usr/local/bin/genpass-dict-jp"
let starttime = (date now)
# Find number of lines with strings less than or equal to the supplied length
let num_lines = (open ($dictfile) | lines | wrap word | upsert len {|it| $it.word | split chars | length} | where len <= ($word_length) | length)
# Get random words from dictionary file
let random_words = (1..$words | par-each { |i| $dictfile | get-random-word $word_length $num_lines | random-format-word } --threads $threads)
# Get some symbols to sprinkle like salt bae
# Update default symbol chars in symbols flag
let symbols_len = ($symbols | str length)
let random_symbols = (1..$words | par-each { |i| $symbols | get-random-symbol $symbols $symbols_len } --threads $threads)
# Get some random numbers
let random_numbers = (1..$words | par-each { |i| (random int 0..99) } --threads $threads)
# Print some vars if debug flag is set
if $debug {
print $"(ansi bg_red) ====== DEBUG INFO ====== (ansi reset)"
print $"(ansi bg_blue) 🔔 Number of lines in dict with words under ($word_length) chars: (ansi reset)"
print $num_lines
print $"(ansi bg_blue) 🔔 Words from randomly selected lines: (ansi reset)"
print $random_words
print $"(ansi bg_blue) 🔔 Randomly selected symbols: (ansi reset)"
print $random_symbols
print $"(ansi bg_blue) 🔔 Randomly selected numbers: (ansi reset)"
print $random_numbers
let endtime = (date now)
print $"(ansi bg_green) 🔔 Generated password in ($endtime - $starttime): (ansi reset)"
}
# Return password in selected variant
if $variant == "regular" {
# Default variant, with regular distribution
# Generate new list w symbol, words, numbers, then reduce to string
return (0..($words - 1) | each { |it| ($random_symbols | get $it) + ($random_words | get $it) + ($random_numbers | get $it | into string) } | reduce { |it, acc| $acc + $it })
} else if $variant == "mixnmatch" {
# Combine lists, shuffle randomly, reduce to string
return (($random_words ++ $random_symbols ++ $random_numbers | shuffle) | reduce { |it, acc| ($acc | into string) + ($it | into string) })
} else if $variant == "alphanum" {
# Combined random int and random word, reduce to string
return (0..($words - 1) | each { |it| (random int 0..99 | into string) + ($random_words | get $it) } | reduce { |it, acc| $acc + $it })
} else if $variant == "alpha" {
# Reduce random words only to string
return ($random_words | reduce { |it, acc| $acc + $it })
} else if $variant == "diceware" {
# Reduce to string with hyphen between words
return ($random_words | reduce { |it, acc| $acc + $"($delimiter)($it)" })
}
}
##### Utility functions #####
# Function to get random word from a dictionary file
def get-random-word [
wordlength: int
numlines: int
] {
open
| lines
| wrap word
| upsert len {|it| $it.word | str length}
| where len <= ($wordlength)
| get (random int 1..($numlines))
| get word
}
# Function to format a word randomly
def random-format-word [] {
par-each {|it|
let rint = (random int 1..4)
if $rint == 1 {
($it | str capitalize)
} else if $rint == 2 {
($it | str upcase)
} else if $rint == 3 {
($it | split chars | each {|c| if (random float) < 0.2 { $c | str upcase } else { $c }} | str join "")
} else {
($it | str downcase)
}
}
}
# Function to get random symbol from list of symbols
def get-random-symbol [
symbolchars: string
symbolcharslen: int
] {
$symbolchars
| split chars
| get (random int 0..($symbolcharslen - 1))
}

View File

@@ -0,0 +1,52 @@
let table = (echo [
[url user_login title];
[https://api.github.com/repos/nushell/nushell/issues/3382 ammkrn 'Dont unwrap rustyline helper in cli']
[https://api.github.com/repos/nushell/nushell/issues/3379 jonathandturner 'Simplify down to one type of context']
[https://api.github.com/repos/nushell/nushell/issues/3377 kubouch 'Port range to engine-p']
[https://api.github.com/repos/nushell/nushell/issues/3375 fdncred 'added check for endian-ness, added a bytes and skip']
[https://api.github.com/repos/nushell/nushell/issues/3374 fdncred 'added ability to change ']
[https://api.github.com/repos/nushell/nushell/issues/3370 fdncred 'add nu-pretty-hex, add into binary, update binaryview']
[https://api.github.com/repos/nushell/nushell/issues/3367 fdncred 'tweaked the error handling to show specific errors']
])
# Show what the table looks like
print $"This is an example table (char nl)"
print $table
print $"This is markdown created from the example table (char nl)"
# Now show what the table in Markdown looks like
print $"## Nushell(char nl)(char nl)"
print ($table | group-by user_login | transpose user prs | each { |row|
let user_name = $row.user
let pr_count = (echo $row.prs | length)
# only print the comma if there's another item
let user_prs = ($row.prs | enumerate | each { |pr|
if $pr_count == ($pr.index + 1) {
echo $'[($pr.item.title)](char lp)($pr.item.url)(char rp)'
} else {
echo $'[($pr.item.title)](char lp)($pr.item.url)(char rp), and '
}
} | str join)
echo $"- ($user_name) created ($user_prs) (char nl)"
} | str join)
# ╭───┬──────────────────────────────────────────────────────────┬─────────────────┬───────────────────────────────────────────────────────╮
# │ # │ url │ user_login │ title │
# ├───┼──────────────────────────────────────────────────────────┼─────────────────┼───────────────────────────────────────────────────────┤
# │ 0 │ https://api.github.com/repos/nushell/nushell/issues/3382 │ ammkrn │ Dont unwrap rustyline helper in cli │
# │ 1 │ https://api.github.com/repos/nushell/nushell/issues/3379 │ jonathandturner │ Simplify down to one type of context │
# │ 2 │ https://api.github.com/repos/nushell/nushell/issues/3377 │ kubouch │ Port range to engine-p │
# │ 3 │ https://api.github.com/repos/nushell/nushell/issues/3375 │ fdncred │ added check for endian-ness, added a bytes and skip │
# │ 4 │ https://api.github.com/repos/nushell/nushell/issues/3374 │ fdncred │ added ability to change "#" color using header_color │
# │ 5 │ https://api.github.com/repos/nushell/nushell/issues/3370 │ fdncred │ add nu-pretty-hex, add into binary, update binaryview │
# │ 6 │ https://api.github.com/repos/nushell/nushell/issues/3367 │ fdncred │ tweaked the error handling to show specific errors │
# ╰───┴──────────────────────────────────────────────────────────┴─────────────────┴───────────────────────────────────────────────────────╯
def log [message:any] {
let now = (date now | format date '%Y%m%d_%H%M%S.%f')
let mess = ([$now '|DBG|' $message (char newline)] | str join)
echo $mess
}