Skip to content

Instantly share code, notes, and snippets.

@pirogoeth pirogoeth/envmgr.sh
Created Jan 23, 2019

Embed
What would you like to do?
#!/usr/bin/env zsh
# -*- coding: utf-8 -*-
# vim: set ai et ts=4 sts=4 sw=4 syntax=zsh:
set -o pipefail
function __ensure_envdir() {
[[ ! -d "${HOME}/.envmgr.d/" ]] && mkdir -p "${HOME}/.envmgr.d/"
return 0
}
# Function exit codes:
# 0 - Ok
# 1 - ENVNAME missing
# 2 - Environment file missing
# 3 - Environment file already exists
# 127 - Programmer error
function __load_env() {
[[ -z "${1}" ]] && return 1 || ENVNAME=${1}
[[ ! -z "${1}" ]] && ENVNAME=${1}
[[ -f "${HOME}/.envmgr.d/${ENVNAME}.env" ]] && \
source "${HOME}/.envmgr.d/${ENVNAME}.env" && \
$SHELL ; \
return 0
return 2
}
function __new_env() {
[[ -z "${1}" ]] && return 1 || ENVNAME=${1}
[[ ! -z "${1}" ]] && ENVNAME=${1}
[[ ! -f "${HOME}/.envmgr.d/${ENVNAME}.env" ]] && \
touch "${HOME}/.envmgr.d/${ENVNAME}.env" && \
return 0
return 3
}
function __list_envs() {
[[ -d "${HOME}/.envmgr.d" ]] && \
ls ${HOME}/.envmgr.d/*.env | \
xargs -n1 basename | \
cut -d'.' -f1 && \
return 0
return 127
}
function __delete_env() {
[[ -z "${1}" ]] && return 1 || ENVNAME=${1}
[[ -f "${HOME}/.envmgr.d/${ENVNAME}.env" ]] && \
rm -v "${HOME}/.envmgr.d/${ENVNAME}.env" && \
return 0
return 127
}
function __edit_env() {
[[ -z "${EDITOR}" ]] && EDITOR="vim"
[[ ! -z "${1}" ]] && ENVNAME=${1}
[[ -f "${HOME}/.envmgr.d/${ENVNAME}.env" ]] && \
$EDITOR "${HOME}/.envmgr.d/${ENVNAME}.env" && \
return 0
return 2
}
function __handle_command() {
COMMAND="${1}"
shift
case "${COMMAND}" in
new)
ENVNAME="${1}"
__new_env "${ENVNAME}"
__handle_retcode $?
;;
delete)
ENVNAME="${1}"
__delete_env "${ENVNAME}"
__handle_retcode $?
;;
edit)
ENVNAME="${1}"
__edit_env "${ENVNAME}"
__handle_retcode $?
;;
load)
ENVNAME="${1}"
__load_env "${ENVNAME}"
__handle_retcode $?
;;
list)
__list_envs
__handle_retcode $?
;;
help|*)
echo "envmgr - a simple shell environment manager"
echo " commands:"
echo " new [envname]: create a new environment"
echo " delete [envname]: delete an environment"
echo " edit [envname]: open an environment file in your editor"
echo " load [envname]: load an environment"
echo " list: show available environments"
echo
;;
esac
}
function __handle_retcode() {
[[ -z "${1}" ]] && \
echo "No return code provided" && \
return 127
RETURN_CODE=${1}
case "${RETURN_CODE}" in
1)
echo "Environment name required but not provided"
;;
2)
echo "Could not find environment file: ${ENVNAME}"
;;
3)
echo "Environment file already exists: ${ENVNAME}"
;;
127)
echo "This is probably a bug"
;;
esac
exit ${RETURN_CODE}
}
__ensure_envdir
COMMAND=$(echo ${1} | tr '[A-Z]' '[a-z]')
[[ $# > 1 ]] && shift
__handle_command "${COMMAND}" "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.