Committing stuff

master
Taeyeon Mori 10 years ago
parent e477196e62
commit 079729918f
  1. 119
      bin/abs2
  2. 136
      bin/aconvert
  3. 51
      bin/aur.sh
  4. 94
      bin/ffpsp
  5. 98
      bin/ffpsp-batch
  6. 72
      bin/mountpart
  7. 28
      bin/shedshut
  8. 63
      bin/videothumb
  9. 16
      dotfiles/makepkg.conf
  10. 11
      etc/aur.conf
  11. 11
      etc/aur.conf~
  12. 6
      ffpsp_bat.desktop
  13. 4
      install
  14. 111
      lib/libssh-agent.sh
  15. 1
      zsh/lib.zsh
  16. 4
      zsh/zpreztorc
  17. 1
      zsh/zprofile
  18. 2
      zsh/zshrc

@ -0,0 +1,119 @@
#!/usr/bin/python3
# (c) 2014 Taeyeon MORI
import os
import argparse
import subprocess
import hashlib
import contextlib
import sys
import termios
import shutil
system = lambda *a: subprocess.check_call(a)
class Package:
def __init__(self, x):
self.fqn = x
self.repo, self.name = x.split("/")
def parse_args(argv):
parser = argparse.ArgumentParser(prog=argv[0])
def add_option(option, default, help=None):
parser.add_argument(option, default=default)
def add_switch(option, default=False, help=None):
parser.add_argument(option, default=default, action="store_const", const=not default)
parser.add_argument("package", type=Package)
add_option("-buildroot", "/tmp/abs-%i" % os.getuid())
add_option("-makepkg", "makepkg")
add_switch("-nobuild")
add_switch("-install")
return parser.parse_args(argv[1:])
def file_sha1(name):
with open(name, "rb") as f:
hash = hashlib.sha1()
while True:
data = f.read(2048)
if not data:
return hash.digest()
hash.update(data)
@contextlib.contextmanager
def rawinput(file):
fd = file.fileno() if hasattr(file, "fileno") else file
flags = save = termios.tcgetattr(fd)
flags[3] &= ~termios.ICANON
flags[6][termios.VMIN] = 1
flags[6][termios.VTIME] = 0
termios.tcsetattr(fd, termios.TCSADRAIN, flags)
yield
termios.tcsetattr(fd, termios.TCSADRAIN, save)
def yesno(prompt):
ch = ""
while ch not in "yYnN":
sys.stdout.write(prompt)
sys.stdout.write(" [Y/N] ")
sys.stdout.flush()
with rawinput(sys.stdin):
ch = sys.stdin.read(1)
sys.stdout.write("\r")
sys.stdout.write("\n")
return ch in "yY"
def main(argv):
args = parse_args(argv)
print("===> Synchronizing ABS")
system("sudo", "abs", args.package.fqn)
print("===> Updating build directory")
ABS_DIR = os.path.join("/var/abs", args.package.fqn)
if not os.path.exists(ABS_DIR):
print("=ERROR=> No such pacakge: %s" % args.package.fqn)
return 1
REPODIR = os.path.join(args.buildroot, args.package.repo)
PACKDIR = os.path.join(REPODIR, args.package.name)
if not os.path.exists(PACKDIR):
os.makedirs(PACKDIR)
for path, dirs, files in os.walk(ABS_DIR):
rel_path = os.path.relpath(path, ABS_DIR)
dest_path = os.path.join(PACKDIR, rel_path)
for dir in dirs:
dest = os.path.join(dest_path, dir)
os.path.exists(dest) or os.mkdir(dest)
for file in files:
source = os.path.join(path, file)
dest = os.path.join(dest_path, file)
(not os.path.exists(dest) or (file_sha1(source) != file_sha1(dest) and yesno("=> Overwrite %s?" % os.path.join(rel_path, file)))) and shutil.copy(source, dest)
yesno("=> Edit %s PKGBUILD?" % args.package.fqn) and system(os.environ.get("EDITOR", "vim"), os.path.join(PACKDIR, "PKGBUILD"))
if not args.nobuild:
print("===> Building Package %s" % args.package.fqn)
os.chdir(PACKDIR)
if args.install:
system(args.makepkg, "-i")
else:
system(args.makepkg)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))

