Sub topic 9
Targeting branches and tags with ref name patterns
This chapter assumes you know what a ruleset is and can read the JSON body of a ruleset. It covers only which refs a ruleset applies to. Enforcement and bypass come later.
Where targeting lives
A ruleset has two settings that decide its scope:
targetis the kind of ref the ruleset covers:branchortag.conditions.ref_nameholds anincludelist and anexcludelist of patterns.
A ref is covered when it matches at least one include pattern and no exclude pattern. Exclusions win. An empty include list matches nothing, so a ruleset with no includes protects nothing.
Pattern syntax
Patterns use fnmatch syntax. The API accepts full ref names such as refs/heads/main. It also accepts two special values.
| Pattern | Meaning |
|---|---|
| `~DEFAULT_BRANCH` | The repository's current default branch, even if it is renamed later |
| `~ALL` | Every ref of the target type |
| `refs/heads/release/*` | `release/1.0`, but not `release/1.0/hotfix` |
| `refs/heads/release/**` | Everything under `release/`, at any depth |
| `refs/tags/v*` | Tags such as `v1.0.0` and `v2` |
| `refs/heads/hotfix-?` | `hotfix-1`, but not `hotfix-10` |
A single * does not match /. This is the most common targeting mistake. A rule for release/* silently misses release/2.x/rc1. Use ** when you want nested names.
Classic branch protection uses the same fnmatch idea. It also treats / as a boundary, so qa/* does not match qa/foo/bar there either.
Example: release branches and version tags
This ruleset covers every release branch except a scratch area. It blocks deletion and force pushes.
{
"name": "protect-release-branches",
"target": "branch",
"enforcement": "evaluate",
"conditions": {
"ref_name": {
"include": ["refs/heads/release/**"],
"exclude": ["refs/heads/release/scratch/**"]
}
},
"rules": [
{ "type": "deletion" },
{ "type": "non_fast_forward" }
]
}A second ruleset covers tags. It must use "target": "tag", and its patterns start with refs/tags/:
{
"name": "protect-version-tags",
"target": "tag",
"enforcement": "evaluate",
"conditions": {
"ref_name": {
"include": ["refs/tags/v*"],
"exclude": []
}
},
"rules": [
{ "type": "deletion" },
{ "type": "update" }
]
}Create either one with gh api --method POST repos/OWNER/REPO/rulesets --input FILE.json.
Checking your patterns
Don't guess whether a pattern matches. The endpoint gh api repos/OWNER/REPO/rules/branches/release/1.0/hotfix lists the rules that apply to that exact branch. If the list is empty, your pattern missed it. Run this check before you change enforcement from evaluate to active.
Exercise
A ruleset targets branches with include ["refs/heads/feature/*"]. Does it cover feature/login/ui? What change would cover it?
Show answer
No. A single * does not match /, so it covers feature/login but not feature/login/ui. Change the include pattern to refs/heads/feature/**.