Refactor zsh, add aws-sharable-url shell alias

This commit is contained in:
arnie
2025-07-16 10:10:23 +02:00
parent b7ff5d4869
commit a7feabf2b8
13 changed files with 160 additions and 115 deletions
+159
View File
@@ -0,0 +1,159 @@
{
lib,
pkgs,
...
}:
let
isDarwin = pkgs.stdenv.hostPlatform.isDarwin;
isLinux = pkgs.stdenv.hostPlatform.isLinux;
in
{
programs.zsh = {
enable = true;
autocd = lib.mkDefault true;
history = {
expireDuplicatesFirst = true;
ignoreDups = true;
save = 10000;
share = false;
size = 10000;
};
shellAliases =
{
# use eval $(aws-export-credentials) to expose them to environment
aws-export-credentials = lib.mkDefault "${pkgs.awscli2}/bin/aws configure export-credentials --format env --profile";
aws-export-assume-role = lib.mkDefault "${pkgs.writeShellScript "aws-export-assume-role" ''
[[ -z "$1" || -z "$2" ]] && echo "Usage: aws-export-assume-role <profile> <role-arn>" && exit 1
${pkgs.coreutils}/bin/printf 'export AWS_ACCESS_KEY_ID=%s\nexport AWS_SECRET_ACCESS_KEY=%s\nexport AWS_SESSION_TOKEN=%s' $(${pkgs.awscli2}/bin/aws --profile "$1" sts assume-role --role-arn "$2" --role-session-name lcech --query "Credentials.[AccessKeyId,SecretAccessKey,SessionToken]" --output text)
''}";
# https://docs.aws.amazon.com/singlesignon/latest/userguide/createshortcutlink.html
aws-sharable-url = lib.mkDefault "${pkgs.writeShellScript "aws-sharable-url" ''
set -e
URL=$1
[[ -z "$URL" ]] && read -p "Enter URL: " URL
# Strip schema
URL="''${URL#https://}"
# Parse Account ID from multi-session URL
ACCOUNT_ID="''${URL%%-*}"
# Strip account ID and hash up to the region part
URL="''${URL#*\.}"
PROFILE=$(${pkgs.coreutils}/bin/grep "sso_account_id = $ACCOUNT_ID" ~/.aws/config -B 5 | ${pkgs.coreutils}/bin/grep "\[profile" | ${pkgs.coreutils}/bin/tail -n 1 | ${pkgs.coreutils}/bin/tr -d '[]')
PROFILE="''${PROFILE#profile }"
ROLE_NAME=$(${pkgs.awscli2}/bin/aws configure get profile.$PROFILE.sso_role_name)
SSO_SESSION=$(${pkgs.awscli2}/bin/aws configure get profile.$PROFILE.sso_session)
SSO_URL=$(${pkgs.coreutils}/bin/grep "\[sso-session $SSO_SESSION" ~/.aws/config -A5 | ${pkgs.coreutils}/bin/grep sso_start_url | ${pkgs.coreutils}/bin/head -n 1)
SSO_URL="''${SSO_URL#sso_start_url = }"
# Strip trailing slash from SSO_URL if present
SSO_URL="''${SSO_URL%/}"
SHARABLE_URL="$SSO_URL/#/console?account_id=$ACCOUNT_ID&role_name=$ROLE_NAME&destination=$(${pkgs.urlencode}/bin/urlencode "https://$URL")"
${if isDarwin then ''
echo -n "$SHARABLE_URL" | pbcopy
'' else ''
echo -n "$SHARABLE_URL" | ${pkgs.xclip}/bin/xclip -selection clipboard
''}
echo "URL copied to clipboard"
''}";
aws-s3-cp-public = lib.mkDefault ''
${pkgs.awscli2}/bin/aws s3 cp --acl "public-read" --expires "$(${pkgs.coreutils}/bin/date '+%a, %d %b %Y 00:00:00 GMT' -d "$(${pkgs.coreutils}/bin/date +%Y-%m-%d) + 365 day")" --cache-control "max-age=31536000" --metadata-directive REPLACE
'';
bcrypt = lib.mkDefault "${pkgs.writeShellScript "bcrypt" ''
if [[ -z "$1" ]]; then
echo "Usage: bcrypt <password> [cost]"
exit 1
fi
echo -n "$1" | ${pkgs.apacheHttpd}/bin/htpasswd -i -nB -C ''${2:-12} "" | tr -d ':'
''}";
cat = lib.mkDefault "${pkgs.bat}/bin/bat --paging=never";
# use curl-aws --aws-sigv4 "aws:amz:region:service"
curl-aws = lib.mkDefault "${pkgs.curl}/bin/curl -H \"X-Amz-Security-Token: $AWS_SESSION_TOKEN\" --user \"$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY\"";
curl-timing = lib.mkDefault "${pkgs.curl}/bin/curl -w \" time_namelookup: %{time_namelookup}s\n time_connect: %{time_connect}s\n time_appconnect: %{time_appconnect}s\n time_pretransfer: %{time_pretransfer}s\n time_redirect: %{time_redirect}s\n time_starttransfer: %{time_starttransfer}s\n ----------\n time_total: %{time_total}s\n\" -o /dev/null";
dbase64 = lib.mkDefault "${pkgs.writeShellScript "dbase64" "echo -n \"$1\" | base64 -d"}";
git-sync-remote = lib.mkDefault "git remote update origin --prune";
klogs = lib.mkDefault "${pkgs.writeShellScript "klogs" ''
ctx="$1"
shift
namespace="$1"
shift
label="$1"
shift
if [[ "$ctx" == "" || "$namespace" == "" || "$label" == "" ]]; then
echo "Usage: klogs context namespace label"
echo "${"\n"}Contexts:"
kubectl config get-contexts -o name | sed 's/^/\t/g'
echo "Label examples:"
echo "${"\t"}app.kubernetes.io/name=..."
echo "${"\t"}eks.amazonaws.com/component=..."
exit 1
fi
kubectl --context "$ctx" logs -f -n "$namespace" -l "$label" $@
''}";
nixfix = lib.mkDefault "nix fmt ./**/*.nix";
# Git
a = "git add";
c = "git commit -m";
d = "git diff";
d-s = "git diff --staged";
gtag = "${pkgs.writeShellScript "gtag" "git tag -a $1 -m '$2'"}";
gtag-replace = "${pkgs.writeShellScript "gtag" ''
msg=$(git tag -l -n9 $1 | sed "s/$1\s\+//g")
git tag -d $1 && \
git push origin :refs/tags/$1 && \
git tag -a $1 -m "$msg" && \
git push origin $1
''}";
gtagl = "git fetch --tags && git tag -l -n9 --sort=-v:refname";
s = "git status";
}
// (
if isDarwin then
{
hm-switch = lib.mkDefault "sudo darwin-rebuild switch --flake ~/.config/nix";
}
else if isLinux then
{
hm-switch = lib.mkDefault "home-manager switch --impure --flake ~/.config/nix";
}
else
{ }
);
initContent = lib.mkBefore ''
for file in ${./zsh}/*.zsh; do
source "$file"
done
# [Ctrl-RightArrow] - move forward one word
bindkey '^[[1;3C' forward-word
# [Ctrl-LeftArrow] - move backward one word
bindkey '^[[1;3D' backward-word
'';
};
}
+19
View File
@@ -0,0 +1,19 @@
autoload colors; colors
# The variables are wrapped in %{%}. This should be the case for every
# variable that does not contain space.
for COLOR in RED GREEN YELLOW BLUE MAGENTA CYAN BLACK WHITE; do
eval PR_$COLOR='%{$fg_no_bold[${(L)COLOR}]%}'
eval PR_BOLD_$COLOR='%{$fg_bold[${(L)COLOR}]%}'
done
eval RESET='$reset_color'
export PR_RED PR_GREEN PR_YELLOW PR_BLUE PR_WHITE PR_BLACK
export PR_BOLD_RED PR_BOLD_GREEN PR_BOLD_YELLOW PR_BOLD_BLUE
export PR_BOLD_WHITE PR_BOLD_BLACK
# Clear LSCOLORS
unset LSCOLORS
export CLICOLOR=1
export LS_COLORS=exfxcxdxbxegedabagacad
export LS_COLORS='rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=00:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.zst=01;31:*.tzst=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.jpg=01;35:*.jpeg=01;35:*.mjpg=01;35:*.mjpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.m4a=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.oga=00;36:*.opus=00;36:*.spx=00;36:*.xspf=00;36:';
+2
View File
@@ -0,0 +1,2 @@
LC_CTYPE=en_US.UTF-8
LC_ALL=en_US.UTF-8
+43
View File
@@ -0,0 +1,43 @@
# ===== Basics
# If you type foo, and it isn't a command, and it is a directory in your cdpath, go there
setopt AUTO_CD
# Allow comments even in interactive shells (especially for Muness)
# setopt INTERACTIVE_COMMENTS
# ===== History
# Allow multiple terminal sessions to all append to one zsh command history
setopt APPEND_HISTORY
# Add comamnds as they are typed, don't wait until shell exit
setopt INC_APPEND_HISTORY
# Do not write events to history that are duplicates of previous events
setopt HIST_IGNORE_DUPS
# When searching history don't display results already cycled through twice
setopt HIST_FIND_NO_DUPS
# Remove extra blanks from each command line being added to history
setopt HIST_REDUCE_BLANKS
# Include more information about when the command was executed, etc
setopt EXTENDED_HISTORY
# ===== Completion
# Allow completion from within a word/phrase
setopt COMPLETE_IN_WORD
# When completing from the middle of a word, move the cursor to the end of the word
setopt ALWAYS_TO_END
# ===== Prompt
# Enable parameter expansion, command substitution, and arithmetic expansion in the prompt
setopt PROMPT_SUBST
unsetopt MENU_COMPLETE
setopt AUTO_MENU
+69
View File
@@ -0,0 +1,69 @@
# add in zsh-completions
fpath=(~/zsh/completions $fpath)
autoload -U compinit && compinit
zmodload -i zsh/complist
# man zshcontrib
zstyle ':vcs_info:*' actionformats '%F{5}(%f%s%F{5})%F{3}-%F{5}[%F{2}%b%F{3}|%F{1}%a%F{5}]%f '
zstyle ':vcs_info:*' formats '%F{5}(%f%s%F{5})%F{3}-%F{5}[%F{2}%b%F{5}]%f '
zstyle ':vcs_info:*' enable git #svn cvs
# Enable completion caching, use rehash to clear
zstyle ':completion::complete:*' use-cache on
zstyle ':completion::complete:*' cache-path ~/.zsh/cache/$HOST
# Fallback to built in ls colors
zstyle ':completion:*' list-colors ''
# Make the list prompt friendly
zstyle ':completion:*' list-prompt '%SAt %p: Hit TAB for more, or the character to insert%s'
# Make the selection prompt friendly when there are a lot of choices
zstyle ':completion:*' select-prompt '%SScrolling active: current selection at %p%s'
# Add simple colors to kill
zstyle ':completion:*:*:kill:*:processes' list-colors '=(#b) #([0-9]#) ([0-9a-z-]#)*=01;34=0=01'
# list of completers to use
zstyle ':completion:*::::' completer _expand _complete _ignored _approximate
zstyle ':completion:*' menu select=1 _complete _ignored _approximate
# insert all expansions for expand completer
# zstyle ':completion:*:expand:*' tag-order all-expansions
# match uppercase from lowercase
zstyle ':completion:*' matcher-list 'm:{a-z}={A-Z}'
# offer indexes before parameters in subscripts
zstyle ':completion:*:*:-subscript-:*' tag-order indexes parameters
# formatting and messages
zstyle ':completion:*' verbose yes
zstyle ':completion:*:descriptions' format '%B%d%b'
zstyle ':completion:*:messages' format '%d'
zstyle ':completion:*:warnings' format 'No matches for: %d'
zstyle ':completion:*:corrections' format '%B%d (errors: %e)%b'
zstyle ':completion:*' group-name ''
# ignore completion functions (until the _ignored completer)
zstyle ':completion:*:functions' ignored-patterns '_*'
zstyle ':completion:*:scp:*' tag-order files users 'hosts:-host hosts:-domain:domain hosts:-ipaddr"IP\ Address *'
zstyle ':completion:*:scp:*' group-order files all-files users hosts-domain hosts-host hosts-ipaddr
zstyle ':completion:*:ssh:*' tag-order users 'hosts:-host hosts:-domain:domain hosts:-ipaddr"IP\ Address *'
zstyle ':completion:*:ssh:*' group-order hosts-domain hosts-host users hosts-ipaddr
zstyle '*' single-ignored show
# ZAW styles
zstyle ':filter-select:highlight' matched fg=yellow,standout
zstyle ':filter-select' max-lines 10 # use 10 lines for filter-select
zstyle ':filter-select' max-lines -10 # use $LINES - 10 for filter-select
zstyle ':filter-select' rotate-list yes # enable rotation for filter-select
zstyle ':filter-select' case-insensitive yes # enable case-insensitive search
zstyle ':filter-select' extended-search no # see below
# Docker autocompletion
zstyle ':completion:*:*:docker:*' option-stacking yes
zstyle ':completion:*:*:docker-*:*' option-stacking yes
+150
View File
@@ -0,0 +1,150 @@
# -*- mode: sh -*-
#
# manydots-magic - zle tweak for emulating "..."=="../.." etc.
#
# Copyright (c) 2011, 2012 Akinori MUSHA
# Licensed under the 2-clause BSD license.
#
# This tweek helps input ancestor directories beyond the parent (`..')
# in a handy way. You can just type triple dots to input `../..',
# quadruple dots to `../../..', etc..
#
# % .. [Hit <.>]
# % ../.. [Hit <.>]
# % ../../.. [Hit <^H>]
# % ../.. [Hit <^H>]
# % ..
#
# As you see above, each of the `/..' parts complemented by this tweak
# can be deleted by a single invocation of the backward-delete-char
# command, only if invoked right after the magic happens.
#
# % .. [Hit </><.><.>]
# % ../.. [Hit <^H>]
# % ../.
#
# Usage:
# autoload -Uz manydots-magic
# manydots-magic
#
manydots-magic.self-insert() {
emulate -L zsh
local self_insert_function magic_count
zstyle -s ':manydots-magic' self-insert-function self_insert_function
if [[ "$KEYS" == .* && "$LBUFFER" != *...* && "$LBUFFER" == *.. ]] && {
local -a words
words=("${(@Q)${(z)LBUFFER}}")
# `...` is a wildcard operator in go
[[ ${${(@)words[1,-2]}[(I)go]} = 0 ]] &&
[[ $words[-1] == (|*[/=]|[\<\>=]\().. ]]
}
then
[[ "$LASTWIDGET" == (self-insert|backward-delete-char) ]] &&
zstyle -s ':manydots-magic' magic-count magic_count
zstyle ':manydots-magic' magic-count $((magic_count+1))
LBUFFER="$LBUFFER/."
zle "$self_insert_function"
return
fi
# cancel expansion if it does not seem right
if [[ "$KEYS" != [=/,:\;\|\&\<\>\(\)\[\]{}^~\'\"\`[:space:]]* &&
"$LASTWIDGET" == (self-insert|backward-delete-char) && "$LBUFFER" == *../.. ]] && {
zstyle -s ':manydots-magic' magic-count magic_count
[[ "$magic_count" -gt 0 ]]
}
then
repeat $magic_count LBUFFER="${LBUFFER%/..}"
repeat $magic_count LBUFFER="$LBUFFER."
fi
zstyle ':manydots-magic' magic-count 0
zle "$self_insert_function"
}
manydots-magic.backward-delete-char() {
emulate -L zsh
local backward_delete_char_function
zstyle -s ':manydots-magic' backward-delete-char-function backward_delete_char_function
if [[ "$LASTWIDGET" == (self-insert|backward-delete-char) && "$LBUFFER" == *../.. ]] && {
local magic_count
zstyle -s ':manydots-magic' magic-count magic_count
[[ "$magic_count" -gt 0 ]]
}
then
zstyle ':manydots-magic' magic-count $((magic_count-1))
LBUFFER="${LBUFFER%..}"
else
zstyle ':manydots-magic' magic-count 0
fi
zle "$backward_delete_char_function"
}
manydots-magic.on() {
emulate -L zsh
local self_insert_function="${$(zle -lL | awk \
'$1=="zle"&&$2=="-N"&&$3=="self-insert"{print $4;exit}'):-.self-insert}"
[[ "$self_insert_function" == manydots-magic.self-insert ]] &&
return 0
# For url-quote-magic which does not zle -N itself
zle -la "$self_insert_function" || zle -N "$self_insert_function"
zstyle ':manydots-magic' self-insert-function "$self_insert_function"
zle -A manydots-magic.self-insert self-insert
local backward_delete_char_function="$(zle -lL | awk \
'$1=="zle"&&$2=="-N"&&$3=="backward-delete-char"{print $4;exit}')"
if [[ -n "$backward_delete_char_function" ]]
then
zle -la "$backward_delete_char_function" || zle -N "$backward_delete_char_function"
else
zle -A backward-delete-char manydots-magic.orig.backward-delete-char
backward_delete_char_function=manydots-magic.orig.backward-delete-char
fi
zstyle ':manydots-magic' backward-delete-char-function "$backward_delete_char_function"
zle -A manydots-magic.backward-delete-char backward-delete-char
zstyle ':manydots-magic' magic-count 0
return 0
}
manydots-magic.off() {
emulate -L zsh
local self_insert_function backward_delete_char_function
zstyle -s ':manydots-magic' self-insert-function self_insert_function
[[ -n "$self_insert_function" ]] &&
zle -A "$self_insert_function" self-insert
zstyle -s ':manydots-magic' backward-delete-char-function backward_delete_char_function
[[ -n "$backward_delete_char_function" ]] &&
zle -A "$backward_delete_char_function" backward-delete-char
zstyle ':manydots-magic' magic-count 0
return 0
}
zle -N manydots-magic.self-insert
zle -N manydots-magic.backward-delete-char
zle -N manydots-magic.on
zle -N manydots-magic.off
manydots-magic() {
manydots-magic.on
}
[[ -o kshautoload ]] || manydots-magic "$@"
+16
View File
@@ -0,0 +1,16 @@
# To see the key combo you want to use just do:
# cat > /dev/null
# And press it
bindkey "^K" kill-whole-line # ctrl-k
# bindkey "^R" history-incremental-search-backward # ctrl-r
#bindkey "^A" beginning-of-line # ctrl-a
#bindkey "^E" end-of-line # ctrl-e
# bindkey "[B" history-search-forward # down arrow
# bindkey "[A" history-search-backward # up arrow
# bindkey "^D" delete-char # ctrl-d
# bindkey "^F" forward-char # ctrl-f
# bindkey "^B" backward-char # ctrl-b
bindkey "^[[1;5D" backward-word # ctrl-left arrow
bindkey "^[[1;5C" forward-word # ctrl-right arrow
bindkey -e # Default to standard emacs bindings, regardless of editor string
+70
View File
@@ -0,0 +1,70 @@
function zsh_recompile {
autoload -U zrecompile
rm -f ~/.zsh/*.zwc
[[ -f ~/.zshrc ]] && zrecompile -p ~/.zshrc
[[ -f ~/.zshrc.zwc.old ]] && rm -f ~/.zshrc.zwc.old
for f in ~/.zsh/**/*.zsh; do
[[ -f $f ]] && zrecompile -p $f
[[ -f $f.zwc.old ]] && rm -f $f.zwc.old
done
[[ -f ~/.zcompdump ]] && zrecompile -p ~/.zcompdump
[[ -f ~/.zcompdump.zwc.old ]] && rm -f ~/.zcompdump.zwc.old
source ~/.zshrc
}
function extract {
echo Extracting $1 ...
if [ -f $1 ] ; then
case $1 in
*.tar.bz2) tar xjf $1 ;;
*.tar.gz) tar xzf $1 ;;
*.bz2) bunzip2 $1 ;;
*.rar) unrar x $1 ;;
*.gz) gunzip $1 ;;
*.tar) tar xf $1 ;;
*.tbz2) tar xjf $1 ;;
*.tgz) tar xzf $1 ;;
*.zip) unzip $1 ;;
*.Z) uncompress $1 ;;
*.7z) 7z x $1 ;;
*) echo "'$1' cannot be extracted via extract()" ;;
esac
else
echo "'$1' is not a valid file"
fi
}
function trash () {
local path
for path in "$@"; do
# ignore any arguments
if [[ "$path" = -* ]]; then :
else
local dst=${path##*/}
# append the time if necessary
while [ -e ~/.Trash/"$dst" ]; do
dst="$dst "$(date +%H-%M-%S)
done
/bin/mv "$path" ~/.Trash/"$dst"
fi
done
}
function strip_diff_leading_symbols {
local color_code_regex="(\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K])"
# simplify the unified patch diff header
sed -r "s/^($color_code_regex)diff --git .*$//g" | \
sed -r "s/^($color_code_regex)index .*$/\n\1$(rule)/g" | \
sed -r "s/^($color_code_regex)\+\+\+(.*)$/\1+++\5\n\1$(rule)\x1B\[m/g" |\
# actually strips the leading symbols
sed -r "s/^($color_code_regex)[\+\-]/\1 /g"
}
## Print a horizontal rule
rule () {
printf "%$(tput cols)s\n"|tr " " "─"}}
+22
View File
@@ -0,0 +1,22 @@
function precmd {
# vcs_info
# Put the string "hostname::/full/directory/path" in the title bar:
echo -ne "\e]2;$PWD\a"
# Put the parentdir/currentdir in the tab
echo -ne "\e]1;$PWD:h:t/$PWD:t\a"
}
function set_running_app {
#print "\e]1; $PWD:t:$(history $HISTCMD | cut -b7- ) \a"
print -Pn $'\e]1; $PWD:t:$(history $HISTCMD | cut -b7- ) \a'
}
function preexec {
set_running_app
}
function postexec {
set_running_app
}
+7
View File
@@ -0,0 +1,7 @@
alias less='less -R'
function appConnections()
{
ss -tpla | grep -v Recv-Q | awk '{print $5 $6}' | sed -e 's#\(.*\)users:((\"\(\w\+\)\".*#\2 - \1#' | sort | uniq
}
alias conns=appConnections
+66
View File
@@ -0,0 +1,66 @@
function adminer() {
command -v kubectl >/dev/null 2>&1 || { echo >&2 "kubectl is required for portforwarding"; return 1; }
local ctx="${1}"
local ns="${2}"
local label="${3}"
local remotePort=${4}
local localPort=
[[ "${ctx}" == "" ]] && {echo >&2 "please provide name of the kubeconfig context\n\navailable contexts:"; kubectl config get-contexts --no-headers -o name >&2; return 1; }
[[ "${ns}" == "" ]] && ns="devops"
[[ "${label}" == "" ]] && label="app.kubernetes.io/name=adminer"
[[ "${remotePort}" == "" ]] && remotePort="8080"
kubectl config get-contexts --no-headers -o name | grep -q -- "^${ctx}$"
if [[ $? -ne 0 ]]; then
echo >&2 "context ${ctx} not found in kubectl\n\navailable contexts:\n"
kubectl config get-contexts --no-headers -o name >&2
return 1
fi
echo -n "specify a local port [8080]: "
read localPort
[[ "${localPort}" == "" ]] && localPort="8080"
local pod=$(kubectl --context "${ctx}" -n "${ns}" get pods --no-headers -l "${label}" -o name)
[[ "${pod}" == "" ]] && { echo >&2 "could not find the adminer pod using context '${ctx}' and namespace '${ns}' and label '${label}'"; return 1; }
kubectl --context "${ctx}" -n "${ns}" port-forward "${pod}" "${localPort}":"${remotePort}" &
local pfPid=$!
local attempt=0
echo "waiting for connection to open..."
while kill -0 $pfPid > /dev/null 2>&1; do
timeout 1 bash -c "</dev/tcp/127.0.0.1/${localPort}" > /dev/null 2>&1
if [[ $? -eq 0 ]]; then
xdg-open "http://adminer${localPort}:${localPort}"
break
fi
attempt=$((attempt+1))
[[ ${attempt} -eq 10 ]] && { echo &>2 "Connection took too long to establish"; break; }
sleep 1
done
fg %kubectl > /dev/null 2>&1
}
function adminer-local() {
local localPort=
echo -n "specify a local port [8080]: "
read localPort
[[ "${localPort}" == "" ]] && localPort="8080"
local contName="local-adminer-${localPort}"
sudo docker run --name $contName --rm -d --net host adminer
#sudo docker run --name $contName --rm -d -p $localPort:8080 adminer
[[ $? -ne 0 ]] && echo "Could not start adminer" && exit 1
xdg-open "http://adminer:${localPort}"
sudo docker attach $contName
}