Merge branch 'master' into feature/pre-commit-hook

* master: (285 commits)
  added git alias to list remote branch creators with date and time
  Add Kind support
  Fix the commandline for gifski
  Add Terraform and Terragrunt aliases
  lib: helpers: Handle stable revert update
  lib: helpers: Rename Upgrading -> Updating
  lib: Fetch from remote before calculating latest tag in bash-it update
  test: Add completion test for -s --silent flag
  completion: Add --silent and -s completion
  doc: Add --silent flag documentation
  helpers: Add --slient option to bash-it update
  lib: Update no-op message in case of stable update
  lib: Add BASH_IT_DEVELOPMENT_BRANCH variable
  lib: Update to stable now correctly fails if no tags are present
  doc: Add stable/dev option to update section
  completion: Update completion for new bash-it update
  lib: Improve bash-it update so it can update to latest tag
  alias: git: Add new pretty git log alias (ggf)
  alias: git: Add git pull / git push --force aliases
  Add bash-it restart command
  ...
pull/1434/head^2
Ira Abramov 2020-10-17 11:56:55 +03:00
commit 05934b2883
131 changed files with 3192 additions and 10367 deletions

View File

@ -1,32 +1,15 @@
# EditorConfig is awesome: http://EditorConfig.org # EditorConfig is awesome: http://EditorConfig.org
[*] [*]
indent_style = tab indent_style = space
indent_size = 4 indent_size = 2
end_of_line = lf
shell_variant = bash charset = utf-8
binary_next_line = true # like -bn
switch_case_indent = true # like -ci
space_redirects = true # like -sr
keep_padding = true # like -kp
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true trim_trailing_whitespace = true
insert_final_newline = true insert_final_newline = true
[*.md] [*.md]
trim_trailing_whitespace = false trim_trailing_whitespace = false
[*.*sh] [.git*]
indent_style = tab indent_style = tab
indent_size = 4
shell_variant = bash
binary_next_line = true # like -bn
switch_case_indent = true # like -ci
space_redirects = true # like -sr
keep_padding = true # like -kp
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

10
.gitmodules vendored
View File

@ -1,12 +1,16 @@
[submodule "test_lib/bats-core"] [submodule "test_lib/bats-core"]
path = test_lib/bats-core path = test_lib/bats-core
url = https://github.com/bats-core/bats-core url = https://github.com/bats-core/bats-core
branch = tags/v1.2.0
[submodule "test_lib/bats-support"] [submodule "test_lib/bats-support"]
path = test_lib/bats-support path = test_lib/bats-support
url = https://github.com/ztombol/bats-support url = https://github.com/bats-core/bats-support
branch = tags/v0.3.0
[submodule "test_lib/bats-assert"] [submodule "test_lib/bats-assert"]
path = test_lib/bats-assert path = test_lib/bats-assert
url = https://github.com/ztombol/bats-assert url = https://github.com/bats-core/bats-assert
branch = tags/v2.0.0
[submodule "test_lib/bats-file"] [submodule "test_lib/bats-file"]
path = test_lib/bats-file path = test_lib/bats-file
url = https://github.com/ztombol/bats-file url = https://github.com/bats-core/bats-file
branch = tags/v0.3.0

View File

@ -1,6 +1,31 @@
sudo: false # YAML anchors need to appear first.
script: test/run # Keys starting with an underscore are the custom ones, refer to
language: c # https://docs.travis-ci.com/user/build-config-yaml#private-keys-as-yaml-anchors-and-aliases-and-external-tooling
os:
- linux _native_job: &native_job
- osx script: |
test/run
language: shell
os: linux
dist: xenial
jobs:
- <<: *native_job
name: Ubuntu 16.04
- <<: *native_job
name: Ubuntu 18.04
dist: bionic
- <<: *native_job
name: MacOS xcode9.4
os: osx
osx_image: xcode9.4 # Default xcode on Travis.
- <<: *native_job
name: MacOS xcode11.5
os: osx
osx_image: xcode11.5 # Latest xcode on Travis.

View File

@ -2,6 +2,22 @@
This page summarizes a couple of rules to keep in mind when developing features or making changes in Bash-it. This page summarizes a couple of rules to keep in mind when developing features or making changes in Bash-it.
## Debugging and Logging
### General Logging
While developing feature or making changes in general, you can log error/warning/debug
using `_log_error` `_log_warning` and `_log_debug`. This will help you solve problems quicker
and also propagate important notes to other users of Bash-it.
You can see the logs by using `bash-it doctor` command to reload and see the logs.
Alternatively, you can set `BASH_IT_LOG_LEVEL` to `BASH_IT_LOG_LEVEL_ERROR`, `BASH_IT_LOG_LEVEL_WARNING` or `BASH_IT_LOG_LEVEL_ALL`.
### Log Prefix/Context
You can define `BASH_IT_LOG_PREFIX` in your files in order to a have a constant prefix before your logs.
Note that we prefer to uses "tags" based logging, i.e `plugins: git: DEBUG: Loading git plugin`.
## Load Order ## Load Order
### General Load Order ### General Load Order
@ -44,6 +60,11 @@ Having the order based on a numeric priority in a common directory allows for mo
These items are subject to change. When making changes to the internal functionality, this page needs to be updated as well. These items are subject to change. When making changes to the internal functionality, this page needs to be updated as well.
## Plugin Disable Callbacks
Plugins can define a function that will be called when the plugin is being disabled.
The callback name should be `{PLUGIN_NAME}_on_disable`, you can see `gitstatus` for usage example.
## Using the pre-commit hook ## Using the pre-commit hook
Note the file .pre-commit-config.yaml at the top of the repo. Note the file .pre-commit-config.yaml at the top of the repo.

View File

