rbw.plugin.zsh
1528 bytes
1if (( ! $+commands[rbw] )); then
2 return
3fi
4
5# If the completion file doesn't exist yet, we need to autoload it and
6# bind it to `rbw`. Otherwise, compinit will have already done that.
7if [[ ! -f "$ZSH_CACHE_DIR/completions/_rbw" ]]; then
8 typeset -g -A _comps
9 autoload -Uz _rbw
10 _comps[rbw]=_rbw
11fi
12
13rbw gen-completions zsh >| "$ZSH_CACHE_DIR/completions/_rbw" &|
14
15# rbwpw function copies the password of a service to the clipboard
16# and clears it after 20 seconds
17function rbwpw {
18 if [[ $# -ne 1 ]]; then
19 echo "usage: rbwpw <service>"
20 return 1
21 fi
22 local service=$1
23 if ! rbw unlock; then
24 echo "rbw is locked"
25 return 1
26 fi
27 local pw=$(rbw get $service 2>/dev/null)
28 if [[ -z $pw ]]; then
29 echo "$service not found"
30 return 1
31 fi
32
33 # Generate a random identifier for this call to rbwpw
34 # so we can check if the clipboard content has changed
35 local _random="$RANDOM" _cache="$ZSH_CACHE_DIR/.rbwpw"
36 echo -n "$_random" > "$_cache"
37
38 # Use clipcopy to copy the password to the clipboard
39 echo -n $pw | clipcopy
40 echo "password for $service copied!"
41
42 # Clear the clipboard after 20 seconds, but only if the clipboard hasn't
43 # changed (if rbwpw hasn't been called again)
44 {
45 sleep 20 \
46 && [[ "$(<"$_cache")" == "$_random" ]] \
47 && clipcopy </dev/null 2>/dev/null \
48 && command rm -f "$_cache" &>/dev/null
49 } &|
50}
51
52function _rbwpw {
53 local -a services
54 services=("${(@f)$(rbw ls 2>/dev/null)}")
55 [[ -n "$services" ]] && compadd -a -- services
56}
57
58compdef _rbwpw rbwpw