특정 디렉토리에서만 사용할 수 있는 zsh의 명령/별칭 만들기

특정 디렉토리에서만 사용할 수 있는 zsh의 명령/별칭 만들기

현재 디렉터리나 해당 하위 디렉터리에서만 사용할 수 있는 명령을 만드는 것이 가능합니까? 예를 들어, 라는 명령/별칭을 만들고 싶고 cdtheme다음과 같은 디렉터리 구조가 있다고 가정해 보겠습니다.

~/code

# PROJECTNAME and THEMENAME can be anything the rest of the structure will stay the same
~/code/PROJECTNAME/web/themes/THEMENAME

~/code/projectA/web/themes/theme1
~/code/projectB/web/themes/theme2
~/code/xyzproject/web/themes/randomthemename

cdtheme다음 디렉터리에서 실행하면 다음과 같은 결과가 발생합니다.

~/code # error

~/code/projectA # cd to theme1
~/code/projectA/web # cd to theme1

~/code/projectB # cd to theme2

~/code/xyzproject # cd to randomthemename

cdtheme이것은 단지 예일 뿐이며, 예를 들어 더 많은 명령을 추가하고 싶습니다 . 내 초기 아이디어 는 사용자 정의 명령/별칭/변수를 정의하고 자동으로 가져올 수 cdproject있는 디렉터리에 파일을 추가할 수 있다는 것이었습니다 .projectB/.zshrc

편집: 명확성과 추가된 맥락

답변1

별칭이나 함수를 정의하거나 정의 취소할 수 있습니다.chpwd.

function set_theme_dir {
  case $PWD/ in
    ~/code/projectA/) alias cdtheme='cd ~/code/projectA/web/themes/theme1';;
    ~/code/projectB/) alias cdtheme='cd ~/code/projectB/web/themes/theme2';;
    *) unalias cdtheme;;
  esac
}
chpwd_functions+=(set_theme_dir)

cdtheme그러나 귀하의 요구 사항을 고려할 때 항상 런타임에 현재 디렉터리를 정의하고 분석하는 것이 더 합리적이라고 생각합니다 .

function cdtheme {
  case $PWD/ in
    ~/code/projectA/) cd ~/code/projectA/web/themes/theme1;;
    ~/code/projectB/) cd ~/code/projectB/web/themes/theme2;;
    *) echo "Error: not inside a project tree" >&2; return 2;;
  esac
}

테마 디렉토리가 하드코딩되어 있는지 또는 프로젝트에서 결정될 수 있는지 또는 프로젝트 디렉토리가 무엇인지 구분하는 방법이 불분명합니다. 다음은 cdtheme각 프로젝트에 자체 Git 작업 트리가 있고 첫 번째 주제를 사전순으로 정렬한다고 가정 한 구현입니다 .

function cdtheme {
  emulate -L zsh
  setopt err_return
  local root
  root=$(git rev-parse --show-toplevel)
  cd $root/web/themes/theme*([1])
}

관련 정보