beads/internal/gitlab/mapping.go
maxinflection 16b1dd0a71
feat(gitlab): sync issue dependency links on push (#4294)
* feat(gitlab): sync issue dependency links on push

After issue content syncs, mirror local beads dependency edges as GitLab
issue links: blocks -> GitLab blocks/is_blocked_by (direction-normalized),
related/relates-to -> a single relates_to link per unordered pair (deduped).
Children of synced epics also keep the epic's milestone during a
dependency-only sync. Reports links_pushed in --json.

Additive only (never deletes remote links). License-aware: blocks/
is_blocked_by needs GitLab Premium/Ultimate; on instances without it the
link is reported as a single curated, non-fatal message (links_license_skipped
in JSON) while relates_to and milestones still apply. Genuine (non-license)
link failures remain real warnings, kept distinct from the license case.

Feature: max-efe

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(gitlab): address review — drop dead RelationMap, add push link parity

Follow-up to maphew's review on #4294.

- Delete the dead GitLab RelationMap: issueLinksToDependencies maps link
  types via hardcoded constants and ignores MappingConfig, so the field, its
  default, and the test assertion were dead config surface implying a
  configurability that does not exist. (Linear's RelationMap is untouched.)

- Give `bd gitlab push` dependency-link + epic-milestone parity with
  `bd gitlab sync`: extract the shared pushGitLabDependencyLinks helper from
  runGitLabSync's inline block and call it from runGitLabPush, scoped to the
  requested IssueIDs. Render push output natively so the link pass runs
  before the summary, dry-run ordering is correct, and the --json payload
  carries links_pushed / links_license_skipped / milestones_updated, matching
  sync in all output modes; also guard OnMessage under !jsonOutput.

Reviewed with /code-review + /codex (dry-run "Synced" line, output ordering,
and --json link-stat omission all caught and fixed here).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(gitlab): check outputJSON error in runGitLabSync (errcheck)

CI lint (first run on this branch, only-new-issues=false) flagged the
unchecked outputJSON return in the sync --json path. Return it, matching
runGitLabPush. Fixes the Lint / Build Artifacts / PR Lint failures.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(gitlab): carry closed state on push; surface failed-close in sync result

GitLab's POST /issues (and milestone/work-item creation) cannot set state,
so closed beads were pushed as opened issues and closed epics as active
milestones — milestone progress read 0/X even when all children were done.

- Close after create on all three paths (CreateIssue, createMilestone,
  createTaskWorkItem) via a best-effort follow-up state_event=close.
- BeadsIssueToGitLabFields emits state_event close/reopen so the update path
  flips both directions (reopening a bead reopens the GitLab issue). deferred
  stays open — only "done" work counts toward milestone completion.
- A failed best-effort close now records a warning on TrackerIssue.Warnings,
  which the engine drains into the sync result (visible in --json) instead of
  a bare stderr print that left --json reporting errors:0 while the issue was
  left open.

On close failure the created issue and its external_ref are still returned so
the next push doesn't create a duplicate (the push skip-guard means it won't
retry the close until the bead is next modified — hence the surfaced warning).

Reviewed via /code-review + Codex.

bd: max-9t6

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 08:00:41 -07:00

244 lines
6.9 KiB
Go

// Package gitlab provides client and data types for the GitLab REST API.
package gitlab
import (
"fmt"
"strings"
"github.com/steveyegge/beads/internal/types"
)
// MappingConfig configures how GitLab fields map to beads fields.
type MappingConfig struct {
PriorityMap map[string]int // priority label value → beads priority (0-4)
StateMap map[string]string // GitLab state → beads status
LabelTypeMap map[string]string // type label value → beads issue type
}
// DefaultMappingConfig returns the default mapping configuration.
// Uses exported mapping constants from types.go as the single source of truth.
func DefaultMappingConfig() *MappingConfig {
// Copy PriorityMapping to avoid external modification
priorityMap := make(map[string]int, len(PriorityMapping))
for k, v := range PriorityMapping {
priorityMap[k] = v
}
// Copy typeMapping to avoid external modification
labelTypeMap := make(map[string]string, len(typeMapping))
for k, v := range typeMapping {
labelTypeMap[k] = v
}
return &MappingConfig{
PriorityMap: priorityMap,
// StateMap maps GitLab states to beads statuses
// Note: GitLab uses "opened"/"closed"/"reopened", beads uses "open"/"closed"
StateMap: map[string]string{
"opened": StatusMapping["open"],
"closed": StatusMapping["closed"],
"reopened": StatusMapping["open"], // reopened maps to open
},
LabelTypeMap: labelTypeMap,
}
}
// priorityFromLabels extracts priority from GitLab labels.
// Returns default priority (2 = medium) if no priority label found.
func priorityFromLabels(labels []string, config *MappingConfig) int {
for _, label := range labels {
prefix, value := parseLabelPrefix(label)
if prefix == "priority" {
if p, ok := config.PriorityMap[strings.ToLower(value)]; ok {
return p
}
}
}
return 2 // Default to medium
}
// statusFromLabelsAndState determines beads status from GitLab labels and state.
// GitLab's closed state takes precedence over status labels.
func statusFromLabelsAndState(labels []string, state string, config *MappingConfig) string {
// Closed state always wins
if state == "closed" {
return "closed"
}
// Check for status label
for _, label := range labels {
prefix, value := parseLabelPrefix(label)
if prefix == "status" {
normalized := strings.ToLower(value)
switch normalized {
case "open":
return "open"
case "in_progress":
return "in_progress"
case "blocked":
return "blocked"
case "deferred":
return "deferred"
case "done":
return "closed"
}
}
}
// Default: map GitLab state to beads status
if s, ok := config.StateMap[state]; ok {
return s
}
return "open"
}
// typeFromLabels extracts issue type from GitLab labels.
// Checks both scoped (type::bug) and bare (bug) labels.
// Returns "task" if no type label found.
func typeFromLabels(labels []string, config *MappingConfig) string {
for _, label := range labels {
prefix, value := parseLabelPrefix(label)
if prefix == "type" {
if t, ok := config.LabelTypeMap[strings.ToLower(value)]; ok {
return t
}
}
// Also check bare labels (no prefix)
if prefix == "" {
if t, ok := config.LabelTypeMap[strings.ToLower(value)]; ok {
return t
}
}
}
return "task" // Default to task
}
// GitLabIssueToBeads converts a GitLab Issue to a beads Issue.
func GitLabIssueToBeads(gl *Issue, config *MappingConfig) *IssueConversion {
webURL := gl.WebURL
sourceSystem := fmt.Sprintf("gitlab:%d:%d", gl.ProjectID, gl.IID)
issue := &types.Issue{
Title: gl.Title,
Description: gl.Description,
ExternalRef: &webURL,
SourceSystem: sourceSystem,
IssueType: types.IssueType(typeFromLabels(gl.Labels, config)),
Priority: priorityFromLabels(gl.Labels, config),
Status: types.Status(statusFromLabelsAndState(gl.Labels, gl.State, config)),
Labels: filterNonScopedLabels(gl.Labels),
}
// Set estimate from weight (convert to minutes - assume 1 weight = 1 hour)
if gl.Weight > 0 {
estimatedMinutes := gl.Weight * 60
issue.EstimatedMinutes = &estimatedMinutes
}
// Set assignee from GitLab user
if gl.Assignee != nil {
issue.Assignee = gl.Assignee.Username
}
// Set timestamps
if gl.CreatedAt != nil {
issue.CreatedAt = *gl.CreatedAt
}
if gl.UpdatedAt != nil {
issue.UpdatedAt = *gl.UpdatedAt
}
// Convert issue links to dependencies if available.
deps := issueLinksToDependencies(gl.IID, gl.IssueLinksData, config)
return &IssueConversion{
Issue: issue,
Dependencies: deps,
}
}
// BeadsIssueToGitLabFields converts a beads Issue to GitLab API update fields.
func BeadsIssueToGitLabFields(issue *types.Issue, config *MappingConfig) map[string]interface{} {
fields := map[string]interface{}{
"title": issue.Title,
"description": issue.Description,
}
// Build labels from type, priority, and status
var labels []string
// Add type label
if issue.IssueType != "" {
labels = append(labels, "type::"+string(issue.IssueType))
}
// Add priority label
priorityLabel := priorityToLabel(issue.Priority)
if priorityLabel != "" {
labels = append(labels, "priority::"+priorityLabel)
}
// Add status label (if not open or closed - those are handled by GitLab state)
if issue.Status == types.StatusInProgress {
labels = append(labels, "status::in_progress")
} else if issue.Status == types.StatusBlocked {
labels = append(labels, "status::blocked")
} else if issue.Status == types.StatusDeferred {
labels = append(labels, "status::deferred")
}
// Add any existing non-scoped labels
labels = append(labels, issue.Labels...)
fields["labels"] = labels
// Set weight from estimate (convert minutes to weight - 60 minutes = 1 weight)
if issue.EstimatedMinutes != nil && *issue.EstimatedMinutes > 0 {
fields["weight"] = *issue.EstimatedMinutes / 60
}
// Set state_event so the GitLab issue state tracks the bead. On update this
// closes or reopens the issue; on create GitLab's POST /issues ignores
// state_event, so a closed bead is created open and closed by a follow-up
// update in Tracker.CreateIssue.
if issue.Status == types.StatusClosed {
fields["state_event"] = "close"
} else {
fields["state_event"] = "reopen"
}
return fields
}
// priorityToLabel converts beads priority (0-4) to GitLab priority label value.
func priorityToLabel(priority int) string {
switch priority {
case 0:
return "critical"
case 1:
return "high"
case 2:
return "medium"
case 3:
return "low"
case 4:
return "none"
default:
return "medium"
}
}
// filterNonScopedLabels returns only labels without scoped prefixes.
// Removes priority::*, status::*, and type::* labels.
func filterNonScopedLabels(labels []string) []string {
var filtered []string
for _, label := range labels {
prefix, _ := parseLabelPrefix(label)
// Skip scoped labels that we handle specially
if prefix == "priority" || prefix == "status" || prefix == "type" {
continue
}
filtered = append(filtered, label)
}
return filtered
}