@ -0,0 +1,136 @@
#!/usr/bin/env python3
import os
import sys
import subprocess
import argparse
def main():
try:
return main_()
except SystemExit as e:
try:
return int(e.code)
except:
print(e.code)
return 1
def kvpair(x):
if x == "YES":
return True
elif x == "NO":
return False
elif x == "\\YES":
return "YES"
elif x == "\\NO":
return "NO"
else:
return x
def main_():
argp = argparse.ArgumentParser()
argp.add_argument("source", nargs="+")
argp.add_argument("destination")
argp.add_argument("-p", "--profile", choices=["aac", "m4a", "ogg", "wav", "wma"])
argp.add_argument("-u", "--update", help="Only process new files", action="store_true")
argp.add_argument("--avconv", default="avconv")
argp.add_argument("-m", nargs=2, action="append", type=kvpair, default=[])
argp.add_argument("-i", nargs=2, action="append", type=kvpair, default=[])
argp.add_argument("-o", nargs=2, action="append", type=kvpair, default=[])
args = argp.parse_args()
i_flags = dict()
o_flags = dict()
m_flags = dict()
# no video
o_flags["vn"] = True
m_flags["update"] = args.update
# capability checks
s = subprocess.check_output([args.avconv, "-codecs"], stderr=subprocess.DEVNULL)
if b"faac" in s:
aac = {"acodec": "faac"}
else:
aac = {"acodec": "aac", "strict": "experimental"}
if b"libvorbis" in s:
vorbis = {"acodec": "libvorbis"}
else:
vorbis = {"acodec": "vorbis", "strict": "experimental"}
# profiles
m_flags["fileext"] = "raw"
if args.profile == "aac":
m_flags["fileext"] = "aac"
o_flags.update(aac)
elif args.profile == "m4a":
m_flags["fileext"] = "m4a"
o_flags.update(aac)
elif args.profile == "ogg":
m_flags["fileext"] = "ogg"
o_flags.update(vorbis)
elif args.profile == "wav":
m_flags["fileext"] = "wav"
o_flags["acodec"] = "pcm_f32le"
elif args.profile == "wma":
m_flags["fileext"] = "wma"
o_flags["acodec"] = "wmav2"
o_flags["ac"] = 2
i_flags.update(dict(args.i))
o_flags.update(dict(args.o))
m_flags.update(dict(args.m))
if len(args.source) > 1:
run_multiple(m_flags, args.avconv, i_flags, args.source, o_flags, args.destination)
else:
run_once(m_flags, args.avconv, i_flags, args.source[0], o_flags, args.destination)
return 0
def make_destfile(source, m, destination):
if not os.path.isdir(destination):
return destination
stem, ext = os.path.splitext(source)
destfile = ".".join((stem, m["fileext"]))
return os.path.join(destination, destfile)
def add_args(argv, argdict):
for k,v in argdict.items():
argv.append("-%s" % k)
if v is not True:
argv.append(str(v))
def make_argv(m, avconv, i, source, o, destination):
argv = [avconv]
add_args(argv, i)
argv.append("-i")
argv.append(source)
add_args(argv, o)
argv.append(make_destfile(source, m, destination))
return argv
def run_once(m, avconv, i, source, o, destination):
dest = make_destfile(source, m, destination)
if m["update"] and os.path.exists(dest) and os.stat(dest).st_mtime >= os.stat(source).st_mtime:
return
try:
subprocess.check_call(make_argv(m, avconv, i, source, o, destination))
except subprocess.CalledProcessError as e:
raise SystemExit("Worker avconv process exited with nonzero return code: %i\nCommand was: %s\nAborting." % (e.returncode, e.cmd))
def run_multiple(m, avconv, i, sources, o, destination):
if not os.path.isdir(destination):
os.mkdir(destination)
for source in sources:
run_once(m, avconv, i, source, o, destination)
if __name__ == "__main__":
main()

