gunk-dev/the-valley

branchname.go

sourceb8e46aa6aaccmain's published tip history
2.4 KiB
1package cmd
2
3import (
4 "context"
5 "strings"
6
7 "the-valley/flow/internal/git"
8)
9
10// maxBranchSlug caps the descriptive part of a derived branch name.
11const maxBranchSlug = 40
12
13// defaultBranchName names a new run's branch <slug>-<tail>, where tail is the
14// run ID's random tail and slug comes from the first of the issue title, the
15// prompt's first "# " heading, and the prompt's first non-empty line that
16// yields one. It falls back to agent/<id> when none does or git rejects the
17// name.
18func defaultBranchName(ctx context.Context, id, repoName, issueTitle, prompt string) string {
19 heading, firstLine := briefTitles(prompt)
20 for _, src := range []string{issueTitle, heading, firstLine} {
21 slug := branchSlug(src, repoName)
22 if slug == "" {
23 continue
24 }
25 name := slug + "-" + id[strings.LastIndex(id, "-")+1:]
26 if git.CheckBranchName(ctx, name) != nil {
27 break
28 }
29 return name
30 }
31 return "agent/" + id
32}
33
34// briefTitles returns the text of the prompt's first level-1 Markdown heading
35// outside fenced code blocks, and the prompt's first non-empty line.
36func briefTitles(prompt string) (heading, firstLine string) {
37 var fence string
38 for _, line := range strings.Split(prompt, "\n") {
39 line = strings.TrimSpace(line)
40 if firstLine == "" {
41 firstLine = line
42 }
43 switch {
44 case fence != "":
45 if strings.HasPrefix(line, fence) {
46 fence = ""
47 }
48 case strings.HasPrefix(line, "```"), strings.HasPrefix(line, "~~~"):
49 fence = line[:3]
50 case strings.HasPrefix(line, "# "), strings.HasPrefix(line, "#\t"):
51 return strings.TrimSpace(line[1:]), firstLine
52 }
53 }
54 return "", firstLine
55}
56
57// branchSlug lowercases text without a leading "<repoName>:", joins its runs
58// of [a-z0-9] with single dashes, and cuts it at a word boundary to at most
59// maxBranchSlug characters.
60func branchSlug(text, repoName string) string {
61 text = strings.ToLower(strings.TrimSpace(text))
62 if repoName != "" {
63 text = strings.TrimPrefix(text, strings.ToLower(repoName)+":")
64 }
65 var b strings.Builder
66 gap := false
67 for _, r := range text {
68 if !('a' <= r && r <= 'z' || '0' <= r && r <= '9') {
69 gap = true
70 continue
71 }
72 if gap && b.Len() > 0 {
73 b.WriteByte('-')
74 }
75 gap = false
76 b.WriteRune(r)
77 }
78 slug := b.String()
79 if len(slug) <= maxBranchSlug {
80 return slug
81 }
82 if i := strings.LastIndexByte(slug[:maxBranchSlug+1], '-'); i > 0 {
83 return slug[:i]
84 }
85 return slug[:maxBranchSlug]
86}