@ -1,6 +1,7 @@
# Bash-it # Bash-it
[![Build Status](https://travis-ci.org/Bash-it/bash-it.svg?branch=master)](https://travis-ci.org/Bash-it/bash-it) [![Join the chat at https://gitter.im/Bash-it/bash-it](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/Bash-it/bash-it?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Build Status](https://travis-ci.com/Bash-it/bash-it.svg?branch=master)](https://travis-ci.com/Bash-it/bash-it)
[![Join the chat at https://gitter.im/Bash-it/bash-it](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/Bash-it/bash-it?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
**Bash-it** is a collection of community Bash commands and scripts for Bash 3.2+. **Bash-it** is a collection of community Bash commands and scripts for Bash 3.2+.
(And a shameless ripoff of [oh-my-zsh](https://github.com/robbyrussell/oh-my-zsh) :smiley:) (And a shameless ripoff of [oh-my-zsh](https://github.com/robbyrussell/oh-my-zsh) :smiley:)
@ -86,13 +87,24 @@ Have a look at our [bash-it-docker repository](https://github.com/Bash-it/bash-i
### Updating ### Updating
To update Bash-it to the latest version, simply run: To update Bash-it to the latest stable version, simply run:
```bash ```bash
bash-it update bash-it update stable
``` ```
that's all. If you want to update to the latest dev version (directly from master), run:
```bash
bash-it update dev
```
If you want to update automatically and unattended, you can add the optional
`-s/--silent` flag, for example:
```bash
bash-it update dev --silent
```
If you are using an older version of Bash-it, it's possible that some functionality has changed, or that the internal structure of how Bash-it organizes its functionality has been updated. If you are using an older version of Bash-it, it's possible that some functionality has changed, or that the internal structure of how Bash-it organizes its functionality has been updated.
For these cases, we provide a `migrate` command: For these cases, we provide a `migrate` command:
@ -394,6 +406,13 @@ $ git config --global --add bash-it.hide-status 1
Setting this flag globally has the same effect as `SCM_CHECK=true`, but only for Git repos. Setting this flag globally has the same effect as `SCM_CHECK=true`, but only for Git repos.
### Speed up git status calculations
As an alternative to ignoring repo status entirely, you can try out the `gitstatus` plugin.
This plugin speeds up all `git status` calculations by up to 10x times!
**NOTE**: You will need to clone `gitstatus` repo from [here](https://github.com/romkatv/gitstatus).
### Pass function renamed to passgen ### Pass function renamed to passgen
The Bash-it `pass` function has been renamed to `passgen` in order to avoid a naming conflict with the [pass password manager](https://www.passwordstore.org/). The Bash-it `pass` function has been renamed to `passgen` in order to avoid a naming conflict with the [pass password manager](https://www.passwordstore.org/).
@ -409,6 +428,20 @@ Unset `BASH_IT_LEGACY_PASS` to have Bash-it **return to default behavior**:
* `unset BASH_IT_LEGACY_PASS` * `unset BASH_IT_LEGACY_PASS`
### Debugging
If you encounter problems with any part of Bash-it, run the following command:
```bash
bash-it doctor
```
This will reload your bash profile and print out logs of various parts in Bash-it.
Note that this command at default will print all logs, including debug logs.
You can call it like this:
```bash
bash-it doctor [errors/warnings/all]
```
In order to get wanted verbosity.
### Proxy Support ### Proxy Support
If you are working in a corporate environment where you have to go through a proxy server for internet access, If you are working in a corporate environment where you have to go through a proxy server for internet access,

View File

@ -0,0 +1,23 @@
cite about-alias
about-alias 'Aliases for the bash-it command (these aliases are automatically included with the "general" aliases)'
# Common misspellings of bash-it
alias shit='bash-it'
alias batshit='bash-it'
alias bashit='bash-it'
alias batbsh='bash-it'
alias babsh='bash-it'
alias bash_it='bash-it'
alias bash_ti='bash-it'
# Additional bash-it aliases for help/show
alias bshsa='bash-it show aliases'
alias bshsc='bash-it show completions'
alias bshsp='bash-it show plugins'
alias bshha='bash-it help aliases'
alias bshhc='bash-it help completions'
alias bshhp='bash-it help plugins'
alias bshsch="bash-it search"
alias bshenp="bash-it enable plugin"
alias bshena="bash-it enable alias"
alias bshenc="bash-it enable completion"

View File

@ -2,6 +2,8 @@ cite 'about-alias'
about-alias 'docker-compose abbreviations' about-alias 'docker-compose abbreviations'
alias dco="docker-compose" alias dco="docker-compose"
# Defined in the `docker-compose` plugin, please check there for details.
alias dcofresh="docker-compose-fresh" alias dcofresh="docker-compose-fresh"
alias dcol="docker-compose logs -f --tail 100" alias dcol="docker-compose logs -f --tail 100"
alias dcou="docker-compose up" alias dcou="docker-compose up"

View File

@ -33,7 +33,9 @@ alias dkrmflast='docker rm -f $(dklcid)'
alias dkbash='dkelc' alias dkbash='dkelc'
alias dkex='docker exec -it ' # Useful to run any commands into container without leaving host alias dkex='docker exec -it ' # Useful to run any commands into container without leaving host
alias dkri='docker run --rm -i ' alias dkri='docker run --rm -i '
alias dkric='docker run --rm -i -v $PWD:/cwd -w /cwd '
alias dkrit='docker run --rm -it ' alias dkrit='docker run --rm -it '
alias dkritc='docker run --rm -it -v $PWD:/cwd -w /cwd '
# Added more recent cleanup options from newer docker versions # Added more recent cleanup options from newer docker versions
alias dkip='docker image prune -a -f' alias dkip='docker image prune -a -f'

View File

@ -1,3 +1,11 @@
# https://github.com/nvbn/thefuck cite 'about-alias'
alias fuck='eval $(thefuck $(fc -ln -1))' about-alias 'fuck/please to retry last command with sudo'
alias please='fuck'
# Play nicely with 'thefuck' plugin
if ! _command_exists fuck ; then
alias fuck='sudo $(fc -ln -1)'
fi
alias please=fuck
alias plz=please
alias fucking=sudo

View File

@ -28,7 +28,6 @@ alias vbpf="vim ~/.bash_profile"
if grep --color=auto "a" "${BASH_IT}/"*.md &> /dev/null if grep --color=auto "a" "${BASH_IT}/"*.md &> /dev/null
then then
alias grep='grep --color=auto' alias grep='grep --color=auto'
export GREP_COLOR='1;33'
fi fi
if which gshuf &> /dev/null if which gshuf &> /dev/null
@ -75,27 +74,6 @@ fi
alias md='mkdir -p' alias md='mkdir -p'
alias rd='rmdir' alias rd='rmdir'
# Common misspellings of bash-it
alias shit='bash-it'
alias batshit='bash-it'
alias bashit='bash-it'
alias batbsh='bash-it'
alias babsh='bash-it'
alias bash_it='bash-it'
alias bash_ti='bash-it'
# Additional bash-it aliases for help/show
alias bshsa='bash-it show aliases'
alias bshsc='bash-it show completions'
alias bshsp='bash-it show plugins'
alias bshha='bash-it help aliases'
alias bshhc='bash-it help completions'
alias bshhp='bash-it help plugins'
alias bshsch="bash-it search"
alias bshenp="bash-it enable plugin"
alias bshena="bash-it enable alias"
alias bshenc="bash-it enable completion"
# Shorten extract # Shorten extract
alias xt="extract" alias xt="extract"
@ -113,3 +91,12 @@ catt() {
fi fi
done done
} }
# The Bash-it aliases were moved to the `bash-it.aliases.bash` file. The intent of this
# is to keep the script readable and less bloated. If you don't need to use
# the `general` aliases, but you want the Bash-it aliases, you can disable the `general`
# aliases and enable just the ones for Bash-it explicitly:
# bash-it disable alias general
# bash-it enable alias bash-it
# shellcheck source=./bash-it.aliases.bash
source "$BASH_IT/aliases/available/bash-it.aliases.bash"

View File

@ -22,12 +22,13 @@ alias gs='git status'
alias gss='git status -s' alias gss='git status -s'
alias gsu='git submodule update --init --recursive' alias gsu='git submodule update --init --recursive'
alias gl='git pull' alias gl='git pull'
alias gpl='git pull'
alias glum='git pull upstream master' alias glum='git pull upstream master'
alias gpr='git pull --rebase' alias gpr='git pull --rebase'
alias gpp='git pull && git push' alias gpp='git pull && git push'
alias gup='git fetch && git rebase' alias gup='git fetch && git rebase'
alias gp='git push' alias gp='git push'
alias gpo='git push origin' alias gpo='git push origin HEAD'
alias gpu='git push --set-upstream' alias gpu='git push --set-upstream'
alias gpuo='git push --set-upstream origin' alias gpuo='git push --set-upstream origin'
alias gpuoc='git push --set-upstream origin $(git symbolic-ref --short HEAD)' alias gpuoc='git push --set-upstream origin $(git symbolic-ref --short HEAD)'
@ -35,16 +36,23 @@ alias gpom='git push origin master'
alias gr='git remote' alias gr='git remote'
alias grv='git remote -v' alias grv='git remote -v'
alias gra='git remote add' alias gra='git remote add'
alias grb='git rebase'
alias grm='git rebase master'
alias grmi='git rebase master -i'
alias gd='git diff' alias gd='git diff'
alias gds='git diff --staged' alias gds='git diff --staged'
alias gdt='git difftool'
alias gdv='git diff -w "$@" | vim -R -' alias gdv='git diff -w "$@" | vim -R -'
alias gc='git commit -v' alias gc='git commit -v'
alias gca='git commit -v -a' alias gca='git commit -v -a'
alias gcm='git commit -v -m' alias gcm='git commit -v -m'
alias gcam="git commit -v -am" alias gcam="git commit -v -am"
alias gci='git commit --interactive' alias gci='git commit --interactive'
alias gcamd='git commit --amend'
alias gb='git branch' alias gb='git branch'
alias gba='git branch -a' alias gba='git branch -a'
# FROM https://stackoverflow.com/a/58623139/10362396
alias gbc='git for-each-ref --format="%(authorname) %09 %(if)%(HEAD)%(then)*%(else)%(refname:short)%(end) %09 %(creatordate)" refs/remotes/ --sort=authorname DESC'
alias gbt='git branch --track' alias gbt='git branch --track'
alias gbm='git branch -m' alias gbm='git branch -m'
alias gbd='git branch -d' alias gbd='git branch -d'
@ -63,7 +71,9 @@ alias gdel='git branch -D'
alias gmu='git fetch origin -v; git fetch upstream -v; git merge upstream/master' alias gmu='git fetch origin -v; git fetch upstream -v; git merge upstream/master'
alias gll='git log --graph --pretty=oneline --abbrev-commit' alias gll='git log --graph --pretty=oneline --abbrev-commit'
alias gg="git log --graph --pretty=format:'%C(bold)%h%Creset%C(magenta)%d%Creset %s %C(yellow)<%an> %C(cyan)(%cr)%Creset' --abbrev-commit --date=relative" alias gg="git log --graph --pretty=format:'%C(bold)%h%Creset%C(magenta)%d%Creset %s %C(yellow)<%an> %C(cyan)(%cr)%Creset' --abbrev-commit --date=relative"
alias ggf="git log --graph --date=short --pretty=format:'%C(auto)%h %Cgreen%an%Creset %Cblue%cd%Creset %C(auto)%d %s'"
alias ggs="gg --stat" alias ggs="gg --stat"
alias gsh="git show"
alias gsl="git shortlog -sn" alias gsl="git shortlog -sn"
alias gwc="git whatchanged" alias gwc="git whatchanged"
alias gt="git tag" alias gt="git tag"
@ -76,14 +86,38 @@ alias gpatch="git format-patch -1"
alias gnew="git log HEAD@{1}..HEAD@{0}" alias gnew="git log HEAD@{1}..HEAD@{0}"
# Add uncommitted and unstaged changes to the last commit # Add uncommitted and unstaged changes to the last commit
alias gcaa="git commit -a --amend -C HEAD" alias gcaa="git commit -a --amend -C HEAD"
# Rebase with latest remote master
alias gprom="git fetch origin master && git rebase origin/master && git update-ref refs/heads/master origin/master"
alias gpf="git push --force"
alias gpunch="git push --force-with-lease"
alias ggui="git gui" alias ggui="git gui"
alias gcsam="git commit -S -am" alias gcsam="git commit -S -am"
# Stash aliases
alias gst="git stash" alias gst="git stash"
alias gstb="git stash branch" alias gstb="git stash branch"
alias gstd="git stash drop" alias gstd="git stash drop"
alias gstl="git stash list" alias gstl="git stash list"
# Push introduced in git v2.13.2
alias gstpu="git stash push"
alias gstpum="git stash push -m"
# Save deprecated since git v2.16.0
# - aliases now resolve to push
alias gsts="git stash push"
alias gstsm="git stash push -m"
# Alias gstpo added for symmetry with gstpu (push)
# - gstp remains as alias for pop due to long-standing usage
alias gstpo="git stash pop"
alias gstp="git stash pop" alias gstp="git stash pop"
alias gh='cd "$(git rev-parse --show-toplevel)"' # Switch aliases - Requires git v2.23+
alias gsw="git switch"
alias gswm="git switch master"
alias gswc="git switch --create"
alias gswt="git switch --track"
# Git home
alias ghm='cd "$(git rev-parse --show-toplevel)"'
if ! _command_exists gh; then
alias gh='ghm'
fi
# Show untracked files # Show untracked files
alias gu='git ls-files . --exclude-standard --others' alias gu='git ls-files . --exclude-standard --others'

View File

@ -5,12 +5,11 @@
cite 'about-alias' cite 'about-alias'
about-alias 'kubectl aliases' about-alias 'kubectl aliases'
# set apt aliases
function _set_pkg_aliases() function _set_pkg_aliases()
{ {
if [ -x $(which kubectl) ]; then if _command_exists kubectl; then
alias kc='kubectl' alias kc='kubectl'
alias kcgp='kubectl get pods' alias kcgp='kubectl get pods'
alias kcgd='kubectl get deployments' alias kcgd='kubectl get deployments'
alias kcgn='kubectl get nodes' alias kcgn='kubectl get nodes'
alias kcdp='kubectl describe pod' alias kcdp='kubectl describe pod'
@ -18,7 +17,9 @@ function _set_pkg_aliases()
alias kcdn='kubectl describe node' alias kcdn='kubectl describe node'
alias kcgpan='kubectl get pods --all-namespaces' alias kcgpan='kubectl get pods --all-namespaces'
alias kcgdan='kubectl get deployments --all-namespaces' alias kcgdan='kubectl get deployments --all-namespaces'
fi # launches a disposable netshoot pod in the k8s cluster
alias kcnetshoot='kubectl run --generator=run-pod/v1 netshoot-$(date +%s) --rm -i --tty --image nicolaka/netshoot -- /bin/bash'
fi
} }
_set_pkg_aliases _set_pkg_aliases

View File

@ -2,6 +2,8 @@ cite 'about-alias'
about-alias 'common npm abbreviations' about-alias 'common npm abbreviations'
# Aliases # Aliases
# npm
alias ni='npm install' alias ni='npm install'
alias nis='npm install --save' alias nis='npm install --save'
alias nid='npm install --save-dev' alias nid='npm install --save-dev'
@ -20,3 +22,21 @@ alias nud='npm update'
alias nr='npm run' alias nr='npm run'
alias nls='npm list --depth=0 2>/dev/null' alias nls='npm list --depth=0 2>/dev/null'
alias nlsg='npm list -g --depth=0 2>/dev/null' alias nlsg='npm list -g --depth=0 2>/dev/null'
# npx
alias nx='npx'
alias nxplease='npx $(fc -ln -1)'
alias nxn='npx --no-install '
alias nxp='npx -p '
alias nxnp='npx --no-install -p '
alias nxq='npx -q '
alias nxnq='npx --no-install -q '
alias nxqp='npx -q -p '
alias nxnqp='npx --no-install -q -p '
alias nxni='npx --no-install --ignore-existing '
alias nxip='npx --ignore-existing -p '
alias nxnip='npx --no-install --ignore-existing -p '
alias nxqi='npx -q --ignore-existing '
alias nxniq='npx --no-install --ignore-existing -q '
alias nxiqp='npx --ignore-existing -q -p '
alias nxniqp='npx --no-install --ignore-existing -q -p '

View File

@ -0,0 +1,11 @@
# Aliases for Terraform and Terragrunt
cite 'about-alias'
about-alias 'Terraform abbreviations'
alias tf='terraform'
alias tfv='terraform validate'
alias tfp='terraform plan'
alias tfa='terraform apply'
alias tfd='terraform destory'

View File

@ -0,0 +1,16 @@
# Aliases for Terraform and Terragrunt
cite 'about-alias'
about-alias 'Terragrunt abbreviations'
alias tg='terragrunt'
alias tgv='terragrunt validate'
alias tgp='terragrunt plan'
alias tga='terragrunt apply'
alias tgd='terragrunt destroy'
alias tgva='terragrunt validate-all'
alias tgpa='terragrunt plan-all'
alias tgaa='terragrunt apply-all'
alias tgda='terragrunt destroy-all'

View File

@ -0,0 +1,11 @@
cite 'uuid-alias'
about-alias 'uuidgen aliases'
if _command_exists uuid; then # Linux
alias uuidu="uuid | tr '[:lower:]' '[:upper:]'"
alias uuidl=uuid
elif _command_exists uuidgen; then # macOS/BSD
alias uuidu="uuidgen"
alias uuid="uuidgen | tr '[:upper:]' '[:lower:]'" # because upper case is like YELLING
alias uuidl=uuid
fi

View File

@ -1,37 +1,49 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# Initialize Bash It # Initialize Bash It
BASH_IT_LOG_PREFIX="core: main: "
# Only set $BASH_IT if it's not already set # Only set $BASH_IT if it's not already set
if [ -z "$BASH_IT" ]; if [ -z "$BASH_IT" ];
then then
# Setting $BASH to maintain backwards compatibility # Setting $BASH to maintain backwards compatibility
# TODO: warn users that they should upgrade their .bash_profile
export BASH_IT=$BASH export BASH_IT=$BASH
BASH="$(bash -c 'echo $BASH')" BASH="$(bash -c 'echo $BASH')"
export BASH export BASH
fi BASH_IT_OLD_BASH_SETUP=true
# For backwards compatibility, look in old BASH_THEME location
if [ -z "$BASH_IT_THEME" ];
then
# TODO: warn users that they should upgrade their .bash_profile
export BASH_IT_THEME="$BASH_THEME";
unset BASH_THEME;
fi fi
# Load composure first, so we support function metadata # Load composure first, so we support function metadata
# shellcheck source=./lib/composure.bash # shellcheck source=./lib/composure.bash
source "${BASH_IT}/lib/composure.bash" source "${BASH_IT}/lib/composure.bash"
# We need to load logging module first as well in order to be able to log
# shellcheck source=./lib/log.bash
source "${BASH_IT}/lib/log.bash"
# We can only log it now
[ -z "$BASH_IT_OLD_BASH_SETUP" ] || _log_warning "BASH_IT variable not initialized, please upgrade your bash-it version and reinstall it!"
# For backwards compatibility, look in old BASH_THEME location
if [ -z "$BASH_IT_THEME" ];
then
_log_warning "BASH_IT_THEME variable not initialized, please upgrade your bash-it version and reinstall it!"
export BASH_IT_THEME="$BASH_THEME";
unset BASH_THEME;
fi
# support 'plumbing' metadata # support 'plumbing' metadata
cite _about _param _example _group _author _version cite _about _param _example _group _author _version
# libraries, but skip appearance (themes) for now # libraries, but skip appearance (themes) for now
_log_debug "Loading libraries(except appearance)..."
LIB="${BASH_IT}/lib/*.bash" LIB="${BASH_IT}/lib/*.bash"
APPEARANCE_LIB="${BASH_IT}/lib/appearance.bash" APPEARANCE_LIB="${BASH_IT}/lib/appearance.bash"
for _bash_it_config_file in $LIB for _bash_it_config_file in $LIB
do do
if [ "$_bash_it_config_file" != "$APPEARANCE_LIB" ]; then if [ "$_bash_it_config_file" != "$APPEARANCE_LIB" ]; then
filename=${_bash_it_config_file##*/}
filename=${filename%.bash}
BASH_IT_LOG_PREFIX="lib: ${filename}: "
_log_debug "Loading library file..."
# shellcheck disable=SC1090 # shellcheck disable=SC1090
source "$_bash_it_config_file" source "$_bash_it_config_file"
fi fi
@ -51,36 +63,51 @@ done
# Load theme, if a theme was set # Load theme, if a theme was set
if [[ ! -z "${BASH_IT_THEME}" ]]; then if [[ ! -z "${BASH_IT_THEME}" ]]; then
_log_debug "Loading \"${BASH_IT_THEME}\" theme..."
# Load colors and helpers first so they can be used in base theme # Load colors and helpers first so they can be used in base theme
BASH_IT_LOG_PREFIX="themes: colors: "
# shellcheck source=./themes/colors.theme.bash # shellcheck source=./themes/colors.theme.bash
source "${BASH_IT}/themes/colors.theme.bash" source "${BASH_IT}/themes/colors.theme.bash"
BASH_IT_LOG_PREFIX="themes: githelpers: "
# shellcheck source=./themes/githelpers.theme.bash # shellcheck source=./themes/githelpers.theme.bash
source "${BASH_IT}/themes/githelpers.theme.bash" source "${BASH_IT}/themes/githelpers.theme.bash"
BASH_IT_LOG_PREFIX="themes: p4helpers: "
# shellcheck source=./themes/p4helpers.theme.bash # shellcheck source=./themes/p4helpers.theme.bash
source "${BASH_IT}/themes/p4helpers.theme.bash" source "${BASH_IT}/themes/p4helpers.theme.bash"
BASH_IT_LOG_PREFIX="themes: base: "
# shellcheck source=./themes/base.theme.bash # shellcheck source=./themes/base.theme.bash
source "${BASH_IT}/themes/base.theme.bash" source "${BASH_IT}/themes/base.theme.bash"
BASH_IT_LOG_PREFIX="lib: appearance: "
# appearance (themes) now, after all dependencies # appearance (themes) now, after all dependencies
# shellcheck source=./lib/appearance.bash # shellcheck source=./lib/appearance.bash
source "$APPEARANCE_LIB" source "$APPEARANCE_LIB"
fi fi
# Load custom aliases, completion, plugins BASH_IT_LOG_PREFIX="core: main: "
_log_debug "Loading custom aliases, completion, plugins..."
for file_type in "aliases" "completion" "plugins" for file_type in "aliases" "completion" "plugins"
do do
if [ -e "${BASH_IT}/${file_type}/custom.${file_type}.bash" ] if [ -e "${BASH_IT}/${file_type}/custom.${file_type}.bash" ]
then then
BASH_IT_LOG_PREFIX="${file_type}: custom: "
_log_debug "Loading component..."
# shellcheck disable=SC1090 # shellcheck disable=SC1090
source "${BASH_IT}/${file_type}/custom.${file_type}.bash" source "${BASH_IT}/${file_type}/custom.${file_type}.bash"
fi fi
done done
# Custom # Custom
BASH_IT_LOG_PREFIX="core: main: "
_log_debug "Loading general custom files..."
CUSTOM="${BASH_IT_CUSTOM:=${BASH_IT}/custom}/*.bash ${BASH_IT_CUSTOM:=${BASH_IT}/custom}/**/*.bash" CUSTOM="${BASH_IT_CUSTOM:=${BASH_IT}/custom}/*.bash ${BASH_IT_CUSTOM:=${BASH_IT}/custom}/**/*.bash"
for _bash_it_config_file in $CUSTOM for _bash_it_config_file in $CUSTOM
do do
if [ -e "${_bash_it_config_file}" ]; then if [ -e "${_bash_it_config_file}" ]; then
filename=$(basename "${_bash_it_config_file}")
filename=${filename%*.bash}
BASH_IT_LOG_PREFIX="custom: $filename: "
_log_debug "Loading custom file..."
# shellcheck disable=SC1090 # shellcheck disable=SC1090
source "$_bash_it_config_file" source "$_bash_it_config_file"
fi fi

View File

@ -65,7 +65,7 @@ _bash-it-comp()
prev="${COMP_WORDS[COMP_CWORD-1]}" prev="${COMP_WORDS[COMP_CWORD-1]}"
chose_opt="${COMP_WORDS[1]}" chose_opt="${COMP_WORDS[1]}"
file_type="${COMP_WORDS[2]}" file_type="${COMP_WORDS[2]}"
opts="disable enable help migrate reload search show update version" opts="disable enable help migrate reload restart doctor search show update version"
case "${chose_opt}" in case "${chose_opt}" in
show) show)
local show_args="aliases completions plugins" local show_args="aliases completions plugins"
@ -82,7 +82,21 @@ _bash-it-comp()
return 0 return 0
fi fi
;; ;;
migrate | reload | search | update | version) doctor)
local doctor_args="errors warnings all"
COMPREPLY=( $(compgen -W "${doctor_args}" -- ${cur}) )
return 0
;;
update)
if [[ ${cur} == -* ]];then
local update_args="-s --silent"
else
local update_args="stable dev"
fi
COMPREPLY=( $(compgen -W "${update_args}" -- ${cur}) )
return 0
;;
migrate | reload | search | version)
return 0 return 0
;; ;;
enable | disable) enable | disable)

View File

@ -1,11 +1,27 @@
if which brew >/dev/null 2>&1; then #!/usr/bin/env bash
BREW_PREFIX=$(brew --prefix)
if [ -f "$BREW_PREFIX"/etc/bash_completion.d/brew ]; then # Load late to make sure `system` completion loads first
. "$BREW_PREFIX"/etc/bash_completion.d/brew # BASH_IT_LOAD_PRIORITY: 375
fi
if [ -f "$BREW_PREFIX"/Library/Contributions/brew_bash_completion.sh ]; then if [[ "$(uname -s)" != 'Darwin' ]] ; then
. "$BREW_PREFIX"/Library/Contributions/brew_bash_completion.sh _log_warning "unsupported operating system - only 'Darwin' is supported"
fi return 0
fi
# Make sure brew is installed
_command_exists brew || return 0
BREW_PREFIX=${BREW_PREFIX:-$(brew --prefix)}
if [[ -r "$BREW_PREFIX"/etc/bash_completion.d/brew ]] ; then
source "$BREW_PREFIX"/etc/bash_completion.d/brew
elif [[ -r "$BREW_PREFIX"/Library/Contributions/brew_bash_completion.sh ]] ; then
source "$BREW_PREFIX"/Library/Contributions/brew_bash_completion.sh
elif [[ -f "$BREW_PREFIX"/completions/bash/brew ]] ; then
# For the git-clone based installation, see here for more info:
# https://github.com/Bash-it/bash-it/issues/1458
# https://docs.brew.sh/Shell-Completion
source "$BREW_PREFIX"/completions/bash/brew
fi fi

View File

@ -1,7 +1,7 @@
#! bash #! bash
# bash completion for the `bundle` command. # bash completion for the `bundle` command.
# #
# Copyright (c) 2011-2013 Daniel Luz <dev at mernen dot com>. # Copyright (c) 2011-2017 Daniel Luz <dev at mernen dot com>.
# Distributed under the MIT license. # Distributed under the MIT license.
# http://mernen.com/projects/completion-ruby # http://mernen.com/projects/completion-ruby
# #
@ -9,28 +9,166 @@
# . completion-bundle # . completion-bundle
__bundle() { __bundle() {
local cur=$2 local bundle_bin=("${_RUBY_COMMAND_PREFIX[@]}" "$1")
local prev=$3 local cur prev
local bundle_command _get_comp_words_by_ref -n : cur prev
__bundle_get_command local bundle_command
COMPREPLY=() local bundle_command_index
__bundle_get_command
COMPREPLY=()
local options local options
if [[ $cur = -* ]]; then if [[ $cur = -* && $bundle_command != exec ]]; then
options="--no-color --verbose" options="-V --help --no-color --no-no-color --verbose --no-verbose"
if [[ -z $bundle_command ]]; then case $bundle_command in
options="$options --version --help" "")
fi options="$options --version";;
elif [[ $bundle_command = "exec" ]]; then check)
_bundle_exec_completions options="$options --dry-run --gemfile --path -r --retry";;
return clean)
else options="$options --dry-run --force";;
if [[ -z $bundle_command || $bundle_command = help ]]; then config)
options="help install update package exec config check list show options="$options --local --global --delete";;
console open viz init gem" doctor)
fi options="$options --gemfile --quiet --no-quiet";;
fi gem)
COMPREPLY=($(compgen -W "$options" -- "$cur")) options="$options -b -e -t --bin --coc --no-coc --edit --exe
--no-exe --ext --no-ext --mit --no-mit --test";;
init)
options="$options --gemspec";;
install)
options="$options --binstubs --clean --deployment --force --frozen
--full-index --gemfile --jobs --local --no-cache
--no-prune --path --quiet --retry --shebang --standalone
--system --trust-policy --with --without";;
lock)
options="$options --add-platform --conservative --full-index
--local --lockfile --major --minor --patch --print
--remove-platform --strict --update";;
package)
options="$options --all --all-platforms";;
platform)
options="$options --ruby";;
show)
options="$options --outdated --paths --no-paths";;
update)
options="$options --bundler --conservative --force --full-index
--group --jobs --local --major --minor --patch --quiet
--ruby --source --strict";;
viz)
options="$options -f -F -R -v -W --file --format --requirements
--no-requirements --version --no-version --without";;
esac
else
case $bundle_command in
"" | help)
options="help install update package exec config
check show outdated console open lock viz init gem
platform clean doctor"
;;
check | install)
case $prev in
--binstubs | --path)
_filedir -d
return;;
--standalone | --with | --without)
__bundle_complete_groups
return;;
--trust-policy)
options="HighSecurity MediumSecurity LowSecurity
AlmostNoSecurity NoSecurity";;
esac
;;
config)
case $prev in
config | --*)
case $cur in
local.*)
options=($(__bundle_exec_ruby 'puts Bundler.definition.specs.to_hash.keys'))
options=("${options[*]/#/local.}")
;;
*)
options=(path frozen without bin gemfile ssl_ca_cert
ssl_client_cert cache_path disable_multisource
ignore_messages retry redirect timeout
force_ruby_platform specific_platform
disable_checksum_validation disable_version_check
allow_offline_install auto_install
cache_all_platforms cache_all clean console
disable_exec_load disable_local_branch_check
disable_shared_gems jobs major_deprecations
no_install no_prune only_update_to_newer_versions
plugins shebang silence_root_warning
ssl_verify_mode system_bindir user_agent)
# We want to suggest the options above as complete words,
# and also "local." and "mirror." as prefixes
# To achieve that, disable automatic space insertion,
# insert it manually, then add the non-spaced prefixes
compopt -o nospace
options=("${options[@]/%/ }")
# And add prefix suggestions
options+=(local. mirror.)
# Override $IFS for completion to work
local IFS=$'\n'
COMPREPLY=($(compgen -W '${options[@]}' -- "$cur"))
return
;;
esac
;;
path | local.*)
_filedir -d
return;;
esac
;;
exec)
if [[ $COMP_CWORD -eq $bundle_command_index ]]; then
# Figure out Bundler's binaries dir
local bundler_bin=$(__bundle_exec_ruby 'puts Bundler.bundle_path + "bin"')
if [[ -d $bundler_bin ]]; then
local binaries=("$bundler_bin"/*)
# If there are binaries, strip directory name and use them
[[ -f "$binaries" ]] && options="${binaries[@]##*/}"
else
# No binaries found; use full command completion
COMPREPLY=($(compgen -c -- "$cur"))
return
fi
else
local _RUBY_COMMAND_PREFIX=("${bundle_bin[@]}" exec)
_command_offset $bundle_command_index
return
fi
;;
gem)
case $prev in
-e | --edit)
COMPREPLY=($(compgen -c -- "$cur"))
return;;
-t | --test)
options="minitest rspec";;
esac
;;
update)
case $prev in
--group)
__bundle_complete_groups
return;;
*)
options=($(__bundle_exec_ruby 'puts Bundler.definition.specs.to_hash.keys'))
esac
;;
viz)
case $prev in
-F | --format)
options="dot jpg png svg";;
-W | --without)
__bundle_complete_groups
return;;
esac
;;
esac
fi
COMPREPLY=($(compgen -W "${options[*]}" -- "$cur"))
} }
__bundle_get_command() { __bundle_get_command() {
@ -41,25 +179,76 @@ __bundle_get_command() {
case $arg in case $arg in
[^-]*) [^-]*)
bundle_command=$arg bundle_command=$arg
bundle_command_index=$((i + 1))
return;; return;;
--version) --version)
# command-killer # Command-killer
bundle_command=- bundle_command=-
return;; return;;
--help) --help)
bundle_command=help bundle_command=help
bundle_command_index=$((i + 1))
return;; return;;
esac esac
done done
} }
# Provides completion for Bundler group names.
#
# Multiple groups can be entered, separated either by spaces or by colons.
# Input is read from $cur, and the result is directly written to $COMPREPLY.
__bundle_complete_groups() {
# Group being currently written
local cur_group=${cur##*[ :]}
# All groups written before
local prefix=${cur%"$cur_group"}
local groups=$(__bundle_exec_ruby 'puts Bundler.definition.dependencies.map(&:groups).reduce(:|).map(&:to_s)')
if [[ ! $groups ]]; then
COMPREPLY=()
return
fi
# Duplicate "default" and anything already in $prefix, so that `uniq`
# strips it; groups may be separated by ':', ' ', or '\ '
local excluded=$'\ndefault\n'${prefix//[: \'\"\\]/$'\n'}
# Include them twice to ensure they are duplicates
groups=$groups$excluded$excluded
COMPREPLY=($(compgen -W "$(sort <<<"$groups" | uniq -u)" -- "$cur_group"))
# Prepend prefix to all entries
COMPREPLY=("${COMPREPLY[@]/#/$prefix}")
__ltrim_colon_completions "$cur"
}
complete -F __bundle -o bashdefault -o default bundle # __bundle_exec_ruby <script> [args...]
# vim: ai ft=sh sw=4 sts=2 et #
# Runs a Ruby script with Bundler loaded.
# Results may be cached.
__bundle_exec_ruby() {
local bundle_bin=(${bundle_bin[@]:-bundle})
# Lockfile is inferred here, and might not be correct (for example, when
# running on a subdirectory). However, a wrong file path won't be a
# cadastrophic mistake; it just means the cache won't be invalidated when
# the local gem list changes (but will still invalidate if the command is
# run on another directory)
local lockfile=$PWD/Gemfile.lock
local cachedir=${XDG_CACHE_HOME:-~/.cache}/completion-ruby
local cachefile=$cachedir/bundle--exec-ruby
# A representation of all arguments with newlines replaced by spaces,
# to fit in a single line as a cache identifier
local cache_id_line="${bundle_bin[*]} @ $lockfile: ${*//$'\n'/ }"
_bundle_exec_completions() if [[ (! -f $lockfile || $cachefile -nt $lockfile) &&
{ $(head -n 1 -- "$cachefile" 2>/dev/null) = "$cache_id_line" ]]; then
if [[ $COMP_CWORD = 2 ]]; then tail -n +2 -- "$cachefile"
COMPREPLY=($(compgen -c -- "$2")) else
local output=$("${bundle_bin[@]}" exec ruby -e "$@" 2>/dev/null)
if [[ $? -eq 0 ]]; then
(mkdir -p -- "$cachedir" &&
echo "$cache_id_line"$'\n'"$output" >$cachefile) 2>/dev/null
echo "$output"
fi
fi fi
} }
complete -F __bundle -o bashdefault -o default bundle
# vim: ai ft=sh sw=4 sts=4 et

View File

@ -1,11 +1 @@
if which crystal >/dev/null 2>&1; then _log_warning 'Bash completion for "crystal" is now covered by "system". This completion can be disabled.'
if which brew >/dev/null 2>&1; then
BREW_PREFIX=$(brew --prefix)
if [ -f "$BREW_PREFIX"/etc/bash_completion.d/crystal ]; then
. "$BREW_PREFIX"/etc/bash_completion.d/crystal
fi
fi
fi

File diff suppressed because it is too large Load Diff

View File

@ -1,366 +0,0 @@
# hub tab-completion script for bash.
# This script complements the completion script that ships with git.
# Check that git tab completion is available
if declare -F _git > /dev/null; then
# Duplicate and rename the 'list_all_commands' function
eval "$(declare -f __git_list_all_commands | \
sed 's/__git_list_all_commands/__git_list_all_commands_without_hub/')"
# Wrap the 'list_all_commands' function with extra hub commands
__git_list_all_commands() {
cat <<-EOF
alias
pull-request
fork
create
browse
compare
ci-status
release
issue
update
EOF
__git_list_all_commands_without_hub
}
# Ensure cached commands are cleared
__git_all_commands=""
##########################
# hub command completions
##########################
# hub alias [-s] [SHELL]
_git_alias() {
local i c=2 s=-s sh shells="bash zsh sh ksh csh fish"
while [ $c -lt $cword ]; do
i="${words[c]}"
case "$i" in
-s)
unset s
;;
*)
for sh in $shells; do
if [ "$sh" = "$i" ]; then
unset shells
break
fi
done
;;
esac
((c++))
done
__gitcomp "$s $shells"
}
# hub browse [-u] [--|[USER/]REPOSITORY] [SUBPAGE]
_git_browse() {
local i c=2 u=-u repo subpage
local subpages_="commits issues tree wiki pulls branches stargazers
contributors network network/ graphs graphs/"
local subpages_network="members"
local subpages_graphs="commit-activity code-frequency punch-card"
while [ $c -lt $cword ]; do
i="${words[c]}"
case "$i" in
-u)
unset u
;;
*)
if [ -z "$repo" ]; then
repo=$i
else
subpage=$i
fi
;;
esac
((c++))
done
if [ -z "$repo" ]; then
__gitcomp "$u -- $(__hub_github_repos '\p')"
elif [ -z "$subpage" ]; then
case "$cur" in
*/*)
local pfx="${cur%/*}" cur_="${cur#*/}"
local subpages_var="subpages_$pfx"
__gitcomp "${!subpages_var}" "$pfx/" "$cur_"
;;
*)
__gitcomp "$u ${subpages_}"
;;
esac
else
__gitcomp "$u"
fi
}
# hub compare [-u] [USER[/REPOSITORY]] [[START...]END]
_git_compare() {
local i c=$((cword - 1)) u=-u user remote owner repo arg_repo rev
while [ $c -gt 1 ]; do
i="${words[c]}"
case "$i" in
-u)
unset u
;;
*)
if [ -z "$rev" ]; then
# Even though the logic below is able to complete both user/repo
# and revision in the right place, when there is only one argument
# (other than -u) in the command, that argument will be taken as
# revision. For example:
# $ hub compare -u upstream
# > https://github.com/USER/REPO/compare/upstream
if __hub_github_repos '\p' | grep -Eqx "^$i(/[^/]+)?"; then
arg_repo=$i
else
rev=$i
fi
elif [ -z "$arg_repo" ]; then
arg_repo=$i
fi
;;
esac
((c--))
done
# Here we want to find out the git remote name of user/repo, in order to
# generate an appropriate revision list
if [ -z "$arg_repo" ]; then
user=$(__hub_github_user)
if [ -z "$user" ]; then
for i in $(__hub_github_repos); do
remote=${i%%:*}
repo=${i#*:}
if [ "$remote" = origin ]; then
break
fi
done
else
for i in $(__hub_github_repos); do
remote=${i%%:*}
repo=${i#*:}
owner=${repo%%/*}
if [ "$user" = "$owner" ]; then
break
fi
done
fi
else
for i in $(__hub_github_repos); do
remote=${i%%:*}
repo=${i#*:}
owner=${repo%%/*}
case "$arg_repo" in
"$repo"|"$owner")
break
;;
esac
done
fi
local pfx cur_="$cur"
case "$cur_" in
*..*)
pfx="${cur_%%..*}..."
cur_="${cur_##*..}"
__gitcomp_nl "$(__hub_revlist $remote)" "$pfx" "$cur_"
;;
*)
if [ -z "${arg_repo}${rev}" ]; then
__gitcomp "$u $(__hub_github_repos '\o\n\p') $(__hub_revlist $remote)"
elif [ -z "$rev" ]; then
__gitcomp "$u $(__hub_revlist $remote)"
else
__gitcomp "$u"
fi
;;
esac
}
# hub create [NAME] [-p] [-d DESCRIPTION] [-h HOMEPAGE]
_git_create() {
local i c=2 name repo flags="-p -d -h"
while [ $c -lt $cword ]; do
i="${words[c]}"
case "$i" in
-d|-h)
((c++))
flags=${flags/$i/}
;;
-p)
flags=${flags/$i/}
;;
*)
name=$i
;;
esac
((c++))
done
if [ -z "$name" ]; then
repo=$(basename "$(pwd)")
fi
case "$prev" in
-d|-h)
COMPREPLY=()
;;
-p|*)
__gitcomp "$repo $flags"
;;
esac
}
# hub fork [--no-remote]
_git_fork() {
local i c=2 remote=yes
while [ $c -lt $cword ]; do
i="${words[c]}"
case "$i" in
--no-remote)
unset remote
;;
esac
((c++))
done
if [ -n "$remote" ]; then
__gitcomp "--no-remote"
fi
}
# hub pull-request [-f] [-m <MESSAGE>|-F <FILE>|-i <ISSUE>|<ISSUE-URL>] [-b <BASE>] [-h <HEAD>]
_git_pull_request() {
local i c=2 flags="-f -m -F -i -b -h"
while [ $c -lt $cword ]; do
i="${words[c]}"
case "$i" in
-m|-F|-i|-b|-h)
((c++))
flags=${flags/$i/}
;;
-f)
flags=${flags/$i/}
;;
esac
((c++))
done
case "$prev" in
-i)
COMPREPLY=()
;;
-b|-h)
# (Doesn't seem to need this...)
# Uncomment the following line when 'owner/repo:[TAB]' misbehaved
#_get_comp_words_by_ref -n : cur
__gitcomp_nl "$(__hub_heads)"
# __ltrim_colon_completions "$cur"
;;
-F)
COMPREPLY=( "$cur"* )
;;
-f|*)
__gitcomp "$flags"
;;
esac
}
###################
# Helper functions
###################
# __hub_github_user [HOST]
# Return $GITHUB_USER or the default github user defined in hub config
# HOST - Host to be looked-up in hub config. Default is "github.com"
__hub_github_user() {
if [ -n "$GITHUB_USER" ]; then
echo $GITHUB_USER
return
fi
local line h k v host=${1:-github.com} config=${HUB_CONFIG:-~/.config/gh}
if [ -f "$config" ]; then
while read line; do
if [ "$line" = "---" ]; then
continue
fi
k=${line%%:*}
v=${line#*:}
if [ -z "$v" ]; then
if [ "$h" = "$host" ]; then
break
fi
h=$k
continue
fi
k=${k#* }
v=${v#* }
if [ "$h" = "$host" ] && [ "$k" = "user" ]; then
echo "$v"
break
fi
done < "$config"
fi
}
# __hub_github_repos [FORMAT]
# List all github hosted repository
# FORMAT - Format string contains multiple of these:
# \m remote
# \p owner/repo
# \o owner
# escaped characters (\n, \t ...etc) work
# If omitted, prints all github repos in the format of "remote:owner/repo"
__hub_github_repos() {
local f format=$1
if [ -z "$(__gitdir)" ]; then
return
fi
if [ -z "$format" ]; then
format='\1:\2'
else
format=${format//\m/\1}
format=${format//\p/\2}
format=${format//\o/\3}
fi
command git config --get-regexp 'remote\.[^.]*\.url' |
grep -E ' ((https?|git)://|git@)github\.com[:/][^:/]+/[^/]+$' |
sed -E 's#^remote\.([^.]+)\.url +.+[:/](([^/]+)/[^.]+)(\.git)?$#'"$format"'#'
}
# __hub_heads
# List all local "branch", and remote "owner/repo:branch"
__hub_heads() {
local i remote repo branch dir=$(__gitdir)
if [ -d "$dir" ]; then
command git --git-dir="$dir" for-each-ref --format='%(refname:short)' \
"refs/heads/"
for i in $(__hub_github_repos); do
remote=${i%%:*}
repo=${i#*:}
command git --git-dir="$dir" for-each-ref --format='%(refname:short)' \
"refs/remotes/${remote}/" | while read branch; do
echo "${repo}:${branch#${remote}/}"
done
done
fi
}
# __hub_revlist [REMOTE]
# List all tags, and branches under REMOTE, without the "remote/" prefix
# REMOTE - Remote name to search branches from. Default is "origin"
__hub_revlist() {
local i remote=${1:-origin} dir=$(__gitdir)
if [ -d "$dir" ]; then
command git --git-dir="$dir" for-each-ref --format='%(refname:short)' \
"refs/remotes/${remote}/" | while read i; do
echo "${i#${remote}/}"
done
command git --git-dir="$dir" for-each-ref --format='%(refname:short)' \
"refs/tags/"
fi
}
# Enable completion for hub even when not using the alias
complete -o bashdefault -o default -o nospace -F _git gh 2>/dev/null \
|| complete -o default -o nospace -F _git gh
fi

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,10 @@
#!/usr/bin/env bash
cite "about-completion"
about-completion "GitHub CLI completion"
if _command_exists gh; then
if _command_exists brew; then
_log_warning "You don't need github-cli completion enabled if you have system completion enabled"
fi
eval "$(gh completion --shell=bash)"
fi

View File

@ -1,281 +1,13 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# bash completion for go tool # bash completion for go tool
# https://github.com/thomasf/go-bash-completion # https://github.com/posener/complete
# https://pkg.go.dev/github.com/posener/complete?tab=doc
# install in /etc/bash_completion.d/ or your personal directory # Install gocomplete:
# go get -u github.com/posener/complete/gocomplete
# gocomplete -install
complete -f -X '!*.8' 8l if _command_exists gocomplete && _command_exists go ; then
complete -f -X '!*.6' 6l complete -C "${GOBIN}"/gocomplete go
complete -f -X '!*.5' 5l fi
complete -f -X '!*.go' 8g 6g 5g gofmt gccgo
_go_clear_cache() {
unset _go_imports
}
_go_importpath_cache() {
if [ -z "$_go_imports" ]; then
_go_imports=$(go list all 2>/dev/null)
export _go_imports
fi
}
_go_importpath()
{
echo "$(compgen -W "$_go_imports" -- "$1")"
}
_go()
{
# TODO: Only allow flags before other arguments. run already does
# this.
local cur=`_get_cword`
local prev="${COMP_WORDS[COMP_CWORD-1]}"
local cmd="${COMP_WORDS[1]}"
local cmds="build clean doc env fix fmt get
install list run test tool version vet"
local addhelp="gopath importpath remote
testflag testfunc"
local other="help"
local env_vars="GOARCH GOBIN GOEXE GOHOSTARCH GOHOSTOS GOOS GOPATH GORACE
GOROOT GOTOOLDIR GO15VENDOREXPERIMENT CC GOGCCFLAGS CXX CGO_ENABLED"
if [ "$COMP_CWORD" == 1 ]; then
for opt in $cmds; do
if [[ "$opt" == "$cmd" ]]; then
COMPREPLY=("$opt")
return
fi
done
fi
case "$cmd" in
'build')
case "$prev" in
'-o')
_filedir
;;
'-p')
;;
*)
if [[ "$cur" == -* ]]; then
COMPREPLY=($(compgen -W "-a -n -o -p -v -x" -- "$cur"))
else
local found=0
for ((i=0; i < ${#COMP_WORDS[@]}; i++)); do
case "$i" in
0|1|"$COMP_CWORD")
continue
;;
esac
local opt="${COMP_WORDS[i]}"
if [[ "$opt" != -* ]]; then
if [[ "$opt" == *.go && -f "$opt" ]]; then
found=1
break
else
found=2
break
fi
fi
done
case "$found" in
0)
_filedir go
_go_importpath_cache
COMPREPLY+=(`_go_importpath "$cur"`)
;;
1)
_filedir go
;;
2)
_go_importpath_cache
COMPREPLY=(`_go_importpath "$cur"`)
;;
esac
fi
;;
esac
;;
'clean')
if [[ "$cur" == -* ]]; then
COMPREPLY=($(compgen -W "-i -r -n -x" -- "$cur"))
else
_go_importpath_cache
COMPREPLY=(`_go_importpath "$cur"`)
fi
;;
'doc')
_go_importpath_cache
COMPREPLY=(`_go_importpath "$cur"`)
;;
'env')
COMPREPLY=($(compgen -W "$env_vars" -- "$cur"))
;;
'fix')
_go_importpath_cache
COMPREPLY=(`_go_importpath "$cur"`)
;;
'fmt')
_go_importpath_cache
COMPREPLY=(`_go_importpath "$cur"`)
;;
'get')
case "$prev" in
'-p')
;;
*)
if [[ "$cur" == -* ]]; then
COMPREPLY=($(compgen -W "-a -d -fix -n -p -u -v -x" -- "$cur"))
else
_go_importpath_cache
COMPREPLY=(`_go_importpath "$cur"`)
fi
;;
esac
;;
'install')
case "$prev" in
'-p')
;;
*)
if [[ "$cur" == -* ]]; then
COMPREPLY=($(compgen -W "-a -n -p -v -x" -- "$cur"))
else
_go_importpath_cache
COMPREPLY=(`_go_importpath "$cur"`)
fi
;;
esac
;;
'list')
case "$prev" in
'-f')
;;
*)
if [[ "$cur" == -* ]]; then
COMPREPLY=($(compgen -W "-e -f -json" -- "$cur"))
else
_go_importpath_cache
COMPREPLY=(`_go_importpath "$cur"`)
fi
;;
esac
;;
'run')
if [[ "$cur" == -* && "$prev" != *.go ]]; then
COMPREPLY=($(compgen -W "-a -n -x" -- "$cur"))
else
_filedir
fi
;;
'test') # TODO: Support for testflags.
case "$prev" in
'-file')
_filedir go
;;
'-p')
;;
*)
if [[ "$cur" == -* ]]; then
COMPREPLY=($(compgen -W "-c -file -i -p -x" -- "$cur"))
else
_go_importpath_cache
COMPREPLY=(`_go_importpath "$cur"`)
fi
;;
esac
;;
'tool')
if [ "$COMP_CWORD" == 2 ]; then
COMPREPLY=($(compgen -W "$(go tool)" -- "$cur"))
else
case "${COMP_WORDS[2]}" in
[568]a) # TODO: Implement something.
#_go_tool_568a
;;
[568]c) # TODO: Implement something.
#_go_tool_568c
;;
[568]g) # TODO: Implement something.
#_go_tool_568g
;;
[568]l) # TODO: Implement something.
#_go_tool_568l
;;
'api') # TODO: Implement something.
#_go_tool_api
;;
'cgo') # TODO: Implement something.
#_go_tool_cgo
;;
'cov') # TODO: Implement something.
#_go_tool_cov
;;
'dist') # TODO: Implement something.
#_go_tool_dist
;;
'ebnflint') # TODO: Implement something.
#_go_tool_ebnflint
;;
'fix') # TODO: Implement something.
#_go_tool_fix
;;
'gotype') # TODO: Implement something.
#_go_tool_gotype
;;
'nm') # TODO: Implement something.
#_go_tool_nm
;;
'pack') # TODO: Implement something.
#_go_tool_pack
;;
'pprof') # TODO: Implement something.
#_go_tool_pprof
;;
'prof') # TODO: Implement something.
#_go_tool_prof
;;
'vet') # TODO: Implement something.
#_go_tool_vet
;;
'yacc') # TODO: Implement something.
#_go_tool_yacc
;;
esac
if [[ "$cur" == -* ]]; then
COMPREPLY=($(compgen -W "${COMPREPLY[*]} -h" -- "$cur"))
fi
fi
;;
'version')
;;
'vet')
if [[ "$cur" == -* ]]; then
:
else
_go_importpath_cache
COMPREPLY=(`_go_importpath "$cur"`)
fi
;;
'help')
if [ "$COMP_CWORD" == 2 ]; then
COMPREPLY=($(compgen -W "$cmds $addhelp" -- "$cur"))
fi
;;
*)
if [ "$COMP_CWORD" == 1 ]; then
COMPREPLY=($(compgen -W "$cmds $other" -- "$cur"))
else
_filedir
fi
;;
esac
}
complete $filenames -F _go go
# vim:ts=2 sw=2 et syn=sh

View File

@ -6,8 +6,8 @@ if ! declare -F _git > /dev/null && declare -F _completion_loader > /dev/null; t
_completion_loader git _completion_loader git
fi fi
# Check that git tab completion is available # Check that git tab completion is available and we haven't already set up completion
if declare -F _git > /dev/null; then if declare -F _git > /dev/null && ! declare -F __git_list_all_commands_without_hub > /dev/null; then
# Duplicate and rename the 'list_all_commands' function # Duplicate and rename the 'list_all_commands' function
eval "$(declare -f __git_list_all_commands | \ eval "$(declare -f __git_list_all_commands | \
sed 's/__git_list_all_commands/__git_list_all_commands_without_hub/')" sed 's/__git_list_all_commands/__git_list_all_commands_without_hub/')"
@ -17,11 +17,16 @@ if declare -F _git > /dev/null; then
cat <<-EOF cat <<-EOF
alias alias
pull-request pull-request
pr
issue
release
fork fork
create create
delete
browse browse
compare compare
ci-status ci-status
sync
EOF EOF
__git_list_all_commands_without_hub __git_list_all_commands_without_hub
} }
@ -213,21 +218,36 @@ EOF
esac esac
} }
# hub fork [--no-remote] # hub fork [--no-remote] [--remote-name REMOTE] [--org ORGANIZATION]
_git_fork() { _git_fork() {
local i c=2 remote=yes local i c=2 flags="--no-remote --remote-name --org"
while [ $c -lt $cword ]; do while [ $c -lt $cword ]; do
i="${words[c]}" i="${words[c]}"
case "$i" in case "$i" in
--org)
((c++))
flags=${flags/$i/}
;;
--remote-name)
((c++))
flags=${flags/$i/}
flags=${flags/--no-remote/}
;;
--no-remote) --no-remote)
unset remote flags=${flags/$i/}
flags=${flags/--remote-name/}
;; ;;
esac esac
((c++)) ((c++))
done done
if [ -n "$remote" ]; then case "$prev" in
__gitcomp "--no-remote" --remote-name|--org)
fi COMPREPLY=()
;;
*)
__gitcomp "$flags"
;;
esac
} }
# hub pull-request [-f] [-m <MESSAGE>|-F <FILE>|-i <ISSUE>|<ISSUE-URL>] [-b <BASE>] [-h <HEAD>] [-a <USER>] [-M <MILESTONE>] [-l <LABELS>] # hub pull-request [-f] [-m <MESSAGE>|-F <FILE>|-i <ISSUE>|<ISSUE-URL>] [-b <BASE>] [-h <HEAD>] [-a <USER>] [-M <MILESTONE>] [-l <LABELS>]

View File

@ -0,0 +1,6 @@
#!/usr/bin/env bash
if _command_exists kind; then
eval "$(kind completion bash)"
fi

View File

@ -0,0 +1,16 @@
#!/usr/bin/bash
if command -v laravel > /dev/null; then
__laravel_completion() {
local OPTS=("-h --help -q --quiet --ansi --no-ansi -n --no-interaction -v -vv -vvv --verbose help list new")
COMPREPLY=()
for _opt_ in ${OPTS[@]}; do
if [[ "$_opt_" == "$2"* ]]; then
COMPREPLY+=("$_opt_")
fi
done
}
complete -F __laravel_completion laravel
fi

View File

@ -1,3 +1,34 @@
# Add completion for Makefile # Bash completion for Makefile
# see http://stackoverflow.com/a/38415982/1472048 # Loosely adapted from http://stackoverflow.com/a/38415982/1472048
complete -W "\`grep -oE '^[a-zA-Z0-9_-]+:([^=]|$)' Makefile | sed 's/[^a-zA-Z0-9_-]*$//'\`" make
_makecomplete() {
COMPREPLY=()
# https://www.gnu.org/software/make/manual/html_node/Makefile-Names.html
local files=()
for f in 'GNUmakefile' 'makefile' 'Makefile' ; do
[ -f "$f" ] && files+=("$f")
done
[ "${#files[@]}" -eq 0 ] && return 0
# collect all targets
local targets=()
for f in "${files[@]}" ; do
while IFS='' read -r line ; do
targets+=("$line")
done < <(grep -oE '^[a-zA-Z0-9_-]+:([^=]|$)' "$f" | cut -d':' -f1)
done
[ "${#targets[@]}" -eq 0 ] && return 0
# use the targets for completion
while IFS='' read -r line ; do
COMPREPLY+=("$line")
done < <(compgen -W "$(tr ' ' '\n' <<<"${targets[@]}" | sort -u)" -- "${COMP_WORDS[COMP_CWORD]}")
return 0
}
complete -o nospace -F _makecomplete make
complete -o nospace -F _makecomplete gnumake

View File

@ -0,0 +1 @@
_command_exists minishift && source <(minishift completion bash)

View File

@ -1,3 +1,9 @@
. <(ng completion --bash) if _command_exists ng; then
# No longer supported, please see https://github.com/angular/angular-cli/issues/11043
# Fix courtesy of https://stackoverflow.com/questions/50194674/ng-completion-no-longer-exists
# . <(ng completion --bash)
NG_COMMANDS="add build config doc e2e generate help lint new run serve test update version xi18n"
complete -W "$NG_COMMANDS" ng
fi

View File

@ -1,3 +1 @@
#!/usr/bin/env bash _command_exists oc && source <(oc completion bash)
[ -x "$(which oc)" ] && eval "$(oc completion bash)"

View File

@ -1,11 +1,10 @@
# https://pip.pypa.io/en/stable/user_guide/#command-completion
# pip bash completion start # Of course, you should first install the pip, say on Debian:
_pip_completion() # sudo apt-get install python-pip
{ # sudo apt-get install python3-pip
COMPREPLY=( $( COMP_WORDS="${COMP_WORDS[*]}" \ # If the pip package is installed within virtual environments, say, python managed by pyenv,
COMP_CWORD=$COMP_CWORD \ # you should first initilization the corresponding environment.
PIP_AUTO_COMPLETE=1 $1 ) ) # So that the pip/pip3 is in system's path.
} if command -v pip >/dev/null; then
complete -o default -F _pip_completion pip eval "$(pip completion --bash)"
# pip bash completion end fi

View File

@ -1,11 +1,11 @@
# https://pip.pypa.io/en/stable/user_guide/#command-completion
# pip bash completion start # Of course, you should first install the pip, say on Debian:
_pip_completion() # sudo apt-get install python-pip
{ # sudo apt-get install python3-pip
COMPREPLY=( $( COMP_WORDS="${COMP_WORDS[*]}" \ # If the pip package is installed within virtual environments, say, python managed by pyenv,
COMP_CWORD=$COMP_CWORD \ # you should first initilization the corresponding environment.
PIP_AUTO_COMPLETE=1 $1 ) ) # So that the pip/pip3 is in system's path.
} if command -v pip3 >/dev/null; then
complete -o default -F _pip_completion pip3 eval "$(pip3 completion --bash)"
# pip bash completion end fi

View File

@ -1,5 +1,13 @@
# Ensure that we log to doctor so the user can address these issues
_is_function _init_completion ||
_log_error '_init_completion not found. Ensure bash-completion 2.0 or newer is installed and configured properly.'
_is_function _rl_enabled ||
_log_error '_rl_enabled not found. Ensure bash-completion 2.0 or newer is installed and configured properly.'
_pj() { _pj() {
[ -z "$PROJECT_PATHS" ] && return _is_function _init_completion || return
_is_function _rl_enabled || return
[ -n "$PROJECT_PATHS" ] || return
shift shift
[ "$1" == "open" ] && shift [ "$1" == "open" ] && shift

View File

@ -15,7 +15,7 @@ _sshcomplete() {
for fl in "$HOME/.ssh/config" \ for fl in "$HOME/.ssh/config" \
$(grep "^\s*Include" "$HOME/.ssh/config" | $(grep "^\s*Include" "$HOME/.ssh/config" |
awk '{for (i=2; i<=NF; i++) print $i}' | awk '{for (i=2; i<=NF; i++) print $i}' |
sed "s|^~/|$HOME/|") sed -Ee "s|^([^/~])|$HOME/.ssh/\1|" -e "s|^~/|$HOME/|")
do do
if [ -r "$fl" ]; then if [ -r "$fl" ]; then
COMPREPLY=( ${COMPREPLY[@]} $(compgen -W "$(grep -i ^Host "$fl" |grep -v '[*!]' | awk '{for (i=2; i<=NF; i++) print $i}' )" ${OPTIONS}) ) COMPREPLY=( ${COMPREPLY[@]} $(compgen -W "$(grep -i ^Host "$fl" |grep -v '[*!]' | awk '{for (i=2; i<=NF; i++) print $i}' )" ${OPTIONS}) )
@ -37,4 +37,4 @@ _sshcomplete() {
return 0 return 0
} }
complete -o default -o nospace -F _sshcomplete ssh scp slogin complete -o default -o nospace -F _sshcomplete ssh scp slogin sftp

View File

@ -1,28 +1,25 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# Loads the system's Bash completion modules. # Loads the system's Bash completion modules.
# If Homebrew is installed (OS X), its Bash completion modules are loaded. # If Homebrew is installed (OS X), it's Bash completion modules are loaded.
if [ -f /etc/bash_completion ]; then if [[ -r /etc/bash_completion ]] ; then
. /etc/bash_completion # shellcheck disable=SC1091
fi source /etc/bash_completion
# Some distribution makes use of a profile.d script to import completion. # Some distribution makes use of a profile.d script to import completion.
if [ -f /etc/profile.d/bash_completion.sh ]; then elif [[ -r /etc/profile.d/bash_completion.sh ]] ; then
. /etc/profile.d/bash_completion.sh # shellcheck disable=SC1091
source /etc/profile.d/bash_completion.sh
fi fi
if [[ "$(uname -s)" == 'Darwin' ]] && _command_exists brew ; then
BREW_PREFIX=${BREW_PREFIX:-$(brew --prefix)}
if [ $(uname) = "Darwin" ] && command -v brew &>/dev/null ; then # homebrew/versions/bash-completion2 (required for projects.completion.bash) is installed to this path
BREW_PREFIX=$(brew --prefix) if [[ -r "$BREW_PREFIX"/etc/profile.d/bash_completion.sh ]] ; then
# shellcheck disable=SC1090
if [ -f "$BREW_PREFIX"/etc/bash_completion ]; then source "$BREW_PREFIX"/etc/profile.d/bash_completion.sh
. "$BREW_PREFIX"/etc/bash_completion
fi
# homebrew/versions/bash-completion2 (required for projects.completion.bash) is installed to this path
if [ "${BASH_VERSINFO}" -ge 4 ] && [ -f "$BREW_PREFIX"/share/bash-completion/bash_completion ]; then
export BASH_COMPLETION_COMPAT_DIR="$BREW_PREFIX"/etc/bash_completion.d
. "$BREW_PREFIX"/share/bash-completion/bash_completion
fi fi
fi fi

View File

@ -1,65 +1,10 @@
#!/usr/bin/env bash #!/usr/bin/env bash
#
# Bash completion for the terraform command
#
# Copyright (C) 2018 Vangelis Tasoulas
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
_terraform() # Make sure terraform is installed
{ _command_exists terraform || return
local cur prev words cword opts
_get_comp_words_by_ref -n : cur prev words cword
COMPREPLY=()
opts=""
if [[ ${cword} -eq 1 ]] ; then # Don't handle completion if it's already managed
complete -p terraform &>/dev/null && return
# Options that do not start with a hyphen, are always starting with four spaces. # Terraform completes itself
opts="$(terraform --help | grep -E '^\s\s\s\s\S' | awk '{print $1}')" complete -C terraform terraform
opts="${opts} --help --version"
elif [[ ${cword} -gt 1 ]] ; then
if [[ ${cword} -eq 2 && ${prev} == '--help' ]] ; then
opts="$(terraform --help | grep -E '^\s\s\s\s\S' | awk '{print $1}')"
elif [[ ${words[1]} != "--help" && ${words[1]} != "--version" && ${words[1]} != "version" ]] ; then
# Some commands accept hyphened parameters, ...
opts="$(terraform --help "${words[1]}" | grep -E '^\s+-' | awk '{print $1}' | awk -F '=' '{ if ($0 ~ /=/) {print $1"="} else {print $1} }')"
# but some other commands accept non-hyphened parameters.
opts="${opts} $(terraform --help "${words[1]}" | grep -E '^\s\s\s\s\S' | awk '{print $1}')"
# All of the commands accept the --help parameter which is not listed
# by the 'terraform --help <command>
opts="${opts} --help"
fi
fi
COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
if [[ ${#COMPREPLY[*]} -eq 1 ]] ; then
if [[ ${COMPREPLY[0]} == *= ]] ; then
# When only one completion is left, check if there is an equal sign.
# If an equal sign, then add no space after the autocompleted word.
compopt -o nospace
fi
fi
return 0
}
complete -F _terraform terraform

View File

@ -53,7 +53,7 @@ __vagrantinvestigate() {
_vagrant() { _vagrant() {
cur="${COMP_WORDS[COMP_CWORD]}" cur="${COMP_WORDS[COMP_CWORD]}"
prev="${COMP_WORDS[COMP_CWORD-1]}" prev="${COMP_WORDS[COMP_CWORD-1]}"
commands="snapshot box connect destroy docker-logs docker-run global-status halt help init list-commands login package plugin provision rdp reload resume rsync rsync-auto share ssh ssh-config status suspend up version" commands="box cloud destroy global-status halt help hostmanager init login package plugin port powershell provision push rdp reload resume scp snapshot ssh ssh-config status suspend up upload validate vbguest version winrm winrm-config"
if [ $COMP_CWORD == 1 ] if [ $COMP_CWORD == 1 ]
then then
@ -91,12 +91,12 @@ _vagrant() {
return 0 return 0
;; ;;
"box") "box")
box_commands="add help list remove repackage" box_commands="add list outdated prune remove repackage update"
COMPREPLY=($(compgen -W "${box_commands}" -- ${cur})) COMPREPLY=($(compgen -W "${box_commands}" -- ${cur}))
return 0 return 0
;; ;;
"plugin") "plugin")
plugin_commands="install license list uninstall update" plugin_commands="expunge install license list repair uninstall update"
COMPREPLY=($(compgen -W "${plugin_commands}" -- ${cur})) COMPREPLY=($(compgen -W "${plugin_commands}" -- ${cur}))
return 0 return 0
;; ;;
@ -105,7 +105,7 @@ _vagrant() {
return 0 return 0
;; ;;
"snapshot") "snapshot")
snapshot_commands="back delete go list take" snapshot_commands="delete list pop push restore save"
COMPREPLY=($(compgen -W "${snapshot_commands}" -- ${cur})) COMPREPLY=($(compgen -W "${snapshot_commands}" -- ${cur}))
return 0 return 0
;; ;;
@ -135,13 +135,29 @@ _vagrant() {
esac esac
;; ;;
"snapshot") "snapshot")
if [ "$prev" == "go" ]; then if [ "$prev" == "restore" ]; then
local snapshot_list=$(vagrant snapshot list | awk '/Name:/ { print $2 }') COMPREPLY=($(compgen -W "${vm_list}" -- ${cur}))
COMPREPLY=($(compgen -W "${snapshot_list}" -- ${cur}))
return 0 return 0
fi fi
;; ;;
esac esac
fi fi
if [ $COMP_CWORD == 4 ]
then
action="${COMP_WORDS[COMP_CWORD-3]}"
prev="${COMP_WORDS[COMP_CWORD-2]}"
case "$action" in
"snapshot")
if [ "$prev" == "restore" ]; then
local snapshot_list="$(vagrant snapshot list ${cur} 2>/dev/null | awk '{ORS=" "} /==>/ {next} {print}')"
COMPREPLY=($(compgen -W "${snapshot_list}" -- ${cur}))
return 0
fi
;;
*)
;;
esac
fi
} }
complete -F _vagrant vagrant complete -F _vagrant vagrant

View File

@ -19,9 +19,11 @@ function _command_exists ()
{ {
_about 'checks for existence of a command' _about 'checks for existence of a command'
_param '1: command to check' _param '1: command to check'
_param '2: (optional) log message to include when command not found'
_example '$ _command_exists ls && echo exists' _example '$ _command_exists ls && echo exists'
_group 'lib' _group 'lib'
type "$1" &> /dev/null ; local msg="${2:-Command '$1' does not exist!}"
type "$1" &> /dev/null || (_log_warning "$msg" && return 1) ;
} }
function _make_reload_alias() { function _make_reload_alias() {
@ -43,7 +45,7 @@ alias reload_plugins="$(_make_reload_alias plugin plugins)"
bash-it () bash-it ()
{ {
about 'Bash-it help and maintenance' about 'Bash-it help and maintenance'
param '1: verb [one of: help | show | enable | disable | migrate | update | search | version | reload ] ' param '1: verb [one of: help | show | enable | disable | migrate | update | search | version | reload | restart | doctor ] '
param '2: component type [one of: alias(es) | completion(s) | plugin(s) ] or search term(s)' param '2: component type [one of: alias(es) | completion(s) | plugin(s) ] or search term(s)'
param '3: specific component [optional]' param '3: specific component [optional]'
example '$ bash-it show plugins' example '$ bash-it show plugins'
@ -55,6 +57,8 @@ bash-it ()
example '$ bash-it search [-|@]term1 [-|@]term2 ... [ -e/--enable ] [ -d/--disable ] [ -r/--refresh ] [ -c/--no-color ]' example '$ bash-it search [-|@]term1 [-|@]term2 ... [ -e/--enable ] [ -d/--disable ] [ -r/--refresh ] [ -c/--no-color ]'
example '$ bash-it version' example '$ bash-it version'
example '$ bash-it reload' example '$ bash-it reload'
example '$ bash-it restart'
example '$ bash-it doctor errors|warnings|all'
typeset verb=${1:-} typeset verb=${1:-}
shift shift
typeset component=${1:-} typeset component=${1:-}
@ -70,15 +74,19 @@ bash-it ()
func=_disable-$component;; func=_disable-$component;;
help) help)
func=_help-$component;; func=_help-$component;;
doctor)
func=_bash-it-doctor-$component;;
search) search)
_bash-it-search $component "$@" _bash-it-search $component "$@"
return;; return;;
update) update)
func=_bash-it_update;; func=_bash-it_update-$component;;
migrate) migrate)
func=_bash-it-migrate;; func=_bash-it-migrate;;
version) version)
func=_bash-it-version;; func=_bash-it-version;;
restart)
func=_bash-it-restart;;
reload) reload)
func=_bash-it-reload;; func=_bash-it-reload;;
*) *)
@ -109,6 +117,10 @@ bash-it ()
do do
$func $arg $func $arg
done done
if [ -n "$BASH_IT_AUTOMATIC_RELOAD_AFTER_CONFIG_CHANGE" ]; then
_bash-it-reload
fi
else else
$func "$@" $func "$@"
fi fi
@ -146,60 +158,127 @@ _bash-it-plugins ()
_bash-it-describe "plugins" "a" "plugin" "Plugin" _bash-it-describe "plugins" "a" "plugin" "Plugin"
} }
_bash-it_update() { _bash-it_update-dev() {
_about 'updates Bash-it' _about 'updates Bash-it to the latest master'
_group 'lib' _group 'lib'
_bash-it_update- dev "$@"
}
_bash-it_update-stable() {
_about 'updates Bash-it to the latest tag'
_group 'lib'
_bash-it_update- stable "$@"
}
_bash-it_pull_and_update_inner() {
git checkout "$1" &> /dev/null
if [[ $? -eq 0 ]]; then
echo "Bash-it successfully updated."
echo ""
echo "Migrating your installation to the latest $2 version now..."
_bash-it-migrate
echo ""
echo "All done, enjoy!"
bash-it reload
else
echo "Error updating Bash-it, please, check if your Bash-it installation folder (${BASH_IT}) is clean."
fi
}
_bash-it_update-() {
_about 'updates Bash-it'
_param '1: What kind of update to do (stable|dev)'
_group 'lib'
declare silent
for word in $@; do
if [[ ${word} == "--silent" || ${word} == "-s" ]]; then
silent=true
fi
done
local old_pwd="${PWD}" local old_pwd="${PWD}"
cd "${BASH_IT}" || return cd "${BASH_IT}" || return
if [ -z $BASH_IT_REMOTE ]; then if [ -z "$BASH_IT_REMOTE" ]; then
BASH_IT_REMOTE="origin" BASH_IT_REMOTE="origin"
fi fi
git fetch &> /dev/null git fetch $BASH_IT_REMOTE --tags &> /dev/null
if [ -z "$BASH_IT_DEVELOPMENT_BRANCH" ]; then
BASH_IT_DEVELOPMENT_BRANCH="master"
fi
# Defaults to stable update
if [ -z "$1" ] || [ "$1" == "stable" ]; then
version="stable"
TARGET=$(git describe --tags "$(git rev-list --tags --max-count=1)" 2> /dev/null)
if [[ -z "$TARGET" ]]; then
echo "Can not find tags, so can not update to latest stable version..."
return
fi
else
version="dev"
TARGET=${BASH_IT_REMOTE}/${BASH_IT_DEVELOPMENT_BRANCH}
fi
declare revision
revision="HEAD..${TARGET}"
declare status declare status
status="$(git rev-list master..${BASH_IT_REMOTE}/master 2> /dev/null)" status="$(git rev-list ${revision} 2> /dev/null)"
declare revert
if [[ -z "${status}" && ${version} == "stable" ]]; then
revision="${TARGET}..HEAD"
status="$(git rev-list ${revision} 2> /dev/null)"
revert=true
fi
if [[ -n "${status}" ]]; then if [[ -n "${status}" ]]; then
if [[ $revert ]]; then
echo "Your version is a more recent development version ($(git log -1 --format=%h HEAD))"
echo "You can continue in order to revert and update to the latest stable version"
echo ""
log_color="%Cred"
fi
for i in $(git rev-list --merges --first-parent master..${BASH_IT_REMOTE}); do for i in $(git rev-list --merges --first-parent ${revision}); do
num_of_lines=$(git log -1 --format=%B $i | awk 'NF' | wc -l) num_of_lines=$(git log -1 --format=%B $i | awk 'NF' | wc -l)
if [ $num_of_lines -eq 1 ]; then if [ $num_of_lines -eq 1 ]; then
description="%s" description="%s"
else else
description="%b" description="%b"
fi fi
git log --format="%h: $description (%an)" -1 $i git log --format="${log_color}%h: $description (%an)" -1 $i
done done
echo "" echo ""
read -e -n 1 -p "Would you like to update to $(git log -1 --format=%h origin/master)? [Y/n] " RESP
case $RESP in if [[ $silent ]]; then
[yY]|"") echo "Updating to ${TARGET}($(git log -1 --format=%h "${TARGET}"))..."
git pull --rebase &> /dev/null _bash-it_pull_and_update_inner $TARGET $version
if [[ $? -eq 0 ]]; then else
echo "Bash-it successfully updated." read -e -n 1 -p "Would you like to update to ${TARGET}($(git log -1 --format=%h "${TARGET}"))? [Y/n] " RESP
echo "" case $RESP in
echo "Migrating your installation to the latest version now..." [yY]|"")
_bash-it-migrate _bash-it_pull_and_update_inner $TARGET $version
echo "" ;;
echo "All done, enjoy!" [nN])
bash-it reload echo "Not updating…"
else ;;
echo "Error updating Bash-it, please, check if your Bash-it installation folder (${BASH_IT}) is clean." *)
fi echo -e "\033[91mPlease choose y or n.\033[m"
;; ;;
[nN]) esac
echo "Not upgrading…" fi
;;
*)
echo -e "\033[91mPlease choose y or n.\033[m"
;;
esac
else else
echo "Bash-it is up to date, nothing to do!" if [[ ${version} == "stable" ]]; then
echo "You're on the latest stable version. If you want to check out the latest 'dev' version, please run \"bash-it update dev\""
else
echo "Bash-it is up to date, nothing to do!"
fi
fi fi
cd "${old_pwd}" &> /dev/null || return cd "${old_pwd}" &> /dev/null || return
} }
@ -234,6 +313,10 @@ _bash-it-migrate() {
done done
done done
if [ -n "$BASH_IT_AUTOMATIC_RELOAD_AFTER_CONFIG_CHANGE" ]; then
_bash-it-reload
fi
if [ "$migrated_something" = "true" ]; then if [ "$migrated_something" = "true" ]; then
echo "" echo ""
echo "If any migration errors were reported, please try the following: reload && bash-it migrate" echo "If any migration errors were reported, please try the following: reload && bash-it migrate"
@ -263,6 +346,61 @@ _bash-it-version() {
cd - &> /dev/null || return cd - &> /dev/null || return
} }
_bash-it-doctor() {
_about 'reloads a profile file with a BASH_IT_LOG_LEVEL set'
_param '1: BASH_IT_LOG_LEVEL argument: "errors" "warnings" "all"'
_group 'lib'
BASH_IT_LOG_LEVEL=$1
_bash-it-reload
unset BASH_IT_LOG_LEVEL
}
_bash-it-doctor-all() {
_about 'reloads a profile file with error, warning and debug logs'
_group 'lib'
_bash-it-doctor $BASH_IT_LOG_LEVEL_ALL
}
_bash-it-doctor-warnings() {
_about 'reloads a profile file with error and warning logs'
_group 'lib'
_bash-it-doctor $BASH_IT_LOG_LEVEL_WARNING
}
_bash-it-doctor-errors() {
_about 'reloads a profile file with error logs'
_group 'lib'
_bash-it-doctor $BASH_IT_LOG_LEVEL_ERROR
}
_bash-it-doctor-() {
_about 'default bash-it doctor behavior, behaves like bash-it doctor all'
_group 'lib'
_bash-it-doctor-all
}
_bash-it-restart() {
_about 'restarts the shell in order to fully reload it'
_group 'lib'
saved_pwd=$(pwd)
case $OSTYPE in
darwin*)
init_file=.bash_profile
;;
*)
init_file=.bashrc
;;
esac
exec "${0/-/}" --rcfile <(echo "source \"$HOME/$init_file\"; cd \"$saved_pwd\"")
}
_bash-it-reload() { _bash-it-reload() {
_about 'reloads a profile file' _about 'reloads a profile file'
_group 'lib' _group 'lib'
@ -318,6 +456,17 @@ _bash-it-describe ()
printf '%s\n' "$ bash-it disable $file_type <$file_type name> [$file_type name]... -or- $ bash-it disable $file_type all" printf '%s\n' "$ bash-it disable $file_type <$file_type name> [$file_type name]... -or- $ bash-it disable $file_type all"
} }
_on-disable-callback()
{
_about 'Calls the disabled plugin destructor, if present'
_param '1: plugin name'
_example '$ _on-disable-callback gitstatus'
_group 'lib'
callback=$1_on_disable
_command_exists $callback && $callback
}
_disable-plugin () _disable-plugin ()
{ {
_about 'disables bash_it plugin' _about 'disables bash_it plugin'
@ -326,6 +475,7 @@ _disable-plugin ()
_group 'lib' _group 'lib'
_disable-thing "plugins" "plugin" $1 _disable-thing "plugins" "plugin" $1
_on-disable-callback $1
} }
_disable-alias () _disable-alias ()
@ -400,10 +550,6 @@ _disable-thing ()
_bash-it-clean-component-cache "${file_type}" _bash-it-clean-component-cache "${file_type}"
if [ -n "$BASH_IT_AUTOMATIC_RELOAD_AFTER_CONFIG_CHANGE" ]; then
exec ${0/-/}
fi
printf '%s\n' "$file_entity disabled." printf '%s\n' "$file_entity disabled."
} }
@ -500,10 +646,6 @@ _enable-thing ()
_bash-it-clean-component-cache "${file_type}" _bash-it-clean-component-cache "${file_type}"
if [ -n "$BASH_IT_AUTOMATIC_RELOAD_AFTER_CONFIG_CHANGE" ]; then
exec ${0/-/}
fi
printf '%s\n' "$file_entity enabled with priority $use_load_priority." printf '%s\n' "$file_entity enabled with priority $use_load_priority."
} }

60
lib/log.bash 100644
View File

@ -0,0 +1,60 @@
#!/usr/bin/env bash
export BASH_IT_LOG_LEVEL_ERROR=1
export BASH_IT_LOG_LEVEL_WARNING=2
export BASH_IT_LOG_LEVEL_ALL=3
function _has_colors()
{
# Check that stdout is a terminal
test -t 1 || return 1
ncolors=$(tput colors)
test -n "$ncolors" && test "$ncolors" -ge 8 || return 1
return 0
}
function _log_general()
{
about 'Internal function used for logging, uses BASH_IT_LOG_PREFIX as a prefix'
param '1: color of the message'
param '2: log level to print before the prefix'
param '3: message to log'
group 'log'
message=$2${BASH_IT_LOG_PREFIX}$3
_has_colors && echo -e "$1${message}${echo_normal}" || echo -e "${message}"
}
function _log_debug()
{
about 'log a debug message by echoing to the screen. needs BASH_IT_LOG_LEVEL >= BASH_IT_LOG_LEVEL_ALL'
param '1: message to log'
example '$ _log_debug "Loading plugin git..."'
group 'log'
[[ "$BASH_IT_LOG_LEVEL" -ge $BASH_IT_LOG_LEVEL_ALL ]] || return 0
_log_general "${echo_green}" "DEBUG: " "$1"
}
function _log_warning()
{
about 'log a message by echoing to the screen. needs BASH_IT_LOG_LEVEL >= BASH_IT_LOG_LEVEL_WARNING'
param '1: message to log'
example '$ _log_warning "git binary not found, disabling git plugin..."'
group 'log'
[[ "$BASH_IT_LOG_LEVEL" -ge $BASH_IT_LOG_LEVEL_WARNING ]] || return 0
_log_general "${echo_yellow}" " WARN: " "$1"
}
function _log_error()
{
about 'log a message by echoing to the screen. needs BASH_IT_LOG_LEVEL >= BASH_IT_LOG_LEVEL_ERROR'
param '1: message to log'
example '$ _log_error "Failed to load git plugin..."'
group 'log'
[[ "$BASH_IT_LOG_LEVEL" -ge $BASH_IT_LOG_LEVEL_ERROR ]] || return 0
_log_general "${echo_red}" "ERROR: " "$1"
}

View File

@ -123,7 +123,7 @@ function preexec_install () {
# Finally, install the actual traps. # Finally, install the actual traps.
if [[ ! -z "${PROMPT_COMMAND// }" ]]; then if [[ ! -z "${PROMPT_COMMAND// }" ]]; then
PROMPT_COMMAND="${PROMPT_COMMAND};preexec_invoke_cmd" PROMPT_COMMAND="${PROMPT_COMMAND}"$'\n'"preexec_invoke_cmd"
else else
PROMPT_COMMAND="preexec_invoke_cmd" PROMPT_COMMAND="preexec_invoke_cmd"
fi fi

View File

@ -134,14 +134,14 @@ ${echo_underline_yellow}EXAMPLES${echo_normal}
${echo_bold_green} bash-it search git${echo_bold_blue} ${echo_bold_green} bash-it search git${echo_bold_blue}
${echo_bold_yellow}aliases: ${echo_bold_green}git ${echo_normal}gitsvn ${echo_bold_yellow}aliases: ${echo_bold_green}git ${echo_normal}gitsvn
${echo_bold_yellow}plugins: ${echo_normal}autojump fasd ${echo_bold_green}git ${echo_normal}git-subrepo jgitflow jump ${echo_bold_yellow}plugins: ${echo_normal}autojump ${echo_bold_green}git ${echo_normal}git-subrepo jgitflow jump
${echo_bold_yellow}completions: ${echo_bold_green}git ${echo_normal}git_flow git_flow_avh${echo_normal} ${echo_bold_yellow}completions: ${echo_bold_green}git ${echo_normal}git_flow git_flow_avh${echo_normal}
You can exclude some terms by prefixing a term with a minus, eg: You can exclude some terms by prefixing a term with a minus, eg:
${echo_bold_green} bash-it search git -flow -svn${echo_bold_blue} ${echo_bold_green} bash-it search git -flow -svn${echo_bold_blue}
${echo_bold_yellow}aliases: ${echo_normal}git ${echo_bold_yellow}aliases: ${echo_normal}git
${echo_bold_yellow}plugins: ${echo_normal}autojump fasd git git-subrepo jump ${echo_bold_yellow}plugins: ${echo_normal}autojump git git-subrepo jump
${echo_bold_yellow}completions: ${echo_normal}git${echo_normal} ${echo_bold_yellow}completions: ${echo_normal}git${echo_normal}
Finally, if you prefix a term with '@' symbol, that indicates an exact Finally, if you prefix a term with '@' symbol, that indicates an exact

View File

@ -2,6 +2,69 @@
# #
# A collection of reusable functions. # A collection of reusable functions.
###########################################################################
# Generic utilies
###########################################################################
_bash-it-get-component-name-from-path() {
# filename without path
filename=${1##*/}
# filename without path or priority
filename=${filename##*---}
# filename without path, priority or extension
echo ${filename%.*.bash}
}
_bash-it-get-component-type-from-path() {
# filename without path
filename=${1##*/}
# filename without path or priority
filename=${filename##*---}
# extension
echo ${filename} | cut -d '.' -f 2
}
# This function searches an array for an exact match against the term passed
# as the first argument to the function. This function exits as soon as
# a match is found.
#
# Returns:
# 0 when a match is found, otherwise 1.
#
# Examples:
# $ declare -a fruits=(apple orange pear mandarin)
#
# $ _bash-it-array-contains-element apple "@{fruits[@]}" && echo 'contains apple'
# contains apple
#
# $ if $(_bash-it-array-contains-element pear "${fruits[@]}"); then
# echo "contains pear!"
# fi
# contains pear!
#
#
_bash-it-array-contains-element() {
local e
for e in "${@:2}"; do
[[ "$e" == "$1" ]] && return 0
done
return 1
}
# Dedupe a simple array of words without spaces.
_bash-it-array-dedup() {
echo "$*" | tr ' ' '\n' | sort -u | tr '\n' ' '
}
# Outputs a full path of the grep found on the filesystem
_bash-it-grep() {
if [[ -z "${BASH_IT_GREP}" ]] ; then
export BASH_IT_GREP="$(which egrep || which grep || '/usr/bin/grep')"
fi
printf "%s " "${BASH_IT_GREP}"
}
########################################################################### ###########################################################################
# Component-specific functions (component is either an alias, a plugin, or a # Component-specific functions (component is either an alias, a plugin, or a
# completion). # completion).
@ -50,51 +113,6 @@ _bash-it-clean-component-cache() {
fi fi
} }
###########################################################################
# Generic utilies
###########################################################################
# This function searches an array for an exact match against the term passed
# as the first argument to the function. This function exits as soon as
# a match is found.
#
# Returns:
# 0 when a match is found, otherwise 1.
#
# Examples:
# $ declare -a fruits=(apple orange pear mandarin)
#
# $ _bash-it-array-contains-element apple "@{fruits[@]}" && echo 'contains apple'
# contains apple
#
# $ if $(_bash-it-array-contains-element pear "${fruits[@]}"); then
# echo "contains pear!"
# fi
# contains pear!
#
#
_bash-it-array-contains-element() {
local e
for e in "${@:2}"; do
[[ "$e" == "$1" ]] && return 0
done
return 1
}
# Dedupe a simple array of words without spaces.
_bash-it-array-dedup() {
echo "$*" | tr ' ' '\n' | sort -u | tr '\n' ' '
}
# Outputs a full path of the grep found on the filesystem
_bash-it-grep() {
if [[ -z "${BASH_IT_GREP}" ]] ; then
export BASH_IT_GREP="$(which egrep || which grep || '/usr/bin/grep')"
fi
printf "%s " "${BASH_IT_GREP}"
}
# Returns an array of items within each compoenent. # Returns an array of items within each compoenent.
_bash-it-component-list() { _bash-it-component-list() {
local component="$1" local component="$1"

View File

@ -65,12 +65,21 @@ function alias_completion {
if [[ "${compl_func#_$namespace::}" == $compl_func ]]; then if [[ "${compl_func#_$namespace::}" == $compl_func ]]; then
local compl_wrapper="_${namespace}::${alias_name}" local compl_wrapper="_${namespace}::${alias_name}"
echo "function $compl_wrapper { echo "function $compl_wrapper {
local compl_word=\$2
local prec_word=\$3
# check if prec_word is the alias itself. if so, replace it
# with the last word in the unaliased form, i.e.,
# alias_cmd + ' ' + alias_args.
if [[ \$COMP_LINE == \"\$prec_word \$compl_word\" ]]; then
prec_word='$alias_cmd $alias_args'
prec_word=\${prec_word#* }
fi
(( COMP_CWORD += ${#alias_arg_words[@]} )) (( COMP_CWORD += ${#alias_arg_words[@]} ))
COMP_WORDS=($alias_cmd $alias_args \${COMP_WORDS[@]:1}) COMP_WORDS=($alias_cmd $alias_args \${COMP_WORDS[@]:1})
(( COMP_POINT -= \${#COMP_LINE} )) (( COMP_POINT -= \${#COMP_LINE} ))
COMP_LINE=\${COMP_LINE/$alias_name/$alias_cmd $alias_args} COMP_LINE=\${COMP_LINE/$alias_name/$alias_cmd $alias_args}
(( COMP_POINT += \${#COMP_LINE} )) (( COMP_POINT += \${#COMP_LINE} ))
$compl_func $compl_func \"$alias_cmd\" \"\$compl_word\" \"\$prec_word\"
}" >> "$tmp_file" }" >> "$tmp_file"
new_completion="${new_completion/ -F $compl_func / -F $compl_wrapper }" new_completion="${new_completion/ -F $compl_func / -F $compl_wrapper }"
fi fi

View File

@ -40,7 +40,8 @@ function __awskeys_help {
function __awskeys_get { function __awskeys_get {
local ln=$(grep -n "\[ *$1 *\]" "${AWS_SHARED_CREDENTIALS_FILE}" | cut -d ":" -f 1) local ln=$(grep -n "\[ *$1 *\]" "${AWS_SHARED_CREDENTIALS_FILE}" | cut -d ":" -f 1)
if [[ -n "${ln}" ]]; then if [[ -n "${ln}" ]]; then
tail -n +${ln} "${AWS_SHARED_CREDENTIALS_FILE}" | egrep -m 3 "aws_access_key_id|aws_secret_access_key|aws_session_token" tail -n +${ln} "${AWS_SHARED_CREDENTIALS_FILE}" | egrep -m 2 "aws_access_key_id|aws_secret_access_key"
tail -n +${ln} "${AWS_SHARED_CREDENTIALS_FILE}" | egrep -m 1 "aws_session_token"
fi fi
} }

View File

@ -32,7 +32,7 @@ function myip ()
list=("http://myip.dnsomatic.com/" "http://checkip.dyndns.com/" "http://checkip.dyndns.org/") list=("http://myip.dnsomatic.com/" "http://checkip.dyndns.com/" "http://checkip.dyndns.org/")
for url in ${list[*]} for url in ${list[*]}
do do
res=$(curl -s "${url}") res=$(curl -fs "${url}")
if [ $? -eq 0 ];then if [ $? -eq 0 ];then
break; break;
fi fi

View File

@ -0,0 +1,21 @@
cite about-plugin
about-plugin 'Simplify `curl cht.sh/<query>` to `cht.sh <query>`'
# Play nicely if user already installed cht.sh cli tool
if ! _command_exists cht.sh ; then
function cht.sh () {
about 'Executes a cht.sh curl query using the provided arguments'
param ' [ ( topic [sub-topic] ) | ~keyword ] [ :list | :help | :learn ]'
example '$ cht.sh :help'
example '$ cht.sh :list'
example '$ cht.sh tar'
example '$ cht.sh js "parse json"'
example '$ cht.sh python :learn'
example '$ cht.sh rust :list'
group 'cht-sh'
# Separate arguments with '/', preserving spaces within them
local query=$(IFS=/ ; echo "$*")
curl "cht.sh/${query}"
}
fi

View File

@ -29,12 +29,28 @@ End-Of-Usage
[ $# -eq 0 ] && extract -h && return 1 [ $# -eq 0 ] && extract -h && return 1
while [ $# -gt 0 ]; do while [ $# -gt 0 ]; do
if [ -f "$1" ]; then if [[ ! -f "$1" ]]; then
case "$1" in echo "extract: '$1' is not a valid file" >&2
*.tar.bz2|*.tbz|*.tbz2) tar "x${verbose}jf" "$1" ;; shift
*.tar.gz|*.tgz) tar "x${verbose}zf" "$1" ;; continue
*.tar.xz) xz --decompress "$1"; set -- "$@" "${1:0:-3}" ;; fi
*.tar.Z) uncompress "$1"; set -- "$@" "${1:0:-2}" ;;
local -r filename=$(basename -- $1)
local -r filedirname=$(dirname -- $1)
local targetdirname=$(sed 's/\(\.tar\.bz2$\|\.tbz$\|\.tbz2$\|\.tar\.gz$\|\.tgz$\|\.tar$\|\.tar\.xz$\|\.txz$\|\.tar\.Z$\|\.7z$\)//g' <<< $filename)
if [ "$filename" = "$targetdirname" ]; then
# archive type either not supported or it doesn't need dir creation
targetdirname=""
else
mkdir -v "$filedirname/$targetdirname"
fi
if [ -f "$1" ]; then
case "$1" in
*.tar.bz2|*.tbz|*.tbz2) tar "x${verbose}jf" "$1" -C "$filedirname/$targetdirname" ;;
*.tar.gz|*.tgz) tar "x${verbose}zf" "$1" -C "$filedirname/$targetdirname" ;;
*.tar.xz|*.txz) tar "x${verbose}Jf" "$1" -C "$filedirname/$targetdirname" ;;
*.tar.Z) tar "x${verbose}Zf" "$1" -C "$filedirname/$targetdirname" ;;
*.bz2) bunzip2 "$1" ;; *.bz2) bunzip2 "$1" ;;
*.deb) dpkg-deb -x${verbose} "$1" "${1:0:-4}" ;; *.deb) dpkg-deb -x${verbose} "$1" "${1:0:-4}" ;;
*.pax.gz) gunzip "$1"; set -- "$@" "${1:0:-3}" ;; *.pax.gz) gunzip "$1"; set -- "$@" "${1:0:-3}" ;;
@ -43,17 +59,15 @@ End-Of-Usage
*.pkg) pkgutil --expand "$1" "${1:0:-4}" ;; *.pkg) pkgutil --expand "$1" "${1:0:-4}" ;;
*.rar) unrar x "$1" ;; *.rar) unrar x "$1" ;;
*.rpm) rpm2cpio "$1" | cpio -idm${verbose} ;; *.rpm) rpm2cpio "$1" | cpio -idm${verbose} ;;
*.tar) tar "x${verbose}f" "$1" ;; *.tar) tar "x${verbose}f" "$1" -C "$filedirname/$targetdirname" ;;
*.txz) mv "$1" "${1:0:-4}.tar.xz"; set -- "$@" "${1:0:-4}.tar.xz" ;;
*.xz) xz --decompress "$1" ;; *.xz) xz --decompress "$1" ;;
*.zip|*.war|*.jar) unzip "$1" ;; *.zip|*.war|*.jar) unzip "$1" ;;
*.Z) uncompress "$1" ;; *.Z) uncompress "$1" ;;
*.7z) 7za x "$1" ;; *.7z) 7za x "$1" ;;
*) echo "'$1' cannot be extracted via extract" >&2;; *) echo "'$1' cannot be extracted via extract" >&2;;
esac esac
else fi
echo "extract: '$1' is not a valid file" >&2
fi
shift shift
done done
} }

