Función bash / zsh que hace cd a la raíz del árbol git

Nov 26 2020

Me gustaría obtener una revisión de la función que ingresa en la raíz del árbol git o no hace nada si estamos fuera del repositorio.

versión 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
}

Versión actualizada:

#!/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
}

Respuestas

4 chicks Nov 26 2020 at 10:12

Excelente

  • Pase el 100% de shellcheck, lo que significa que le va muy bien citando todo lo que podría ser potencialmente problemático.
  • variables de alcance
  • usando [[condicional para elif
  • buena explicación de lo que está haciendo y por qué

Podría ser mejor

  • una línea sh-bang en la parte superior es una buena idea para los scripts, incluso si esto normalmente solo se obtendría durante sus scripts de inicio de sesión.
  • Su función interna se define con una sintaxis diferente a la de su función externa.
  • Puede definir el alcance y definir una variable en una línea. Por ejemplo: local super_root="$(git rev-parse --show-superproject-working-tree)". Esto asegura que no deje de definir una variable local o no pueda definir el alcance de una nueva variable. Y corta una línea de código en cada caso.
  • Reutilizar git_rootpara un nombre de variable y el nombre de función es confuso. Inicialmente me pregunté por qué intentaba establecer el alcance de la función después de haberla definido.
  • use [[conditional for conditional en la última línea.