Initial commit

This commit is contained in:
ItsDrike 2022-10-29 20:25:42 +02:00
parent b912871070
commit a3e01caebf
No known key found for this signature in database
GPG key ID: B014E761034AF742
157 changed files with 9696 additions and 0 deletions

298
home/.config/shell/aliases Executable file
View file

@ -0,0 +1,298 @@
#!/bin/sh
# I'm not the greatest typist
alias sl='ls'
alias mdkir='mkdir'
alias soruce='source'
alias souce='source'
alias suod='sudo '
alias sduo='sudo '
# Replacements (adding flags)
alias cp='cp -iv' # Ask before overwriting, verbose
alias mv='mv -iv' # Ask before overwriting, verbose
alias rm='trash-put' # Use trash-cli instead of true removal
alias rmr='\rm -v' # True rm, verbose (asking here is too annoying)
alias wget='wget -c' # Resume wget by default
alias df='df -H' # Show sizes as powers of 1000
# Directory changing
alias ..='cd ..'
alias ...='cd ../../'
alias ....='cd ../../../'
alias .....='cd ../../../../'
alias .2='cd ../../'
alias .3='cd ../../../'
alias .4='cd ../../../../'
alias .5='cd ../../../../../'
# Files/Directories utilities
alias mkdir='mkdir -p'
alias md='mkdir'
alias fhere='find . -name'
alias rr='rmr -r'
alias rf='rmr -f'
alias rrf='rmr -rf'
alias vimdiff='nvim -d'
# Directory listing aliases, defaults to exa, if aviable
if command -v exa > /dev/null; then
alias ls='exa'
alias l='exa -glah --classify'
alias ll='exa -glah --classify -s=size --group-directories-first -r'
alias ldir='exa -glahD'
alias tree='exa -Tlagh'
alias dotall='exa -hulad .[a-z]*' # Show both dotdirs and dotfiles
alias dotfiles='dotall | grep -v ^d' # Show all dotfiles
alias dotdirs='dotall | grep --color=never ^d' # Show all dotdirs
else
alias ls='ls --color=auto'
alias l='ls -lahX --classify'
alias ll='ls -lahX --classify --group-directories-first'
alias ldir='ls -lahX --classify | grep --color=never ^d'
alias dotall='ls -lahXd .[a-z]*'
alias dotfiles='dotall | grep -v ^d'
alias dotdirs='dotall | grep --color=never ^d'
fi
# Config access shortcuts
alias cfzsh='vim ~/.config/zsh/.zshrc'
alias cfalias='vim ~/.config/shell/aliases'
alias cffunctions='vim ~/.config/shell/functions'
alias cfprofile='vim ~/.config/shell/profile'
alias cfenvironment='vim ~/.config/shell/environment'
alias cfenv='cfenvironment'
alias cfhandlers='vim ~/.config/shell/handlers'
alias cfprompt='vim ~/.config/shell/prompt'
alias cfkeybinds='vim ~/.config/shell/keybinds'
alias cfxprofile='vim ~/.config/x11/xprofile'
alias cfsxhkd='vim ~/.config/sxhkd/sxhkdrc'
alias cfkbd='cfsxhkd'
alias cfbspwm='vim ~/.config/bspwm/bspwmrc'
alias cfxmonad='vim ~/.config/xmonad/xmonad.hs && xmonad --recompile && xmonad --restart'
alias cfxmobar='vim ~/.config/xmobar/xmobarrc.hs && ~/.config/xmobar/multi_mon.sh 2'
alias cftodo='vim ~/Personal/vimwiki/todo.md'
alias cfnvim='vim ~/.config/nvim'
alias cfvim='cfnvim'
# z.lua shortcuts
alias j='z' # for the sake of autojump old habits
alias zz='z -c' # restrict matches to subdirs of $PWD
alias zb='z -b' # restrict matches to parent directories
alias zi='z -I' # cd with interactive fzf selection
alias zbi='z -b -I' # pick parent directory to cd into with fzf
# Fallbacks
command -v hd > /dev/null || alias hd='hexdump -C' # Cannonical hex dump; some systems have this symlinked
command -v md5sum > /dev/null || alias md5sum='md5' # Fallback from `md5sum` to `md5`
command -v sha1sum > /dev/null || alias sha1sum='shasum' # Fallback from `sha1sum` to `shasum`
command -v vim > /dev/null && alias vi='vim' # Let vim take precedence over vi
command -v nvim > /dev/null && alias vi='nvim' && alias vim='nvim' # Let nvim take precedence over vi/vim
command -v vimtutor > /dev/null || alias vimtutor='nvim -c Tutor' # Let vimtutor fallback to nvim's tutor
# X11 clipboard (either using xclip or xsel, xsel takes precedence if both)
command -v xclip > /dev/null && alias pbcopy='xclip -selection clipboard'
command -v xclip > /dev/null && alias pbpaste='xclip -selection clipboard -o'
command -v xsel > /dev/null && alias pbcopy='xsel --clipboard --input'
command -v xsel > /dev/null && alias pbpaste='xsel --clipboard --output'
# File validation and manipulation
alias yamlcheck='python -c "import sys, yaml as y; y.safe_load(open(sys.argv[1]))"' # Validate YAML
alias jsoncheck='jq "." >/dev/null <' # Validate JSON
alias urlencode='python2 -c "import sys, urllib as ul; print ul.quote_plus(sys.argv[1]);"' # Encode strings as URLs (space->%20, etc.)
alias mergepdf='gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=_merged.pdf' # Usage: `mergepdf input{1,2,3}.pdf``
alias encrypt='gpg -c --no-symkey-cache --cipher-algo AES256' # Encrypt file with AES256 symetric encryption
alias decrypt='gpg' # For the sake of completeness, include decrypt command to the above, though it's only just gpg alias
# Terminal window swallowing for blocking programs (devour)
alias xdg-open='devour xdg-open'
alias mpv='devour mpv'
alias nomacs='devour nomacs'
alias pcmanfm='devour pcmanfm'
alias spotify='devour spotify'
# Regular expressions
alias reg_email='echo "[a-Z0-9._%-]+@[a-Z0-9.-]+\.[a-Z]{2,10}"'
alias reg_mac='echo "([[:xdigit:]]{2}:){5}[[:xdigit:]]{2}"'
alias reg_ipv4='echo "([0-9]{1,3}\.){3}[0-9]{1,3}"'
alias reg_ipv6='echo "\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*"' # Also catches loopbacks (::1), (for valid matching, it needs to be this long...)
alias reg_ip='echo "(`reg_ipv4`|`reg_ipv6`)"' # Match both IPv4 and IPv6
# Grep aliases
alias grep_email='grep -E `reg_email`'
alias grep_ip='grep -E `reg_ip`'
alias grep_mac='grep -E `reg_mac`'
alias massgrep='grep -RHIni'
# Network
alias ip-show='curl https://ifconfig.co' # Get global IP address
alias ips="ifconfig -a | grep -oE \"inet6? (addr:)?s?\`reg_ip\`\" | awk '{ sub(/inet6? (addr:)? ?/, \"\"); print }'"
alias lan-device-scan='nmap -T5 -sP 192.168.0.0-255'
alias lan-vuln-scan='nmap -sT -O --script vuln 192.168.0.0-255'
alias ports='netstat -tulanp'
alias listening-ports='netstat -vtlnp --listening'
alias ssh-list='ss | grep ssh' # List all SSH connections
alias serve='python -m http.server' # Serve current directorty as HTTP
alias reverse-dns='host' # It might be easier to just use `host` though
alias torify='source torsocks on' # Pass every command via torsocks
alias untorify='source torsocks off' # Stop passing commands via torsocks
# Firewall aliases (IPTables/UFW)
alias ipt='iptables' # Shortcut
alias iptlist='iptables -L -n -v --line-numbers' # All rules
alias iptlistin='iptables -L INPUT -n -v --line-numbers' # IN rules
alias iptlistout='iptables -L OUTPUT -n -v --line-numbers' # OUT rules
alias iptlistfw='iptables -L FORWARD -n -v --line-numbers' # FORWARD rules
alias ufw-log='journalctl -f -n 100 -g ufw' # Show UFW log entries in system journal
# Kernel actions
alias kernel-recompile='cd /usr/src/linux && make -j7 && make -j7 modules_install && make install'
alias kernel-oldconfig='cd /usr/src/linux && make oldconfig'
alias kernel-configure='cd /usr/src/linux && make menuconfig'
# System actions
alias sv='systemctl'
alias pacnew="find / -name '*.pacnew' 2>/dev/null" # Search for all new configurations after pacman update
alias backup="rsync -avHAXS --delete --filter='dir-merge /.rsync-filter'" # Make full rsync backup, respecting .rsync-filter files for exclusions
alias upload='curl -F "f:1=<-" ix.io'
alias upload-journal='sudo journalctl -b -1 | upload' # Upload journalctl from last boot to ix.io
alias auth-log='journalctl SYSLOG_FACILITY=10 -r'
alias cpu-stress='for i in $(seq $(getconf _NPROCESSORS_ONLN)); do yes > /dev/null & done' # Run `yes > /dev/null` on all cores as stress test
alias nvidia='__NV_PRIME_RENDER_OFFLOAD=1 __GLX_VENDOR_LIBRARY_NAME=nvidia' # Run app with nvidia (on hybrid mode with optimus)
alias swapout='sudo swapoff -a; sudo swapon -a' # Reset swap (move everything to RAM)
alias mount-ram='mount -t tmpfs tmpfs' # Mount RAM disk for fast filesystem
alias screenlock='xset s activate' # Use DPMS to trigger xss-lock and handle screen locking
# System info
alias meminfo='free -m -l -t'
alias cpuinfo='lscpu'
alias batinfo='sudo watch -d -n 2 tlp-stat -b'
alias battery='cat /sys/class/power_supply/BAT0/capacity'
alias gpumeminfo='frep -i --color memory /var/log/Xorg.0.log'
alias journalerr='sudo journalctl -p 3 -xb'
alias distro='cat /etc/*-release'
alias diskspace_report="df -P -kHl"
alias kernel='uname -r'
# System processes
alias psmem='ps auxf | sort -nr -k 4' # Top memory eaters
alias psmem10='psmem | head -10' # Top 10 memory eaters
alias pscpu='ps auxf | sort -nr -k 3' # Top cpu eaters
alias pscpu10='pscpu | head -10' # Top 10 cpu eaters
alias psg='ps aux | grep -v grep | grep -i -e VSZ -e' # Get searchable process with nice output
# Time info
alias now='date +"%T"'
alias nowtime='now'
alias nowdate='date +"%d-%m-%Y"'
alias week='date +%V'
# Cleanup
alias clean-trash='rm -rf ~/.local/share/Trash/* || echo "Trash already empty"'
alias clean-downloads='rm -rf ~/Downloads/* || echo "Downloads directory is already empty"'
alias clean-journal='journalctl --vacuum-size=200M || echo "You have to be root to clean journal"'
alias clean-pacman='pacman -Sc || echo "You have to be root to clean pacman cache"'
alias cleanup='clean-trash && clean-down && clean-journal && clean-pacman'
# Git aliases
alias g='git'
alias gp='git push'
alias gpl='git pull'
alias gf='git fetch'
alias gs='git status --short --branch'
alias gss='git status'
alias ga='git add'
alias gap='git add --patch'
alias gc='git commit'
alias gcm='git commit --message'
alias gb='git branch'
alias gch='git checkout'
alias gchb='git checkout -b'
alias gd='git diff'
alias gdc='git diff --cached'
alias gundo='git reset --soft HEAD~'
alias gredo="git reset 'HEAD@{1}'"
# Youtube-dl aliases
alias ytv-best='youtube-dl -f bestvideo+bestaudio'
alias yta-best='youtube-dl --extract-audio --audio-format best'
alias yta-mp3='youtube-dl --extract-audio --audio-format mp3'
alias yta-wav='youtube-dl --extract-audio --audio-format wav'
# Terminal vim-like exits, in case I think the terminal is vim
alias :q='exit'
alias :q!='exit'
alias :wq='exit'
alias :wq!='exit'
# Shell aliases
alias reload="exec \$SHELL" # Reload the shell (i.e. invoke as a login shell)
alias path='echo -e ${PATH//:/\\n}' # Print each PATH entry on a separate line
alias unsudo='sudo -k' # Reset sudo timeout (sudo will require password)
alias vimwiki='vim -c VimwikiIndex' # Open vimwiki index
alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"'
alias tty-clock='tty-clock -Ssc' # Terminal clock screensaver
alias rick='curl -s -L https://raw.githubusercontent.com/ItsDrike/rickrollrc/master/roll.sh| bash' # Terminal rickroll
alias hist='fc -lt "$HISTTIMEFORMAT" 1'
alias sudovim='sudoedit'
# If user is not root, pass all commands via sudo/doas
if [ "$(id -u)" -ne 0 ]; then
# Enable aliases to be sudoed/doased
# with doas having precedence over sudo if found
## Uncomment if you are using autocompletion (is ZSH)
#command -v /usr/bin/sudo > /dev/null && alias doas='nocorrect sudo ' && alias sudo='nocorrect sudo '
#command -v /usr/bin/doas > /dev/null && alias doas='nocorrect doas ' && alias sudo='nocorrect doas '
## if the above is uncommented, comment this
command -v /usr/bin/sudo > /dev/null && alias doas='sudo ' && alias sudo='sudo '
command -v /usr/bin/doas > /dev/null && alias doas='doas ' && alias sudo='doas '
fi
# enable color support
if [ -x /usr/bin/dircolors ]; then
(test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)") || eval "$(dircolors -b)"
alias dir='dir --color=auto'
alias vdir='vdir --color=auto'
alias grep='grep --color=auto'
alias cgrep='grep --color=always'
alias fgrep='fgrep --color=auto'
alias egrep='egrep --color=auto'
alias diff='diff --color=auto'
alias ip='ip --color=auto'
# Take advantage of $LS_COLORS for completion as well
zstyle ':completion:*' list-colors "${(s.:.)LS_COLORS}"
fi
# Normalize `open` across Linux, macOS, and Windows.
# This is needed to make `open` function (see below) cross-platform
if [ ! "$(uname -s)" = 'Darwin' ]; then
if grep -q Microsoft /proc/version; then
# Ubuntu on Windows using the Linux subsystem
alias open='explorer.exe'
else
alias open='xdg-open'
fi
fi
# Autogenerate python aliases
if [ -f ~/.config/shell/py-alias ]; then
# shellcheck source=/home/itsdrike/.config/shell/py-alias
. "$HOME/.config/shell/py-alias"
fi
# Functions
if [ -f ~/.config/shell/functions ]; then
# shellcheck source=/home/itsdrike/.config/shell/functions
. "$HOME/.config/shell/functions"
fi
# Extra
if [ -f ~/.config/shell/extra ]; then
# shellcheck source=/home/itsdrike/.config/shell/extra
. "$HOME/.config/shell/extra"
fi

