¿Cómo se puede cambiar la marca de tiempo de una confirmación antigua en Git?


Las respuestas a ¿Cómo modificar confirmaciones existentes sin publicar? describa una forma de modificar mensajes de confirmación anteriores que aún no se han enviado. Los nuevos mensajes heredan las marcas de tiempo de las confirmaciones originales. Esto parece lógico, pero ¿hay alguna manera de reestablecer también los tiempos?

Author: Community, 2009-01-18

17 answers

Use git filter-branch con un filtro env que establece GIT_AUTHOR_DATE y GIT_COMMITTER_DATE para el hash específico de la confirmación que desea corregir.

Esto invalidará eso y todos los hashes futuros.

Ejemplo:

Si quisieras cambiar las fechas de commit 119f9ecf58069b265ab22f1f97d2b648faf932e0, podrías hacerlo con algo como esto:

git filter-branch --env-filter \
    'if [ $GIT_COMMIT = 119f9ecf58069b265ab22f1f97d2b648faf932e0 ]
     then
         export GIT_AUTHOR_DATE="Fri Jan 2 21:38:53 2009 -0800"
         export GIT_COMMITTER_DATE="Sat May 19 01:01:01 2007 -0700"
     fi'
 431
Author: Dustin,
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-12-07 21:34:40

Puede hacer un rebase interactivo y elegir editar para la confirmación cuya fecha desea alterar. Cuando el proceso de rebase se detiene para modificar el commit, escribe por ejemplo:

git commit --amend --date="Wed Feb 16 14:00 2011 +0100"

Después continúas tu rebase interactivo.

UPDATE (en respuesta al comentario de studgeek): para cambiar la fecha de confirmación en lugar de la fecha de autor:

GIT_COMMITTER_DATE="Wed Feb 16 14:00 2011 +0100" git commit --amend

Las líneas anteriores establecen una variable de entorno GIT_COMMITTER_DATE que se usa en amend cometer.

Todo se prueba en Git Bash.

 632
Author: Paul Pladijs,
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-20 19:51:57

Una mejor manera de manejar todas estas sugerencias en un comando es

LC_ALL=C GIT_COMMITTER_DATE="$(date)" git commit --amend --no-edit --date "$(date)"

Esto establecerá la fecha de confirmación y autor de la última confirmación en "ahora mismo."

 342
Author: Luke Ehresman,
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-02-24 02:57:36

Simplemente haz git commit --amend --reset-author --no-edit. Para confirmaciones anteriores, puedes hacer un rebase interactivo y elegir edit para la confirmación cuya fecha deseas modificar.

git rebase -i <ref>

Luego modifica el commit con --reset-author y --no-edit para cambiar la fecha del autor a la fecha actual:

git commit --amend --reset-author --no-edit

Finalmente continúe con su rebase interactivo:

git rebase --continue
 131
Author: Miguel de Val-Borro,
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-11-30 23:29:47

Escribí un script y un paquete Homebrew para esto. Súper fácil de instalar, lo puedes encontrar en GitHub PotatoLabs/git-redate page.

Sintaxis:

git redate -c 3

Solo tienes que ejecutar git redate y podrás editar todas las fechas en vim de las 5 confirmaciones más recientes (también hay una opción -c para cuántas confirmaciones quieres volver, solo por defecto es 5). ¡Avísame si tienes alguna pregunta, comentario o sugerencia!

introduzca la descripción de la imagen aquí

 71
Author: Edmund,
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-03-14 12:02:32

Cada commit está asociado con dos fechas, la fecha del committer y la fecha del autor. Puedes ver estas fechas con:

git log --format=fuller

Si desea cambiar la fecha del autor y la fecha del committer de los últimos 6 commits, simplemente puede usar un rebase interactivo:

git rebase -i HEAD~6

.

pick c95a4b7 Modification 1
pick 1bc0b44 Modification 2
pick de19ad3 Modification 3
pick c110e7e Modification 4
pick 342256c Modification 5
pick 5108205 Modification 6

# Rebase eadedca..5108205 onto eadedca (6 commands)
#
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# x, exec = run command (the rest of the line) using shell
# d, drop = remove commit

Para todas las confirmaciones en las que desea cambiar la fecha, reemplace pick por edit (o simplemente e), luego guarde y salga de su editor.

Ahora puede modificar cada confirmación especificando el autor fecha y fecha del committer en formato ISO-8601:

GIT_COMMITTER_DATE="2017-10-08T09:51:07" git commit --amend --date="2017-10-08T09:51:07"

