Funkcja Bash / zsh, która prowadzi do katalogu głównego drzewa git
Nov 26 2020
Chciałbym uzyskać recenzję funkcji, która umieszcza CD w katalogu głównym drzewa git lub nic nie robi, jeśli jesteśmy poza repozytorium.
wersja recenzowana:
# 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
}
zaktualizowana wersja:
#!/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
}
Odpowiedzi
4 chicks Nov 26 2020 at 10:12
Świetny
- 100% pass on shellcheck, co oznacza, że świetnie sobie radzisz z cytowaniem wszystkiego, co może być potencjalnie problematyczne.
- zakres zmiennych
- używanie
[[
warunkowe dlaif
- ładne wyjaśnienie tego, co robi i dlaczego
Może być lepiej
- Linia sh-bang na górze jest dobrym pomysłem dla skryptów, nawet jeśli zwykle jest ona pobierana podczas skryptów logowania.
- Twoja funkcja wewnętrzna jest zdefiniowana za pomocą innej składni niż funkcja zewnętrzna.
- Możesz określić zakres i zdefiniować zmienną w jednej linii. Na przykład:
local super_root="$(git rev-parse --show-superproject-working-tree)"
. Daje to pewność, że nie pomylisz się z definicją zmiennej lokalnej lub nie określisz zakresu nowej zmiennej. I w każdym przypadku wycina wiersz kodu. - Ponowne użycie
git_root
nazwy zmiennej i nazwy funkcji jest mylące. Początkowo zastanawiałem się, dlaczego próbujesz określić zakres funkcji po jej zdefiniowaniu. - użyj
[[
warunkowego dla warunkowego w ostatniej linii.