@ -0,0 +1,51 @@
#!/bin/zsh
# vim: ft=sh:ts=2:sw=2:et
source "$DOTFILES/zsh/lib.zsh"
source "$DOTFILES/etc/aur.conf"
function throw {
err "$2"
exit $1
}
tmpbuild=$TMPDIR/aur.sh.$$
build="${BUILDDIR:-$tmpbuild}"
test -d "$build" || mkdir -p "$build" || exit 1
packages=(${@##-*})
makepkg_flags=(${@##[^\-]*})
msg "[AUR] AURDIR=$AURDIR; PKGDEST=$PKGDEST"
test "$build" = "$PWD" || \
msg "[AUR] Working in $build."
msg "[AUR] Building packages: $packages"
for p in "${packages[@]}"; do
cd "$AURDIR"
msg "[AUR] $p: Getting PKGBUILD"
{
test -d $p && \
test -f $p/PKGBUILD && \
grep -q "#CUSTOMPKG" $p/PKGBUILD && \
warn "[AUR] $p: Found #CUSTOMPKG; not updating PKGBUILD from AUR!" \
} || \
{ curl https://aur.archlinux.org/packages/${p:0:2}/$p/$p.tar.gz | tar xz } || \
throw 2 "[AUR] $p: Couldn't download package"
cd $p
msg "[AUR] $p: Building..."
makepkg "${makepkg_flags[@]}" || \
throw 1 "[AUR] $p: Makepkg failed!"
msg "[AUR] $p: Done!"
done
msg "[AUR] All Done!"
test "$build" = "$tmpbuild" && \
warn "[AUR] Removing temporary directory $tmpbuild" && \
rm -rf "$tmpbuild"

@ -0,0 +1,94 @@
#!/bin/bash
# (c) 2012-2014 MORI Taeyeon
# Convert video for playback on Sony PSP
usage() {
echo "Usage: `basename "$1"` [-subs] [-nothumb] <infile> [outfile] [-- <HandBrakeCLI options>]"
echo
echo "ffpsp (c) 2012-2014 MORI Taeyeon"
echo "Convert a video for Sony PSP"
echo
echo "Positional Arguments:"
echo -e "\tinfile\t\tInput file"
echo -e "\toutfile\t\tOutput file (default: same name in psp/ subdir)"
echo
echo "Options:"
echo -e "\t-h\t\tDisplay this help message and exit."
echo -e "\t-subs\t\tHardcode softsubs"
echo -e "\t-nothumb\tDon't generate Thumbnails"
echo
echo "Override Application executables:"
echo -e "\t-avprobe -ffmpeg -hbcli -videothumb"
echo
echo "Additional HB-CLI options may be added after a '--' (if you know what you're doing!)"
}
# commandline options
SUBTITLES=false
THUMBNAIL=true
INPUT_FILE=
OUTPUT_FILE=
avprobe=avprobe
hbcli=HandBrakeCLI
ffmpeg=ffmpeg
videothumb=videothumb
# Parse commandline options
pos_args=0
next=
for i in "$@"; do
shift;
if [[ -z "$next" ]]; then
case "$i" in
-subs)
SUBTITLES=true;;
-nothumb)
THUMBNAIL=false;;
-avprobe|-ffmpeg|-hbcli|-videothumb)
next=${1#-};;
--)
break;;
-h|-help|--help)
usage $0
exit 0;;
*)
case $pos_args in
0) INPUT_FILE=$i;;
1) OUTPUT_FILE=$i;;
esac
pos_args=$[$pos_args+1];;
esac
else
eval "$next=\"\$i\""
next=
fi
done
[[ $pos_args -lt 1 || $pos_args -gt 2 ]] && usage $0 && exit 1
# Generate output filename
if [[ -z "$OUTPUT_FILE" ]]; then
OUTPUT_DIR=`dirname "$INPUT_FILE"`/psp
OUTPUT_FILE=`basename "$INPUT_FILE"`
OUTPUT_FILE=$OUTPUT_DIR/${OUTPUT_FILE%.*}.mp4
if ! [[ -e "$OUTPUT_DIR" ]]; then
mkdir -p "$OUTPUT_DIR"
elif [[ -e "$OUTPUT_FILE" ]]; then
echo "File already exists: \"$OUTPUT_FILE\". Specify it explicitly to overwrite"
exit 1
fi
fi
THUMBNAIL_FILE=${OUTPUT_FILE%.*}.thm
# Handle Softsubs
if $SUBTITLES && $avprobe "$INPUT_FILE" 2>&1 | grep -i Subtitle | grep -qi ass; then
SUB_ARGS="--subtitle-burned 1 -s 1"
echo "Found a subtitle Track!"
fi
# Go!
$hbcli -X 480 -Y 272 --modulus 16 -E faac -B 128 -R 44.1 -6 stereo -e x264 -r 23.976 -x profile=main:level=30:weightp=1:subq=9:rc-lookahead=20:8x8dct=0:b-pyramid=none:me=umh:bframes=16 -i "$INPUT_FILE" -o "$OUTPUT_FILE" -q 20 $SUB_ARGS "$@" || exit $?
$THUMBNAIL && $videothumb "$OUTPUT_FILE" "$THUMBNAIL_FILE" -s 160x120 || exit $?

