create-new-feature.ps1 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. #!/usr/bin/env pwsh
  2. # Create a new feature
  3. [CmdletBinding()]
  4. param(
  5. [switch]$Json,
  6. [switch]$AllowExistingBranch,
  7. [switch]$DryRun,
  8. [string]$ShortName,
  9. [Parameter()]
  10. [long]$Number = 0,
  11. [switch]$Timestamp,
  12. [switch]$Help,
  13. [Parameter(Position = 0, ValueFromRemainingArguments = $true)]
  14. [string[]]$FeatureDescription
  15. )
  16. $ErrorActionPreference = 'Stop'
  17. # Show help if requested
  18. if ($Help) {
  19. Write-Host "Usage: ./create-new-feature.ps1 [-Json] [-DryRun] [-AllowExistingBranch] [-ShortName <name>] [-Number N] [-Timestamp] <feature description>"
  20. Write-Host ""
  21. Write-Host "Options:"
  22. Write-Host " -Json Output in JSON format"
  23. Write-Host " -DryRun Compute feature name and paths without creating directories or files"
  24. Write-Host " -AllowExistingBranch Reuse an existing feature directory if it already exists"
  25. Write-Host " -ShortName <name> Provide a custom short name (2-4 words) for the feature"
  26. Write-Host " -Number N Specify branch number manually (overrides auto-detection)"
  27. Write-Host " -Timestamp Use timestamp prefix (YYYYMMDD-HHMMSS) instead of sequential numbering"
  28. Write-Host " -Help Show this help message"
  29. Write-Host ""
  30. Write-Host "Examples:"
  31. Write-Host " ./create-new-feature.ps1 'Add user authentication system' -ShortName 'user-auth'"
  32. Write-Host " ./create-new-feature.ps1 'Implement OAuth2 integration for API'"
  33. Write-Host " ./create-new-feature.ps1 -Timestamp -ShortName 'user-auth' 'Add user authentication'"
  34. exit 0
  35. }
  36. # Check if feature description provided
  37. if (-not $FeatureDescription -or $FeatureDescription.Count -eq 0) {
  38. Write-Error "Usage: ./create-new-feature.ps1 [-Json] [-DryRun] [-AllowExistingBranch] [-ShortName <name>] [-Number N] [-Timestamp] <feature description>"
  39. exit 1
  40. }
  41. $featureDesc = ($FeatureDescription -join ' ').Trim()
  42. # Validate description is not empty after trimming (e.g., user passed only whitespace)
  43. if ([string]::IsNullOrWhiteSpace($featureDesc)) {
  44. Write-Error "Error: Feature description cannot be empty or contain only whitespace"
  45. exit 1
  46. }
  47. function Get-HighestNumberFromSpecs {
  48. param([string]$SpecsDir)
  49. [long]$highest = 0
  50. if (Test-Path $SpecsDir) {
  51. Get-ChildItem -Path $SpecsDir -Directory | ForEach-Object {
  52. # Match sequential prefixes (>=3 digits), but skip timestamp dirs.
  53. if ($_.Name -match '^(\d{3,})-' -and $_.Name -notmatch '^\d{8}-\d{6}-') {
  54. [long]$num = 0
  55. if ([long]::TryParse($matches[1], [ref]$num) -and $num -gt $highest) {
  56. $highest = $num
  57. }
  58. }
  59. }
  60. }
  61. return $highest
  62. }
  63. function ConvertTo-CleanBranchName {
  64. param([string]$Name)
  65. return $Name.ToLower() -replace '[^a-z0-9]', '-' -replace '-{2,}', '-' -replace '^-', '' -replace '-$', ''
  66. }
  67. # Load common functions (includes Get-RepoRoot and Resolve-Template)
  68. . "$PSScriptRoot/common.ps1"
  69. # Use common.ps1 functions which prioritize .specify
  70. $repoRoot = Get-RepoRoot
  71. Set-Location $repoRoot
  72. $specsDir = Join-Path $repoRoot 'specs'
  73. if (-not $DryRun) {
  74. New-Item -ItemType Directory -Path $specsDir -Force | Out-Null
  75. }
  76. # Function to generate branch name with stop word filtering and length filtering
  77. function Get-BranchName {
  78. param([string]$Description)
  79. # Common stop words to filter out
  80. $stopWords = @(
  81. 'i', 'a', 'an', 'the', 'to', 'for', 'of', 'in', 'on', 'at', 'by', 'with', 'from',
  82. 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had',
  83. 'do', 'does', 'did', 'will', 'would', 'should', 'could', 'can', 'may', 'might', 'must', 'shall',
  84. 'this', 'that', 'these', 'those', 'my', 'your', 'our', 'their',
  85. 'want', 'need', 'add', 'get', 'set'
  86. )
  87. # Convert to lowercase and extract words (alphanumeric only)
  88. $cleanName = $Description.ToLower() -replace '[^a-z0-9\s]', ' '
  89. $words = $cleanName -split '\s+' | Where-Object { $_ }
  90. # Filter words: remove stop words and words shorter than 3 chars (unless they're uppercase acronyms in original)
  91. $meaningfulWords = @()
  92. foreach ($word in $words) {
  93. # Skip stop words
  94. if ($stopWords -contains $word) { continue }
  95. # Keep words that are length >= 3 OR appear as uppercase in original (likely acronyms)
  96. if ($word.Length -ge 3) {
  97. $meaningfulWords += $word
  98. } elseif ($Description -match "\b$($word.ToUpper())\b") {
  99. # Keep short words if they appear as uppercase in original (likely acronyms)
  100. $meaningfulWords += $word
  101. }
  102. }
  103. # If we have meaningful words, use first 3-4 of them
  104. if ($meaningfulWords.Count -gt 0) {
  105. $maxWords = if ($meaningfulWords.Count -eq 4) { 4 } else { 3 }
  106. $result = ($meaningfulWords | Select-Object -First $maxWords) -join '-'
  107. return $result
  108. } else {
  109. # Fallback to original logic if no meaningful words found
  110. $result = ConvertTo-CleanBranchName -Name $Description
  111. $fallbackWords = ($result -split '-') | Where-Object { $_ } | Select-Object -First 3
  112. return [string]::Join('-', $fallbackWords)
  113. }
  114. }
  115. # Generate branch name
  116. if ($ShortName) {
  117. # Use provided short name, just clean it up
  118. $branchSuffix = ConvertTo-CleanBranchName -Name $ShortName
  119. } else {
  120. # Generate from description with smart filtering
  121. $branchSuffix = Get-BranchName -Description $featureDesc
  122. }
  123. # Warn if -Number and -Timestamp are both specified
  124. if ($Timestamp -and $Number -ne 0) {
  125. Write-Warning "[specify] Warning: -Number is ignored when -Timestamp is used"
  126. $Number = 0
  127. }
  128. # Determine branch prefix
  129. if ($Timestamp) {
  130. $featureNum = Get-Date -Format 'yyyyMMdd-HHmmss'
  131. $branchName = "$featureNum-$branchSuffix"
  132. } else {
  133. # Determine branch number from existing feature directories
  134. if ($Number -eq 0) {
  135. $Number = (Get-HighestNumberFromSpecs -SpecsDir $specsDir) + 1
  136. }
  137. $featureNum = ('{0:000}' -f $Number)
  138. $branchName = "$featureNum-$branchSuffix"
  139. }
  140. # GitHub enforces a 244-byte limit on branch names
  141. # Validate and truncate if necessary
  142. $maxBranchLength = 244
  143. if ($branchName.Length -gt $maxBranchLength) {
  144. # Calculate how much we need to trim from suffix
  145. # Account for prefix length: timestamp (15) + hyphen (1) = 16, or sequential (3) + hyphen (1) = 4
  146. $prefixLength = $featureNum.Length + 1
  147. $maxSuffixLength = $maxBranchLength - $prefixLength
  148. # Truncate suffix
  149. $truncatedSuffix = $branchSuffix.Substring(0, [Math]::Min($branchSuffix.Length, $maxSuffixLength))
  150. # Remove trailing hyphen if truncation created one
  151. $truncatedSuffix = $truncatedSuffix -replace '-$', ''
  152. $originalBranchName = $branchName
  153. $branchName = "$featureNum-$truncatedSuffix"
  154. Write-Warning "[specify] Branch name exceeded GitHub's 244-byte limit"
  155. Write-Warning "[specify] Original: $originalBranchName ($($originalBranchName.Length) bytes)"
  156. Write-Warning "[specify] Truncated to: $branchName ($($branchName.Length) bytes)"
  157. }
  158. $featureDir = Join-Path $specsDir $branchName
  159. $specFile = Join-Path $featureDir 'spec.md'
  160. if (-not $DryRun) {
  161. if ((Test-Path -LiteralPath $featureDir -PathType Container) -and -not $AllowExistingBranch) {
  162. if ($Timestamp) {
  163. Write-Error "Error: Feature directory '$featureDir' already exists. Rerun to get a new timestamp or use a different -ShortName."
  164. } else {
  165. Write-Error "Error: Feature directory '$featureDir' already exists. Please use a different feature name or specify a different number with -Number."
  166. }
  167. exit 1
  168. }
  169. New-Item -ItemType Directory -Path $featureDir -Force | Out-Null
  170. if (-not (Test-Path -PathType Leaf $specFile)) {
  171. $template = Resolve-Template -TemplateName 'spec-template' -RepoRoot $repoRoot
  172. if ($template -and (Test-Path $template)) {
  173. # Read the template content and write it to the spec file with UTF-8 encoding without BOM
  174. $content = [System.IO.File]::ReadAllText($template)
  175. $utf8NoBom = New-Object System.Text.UTF8Encoding($false)
  176. [System.IO.File]::WriteAllText($specFile, $content, $utf8NoBom)
  177. } else {
  178. New-Item -ItemType File -Path $specFile -Force | Out-Null
  179. }
  180. }
  181. # Persist to .specify/feature.json so downstream commands can find the feature
  182. Save-FeatureJson -RepoRoot $repoRoot -FeatureDirectory $featureDir
  183. # Set environment variables for the current session
  184. $env:SPECIFY_FEATURE = $branchName
  185. $env:SPECIFY_FEATURE_DIRECTORY = $featureDir
  186. }
  187. if ($Json) {
  188. $obj = [PSCustomObject]@{
  189. BRANCH_NAME = $branchName
  190. SPEC_FILE = $specFile
  191. FEATURE_NUM = $featureNum
  192. }
  193. if ($DryRun) {
  194. $obj | Add-Member -NotePropertyName 'DRY_RUN' -NotePropertyValue $true
  195. }
  196. $obj | ConvertTo-Json -Compress
  197. } else {
  198. Write-Output "BRANCH_NAME: $branchName"
  199. Write-Output "SPEC_FILE: $specFile"
  200. Write-Output "FEATURE_NUM: $featureNum"
  201. if (-not $DryRun) {
  202. Write-Output "SPECIFY_FEATURE set to: $branchName"
  203. Write-Output "SPECIFY_FEATURE_DIRECTORY set to: $featureDir"
  204. }
  205. }