git-ea/cmd/tag.go

123 lines
3.0 KiB
Go
Raw Normal View History

package cmd
import (
"context"
"errors"
"flag"
"fmt"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"github.com/AlecAivazis/survey/v2"
"github.com/go-git/go-git/v5"
"github.com/peterbourgon/ff/v3/ffcli"
)
var (
treeURL = "https://github.com/go-gitea/gitea/tree/%s"
versionRe = regexp.MustCompile(`v\d+\.\d+\.\d+`)
)
func (h *Handler) Tag() *ffcli.Command {
fs := flag.NewFlagSet("tag", flag.ContinueOnError)
pushFlag := fs.Bool("push", false, "Push immediately")
fs.BoolVar(pushFlag, "p", *pushFlag, "--push")
return &ffcli.Command{
Name: "tag",
FlagSet: fs,
ShortUsage: "tag <branch>",
ShortHelp: "tag makes a signed tag for `branch`",
Exec: func(ctx context.Context, args []string) error {
if err := h.checkInit(); err != nil {
return err
}
h.fetch(ctx)
var branch string
if len(args) > 0 {
branch = args[0]
}
if branch == "" {
var branches []string
remote, err := h.repo().Remote("upstream")
if err != nil {
return err
}
refs, err := remote.List(&git.ListOptions{})
if err != nil {
return err
}
for _, ref := range refs {
if ref.Name().IsBranch() {
branches = append(branches, strings.TrimPrefix(ref.Name().String(), "refs/heads/"))
}
}
sort.Strings(branches)
if err := survey.AskOne(&survey.Select{
Message: "Branch",
Options: branches,
}, &branch, survey.WithValidator(survey.Required)); err != nil {
return err
}
}
if !strings.HasPrefix(branch, "release") {
if !strings.HasPrefix(branch, "v") {
branch = fmt.Sprintf("v%s", branch)
}
branch = fmt.Sprintf("release/%s", branch)
}
var version string
if err := survey.AskOne(&survey.Input{
Message: "Version",
}, &version, survey.WithValidator(func(ans any) error {
if !versionRe.MatchString(fmt.Sprint(ans)) {
return errors.New("version isn't valid v$maj.$min.$")
}
return nil
})); err != nil {
return err
}
workspaceName := fmt.Sprintf("release-%s", version)
if err := h.Branch().ParseAndRun(ctx, []string{"--base", branch, workspaceName}); err != nil {
return err
}
var changelog string
if err := survey.AskOne(&survey.Editor{
Message: "Changelog",
FileName: "*.md",
}, &changelog, survey.WithValidator(survey.Required)); err != nil {
return err
}
fi, err := os.Create(filepath.Join(h.Config.WorkspaceBranch(workspaceName), "release.notes"))
if err != nil {
return err
}
if _, err := fi.WriteString(changelog); err != nil {
return err
}
if err := fi.Close(); err != nil {
return err
}
if err := run(ctx, h.Config.WorkspaceBranch(workspaceName), "git", "tag", "-s", "-F", "release.notes", version); err != nil {
return err
}
if *pushFlag {
return run(ctx, h.Config.WorkspaceBranch(workspaceName), "git", "push", "upstream", version)
}
fmt.Printf("cd %s && git push upstream %s \n", h.Config.WorkspaceBranch(workspaceName), version)
return nil
},
}
}