@ -0,0 +1,98 @@
#!/bin/bash
# (c) 2012-2014 MORI Taeyeon
# Batch-convert videos for playback on Sony PSP
usage() {
echo "Usage: `basename "$1"` [-subs] [-nothumb] [-log <path>] [-out <path>] <file [...]>"
echo
echo "ffpsp-batch (c) 2012-2014 MORI Taeyeon"
echo "Batch-convert videos for Sony PSP"
echo
echo "Options:"
echo -e "\t-h\t\tDisplay this help message and exit."
echo -e "\t-subs\t\tHardcode softsubs"
echo -e "\t-nothumb\tDon't generate Thumbnails"
echo -e "\t-log <path>\tThe logfile path"
echo -e "\t-out <path>\tThe output directory"
echo
echo "Override Application executables: -<prog> <path>"
echo -e "\t-avprobe -ffmpeg -hbcli -videothumb -ffpsp"
}
FFPSP_OPT=()
FILES=()
log="${XDG_CACHE_HOME-$HOME/.cache}/ffpsp/ffpsp-batch.$(date +%Y%m%d-%H%M).$$.log"
ffpsp=ffpsp
# Parse commandline options
next=
for i in "$@"; do
shift
if [[ -z "$next" ]]; then
case "$i" in
-subs|-nothumb)
FFPSP_OPT+=("$i");;
-avprobe|-ffmpeg|-hbcli|-videothumb)
FFPSP_OPT+=("$i")
next=ffpsp-opt;;
-ffpsp|-out|-log)
next=${i#-};;
-h|-help|--help)
usage "$0"
exit 0;;
--)
FILES+=("$@")
break;;
*)
FILES+=("$i")
esac
elif [[ "$next" == "ffpsp-opt" ]]; then
FFPSP_OPT+=("$i")
next=
else
eval "$next=\"\$i\""
next=
fi
done
# Create log dir
mkdir -p "`dirname "$log"`"
# Set title
echo -ne "\033]1;ffpsp\007"
# sort input files, for convenience
readarray -t sorted < <(for a in "${FILES[@]}"; do echo "$a"; done | sort)
# Report Queue
echo "-- ffpsp-batch v1 --" | tee "$log"
echo "[[ QUEUE ]]"
for f in "${sorted[@]}"; do echo "`basename "$f"`"; done
echo
# Process queue
i=0
for f in "${sorted[@]}"; do
# Report progress.
i=$[ i + 1 ]
echo [[ \>\> $f \<\< ]] | tee -a "$log"
echo -ne "\033]2;[ffpsp] ($i of ${#sorted[@]}) $f\007"
# Generate output filename
OUTPUT_DIR=${out-$(dirname "$f")/psp}
OUTPUT_FILE=`basename "$f"`
OUTPUT_FILE=$OUTPUT_DIR/${OUTPUT_FILE%.*}.mp4
if ! [[ -e "$OUTPUT_DIR" ]]; then
mkdir -p "$OUTPUT_DIR"
elif [[ -e "$OUTPUT_FILE" ]]; then
echo "File already exists: \"$OUTPUT_FILE\". Skipping"
continue
fi
$ffpsp "${FFPSP_OPT[@]}" "$f" "$OUTPUT_FILE" 2> >(tee -a "$log" >&2)
done
# Notify completion
echo -ne "\033]1;ffpsp - done\007\033]2;[ffpsp] done.\007"