78
home/.config/shell/environment Executable file
View file

@ -0,0 +1,78 @@
#!/bin/sh
# Environmental variable definitions.
# This file is only sourced once after login, unlike .zshrc/.bashrc
#
# NOTE: This file shouldn't be defined for root account. Sudo
# will not source it (and neither will it source .zshrc/.zprofile),
# which means the XDG definitions will be ignored anyway, and
# defining them may break programs when root is actually logged in.
# Define some variables for POSIX compatibility
uid="$(id -u)"
# Default programs
export EDITOR="nvim"
export BROWSER="firefox"
export TERMINAL="alacritty"
export DIFFPROG="nvim -d"
export FILEMANAGER="pcmanfm"
# XDG Standard paths
export XDG_CONFIG_HOME="$HOME/.config"
export XDG_CACHE_HOME="$HOME/.cache"
export XDG_DATA_HOME="$HOME/.local/share"
export XDG_RUNTIME_DIR="/run/user/$uid"
# Per-Application XDG settings
export ZDOTDIR="$XDG_CONFIG_HOME/zsh"
export XINITRC="$XDG_CONFIG_HOME/x11/xinitrc"
#export XAUTHORITY="$XDG_RUNTIME_DIR/Xauthority" # This line will break some DMs.
export LESSHISTFILE="-"
export GTK2_RC_FILES="$XDG_CONFIG_HOME/gtk-2.0/gtkrc"
export WGETRC="$XDG_CONFIG_HOME/wget/wgetrc"
export GNUPGHOME="$XDG_DATA_HOME/gnupg"
export GOPATH="$XDG_DATA_HOME/go"
export CARGO_HOME="$XDG_DATA_HOME/cargo"
export RUSTUP_HOME="$XDG_DATA_HOME/rustup"
export GRADLE_USER_HOME="$XDG_DATA_HOME/gradle"
export _JAVA_OPTIONS="-Djava.util.prefs.userRoot=$XDG_CONFIG_HOME/java"
export NPM_CONFIG_USERCONFIG="$XDG_CONFIG_HOME/npm/npmrc"
export NUGET_PACKAGES="$XDG_CACHE_HOME/NuGetPackages"
# Less commonly used applications
export _ZL_DATA="$XDG_DATA_HOME/zlua"
export SQLITE_HISTORY="$XDG_DATA_HOME/sqlite_history"
export WAKATIME_HOME="$XDG_CONFIG_HOME/wakatime"
export IPYTHONDIR="$XDG_CONFIG_HOME/ipython"
export PYENV_ROOT="$XDG_DATA_HOME/pyenv"
export MYPY_CACHE_DIR="$XDG_CACHE_HOME/mypy"
#export PYLINTHOME="$XDG_CACHE_HOME/pylint"
#export DOCKER_CONFIG="$XDG_CONFIG_HOME/docker"
#export CUDA_CACHE_PATH="$XDG_CACHE_HOME/nv"
# Colorful man pages
# If bat is installed, use it as manpager
# shellcheck disable=SC2155
if command -v bat > /dev/null; then
export MANPAGER="sh -c 'col -bx | bat -l man -p'"
else
export LESS_TERMCAP_mb="$(printf '%b' '[1;31m')"
export LESS_TERMCAP_md="$(printf '%b' '[1;36m')"
export LESS_TERMCAP_me="$(printf '%b' '[0m')"
export LESS_TERMCAP_so="$(printf '%b' '[01;44;33m')"
export LESS_TERMCAP_se="$(printf '%b' '[0m')"
export LESS_TERMCAP_us="$(printf '%b' '[1;32m')"
export LESS_TERMCAP_ue="$(printf '%b' '[0m')"
fi
# Other program settings
export HISTTIMEFORMAT="%Y-%m-%d %T "
export SUDO_ASKPASS="$HOME/.local/bin/scripts/dmenu/dmenupass"
export PIPENV_VENV_IN_PROJECT=1 # Force pipenv to create new environments within projects ./.venv
export XSECURELOCK_SHOW_HOSTNAME=0 # Don't show hostname in xsecurelock
export XSECURELOCK_SHOW_DATETIME=1 # Show current date and time in xsecurelock
export QT_QPA_PLATFORMTHEME="qt5ct" # Have QT use theme from qt5ct.
#export QT_STYLE_OVERRIDE="gtk2" # Have QT use the gtk2 theme (needs aur/qt5-styleplugins)
# Remove irrelevant variables added for posix compatibility
unset posix

