¿Cómo puedo obtener una lista de ramas de git, ordenadas por la confirmación más reciente?
Quiero obtener una lista de todas las ramas en un repositorio Git con las ramas "freshest" en la parte superior, donde la rama "freshest" es la que se ha comprometido más recientemente (y, por lo tanto, es más probable que sea una a la que quiero prestar atención).
¿Hay alguna forma de usar Git para (a) ordenar la lista de ramas por última confirmación, o (b) obtener una lista de ramas junto con la fecha de última confirmación de cada una, en algún tipo de formato legible por máquina?
En el peor de los casos, I siempre podría ejecutar git branch
para obtener una lista de todas las ramas, analizar su salida, y luego git log -n 1 branchname --format=format:%ci
para cada una, para obtener la fecha de confirmación de cada rama. Pero esto se ejecutará en una caja de Windows, donde girar un nuevo proceso es relativamente caro, por lo que lanzar el ejecutable de git una vez por rama podría ser lento si hay muchas ramas. ¿Hay alguna manera de hacer todo esto con un solo comando?
24 answers
Uso --sort=-committerdate
opción de git for-each-ref
;
También disponible desde Git 2.7.0 para git branch
:
Uso básico:
git for-each-ref --sort=-committerdate refs/heads/
# or using git branch (since version 2.7.0)
git branch --sort=-committerdate # DESC
git branch --sort=committerdate # ASC
Resultado:
Uso avanzado:
git for-each-ref --sort=committerdate refs/heads/ --format='%(HEAD) %(color:yellow)%(refname:short)%(color:reset) - %(color:red)%(objectname:short)%(color:reset) - %(contents:subject) - %(authorname) (%(color:green)%(committerdate:relative)%(color:reset))'
Resultado:
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-08 16:10:00
Lista de nombres de rama de git, ordenados por la confirmación más reciente {
Expandiendo la respuesta de Jakub y la sugerencia de Joe, lo siguiente eliminará los "refs / heads /" para que la salida solo muestre los nombres de las ramas:
Orden:
git for-each-ref --count=30 --sort=-committerdate refs/heads/ --format='%(refname:short)'
Resultado:
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-30 16:53:21
Aquí está el código óptimo, que combina las otras dos respuestas:
git for-each-ref --sort=-committerdate refs/heads/ --format='%(committerdate:short) %(authorname) %(refname:short)'
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-05 19:04:44
Aquí hay un comando simple que enumera todas las ramas con las últimas confirmaciones:
git branch -v
Para ordenar por confirmación más reciente, use
git branch -v --sort=committerdate
Fuente: http://git-scm.com/book/en/Git-Branching-Branch-Management
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-14 16:36:26
Utilizo el siguiente alias:
recent = "!r(){git for-each-ref --sort=-committerdate refs/heads --format='%(HEAD)%(color:yellow)%(refname:short)|%(color:bold green)%(committerdate:relative)|%(color:blue)%(subject)|%(color:magenta)%(authorname)%(color:reset)'|column -ts'|'}; r"
Que produce:
Editar: usa ' / ' para separar, gracias a @ Björn Lindqvist
Actualización: añadida * antes de la rama actual, gracias a @elhadi
Editar: se ha corregido un caso en el que la rama actual era una subcadena de otra rama
Editar: use una sintaxis más simple para la rama actual, gracias a @Joshua Skrzypek
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:55:13
También necesitaba colores, etiquetas y referencias remotas sin duplicados:
for ref in $(git for-each-ref --sort=-committerdate --format="%(refname)" refs/heads/ refs/remotes ); do git log -n1 $ref --pretty=format:"%Cgreen%cr%Creset %C(yellow)%d%Creset %C(bold blue)<%an>%Creset%n" | cat ; done | awk '! a[$0]++'
Debido a que citar puede ser difícil, aquí el alias para bash:
alias glist='for ref in $(git for-each-ref --sort=-committerdate --format="%(refname)" refs/heads/ refs/remotes ); do git log -n1 $ref --pretty=format:"%Cgreen%cr%Creset %C(yellow)%d%Creset %C(bold blue)<%an>%Creset%n" | cat ; done | awk '"'! a["'$0'"]++'"
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-19 09:27:32
Las otras respuestas no parecen permitir pasar -vv
para obtener una salida detallada.
Así que aquí hay una línea que ordena git branch -vv
por fecha de confirmación, preservando el color, etc.:
git branch -vv --color=always | while read; do echo -e $(git log -1 --format=%ct $(echo "_$REPLY" | awk '{print $2}' | perl -pe 's/\e\[?.*?[\@-~]//g') 2> /dev/null || git log -1 --format=%ct)"\t$REPLY"; done | sort -r | cut -f 2
Si además desea imprimir la fecha de confirmación, puede usar esta versión en su lugar:
git branch -vv --color=always | while read; do echo -e $(git log -1 --format=%ci $(echo "_$REPLY" | awk '{print $2}' | perl -pe 's/\e\[?.*?[\@-~]//g') 2> /dev/null || git log -1 --format=%ci)" $REPLY"; done | sort -r | cut -d ' ' -f -1,4-
Salida de muestra:
2013-09-15 master da39a3e [origin/master: behind 7] Some patch
2013-09-11 * (detached from 3eba4b8) 3eba4b8 Some other patch
2013-09-09 my-feature e5e6b4b [master: ahead 2, behind 25] WIP
Es probablemente más legible dividido en varias líneas:
git branch -vv --color=always | while read; do
# The underscore is because the active branch is preceded by a '*', and
# for awk I need the columns to line up. The perl call is to strip out
# ansi colors; if you don't pass --color=always above you can skip this
local branch=$(echo "_$REPLY" | awk '{print $2}' | perl -pe 's/\e\[?.*?[\@-~]//g')
# git log fails when you pass a detached head as a branch name.
# Hide the error and get the date of the current head.
local branch_modified=$(git log -1 --format=%ci "$branch" 2> /dev/null || git log -1 --format=%ci)
echo -e "$branch_modified $REPLY"
# cut strips the time and timezone columns, leaving only the date
done | sort -r | cut -d ' ' -f -1,4-
Esto también debería funcionar con otros argumentos para git branch
, por ejemplo, -vvr
para listar el seguimiento remoto ramas, o -vva
para listar ramas locales y de seguimiento remoto.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-12 16:14:15
Pude hacer referencia a los ejemplos anteriores para crear algo que funcione mejor para mí.
Git for-each-ref sort sort= - committerdate refs / heads/ -- format= ' %(authordate:short) %(color: red)%(objectname: short) %(color: yellow)%(refname:short)%(color: reset) (%(color:green)%(committerdate:relative)%(color:reset))'
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-13 19:09:37
Me gusta usar una fecha relativa y acortar el nombre de la rama de esta manera:
git for-each-ref --sort='-authordate:iso8601' --format=' %(authordate:relative)%09%(refname:short)' refs/heads
Que te da salida:
21 minutes ago nathan/a_recent_branch
6 hours ago master
27 hours ago nathan/some_other_branch
29 hours ago branch_c
6 days ago branch_d
Recomiendo hacer un archivo bash para agregar todos tus alias favoritos y luego compartir el script con tu equipo. Aquí hay un ejemplo para agregar solo este:
#!/bin/sh
git config --global alias.branches "!echo ' ------------------------------------------------------------' && git for-each-ref --sort='-authordate:iso8601' --format=' %(authordate:relative)%09%(refname:short)' refs/heads && echo ' ------------------------------------------------------------'"
Entonces puede hacer esto para obtener una lista de ramas locales bien formateada y ordenada:
git branches
Actualizar: Haga esto si desea colorear:
#!/bin/sh
#
(echo ' ------------------------------------------------------------' && git for-each-ref --sort='-authordate:iso8601' --format=' %(authordate:relative)%09%(refname:short)' refs/heads && echo ' ------------------------------------------------------------') | grep --color -E "$(git rev-parse --abbrev-ref HEAD)$|$"
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-11 22:27:25
Git 2.7 (Q4 2015) introducirá la ordenación de ramas usando directamente git branch
:
Véase commit aa3bc55, commit aedcb7d, commit 1511b22, commit f65f139,... (23 de septiembre de 2015), commit aedcb7d, commit 1511b22, commit ca41799 (24 Sep 2015), and commit f65f139 ,... (23 de septiembre de 2015) por Karthik Nayak (KarthikNayak
).
(Merged by Junio C Hamano -- gitster
-- in commit 7f11b48, 15 de octubre 2015)
En particular, commit aedcb7d :
branch.c
: use'ref-filter
' APIs
Make 'branch.c
' use 'ref-filter
' APIs para iterar a través de la clasificación de refs. Esto elimina la mayor parte del código utilizado en' branch.c
' reemplazándolo
con llamadas a la biblioteca' ref-filter
'.
It añade la opción --sort=<key>
:
Ordenar en función de la clave dada.
Prefijo-
para ordenar en orden descendente del valor.Puede usar la opción
--sort=<key>
varias veces, en cuyo caso la última clave se convierte en la clave primaria.Las claves soportadas son las mismas que las de
git for-each-ref
.
Por defecto, el orden de ordenación se basa en el nombre de referencia completo (incluido el prefijorefs/...
). Esto enumera la CABEZA separada (si está presente) primero, luego las ramas locales y finalmente las ramas de seguimiento remoto.
Aquí:
git branch --sort=-committerdate
Véase también commit 9e46833 (30 Oct 2015) by Karthik Nayak (KarthikNayak
).
Helped-by: Junio C Hamano (gitster
).
(Merged by Junio C Hamano -- gitster
-- in commit 415095f, 03 Nov 2015)
Al ordenar según valores numéricos (por ejemplo,
--sort=objectsize
) no hay comparación de reserva cuando ambas referencias tienen el mismo valor. Esto puede causar resultados inesperados (es decir, el orden de listado de referencias con valores iguales no puede ser predeterminado) como señaló Johannes Sixt ( g gmane/280117).Por lo tanto, recurrir a la comparación alfabética basada en el nombre de referencia siempre que el otro criterio sea igual.
$ git branch --sort=objectsize
* (HEAD detached from fromtag)
branch-two
branch-one
master
Con Git 2.19, el orden de clasificación se puede establecer de forma predeterminada.git branch
soporta una configuración branch.sort
, como git tag
, que ya tenía una configuración tag.sort
.
Véase commit 560ae1c (16 de agosto de 2018) por Samuel Maftoul (`).
(Merged by Junio C Hamano -- gitster
-- in commit d89db6f , 27 Ago 2018)
branch.sort:
Esta variable controla el orden de las ramas cuando se muestra por
git-branch
.
Sin la opción"--sort=<value>
" proporcionada, el valor de esta variable se utilizará como predeterminado.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-28 21:03:22
Añade un poco de color (ya que pretty-format
no está disponible)
[alias]
branchdate = for-each-ref --sort=-committerdate refs/heads/ --format="%(authordate:short)%09%(objectname:short)%09%1B[0;33m%(refname:short)%1B[m%09"
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-27 19:23:50
Tuve el mismo problema, así que escribí una gema de rubí llamada Ramita. Enumera las ramas en orden cronológico (la más reciente primero), y también puede permitirle establecer una edad máxima para que no enumere todas las ramas (si tiene muchas). Por ejemplo:
$ twig
issue status todo branch
----- ------ ---- ------
2013-01-26 18:00:21 (7m ago) 486 In progress Rebase optimize-all-the-things
2013-01-26 16:49:21 (2h ago) 268 In progress - whitespace-all-the-things
2013-01-23 18:35:21 (3d ago) 159 Shipped Test in prod * refactor-all-the-things
2013-01-22 17:12:09 (4d ago) - - - development
2013-01-20 19:45:42 (6d ago) - - - master
También le permite almacenar propiedades personalizadas para cada rama, por ejemplo, id de ticket, estado, todos, y filtrar la lista de ramas de acuerdo con estas propiedades. Más información: http://rondevera.github.io/twig /
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-16 01:22:49
Se me ocurrió el siguiente comando (para Git 2.13 y posteriores):
git branch -r --sort=creatordate \
--format "%(creatordate:relative);%(committername);%(refname:lstrip=-1)" \
| grep -v ";HEAD$" \
| column -s ";" -t
Si no tienes column
puedes reemplazar la última línea con
| sed -e "s/;/\t/g"
La salida se ve como
6 years ago Tom Preston-Werner book
4 years, 4 months ago Parker Moore 0.12.1-release
4 years ago Matt Rogers 1.0-branch
3 years, 11 months ago Matt Rogers 1.2_branch
3 years, 1 month ago Parker Moore v1-stable
12 months ago Ben Balter pages-as-documents
10 months ago Jordon Bedwell make-jekyll-parallel
6 months ago Pat Hawks to_integer
5 months ago Parker Moore 3.4-stable-backport-5920
4 months ago Parker Moore yajl-ruby-2-4-patch
4 weeks ago Parker Moore 3.4-stable
3 weeks ago Parker Moore rouge-1-and-2
19 hours ago jekyllbot master
Escribí una entrada de blog sobre cómo funcionan las diversas piezas.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-19 02:54:52
Para su información, si desea obtener una lista de ramas recientemente retiradas (a diferencia de las confirmadas recientemente) puede usar reflog de git:
$ git reflog | egrep -io "moving from ([^[:space:]]+)" | awk '{ print $3 }' | head -n5
master
stable
master
some-cool-feature
feature/improve-everything
Véase también: ¿Cómo puedo obtener una lista de ramas de git que he revisado recientemente?
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:55:13
Aquí hay otro script que hace lo que hacen todos los otros scripts. De hecho, proporciona una función para su shell.
Su contribución es que extrae algunos colores de tu configuración de git (o usa valores predeterminados).
# Git Branch by Date
# Usage: gbd [ -r ]
gbd() {
local reset_color=`tput sgr0`
local subject_color=`tput setaf 4 ; tput bold`
local author_color=`tput setaf 6`
local target=refs/heads
local branch_color=`git config --get-color color.branch.local white`
if [ "$1" = -r ]
then
target=refs/remotes/origin
branch_color=`git config --get-color color.branch.remote red`
fi
git for-each-ref --sort=committerdate $target --format="${branch_color}%(refname:short)${reset_color} ${subject_color}%(subject)${reset_color} ${author_color}- %(authorname) (%(committerdate:relative))${reset_color}"
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-09 19:46:21
Basado en la versión de ilius, pero con la rama actual mostrada con una estrella y en color, y solo mostrando cualquier cosa que no se describe como "meses" o "años":
current_branch="$(git symbolic-ref --short -q HEAD)"
git for-each-ref --sort=committerdate refs/heads \
--format='%(refname:short)|%(committerdate:relative)' \
| grep -v '\(year\|month\)s\? ago' \
| while IFS='|' read branch date
do
start=' '
end=''
if [[ $branch = $current_branch ]]; then
start='* \e[32m'
end='\e[0m'
fi
printf "$start%-30s %s$end\\n" "$branch" "$date"
done
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-13 15:51:16
Aquí hay un pequeño script que uso para cambiar entre ramas recientes:
#!/bin/bash
# sudo bash
re='^[0-9]+$'
if [[ "$1" =~ $re ]]; then
lines="$1"
else
lines=10
fi
branchs="$(git recent | tail -n $lines | nl)"
branchs_nf="$(git recent-nf | tail -n $lines | nl)"
echo "$branchs"
# Prompt which server to connect to
max="$(echo "$branchs" | wc -l)"
index=
while [[ ! ( "$index" =~ ^[0-9]+$ && "$index" -gt 0 && "$index" -le "$max" ) ]]; do
echo -n "Checkout to: "
read index
done
branch="$( echo "$branchs_nf" | sed -n "${index}p" | awk '{ print $NF }' )"
git co $branch
clear
Usando esos dos alias
recent = for-each-ref --sort=committerdate refs/heads/ --format=' %(color:blue) %(authorname) %(color:yellow)%(refname:short)%(color:reset)'
recent-nf = for-each-ref --sort=committerdate refs/heads/ --format=' %(authorname) %(refname:short)'
Simplemente llame a eso en un repositorio de git y le mostrará las últimas N ramas (10 por defecto) y un número aparte cada una. Introduzca el número de la rama y se comprueba:
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-18 20:36:47
A partir de git 2.19 puedes simplemente:
git config --global branch.sort -committerdate
Por lo tanto, cada vez que enumere ramas, se listarán ordenadas por committerdate.
Descargo de responsabilidad: Soy el autor de esta característica en git, la implementé cuando vi esta pregunta.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-12 13:05:10
Mi mejor resultado como script:
git for-each-ref --sort=-committerdate refs/heads/ --format='%(refname:short)|%(committerdate:iso)|%(authorname)' |
sed 's/refs\/heads\///g' |
grep -v BACKUP |
while IFS='|' read branch date author
do
printf '%-15s %-30s %s\n' "$branch" "$date" "$author"
done
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-01 13:10:22
Aquí está la variación que estaba buscando:
git for-each-ref --sort=-committerdate --format='%(committerdate)%09%(refname:short)' refs/heads/ | tail -r
Que tail -r
invierte la lista para que el commiterdate
más reciente sea el último.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-14 17:36:54
Tarde a la fiesta aquí. La respuesta CML aceptada es genial, pero si quieres algo más bonito, como una GUI, y tu origen = = = "github".
Puede hacer clic en "Ramas" en el repositorio. o pulsa la url directa: https://github.com/ORGANIZATION_NAME/REPO_NAME/branches
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-11 14:36:25
Canalizo la salida de la respuesta aceptada en dialog
, para darme una lista interactiva:
#!/bin/bash
TMP_FILE=/tmp/selected-git-branch
eval `resize`
dialog --title "Recent Git Branches" --menu "Choose a branch" $LINES $COLUMNS $(( $LINES - 8 )) $(git for-each-ref --sort=-committerdate refs/heads/ --format='%(refname:short) %(committerdate:short)') 2> $TMP_FILE
if [ $? -eq 0 ]
then
git checkout $(< $TMP_FILE)
fi
rm -f $TMP_FILE
clear
Guardar como (por ejemplo) ~/bin/git_recent_branches.sh
y chmod +x
it. Entonces git config --global alias.rb '!git_recent_branches.sh'
para darme un nuevo comando git rb
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-14 14:59:57
git for-each-ref --sort=committerdate refs/heads/ --format='%(HEAD) %(color:yellow)%(refname:short)%(color:reset) - %(color:red)%(objectname:short)%(color:reset) - %(contents:subject) - %(authorname) (%(color:green)%(committerdate:relative)%(color:reset))'
esto es lo que necesitas
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-10 19:32:29
Git v2.19 introduce la opción de configuración branch.sort
(consulte la rama .sort ).
Así que git branch
ordenará por fecha de confirmación (desc) por defecto con
# gitconfig
[branch]
sort = -committerdate # desc
Script:
$ git config --global branch.sort -committerdate
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-18 04:53:46