What's the equivalent of Subversion's "use-commit-times" for Git?

Viewed 29943

I need the timestamps of files on my local system and on my server to be in sync. This is accomplished with Subversion by setting use-commit-times=true in the configuration so that the last modified of each file is when it was committed.

Each time I clone my repository, I want the timestamps of files to reflect when they were last changed in the remote repository, not when I cloned the repository.

Is there a way to do this with Git?

10 Answers

If, however you really want to use commit times for timestamps when checking out then try using this script and place it (as executable) in the file $GIT_DIR/.git/hooks/post-checkout:

#!/bin/sh -e

OS=${OS:-`uname`}
old_rev="$1"
new_rev="$2"

get_file_rev() {
    git rev-list -n 1 "$new_rev" "$1"
}

if   [ "$OS" = 'Linux' ]
then
    update_file_timestamp() {
        file_time=`git show --pretty=format:%ai --abbrev-commit "$(get_file_rev "$1")" | head -n 1`
        touch -d "$file_time" "$1"
    }
elif [ "$OS" = 'FreeBSD' ]
then
    update_file_timestamp() {
        file_time=`date -r "$(git show --pretty=format:%at --abbrev-commit "$(get_file_rev "$1")" | head -n 1)" '+%Y%m%d%H%M.%S'`
        touch -h -t "$file_time" "$1"
    }
else
    echo "timestamp changing not implemented" >&2
    exit 1
fi

IFS=`printf '\t\n\t'`

git ls-files | while read -r file
do
    update_file_timestamp "$file"
done

Note however, that this script will cause quite a large delay for checking out large repositories (where large means large amount of files, not large file sizes).

I am not sure this would be appropriate for a DVCS (as in "Distributed" VCS)

The huge discussion had already took place in 2007 (see this thread)

And some of Linus's answer were not too keen on the idea. Here is one sample:

I'm sorry. If you don't see how it's WRONG to set a datestamp back to something that will make a simple "make" miscompile your source tree, I don't know what defintiion of "wrong" you are talking about.
It's WRONG.
It's STUPID.
And it's totally INFEASIBLE to implement.


(Note: small improvement: after a checkout, timestamps of up-to-date files are no longer modified (Git 2.2.2+, January 2015): "git checkout - how can I maintain timestamps when switching branches?".)


The long answer was:

I think you're much better off just using multiple repositories instead, if this is something common.

Messing with timestamps is not going to work in general. It's just going to guarantee you that "make" gets confused in a really bad way, and does not recompile enough instead of recompiling too much.

Git does make it possible to do your "check the other branch out" thing very easily, in many different ways.

You could create some trivial script that does any of the following (ranging from the trivial to the more exotic):

  • just create a new repo:
    git clone old new
    cd new
    git checkout origin/<branch>

and there you are. The old timestamps are fine in your old repo, and you can work (and compile) in the new one, without affectign the old one at all.

Use the flags "-n -l -s" to "git clone" to basically make this instantaneous. For lots of files (eg big repos like the kernel), it's not going to be as fast as just switching branches, but havign a second copy of the working tree can be quite powerful.

  • do the same thing with just a tar-ball instead, if you want to
    git archive --format=tar --prefix=new-tree/ <branchname> |
            (cd .. ; tar xvf -)

which is really quite fast, if you just want a snapshot.

  • get used to "git show", and just look at individual files.
    This is actually really useful at times. You just do
    git show otherbranch:filename

in one xterm window, and look at the same file in your current branch in another window. In particular, this should be trivial to do with scriptable editors (ie GNU emacs), where it should be possible to basically have a whole "dired mode" for other branches within the editor, using this. For all I know, the emacs git mode already offers something like this (I'm not an emacs user)

  • and in the extreme example of that "virtual directory" thing, there was at least somebody working on a git plugin for FUSE, ie you could literally just have virtual directories showing all your branches.

and I'm sure any of the above are better alternatives than playing games with file timestamps.

Linus

I saw some requests for a Windows version, so here it is. Create the following two files:

C:\Program Files\Git\mingw64\share\git-core\templates\hooks\post-checkout

#!C:/Program\ Files/Git/usr/bin/sh.exe
exec powershell.exe -NoProfile -ExecutionPolicy Bypass -File "./$0.ps1"

C:\Program Files\Git\mingw64\share\git-core\templates\hooks\post-checkout.ps1

[string[]]$changes = &git whatchanged --pretty=%at
$mtime = [DateTime]::Now;
[string]$change = $null;
foreach($change in $changes)
{
    if($change.Length -eq 0) { continue; }
    if($change[0] -eq ":")
    {
        $parts = $change.Split("`t");
        $file = $parts[$parts.Length - 1];
        if([System.IO.File]::Exists($file))
        {
            [System.IO.File]::SetLastWriteTimeUtc($file, $mtime);
        }
    }
    else
    {
        #get timestamp
        $mtime = [DateTimeOffset]::FromUnixTimeSeconds([Int64]::Parse($change)).DateTime;
    }
}

This utilizes git whatchanged, so it runs through all the files in one pass instead of calling git for each file.

Here is a Go program:

import "bufio"
import "log"
import "os/exec"

func check(e error) {
   if e != nil {
      log.Fatal(e)
   }
}

func popen(name string, arg ...string) (*bufio.Scanner, error) {
   cmd := exec.Command(name, arg...)
   pipe, e := cmd.StdoutPipe()
   if e != nil {
      return nil, e
   }
   return bufio.NewScanner(pipe), cmd.Start()
}
import "os"
import "strconv"
import "time"

func main() {
   gitLs, e := popen("git", "ls-files")
   check(e)
   files := map[string]bool{}
   for gitLs.Scan() {
      files[gitLs.Text()] = true
   }
   gitLog, e := popen(
      "git", "log", "-m",
      "--name-only", "--relative", "--pretty=format:%ct", ".",
   )
   check(e)
   for len(files) > 0 {
      gitLog.Scan()
      sec, e := strconv.ParseInt(gitLog.Text(), 10, 64)
      check(e)
      unix := time.Unix(sec, 0)
      for gitLog.Scan() {
         name := gitLog.Text()
         if name == "" {
            break
         }
         if ! files[name] {
            continue
         }
         os.Chtimes(name, unix, unix)
         delete(files, name)
      }
   }
}

It is similar to this answer. It builds up a file list like that answer, but it builds from git ls-files instead of just looking in the working directory. This solves the problem of excluding .git, and it also solves the problem of untracked files. Also, that answer fails if the last commit of a file was a merge commit, which I solved with git log -m. Like the other answer, will stop once all files are found, so it doesn't have to read all the commits.

For example with git/git, as of this posting it only had to read 182 commits. Also it ignores old files from the history as needed, and it won't touch a file that has already been touched. Finally, it is faster than the other solution. Results with git/git repo:

PS C:\git> Measure-Command { ..\git-touch }
Milliseconds      : 470
Related