245
home/.config/shell/extra Executable file
View file

@ -0,0 +1,245 @@
#!/usr/bin/env zsh
# ----------------------------------------------------------------
# Additional aliases
alias cfextra='vim ~/.config/shell/extra'
alias cflvim='lvim ~/.config/lvim/config.lua'
alias cfgit='vim ~/.config/git/config'
alias cfhypr="vim ~/.config/hypr/hyprland.conf"
alias cfwaybar='vim ~/.config/waybar/config-hypr'
alias dotsync='git checkout arch && git push && git checkout gentoo && git merge --ff arch && git push && git checkout arch'
alias kbsk='setxkbmap sk qwerty'
alias kbus='setxkbmap us'
alias update-webpage='ssh webpage "cd /var/www/itsdrike.com; git pull; ./scripts/build.sh"'
alias octave='octave --quiet'
alias savekern='cp /proc/vmcore /root/crash.dump'
alias discord-bump='sleep $((2*60*60)) && notify-send "Bump" "Bump time expired"'
alias svim='nvim'
alias vim='lvim'
alias vpn-home='sudo systemctl stop wg-quick@wgivpn && sudo systemctl start wg-quick@wg0'
alias vpn-ivpn='sudo systemctl stop wg-quick@wg0 && sudo systemctl start wg-quick@wgivpn'
alias vpn-wg0='vpn-home'
alias vpn-wgivpn='vpn-ivpn'
alias vpn-off='sudo systemctl stop wg-quick@wg0 && sudo systemctl stop wg-quick@wgivpn'
alias spotify-adblock='env LD_PRELOAD=/usr/lib/spotify-adblock.so spotify'
alias mono-on='pacmd load-module module-remap-sink sink_name=mono master=2 channels=1'
alias mono-off='pacmd unload-module module-remap-sink'
# ----------------------------------------------------------------
# Additional functions
git-uni() {
git config --local commit.gpgsign false
git config --local user.email "p_vacho@utb.cz"
git config --local user.name "Peter Vacho"
}
dot-sync() {
target="$(realpath -s "$1")"
if [[ "$target" == "$HOME/"* ]]; then
rel_path="$(realpath --relative-to="$HOME" "$target")"
dot_target="$dothome/$rel_path"
else
rel_path="$(realpath --relative-to="/" "$target")"
dot_target="$dotroot/$rel_path"
fi
>&2 echo "Would copy $target -> $dot_target"
if [[ -d "$target" ]]; then
rsync -av --delete "${@:2}" "$target/" "$dot_target"
else
rsync -av "${@:2}" "$target" "$dot_target"
fi
}
pytemp() {
dir="$(mktemp --tmpdir=/tmp -d "tmp.pytemp.XXXXXX")"
pushd "$dir" >/dev/null
yes "" | poetry init
cp ~/Personal/Programming/Python/Templates/GitHub/.flake8 .
sed -i 's/project_name/src/' ./.flake8
poetry add --dev flake8 black isort pyright # also performs install
mkdir ./src
touch ./src/__init__.py
echo "def main():\n ...\n\n" > ./src/__main__.py
echo "if __name__ == \"__main__\":\n main()" >> ./src/__main__.py
poetry run lvim +2 -c 'execute "normal $ciw" | startinsert!' ./src/__main__.py
popd
rm -rf "$dir"
}
setuppy(){
cp -r "/home/itsdrike/Personal/Programming/Python/Templates/GitHub" "$1"
cd "$1"
git init
poetry update
poetry install
echo "TODO" >> .gitignore_local
poetry shell
# Show all places where we used "project_name", these are expected to be renamed
grep -RHIni --exclude-dir=.venv project_name
}
webpage-put(){
scp $@ webpage:/var/www/itsdrike.com/etc
}
webpage-remove(){
sftp webpage:/var/www/itsdrike.com/etc <<< "rm $@"
}
vidtrim(){
if [ $# -ne 3 ]; then
echo "Invalid number of parameters passed!"
echo "Usage: vidtrim [file name] [start time] [end time]"
return 1
fi
no_ext_name=$1:r
ext=$1:e
i=1
while true; do
new_name="${no_ext_name}-trimmed-${i}.${ext}"
if [ -e "$new_name" ]; then
i=$((i + 1))
else
break
fi
done
ffmpeg -ss "$2" -i "$1" -to "$3" -c copy -copyts "$new_name"
}
vidmerge(){
if [ $# -lt 3 ]; then
echo "Invalid number of parameters passed!"
echo "Usage: vidmerge [input path 1] [input path 2] [optionally more inputs ...] [output name]"
echo "Example: vidmerge . REC-2020-05-.*.mp4 output.mp4"
return 1
fi
# Parse the input
first_file="$1"
files="$2"
out="$3"
shift; shift; shift
# Process extra filenames, in case there's more than 2 to merge
while [ $# -gt 0 ]; do
files="$files\n$out"
out="$1"
shift
done
# Prefer MP4Box over ffmpeg if installed
# this is benefitial because merging with ffmpeg results in files with
# messed up timeline (the file will be a merge product of all given files,
# but the timeline will suddenly skip i.e. from 10s to 50s seemlessly, resulting
# in proper merge, but with weird timeline info)
if ! command -v MP4Box >/dev/null 2>&1; then
files="$first_file\n$files"
# Create file with all of the file paths to concat for ffmpeg
substring="'"
if test "${files#*$substring}" != "$files"; then
echo "Can't handle files with $substring in their names!"
return 1
fi
loc="files.txt"
echo "$files" | while IFS= read -r line; do
printf "file '%s'\n" "$line" >> "$loc"
done
if ffmpeg -f concat -safe 0 -i "$loc" -c copy "$out"; then
rm "$loc"
else
echo "Ffmpeg failed, check '$loc' file, containing the files passed to ffmpeg"
fi
else
cat_list="$(echo "$files" | xargs -d '\n' printf -- '-cat "%s" ')"
cmd="MP4Box -add \"$first_file\" $cat_list \"$out\""
echo "$cmd"
if eval "$cmd"; then
echo "Video merge complete, generated output: $out"
else
echo "MP4Box failed, used cmd: $cmd"
fi
fi
}
vidrot(){
if [ $# -ne 2 ]; then
echo "Invalid number of parameters passed!"
echo "Usage: vidrot [video file] [rotation (0/1/2/3)]"
echo "0: cclock_flip (90° counterclockwise and vertical flip)"
echo "1: clock (90° clockwise)"
echo "2: cclock (90° counterclockwise)"
echo "3: clock_flip (90° clockwise and vertical flip)"
return 1
fi
name="$1"
rotation="$2"
no_ext_name=$name:r
ext=$name:e
editname="${no_ext_name}-rot.${ext}"
ffmpeg -i "$name" -vf "transpose=$rotation" "$editname"
}
# ----------------------------------------------------------------
# Additional exports
export dothome="$HOME/Personal/dotfiles/home"
export dotroot="$HOME/Personal/dotfiles/root"
export dotvim="$dothome/.config/nvim"
# ----------------------------------------------------------------
# Pacman/Emerge
if command -v pacman > /dev/null; then
alias pkg-info='pacman -Si' # Info about a package in sync index
alias pkg-info-local='pacman -Qi' # Same as above, but for locally installed pkgs
alias pkg-file-owner='pacman -F' # Show package that owns given file in sync index
alias pkg-file-owner-regex='pacman -Fx' # Same as above, but works with partial names/regex
alias pkg-file-owner-local='pacman -Qo' # Same as above, but for locally installed pkgs
alias pkg-owned-files='pacman -Fl' # Show all files owned by given package in sync index
alias pkg-owned-files-local='pacman -Ql' # Same as above 2, but for locally installed pkgs
alias pkg-group-list='pacman -Sg' # List all pkgs that will be installed with a group
alias pkg-group-list-local='pacman -Qg' # Same as above, but from locally installed pkgs
alias pkg-orphans='pacman -Qtdq'
alias pkg-get-upgrades='pacman -Syyuw' # Download new pkgs, but don't upgrade them
alias pkg-extract='pacman -Syw --cachedir .' # Download given pkg to current directory
alias pkg-clean-cache='pacman -Sc' # Remove old packages in pacman cache
alias pkg-vuln-upgrade="pacman -Sy \"\$(arch-audit --upgradable --quiet | awk '{sub(/>=.+/, \"\"); print}' | paste -s -d ' ')\"" # Upgrade all vulnerable packages, with released fixes
alias vuln='arch-audit' # Show vulnerable packages that can be upgraded (Arch Linux)
# Get fastest mirrors (using reflector)
alias mirror="sudo reflector -f 30 -l 30 --number 10 --verbose --save /etc/pacman.d/mirrorlist"
alias mirrord="sudo reflector --latest 50 --number 20 --sort delay --save /etc/pacman.d/mirrorlist"
alias mirrors="sudo reflector --latest 50 --number 20 --sort score --save /etc/pacman.d/mirrorlist"
alias mirrora="sudo reflector --latest 50 --number 20 --sort age --save /etc/pacman.d/mirrorlist"
fi
if command -v emerge > /dev/null; then
if command -v eix > /dev/null; then
alias pkg-sync='eix-sync'
alias pkg-search='eix'
else
alias pkg-sync='emerge --sync --quiet=n'
alias pkg-search='emerge -s'
fi
alias pkg-update='emerge --update --deep @world'
alias pkg-upgrade='pkg-sync && pkg-update'
alias pkg-changed-use='pkg-update --changed-use'
alias pkg-recompile-all='emerge -e @world'
alias pkg-which='equery which'
alias pkg-size='equery size'
alias pkg-depgraph='equery depgraph'
alias pkg-depends='equery depends'
alias pkg-check='equery check'
alias pkg-uses='equery uses'
alias pkg-keywords='equery keywords'
alias update-conf='dispatch-conf'
fi

291
home/.config/shell/functions Executable file
View file

@ -0,0 +1,291 @@
#!/bin/sh
# TODO: Currently, this file isn't entirely POSIX compatible,
# it will run fine with bash or zsh, however some functions may cause
# issues with pure POSIX. The fill will however run fine, the errors
# would only occur if the incompatible functions would be started.
# Show application listening on given port
port() {
sudo netstat -pln | grep "$1" | awk '{print $NF}'
}
# Create a new directory and enter it
mkd() {
# shellcheck disable=SC2164
mkdir -p "$1" && cd "$1";
}
# `o` with no arguments opens the current directory, otherwise opens the given
# location
o() {
if [ $# -eq 0 ]; then
open .;
else
open "$@";
fi;
}
# Use bat for nicer git diffs
batdiff() {
git diff --name-only --diff-filter=d | xargs bat --diff
}
# Determine size of a file or total size of a directory
dirsize() {
if du -b /dev/null > /dev/null 2>&1; then
arg=-sbh;
else
arg=-sh;
fi
if [[ -n "$*" ]]; then
\du $arg -- "$@";
else
\du $arg .[^.]* ./*;
fi;
}
randmac() {
sudo ip link set dev "$1" down
sudo macchanger -A "$1"
sudo ip link set dev "$1" up
}
# Go to the root of a git tree
cdgit () {
if [ "$(git rev-parse --is-inside-work-tree > /dev/null 2>&1)" -eq 0 ]; then
while ! [ -d .git ]; do
cd ..
done
return 0
else
echo "Not a git directory"
return 1
fi
}
# Create a data URL from a file
dataurl() {
mimeType="$(file -b --mime-type "$1")"
if echo "$mimeType" | grep -e "^text/.*$" >/dev/null; then
mimeType="${mimeType};charset=utf-8"
fi
echo "data:${mimeType};base64,$(openssl base64 -in "$1" | tr -d '\n')";
}
# `tre` is a shorthand for `tree` with hidden files and color enabled, ignoring
# the `.git` directory, listing directories first. The output gets piped into
# `less` with options to preserve color and line numbers, unless the output is
# small enough for one screen.
tre() {
tree -I '.git|node_modules|bower_components' --group-directories-first "$@" | less -FRNX;
}
# Show all the names (CNs and SANs) listed in the SSL certificate
# for a given domain
getcertnames() {
if [ -z "${1}" ]; then
echo "ERROR: No domain specified.";
return 1;
fi;
domain="${1}";
echo "Testing ${domain}…";
echo ""; # newline
tmp=$(echo -e "GET / HTTP/1.0\nEOT" \
| openssl s_client -connect "${domain}:443" -servername "${domain}" 2>&1);
if [[ "${tmp}" = *"-----BEGIN CERTIFICATE-----"* ]]; then
certText=$(echo "${tmp}" \
| openssl x509 -text -certopt "no_aux, no_header, no_issuer, no_pubkey, \
no_serial, no_sigdump, no_signame, no_validity, no_version");
echo "Common Name:";
echo ""; # newline
echo "${certText}" | grep "Subject:" | sed -e "s/^.*CN=//" | sed -e "s/\/emailAddress=.*//";
echo ""; # newline
echo "Subject Alternative Name(s):";
echo ""; # newline
echo "${certText}" | grep -A 1 "Subject Alternative Name:" \
| sed -e "2s/DNS://g" -e "s/ //g" | tr "," "\n" | tail -n +2;
return 0;
else
echo "ERROR: Certificate not found.";
return 1;
fi;
}
# Compare original and gzipped file size
gz_compare() {
origsize=$(wc -c < "$1");
gzipsize=$(gzip -c "$1" | wc -c);
ratio=$(echo "$gzipsize * 100 / $origsize" | bc -l);
printf "orig: %d bytes\n" "$origsize";
printf "gzip: %d bytes (%2.2f%%)\n" "$gzipsize" "$ratio";
}
# Extract almost any archive
extract() {
if [ -z "$1" ]; then
# display usage if no parameters given
echo "Usage: extract <path/file_name>.<zip|rar|bz2|gz|tar|tbz2|tgz|Z|7z|xz|ex|tar.bz2|tar.gz|tar.xz>"
echo " extract <path/file_name_1.ext> [path/file_name_2.ext] [path/file_name_3.ext]"
return 1
else
for n in "$@"
do
if [ -f "$n" ] ; then
case "${n%,}" in
*.tar.bz2|*.tar.gz|*.tar.xz|*.tbz2|*.tgz|*.txz|*.tar)
tar xvf "$n" ;;
*.lzma) unlzma ./"$n" ;;
*.bz2) bunzip2 ./"$n" ;;
*.rar) unrar x -ad ./"$n" ;;
*.gz) gunzip ./"$n" ;;
*.zip) unzip ./"$n" ;;
*.z) uncompress ./"$n" ;;
*.7z|*.arj|*.cab|*.chm|*.deb|*.dmg|*.iso|*.lzh|*.msi|*.rpm|*.udf|*.wim|*.xar)
7z x ./"$n" ;;
*.xz) unxz ./"$n" ;;
*.exe) cabextract ./"$n" ;;
*)
echo "extract: '$n' - unknown archive method"
return 1
;;
esac
else
echo "'$n' - file does not exist"
return 1
fi
done
fi
}
# Create a .tar.gz archive, using `zopfli`, `pigz` or `gzip` for compression
targz() {
# Combine given names spearated with spaces as the filename
tmpFile="${*%/}.tar"
tar -cvf "${tmpFile}" "${@}" || return 1
size=$(
stat -f"%z" "${tmpFile}" 2> /dev/null; # macOS `stat`
stat -c"%s" "${tmpFile}" 2> /dev/null; # GNU `stat`
);
cmd="";
if (( size < 52428800 )) && hash zopfli 2> /dev/null; then
# the .tar file is smaller than 50 MB and Zopfli is available; use it
cmd="zopfli";
else
if hash pigz 2> /dev/null; then
cmd="pigz";
else
cmd="gzip";
fi;
fi;
echo "Compressing .tar ($((size / 1000)) kB) using \`${cmd}\`…";
"${cmd}" -v "${tmpFile}" || return 1;
[ -f "${tmpFile}" ] && rm "${tmpFile}";
zippedSize=$(
stat -f"%z" "${tmpFile}.gz" 2> /dev/null; # macOS `stat`
stat -c"%s" "${tmpFile}.gz" 2> /dev/null; # GNU `stat`
);
echo "${tmpFile}.gz ($((zippedSize / 1000)) kB) created successfully.";
}
anonymize() {
# Reset the prompt on initial run to allow this script
# to be ran multiple times without user having to reload
# PS1 manually
# shellcheck source=/home/itsdrike/.config/shell/prompt
. "${XDG_CONFIG_DIR:-$HOME/.config}/shell/prompt"
# Regular expression to match 0-255 numbers (color)
color_int_re='^(0+)?([0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])$'
# Defaults
NAME="%n"
MACHINE=""
#NAME_COLOR="%F{047}"
NAME_COLOR="%F{172}"
#DIR_COLOR="%F{027}"
DIR_COLOR="%F{158}"
AT_COLOR="%F{004}"
MACHINE_COLOR="%F{070}"
while [ $# -gt 0 ]; do
key=$1
case $key in
-n|--name)
NAME=$2
shift
shift
;;
-m|--machine)
MACHINE=$2
shift
shift
;;
-nc|--name-color)
if [[ $2 =~ $color_int_re ]]; then
NAME_COLOR="%F{$2}"
else
NAME_COLOR=$2
fi
shift
shift
;;
-dc|--dir-color)
if [[ $2 =~ $color_int_re ]]; then
DIR_COLOR="%F{$2}"
else
DIR_COLOR=$2
fi
shift
shift
;;
-mc|--machine-color)
if [[ $2 =~ $color_int_re ]]; then
MACHINE_COLOR="%F{$2}"
else
MACHINE_COLOR=$2
fi
shift
shift
;;
-ac|--at-color)
if [[ $2 =~ $color_int_re ]]; then
AT_COLOR="%F{$2}"
else
AT_COLOR=$2
fi
shift
shift
;;
*)
echo "Unrecognized argument: $key"
echo "Arguments: -n|--name, -m|--machine, -nc|--name-color, -dc|--dir-color, -mc|--machine-color, -ac|--at-color"
return 1
;;
esac
done
OLD_LINE="%F{047}%n%f %F{027}"
[ -n "$NAME" ] && NEW_LINE="${NAME_COLOR}${NAME}"
[ -n "$NAME" ] && [ -n "$MACHINE" ] && NEW_LINE="${NEW_LINE}${AT_COLOR}@"
[ -n "$MACHINE" ] && NEW_LINE="${NEW_LINE}${MACHINE_COLOR}${MACHINE}"
[ -n "$NAME" ] || [ -n "$MACHINE" ] && NEW_LINE="${NEW_LINE}%f "
NEW_LINE="${NEW_LINE}${DIR_COLOR}"
# Use new anonymized name, machine and colors in PS1
PS1=${PS1/"$OLD_LINE"/"$NEW_LINE"}
}