@ -0,0 +1,72 @@
#!/usr/bin/env python3
import sys, os
import argparse
import subprocess
def existing_filename(f):
if not os.path.exists(f):
raise ValueError("No such file or directory.")
return f
def existing_dirname_or_dash(f):
if f == '-':
pass
elif not os.path.exists(f):
raise ValueError("No such file or directory.")
elif not os.path.isdir(f):
raise ValueError("Not a directory: %s" % f)
return f
def int_1plus(s):
i = int(s)
if i < 1:
raise ValueError("Index must be greater 0.")
return i
def parse_args(argv):
parser = argparse.ArgumentParser(prog=argv[0])
parser.add_argument("image", help="image file", type=existing_filename)
parser.add_argument("mountpoint", help="mount point/loop device ['-' uses next available]", type=existing_dirname_or_dash)
parser.add_argument("-p", help="partition index, 1-based [default: 1]", type=int_1plus, default=1, metavar="index", dest="part")
parser.add_argument("-l", help="Don't mount, just setup the loop device.", action="store_true", default=False)
parser.add_argument("-t", help="filesystem type [default: auto]", metavar="vfstype")
parser.add_argument("-o", help="mount options [default: none]", metavar="options")
parser.add_argument("-parted", help="parted executable [default: parted]", default="parted")
parser.add_argument("-mount", help="mount executable [default: mount]", default="mount")
parser.add_argument("-losetup", help="losetup executable [default: losetup]", default="losetup")
return parser.parse_args(argv[1:])
def main(argv):
args = parse_args(argv)
parted = subprocess.check_output([args.parted, args.image, "-s", "-m", "u", "b", "p"])
partitions = parted.split(b";\n")[2:]
try:
part = partitions[args.part-1]
except IndexError:
raise SystemExit("Partition index out of range: %i, has %i" % (args.part, len(partitions)))
offset = part.split(b':')[1].rstrip(b'B').decode("ascii")
if args.l:
if args.mountpoint == '-':
args.mountpoint = "-f"
losetup = [args.losetup, "--show", "--offset", offset, args.mountpoint, args.image]
subprocess.check_call(losetup)
else:
if args.mountpoint == '-':
raise ValueError("Mountpoint cannot be '-' unless -l (only setup loop device) is also given")
options = "offset=%s" % offset
if args.o:
options += ',' + args.o
mount = [args.mount, args.image, args.mountpoint, "-o", options]
if args.t:
mount.append("-t")
mount.append(args.t)
subprocess.check_call(mount)
if __name__ == "__main__":
import sys
sys.exit(main(sys.argv))

