get the last modification data of a file in git repo

陌路散爱 提交于 2021-02-06 02:25:32

问题


Im trying to find the command to get the last modified date of a file in a local git repo.

Created the repo and have done one commit. Had to edit one file and will commit this file but was wondering what the last modification data of the file in the repo is (not the commit date).

Have no gui onl command line.

git log ./path/to/filename.php

only gives me the commit date


回答1:


The correct way to do this is to use git log as follows.

git log -1 --pretty="format:%ci" /path/to/repo/anyfile.any)

-1 restricts it to the very last time the file changed

%ci is just one of the date formats you can choose from others here at https://git-scm.com/docs/pretty-formats

This method is fool proof and 100% accurate.




回答2:


MitchellK's answer exactly fit my needs, setting my local files' last written times to what's in git. Here's a little C# LinqPad script to automate the process:

var root = new DirectoryInfo(@"C:\gitlab\mydirectory\");

Directory.SetCurrentDirectory(root.FullName); // Give git some context

var files = root.GetFiles("*.*", SearchOption.AllDirectories);

foreach (var file in files)
{
  var results = Util.Cmd("git", 
                         $"log -1 --pretty=\"format:%ci\" \"{file.FullName}\"",
                         true);
  
  var lastUpdatedString = results.FirstOrDefault();
  if (lastUpdatedString == null)
  {
    Console.WriteLine($"{file.FullName} did not have a last updated date!!");
    continue;
  }
  
  var dt = DateTimeOffset.Parse(lastUpdatedString);
  if (file.LastWriteTimeUtc != dt.UtcDateTime)
  {
    Console.WriteLine($"{file.FullName}, {file.LastWriteTimeUtc} => {dt.UtcDateTime}");
    file.LastWriteTimeUtc = dt.UtcDateTime;
  }
  else
  {
    Console.WriteLine($"{file.FullName} already updated.");
  }
}



回答3:


Git doesn't record the last modification date, only the commit/author dates for a all commit (which can include more than one file).

You would need to run a script in order to amend a commit with the last modification date of a particular file (not very useful if said commit has more than one file in it).
See an example at "Git: Change timestamp after pushing".

Another option would be to record those timestamp in a separate file, and amend your commit that way: see "What's the equivalent of use-commit-times for git?".

That includes:

  1. mtimestore - core script providing 3 options:
    • -a (save all - for initialization in already existing repo (works with git-versed files)),
    • -s (to save staged changes), and
    • -r to restore them.
  2. pre-commit hook
  3. post-checkout hook

Incidentally, this is the post where I explained 5 years ago why Git doesn't record timestamps.



来源:https://stackoverflow.com/questions/22497597/get-the-last-modification-data-of-a-file-in-git-repo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!