git-common.sh 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #!/usr/bin/env bash
  2. # Git-specific common functions for the git extension.
  3. # Extracted from scripts/bash/common.sh — contains only git-specific
  4. # branch validation and detection logic.
  5. # Check if we have git available at the repo root
  6. has_git() {
  7. local repo_root="${1:-$(pwd)}"
  8. { [ -d "$repo_root/.git" ] || [ -f "$repo_root/.git" ]; } && \
  9. command -v git >/dev/null 2>&1 && \
  10. git -C "$repo_root" rev-parse --is-inside-work-tree >/dev/null 2>&1
  11. }
  12. # Strip a single optional path segment (e.g. gitflow "feat/004-name" -> "004-name").
  13. # Only when the full name is exactly two slash-free segments; otherwise returns the raw name.
  14. spec_kit_effective_branch_name() {
  15. local raw="$1"
  16. if [[ "$raw" =~ ^([^/]+)/([^/]+)$ ]]; then
  17. printf '%s\n' "${BASH_REMATCH[2]}"
  18. else
  19. printf '%s\n' "$raw"
  20. fi
  21. }
  22. # Validate that a branch name matches the expected feature branch pattern.
  23. # Accepts sequential (###-* with >=3 digits) or timestamp (YYYYMMDD-HHMMSS-*) formats.
  24. # Logic aligned with scripts/bash/common.sh check_feature_branch after effective-name normalization.
  25. check_feature_branch() {
  26. local raw="$1"
  27. local has_git_repo="$2"
  28. # For non-git repos, we can't enforce branch naming but still provide output
  29. if [[ "$has_git_repo" != "true" ]]; then
  30. echo "[specify] Warning: Git repository not detected; skipped branch validation" >&2
  31. return 0
  32. fi
  33. local branch
  34. branch=$(spec_kit_effective_branch_name "$raw")
  35. # Accept sequential prefix (3+ digits) but exclude malformed timestamps
  36. # Malformed: 7-or-8 digit date + 6-digit time with no trailing slug (e.g. "2026031-143022" or "20260319-143022")
  37. local is_sequential=false
  38. if [[ "$branch" =~ ^[0-9]{3,}- ]] && [[ ! "$branch" =~ ^[0-9]{7}-[0-9]{6}- ]] && [[ ! "$branch" =~ ^[0-9]{7,8}-[0-9]{6}$ ]]; then
  39. is_sequential=true
  40. fi
  41. if [[ "$is_sequential" != "true" ]] && [[ ! "$branch" =~ ^[0-9]{8}-[0-9]{6}- ]]; then
  42. echo "ERROR: Not on a feature branch. Current branch: $raw" >&2
  43. echo "Feature branches should be named like: 001-feature-name, 1234-feature-name, or 20260319-143022-feature-name" >&2
  44. return 1
  45. fi
  46. return 0
  47. }