1 param (
2   $TargetDirectory, # should be in relative form from root of repo. EG: sdk/servicebus
3   $RootDirectory, # ideally $(Build.SourcesDirectory)
4   $VsoVariable = "" # target devops output variable
5 )
6 $target = $TargetDirectory.ToLower().Trim("/")
7 $codeOwnersLocation = Join-Path $RootDirectory -ChildPath ".github/CODEOWNERS"
8 $ownedFolders = @{}
9 
10 if (!(Test-Path $codeOwnersLocation)) {
11   Write-Host "Unable to find CODEOWNERS file in target directory $RootDirectory"
12   exit 1
13 }
14 
15 $codeOwnersContent = Get-Content $codeOwnersLocation
16 
17 foreach ($contentLine in $codeOwnersContent) {
18   if (-not $contentLine.StartsWith("#") -and $contentLine){
19     $splitLine = $contentLine -split "\s+"
20 
21     # CODEOWNERS file can also have labels present after the owner aliases
22     # gh aliases start with @ in codeowners. don't pass on to API calls
23     $ownedFolders[$splitLine[0].ToLower().Trim("/")] = ($splitLine[1..$($splitLine.Length)] `
24       | ? { $_.StartsWith("@") } `
25       | % { return $_.substring(1) }) -join ","
26   }
27 }
28 
29 $results = $ownedFolders[$target]
30 
31 if ($results) {
32   Write-Host "Found a folder $results to match $target"
33 
34   if ($VsoVariable) {
35     $alreadyPresent = [System.Environment]::GetEnvironmentVariable($VsoVariable)
36 
37     if ($alreadyPresent) {
38       $results += ",$alreadyPresent"
39     }
40     Write-Host "##vso[task.setvariable variable=$VsoVariable;]$results"
41   }
42 
43   return $results
44 }
45 else {
46   Write-Host "Unable to match path $target in CODEOWNERS file located at $codeOwnersLocation."
47   Write-Host ($ownedFolders | ConvertTo-Json)
48   return ""
49 }
50 
51