40
home/.config/shell/handlers Executable file
View file

@ -0,0 +1,40 @@
#!/bin/sh
if command -v pkgfile > /dev/null; then
# Command not found hook that uses `pkgfile` package
# to search through the package index in order to find
# a package which includes given command, which was resolved
# and not found, if there are no such packages, only print
# command not found message
command_not_found_handler() {
cmd="$1"
printf 'zsh: command not found: %s' "$cmd" # print command not found asap, then search for packages
repos="$(pkgfile "$cmd")"
if [ -n "$repos" ]; then
printf '\r%s may be found in the following packages:\n' "$cmd"
echo "$repos" | while read -r pkg; do
printf ' %s\n' "$pkg"
done
else
printf '\n'
fi
return 127
}
elif [ -x /usr/lib/command-not-found ] || [ -x /usr/share/command-not-found/command-not-found ]; then
# Ubuntu handle for bash default command-not-found
# it works similarely to the above arch alternative,
# this is based on the original bash implementation
command_not_found_handler() {
# check because cmd not found could've been removed in the meantime
if [ -x /usr/lib/command-not-found ]; then
/usr/lib/command-not-found -- "$1"
return $?
elif [ -x /usr/share/command-not-found/command-not-found ]; then
/usr/share/command-not-found/command-not-found -- "$1"
return $?
else
printf "%s: command not found\n" "$1" >&2
return 127
fi
}
fi

