user264953
user264953

Reputation: 1957

How to get the github repo name in Azure pipeline

Are there any variables in Azure which I can use to get the name of the source folder(repository name). I tried using Build.SourcesDirectory and System.DefaultWorkingDirectory , both returned /Users/runner/work/1/s. I expect to get MyProjectFolderName which is the source directory of my project in github.

Upvotes: 5

Views: 8948

Answers (2)

krad
krad

Reputation: 1419

Build.Repository.Name is not entirely correct, this is the repo that triggered the build, so not necessarily the same as the root repo name. Eg in a scenario where a pipeline has repos a, b, and c defined, all with triggers. You will find that if a change in repo A triggered the pipeline Build.Repository.Name=a, However if where triggered by a change in c, then Build.Repository.Name=c So things get a little dirty. You can use the $PIPELINE_REPOSITORY_NAME env var maybe as that is static

Upvotes: 0

Bowman Zhu
Bowman Zhu

Reputation: 7146

If you checkout self repo(This is default situation), then just follow Daniel's suggestion is ok:

$(Build.Repository.Name)

yml file like this:

trigger:
- none

pool:
  vmImage: ubuntu-latest

steps:
- task: PythonScript@0
  inputs:
    scriptSource: 'inline'
    script: |
      str = "$(Build.Repository.Name)"
      
      str.split("/")
      
      #get the last name
      print(str.split("/")[-1])

enter image description here

If you only checkout one repo and not check out self, then just use below yml:

trigger:
- none

pool:
  vmImage: ubuntu-latest
resources:
  repositories:
  - repository: 222
    type: github
    name: xxx/222
    endpoint: xxx
  - repository: 333
    type: github
    name: xxx/333
    endpoint: xxx
variables:
 - name: checkoutreporef
   value: $[ resources.repositories['333'].name ]
steps:
- checkout: 333
- task: PythonScript@0
  inputs:
    scriptSource: 'inline'
    script: |
      str = "$(checkoutreporef)"
      
      str.split("/")
      
      #get the last name
      print(str.split("/")[-1])

enter image description here

If you checkout two and more repo, below yml will help you get the repo names:

trigger:
- none

pool:
  vmImage: ubuntu-latest
resources:
  repositories:
  - repository: 222
    type: github
    name: xxx/xxx
    endpoint: xxx
  - repository: 333
    type: github
    name: xxx/xxx
    endpoint: xxx
steps:
- checkout: 222
- checkout: 333
- task: PythonScript@0
  inputs:
    scriptSource: 'inline'
    script: |
      import os
      
      #get current sub folders name
      def getfoldersname():
          folders = [f for f in os.listdir('.') if os.path.isdir(f)]
          return folders
      #print each folder name
      def printfoldersname():
          for folder in getfoldersname():
              print(folder)
      
      printfoldersname()

enter image description here

Upvotes: 9

Related Questions