@ -0,0 +1,28 @@
#!/bin/bash
echo "[ShedShut v1] Waiting for \"$1\" to finish"
NXC="$IFS";IFS=$'\n'
ps=($(ps xaht | grep -v grep | grep -v "$0" | grep "$1" | awk '{ printf "("$1") "; for (i=5; i<=NF; i++) printf $i" "; printf "\n" }'))
IFS="$NXC"
echo "Expression matches on:"; for i in "${ps[@]}"; do echo " $i"; done
#echo "Filtering Keywords: 'grep', '$0'"
if test -z "$2"; then cmd="shutdown -h now"; else cmd="$2"; fi
echo "Sheduled Command: $cmd"
if ! test `id -u` = 0; then echo "WARNING: Your Command may not work as user '$(id -un)'"; fi
f="date +%H:%M:%S"
watch() {
declare -g -a watch_pids=($(ps xaht | grep -v grep | grep -v "$0" | grep "$1" | awk '{ print $1 }'))
if test ${#watch_pids[@]} -gt 0; then
echo "[$($f)] Processes: ${watch_pids[@]}"
return 0
else
echo "[$($f)] No Processes."
return 1
fi
}
while watch $1; do sleep 60; done
echo "[$($f)] Shutting down: $cmd"
$cmd

@ -0,0 +1,63 @@
#!/usr/bin/python3
# (c) 2013 MORI Taeyeon
# Create Video Thumbnails using FFmpeg
from __future__ import print_function, division, absolute_import, unicode_literals
import subprocess
import re
import os
import random
import argparse
ffmpeg_cmd = ["ffmpeg"]
ffprobe_cmd = ["ffmpeg", "-i"]
regexp = re.compile(r"Duration: (\d+):(\d\d):(\d\d).\d\d,")
def getdur(file):
cmd = ffprobe_cmd + [file]
pipe = subprocess.Popen(cmd, stderr=subprocess.PIPE)
pipe.wait()
try:
for line in pipe.stderr:
sys.stderr.buffer.write(line)
line = str(line, "utf8").rstrip()
if "Duration:" in line:
dur = regexp.search(line)
return int(dur.group(1))*3600+int(dur.group(2))*60+int(dur.group(3))
else:
raise ValueError("Duration not in FFMpeg output!")
finally:
sys.stderr.buffer.flush()
sys.stderr.flush()
def randpos(file):
dur = getdur(file)
pos = random.randint(1, dur)
print("Dur: %i, Pos: %i" % (dur, pos))
return pos
def mkthumb(file, pos, target, res=None):
cmd = ffmpeg_cmd + ["-ss", pos, "-i", file, "-an", "-vframes", 1, "-f", "image2"]
if res is not None:
cmd.extend(["-s", res])
cmd.append(target)
return subprocess.check_call(map(str,cmd))
def main(argv):
parser = argparse.ArgumentParser(prog=argv[0])
parser.add_argument("input", help="input file name")
parser.add_argument("target", help="thumbnail file name")
parser.add_argument("-p", help="Position in Video (random if omitted)", type=int)
parser.add_argument("-s", help="scale picture (WxH)")
args = parser.parse_args(argv[1:])
os.stat(args.input)
if args.p:
mkthumb(args.input, args.p, args.target, args.s)
else:
mkthumb(args.input, randpos(args.input), args.target, args.s)
if __name__ == "__main__":
import sys
sys.exit(main(sys.argv))

@ -1,6 +1,20 @@
# vim: ft=sh
# Packager Info
source "$DOTFILES/user-info" source "$DOTFILES/user-info"
PACKAGER="$REALNAME <$EMAIL>" PACKAGER="$REALNAME <$EMAIL>"
# Optimizations
function fix_march {
echo $@ | sed 's/-march=[\w-]+ -mtune=\w+/-march=native/'
}
CFLAGS="`fix_march $CFLAGS`"
CXXFLAGS="`fix_march $CXXFLAGS`"
LDFLAGS="$LDFLAGS"
MAKEFLAGS="-j4" MAKEFLAGS="-j4"
CFLAGS="-march=native"
# Store stuff
source "$DOTFILES/etc/aur.conf"

@ -0,0 +1,11 @@
# vim: ft=sh
# Folders
AURDIR="$HOME/aur"
PKGDEST="$AURDIR/Packages"
SRCDEST="$AURDIR/Source"
test -d "$AURDIR" || mkdir -p "$AURDIR" || exit 1
test -d "$PKGDEST" || mkdir -p "$PKGDEST" || exit 1
test -d "$SRCDEST" || mkdir -p "$SRCDEST" || exit 1

@ -0,0 +1,11 @@
# vim: ft=sh
# Folders
AURDIR="$HOME/aur"
PKGDEST="$AURDIR/.pkg"
SRCDEST="$AURDIR/.sauce"
test -d "$AURDIR" || mkdir -p "$AURDIR" || exit 1
test -d "$PKGDEST" || mkdir -p "$PKGDEST" || exit 1
test -d "$SRCDEST" || mkdir -p "$SRCDEST" || exit 1

@ -0,0 +1,6 @@
[Desktop Entry]
Type=Application
Exec=ffpsp-batch -subs %F
Terminal=true
Name=[ffpsp] Drop files to convert
Icon=hb-icon

@ -44,8 +44,8 @@ done
function generate() { function generate() {
[[ -e "$1" ]] && ! $OVERWRITE && ! grep -q "Generated by .files/install" "$1" && \ [[ -e "$1" ]] && ! $OVERWRITE && ! grep -q "Generated by .files/install" "$1" && \
err "Custom version of $1 detected. Please delete it before running .files/install" && exit 1 err "Custom version of $1 detected. Please delete it before running .files/install" && exit 1
echo "# Generated by .files/install" >"$1" echo "${2-#} Generated by .files/install" >"$1"
echo "# `date "+%m/%d/%Y %H:%M:%S"`" >>"$1" echo "${2-#} `date "+%m/%d/%Y %H:%M:%S"`" >>"$1"
echo >>"$1" echo >>"$1"
cat >>"$1" cat >>"$1"
} }

@ -0,0 +1,111 @@
#!/bin/bash
# libssh-agent 0.1
# (c) 2013-2014 Orochimarufan
#
# Managing SSH keys and agents
LSA_VERSION=0.1
# === Tools ===
# Echo colored text to STDERR
echocolor() {
# (int color, string... text)
local COLOR=$1 && shift
echo -e "\e[${COLOR}m$*\e[0m" >&2
}
# Look for keys in ssh argv
ssh_keys_from_argv() {
# (string... argv) -> global "KEYS"
local EX=false
declare -ga KEYS
for arg in "$@"; do
if $EX; then
KEYS=("${KEYS[@]}" "$arg")
EX=false
else
[ "$arg" = "-i" ] && EX=true
fi
done
}
# === Private Functions ===
# Private SSH Agent instance management
PRIVATE_SSH_AGENT=false
private_ssh_agent_start() {
echocolor 35 "Starting private SSH Agent."
PRIVATE_SSH_AGENT_P_PID=$SSH_AGENT_PID
PRIVATE_SSH_AGENT_P_SOCK=$SSH_AUTH_SOCK
# We don't want the PID printed.
eval `ssh-agent -s` >/dev/null
PRIVATE_SSH_AGENT=true
}
private_ssh_agent_stop() {
echocolor 35 "Stopping private SSH Agent."
# We don't need the output.
eval `ssh-agent -ks` >/dev/null
PRIVATE_SSH_AGENT=false
export SSH_AGENT_PID=$PRIVATE_SSH_AGENT_P_PID
export SSH_AUTH_SOCK=$PRIVATE_SSH_AGENT_P_SOCK
}
gnome_keyring_ssh_agent_ckeck() {
# the GNOME Keyring agent doesn't support ecdsa keys.
local PID=$1; shift
# FIXME: Linux specific!
# FIXME: is this reliable?
CMDLINE="/proc/$PID/cmdline"
if grep -qi gnome-session "$CMDLINE" 2>/dev/null; then
echocolor 33 "Warning: Detected GNOME Keyring, lacking ECDSA support."
for key in "$@"; do
if grep -q "BEGIN EC PRIVATE KEY" "$key"; then
echocolor 31 "Found ECDSA Identity: $key"
echocolor 31 "Identities contain ECDSA key(s). Forcing creation of a private OpenSSH agent."
return 1
fi
done
fi
return 0
}
# === Public API ===
# Check for running agent or start a new one
# Keys will be added if they don't exist.
# Setting start to false will basically do a dry run.
# You should use the aliases below.
ssh_agent() {
# (bool start, string... keys)
local START=$1 && shift
local KEYS="`ssh-add -l 2>/dev/null`"
{ [ $? -eq 2 ] || ! gnome_keyring_ssh_agent_ckeck $SSH_AGENT_PID "$@" || $START && test -n "$LSA_FORCE_AGENT"; } && \
{ $START && private_ssh_agent_start || return 2; }
local RT=0
for key in "$@"; do
echo "$KEYS" | grep -q "$key" \
|| { $START && ssh-add "$key"; } \
|| { RT=1; echocolor 34 "SSH Agent is missing a key: $key"; }
done
return $RT
}
ssh_agent_dry() {
# (string... keys)
ssh_agent false "$@"
}
ssh_agent_begin() {
# (string... keys)
ssh_agent true "$@"
}
ssh_agent_end() {
# (void)
$PRIVATE_SSH_AGENT && private_ssh_agent_stop
}

@ -19,6 +19,7 @@ function color {
} }
alias msg="color 34 echo" alias msg="color 34 echo"
alias warn="color 33 echo"
alias err="color 31 echo" alias err="color 31 echo"
# Ask a question # Ask a question

