enonic / cli-enonic

GNU General Public License v3.0
41 stars 1 forks source link

shim for cd like avn does #134

Closed ComLock closed 4 years ago

ComLock commented 5 years ago

I install and use multiple different versions of node via nvm.

In order to not have to think about it I use avn: https://github.com/wbyoung/avn

The cool thing is that when I cd into a project folder it will automatically change environment variables base on a .node-version file.

This is possible because the cd command is wrapped with a function in .bash_profile.

Normally

$ type cd
cd is a shell builtin

But after wrapping

$ type cd
cd is a function

It would be cool if we could have such a wrapper which reads the .enonic file and sets up the environment.

ComLock commented 5 years ago

https://direnv.net/

ComLock commented 5 years ago

The challenge here is that cd may be a builtin or a function. And if you wrap another function, you don't want to wrap yourself if the code for some reason is executed another time.

ComLock commented 5 years ago

This code doesn't protect against a second run, but it may contain useful info:

function_exists() {
    declare -f -F $1 > /dev/null
    return $?
}

copy_function() { # Only works when cd is a function
  test -n "$(declare -f "$1")" || return
  eval "${_/$1/$2}"
}

rename_function() {
  copy_function "$@" || return
  unset -f "$1"
}

if function_exists 'cd'; then
  rename_function cd __cd_before_enonic_wrapper;
else
  __cd_before_enonic_wrapper() { builtin cd "$@"; }
fi

function cd() {
  __cd_before_enonic_wrapper "$@";
  if [ -f './.enonic' -a -r './.enonic' ]; then
    echo -e "\033[90m$(/Users/cwe/Downloads/enonic -v)\033[00m"
    eval $(/Users/cwe/Downloads/enonic project env)
    echo -e "\033[90mJAVA_HOME=\033[32m$JAVA_HOME\n\033[90mXP_HOME=\033[32m$XP_HOME"
  fi
}