65
home/.config/shell/keybinds Executable file
View file

@ -0,0 +1,65 @@
#!/usr/bin/env zsh
# shellcheck disable=SC2030,SC2031,SC2015
# Set default keybindings (mostly from oh-my-zsh)
# Make sure that the terminal is in application mode when zle is active, since
# only then values from $terminfo are valid
if (( ${+terminfo[smkx]} )) && (( ${+terminfo[rmkx]} )); then
function zle-line-init() {
echoti smkx
}
function zle-line-finish() {
echoti rmkx
}
zle -N zle-line-init
zle -N zle-line-finish
fi
# Use emacs keybindings
bindkey -e
# Start typing + [Up-Arrow] - fuzzy find history forward
if [ -n "${terminfo[kcuu1]}" ]; then
autoload -U up-line-or-beginning-search
zle -N up-line-or-beginning-search
bindkey "${terminfo[kcuu1]}" up-line-or-beginning-search
fi
# Start typing + [Down-Arrow] - fuzzy find history backward
if [ -n "${terminfo[kcud1]}" ]; then
autoload -U down-line-or-beginning-search
zle -N down-line-or-beginning-search
bindkey "${terminfo[kcud1]}" down-line-or-beginning-search
fi
# [Home] - Go to beginning of line
[ -n "${terminfo[khome]}" ] && bindkey "${terminfo[khome]}" beginning-of-line || bindkey "^[[H" beginning-of-line
# [End] - Go to end of line
[ -n "${terminfo[kend]}" ] && bindkey "${terminfo[kend]}" end-of-line || bindkey "^[[F" end-of-line
# [Shift-Tab] - move through the completion menu backwards
[ -n "${terminfo[kcbt]}" ] && bindkey "${terminfo[kcbt]}" reverse-menu-complete
# [Backspace] - delete backward
bindkey '^?' backward-delete-char
# [Delete] - delete forward
[ -n "${terminfo[kdch1]}" ] && bindkey "${terminfo[kdch1]}" delete-char || bindkey "^[[3~" delete-char
# [Ctrl-Delete] - delete whole forward-word
bindkey '^[[3;5~' kill-word
# [Ctrl-RightArrow] - move forward one word
bindkey '^[[1;5C' forward-word
# [Ctrl-LeftArrow] - move backward one word
bindkey '^[[1;5D' backward-word
# [Ctrl-r] - Search backward incrementally for a specified string. The string may begin with ^ to anchor the search to the beginning of the line.
bindkey '^r' history-incremental-search-backward
# [PageUp] - Up a line of history
[ -n "${terminfo[kpp]}" ] && bindkey "${terminfo[kpp]}" up-line-or-history
# [PageDown] - Down a line of history
[ -n "${terminfo[knp]}" ] && bindkey "${terminfo[knp]}" down-line-or-history
# [Space] - do history expansion on space
bindkey ' ' magic-space
# [ctrl+space] Accept suggestion from zsh-autosuggestions plugin
bindkey '^ ' autosuggest-accept

