Função Bash / zsh que vai para a raiz da árvore git
Nov 26 2020
Eu gostaria de obter uma revisão para a função que cd na raiz da árvore git ou não faz nada se estivermos fora do repositório.
versão revisada:
# cd to the root of the current git directory
# If $PWD is submodule, will cd to the root of the top ancestor # It requires to stay in the current directory, if the root is . or unknown, # and use cd only once, to have a way to do `cd -` function cg { git_root() { local super_root local top top="$(git rev-parse --show-cdup)"
top="${top:-./}" super_root="$(git rev-parse --show-superproject-working-tree)"
if [[ "$super_root" ]]; then printf '%s' "$top../"
( cd "$top../" && git_root || return ) fi printf '%s' "$top"
}
local git_root
git_root="$(git_root)" [ "x${git_root}" != "x./" ] && cd "$(git_root)" && return || return 0
}
versão atualizada:
#!/bin/bash
# cd to the root of the current git directory
# If $PWD is submodule, will cd to the root of the top ancestor
# It requires to stay in the current directory, if the root is . or unknown,
# and use cd only once, to have a way to do `cd -`
function cg {
function git_root {
local top; top="$(git rev-parse --show-cdup)" top="${top:-./}"
local super_root; super_root="$(git rev-parse --show-superproject-working-tree)" if [[ "$super_root" ]]; then
printf '%s' "$top../" ( cd "$top../" && git_root || return )
fi
printf '%s' "$top" } local tree_root tree_root="$(git_root)"
[[ "x${tree_root}" != "x./" ]] && cd "${tree_root}" && return || return 0
}
Respostas
4 chicks Nov 26 2020 at 10:12
Ótimo
- 100% repassa o shellcheck, o que significa que você está se saindo muito bem citando tudo que pode ser potencialmente problemático.
- variáveis de escopo
- usando
[[
condicional para oif
- boa explicação do que está fazendo e por que
Poderia ser melhor
- uma linha sh-bang no topo é uma boa ideia para scripts, mesmo que isso normalmente seja obtido durante seus scripts de login.
- Sua função interna é definida com uma sintaxe diferente da função externa.
- Você pode definir o escopo e definir uma variável em uma linha. Por exemplo:
local super_root="$(git rev-parse --show-superproject-working-tree)"
. Isso garante que você não falhe na definição de uma variável local ou no escopo de uma nova variável. E corta uma linha de código em cada caso. - Reutilizar
git_root
para um nome de variável e o nome da função é confuso. Inicialmente me perguntei por que você estava tentando definir o escopo da função depois de defini-la. - use
[[
condicional para condicional na última linha.
O que significa um erro “Não é possível encontrar o símbolo” ou “Não é possível resolver o símbolo”?