Skip to main content

Fetch Last Matching GitHub Reference

The Fetch Last Matching GitHub Reference recipe fetches the last Git reference (branch or tag) of a GitHub repository that matches a pattern such as tags/v1 or heads/feature. The result is stored in a configurable environment variable and can be used throughout your build pipeline — for example for release pipelines or dynamic versioning.

Recipe IDjjideenschmiede/github-last-matching-ref
MarketplaceFetch Last Matching GitHub Reference
Source codeGitHub

How It Works​

The recipe uses the GitHub REST API to fetch all references that start with the given pattern and takes the last entry of the returned list. The prefix is removed from the name of the reference: refs/tags/v1.4.2 becomes v1.4.2, and refs/heads/feature/login becomes feature/login.

Installation​

The recipe requires TeamCity 2025.03 or later. How to add it to a build configuration is described under Using a Recipe.

Inputs​

InputRequiredDefaultDescription
RepositoryYes–GitHub repository in owner/repo format, for example JetBrains/teamcity-recipes
Reference PatternYestagsPattern that the reference has to start with
GitHub Access TokenNo–Personal access token for authenticated requests. Increases rate limits and allows access to private repositories.
Environment Variable NameNoGITHUB_LATEST_REFName of the environment variable that stores the reference

Patterns​

PatternResult
heads/All branches
tags/All tags
heads/featureBranches starting with feature
tags/v1.Tags starting with v1.
heads/mainThe branch main

Output​

ParameterDescriptionExample
env.GITHUB_LATEST_REFName of the last matching reference; the name of the variable follows the input Environment Variable Namev1.4.2

Example​

With the repository JetBrains/teamcity-recipes and the pattern tags/v1., the recipe returns the last tag of version 1. The value can be used directly in a subsequent command line step:

git checkout %env.GITHUB_LATEST_REF%

Error Messages​

MessageCause
No matching refs found for patternNo reference starts with the given pattern
Failed to fetch latest matching ref (HTTP 404)The repository does not exist, or it is private and no valid token was given
Failed to fetch latest matching ref (HTTP 401)The token is invalid or expired
Failed to fetch latest matching ref (HTTP 403)The rate limit of the GitHub API is reached or the token lacks the permission

Notes​

  • The order in which GitHub returns the references is decisive. It follows the name of the reference, not the creation date or the semantic version — v1.9 is therefore sorted after v1.10. Narrow down the pattern accordingly or use version numbers with a fixed number of digits.
  • If no matching reference is found, the recipe fails with an error.
  • Without a token, the rate limits of the GitHub API for anonymous requests apply.