19
home/.config/shell/profile Executable file
View file

@ -0,0 +1,19 @@
#!/bin/sh
# User .profile definition.
# This file is only sourced once, after login, Unlike
# .zshrc/.bashrc, which will run whenever a new terminal
# is opened.
# Add all folders in ~/.local/bin into PATH
# Some window managers require this line to be in profile
# not in .zshenv
PATH+=":${$(find ~/.local/bin -type d | tr '\n' ':')%%:}"
# Start graphical session automatically on tty1 if startx is aviable
if [ "$(tty)" = "/dev/tty1" ] && [ "$UID" != 0 ]; then
if command -v Hyprland >/dev/null; then
! pidof -s Hyprland >/dev/null 2>&1 && launch-hypr
fi
fi

187
home/.config/shell/prompt Executable file
View file

@ -0,0 +1,187 @@
#!/usr/bin/env zsh
# shellcheck disable=SC2155
# Configuration variables:
# Once we are too deep in the filestructure, we can usually afford to shorten
# the whole working directory and only print something like ~/.../dir3/dir4/dir5
# instead of ~/dir1/dir2/dir3/dir4/dir5. If this isn't desired, set this to 0
USE_SHORTENED_WORKDIR=1
# Show how much time it took to run a command
CMD_TIME_SHOW=1
# Minimum units to show the time precision, if
# we use "s" (seconds), and the output took 0s,
# we don't print the output at all to avoid clutter.
# Same goes for any other units, however with "ms"
# (miliseconds), this is very unlikely
# Valid options: ms/s/m/h/d
CMD_TIME_PRECISION="s"
# Minimum time in miliseconds, to print the time took,
# if the command takes less than this amount of miliseconds,
# don't bother printing the time took, this is nice if you
# don't need to see how long commands like 'echo' took
# Setting this to 0 will always print the time taken
CMD_TIME_MINIMUM=100
# hide EOL sign ('%')
export PROMPT_EOL_MARK=""
# TTY (pure linux) terminal only has 8-bit color support
# (unless you change it in kernel), respect this and downgrade
# the color scheme accordingly (it won't look best, but it's
# still better than no colors)
if [ "$TERM" = "linux" ]; then
GREEN="%F{002}"
RED="%F{001}"
ORANGE="%F{003}"
BLUE="%F{004}"
LBLUE="%F{006}"
PURPLE="%F{005}"
else
GREEN="%F{047}"
RED="%F{196}"
ORANGE="%F{214}"
BLUE="%F{027}"
LBLUE="%F{075}"
PURPLE="%F{105}"
fi
RESET="%f"
# Signals git status of CWD repository (if any)
git_prompt() {
ref=$(command git symbolic-ref HEAD 2> /dev/null) || ref=$(command git rev-parse --short HEAD 2> /dev/null) || return 0
echo -n " $ORANGE${ref#refs/heads/}"
if [ -n "$(git status --short 2>/dev/null)" ]; then
echo "$RED+"
fi
}
# Adds @chroot or @ssh
foreign_prompt() {
if [ "$(awk '$5=="/" {print $1}' </proc/1/mountinfo)" != "$(awk '$5=="/" {print $1}' </proc/$$/mountinfo)" ]; then
echo -n "@${ORANGE}chroot"
elif [ -n "$SSH_CLIENT" ] || [ -n "$SSH_TTY" ]; then
echo -n "@${ORANGE}ssh"
fi
}
#nd Prints appropriate working directory
working_directory() {
# By default up to 5 directories will be tolerated before shortening
# After we surpass that, first directory (or ~) will be printed together with last 3
# This feature uses special symbol '…', but this isn't aviable when in TTY. Because
# of this, when we are in TTY, we fall back to longer '...'
if [ $USE_SHORTENED_WORKDIR != 1 ]; then
echo -n " $BLUE$~"
elif [ "$TERM" = "linux" ]; then
echo -n " $BLUE%(5~|%-1~/.../%3~|%4~)"
else
echo -n " $BLUE%(5~|%-1~/…/%3~|%4~)"
fi
}
# Execution time tracking hooks, this is unique to zsh, as it can add
# preexec and precmd hooks. We can utilize this to keep track of the
# amount of time it took to run certain command. We store the start time
# within a variable: PROMPT_EXEC_TIME_START, which we then compare and
# unset after the command was finished. In here, we simply set the
# PROMPT_EXEC_TIME_DURATION, which is then used in the actual prompt
# This will only be enabled if SHOW_CMD_TIME is 1.
exec_time_preexec_hook() {
[[ $SHOW_CMD_TIME == 0 ]] && return
PROMPT_EXEC_TIME_START=$(date +%s.%N)
}
exec_time_precmd_hook() {
[[ $SHOW_CMD_TIME == 0 ]] && return
[[ -z $PROMPT_EXEC_TIME_START ]] && return
local PROMPT_EXEC_TIME_STOP="$(date +%s.%N)"
PROMPT_EXEC_TIME_DURATION=$(echo "($PROMPT_EXEC_TIME_STOP - $PROMPT_EXEC_TIME_START) * 1000" | bc -l)
unset PROMPT_EXEC_TIME_START
}
format_time() {
# Do some formatting to get nice time (e.g. 2m 12s) from miliseconds
# $1 is the milisecond amount (int or float)
# $2 is the precision (ms/s/m/h/d)
local T="$1"
local D="$(echo "scale=0;$T/1000/60/60/24" | bc -l)"
local H="$(echo "scale=0;$T/1000/60/60%24" | bc -l)"
local M="$(echo "scale=0;$T/1000/60%60" | bc -l)"
local S="$(echo "scale=0;$T/1000%60" | bc -l)"
local MS="$(echo "scale=0;$T%1000" | bc -l)"
local precision=$2
local out=""
case "$precision" in
"ms") [[ "$MS" -gt 0 ]] && out="$(printf "%dms" "$MS") ${out}"; precision="s" ;&
"s") [[ "$S" -gt 0 ]] && out="$(printf "%ds" "$S") ${out}"; precision="m" ;&
"m") [[ "$M" -gt 0 ]] && out="$(printf "%dm" "$M") ${out}"; precision="h" ;&
"h") [[ "$H" -gt 0 ]] && out="$(printf "%dh" "$H") ${out}"; precision="d" ;&
"d") [[ "$D" -gt 0 ]] && out="$(printf "%dd" "$D") ${out}" ;;
*) out="$T" ;; # Return $1 ($T) if precision wasn't specified/valid
esac
printf "%s" "$out"
}
display_cmd_time() {
[[ $CMD_TIME_SHOW == 0 ]] && return
[[ -z $PROMPT_EXEC_TIME_DURATION ]] && return
# If the time duration is less than minimum time,
# don't print the time taken
[[ $PROMPT_EXEC_TIME_DURATION -lt $CMD_TIME_MINIMUM ]] && return
local time_took="$(format_time "$PROMPT_EXEC_TIME_DURATION" "$CMD_TIME_PRECISION")"
# Don't display if the time didn't give us output
# this happens when all fields (seconds/minutes/...) are 0,
# if we use milisecond precision, this will likely never happen
# but with other precisions, it could
[ ${#time_took} -eq 0 ] && return
echo -n " ${LBLUE}took ${time_took}"
}
setopt promptsubst # enable command substitution in prompt
# Setup ZSH hooks to display the running time of commands
autoload -Uz add-zsh-hook
add-zsh-hook preexec exec_time_preexec_hook
add-zsh-hook precmd exec_time_precmd_hook
# Primary Prompt
[ "$EUID" -eq 0 ] && PS1="$RED%n$RESET" || PS1="$GREEN%n$RESET" # user
PS1+="$(foreign_prompt)"
PS1+="$(working_directory)"
PS1+="\$(git_prompt)"
PS1+="\$(display_cmd_time)"
PS1+=" $PURPLE%(!.#.$)$RESET " # Final symbol (# or $)
# Next line prompt
PS2="$RED\ $RESET"
# Right side prompt
RPS1=""
if [ "$TERM" = "linux" ]; then
# Displaying cmd time here works, but often causes issues when we
# resize the terminal, since right prompts can be annoying to deal
# with when resizing. This would run relatively often so it makes
# more sense to only use it in PS1 (left prompt), but if desired,
# this can be uncommented
#RPS1+="\$(display_cmd_time)"
# If we find a non-zero return code, print it in the right prompt,
# use X here, to avoid issues with TTY not having support for
# a nicer unicode character that we use otherwise ("↵")
RPS1+="%(?..${RED}%? X$RESET)"
else
# Read comments for the section above.
#RPS1+="\$(display_cmd_time)"
# NOTE: "↵" symbol could cause issues with on some terminals/machines that
# don't handle unicode well, this issue could be very confusing to debug,
# and it would not be apparent what's wrong since the symbol itself will
# be drawn, however when it is drawn, it will also move the cursor line
# 2 places back since this symbol is made up of 3 bytes (in unicode) and
# regular ASCII characters only take up 1 byte, this means that whenever
# the right-side prompt appears (on error), the prompt would have this issue.
RPS1="%(?..${RED}%? ↵$RESET)"
fi

196
home/.config/shell/py-alias Executable file
View file

@ -0,0 +1,196 @@
#!/usr/bin/env zsh
# Simple script which automatically defines certain aliases for python,
# which will automatically use certain python version
# Versions are automatically obtained from $PYENV_ROOT/versions directories
# NOTE: This assumes that all folders in this directory are valid python versions
#
# Assume we have these installed pyenv python versions 3.6.5, 3.6.12 and 3.10.1:
# - Set full-version aliases: py3.6.5, py3.6.12 and py3.10.1
# - Set py3 to 3.10.1 (latest with major version 3)
# - Set py3.6 to 3.6.12 (latest with major version 3 and minor version 6)
# - Set py3.10 to 3.10.1 (latest, and only python with major version 3 and minor version 10)
# Define all wanted aliases for a given python version
# $1 - full valid pyenv python version (for example '3.6.12', `3.11-dev`, or `pypy3.6-7.2.0-src`)
# $2 - version used in the alias (for example '3.6', '3', or even '', but also `pypy3.7`, ...)
define_aliases() {
version="$1"
alias_version="$2"
cmd_prefix="PYENV_VERSION=$version"
alias "py$alias_version=$cmd_prefix python"
alias "ipy$alias_version=$cmd_prefix ipython"
alias "bpy$alias_version=$cmd_prefix bpython"
alias "pydoc$alias_version=$cmd_prefix pydoc"
alias "pytest$alias_version=$cmd_prefix pytest"
alias -g "PY$alias_version=$cmd_prefix"
}
# Handle splitting full version into prefix, version number and suffix
# Because of the huge variaty of python implemenations and their different namings,
# this function will only be able to handle the default CPython version names,
# which follow the regex pattern of: '\d+\.\d+\.\d+', the rest will print 'full_version;;'
# In the future, this may also include support for some other naming schemes.
# $1 - full valid pyenv python version (for example '3.6.12', `3.11-dev`, or `pypy3.6-7.2.0-src`)
parse_python_version() {
full_version="$1"
if echo "$full_version" | grep -E "[0-9]+\.[0-9]+\.[0-9]+" >/dev/null; then
echo ";$full_version;"
else
echo ';;'
fi
}
# Prints version number extracted from alias for given version
# $1 - version used in the alias (for example '3.6', '3', or even '', but also 'pypy3.6', ...)
get_alias_version() {
alias_version="$1"
definition="$(alias "py$alias_version")"
full_version="$(echo "$definition" | cut -d= -f3 | cut -d' ' -f1)"
version_info="$(parse_python_version "$full_version")"
version="$(echo "$version_info" | cut -d';' -f2)"
echo "$version"
}
# Compares 2 python versions in major, minor and micro parts
# $1 - version #1
# $2 - version #2
# Returns:
# 0 - version #1 is newer
# 1 - version #2 is newer
# 2 - versions are equal
version_compare() {
version_1="$1"
version_2="$2"
# ZSH Only:
version_1=("${(@s:.:)version_1}")
version_2=("${(@s:.:)version_2}")
major_1=$version_1[1]
major_2=$version_2[1]
minor_1=$version_1[2]
minor_2=$version_2[2]
micro_1=$version_1[3]
micro_2=$version_2[3]
# POSIX, but slow:
# major_1="$(echo "$version_1" | cut -d. -f1)"
# major_2="$(echo "$version_2" | cut -d. -f1)"
# minor_1="$(echo "$version_1" | cut -d. -f2)"
# minor_2="$(echo "$version_2" | cut -d. -f2)"
# micro_1="$(echo "$version_1" | cut -d. -f3)"
# micro_2="$(echo "$version_2" | cut -d. -f3)"
# Compare majors
if [ $major_1 -gt $major_2 ]; then
# version 1's major is bigger, version 1 is newer
return 0
elif [ $major_1 -lt $major_2 ]; then
# version 1's major is smaller, version 2 is newer
return 1
fi
# Majors equal, compare minors
if [ $minor_1 -gt $minor_2 ]; then
# version 1's minor is bigger, version 1 is newer
return 0
elif [ $minor_1 -lt $minor_2 ]; then
# version 1's major is smaller, version 2 is newer
return 1
fi
# Minors equal, compare micros
if [ $micro_1 -gt $micro_2 ]; then
# version 1's micro is bigger, version 1 is newer
return 0
elif [ $micro_1 -lt $micro_2 ]; then
# version 1's micro is smaller, version 2 is newer
return 1
fi
# Micros equal, versions equal
return 2
}
# Define new aliases if they don't already exsist, in which case override
# if the current version is newer than the version in the alias
# $1 - full valid pyenv python version (for example '3.6.12', `3.11-dev`, or `pypy3.6-7.2.0-src`)
# $2 - version used in the alias (for example '3.6', '3', or even '', but also `pypy3.7`, ...)
try_define_aliases() {
version="$1"
alias_version="$2"
# Check if alias already exists
if alias "py$alias_version" >/dev/null; then
# Compare version from the existing alias with current version,
# if current is newer, override the existing alias(es)
defined_version="$(get_alias_version "$alias_version")"
if version_compare "$version" "$defined_version"; then
define_aliases "$version" "$alias_version"
# echo "Overwrote '$alias_version' aliases to point to '$version'"
return 0
else
return 1
fi
fi
# The aliases aren't already defined, it's safe to create them
define_aliases "$version" "$alias_version"
# echo "Made '$alias_version' aliases pointing to '$version'"
return 0
}
define_version_aliases() {
prefix="$1"
version="$2"
suffix="$3"
# ZSH only:
version_data=("${(@s:.:)version}")
major_version=$version_data[1]
minor_version=$version_data[2]
# POSIX, but slow:
# major_version="$(echo "$version" | cut -d. -f1)"
# minor_version="$(echo "$version" | cut -d. -f2)"
# Define the major.minor.micro (full) alias
try_define_aliases "$version" "$prefix$version$suffix"
# Define the major.minor alias
try_define_aliases "$version" "$prefix$major_version.$minor_version$suffix"
# Define the major alias
try_define_aliases "$version" "$prefix$major_version$suffix"
# Define top level alias
try_define_aliases "$version" "$prefix$suffix"
}
for python_dir in "$PYENV_ROOT"/versions/*/ ; do
full_version="$(basename $python_dir)"
version_info="$(parse_python_version "$full_version")"
if [ $version_info = ';;' ]; then
# Version info wasn't obtained successfully, skip this version
echo "Skipped $full_version"
continue
fi
# ZSH only:
version_data=("${(@s:;:)version_info}")
prefix=$version_data[1]
version=$version_data[2]
suffix=$version_data[3]
# POSIX, but slow:
# prefix="$(echo "$version_info" | cut -d';' -f1)"
# version="$(echo "$version_info" | cut -d';' -f2)"
# suffix="$(echo "$version_info" | cut -d';' -f3)"
# startTime=$(date +%N)
define_version_aliases "$prefix" "$version" "$suffix"
# endTime=$(date +%N)
# nanos="$(expr $endTime - $startTime)"
# echo "took $(expr $nanos / 1000000) miliseconds"
done
if command -v poetry >/dev/null 2>&1; then
alias poetry-pyenv='poetry env use "$(pyenv which python)" && poetry install'
fi