aboutsummaryrefslogtreecommitdiffhomepage
path: root/cmd/git-extract-issue/main.go
blob: 2e9255d1f35ee5ea71ec896cf682474413fc4bf6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package main

import (
	"fmt"
	"os"
	"regexp"
)

func main() {
	argv := os.Args
	argc := len(argv)
	if argc != 2 {
		return
	}
	branchName := argv[1]
	fmt.Println(extractIssueNumberFromBranchName(branchName))
}

// * 123                       => #123
// * 123-suffix                => #123
// * feature/123               => #123
// * feature/123-suffix        => #123
// * feature/123-2             => #123
// * feature/prefix-123        => prefix-123
// * feature/prefix-123-suffix => prefix-123
func extractIssueNumberFromBranchName(branchName string) string {
	pattern := regexp.MustCompile(`\A(?:\w+/)?([A-Za-z][0-9A-Za-z]*-)?(\d+)(?:-\w+)*\z`)
	matches := pattern.FindSubmatch([]byte(branchName))
	if len(matches) != 3 {
		return ""
	}
	var prefix string
	if len(matches[1]) == 0 {
		prefix = "#"
	} else {
		prefix = string(matches[1])
	}
	return prefix + string(matches[2])
}