Home > Enterprise >  How to find the git log or commit history for a specific file using PowerShell
How to find the git log or commit history for a specific file using PowerShell

Time:12-06

I wanted to find the commit history for a specific file/path using powershell. Based on the last commit message,if it was deleted i am invoking a deleted function. which it invokes a rest API to delete it from Azure else it will go to next.

Here what i am trying to do

  $commited_file_name = $([io.path]::GetFileNameWithoutExtension($_.Line)) #This gives Me the filename

  $path = $_.Line #This Gives me the complete Path. They change it dynamically based on the committed file in the Azure Devops Repo

by make using of the above lines i'm passing the following git commands to fetch commit history of a specic file. most of my files are Json files.

By referencing these two Find when a file was deleted in Git and How to find a deleted file in the project commit history. As i couldn't find how to do it via powershell.

Here is what i Did.

      #Tried to get the commit history using a Path
      $commit_log = git log --full-history -1 [$path]
      WriteDebug "Commit Log:$commit_log" #[However this is not returning anything ]

      #Then tried to get the commit history using a Filename
      $commit_file = git log --all --full-history -1 -- "**/$commited_file_name.json.*"
      WriteDebug  "Commit File history:$commit_file" #[This is also not returing anything]
      
      #And it is failing at this point and invoked the DotheNextTask function even if the last commit of the file was deleted.

      $filter_commit = $("$commit_file" | grep -c "Deleted")
      if ("$filter_commit" -ne 0 ) {
        Deletefile
      }
      else{
        DotheNextTask
      }

is there something i'm not doing right? or am i missing something here.

CodePudding user response:

I have updated the code and tested against it. Now it is displaying the output.

Please note, if you're using PowerShell, the hyphens have to be escaped: git log '--' [file path].

$commit_file = git log --all --full-history -1 $("**/$commited_file_name.*")
WriteDebug  "Commit File history:$commit_file" #[Fetches previous commit history from all branches for that specific file]
  • Related