Thursday, 6 September 2018

Getting Content of a File in VSTS Git Repo

GItHub has a easy way to get raw contents of a file by clicking on Raw button for any code file in GitHub, where it will redirect to url starting with ‘https://raw.githubusercontent.com/’. For example the PowerShell script here can be viewed as raw content or retrieved programmatically using PowerShell using Invoke-WebRequest with url  https://raw.githubusercontent.com/chamindac/VSTS_PS_Utils/master/CreateAzureWebApp/CreateAzureWebApp.ps1. Let’s look at possibility of retrieving raw content of a file in VSTS Git repo via VSTS REST API.

You can use the ‘Git Items Get’ REST API call to retrieve the content of a file with VSTS Git. Let’s try this with an example. Below is a simple PowerShell script that retrieves the content of a given file in VSTS. For the Personal Access Token (PAT) you need code read access scope for this script to work.

$vstsAccoutName = 'YourVstsAccountName'
$vstsTeamProjectName = 'YourTeamProject'
$vstsPAT = 'YourPAT'
$vstsBaseUrl = 'https://' + $vstsAccoutName + '.visualstudio.com'

$FileRepo = 'GItRepoName'
$FileRepoBranch = 'GitBranchName'
$FilePath = 'File Path' # example: src/test text/ProjectDepedancy.txt

$User=""

# Base64-encodes the Personal Access Token (PAT) appropriately
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $User,$vstsPAT)));
$vstsAuthHeader = @{Authorization=("Basic {0}" -f $base64AuthInfo)};

$Uri = $vstsBaseUrl+ '/' + $vstsTeamProjectName + '/_apis/git/repositories/' + $FileRepo  + '/items?path=' + $FilePath + '&$format=json&includeContent=true&versionDescriptor.version=' + $FileRepoBranch + '&versionDescriptor.versionType=branch&api-version=4.1'

$File = Invoke-RestMethod -Method Get -ContentType application/json -Uri $Uri -Headers $vstsAuthHeader

Write-Host $File.content


With the above script a file content in VSTS such as below can be retried as raw content.image

image

The URI parameter includeContent as true is required to enable get the content. If you do not specify the URI parameter $format with value json, you can get file content to $File variable directly in the PowerShell script. In that case you do not need to use $File.content to get the file contents. However, when you specify the $format=json you get file content with additional information such as commitId.image

The versionDescriptor.versionType is set to branch and versionDescriptor.version is used to define the branch of the Git repo where the file contains in above script.

No comments:

Popular Posts