Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
978 views
in Technique[技术] by (71.8m points)

yaml - Is there a short 7-digit version of $(SourceVersion) in Azure Devops?

I am trying to set our build names to a format of...

$(BuildDefinitionName)_$(versionMajor).$(versionMinor).$(versionPatch)+$(SourceBranchName).$(SourceVersion) e.g. OurBigLibraryCI_1.2.3+master.10bbc577

However I coudn't find any predefined variable holding the "short" (7-digit) version of the commit hash. $(SourceVersion) holds the full SHA-1 hash.

How would one shorten that in yaml based pipeline?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use traditional command substitution via backticks to obtain the short git hash (SHA-1), assuming that the code is being checked out in $(Build.SourcesDirectory):

  - bash: |
      short_hash=`git rev-parse --short=7 HEAD`  ## At least 7 digits, more if needed for uniqueness
      echo ""
      echo "Full git hash:  $(Build.SourceVersion)"
      echo "Short git hash: $short_hash"
      echo "##vso[task.setvariable variable=short_hash]$short_hash"  ## Store variable for subsequent steps
    workingDirectory: $(Build.SourcesDirectory)
    displayName: Get short git hash

Output:

Full git hash:  f8d63b1aaa20cf348a9b5fc6477ac80ed23d5ca0
Short git hash: f8d63b1

The following steps in the pipeline can then use the short hash via the variable $(short_hash).

(This is better than manually trimming down the full git hash to seven characters, since this will add extra digits if needed to uniquely identify the commit, see https://stackoverflow.com/a/21015031/1447415.)

Update: Improved version

The following improved version checks that the git hashes match (that the full hash starts with the short hash) and fails the step otherwise:

  - bash: |
      short_hash=`git rev-parse --short=7 HEAD`
      echo ""
      echo "Full git hash:  $(Build.SourceVersion)"
      echo "Short git hash: $short_hash"
      echo ""
      ## Fail step if full hash does not start with short hash
      if [[ $(Build.SourceVersion) != $short_hash* ]]; then
        echo "--> Hashes do not match! Aborting."
        exit 1
      fi
      echo "--> Hashes match. Storing short hash for subsequent steps."
      ## Store variable for subsequent steps
      echo "##vso[task.setvariable variable=short_hash]$short_hash"
    workingDirectory: $(Build.SourcesDirectory)
    displayName: Get short git hash

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...