1// SPDX-FileCopyrightText: Amolith <amolith@secluded.site>
  2//
  3// SPDX-License-Identifier: AGPL-3.0-or-later
  4
  5package main
  6
  7import (
  8	"context"
  9	"fmt"
 10	"os"
 11	"os/exec"
 12	"runtime/debug"
 13	"strings"
 14
 15	"github.com/charmbracelet/fang"
 16	"github.com/spf13/cobra"
 17)
 18
 19var (
 20	commitType     string
 21	message        string
 22	trailers       []string
 23	body           string
 24	scope          string
 25	breakingChange bool
 26)
 27
 28var rootCmd = &cobra.Command{
 29	Use:   "formatted-commit",
 30	Short: "Create conventionally formatted Git commits",
 31	Long: `formatted-commit helps you create well-formatted Git commits that follow
 32the Conventional Commits specification with proper subject length validation,
 33body wrapping, and trailer formatting.`,
 34	Example: `
 35# With co-author
 36formatted-commit -t feat -m "do a thing" -T "Crush <crush@charm.land>"
 37
 38# Breaking change with longer body
 39formatted-commit -t feat -m "do a thing that borks a thing" -B "$(cat <<'EOF'
 40Multi-line
 41- Body
 42- Here
 43
 44This is what borked because of new shiny, this is how migrate
 45EOF
 46)"
 47
 48# Including scope for more precise changes
 49formatted-commit -t refactor -s "web/git-bug" -m "fancy shmancy" \
 50  -b "Had to do a weird thing because..."
 51`,
 52	RunE: func(cmd *cobra.Command, args []string) error {
 53		subject, err := buildAndValidateSubject(commitType, scope, message, breakingChange)
 54		if err != nil {
 55			return err
 56		}
 57
 58		var commitMsg strings.Builder
 59		commitMsg.WriteString(subject)
 60
 61		if body != "" {
 62			formattedBody, err := formatBody(body)
 63			if err != nil {
 64				return fmt.Errorf("failed to format body: %w", err)
 65			}
 66			commitMsg.WriteString("\n\n")
 67			commitMsg.WriteString(formattedBody)
 68		}
 69
 70		if len(trailers) > 0 {
 71			trailersBlock, err := buildTrailersBlock(trailers)
 72			if err != nil {
 73				return fmt.Errorf("failed to build trailers: %w", err)
 74			}
 75			commitMsg.WriteString("\n\n")
 76			commitMsg.WriteString(trailersBlock)
 77		}
 78
 79		gitCmd := exec.Command("git", "commit", "-F", "-")
 80		gitCmd.Stdout = os.Stdout
 81		gitCmd.Stderr = os.Stderr
 82
 83		stdin, err := gitCmd.StdinPipe()
 84		if err != nil {
 85			return fmt.Errorf("failed to create stdin pipe: %w", err)
 86		}
 87
 88		if err := gitCmd.Start(); err != nil {
 89			return fmt.Errorf("failed to start git command: %w", err)
 90		}
 91
 92		if _, err := stdin.Write([]byte(commitMsg.String())); err != nil {
 93			return fmt.Errorf("failed to write to git stdin: %w", err)
 94		}
 95
 96		if err := stdin.Close(); err != nil {
 97			return fmt.Errorf("failed to close stdin: %w", err)
 98		}
 99
100		if err := gitCmd.Wait(); err != nil {
101			return fmt.Errorf("git commit failed: %w", err)
102		}
103
104		return nil
105	},
106}
107
108func init() {
109	rootCmd.Flags().StringVarP(&commitType, "type", "t", "", "commit type (required)")
110	rootCmd.Flags().StringVarP(&message, "message", "m", "", "commit message (required)")
111	rootCmd.Flags().StringArrayVarP(&trailers, "trailer", "T", []string{}, "trailer in 'Sentence-case-key: value' format (optional, repeatable)")
112	rootCmd.Flags().StringVarP(&body, "body", "b", "", "commit body (optional)")
113	rootCmd.Flags().StringVarP(&scope, "scope", "s", "", "commit scope (optional)")
114	rootCmd.Flags().BoolVarP(&breakingChange, "breaking", "B", false, "mark as breaking change (optional)")
115
116	if err := rootCmd.MarkFlagRequired("type"); err != nil {
117		panic(err)
118	}
119	if err := rootCmd.MarkFlagRequired("message"); err != nil {
120		panic(err)
121	}
122}
123
124func buildAndValidateSubject(commitType, scope, message string, breaking bool) (string, error) {
125	var subject strings.Builder
126
127	subject.WriteString(commitType)
128
129	if scope != "" {
130		subject.WriteString("(")
131		subject.WriteString(scope)
132		subject.WriteString(")")
133	}
134
135	if breaking {
136		subject.WriteString("!")
137	}
138
139	subject.WriteString(": ")
140	subject.WriteString(message)
141
142	result := subject.String()
143	length := len(result)
144
145	if length > 50 {
146		exceededBy := length - 50
147		truncated := result[:50] + "…"
148		return "", fmt.Errorf("subject exceeds 50 character limit by %d:\n%s", exceededBy, truncated)
149	}
150
151	return result, nil
152}
153
154func main() {
155	ctx := context.Background()
156
157	var version string
158	if info, ok := debug.ReadBuildInfo(); ok {
159		version = info.Main.Version
160	}
161	if version == "" || version == "(devel)" {
162		version = "dev"
163	}
164
165	if err := fang.Execute(ctx, rootCmd,
166		fang.WithVersion(version),
167		fang.WithoutCompletions(),
168	); err != nil {
169		os.Exit(1)
170	}
171}