Restore a file's modification time in Git

后端 未结 9 1539
猫巷女王i
猫巷女王i 2020-11-29 01:13

I understand the default Git behaviour of updating the modification time every time it changes a file, but there are times when I want to restore a file\'s original modifica

9条回答
  •  借酒劲吻你
    2020-11-29 01:40

    This tool should do the trick. It updates mtimes to the author time and the atimes to the committer time. It would work as a checkout hook.

    Run with DEBUG=1 to get it to tell you exactly what it's doing.

    Notice also that it uses no modules, just basic perl, so should run anywhere.

    #!/usr/bin/perl
    
    # git-utimes: update file times to last commit on them
    # Tom Christiansen 
    
    use v5.10;      # for pipe open on a list
    use strict;
    use warnings;
    use constant DEBUG => !!$ENV{DEBUG};
    
    my @gitlog = ( 
        qw[git log --name-only], 
        qq[--format=format:"%s" %ct %at], 
        @ARGV,
    );
    
    open(GITLOG, "-|", @gitlog)             || die "$0: Cannot open pipe from `@gitlog`: $!\n";
    
    our $Oops = 0;
    our %Seen;
    $/ = ""; 
    
    while () {
        next if /^"Merge branch/;
    
        s/^"(.*)" //                        || die;
        my $msg = $1; 
    
        s/^(\d+) (\d+)\n//gm                || die;
        my @times = ($1, $2);               # last one, others are merges
    
        for my $file (split /\R/) {         # I'll kill you if you put vertical whitespace in our paths
            next if $Seen{$file}++;             
            next if !-f $file;              # no longer here
    
            printf "atime=%s mtime=%s %s -- %s\n", 
                    (map { scalar localtime $_ } @times), 
                    $file, $msg,
                                            if DEBUG;
    
            unless (utime @times, $file) {
                print STDERR "$0: Couldn't reset utimes on $file: $!\n";
                $Oops++;
            }   
        }   
    
    }
    exit $Oops;
    

提交回复
热议问题