azureazure-devopsazure-pipelines

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.


Solution

  • 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