How to git diff on a Azure CI pipeline


I’m having a challenge to make git diff work in a Azure DevOps pipeline environment. Here is the pipeline script to compare the git HEAD with previous commit and only copy the files that have been changed. The git command runs fine locally, but it will fail in Azure pipeline because there is no HEAD^ in a CI run. Looking for suggestions if such comparison is feasible in Azure and how may I achieve that.

- task: [email protected]
    targetType: 'inline'
    script: |
      $targetfolder = "$(Build.StagingDirectory)" + "/"
      function CopyFiles{
          param( [string]$source )
          $target = $targetfolder + $source
          New-Item -Force $target
          copy-item $source $target -Force
      $changes = git diff --name-only --relative --diff-filter AMR HEAD^ HEAD .
      if ($changes -is [string]){ CopyFiles $changes }
          if ($changes -is [array])
              foreach ($change in $changes){ CopyFiles $change }

The error message looks like this:
enter image description here

I think in the Azure pipeline setup, when it checks out the reposition it only pulls the latest commit without the full commit history. That’s why when git tries to get previous commit like HEAD^, it couldn’t find anything.

Thanks a lot in advance for help!


I just found out a way to solve this. Posting the answer here for anyone who might have similar questions.

By default, the build agent performs a "shallow fetch" from the repo during pipeline build. This only fetches the latest commit without any other commit history. To fetch more commits or disable shallow fetch, refer to this doc from Microsoft. There is an option to specify the fetch depth or disable shallow fetch all together.

Hope it helps!

Answered By – got2nosth

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published