La primera fecha es la fecha de confirmación, la segunda es la fecha del autor.

Luego ve a la siguiente confirmación con:

git rebase --continue

Repita el proceso hasta que modifique todas sus confirmaciones. Compruebe su progresión con git status.

 61
Author: Ortomala Lokni,
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-31 08:59:51

Basándome en la respuestade theosp, escribí un script llamado git-cdc (para change date commit) que puse en mi PATH.

El nombre es importante: git-xxx en cualquier lugar de su PATH le permite escribir:

git xxx
# here
git cdc ... 

Ese script está en bash, incluso en Windows (ya que Git lo llamará desde su entorno msys)

#!/bin/bash
# commit
# date YYYY-mm-dd HH:MM:SS

commit="$1" datecal="$2"
temp_branch="temp-rebasing-branch"
current_branch="$(git rev-parse --abbrev-ref HEAD)"

date_timestamp=$(date -d "$datecal" +%s)
date_r=$(date -R -d "$datecal")

if [[ -z "$commit" ]]; then
    exit 0
fi

git checkout -b "$temp_branch" "$commit"
GIT_COMMITTER_DATE="$date_timestamp" GIT_AUTHOR_DATE="$date_timestamp" git commit --amend --no-edit --date "$date_r"
git checkout "$current_branch"
git rebase  --autostash --committer-date-is-author-date "$commit" --onto "$temp_branch"
git branch -d "$temp_branch"

Con eso, puedes escribir:

git cdc @~ "2014-07-04 20:32:45"

Que restablecería la fecha de autor / confirmación de la confirmación antes de HEAD (@~) a la fecha especificada.

git cdc @~ "2 days ago"

Que restablecería la fecha de autor/confirmación de la confirmación antes de HEAD (@~) a la misma hora, pero hace 2 días.


Ilya Semenov menciona en los comentarios:

Para OS X también puede instalar GNU coreutils (brew install coreutils), añadir a PATH (PATH="/usr/local/opt/coreutils/libexec/gnubin:$PATH") y luego use la sintaxis" 2 days ago".

 40
Author: VonC,
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 12:26:36

Esto cambia la fecha (marca de tiempo) de la última confirmación

git commit --amend --date "Thu May 28 18:21:46 2015 +0530"

 26
Author: Nishant,
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
2015-06-02 13:04:24

Si es la última confirmación anterior.

git rebase  -i HEAD~2
git commit --amend --date=now

Si ya presiona a orgin y puede forzar el uso:

git push --force 

Si no puedes forzar el push y si es push, ¡no puedes cambiar el commit! .

 18
Author: Sérgio,
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-04-25 00:34:39
git commit --amend --date="now"
 18
Author: Harald Nordgren,
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-07 15:16:42

Aquí hay un alias conveniente que cambia los tiempos de confirmación y de autor de la última confirmación a un tiempo aceptado por date --date:

[alias]
    cd = "!d=\"$(date -d \"$1\")\" && shift && GIT_COMMITTER_DATE=\"$d\" \
            git commit --amend --date \"$d\""

Uso: git cd <date_arg>

Ejemplos:

git cd now  # update the last commit time to current time
git cd '1 hour ago'  # set time to 1 hour ago

Editar: Aquí hay una versión más automatizada que comprueba que el índice está limpio (no hay cambios sin confirmar) y reutiliza el último mensaje de confirmación, o falla de otra manera (a prueba de tontos):

[alias]
    cd = "!d=\"$(date -d \"$1\")\" && shift && \
        git diff-index --cached --quiet HEAD --ignore-submodules -- && \
        GIT_COMMITTER_DATE=\"$d\" git commit --amend -C HEAD --date \"$d\"" \
        || echo >&2 "error: date change failed: index not clean!"
 14
Author: eold,
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-16 05:58:09

Si desea obtener la fecha exacta de otro commit (digamos que rebase editó un commit y desea que tenga la fecha de la versión original pre-rebase):

git commit --amend --date="$(git show -s --format=%ai a383243)"

Esto corrige que la fecha de la confirmación PRINCIPAL es exactamente la fecha de la confirmación a383243 (incluya más dígitos si hay ambigüedades). También aparecerá una ventana del editor para que pueda editar el mensaje de confirmación.

Eso es para la fecha del autor que es lo que te importa generalmente-ver otras respuestas para el fecha de confirmación.

 8
Author: Mr_and_Mrs_D,
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-11-18 11:17:18

La siguiente función bash cambiará el tiempo de cualquier confirmación en la rama actual.

