GitLab & GitHub Auto-Fix with sonar_autofix()
Source:vignettes/gitlab-autofix.Rmd
gitlab-autofix.RmdOverview
sonar_autofix() is a generic function
for automatic code fixes with Git platform integration. It runs
sonar_fix() to correct code issues, then commits changes
and creates a Merge Request (GitLab) or Pull Request (GitHub).
The function auto-detects the CI environment:
| Platform | Detection | Output |
|---|---|---|
| GitLab |
GITLAB_CI or CI_PROJECT_ID set |
Merge Request via API v4 |
| GitHub |
GITHUB_ACTIONS set |
Pull Request via gh CLI |
Quick start
One-liner (auto-detect)
The function automatically detects whether you’re in GitLab CI or GitHub Actions.
GitLab CI
sonar_autofix(provider = "gitlab")Requires GITLAB_TOKEN or CI_JOB_TOKEN
environment variable.
GitHub Actions
sonar_autofix(provider = "github")Requires gh CLI installed and authenticated, or
GITHUB_TOKEN set.
Parameters
Provider selection
# Auto-detect
sonar_autofix(provider = "auto")
# Force GitLab
sonar_autofix(provider = "gitlab")
# Force GitHub
sonar_autofix(provider = "github")Branch and target
sonar_autofix(
branch = "auto/style-fix",
target_branch = "develop"
)Fix categories
# Only formatting and spacing
sonar_autofix(fixes = c("styler", "spacing", "cleanup"))Dry-run mode
# Simulate without modifying anything
sonar_autofix(dry_run = TRUE)Auto-detected CI variables
Token authentication
GitLab
Token resolution order: 1. GITLAB_TOKEN environment
variable 2. PERSONAL_ACCESS_TOKEN environment variable 3.
CI_JOB_TOKEN (built-in GitLab CI token)
Setting up a Project Access Token: 1.
Settings > Access Tokens > Add new token 2. Token
name: rsonar-autofix 3. Role: Maintainer 4.
Scopes: write_repository, api 5. Add to
Settings > CI/CD > Variables as
GITLAB_TOKEN (masked)
How it works
sonar_autofix(provider = "gitlab")
│
├── 1. sonar_fix() → auto-correct code (16 fix categories)
├── 2. git checkout -b auto/rsonar-fix
├── 3. git add + git commit
├── 4. git push -f origin auto/rsonar-fix
└── 5. GitLab API → POST /merge_requests
or
gh pr create → Pull Request
Architecture
The function uses a common engine for Git operations and platform-specific connectors:
-
.run_git_operations()— Common: checkout, commit, push -
.create_gitlab_mr()— GitLab: Merge Request via API v4 -
.create_github_pr()— GitHub: Pull Request viaghCLI
See also
- Auto-Fix with sonar_fix() for detailed fix categories
- CI/CD Integration for general pipeline configuration
- Introduction to rsonar for a general overview