Search code examples
gitshellazure-devopsazure-repos

Export git history of all files in a specific folder in Azure Repos for a specific date range


Salesforce Folder structure as below containing numerous classes and meta xml's:

Project
 --src
   --classes
       -- Class A
       -- Class A-Meta.xml
       -- Class B
       -- Class B-Meta.xml
       -- Class N

Problem statement: For each class, I need

  1. The history within a date range
  2. Output should contain File name, commit id and author name who have made commits in this file within this date range.
  3. Export this information in excel/csv/word

Sample output

 Classname  Author commit
 Class A    Dev1   abcd
 Class A    Dev2   pqrs
 Class A    Dev3   uvwz
 Class B    Dev9   yuot
 Class B    Dev1   qwew

I am using VSTS Azure Repos. Open to use git log or any other way of getting this done quickly.


Solution

    1. The history within a date range

    We can use this REST API to retrieve git commits for a project in a date range, we can get commit ID, author and committer Info.

    Sample:

    GET https://dev.azure.com/{Org name}/_apis/git/repositories/{repositoryId}/commits?searchCriteria.toDate=6/16/2018 12:00:00 AM&searchCriteria.fromDate=6/14/2018 12:00:00 AM&api-version=5.0
    

    We can get the commit Folder name via commit ID

    GET https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repositoryId}/commits/{commitId}/changes?api-version=6.0-preview.1
    

    And get the detail commit info with below API

    Get https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repositoryId}/commits/{commitId}?api-version=6.0-preview.1 
    

    Power shell sample:

    $connectionToken="{pat}"
    $base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($connectionToken)"))
    $Commits = "https://dev.azure.com/{org name}/_apis/git/repositories/{repo id}/commits?searchCriteria.toDate=9/15/2020 12:00:00 AM&searchCriteria.fromDate=9/1/2020 12:00:00 AM&api-version=5.0" 
    $CommitInfo = Invoke-RestMethod -Uri $Commits -Headers @{authorization = "Basic $base64AuthInfo"} -Method Get
    
    ForEach ($ID in $CommitInfo.value.commitId)
    {
        Write-Host $ID
    
        $url = "https://dev.azure.com/{org name}/{project name}/_apis/git/repositories/{repo id}/commits/$($ID)?api-version=6.0-preview.1"
        $base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($connectionToken)"))
        $CommitDetail = Invoke-RestMethod -Uri $url -Headers @{authorization = "Basic $base64AuthInfo"} -Method Get
        Write-Host "commit ID is" $CommitDetail.commitId "author is" $CommitDetail.author.name "committer is" $CommitDetail.committer.name
    
    }
    

    Result:

    enter image description here