Tenga cuidado de no usar si ya ha empujado el commit o si utiliza el commit en otra rama.

# rewrite_commit_date(commit, date_timestamp)
#
# !! Commit has to be on the current branch, and only on the current branch !!
# 
# Usage example:
#
# 1. Set commit 0c935403 date to now:
#
#   rewrite_commit_date 0c935403
#
# 2. Set commit 0c935403 date to 1402221655:
#
#   rewrite_commit_date 0c935403 1402221655
#
rewrite_commit_date () {
    local commit="$1" date_timestamp="$2"
    local date temp_branch="temp-rebasing-branch"
    local current_branch="$(git rev-parse --abbrev-ref HEAD)"

    if [[ -z "$date_timestamp" ]]; then
        date="$(date -R)"
    else
        date="$(date -R --date "@$date_timestamp")"
    fi

    git checkout -b "$temp_branch" "$commit"
    GIT_COMMITTER_DATE="$date" git commit --amend --date "$date"
    git checkout "$current_branch"
    git rebase "$commit" --onto "$temp_branch"
    git branch -d "$temp_branch"
}
 8
Author: theosp,
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-09 10:28:56

Para cambiar tanto la fecha del autor como la fecha de confirmación:

GIT_COMMITTER_DATE="Wed Sep 23 9:40 2015 +0200" git commit --amend --date "Wed Sep 23 9:40 2015 +0200"
 6
Author: Jan H,
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
2015-09-23 07:41:28

He creado este paquete npm para cambiar la fecha de las confirmaciones antiguas.

Https://github.com/bitriddler/git-change-date

Uso de la muestra:

npm install -g git-change-date
cd [your-directory]
git-change-date

Se le pedirá que elija la confirmación que desea modificar y luego introduzca la nueva fecha.

Si quieres cambiar un commit por un hash específico ejecuta esto git-change-date --hash=[hash]

 6
Author: Kareem Elbahrawy,
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-24 22:20:39

Si desea realizar la respuesta aceptada ( https://stackoverflow.com/a/454750/72809 ) en la línea de comandos estándar de Windows, necesita el siguiente comando:

git filter-branch -f --env-filter "if [ $GIT_COMMIT = 578e6a450ff5318981367fe1f6f2390ce60ee045 ]; then export GIT_AUTHOR_DATE='2009-10-16T16:00+03:00'; export GIT_COMMITTER_DATE=$GIT_AUTHOR_DATE; fi"

Notas:

  • Puede ser posible dividir el comando en varias líneas (Windows admite la división de líneas con el símbolo carret ^), pero no tuve éxito.
  • Puede escribir fechas ISO, ahorrando mucho tiempo encontrando el día de la semana correcto y frustración general sobre el orden de elemento.
  • Si desea que la fecha del Autor y del Committer sean las mismas, solo puede hacer referencia a la variable establecida anteriormente.

Muchas gracias a un entrada de blog por Colin Svingen. A pesar de que su código no funcionó para mí, me ayudó a encontrar la solución correcta.

 4
Author: Peter,
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:47:29

Ya hay muchas respuestas geniales, pero cuando quiero cambiar la fecha para varias confirmaciones en un día o en un mes, no encuentro una respuesta adecuada. Así que creo un nuevo script para esto con explicación, espero que ayude a alguien:

#!/bin/bash

# change GIT_AUTHOR_DATE for commit at Thu Sep 14 13:39:41 2017 +0800
# you can change the data_match to change all commits at any date, one day or one month
# you can also do the same for GIT_COMMITTER_DATE

git filter-branch --force --env-filter '

date_match="^Thu, 14 Sep 2017 13+"              

# GIT_AUTHOR_DATE will be @1505367581 +0800, Git internal format 
author_data=$GIT_AUTHOR_DATE;                   
author_data=${author_data#@}                  
author_data=${author_data% +0800}                # author_data is 1505367581     

oneday=$((24*60*60))

# author_data_str will be "Thu, 14 Sep 2017 13:39:41 +0800", RFC2822 format
author_data_str=`date -R -d @$author_data`      

if [[ $author_data_str =~ $date_match ]];
then
    # remove one day from author_data
    new_data_sec=$(($author_data-$oneday))
    # change to git internal format based on new_data_sec
    new_data="@$new_data_sec +0800"             
    export GIT_AUTHOR_DATE="$new_data"
fi
' --tag-name-filter cat -- --branches --tags

La fecha será cambiada:

AuthorDate: Wed Sep 13 13:39:41 2017 +0800
 1
Author: detective0922,
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-09-15 01:57:05