34
plugins/available/fasd.plugin.bash 100755 → 100644
View File

@ -1,34 +1,6 @@
cite about-plugin cite about-plugin
about-plugin 'initialize fasd (see https://github.com/clvv/fasd)' about-plugin 'load fasd, if you are using it'
__init_fasd() { _command_exists fasd || return
command -v fasd &> /dev/null
if [ $? -eq 1 ]; then
echo -e "You must install fasd before you can use this plugin"
echo -e "See: https://github.com/clvv/fasd"
else
eval "$(fasd --init posix-alias)"
# Note, this is a custom bash-hook to ensure that the last exit status eval "$(fasd --init auto)"
# is maintained even while this hook is in place. This code can be
# removed once PR #72 is merged into fasd.
#
# See: https://github.com/clvv/fasd/pull/72
_fasd_prompt_func() {
local _exit_code="$?"
eval "fasd --proc $(fasd --sanitize $(history 1 | \
sed "s/^[ ]*[0-9]*[ ]*//"))" >> "/dev/null" 2>&1
return $_exit_code
}
# add bash hook
case $PROMPT_COMMAND in
*_fasd_prompt_func*) ;;
"") PROMPT_COMMAND="_fasd_prompt_func";;
*) PROMPT_COMMAND="_fasd_prompt_func;$PROMPT_COMMAND";;
esac
eval "$(fasd --init bash-ccomp bash-ccomp-install)"
fi
}
__init_fasd