@ -47,7 +47,7 @@ zstyle ':prezto:load' pmodule \
zstyle ':prezto:module:editor' key-bindings 'emacs' zstyle ':prezto:module:editor' key-bindings 'emacs'
# Auto convert .... to ../.. # Auto convert .... to ../..
# zstyle ':prezto:module:editor' dot-expansion 'yes' zstyle ':prezto:module:editor' dot-expansion 'yes'
# #
# Git # Git
@ -90,7 +90,7 @@ zstyle ':prezto:module:pacman' frontend 'pacaur'
# Set the prompt theme to load. # Set the prompt theme to load.
# Setting it to 'random' loads a random theme. # Setting it to 'random' loads a random theme.
# Auto set to 'off' on dumb terminals. # Auto set to 'off' on dumb terminals.
zstyle ':prezto:module:prompt' theme 'sorin' zstyle ':prezto:module:prompt' theme "steeef"
# #
# Ruby # Ruby

@ -43,6 +43,7 @@ typeset -gU cdpath fpath mailpath path
# Set the list of directories that Zsh searches for programs. # Set the list of directories that Zsh searches for programs.
path=( path=(
$DOTFILES/bin
$HOME/.local/bin $HOME/.local/bin
$HOME/bin $HOME/bin
/usr/local/{bin,sbin} /usr/local/{bin,sbin}

@ -34,5 +34,5 @@ function gupf {
} }
# Local overrides # Local overrides
[[ -e "$DOTDIR/zsh/zshrc.local" ]] && source "$DOTDIR/zsh/zshrc.local" [[ -e "$DOTFILES/zsh/zshrc.local" ]] && source "$DOTFILES/zsh/zshrc.local"

Loading…
Cancel
Save