@@ -0,0 +1,191 @@
#!/usr/bin/env bash
#==============================================================#
# Author: Vonng(fengruohang@outlook.com) #
# Desc : Bash core-utils #
# Dep : None #
#==============================================================#

# module name
declare -g -r __MODULE_COREUTILS="coreutils"


#==============================================================#
# ls #
#==============================================================#
if ls --color > /dev/null 2>&1; then # GNU flavor
colorflag="--color"
else # Darwin flavor
colorflag="-G"
fi

alias sl=ls
alias ll="ls -lh ${colorflag}"
alias l="ls -lh ${colorflag}"
alias la="ls -lha ${colorflag}"
alias lsa="ls -a ${colorflag}"
alias ls="command ls ${colorflag}"
alias lsd="ls -lh ${colorflag} | grep --color=never '^d'" # List only directories
if [ "${TERM}" != "dumb" ]; then
if [ -e "$HOME/.dircolors" ]; then
eval "`dircolors -b $HOME/.dircolors`"
else
export LS_COLORS='no=00:fi=00:di=01;34:ln=01;36:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:\ex=01;32:*.tar=01;31:*.tgz=01;31:*.arj=01;31:*.taz=01;31:*.lzh=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.gz=01;31:*.bz2=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.jpg=01;35:*.jpeg=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:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.avi=01;35:*.fli=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.ogg=01;35:*.mp3=01;35:*.wav=01;35:'
fi
fi
#==============================================================#


#==============================================================#
# cd #
#==============================================================#
alias ~="cd ~"
alias ..="cd .."
alias cd..="cd .."
alias ...="cd ../.."
alias cd...="cd ../.."
alias ....="cd ../../.."
alias .....="cd ../../../.."
#==============================================================#



#==============================================================#
# grep #
#==============================================================#
alias grep="grep --color=auto"
alias fgrep="fgrep --color=auto"
alias egrep="egrep --color=auto"
#==============================================================#