View File

@ -4,14 +4,16 @@
cite about-plugin cite about-plugin
about-plugin 'load fzf, if you are using it' about-plugin 'load fzf, if you are using it'
if [ -f ~/.fzf.bash ]; then _command_exists fzf || return
if [ -r ~/.fzf.bash ] ; then
source ~/.fzf.bash source ~/.fzf.bash
elif [ -f "${XDG_CONFIG_HOME:-$HOME/.config}"/fzf/fzf.bash ]; then elif [ -r "${XDG_CONFIG_HOME:-$HOME/.config}"/fzf/fzf.bash ] ; then
source "${XDG_CONFIG_HOME:-$HOME/.config}"/fzf/fzf.bash source "${XDG_CONFIG_HOME:-$HOME/.config}"/fzf/fzf.bash
fi fi
if [ -z ${FZF_DEFAULT_COMMAND+x} ]; then if [ -z ${FZF_DEFAULT_COMMAND+x} ] && _command_exists fd ; then
command -v fd &> /dev/null && export FZF_DEFAULT_COMMAND='fd --type f' export FZF_DEFAULT_COMMAND='fd --type f'
fi fi
fe() { fe() {
@ -37,13 +39,3 @@ fcd() {
-o -type d -print 2> /dev/null | fzf +m) && -o -type d -print 2> /dev/null | fzf +m) &&
cd "$dir" cd "$dir"
} }
vf() {
about "Use fasd to search the file to open in vim"
group "fzf"
param "1: Search term for fasd"
example "vf xml"
local file
file="$(fasd -Rfl "$1" | fzf -1 -0 --no-sort +m)" && vi "${file}" || return 1
}

View File

@ -1,4 +0,0 @@
cite about-plugin
about-plugin 'load gh, if you are using it (DEPRECATED, use hub instead)'
command -v gh 2> /dev/null && eval "$(gh alias -s)"

View File

@ -162,7 +162,7 @@ function v2gif {
if [[ "$use_gifski" = "true" ]] ; then if [[ "$use_gifski" = "true" ]] ; then
# I trust @pornel to do his own resizing optimization choices # I trust @pornel to do his own resizing optimization choices
$ffmpeg -loglevel panic -i "$file" -r $fps -vcodec png v2gif-tmp-%05d.png && \ $ffmpeg -loglevel panic -i "$file" -r $fps -vcodec png v2gif-tmp-%05d.png && \
$gifski $maxwidthski --fps $(printf "%.0f" $fps) -o "$output_file" v2gif-tmp-*.png || return 2 $gifski v2gif-tmp-*.png $maxwidthski --fps $(printf "%.0f" $fps) -o "$output_file" || return 2
else else
$ffmpeg -loglevel panic -i "$file" $maxsize -r $fps -vcodec png v2gif-tmp-%05d.png && \ $ffmpeg -loglevel panic -i "$file" $maxsize -r $fps -vcodec png v2gif-tmp-%05d.png && \
$convert +dither -layers Optimize v2gif-tmp-*.png GIF:- | \ $convert +dither -layers Optimize v2gif-tmp-*.png GIF:- | \

View File

@ -0,0 +1,26 @@
cite about-plugin
about-plugin 'speeds up your life by using gitstatus for git status calculations. install from https://github.com/romkatv/gitstatus'
function gitstatus_on_disable() {
about 'Destructor of gitstatus plugin'
group 'gitstatus'
unset SCM_GIT_USE_GITSTATUS
_command_exists gitstatus_stop && gitstatus_stop
}
# No scm-check
[[ $SCM_CHECK == "true" ]] || return
# non-interactive shell
[[ $- == *i* ]] || return
: "${SCM_GIT_GITSTATUS_DIR:="$HOME/gitstatus"}"
if [[ -d ${SCM_GIT_GITSTATUS_DIR} ]]; then
source "${SCM_GIT_GITSTATUS_DIR}/gitstatus.plugin.sh"
# Start the actual gitstatus binary
gitstatus_stop && gitstatus_start -s -1 -u -1 -c -1 -d -1
export SCM_GIT_USE_GITSTATUS=true
else
_log_warning "Could not find gitstatus directory in ${SCM_GIT_GITSTATUS_DIR}. Please specify directory location using SCM_GIT_GITSTATUS_DIR."
fi

View File

@ -3,27 +3,17 @@
cite about-plugin cite about-plugin
about-plugin 'go environment variables & path configuration' about-plugin 'go environment variables & path configuration'
[ ! command -v go &>/dev/null ] && return command -v go &>/dev/null || return
function _split_path_reverse() { function _go_pathmunge_wrap() {
local a=( ${@//:/ } ) IFS=':' local -a 'a=($1)'
local i=${#a[@]} local i=${#a[@]}
local r=
while [ $i -gt 0 ] ; do while [ $i -gt 0 ] ; do
i=$(( i - 1 )) i=$(( i - 1 ))
if [ $(( i + 1 )) -eq ${#a[@]} ] ; then pathmunge "${a[i]}/bin"
r="${a[i]}"
else
r="${r} ${a[i]}"
fi
done done
echo "$r"
} }
export GOROOT=${GOROOT:-$(go env GOROOT)} export GOROOT="${GOROOT:-$(go env GOROOT)}"
pathmunge "${GOROOT}/bin" export GOPATH="${GOPATH:-$(go env GOPATH)}"
_go_pathmunge_wrap "${GOPATH}:${GOROOT}"
export GOPATH=${GOPATH:-$(go env GOPATH)}
for p in $( _split_path_reverse ${GOPATH} ) ; do
pathmunge "${p}/bin"
done

View File

@ -0,0 +1,20 @@
cite about-plugin
about-plugin 'load goenv, if you are using it'
# Don't modify the environment if we can't find the tool:
# - Check if in $PATH already
# - Check if installed manually to $GOENV_ROOT
# - Check if installed manually to $HOME
_command_exists goenv ||
[[ -n "$GOENV_ROOT" && -x "$GOENV_ROOT/bin/goenv" ]] ||
[[ -x "$HOME/.goenv/bin/goenv" ]] ||
return
# Set GOENV_ROOT, if not already set
export GOENV_ROOT="${GOENV_ROOT:-$HOME/.goenv}"
# Add GOENV_ROOT/bin to PATH, if that's where it's installed
! _command_exists goenv && [[ -x "$GOENV_ROOT/bin/goenv" ]] && pathmunge "$GOENV_ROOT/bin"
# Initialize goenv
eval "$(goenv init - bash)"

View File

@ -1,7 +1,22 @@
cite about-plugin cite about-plugin
about-plugin 'load jenv, if you are using it' about-plugin 'load jenv, if you are using it'
export JENV_ROOT="$HOME/.jenv" # Don't modify the environment if we can't find the tool:
pathmunge "$JENV_ROOT/bin" # - Check if in $PATH already
# - Check if installed manually to $JENV_ROOT
# - Check if installed manually to $HOME
_command_exists jenv ||
[[ -n "$JENV_ROOT" && -x "$JENV_ROOT/bin/jenv" ]] ||
[[ -x "$HOME/.jenv/bin/jenv" ]] ||
return
if which jenv > /dev/null; then eval "$(jenv init - bash)"; fi # Set JENV_ROOT, if not already set
export JENV_ROOT="${JENV_ROOT:-$HOME/.jenv}"
# Add JENV_ROOT/bin to PATH, if that's where it's installed
! _command_exists jenv &&
[[ -x "$JENV_ROOT/bin/jenv" ]] &&
pathmunge "$JENV_ROOT/bin"
# Initialize jenv
eval "$(jenv init - bash)"

View File

@ -1,9 +1,9 @@
cite about-plugin cite about-plugin
about-plugin 'initialize jump (see https://github.com/gsamokovarov/jump)' about-plugin 'initialize jump (see https://github.com/gsamokovarov/jump). Add `export JUMP_OPTS=("--bind=z")` to change keybinding'
__init_jump() { __init_jump() {
command -v jump &> /dev/null || return command -v jump &> /dev/null || return
eval "$(jump shell --bind=z)" eval "$(jump shell bash "${JUMP_OPTS[@]}")"
} }
__init_jump __init_jump

View File

@ -0,0 +1,10 @@
cite about-plugin
about-plugin 'colorize man pages for better readability'
export LESS_TERMCAP_mb=$'\e[1;32m'
export LESS_TERMCAP_md=$'\e[1;32m'
export LESS_TERMCAP_me=$'\e[0m'
export LESS_TERMCAP_se=$'\e[0m'
export LESS_TERMCAP_so=$'\e[01;33m'
export LESS_TERMCAP_ue=$'\e[0m'
export LESS_TERMCAP_us=$'\e[1;4;31m'

View File

@ -1,7 +1,13 @@
cite about-plugin cite about-plugin
about-plugin 'Node.js helper functions' about-plugin 'Node.js helper functions'
# Ensure local modules are preferred in PATH
pathmunge "./node_modules/.bin" "after" pathmunge "./node_modules/.bin" "after"
# Make sure the global npm prefix is on the path # Check that we have npm
[[ `which npm 2>/dev/null` ]] && pathmunge "$(npm config get prefix)/bin" "after" out=$(command -v npm 2>&1) || return
# If not using nodenv, ensure global modules are in PATH
if [[ ! $out == *"nodenv/shims"* ]] ; then
pathmunge "$(npm config get prefix)/bin" "after"
fi

View File

@ -1,5 +1,5 @@
cite about-plugin cite about-plugin
about-plugin 'Search&Select history and fasd with percol' about-plugin 'Search&Select history with percol'
# Notice # Notice
## You have to upgrade bash to bash 4.x on Mac OS X. ## You have to upgrade bash to bash 4.x on Mac OS X.
@ -8,11 +8,9 @@ about-plugin 'Search&Select history and fasd with percol'
# Install # Install
## (sudo) pip install percol ## (sudo) pip install percol
## bash-it enable percol ## bash-it enable percol
## optional: bash-it enable fasd
# Usage # Usage
## C-r to search&select from history ## C-r to search&select from history
## zz to search&select from fasd
_replace_by_history() { _replace_by_history() {
if command -v tac>/dev/null; then if command -v tac>/dev/null; then
@ -33,17 +31,5 @@ if command -v percol>/dev/null; then
echo -e "\033[91m Your current Bash version is $BASH_VERSION.\033[m" echo -e "\033[91m Your current Bash version is $BASH_VERSION.\033[m"
else else
bind -x '"\C-r": _replace_by_history' bind -x '"\C-r": _replace_by_history'
# bind zz to percol if fasd enable
if [[ $(type -t zz) == 'alias' ]]; then
unalias zz
fi
if command -v fasd>/dev/null; then
function zz() {
local l=$(fasd -d | awk '{print $2}' | percol)
cd $l
}
fi
fi fi
fi fi

View File

@ -1,5 +1,5 @@
cite about-plugin cite about-plugin
about-plugin 'add "export PROJECT_PATHS=~/projects:~/intertrode/projects" to navigate quickly to your project directories with `pj` and `pjo`' about-plugin 'quickly navigate configured paths with `pj` and `pjo`. example: "export PROJECT_PATHS=~/projects:~/work/projects"'
function pj { function pj {
about 'navigate quickly to your various project directories' about 'navigate quickly to your various project directories'

View File

@ -8,6 +8,9 @@ function add_ssh() {
param '3: user' param '3: user'
group 'ssh' group 'ssh'
[[ $# -ne 3 ]] && echo "add_ssh host hostname user" && return 1
[[ ! -d ~/.ssh ]] && mkdir -m 700 ~/.ssh
[[ ! -e ~/.ssh/config ]] && touch ~/.ssh/config && chmod 600 ~/.ssh/config
echo -en "\n\nHost $1\n HostName $2\n User $3\n ServerAliveInterval 30\n ServerAliveCountMax 120" >> ~/.ssh/config echo -en "\n\nHost $1\n HostName $2\n User $3\n ServerAliveInterval 30\n ServerAliveCountMax 120" >> ~/.ssh/config
} }

View File

@ -94,7 +94,6 @@ function _ensure_valid_sshagent_env() {
return return
fi fi
echo "There's a dead ssh-agent at the landing..."
ssh-agent > "${SSH_AGENT_ENV}" ssh-agent > "${SSH_AGENT_ENV}"
return return
} }
@ -125,7 +124,7 @@ function sshagent() {
about 'ensures ssh-agent is up and running' about 'ensures ssh-agent is up and running'
param '1: on|off ' param '1: on|off '
example '$ sshagent on' example '$ sshagent on'
group 'ssh' group 'ssh'
[[ -z "${SSH_AGENT_ENV}" ]] \ [[ -z "${SSH_AGENT_ENV}" ]] \
&& export SSH_AGENT_ENV="${HOME}/.ssh/agent_env.${HOSTNAME}" && export SSH_AGENT_ENV="${HOME}/.ssh/agent_env.${HOSTNAME}"

View File

@ -0,0 +1,22 @@
cite about-plugin
about-plugin 'Toggle sudo at the beginning of the current or the previous command by hitting the ESC key twice'
function sudo-command-line() {
about "toggle sudo at the beginning of the current or the previous command by hitting the ESC key twice"
group "sudo"
[[ ${#READLINE_LINE} -eq 0 ]] && READLINE_LINE=$(fc -l -n -1 | xargs)
if [[ $READLINE_LINE == sudo\ * ]]; then
READLINE_LINE="${READLINE_LINE#sudo }"
else
READLINE_LINE="sudo $READLINE_LINE"
fi
READLINE_POINT=${#READLINE_LINE}
}
# Define shortcut keys: [Esc] [Esc]
# Readline library requires bash version 4 or later
if [ "${BASH_VERSINFO}" -ge 4 ]; then
bind -x '"\e\e": sudo-command-line'
fi

View File

@ -0,0 +1,9 @@
cite about-plugin
about-plugin 'Initialization for fuck'
# https://github.com/nvbn/thefuck
if _command_exists thefuck; then
# shellcheck disable=SC2046
eval $(thefuck --alias)
fi

View File

@ -1,12 +0,0 @@
cite about-plugin
about-plugin 'Defines the `code` executable for Visual Studio Code on OS X'
# Based on https://code.visualstudio.com/Docs/editor/setup
if [[ `uname -s` == "Darwin" ]]; then
function code () {
about 'Starts Visual Studio Code in the provided directory'
group 'visual-studio-code'
VSCODE_CWD="$PWD" open -n -b "com.microsoft.VSCode" --args $* ;
}
fi

View File

@ -3,7 +3,7 @@ about-plugin 'automatically set your xterm title with host and location info'
_short-dirname () { _short-dirname () {
local dir_name=`dirs -0` local dir_name=`dirs +0`
[ "$SHORT_TERM_LINE" = true ] && [ ${#dir_name} -gt 8 ] && echo ${dir_name##*/} || echo $dir_name [ "$SHORT_TERM_LINE" = true ] && [ ${#dir_name} -gt 8 ] && echo ${dir_name##*/} || echo $dir_name
} }

View File

@ -1,153 +0,0 @@
cite about-plugin
about-plugin 'maintains a jump-list of the directories you actually use'
about-plugin ' z is DEPRECATED, use fasd instead'
# INSTALL:
# * put something like this in your .bashrc:
# . /path/to/z.sh
# * cd around for a while to build up the db
# * PROFIT!!
#
# USE:
# * z foo # goes to most frecent dir matching foo
# * z foo bar # goes to most frecent dir matching foo and bar
# * z -r foo # goes to highest ranked dir matching foo
# * z -t foo # goes to most recently accessed dir matching foo
# * z -l foo # list all dirs matching foo (by frecency)
if [ -e "${BASH_IT}/plugins/enabled/fasd.plugin.bash" ] || [ -e "${BASH_IT}/plugins/enabled/*${BASH_IT_LOAD_PRIORITY_SEPARATOR}fasd.plugin.bash" ]; then
printf '%s\n' 'sorry, the z plugin is incompatible with the fasd plugin. you may use either, but not both.'
return
fi
z() {
local datafile="$HOME/.z"
if [ "$1" = "--add" ]; then
# add
shift
# $HOME isn't worth matching
[ "$*" = "$HOME" ] && return
awk -v p="$*" -v t="$(date +%s)" -F"|" '
BEGIN { rank[p] = 1; time[p] = t }
$2 >= 1 {
if( $1 == p ) {
rank[$1] = $2 + 1
time[$1] = t
} else {
rank[$1] = $2
time[$1] = $3
}
count += $2
}
END {
if( count > 1000 ) {
for( i in rank ) print i "|" 0.9*rank[i] "|" time[i] # aging
} else for( i in rank ) print i "|" rank[i] "|" time[i]
}
' "$datafile" 2>/dev/null > "$datafile.tmp"
mv -f "$datafile.tmp" "$datafile"
elif [ "$1" = "--complete" ]; then
# tab completion
awk -v q="$2" -F"|" '
BEGIN {
if( q == tolower(q) ) nocase = 1
split(substr(q,3),fnd," ")
}
{
if( system("test -d \"" $1 "\"") ) next
if( nocase ) {
for( i in fnd ) tolower($1) !~ tolower(fnd[i]) && $1 = ""
if( $1 ) print $1
} else {
for( i in fnd ) $1 !~ fnd[i] && $1 = ""
if( $1 ) print $1
}
}
' "$datafile" 2>/dev/null
else
# list/go
while [ "$1" ]; do case "$1" in
-h) echo "z [-h][-l][-r][-t] args" >&2; return;;
-l) local list=1;;
-r) local typ="rank";;
-t) local typ="recent";;
--) while [ "$1" ]; do shift; local fnd="$fnd $1";done;;
*) local fnd="$fnd $1";;
esac; local last=$1; shift; done
[ "$fnd" ] || local list=1
# if we hit enter on a completion just go there
[ -d "$last" ] && cd "$last" && return
[ -f "$datafile" ] || return
local cd="$(awk -v t="$(date +%s)" -v list="$list" -v typ="$typ" -v q="$fnd" -v tmpfl="$datafile.tmp" -F"|" '
function frecent(rank, time) {
dx = t-time
if( dx < 3600 ) return rank*4
if( dx < 86400 ) return rank*2
if( dx < 604800 ) return rank/2
return rank/4
}
function output(files, toopen, override) {
if( list ) {
if( typ == "recent" ) {
cmd = "sort -nr >&2"
} else cmd = "sort -n >&2"
for( i in files ) if( files[i] ) printf "%-10s %s\n", files[i], i | cmd
if( override ) printf "%-10s %s\n", "common:", override > "/dev/stderr"
} else {
if( override ) toopen = override
print toopen
}
}
function common(matches, fnd, nc) {
for( i in matches ) {
if( matches[i] && (!short || length(i) < length(short)) ) short = i
}
if( short == "/" ) return
for( i in matches ) if( matches[i] && i !~ short ) x = 1
if( x ) return
if( nc ) {
for( i in fnd ) if( tolower(short) !~ tolower(fnd[i]) ) x = 1
} else for( i in fnd ) if( short !~ fnd[i] ) x = 1
if( !x ) return short
}
BEGIN { split(q, a, " ") }
{
if( system("test -d \"" $1 "\"") ) next
print $0 >> tmpfl
if( typ == "rank" ) {
f = $2
} else if( typ == "recent" ) {
f = t-$3
} else f = frecent($2, $3)
wcase[$1] = nocase[$1] = f
for( i in a ) {
if( $1 !~ a[i] ) delete wcase[$1]
if( tolower($1) !~ tolower(a[i]) ) delete nocase[$1]
}
if( wcase[$1] > oldf ) {
cx = $1
oldf = wcase[$1]
} else if( nocase[$1] > noldf ) {
ncx = $1
noldf = nocase[$1]
}
}
END {
if( cx ) {
output(wcase, cx, common(wcase, a, 0))
} else if( ncx ) output(nocase, ncx, common(nocase, a, 1))
}
' "$datafile")"
if [ $? -gt 0 ]; then
rm -f "$datafile.tmp"
else
mv -f "$datafile.tmp" "$datafile"
[ "$cd" ] && cd "$cd"
fi
fi
}
# tab completion
complete -C 'z --complete "$COMP_LINE"' z
# populate directory list. avoid clobbering other PROMPT_COMMANDs.
echo $PROMPT_COMMAND | grep -q "z --add"
[ $? -gt 0 ] && PROMPT_COMMAND='z --add "$(pwd -P)";'"$PROMPT_COMMAND"

View File

@ -1,15 +1,26 @@
#!/bin/bash #!/bin/bash
BASH_IT_LOG_PREFIX="core: reloader: "
pushd "${BASH_IT}" >/dev/null || exit 1 pushd "${BASH_IT}" >/dev/null || exit 1
# TODO: Add debugging output function _set-prefix-based-on-path()
{
filename=$(_bash-it-get-component-name-from-path "$1")
extension=$(_bash-it-get-component-type-from-path "$1")
BASH_IT_LOG_PREFIX="$extension: $filename: "
}
if [ "$1" != "skip" ] && [ -d "./enabled" ]; then if [ "$1" != "skip" ] && [ -d "./enabled" ]; then
_bash_it_config_type="" _bash_it_config_type=""
if [[ "${1}" =~ ^(alias|completion|plugin)$ ]]; then if [[ "${1}" =~ ^(alias|completion|plugin)$ ]]; then
_bash_it_config_type=$1 _bash_it_config_type=$1
_log_debug "Loading enabled $1 components..."
else
_log_debug "Loading all enabled components..."
fi fi
for _bash_it_config_file in $(sort <(compgen -G "./enabled/*${_bash_it_config_type}.bash")); do for _bash_it_config_file in $(sort <(compgen -G "./enabled/*${_bash_it_config_type}.bash")); do
if [ -e "${_bash_it_config_file}" ]; then if [ -e "${_bash_it_config_file}" ]; then
_set-prefix-based-on-path "${_bash_it_config_file}"
_log_debug "Loading component..."
# shellcheck source=/dev/null # shellcheck source=/dev/null
source $_bash_it_config_file source $_bash_it_config_file
else else
@ -20,9 +31,11 @@ fi
if [ ! -z "${2}" ] && [[ "${2}" =~ ^(aliases|completion|plugins)$ ]] && [ -d "${2}/enabled" ]; then if [ ! -z "${2}" ] && [[ "${2}" =~ ^(aliases|completion|plugins)$ ]] && [ -d "${2}/enabled" ]; then
# TODO: We should warn users they're using legacy enabling _log_warning "Using legacy enabling for $2, please update your bash-it version and migrate"
for _bash_it_config_file in $(sort <(compgen -G "./${2}/enabled/*.bash")); do for _bash_it_config_file in $(sort <(compgen -G "./${2}/enabled/*.bash")); do
if [ -e "$_bash_it_config_file" ]; then if [ -e "$_bash_it_config_file" ]; then
_set-prefix-based-on-path "${_bash_it_config_file}"
_log_debug "Loading component..."
# shellcheck source=/dev/null # shellcheck source=/dev/null
source "$_bash_it_config_file" source "$_bash_it_config_file"
else else

View File

@ -18,6 +18,10 @@ export BASH_IT_THEME='bobby'
# cloned bash-it with a remote other than origin such as `bash-it`. # cloned bash-it with a remote other than origin such as `bash-it`.
# export BASH_IT_REMOTE='bash-it' # export BASH_IT_REMOTE='bash-it'
# (Advanced): Change this to the name of the main development branch if
# you renamed it or if it was changed for some reason
# export BASH_IT_DEVELOPMENT_BRANCH='master'
# Your place for hosting Git repos. I use this for private repos. # Your place for hosting Git repos. I use this for private repos.
export GIT_HOSTING='git@git.domain.com' export GIT_HOSTING='git@git.domain.com'
@ -32,6 +36,10 @@ export TODO="t"
# Set this to false to turn off version control status checking within the prompt for all themes # Set this to false to turn off version control status checking within the prompt for all themes
export SCM_CHECK=true export SCM_CHECK=true
# Set to actual location of gitstatus directory if installed
#export SCM_GIT_GITSTATUS_DIR="$HOME/gitstatus"
# per default gitstatus uses 2 times as many threads as CPU cores, you can change this here if you must
#export GITSTATUS_NUM_THREADS=8
# Set Xterm/screen/Tmux title with only a short hostname. # Set Xterm/screen/Tmux title with only a short hostname.
# Uncomment this (or set SHORT_HOSTNAME to something else), # Uncomment this (or set SHORT_HOSTNAME to something else),

View File

@ -1,4 +1,13 @@
## Testing with [Bats](https://github.com/sstephenson/bats#installing-bats-from-source) # Testing with Bats
## Overview
The Bash-it unit tests leverage the [Bats unit test framework for Bash](https://github.com/bats-core/bats-core).
There is no need to install Bats explicitly, the test run script will automatically download and install Bats and its dependencies.
When making changes to Bash-it, the tests are automatically executed in a test build environment on [Travis CI](https://travis-ci.com).
## Test Execution
To execute the unit tests, please run the `run` script: To execute the unit tests, please run the `run` script:
@ -10,4 +19,22 @@ To execute the unit tests, please run the `run` script:
test/run test/run
``` ```
The `run` script will automatically install [Bats](https://github.com/sstephenson/bats#installing-bats-from-source) if it is not already present, and will then run all tests found under the `test` directory, including subdirectories. The `run` script will automatically install if it is not already present, and will then run all tests found under the `test` directory, including subdirectories.
To run only a subset of the tests, you can provide the name of the test subdirectory that you want to run, e.g. like this for the tests in the `test/themes` directory:
```bash
# If you are in the root `.bash_it` directory:
test/run test/themes
```
By default, the tests run in single-threaded mode.
If you want to speed up the test execution, you can install the [GNU `parallel` tool](https://www.gnu.org/software/parallel/), which is supported by Bats.
When using `parallel`, the `test/run` script will use a number of threads in parallel, depending on the available CPU cores of your system.
This can speed up test execution significantly.
## Writing Tests
When adding or modifying tests, please stick to the format and conventions of the existing test cases.
The `test_helper.bash` script provides a couple of reusable helper functions that you should use when writing a test case,
for example for setting up an isolated test environment.

View File

@ -4,36 +4,17 @@ load ../test_helper
load ../../lib/composure load ../../lib/composure
function local_setup { function local_setup {
mkdir -p "$BASH_IT" setup_test_fixture
lib_directory="$(cd "$(dirname "$0")" && pwd)"
echo "Bi : $BASH_IT"
echo "Lib: $lib_directory"
# Use rsync to copy Bash-it to the temp folder
# rsync is faster than cp, since we can exclude the large ".git" folder
rsync -qavrKL -d --delete-excluded --exclude=.git $lib_directory/../../.. "$BASH_IT"
rm -rf "$BASH_IT"/enabled
rm -rf "$BASH_IT"/aliases/enabled
rm -rf "$BASH_IT"/completion/enabled
rm -rf "$BASH_IT"/plugins/enabled
# Copy the test fixture to the Bash-it folder # Copy the test fixture to the Bash-it folder
rsync -a "$BASH_IT/test/fixtures/bash_it/" "$BASH_IT/" if command -v rsync &> /dev/null
then
# Don't pollute the user's actual $HOME directory rsync -a "$BASH_IT/test/fixtures/bash_it/" "$BASH_IT/"
# Use a test home directory instead else
export BASH_IT_TEST_CURRENT_HOME="${HOME}" find "$BASH_IT/test/fixtures/bash_it" \
export BASH_IT_TEST_HOME="$(cd "${BASH_IT}/.." && pwd)/BASH_IT_TEST_HOME" -mindepth 1 -maxdepth 1 \
mkdir -p "${BASH_IT_TEST_HOME}" -exec cp -r {} "$BASH_IT/" \;
export HOME="${BASH_IT_TEST_HOME}" fi
}
function local_teardown {
export HOME="${BASH_IT_TEST_CURRENT_HOME}"
rm -rf "${BASH_IT_TEST_HOME}"
assert_equal "${BASH_IT_TEST_CURRENT_HOME}" "${HOME}"
} }
@test "bash-it: verify that the test fixture is available" { @test "bash-it: verify that the test fixture is available" {

View File

@ -5,36 +5,7 @@ load ../../lib/composure
load ../../completion/available/bash-it.completion load ../../completion/available/bash-it.completion
function local_setup { function local_setup {
mkdir -p "$BASH_IT" setup_test_fixture
lib_directory="$(cd "$(dirname "$0")" && pwd)"
# Use rsync to copy Bash-it to the temp folder
# rsync is faster than cp, since we can exclude the large ".git" folder
rsync -qavrKL -d --delete-excluded --exclude=.git $lib_directory/../../.. "$BASH_IT"
rm -rf "$BASH_IT"/enabled
rm -rf "$BASH_IT"/aliases/enabled
rm -rf "$BASH_IT"/completion/enabled
rm -rf "$BASH_IT"/plugins/enabled
mkdir -p "$BASH_IT"/enabled
mkdir -p "$BASH_IT"/aliases/enabled
mkdir -p "$BASH_IT"/completion/enabled
mkdir -p "$BASH_IT"/plugins/enabled
# Don't pollute the user's actual $HOME directory
# Use a test home directory instead
export BASH_IT_TEST_CURRENT_HOME="${HOME}"
export BASH_IT_TEST_HOME="$(cd "${BASH_IT}/.." && pwd)/BASH_IT_TEST_HOME"
mkdir -p "${BASH_IT_TEST_HOME}"
export HOME="${BASH_IT_TEST_HOME}"
}
function local_teardown {
export HOME="${BASH_IT_TEST_CURRENT_HOME}"
rm -rf "${BASH_IT_TEST_HOME}"
assert_equal "${BASH_IT_TEST_CURRENT_HOME}" "${HOME}"
} }
@test "completion bash-it: ensure that the _bash-it-comp function is available" { @test "completion bash-it: ensure that the _bash-it-comp function is available" {
@ -72,6 +43,11 @@ function __check_completion () {
echo "${COMPREPLY[@]}" echo "${COMPREPLY[@]}"
} }
@test "completion bash-it: doctor - show options" {
run __check_completion 'bash-it doctor '
assert_line -n 0 "errors warnings all"
}
@test "completion bash-it: help - show options" { @test "completion bash-it: help - show options" {
run __check_completion 'bash-it help ' run __check_completion 'bash-it help '
assert_line -n 0 "aliases completions migrate plugins update" assert_line -n 0 "aliases completions migrate plugins update"
@ -82,9 +58,14 @@ function __check_completion () {
assert_line -n 0 "vagrant vault vim" assert_line -n 0 "vagrant vault vim"
} }
@test "completion bash-it: update - show no options" { @test "completion bash-it: update - show options" {
run __check_completion 'bash-it update ' run __check_completion 'bash-it update '
assert_line -n 0 "" assert_line -n 0 "stable dev"
}
@test "completion bash-it: update - show optional flags" {
run __check_completion 'bash-it update -'
assert_line -n 0 "-s --silent"
} }
@test "completion bash-it: search - show no options" { @test "completion bash-it: search - show no options" {
@ -99,32 +80,32 @@ function __check_completion () {
@test "completion bash-it: show options" { @test "completion bash-it: show options" {
run __check_completion 'bash-it ' run __check_completion 'bash-it '
assert_line -n 0 "disable enable help migrate reload search show update version" assert_line -n 0 "disable enable help migrate reload restart doctor search show update version"
} }
@test "completion bash-it: bash-ti - show options" { @test "completion bash-it: bash-ti - show options" {
run __check_completion 'bash-ti ' run __check_completion 'bash-ti '
assert_line -n 0 "disable enable help migrate reload search show update version" assert_line -n 0 "disable enable help migrate reload restart doctor search show update version"
} }
@test "completion bash-it: shit - show options" { @test "completion bash-it: shit - show options" {
run __check_completion 'shit ' run __check_completion 'shit '
assert_line -n 0 "disable enable help migrate reload search show update version" assert_line -n 0 "disable enable help migrate reload restart doctor search show update version"
} }
@test "completion bash-it: bashit - show options" { @test "completion bash-it: bashit - show options" {
run __check_completion 'bashit ' run __check_completion 'bashit '
assert_line -n 0 "disable enable help migrate reload search show update version" assert_line -n 0 "disable enable help migrate reload restart doctor search show update version"
} }
@test "completion bash-it: batshit - show options" { @test "completion bash-it: batshit - show options" {
run __check_completion 'batshit ' run __check_completion 'batshit '
assert_line -n 0 "disable enable help migrate reload search show update version" assert_line -n 0 "disable enable help migrate reload restart doctor search show update version"
} }
@test "completion bash-it: bash_it - show options" { @test "completion bash-it: bash_it - show options" {
run __check_completion 'bash_it ' run __check_completion 'bash_it '
assert_line -n 0 "disable enable help migrate reload search show update version" assert_line -n 0 "disable enable help migrate reload restart doctor search show update version"
} }
@test "completion bash-it: show - show options" { @test "completion bash-it: show - show options" {

4
test/fixtures/svn/broken/svn vendored 100755
View File

@ -0,0 +1,4 @@
#!/usr/bin/env bash
# Simply return an error code to simulate a broken SVN installation
exit 72

10
test/fixtures/svn/working/svn vendored 100755
View File

@ -0,0 +1,10 @@
#!/usr/bin/env bash
# If the info command is called
# AND the parent folder contains the .svn folder
# THEN return the current path, similar to what `svn info` does
if [[ "$1" == "info" ]] && [[ -d "../.svn" ]]; then
echo "$PWD"
fi
exit 0

View File

@ -14,31 +14,7 @@ case $OSTYPE in
esac esac
function local_setup { function local_setup {
mkdir -p "$BASH_IT" setup_test_fixture
lib_directory="$(cd "$(dirname "$0")" && pwd)"
# Use rsync to copy Bash-it to the temp folder
# rsync is faster than cp, since we can exclude the large ".git" folder
rsync -qavrKL -d --delete-excluded --exclude=.git $lib_directory/../../.. "$BASH_IT"
rm -rf "$BASH_IT"/enabled
rm -rf "$BASH_IT"/aliases/enabled
rm -rf "$BASH_IT"/completion/enabled
rm -rf "$BASH_IT"/plugins/enabled
# Don't pollute the user's actual $HOME directory
# Use a test home directory instead
export BASH_IT_TEST_CURRENT_HOME="${HOME}"
export BASH_IT_TEST_HOME="$(cd "${BASH_IT}/.." && pwd)/BASH_IT_TEST_HOME"
mkdir -p "${BASH_IT_TEST_HOME}"
export HOME="${BASH_IT_TEST_HOME}"
}
function local_teardown {
export HOME="${BASH_IT_TEST_CURRENT_HOME}"
rm -rf "${BASH_IT_TEST_HOME}"
assert_equal "${BASH_IT_TEST_CURRENT_HOME}" "${HOME}"
} }
@test "install: verify that the install script exists" { @test "install: verify that the install script exists" {

View File

@ -14,31 +14,7 @@ case $OSTYPE in
esac esac
function local_setup { function local_setup {
mkdir -p "$BASH_IT" setup_test_fixture
lib_directory="$(cd "$(dirname "$0")" && pwd)"
# Use rsync to copy Bash-it to the temp folder
# rsync is faster than cp, since we can exclude the large ".git" folder
rsync -qavrKL -d --delete-excluded --exclude=.git $lib_directory/../../.. "$BASH_IT"
rm -rf "$BASH_IT"/enabled
rm -rf "$BASH_IT"/aliases/enabled
rm -rf "$BASH_IT"/completion/enabled
rm -rf "$BASH_IT"/plugins/enabled
# Don't pollute the user's actual $HOME directory
# Use a test home directory instead
export BASH_IT_TEST_CURRENT_HOME="${HOME}"
export BASH_IT_TEST_HOME="$(cd "${BASH_IT}/.." && pwd)/BASH_IT_TEST_HOME"
mkdir -p "${BASH_IT_TEST_HOME}"
export HOME="${BASH_IT_TEST_HOME}"
}
function local_teardown {
export HOME="${BASH_IT_TEST_CURRENT_HOME}"
rm -rf "${BASH_IT_TEST_HOME}"
assert_equal "${BASH_IT_TEST_CURRENT_HOME}" "${HOME}"
} }
@test "uninstall: verify that the uninstall script exists" { @test "uninstall: verify that the uninstall script exists" {

View File

@ -2,6 +2,7 @@
load ../test_helper load ../test_helper
load ../../lib/composure load ../../lib/composure
load ../../lib/log
load ../../lib/utilities load ../../lib/utilities
load ../../lib/search load ../../lib/search
load ../../plugins/available/base.plugin load ../../plugins/available/base.plugin
@ -11,21 +12,7 @@ cite _about _param _example _group _author _version
load ../../lib/helpers load ../../lib/helpers
function local_setup { function local_setup {
mkdir -p "$BASH_IT" setup_test_fixture
lib_directory="$(cd "$(dirname "$0")" && pwd)"
# Use rsync to copy Bash-it to the temp folder
# rsync is faster than cp, since we can exclude the large ".git" folder
rsync -qavrKL -d --delete-excluded --exclude=.git $lib_directory/../../.. "$BASH_IT"
rm -rf "$BASH_IT"/enabled
rm -rf "$BASH_IT"/aliases/enabled
rm -rf "$BASH_IT"/completion/enabled
rm -rf "$BASH_IT"/plugins/enabled
mkdir -p "$BASH_IT"/enabled
mkdir -p "$BASH_IT"/aliases/enabled
mkdir -p "$BASH_IT"/completion/enabled
mkdir -p "$BASH_IT"/plugins/enabled
} }
# TODO Create global __is_enabled function # TODO Create global __is_enabled function
@ -33,7 +20,7 @@ function local_setup {
# TODO Create global __get_enabled_name function # TODO Create global __get_enabled_name function
@test "helpers: _command_exists function exists" { @test "helpers: _command_exists function exists" {
type -a _command_exists &> /dev/null run type -a _command_exists &> /dev/null
assert_success assert_success
} }
@ -141,8 +128,8 @@ function local_setup {
@test "helpers: enable the brew completion" { @test "helpers: enable the brew completion" {
run _enable-completion "brew" run _enable-completion "brew"
assert_line -n 0 'brew enabled with priority 350.' assert_line -n 0 'brew enabled with priority 375.'
assert_link_exist "$BASH_IT/enabled/350---brew.completion.bash" assert_link_exist "$BASH_IT/enabled/375---brew.completion.bash"
} }
@test "helpers: enable the node plugin" { @test "helpers: enable the node plugin" {

86
test/lib/log.bats 100644
View File

@ -0,0 +1,86 @@
#!/usr/bin/env bats
load ../test_helper
load ../../lib/composure
load ../../lib/appearance
load ../../plugins/available/base.plugin
cite _about _param _example _group _author _version
load ../../lib/log
@test "lib log: basic debug logging with BASH_IT_LOG_LEVEL_ALL" {
BASH_IT_LOG_LEVEL=$BASH_IT_LOG_LEVEL_ALL
run _log_debug "test test test"
assert_output "DEBUG: test test test"
}
@test "lib log: basic warning logging with BASH_IT_LOG_LEVEL_ALL" {
BASH_IT_LOG_LEVEL=$BASH_IT_LOG_LEVEL_ALL
run _log_warning "test test test"
assert_output " WARN: test test test"
}
@test "lib log: basic error logging with BASH_IT_LOG_LEVEL_ALL" {
BASH_IT_LOG_LEVEL=$BASH_IT_LOG_LEVEL_ALL
run _log_error "test test test"
assert_output "ERROR: test test test"
}
@test "lib log: basic debug logging with BASH_IT_LOG_LEVEL_WARNING" {
BASH_IT_LOG_LEVEL=$BASH_IT_LOG_LEVEL_WARNING
run _log_debug "test test test"
refute_output
}
@test "lib log: basic warning logging with BASH_IT_LOG_LEVEL_WARNING" {
BASH_IT_LOG_LEVEL=$BASH_IT_LOG_LEVEL_WARNING
run _log_warning "test test test"
assert_output " WARN: test test test"
}
@test "lib log: basic error logging with BASH_IT_LOG_LEVEL_WARNING" {
BASH_IT_LOG_LEVEL=$BASH_IT_LOG_LEVEL_WARNING
run _log_error "test test test"
assert_output "ERROR: test test test"
}
@test "lib log: basic debug logging with BASH_IT_LOG_LEVEL_ERROR" {
BASH_IT_LOG_LEVEL=$BASH_IT_LOG_LEVEL_ERROR
run _log_debug "test test test"
refute_output
}
@test "lib log: basic warning logging with BASH_IT_LOG_LEVEL_ERROR" {
BASH_IT_LOG_LEVEL=$BASH_IT_LOG_LEVEL_ERROR
run _log_warning "test test test"
refute_output
}
@test "lib log: basic error logging with BASH_IT_LOG_LEVEL_ERROR" {
BASH_IT_LOG_LEVEL=$BASH_IT_LOG_LEVEL_ERROR
run _log_error "test test test"
assert_output "ERROR: test test test"
}
@test "lib log: basic debug silent logging" {
run _log_debug "test test test"
refute_output
}
@test "lib log: basic warning silent logging" {
run _log_warning "test test test"
refute_output
}
@test "lib log: basic error silent logging" {
run _log_error "test test test"
refute_output
}
@test "lib log: logging with prefix" {
BASH_IT_LOG_LEVEL=$BASH_IT_LOG_LEVEL_ALL
BASH_IT_LOG_PREFIX="nice: prefix: "
run _log_debug "test test test"
assert_output "DEBUG: nice: prefix: test test test"
}

View File

@ -2,9 +2,13 @@
load ../test_helper load ../test_helper
load ../../lib/composure load ../../lib/composure
load ../../lib/log
load ../../lib/helpers load ../../lib/helpers
load ../../lib/utilities load ../../lib/utilities
load ../../lib/search load ../../lib/search
cite _about _param _example _group _author _version
load ../../plugins/available/base.plugin load ../../plugins/available/base.plugin
load ../../aliases/available/git.aliases load ../../aliases/available/git.aliases
load ../../plugins/available/ruby.plugin load ../../plugins/available/ruby.plugin
@ -13,27 +17,10 @@ load ../../completion/available/bundler.completion
load ../../completion/available/gem.completion load ../../completion/available/gem.completion
load ../../completion/available/rake.completion load ../../completion/available/rake.completion
cite _about _param _example _group _author _version
load ../../lib/helpers load ../../lib/helpers
function local_setup { function local_setup {
mkdir -p "$BASH_IT" setup_test_fixture
lib_directory="$(cd "$(dirname "$0")" && pwd)"
# Use rsync to copy Bash-it to the temp folder
# rsync is faster than cp, since we can exclude the large ".git" folder
rsync -qavrKL -d --delete-excluded --exclude=.git $lib_directory/../../.. "$BASH_IT"
rm -rf "$BASH_IT"/enabled
rm -rf "$BASH_IT"/aliases/enabled
rm -rf "$BASH_IT"/completion/enabled
rm -rf "$BASH_IT"/plugins/enabled
rm -rf "$BASH_IT"/tmp/cache
mkdir -p "$BASH_IT"/enabled
mkdir -p "$BASH_IT"/aliases/enabled
mkdir -p "$BASH_IT"/completion/enabled
mkdir -p "$BASH_IT"/plugins/enabled
export OLD_PATH="$PATH" export OLD_PATH="$PATH"
export PATH="/usr/bin:/bin:/usr/sbin" export PATH="/usr/bin:/bin:/usr/sbin"
@ -53,8 +40,13 @@ function local_teardown {
@test "search: git" { @test "search: git" {
run _bash-it-search 'git' --no-color run _bash-it-search 'git' --no-color
assert_line -n 0 ' aliases: git gitsvn ' assert_line -n 0 ' aliases: git gitsvn '
assert_line -n 1 ' plugins: autojump fasd git git-subrepo jgitflow jump ' assert_line -n 1 -p ' plugins:'
assert_line -n 2 ' completions: git git_flow git_flow_avh ' for plugin in "autojump" "git" "gitstatus" "git-subrepo" "jgitflow" "jump"
do
echo $plugin
assert_line -n 1 -p $plugin
done
assert_line -n 2 ' completions: git git_flow git_flow_avh github-cli '
} }
@test "search: ruby gem bundle rake rails" { @test "search: ruby gem bundle rake rails" {

View File

@ -9,22 +9,7 @@ load ../../lib/search
cite _about _param _example _group _author _version cite _about _param _example _group _author _version
function local_setup { function local_setup {
mkdir -p "$BASH_IT" setup_test_fixture
lib_directory="$(cd "$(dirname "$0")" && pwd)"
# Use rsync to copy Bash-it to the temp folder
# rsync is faster than cp, since we can exclude the large ".git" folder
rsync -qavrKL -d --delete-excluded --exclude=.git $lib_directory/../../.. "$BASH_IT"
rm -rf "$BASH_IT"/enabled
rm -rf "$BASH_IT"/aliases/enabled
rm -rf "$BASH_IT"/completion/enabled
rm -rf "$BASH_IT"/plugins/enabled
rm -rf "$BASH_IT"/tmp/cache
mkdir -p "$BASH_IT"/enabled
mkdir -p "$BASH_IT"/aliases/enabled
mkdir -p "$BASH_IT"/completion/enabled
mkdir -p "$BASH_IT"/plugins/enabled
} }
function has_match() { function has_match() {

View File

@ -0,0 +1,24 @@
#!/usr/bin/env bats
load ../test_helper
load ../../lib/composure
load ../../lib/log
load ../../lib/helpers
cite _about _param _example _group _author _version
load ../../completion/available/git.completion
@test "alias-completion: See that aliases with double quotes and brackets do not break the plugin" {
alias gtest="git log --graph --pretty=format:'%C(bold)%h%Creset%C(magenta)%d%Creset %s %C(yellow)<%an> %C(cyan)(%cr)%Creset' --abbrev-commit --date=relative"
load ../../plugins/available/alias-completion.plugin
assert_success
}
@test "alias-completion: See that aliases with single quotes and brackets do not break the plugin" {
alias gtest='git log --graph --pretty=format:"%C(bold)%h%Creset%C(magenta)%d%Creset %s %C(yellow)<%an> %C(cyan)(%cr)%Creset" --abbrev-commit --date=relative'
load ../../plugins/available/alias-completion.plugin
assert_success
}

View File

@ -16,10 +16,6 @@ load ../../plugins/available/base.plugin
} }
@test 'plugins base: myip()' { @test 'plugins base: myip()' {
if [[ ! $SLOW_TESTS ]]; then
skip 'myip is slow - run only with SLOW_TESTS=true'
fi
run myip run myip
assert_success assert_success
declare -r mask_ip=$(echo $output | tr -s '[0-9]' '?') declare -r mask_ip=$(echo $output | tr -s '[0-9]' '?')
@ -43,7 +39,7 @@ load ../../plugins/available/base.plugin
mkcd "${dir_name}" mkcd "${dir_name}"
assert_success assert_success
assert_file_exist "${BASH_IT_ROOT}/${dir_name}" assert_dir_exist "${BASH_IT_ROOT}/${dir_name}"
assert_equal $(pwd) "${BASH_IT_ROOT}/${dir_name}" assert_equal $(pwd) "${BASH_IT_ROOT}/${dir_name}"
} }

View File

@ -1,44 +1,60 @@
#!/usr/bin/env bats #!/usr/bin/env bats
#load ../test_helper load ../test_helper
load ../../lib/helpers load ../../lib/helpers
load ../../lib/composure load ../../lib/composure
load ../../plugins/available/go.plugin
@test 'plugins go: reverse path: single entry' { @test 'ensure _go_pathmunge_wrap is defined' {
run _split_path_reverse '/foo' { [[ $CI ]] || _command_exists go; } || skip 'golang not found'
echo "output = ${output}" load ../../plugins/available/go.plugin
[ "$output" = "/foo" ] run type -t _go_pathmunge_wrap
} assert_line 'function'
@test 'plugins go: reverse path: single entry, colon empty' {
run _split_path_reverse '/foo:'
echo "output = ${output}"
[ "$output" = "/foo" ]
}
@test 'plugins go: reverse path: single entry, colon whitespace' {
run _split_path_reverse '/foo: '
echo "output = ${output}"
[ "$output" = "/foo" ]
}
@test 'plugins go: reverse path: multiple entries' {
run _split_path_reverse '/foo:/bar'
echo "output = ${output}"
[ "$output" = "/bar /foo" ]
} }
@test 'plugins go: single entry in GOPATH' { @test 'plugins go: single entry in GOPATH' {
{ [[ $CI ]] || _command_exists go; } || skip 'golang not found'
export GOPATH="/foo" export GOPATH="/foo"
export GOROOT="/baz"
load ../../plugins/available/go.plugin load ../../plugins/available/go.plugin
echo "$(echo $PATH | cut -d':' -f1,2)" assert_equal "$(cut -d':' -f1,2 <<<$PATH)" "/foo/bin:/baz/bin"
[ "$(echo $PATH | cut -d':' -f1)" = "/foo/bin" ] }
@test 'plugins go: single entry in GOPATH, with space' {
{ [[ $CI ]] || _command_exists go; } || skip 'golang not found'
export GOPATH="/foo bar"
export GOROOT="/baz"
load ../../plugins/available/go.plugin
assert_equal "$(cut -d':' -f1,2 <<<$PATH)" "/foo bar/bin:/baz/bin"
}
@test 'plugins go: single entry in GOPATH, with escaped space' {
{ [[ $CI ]] || _command_exists go; } || skip 'golang not found'
export GOPATH="/foo\ bar"
export GOROOT="/baz"
load ../../plugins/available/go.plugin
assert_equal "$(cut -d':' -f1,2 <<<$PATH)" "/foo\ bar/bin:/baz/bin"
} }
@test 'plugins go: multiple entries in GOPATH' { @test 'plugins go: multiple entries in GOPATH' {
{ [[ $CI ]] || _command_exists go; } || skip 'golang not found'
export GOPATH="/foo:/bar" export GOPATH="/foo:/bar"
export GOROOT="/baz"
load ../../plugins/available/go.plugin load ../../plugins/available/go.plugin
echo "$(echo $PATH | cut -d':' -f1,2)" assert_equal "$(cut -d':' -f1,2,3 <<<$PATH)" "/foo/bin:/bar/bin:/baz/bin"
[ "$(echo $PATH | cut -d':' -f1,2)" = "/foo/bin:/bar/bin" ] }
@test 'plugins go: multiple entries in GOPATH, with space' {
{ [[ $CI ]] || _command_exists go; } || skip 'golang not found'
export GOPATH="/foo:/foo bar"
export GOROOT="/baz"
load ../../plugins/available/go.plugin
assert_equal "$(cut -d':' -f1,2,3 <<<$PATH)" "/foo/bin:/foo bar/bin:/baz/bin"
}
@test 'plugins go: multiple entries in GOPATH, with escaped space' {
{ [[ $CI ]] || _command_exists go; } || skip 'golang not found'
export GOPATH="/foo:/foo\ bar"
export GOROOT="/baz"
load ../../plugins/available/go.plugin
assert_equal "$(cut -d':' -f1,2,3 <<<$PATH)" "/foo/bin:/foo\ bar/bin:/baz/bin"
} }

View File

@ -6,21 +6,7 @@ load ../../lib/composure
load ../../plugins/available/ruby.plugin load ../../plugins/available/ruby.plugin
function local_setup { function local_setup {
mkdir -p "$BASH_IT" setup_test_fixture
lib_directory="$(cd "$(dirname "$0")" && pwd)"
# Use rsync to copy Bash-it to the temp folder
# rsync is faster than cp, since we can exclude the large ".git" folder
rsync -qavrKL -d --delete-excluded --exclude=.git $lib_directory/../../.. "$BASH_IT"
rm -rf "$BASH_IT"/enabled
rm -rf "$BASH_IT"/aliases/enabled
rm -rf "$BASH_IT"/completion/enabled
rm -rf "$BASH_IT"/plugins/enabled
mkdir -p "$BASH_IT"/enabled
mkdir -p "$BASH_IT"/aliases/enabled
mkdir -p "$BASH_IT"/completion/enabled
mkdir -p "$BASH_IT"/plugins/enabled
export OLD_PATH="$PATH" export OLD_PATH="$PATH"
export PATH="/usr/bin:/bin:/usr/sbin" export PATH="/usr/bin:/bin:/usr/sbin"

View File

@ -16,4 +16,33 @@ else
test_dirs=( "$1" ) test_dirs=( "$1" )
fi fi
exec $bats_executable ${CI:+--tap} "${test_dirs[@]}" # Make sure that the `parallel` command is installed,
# AND that it is the GNU version of `parallel`.
# If that is the case, try to guess the number of CPU cores,
# so we can run `bats` in parallel processing mode, which is a lot faster.
if command -v parallel &> /dev/null \
&& parallel -V &> /dev/null \
&& { parallel -V 2> /dev/null | grep -q '^GNU\>'; }
then
# Expect to run at least on a dual-core CPU; slightly degraded performance
# shouldn't matter otherwise.
declare -i -r test_jobs_default=2
declare -i -r test_jobs_effective="$(
if [ "${TEST_JOBS:-detect}" = "detect" ] \
&& command -v nproc &> /dev/null
then
nproc
elif [ -n "${TEST_JOBS}" ] \
&& [ "${TEST_JOBS}" != "detect" ]
then
echo "${TEST_JOBS}"
else
echo ${test_jobs_default}
fi
)"
exec "$bats_executable" ${CI:+--tap} --jobs ${test_jobs_effective} \
"${test_dirs[@]}"
else
# Run `bats` in single-threaded mode.
exec "$bats_executable" ${CI:+--tap} "${test_dirs[@]}"
fi

View File

@ -6,17 +6,12 @@ unset TODO
unset SCM_CHECK unset SCM_CHECK
unset BASH_IT_AUTOMATIC_RELOAD_AFTER_CONFIG_CHANGE unset BASH_IT_AUTOMATIC_RELOAD_AFTER_CONFIG_CHANGE
BASH_IT_TEST_DIR="${BATS_TMPDIR}/.bash_it"
# guard against executing this block twice due to bats internals
if [ "$BASH_IT_ROOT" != "${BASH_IT_TEST_DIR}/root" ]; then
export BASH_IT_ROOT="${BASH_IT_TEST_DIR}/root"
export BASH_IT=$BASH_IT_TEST_DIR
fi
export TEST_MAIN_DIR="${BATS_TEST_DIRNAME}/.." export TEST_MAIN_DIR="${BATS_TEST_DIRNAME}/.."
export TEST_DEPS_DIR="${TEST_DEPS_DIR-${TEST_MAIN_DIR}/../test_lib}" export TEST_DEPS_DIR="${TEST_DEPS_DIR-${TEST_MAIN_DIR}/../test_lib}"
# be independent of git's system configuration
export GIT_CONFIG_NOSYSTEM
load "${TEST_DEPS_DIR}/bats-support/load.bash" load "${TEST_DEPS_DIR}/bats-support/load.bash"
load "${TEST_DEPS_DIR}/bats-assert/load.bash" load "${TEST_DEPS_DIR}/bats-assert/load.bash"
load "${TEST_DEPS_DIR}/bats-file/load.bash" load "${TEST_DEPS_DIR}/bats-file/load.bash"
@ -29,9 +24,70 @@ local_teardown() {
true true
} }
# This function sets up a local test fixture, i.e. a completely
# fresh and isolated Bash-it directory. This is done to avoid
# messing with your own Bash-it source directory.
# If you need this, call it in your .bats file's `local_setup` function.
setup_test_fixture() {
mkdir -p "$BASH_IT"
lib_directory="$(cd "$(dirname "$0")" && pwd)"
local src_topdir="$lib_directory/../../../.."
if command -v rsync &> /dev/null
then
# Use rsync to copy Bash-it to the temp folder
rsync -qavrKL -d --delete-excluded --exclude=.git --exclude=enabled "$src_topdir" "$BASH_IT"
else
rm -rf "$BASH_IT"
mkdir -p "$BASH_IT"
find "$src_topdir" \
-mindepth 1 -maxdepth 1 \
-not -name .git \
-exec cp -r {} "$BASH_IT" \;
fi
rm -rf "$BASH_IT"/enabled
rm -rf "$BASH_IT"/aliases/enabled
rm -rf "$BASH_IT"/completion/enabled
rm -rf "$BASH_IT"/plugins/enabled
mkdir -p "$BASH_IT"/enabled
mkdir -p "$BASH_IT"/aliases/enabled
mkdir -p "$BASH_IT"/completion/enabled
mkdir -p "$BASH_IT"/plugins/enabled
# Some tests use the BASH_IT_TEST_HOME variable, e.g. install/uninstall
export BASH_IT_TEST_HOME="$TEST_TEMP_DIR"
}
setup() { setup() {
# The `temp_make` function from "bats-file" requires the tralston/bats-file fork,
# since the original ztombol/bats-file's `temp_make` does not work on macOS.
TEST_TEMP_DIR="$(temp_make --prefix 'bash-it-test-')"
export TEST_TEMP_DIR
export BASH_IT_TEST_DIR="${TEST_TEMP_DIR}/.bash_it"
export BASH_IT_ROOT="${BASH_IT_TEST_DIR}/root"
export BASH_IT=$BASH_IT_TEST_DIR
mkdir -p -- "${BASH_IT_ROOT}" mkdir -p -- "${BASH_IT_ROOT}"
# Some tools, e.g. `git` use configuration files from the $HOME directory,
# which interferes with our tests. The only way to keep `git` from doing this
# seems to set HOME explicitly to a separate location.
# Refer to https://git-scm.com/docs/git-config#FILES.
unset XDG_CONFIG_HOME
export HOME="${TEST_TEMP_DIR}"
mkdir -p "${HOME}"
# For `git` tests to run well, user name and email need to be set.
# Refer to https://git-scm.com/docs/git-commit#_commit_information.
# This goes to the test-specific config, due to the $HOME overridden above.
git config --global user.name "John Doe"
git config --global user.email "johndoe@example.com"
local_setup local_setup
} }
@ -39,49 +95,5 @@ teardown() {
local_teardown local_teardown
rm -rf "${BASH_IT_TEST_DIR}" rm -rf "${BASH_IT_TEST_DIR}"
} temp_del "${TEST_TEMP_DIR}"
# Fail and display path of the link if it does not exist. Also fails
# if the path exists, but is not a link.
# This function is the logical complement of `assert_file_not_exist'.
# There is no dedicated function for checking that a link does not exist.
#
# Globals:
# BATSLIB_FILE_PATH_REM
# BATSLIB_FILE_PATH_ADD
# Arguments:
# $1 - path
# Returns:
# 0 - link exists and is a link
# 1 - otherwise
# Outputs:
# STDERR - details, on failure
assert_link_exist() {
local -r file="$1"
local -r target="$2"
if [[ ! -L "$file" ]]; then
local -r rem="$BATSLIB_FILE_PATH_REM"
local -r add="$BATSLIB_FILE_PATH_ADD"
if [[ -e "$file" ]]; then
batslib_print_kv_single 4 'path' "${file/$rem/$add}" \
| batslib_decorate 'exists, but is not a link' \
| fail
else
batslib_print_kv_single 4 'path' "${file/$rem/$add}" \
| batslib_decorate 'link does not exist' \
| fail
fi
else
if [ -n "$target" ]; then
local link_target=''
link_target=$(readlink "$file")
if [[ "$link_target" != "$target" ]]; then
batslib_print_kv_single_or_multi 8 'path' "${file/$rem/$add}" \
'expected' "$target" \
'actual' "$link_target" \
| batslib_decorate 'link exists, but does not point to target file' \
| fail
fi
fi
fi
} }

View File

@ -2,6 +2,7 @@
load ../test_helper load ../test_helper
load ../../lib/composure load ../../lib/composure
load ../../lib/log
cite _about _param _example _group _author _version cite _about _param _example _group _author _version

View File

@ -2,6 +2,7 @@
load ../test_helper load ../test_helper
load ../../lib/composure load ../../lib/composure
load ../../lib/log
cite _about _param _example _group _author _version cite _about _param _example _group _author _version

View File

@ -0,0 +1,129 @@
#!/usr/bin/env bats
load ../test_helper
load ../../lib/composure
load ../../lib/log
cite _about _param _example _group _author _version
load ../../lib/helpers
load ../../themes/base.theme
function local_setup {
setup_test_fixture
# Copy the test fixture to the Bash-it folder
if command -v rsync &> /dev/null
then
rsync -a "$BASH_IT/test/fixtures/bash_it/" "$BASH_IT/"
else
find "$BASH_IT/test/fixtures/bash_it" \
-mindepth 1 -maxdepth 1 \
-exec cp -r {} "$BASH_IT/" \;
fi
export OLD_PATH="$PATH"
}
function local_teardown {
export PATH="$OLD_PATH"
unset OLD_PATH
}
function setup_repo {
upstream="$(mktemp -d)"
pushd "$upstream" > /dev/null
# Create a dummy SVN folder - this will not work with an actual `svn` command,
# but will be enough to trigger the SVN check in the base theme.
mkdir .svn
echo "$upstream"
}
function setup_svn_path {
local svn_path="$1"
# Make sure that the requested SVN script is available
assert_file_exist "$svn_path/svn"
# Make sure that the requested SVN script is on the path
export PATH="$svn_path:/usr/bin:/bin:/usr/sbin"
}
@test 'themes base: SVN: detect SVN repo' {
repo="$(setup_repo)"
pushd "$repo"
setup_svn_path "$BASH_IT/test/fixtures/svn/working"
# Load the base theme again so that the working SVN script is detected
load ../../themes/base.theme
scm
# Make sure that the SVN command is used
assert_equal "$SCM" "$SCM_SVN"
}
@test 'themes base: SVN: detect SVN repo even from a subfolder' {
repo="$(setup_repo)"
pushd "$repo"
mkdir foo
pushd foo
setup_svn_path "$BASH_IT/test/fixtures/svn/working"
# Load the base theme again so that the working SVN script is detected
load ../../themes/base.theme
scm
# Make sure that the SVN command is used
assert_equal "$SCM" "$SCM_SVN"
}
@test 'themes base: SVN: no SCM if no .svn folder can be found' {
repo="$(setup_repo)"
pushd "$repo"
rm -rf .svn
setup_svn_path "$BASH_IT/test/fixtures/svn/working"
# Load the base theme again so that the working SVN script is detected
load ../../themes/base.theme
scm
# Make sure that no SVN command is used
assert_equal "$SCM" "$SCM_NONE"
}
@test 'themes base: SVN: ignore SVN repo when using broken SVN command' {
repo="$(setup_repo)"
pushd "$repo"
setup_svn_path "$BASH_IT/test/fixtures/svn/broken"
# Load the base theme again so that the broken SVN script is detected
load ../../themes/base.theme
scm
# Make sure that no SVN command is not used
assert_equal "$SCM" "$SCM_NONE"
}
@test 'themes base: SVN: ignore SVN repo even from a subfolder when using a broken SVN' {
repo="$(setup_repo)"
pushd "$repo"
mkdir foo
pushd foo
setup_svn_path "$BASH_IT/test/fixtures/svn/broken"
# Load the base theme again so that the broken SVN script is detected
load ../../themes/base.theme
scm
# Make sure that no SVN command is used
assert_equal "$SCM" "$SCM_NONE"
}

@ -1 +1 @@
Subproject commit 9f88b4207da750093baabc4e3f41bf68f0dd3630 Subproject commit d750c5a1b44bf6fc96726aea76f4621db5fd602f

@ -1 +1 @@
Subproject commit 85388685632f85d5a1c32e6bca2deec401964cf7 Subproject commit 73b8d2f95513207b319efe34685553b75c0b214e

@ -1 +1 @@
Subproject commit 2fddb2b831d65cdf2e411f3b47f4677fbb15729c Subproject commit c128a1de53ba4a811835af410ce427f1049e2d7f

@ -1 +1 @@
Subproject commit 004e707638eedd62e0481e8cdc9223ad471f12ee Subproject commit 24a72e14349690bcbf7c151b9d2d1cdd32d36eb1

View File

@ -210,7 +210,8 @@ prompt_virtualenv() {
if [[ -n $VIRTUAL_ENV ]]; then if [[ -n $VIRTUAL_ENV ]]; then
color=cyan color=cyan
prompt_segment $color $PRIMARY_FG prompt_segment $color $PRIMARY_FG
prompt_segment $color white "$(basename $VIRTUAL_ENV)" ve=`basename "$VIRTUAL_ENV"`
prompt_segment $color white "$ve"
fi fi
} }

View File

@ -194,7 +194,7 @@ ___atomic_prompt_char() {
color=$white color=$white
prompt_char="${__ATOMIC_PROMPT_CHAR_PS1}" prompt_char="${__ATOMIC_PROMPT_CHAR_PS1}"
if [ "${THEME_SHOW_SUDO}" == "true" ]; then if [ "${THEME_SHOW_SUDO}" == "true" ]; then
if [ $(sudo -n id -u 2>&1 | grep 0) ]; then if sudo -vn 1>/dev/null 2>&1; then
prompt_char="${__ATOMIC_PROMPT_CHAR_PS1_SUDO}" prompt_char="${__ATOMIC_PROMPT_CHAR_PS1_SUDO}"
fi fi
fi fi

View File

@ -0,0 +1,99 @@
# BarbUk theme
A minimal theme with a clean git prompt
## Provided Information
* Current git remote tool logo (support: github, gitlab, bitbucket)
* Current path (red when user is root)
* Current git info
* Last command exit code (only shown when the exit code is greater than 0)
* user@hostname for ssh connection
## Fonts and glyphs
A font with SCM glyphs is required to display the default tool/host logos.
You can use a font from https://www.nerdfonts.com/ or patch your own font with the tool
provided by https://github.com/ryanoasis/nerd-fonts.
You can also override the default variables if you want to use different glyphs or standard ASCII characters.
### Default theme glyphs
```bash
BARBUK_GITLAB_CHAR=' '
BARBUK_BITBUCKET_CHAR=' '
BARBUK_GITHUB_CHAR=' '
BARBUK_GIT_DEFAULT_CHAR=' '
BARBUK_GIT_BRANCH_ICON=''
BARBUK_HG_CHAR='☿ '
BARBUK_SVN_CHAR='⑆ '
BARBUK_EXIT_CODE_ICON=' '
```
### Customize glyphs
Define your custom glyphs before sourcing bash-it:
```bash
export BARBUK_GITHUB_CHAR='•'
source "$BASH_IT"/bash_it.sh
```
## SSH prompt
### Usage
When using a ssh session, the theme will display `user@hostname`.
You can disable this information with `BARBUK_SSH_INFO`.
The hostname is displayed in the FQDN format by default. You
can use the short hostname format with `BARBUK_HOST_INFO`.
```bash
# short or long
export BARBUK_HOST_INFO=short
# true or false
export BARBUK_SSH_INFO=false
source "$BASH_IT"/bash_it.sh
```
### Keep theme with sudoer
If you want the theme to persist using `sudo -s` in a ssh session, you need to configure sudo to keep the `HOME` and `SSH_CONNECTION` environment variables.
`HOME` contains the path to the home directory of the current user. Keeping it will allow to use your user dotfiles when elevating privileges.
Keeping `SSH_CONNECTION` env is necessary for ssh detection in the theme.
Please refer to the following documentation for more information:
- [sudo manual](https://www.sudo.ws/man/1.8.13/sudoers.man.html) for `env_keep` configuration
- [openssh manual](https://linux.die.net/man/1/ssh) for information about `SSH_CONNECTION` environment
```bash
cat << EOF > /etc/sudoers.d/keepenv
Defaults env_keep += HOME
Defaults env_keep += SSH_CONNECTION
EOF
chmod 400 /etc/sudoers.d/keepenv
```
## Examples
### Clean
```bash
~
```
### Git
```bash
 ~/.dotfiles on  master ⤏ origin ↑2 •7 ✗
```
### Ssh
```bash
user@hostname in  ~/bash-it on  master ✓
```

View File

@ -0,0 +1,104 @@
#!/usr/bin/env bash
# shellcheck disable=2034,2154
# Theme custom glyphs
SCM_GIT_CHAR_GITLAB=${BARBUK_GITLAB_CHAR:=' '}
SCM_GIT_CHAR_BITBUCKET=${BARBUK_BITBUCKET_CHAR:=' '}
SCM_GIT_CHAR_GITHUB=${BARBUK_GITHUB_CHAR:=' '}
SCM_GIT_CHAR_DEFAULT=${BARBUK_GIT_DEFAULT_CHAR:=' '}
SCM_GIT_CHAR_ICON_BRANCH=${BARBUK_GIT_BRANCH_ICON:=''}
SCM_HG_CHAR=${BARBUK_HG_CHAR:='☿ '}
SCM_SVN_CHAR=${BARBUK_SVN_CHAR:='⑆ '}
EXIT_CODE_ICON=${BARBUK_EXIT_CODE_ICON:=' '}
# Ssh user and hostname display
SSH_INFO=${BARBUK_SSH_INFO:=true}
HOST_INFO=${BARBUK_HOST_INFO:=long}
# Bash-it default glyphs customization
SCM_NONE_CHAR=
SCM_THEME_PROMPT_DIRTY=" ${bold_red}"
SCM_THEME_PROMPT_CLEAN=" ${bold_green}"
SCM_THEME_PROMPT_PREFIX="|"
SCM_THEME_PROMPT_SUFFIX="${green}| "
SCM_GIT_BEHIND_CHAR="${bold_red}${normal}"
SCM_GIT_AHEAD_CHAR="${bold_green}${normal}"
SCM_GIT_UNTRACKED_CHAR="⌀"
SCM_GIT_UNSTAGED_CHAR="${bold_yellow}${normal}"
SCM_GIT_STAGED_CHAR="${bold_green}+${normal}"
GIT_THEME_PROMPT_DIRTY=" ${bold_red}"
GIT_THEME_PROMPT_CLEAN=" ${bold_green}"
GIT_THEME_PROMPT_PREFIX="${cyan}"
GIT_THEME_PROMPT_SUFFIX="${cyan}"
SCM_THEME_BRANCH_TRACK_PREFIX="${normal}${cyan}"
SCM_THEME_CURRENT_USER_PREFFIX='  '
SCM_GIT_SHOW_CURRENT_USER=false
function _git-uptream-remote-logo {
[[ "$(_git-upstream)" == "" ]] && SCM_GIT_CHAR="$SCM_GIT_CHAR_DEFAULT"
local remote remote_domain
remote=$(_git-upstream-remote)
remote_domain=$(git config --get remote."$remote".url | awk -F'[@:.]' '{print $2}')
# remove // suffix for https:// url
remote_domain=${remote_domain//\//}
case $remote_domain in
github ) SCM_GIT_CHAR="$SCM_GIT_CHAR_GITHUB";;
gitlab ) SCM_GIT_CHAR="$SCM_GIT_CHAR_GITLAB";;
bitbucket ) SCM_GIT_CHAR="$SCM_GIT_CHAR_BITBUCKET";;
* ) SCM_GIT_CHAR="$SCM_GIT_CHAR_DEFAULT";;
esac
}
function git_prompt_info {
git_prompt_vars
echo -e " on $SCM_GIT_CHAR_ICON_BRANCH $SCM_PREFIX$SCM_BRANCH$SCM_STATE$SCM_GIT_AHEAD$SCM_GIT_BEHIND$SCM_GIT_STASH$SCM_SUFFIX"
}
function _exit-code {
if [[ "$1" -ne 0 ]]; then
exit_code=" ${purple}${EXIT_CODE_ICON}${yellow}${exit_code}${bold_orange}"
else
exit_code="${bold_green}"
fi
}
function _prompt {
local exit_code="$?" wrap_char=' ' dir_color=$green ssh_info='' python_venv='' host
_exit-code exit_code
_git-uptream-remote-logo
history -a
# Detect root shell
if [ "$(whoami)" = root ]; then
dir_color=$red
fi
# Detect ssh
if [[ -n "${SSH_CONNECTION}" ]] && [ "$SSH_INFO" = true ]; then
if [ "$HOST_INFO" = long ]; then
host="\H"
else
host="\h"
fi
ssh_info="${bold_blue}\u${bold_orange}@${cyan}$host ${bold_orange}in"
fi
# Detect python venv
if [[ -n "${CONDA_DEFAULT_ENV}" ]]; then
python_venv="${CONDA_DEFAULT_ENV}"
elif [[ -n "${VIRTUAL_ENV}" ]]; then
python_venv=$(basename "${VIRTUAL_ENV}")
fi
PS1="\\n${ssh_info} ${python_venv} ${purple}$(scm_char)${dir_color}\\w${normal}$(scm_prompt_info)${exit_code}"
[[ ${#PS1} -gt $((COLUMNS*3)) ]] && wrap_char="\\n"
PS1="${PS1}${wrap_char}${normal} "
}
safe_append_prompt_command _prompt

Some files were not shown because too many files have changed in this diff Show More