#==============================================================#
# vim #
#==============================================================#
function v() {
if [ $# -eq 0 ]; then
vim .;
else
vim "$@";
fi;
}

alias vi="vim"
alias svim="sudo vim"
alias vvim='vim ${HOME}/.vimrc'
alias vbrc='vim ${HOME}/.bashrc'
alias vbpf='vim ${HOME}/.bash_profile'
alias vssh='vim ${HOME}/.ssh/config'
alias vhst='sudo vim /etc/hosts'
#==============================================================#



#==============================================================#
# Admin #
#==============================================================#
alias tree="find . -print | sed -e 's;[^/]*/;|____;g;s;____|; |;g'"

#--------------------------------------------------------------#
# file back up with timestamp
function buf ()
{
local filename=$1
local filetime=$(date +%Y%m%d_%H%M%S)
cp -r "${filename}" "${filename}_${filetime}"
}

#--------------------------------------------------------------#
# file size
function fs() {
if du -b /dev/null > /dev/null 2>&1; then
local arg=-sbh;
else
local arg=-sh;
fi
if [[ -n "$@" ]]; then
du $arg -- "$@";
else
du $arg .[^.]* *;
fi;
}
#--------------------------------------------------------------#
# disk free
alias df="df -h"
#==============================================================#



#==============================================================#
# Git #
#==============================================================#
alias gst="git status"
alias gci="git commit"
alias gpu="git push origin master"
# Use Git’s colored diff when available
hash git &>/dev/null;
if [ $? -eq 0 ]; then
function diff() {
git diff --no-index --color-words "$@";
}
fi;
#--------------------------------------------------------------#



#==============================================================#
# misc #
#==============================================================#
# bash
alias q='exit'
alias j="jobs"
alias h="history"
alias hg="history | grep --color=auto "
alias cl="clear"
alias clc="clear"
alias rf="rm -rf"
alias ax="chmod a+x";
alias suod='sudo '
alias adm="sudo su admin";
alias admin="sudo su admin";
alias psa="ps aux | grep "
#--------------------------------------------------------------#
function mkcd ()
{
mkdir -p -- "$@" && eval cd -- "\"\$$#\""
}
#--------------------------------------------------------------#
# Map function: ls . | map ls -al
alias map="xargs -n1"
#--------------------------------------------------------------#
# tmux
alias tm="tmux"
alias tma="tmux a -t 0"
#--------------------------------------------------------------#
# ring bell
alias ring="tput bel"
#--------------------------------------------------------------#
# reload shell
alias reload="exec $SHELL -l"
#--------------------------------------------------------------#
# Canonical hex dump; some systems have this symlinked
command -v hd > /dev/null || alias hd="hexdump -C"

#--------------------------------------------------------------#
# calculator
function calc() {
local result="";
result="$(printf "scale=10;$*\n" | bc --mathlib | tr -d '\\\n')";
if [[ "$result" == *.* ]]; then
printf "$result" |
sed -e 's/^\./0./' `# add "0" for cases like ".5"` \
-e 's/^-\./-0./' `# add "0" for cases like "-.5"`\
-e 's/0*$//;s/\.$//'; # remove trailing zeros
else
printf "$result";
fi;
printf "\n";
}
#==============================================================#


@@ -0,0 +1,36 @@
#!/usr/bin/env bash
#==============================================================#
# Author: Vonng(fengruohang@outlook.com) #
# Desc : Bash Crypto Util #
# Dep : None #
#==============================================================#

# module name
declare -g -r __MODULE_CRYPTO="crypto"

#==============================================================#
# Public-Private Key #
#==============================================================#
function genrsa() {
openssl genrsa -out "$1_pri.pem" 1024
openssl rsa -in "$1_pri.pem" -pubout -out "$1_pub.pem"
}
#==============================================================#


#==============================================================#
# Misc #
#==============================================================#
# uuid
alias uuid="uuidgen | tr '[:upper:]' '[:lower:]'"
#==============================================================#



#==============================================================#
# Hash #
#==============================================================#
# OS X hash
command -v md5sum > /dev/null || alias md5sum="md5"
command -v sha1sum > /dev/null || alias sha1sum="shasum"
#==============================================================#
@@ -0,0 +1,104 @@
#!/usr/bin/env bash
#==============================================================#
# Author: Vonng(fengruohang@outlook.com) #
# Desc : Mac OS X specific bash util #
# Dep : None #
#==============================================================#

# module name
declare -g -r __MODULE_DARWIN="darwin"


#==============================================================#
# Darwin #
#==============================================================#
# common dir
alias cloud="cd ~/Library/Mobile\ Documents/com~apple~CloudDocs"
#--------------------------------------------------------------#
# app
alias preview="open -a 'Preview' "
function code (){
if [ $# -eq 0 ]; then
VSCODE_CWD="$PWD" open -n -b "com.microsoft.VSCode" --args ".";
else
VSCODE_CWD="$PWD" open -n -b "com.microsoft.VSCode" --args "$@";
fi;
}
alias safari="open -a safari"
alias firefox="open -a firefox"
alias chrome="open -a google\ chrome"
#--------------------------------------------------------------#
# universal open
function o() {
if [ $# -eq 0 ]; then
open .;
else
open "$@";
fi;
}
#--------------------------------------------------------------#
# cd into finder's directory
function cdf() {
cd "$(osascript -e 'tell app "Finder" to POSIX path of (insertion location as alias)')";
}
#--------------------------------------------------------------#
# rm all .DS_Store
alias rmds='find . -type f -name .DS_Store -delete'
#--------------------------------------------------------------#
# DNS flush
alias dnsflush='dscacheutil -flushcache'
#--------------------------------------------------------------#
# show/hidden files
alias showhidden="defaults write com.apple.finder AppleShowAllFiles TRUE"
alias hidehidden="defaults write com.apple.finder AppleShowAllFiles FALSE"
#--------------------------------------------------------------#
# mute/unmute
alias mute="osascript -e 'set volume output muted true'"
alias unmute="osascript -e 'set volume output muted false'"
#--------------------------------------------------------------#
# Hide/show all desktop icons (useful when presenting)
alias hidedesktop="defaults write com.apple.finder CreateDesktop -bool false && killall Finder"
alias showdesktop="defaults write com.apple.finder CreateDesktop -bool true && killall Finder"
#--------------------------------------------------------------#
# Enable/Disable Spotlight
alias spotoff="sudo mdutil -a -i off"
alias spoton="sudo mdutil -a -i on"
#--------------------------------------------------------------#
# PlistBuddy alias, because sometimes `defaults` just doesn’t cut it
alias plistbuddy="/usr/libexec/PlistBuddy"
#--------------------------------------------------------------#
# Get OS X Software Updates
alias osxupdate='sudo softwareupdate -i -a;'
#--------------------------------------------------------------#
# Clean up LaunchServices to remove duplicates in the “Open With” menu
alias lscleanup="/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -kill -r -domain local -domain system -domain user && killall Finder"
#--------------------------------------------------------------#
# Empty the Trash on all mounted volumes and the main HDD
# Also, clear Apple’s System Logs to improve shell startup speed
alias emptytrash="sudo rm -rfv /Volumes/*/.Trashes; sudo rm -rfv ~/.Trash; sudo rm -rfv /private/var/log/asl/*.asl"
#--------------------------------------------------------------#
# Lock screen
alias afk="/System/Library/CoreServices/Menu\ Extras/User.menu/Contents/Resources/CGSession -suspend"
alias lock="afk"
#--------------------------------------------------------------#
# say something
alias jobdone="say 'Job Done'"

#--------------------------------------------------------------#
# Merge PDF files
# Usage: `mergepdf -o output.pdf input{1,2,3}.pdf`
alias mergepdf='/System/Library/Automator/Combine\ PDF\ Pages.action/Contents/Resources/join.py'
#--------------------------------------------------------------#



#==============================================================#
# homebrew #
#==============================================================#
# Install
# /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

# Mirror
#export HOMEBREW_BOTTLE_DOMAIN=https://mirrors.tuna.tsinghua.edu.cn/homebrew-bottles
#==============================================================#

@@ -0,0 +1,92 @@
#!/usr/bin/env bash
#==============================================================#
# Author: Vonng(fengruohang@outlook.com) #
# Desc : Bash Encoding Util #
# Dep : None #
#==============================================================#

# module name
declare -g -r __MODULE_ENCODING="encoding"

#==============================================================#
# Highlight #
#==============================================================#
# highlight
# require: `pip install pygments`
alias hl=pygmentize

#--------------------------------------------------------------#
# json highlight
# Usage: `json '{"foo":42}'` or `echo '{"foo":42}' | json`
function json() {
if [ -t 0 ]; then # argument
python -mjson.tool <<< "$*" | pygmentize -l javascript;
else # pipe
python -mjson.tool | pygmentize -l javascript;
fi;
}

#--------------------------------------------------------------#
# cat file with auto-detect extension highlight
function ca()
{
filepath=$1
filename=$(basename "$filepath")
extension="${filename##*.}"
cat ${filepath} | pygmentize -l ${extension}
}
#==============================================================#





#--------------------------------------------------------------#
# Format convert
alias yaml2json='ruby -ryaml -rjson -e "puts JSON.pretty_generate(YAML.load(STDIN.read))"'
alias json2yaml='ruby -ryaml -rjson -e "puts YAML.dump(JSON.parse(STDIN.read))"'
#--------------------------------------------------------------#
# URL
alias urlenc='python -c "import sys, urllib as ul; print(ul.quote(sys.argv[1]));"'
alias urldec='python -c "import sys, urllib as ul; print(ul.unquote(sys.argv[1]));"'
#--------------------------------------------------------------#
# Base64
alias b64enc='python -c "import sys,base64 as b;print(b.b64encode(sys.argv[1]));"'
alias b64dec='python -c "import sys,base64 as b;print(b.b64decode(sys.argv[1]));"'
#--------------------------------------------------------------#
# Create a data URL from a file
function dataurl() {
local mimeType=$(file -b --mime-type "$1");
if [[ $mimeType == text/* ]]; then
mimeType="${mimeType};charset=utf-8";
fi
echo "data:${mimeType};base64,$(openssl base64 -in "$1" | tr -d '\n')";
}
#--------------------------------------------------------------#
# UTF-8-encode a string of Unicode symbols
function escape() {
printf "\\\x%s" $(printf "$@" | xxd -p -c1 -u);
# print a newline unless we’re piping the output to another program
if [ -t 1 ]; then
echo ""; # newline
fi;
}
#--------------------------------------------------------------#
# Decode \x{ABCD}-style Unicode escape sequences
function unidec() {
perl -e "binmode(STDOUT, ':utf8'); print \"$@\"";
# print a newline unless we’re piping the output to another program
if [ -t 1 ]; then
echo ""; # newline
fi;
}
#--------------------------------------------------------------#
# Get a character’s Unicode code point
function codepoint() {
perl -e "use utf8; print sprintf('U+%04X', ord(\"$@\"))";
# print a newline unless we’re piping the output to another program
if [ -t 1 ]; then
echo ""; # newline
fi;
}
#==============================================================#
@@ -0,0 +1,60 @@
#!/usr/bin/env bash
#==============================================================#
# Author: Vonng(fengruohang@outlook.com) #
# Desc : Bash Environment Variable & Settings #
# Dep : None #
#==============================================================#

# module name
declare -g -r __MODULE_ENV="env"


#==============================================================#
# Environment #
#==============================================================#
# os
export OS=$(uname)
#--------------------------------------------------------------#
# editor & pager
export EDITOR="vim"
export PAGER="less"
export MANPAGER="less -X";
#--------------------------------------------------------------#
# locale
export LANG="en_US.UTF-8"
export LC_ALL="en_US.UTF-8"
#--------------------------------------------------------------#
# env
ENV="dev"
if [ ${OS} == "Linux" ]; then
ENV="prod"
fi
export ENV
#--------------------------------------------------------------#
# bash history
export HISTSIZE=65535;
export HISTFILESIZE=$HISTSIZE;
export HISTCONTROL=ignoredups;
export HISTIGNORE="l:ls:cd:cd -:pwd:exit:date:* --help";

# append rather than overwrite in bash history
shopt -s histappend;
#--------------------------------------------------------------#
# man page title highlight
export LESS_TERMCAP_md="$(tput setaf 136)";
#==============================================================#



#==============================================================#
# Bash Options #
#==============================================================#
shopt -s nocaseglob; # case-insensitive globbing
shopt -s cdspell; # auto-correct typos in cd
set -o pipefail

# Bash 4 features
for option in autocd globstar; do
shopt -s "$option" 2> /dev/null;
done;
#==============================================================#
@@ -0,0 +1,23 @@
#!/usr/bin/env bash
#==============================================================#
# Author: Vonng(fengruohang@outlook.com) #
# Desc : Linux specific bash util #
# Dep : None #
#==============================================================#

# module name
declare -g -r __MODULE_DARWIN="darwin"


#==============================================================#
# Systemctl #
#==============================================================#
alias sc='systemctl'
alias scr='systemctl daemon-reload'
alias scu='systemctl --user'
alias scur='systemctl --user daemon-reload'
alias sce='systemctl stop'
alias scue='systemctl --user stop'
alias scs='systemctl start'
alias scus='systemctl --user start'
#==============================================================#
@@ -0,0 +1,143 @@
#!/usr/bin/env bash
#==============================================================#
# Author: Vonng(fengruohang@outlook.com) #
# Desc : Standard Bash Log Library #
# Dep : None #
#==============================================================#

# module name
declare -g -r __MODULE_LOG="log"

#--------------------------------------------------------------#
# global variable (int) & public function
# set log level
# $1 : log level (debug:10,info:20,warn:30,error:40,fatal:50)
# default level is INFO:20
#--------------------------------------------------------------#
declare -g -i LOG_LEVEL=20

function log_level(){
local level=$(echo $1 | tr '[:upper:]' '[:lower:]')
case $level in
1|10|d|debug ) LOG_LEVEL=10 ;;
2|20|i|info ) LOG_LEVEL=20 ;;
3|30|w|warn|warning ) LOG_LEVEL=30 ;;
4|40|e|error ) LOG_LEVEL=40 ;;
5|50|f|fatal ) LOG_LEVEL=50 ;;
* ) return 1 ;;
esac
return 0
}


#--------------------------------------------------------------#
# global variable & public function
# set log destination
# $1 : log path ("" represent stderr)
# default destination is stderr with color output enabled
#--------------------------------------------------------------#
declare -g LOG_PATH=""

function log_path(){
LOG_PATH=${1:=''}
}


#--------------------------------------------------------------#
# global variable
# set log timestamp format
# $1 : fmt str (same as date, "" will disable timestamp)
# timestamp disabled by default
#--------------------------------------------------------------#
declare -g LOG_TIME_FMT=""

function log_time_fmt(){
local fmt=${1:=''}
[[ -z ${fmt} ]] && __LOG_TIME_FMT="" return 0
preset_fmt=$(echo $fmt | tr '[:upper:]' '[:lower:]')
case ${preset_fmt} in
datetime|full|dt ) LOG_TIME_FMT="+%Y-%m-%d %H:%M:%S" ;;
date|d ) LOG_TIME_FMT="+%Y-%m-%d" ;;
time|t ) LOG_TIME_FMT="+%H:%M:%S" ;;
ts|timestamp ) LOG_TIME_FMT="+%s" ;;
n|none ) LOG_TIME_FMT="" ;;
* ) LOG_TIME_FMT=${fmt} ;;
esac
return 0
}


#--------------------------------------------------------------#
# private function
# $1 : log level
# $2 : message
#--------------------------------------------------------------#
function __log(){
local -i level=$1
shift
# level less then level setting
(( ${LOG_LEVEL} > level )) && return 0

# determine head and color by level
local head="[LOG] "
local color='\033[0;37m' # white
if (( $level >= 50 )); then head="[FATAL]";color='\033[0;31m' # Red
elif (( $level >= 40 )); then head="[ERROR]";color='\033[0;31m' # Red
elif (( $level >= 30 )); then head="[WARN] ";color='\033[0;33m' # Yellow
elif (( $level >= 20 )); then head="[INFO] ";color='\033[0;32m' # Green
elif (( $level >= 10 )); then head="[DEBUG]";color='\033[0;34m' # Blue
fi

# add timestamp if fmt is specified
local timestamp=""
if [[ "${LOG_TIME_FMT}" == "" ]]; then timestamp=""
else timestamp="[$(date "${LOG_TIME_FMT}")] "
fi

if [[ "${LOG_PATH}" == "" ]]
then
# write to stderr with color
printf "${color}${head}\033[0m\033[0;37m${timestamp}\033[0m$*\n" 1>&2
else
# write to regular file
echo "${head} ${timestamp}$*" >> ${LOG_PATH}
fi
}



#--------------------------------------------------------------#
# public functions
# log with level specified in function name
# $1 : message
#--------------------------------------------------------------#

# blue
function log_debug() {
__log 10 $@
}

# green
function log_info() {
__log 20 $@
}

# orange
function log_warn() {
__log 30 $@
}

function log_warning() {
__log 30 $@
}

# red, write to stderr
function log_error(){
__log 40 $@
}

# red, write to stderr and exit script
function log_fatal(){
__log 50 $@
exit 1
}
@@ -0,0 +1,79 @@
#!/usr/bin/env bash
#==============================================================#
# Author: Vonng(fengruohang@outlook.com) #
# Desc : Bash Network Util #
# Dep : None #
#==============================================================#

# module name
declare -g -r __MODULE_NET="net"


#==============================================================#
# Network #
#==============================================================#
alias cl='curl -sL'
#--------------------------------------------------------------#


function local_ip(){
case $(uname) in
Linux ) local ip=$(ifconfig | grep inet | grep -E '10.|192.168' | head -n1 | awk -F':' '{print $2}' | awk '{print $1}') ;;
Darwin ) local ip=$(ifconfig | grep inet | grep -E '10.|192.168' | head -n1 | awk '{print $2}') ;;
esac
echo $ip
}

#--------------------------------------------------------------#
alias myip="ifconfig -a | grep -o 'inet6\? \(addr:\)\?\s\?\(\(\([0-9]\+\.\)\{3\}[0-9]\+\)\|[a-fA-F0-9:]\+\)' | awk '{ sub(/inet6? (addr:)? ?/, \"\"); print }'"
alias pubip="dig +short myip.opendns.com @resolver1.opendns.com"
#--------------------------------------------------------------#
# Traffic
alias sniff="sudo ngrep -d 'en1' -t '^(GET|POST) ' 'tcp and port 80'"
alias httpdump="sudo tcpdump -i en1 -n -s 0 -w - | grep -a -o -E \"Host\: .*|GET \/.*\""
alias ap="/System/Library/PrivateFrameworks/Apple80211.framework/Versions/A/Resources/airport"
#--------------------------------------------------------------#
# DNS lookup util
function digga() {
dig +nocmd "$1" any +multiline +noall +answer;
}
#--------------------------------------------------------------#
# Show all names in SSL certificate for given domain
function certnames() {
if [ -z "${1}" ]; then
echo "ERROR: No domain specified.";
return 1;
fi;

local domain="${1}";
echo "Testing ${domain}";
echo ""; # newline

local tmp=$(echo -e "GET / HTTP/1.0\nEOT" \
| openssl s_client -connect "${domain}:443" 2>&1);

if [[ "${tmp}" = *"-----BEGIN CERTIFICATE-----"* ]]; then
local certText=$(echo "${tmp}" \
| openssl x509 -text -certopt "no_header, no_serial, no_version, \
no_signame, no_validity, no_issuer, no_pubkey, no_sigdump, no_aux");
echo "Common Name:";
echo ""; # newline
echo "${certText}" | grep "Subject:" | sed -e "s/^.*CN=//";
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;
}
#--------------------------------------------------------------#
# Setup or dismiss (goagent) proxy for curl, wget, etc.
alias gaproxy='export http_proxy=http://127.0.0.1:8087 https_proxy=http://127.0.0.1:8087'
alias noproxy='unset http_proxy https_proxy'
#==============================================================#

alias airport="/System/Library/PrivateFrameworks/Apple80211.framework/Versions/A/Resources/airport"
@@ -0,0 +1,147 @@
#!/usr/bin/env bash
#==============================================================#
# Author: Vonng(fengruohang@outlook.com) #
# Desc : Bash Network Util #
# Dep : None #
#==============================================================#

# module name
declare -g -r __MODULE_PATH="PATH"

#==============================================================#
# Go #
#==============================================================#
GOROOT=${GOROOT:=/usr/local/go}
if [[ -d $GOROOT ]]; then
export GOROOT
PATH="${GOROOT}/bin:${PATH}"
else
unset GOROOT
fi
#--------------------------------------------------------------#
GOPATH=${GOPATH:=${HOME}/go}
if [[ -d $GOPATH ]]; then
export GOPATH
PATH="${GOPATH}/bin:${PATH}"
else
if [[ -d ${HOME}/Dev/go ]]; then
export GOPATH=${HOME}/Dev/go
else
unset GOPATH
fi
fi
#==============================================================#



#==============================================================#
# Postgres #
#==============================================================#
PG_HOME=${PG_HOME:="/usr/local/pgsql"}
if [[ -d $PG_HOME ]]; then
PATH="${PG_HOME}/bin:${PATH}"
else
unset PG_HOME
fi
#==============================================================#



#==============================================================#
# Python #
#==============================================================#
# anaconda
PYTHONHOME=${PYTHONHOME:="${HOME}/anaconda"}
if [[ -d $PYTHONHOME ]]; then
export PYTHONHOME
PATH="${PATH}":${PYTHONHOME}/bin
else
unset PYTHONHOME
fi
#--------------------------------------------------------------#
# alias
alias py=python
alias p="ipython"
alias qt="nohup jupyter qtconsole &"
#--------------------------------------------------------------#
# Tsinghua conda mirror
function py_config_conda(){
conda config --add channels 'https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/'
conda config --set show_channel_urls yes
}
#--------------------------------------------------------------#
# Tsinghua pip mirror
function py_config_pip(){
# pip install -i https://pypi.tuna.tsinghua.edu.cn/simple some-package
mkdir -p ~/.pip/
cat > ~/.pip/pip.conf << EOF
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple
EOF
}
#==============================================================#



#==============================================================#
# Nginx #
#==============================================================#
NGINX_HOME=${NGINX_HOME:=/usr/local/nginx}
if [ -d ${NGINX_HOME} ]; then
export NGINX_HOME
alias nginx_conf="sudo vi ${NGINX_HOME}/nginx.conf"
alias nginx_start="sudo ${NGINX_HOME}/nginx"
alias nginx_reload="sudo ${NGINX_HOME}/nginx -s reload"
PATH="$PATH:${NGINX_HOME}/bin"
else
unset NGINX_HOME
fi
#==============================================================#



#==============================================================#
# Java #
#==============================================================#
# java
if [[ -z "${JAVA_HOME}" ]]; then
case $(uname) in
Darwin ) JAVA_HOME=`/usr/libexec/java_home 2>/dev/null` ;;
Linux ) JAVA_HOME="/usr/local/java" ;;
esac
fi

if [ -d "${JAVA_HOME}" ]; then
export JAVA_HOME
export CLASSPATH=".:${JAVA_HOME}/lib/dt.jar:${JAVA_HOME}/lib/tools.jar"
PATH="$PATH:${JAVA_HOME}/bin"
else
unset JAVA_HOME
fi
#==============================================================#



#==============================================================#
# Node #
#==============================================================#
# node
NODE_HOME=${NODE_HOME:=/usr/local/node}
if [ -d ${NODE_HOME} ]; then
PATH="$PATH:${NODE_HOME}/bin"
alias cnpm="npm --registry=https://registry.npm.taobao.org \
--cache=$HOME/.npm/.cache/cnpm \
--disturl=https://npm.taobao.org/dist \
--userconfig=$HOME/.cnpmrc"

fi

#==============================================================#



#==============================================================#
# PATH #
#==============================================================#
export PATH=$(echo -n $PATH | tr : "\n"| uniq | tr "\n" :)
#==============================================================#
@@ -0,0 +1,55 @@
#!/usr/bin/env bash
#==============================================================#
# Author: Vonng(fengruohang@outlook.com) #
# Desc : PostgreSQL Util #
# Dep : None #
#==============================================================#

# module name
declare -g -r __MODULE_PG="pg"


#==============================================================#
# Postgres #
#==============================================================#
export PGDATA="/var/lib/pgsql/data"
PGDATA=${PGDATA:=/var/lib/pgsql/data}

if [[ -d ${PGDATA} ]]; then
export PGDATA
else
unset PGDATA
fi
#--------------------------------------------------------------#
PGCTL=$(which pg_ctl)
#--------------------------------------------------------------#


#--------------------------------------------------------------#
# alias
alias pg_su="sudo su - postgres"
alias pg_start="${PGCTL} start -D ${PGDATA} -l ${PGDATA}/log"
alias pg_stop="${PGCTL} stop -D ${PGDATA}"
alias pg_restart="${PGCTL} restart -D ${PGDATA}"
alias pg_reload="${PGCTL} reload"
alias pg_conf="vim ${PGDATA}/postgresql.conf"
alias pg_hba="vim ${PGDATA}/pg_hba.conf"

#--------------------------------------------------------------#
# psql standard output to markdown
alias pg2md=" sed 's/+/|/g' | sed 's/^/|/' | sed 's/$/|/' | grep -v rows | grep -v '||'"
# Usage: `psql -c 'select * from account' | pg2md`
#--------------------------------------------------------------#
# Usage: pgschema <database> <table>
function pgschema(){
SQL="SELECT
column_name AS name,
column_default AS default,
is_nullable AS nullable,
udt_name AS type
FROM information_schema.columns
WHERE table_name = '$2'
ORDER BY ordinal_position;"
psql $1 -c "${SQL}" | sed 's/+/|/g' | sed 's/^/|/' | sed 's/$/|/' | grep -v rows | grep -v '||'
}
#==============================================================#
@@ -0,0 +1,146 @@
#!/usr/bin/env bash
#==============================================================#
# Author: Vonng(fengruohang@outlook.com) #
# Desc : Bash Prompt Setting #
# Dep : None #
#==============================================================#

# module name
declare -g -r __MODULE_PROMPT="prompt"


#==============================================================#
# Theme #
#==============================================================#
# term
if [[ ${COLORTERM} = gnome-* && ${TERM} = xterm ]] && infocmp gnome-256color >/dev/null 2>&1; then
export TERM='gnome-256color';
elif infocmp xterm-256color >/dev/null 2>&1; then
export TERM='xterm-256color';
fi;

#==============================================================#
# Color #
#==============================================================#
if tput setaf 1 &> /dev/null; then
tput sgr0; # reset colors
bold=$(tput bold);
reset=$(tput sgr0);
black=$(tput setaf 0);
blue=$(tput setaf 33);
cyan=$(tput setaf 37);
green=$(tput setaf 64);
orange=$(tput setaf 166);
purple=$(tput setaf 125);
red=$(tput setaf 124);
violet=$(tput setaf 61);
white=$(tput setaf 15);
yellow=$(tput setaf 136);
else
bold='';
reset="\e[0m";
black="\e[1;30m";
blue="\e[1;34m";
cyan="\e[1;36m";
green="\e[1;32m";
orange="\e[1;33m";
purple="\e[1;35m";
red="\e[1;31m";
violet="\e[1;35m";
white="\e[1;37m";
yellow="\e[1;33m";
fi;
#==============================================================#


#--------------------------------------------------------------#
prompt_git() {
local s='';
local branchName='';

# Check if the current directory is in a Git repository.
if [ $(git rev-parse --is-inside-work-tree &>/dev/null; echo "${?}") == '0' ]; then

# check if the current directory is in .git before running git checks
if [ "$(git rev-parse --is-inside-git-dir 2> /dev/null)" == 'false' ]; then

# Ensure the index is up to date.
git update-index --really-refresh -q &>/dev/null;

# Check for uncommitted changes in the index.
if ! $(git diff --quiet --ignore-submodules --cached); then
s+='+';
fi;

# Check for unstaged changes.
if ! $(git diff-files --quiet --ignore-submodules --); then
s+='!';
fi;

# Check for untracked files.
if [ -n "$(git ls-files --others --exclude-standard)" ]; then
s+='?';
fi;

# Check for stashed files.
if $(git rev-parse --verify refs/stash &>/dev/null); then
s+='$';
fi;
fi;

# Get the short symbolic ref.
# If HEAD isn’t a symbolic ref, get the short SHA for the latest commit
# Otherwise, just give up.
branchName="$(git symbolic-ref --quiet --short HEAD 2> /dev/null || \
git rev-parse --short HEAD 2> /dev/null || \
echo '(unknown)')";

[ -n "${s}" ] && s=" [${s}]";

echo -e "${1}${branchName}${blue}${s}";
else
return;
fi;
}
#--------------------------------------------------------------#
prompt_venv() {
# Get current Python virtual env if any.
if [[ "$VIRTUAL_ENV" != "" ]]; then
# Strip out the path and just leave the env name.
echo -e "${1}(${VIRTUAL_ENV##*/})"
fi;
}
#--------------------------------------------------------------#
# root with orange
if [[ "${USER}" == "root" ]]; then
userStyle="${red}";
else
userStyle="${orange}";
fi;
#--------------------------------------------------------------#
# ssh with red, local with yellow
if [[ "${SSH_TTY}" ]]; then
hostStyle="${bold}${red}";
else
hostStyle="${yellow}";
fi;
#--------------------------------------------------------------#
# PS1
PS1="\[\033]0;\w\007\]";
PS1+="\[${bold}\]\n"; # newline
PS1+="\[${cyan}\][\t] "
PS1+="\[${userStyle}\]\u"; # username
PS1+="\[${hostStyle}\]@";
PS1+="\[${hostStyle}\]\h"; # host
PS1+="\$(prompt_venv \"${white} ${purple}\" 2>/dev/null)"; # virtual env
PS1+="\[${white}\] ";
PS1+="\[${green}\]\w"; # working directory
PS1+="\$(prompt_git \"${hostStyle} on ${violet}\" 2>/dev/null)"; # Git repository details
PS1+="\n";
PS1+="\[${violet}\]\$ \[${reset}\]"; # `$` (and reset color)
export PS1;
#--------------------------------------------------------------#
# PS2
PS2="\[${yellow}\]→ \[${reset}\]";
export PS2;
#==============================================================#
@@ -0,0 +1,50 @@
#!/usr/bin/env bash
#==============================================================#
# Author: Vonng(fengruohang@outlook.com) #
# Desc : Bash String Util #
# Dep : None #
#==============================================================#

# module name
declare -g -r __MODULE_STRING="string"


#==============================================================#
# encoding #
#==============================================================#
# lower/upper
# Usage: `upper abc` or echo abc | upper
function upper() {
if [ -t 0 ]; then # argument
tr '[:lower:]' '[:upper:]' <<< "$*"
else # pipe
tr '[:lower:]' '[:upper:]'
fi;
}

function lower() {
if [ -t 0 ]; then # argument
tr tr '[:upper:]' '[:lower:]' <<< "$*"
else # pipe
tr tr '[:upper:]' '[:lower:]'
fi;
}
#--------------------------------------------------------------#
# str length

# arg 1 : string
# ret : char count in string
# also archive by `${#1}` in correct locale
function len(){
declare -i charLen=$(echo -n ${1} | wc -m)
echo ${charLen}
}

# arg 1 : string
# ret : byte count in string
# also achieve by `LANG=C LC_ALL=C ${#1}` in locale C
function blen(){
declare -i charLen=$(echo -n ${1} | wc -c)
echo ${charLen}
}
#--------------------------------------------------------------#
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
#==============================================================#
# Author: Vonng(fengruohang@outlook.com) #
# Desc : Bash Sync Util #
# Dep : None #
#==============================================================#

# module name
declare -g -r __MODULE_SYNC="sync"
@@ -0,0 +1,31 @@
#!/usr/bin/env bash
#==============================================================#
# Author: Vonng(fengruohang@outlook.com) #
# Desc : Bash Time Util #
# Dep : None #
#==============================================================#

# module name
declare -g -r __MODULE_TIME="time"


#==============================================================#
# datetime #
#==============================================================#
# datetime
alias now='date +"DATE: %Y-%m-%d TIME: %H:%M:%S EPOCH: %s"'
alias today='date +"%Y%m%d "'
alias week='date +%V'


function yesterday(){
case $(uname) in
Linux ) local ds=$(date -d 'yesterday' +%Y%m%d) ;;
Darwin ) local ds=$(date -v -24H +%Y%m%d) ;;
esac
echo $ds
}

# stopwatch
alias timer='echo "Timer started. Stop with Ctrl-D." && date && time cat && date'
#==============================================================#
@@ -0,0 +1,50 @@
#!/usr/bin/env bash
#==============================================================#
# Author: Vonng(fengruohang@outlook.com) #
# Desc : Bash Standard Library Core #
# Usage : source <path to this file> #
#==============================================================#

#--------------------------------------------------------------#
# global variable
#--------------------------------------------------------------#
declare -g -x OS=$(uname)
declare -g -x SHIT_PATH=${SHTI_PATH:=${HOME}/.shit}
if [[ ! -d ${SHIT_PATH} ]]; then
PROGDIR="$(cd $(dirname $0) && pwd)"

fi

#--------------------------------------------------------------#
# public function #
# import bash library in ${SHIT_PATH} #
# $1 : package name (e.g: log color ...) #
#--------------------------------------------------------------#
function __import(){
local package=${1}
local include_marco="__MODULE_$(echo $1 | tr '[:lower:]' '[:upper:]')"

# already import
if [[ -n "${!include_marco}" ]]
then
return 0
fi

package="${SHIT_PATH}/lib/${package%.sh}.sh"
if [[ -f ${package} ]]
then
source ${package}
return 0
else
return 1
fi
}

#--------------------------------------------------------------#
function import(){
for pkg in $@
do
__import ${pkg}
done
}
#==============================================================#
@@ -0,0 +1,32 @@
SHIT_PATH=$(HOME)/.shit
PROFILE_PATH=$(HOME)/.bash_profile
PWD:=$(shell pwd)

COMMAND1='[[ -f ${HOME}/.shit/main ]] && source ${HOME}/.shit/main'
COMMAND2='[[ -f ${HOME}/.shit/shitrc ]] && source ${HOME}/.shit/shitrc'

install:
rm -rf $(SHIT_PATH) && mkdir -p $(SHIT_PATH)
cp -r ./{lib,bin,main,shitrc} $(SHIT_PATH)/
sed -ie '/shit\/main/d' $(PROFILE_PATH)
sed -ie '/shit\/shitrc/d' $(PROFILE_PATH)
echo $(COMMAND1) >> $(PROFILE_PATH)
echo $(COMMAND2) >> $(PROFILE_PATH)

link:
rm -rf $(SHIT_PATH) && mkdir -p $(SHIT_PATH)
ln -s $(PWD)/{lib,bin,main,shitrc} $(SHIT_PATH)/
sed -ie '/shit\/main/d' $(PROFILE_PATH)
sed -ie '/shit\/shitrc/d' $(PROFILE_PATH)
echo $(COMMAND1) >> $(PROFILE_PATH)
echo $(COMMAND2) >> $(PROFILE_PATH)

uninstall:
sed -ie '/shit\/main/d' $(PROFILE_PATH)
sed -ie '/shit\/shitrc/d' $(PROFILE_PATH)
rm -rf $(HOME)/.shit

private:
cp .private $(HOME)/

.PHONY: install
@@ -0,0 +1,10 @@
#!/usr/bin/env bash
#==============================================================#
# Author: Vonng(fengruohang@outlook.com) #
# Desc : Bash Profile #
#==============================================================#

[[ -r "$HOME/.bashrc" ]] && source $HOME/.bashrc
[[ -f "$HOME/.shit/main" ]] && source $HOME/.shit/main
[[ -f "$HOME/.shit/shitrc" ]] && source $HOME/.shit/shitrc

@@ -0,0 +1,27 @@
#!/usr/bin/env bash

# You must run `source .shit/main` before execute this

import env
import path
import color
import prompt
import log
import completion
import coreutils
import crypto
import encoding
import net
import pg
import string
import sync
import time

case $(uname) in
Darwin ) import darwin ;;
Linux ) import linux ;;
esac

set +e

[[ -f ${HOME}/.private ]] && source ${HOME}/.private