syntax

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 5 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

PkgGoDev

syntax

A fast, zero-dependency Go parser for Conventional Commits 1.0.0 that keeps exact source positions and original input bytes.

  • Strict validation (Parse) and diagnostic error recovery (Inspect)
  • Zero heap allocations for headers, bodies, gaps, and line scanning (1 allocation when footers exist)
  • Zero-copy field accessors and exact byte Span / 1-based line Position offsets
  • Lossless whitespace, line ending (LF / CRLF), and duplicate footer preservation

Requires Go 1.26 or later.

Install

go get github.com/conventionalcommit/syntax

Quick Start

package main

import (
	"fmt"
	"log"

	"github.com/conventionalcommit/syntax"
)

func main() {
	msg := "feat(api)!: replace query format\n\nKeep pagination consistent.\n\nRefs #84\nBREAKING CHANGE: drop v1 params"

	c, err := syntax.Parse(msg)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(c.Type())             // feat
	fmt.Println(c.Scope())            // api
	fmt.Println(c.Description())      // replace query format
	fmt.Println(c.Body())             // Keep pagination consistent.
	fmt.Println(c.IsBreakingChange()) // true

	for f := range c.Footers() {
		fmt.Printf("%s = %s (breaking: %v)\n", f.Token(), f.Value(), f.IsBreaking())
	}
}

Error Positions

When Parse rejects a commit, it returns a zero Commit and a *syntax.ParseError carrying a machine-readable Code and byte Offset. Use syntax.Locate to turn that offset into a 1-based line and column:

c, err := syntax.Parse(msg)
if err != nil {
	var pe *syntax.ParseError
	if errors.As(err, &pe) {
		pos := syntax.Locate(msg, pe.Offset)
		fmt.Printf("%s at line %d, col %d\n", pe.Code, pos.Line, pos.Column)
	}
	return err
}

Linting and Recovery

For linters and tools that want all syntax errors plus any recoverable structure in malformed input, use Inspect:

res := syntax.Inspect(" feat:missing space\nbody without blank line")

if res.Structured {
	// Fields could still be delimited cleanly.
	fmt.Println("type:", res.Commit.Type())
	fmt.Println("indent:", res.Commit.Indent())
	fmt.Println("body gap blank lines:", res.Commit.BodyGap().BlankLines)
}

for _, diag := range res.Diagnostics {
	pos := res.Commit.Position(diag.Offset)
	fmt.Printf("%d:%d %s\n", pos.Line, pos.Column, diag)
}

When res.Valid() is true (res.Structured && len(res.Diagnostics) == 0), Parse accepts the same message with the exact same fields.

Notes on Behaviour

  • Zero-copy slicing: Commit and Footer accessors slice the original input string without copying. Retaining a Commit, Footer, or returned substring can retain the original string in memory.
  • Line endings and gaps: BodyGap() and FooterGap() report raw separator spans and blank line counts without stripping or normalizing \n and \r\n.
  • Footer detection: Footers follow the Conventional Commits token rules (Token: value, Token #value, BREAKING CHANGE: value, and multiline continuations) at the end of the message. Duplicate tokens are preserved in source order.

Performance

On typical single-line and multi-section messages, syntax.Parse runs in ~83 ns (0 allocs) for headers and ~724 ns (1 alloc) for full commits with body and footers, scaling linearly at ~380 MB/s on 1 MB bodies.

See BENCHMARKS.md for local side-by-side numbers comparing syntax, the previous parser, leodido/go-conventionalcommits, conventional-commits-parser, and @commitlint/parse.

API Documentation

Full package documentation is available on pkg.go.dev.

Development

go test ./...
go test -race ./...
go vet ./...
go test -run '^$' -bench . -benchmem
go test -run '^$' -fuzz '^FuzzParse$' -fuzztime=20s ./test

Licence

MIT

Documentation

Overview

Package syntax parses Conventional Commits while preserving source bytes.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Commit

type Commit struct {
	// contains filtered or unexported fields
}

Commit is a read-only parsed message. Copies share the original input and footer storage. Retaining any field may retain the full input allocation. Its zero value is safe to inspect.

func Parse

func Parse(input string) (Commit, error)

Parse reads one Conventional Commit. Successful fields reference input without copying. Failure returns a zero Commit and a *ParseError, with no partial result.

Example
package main

import (
	"fmt"

	"github.com/conventionalcommit/syntax"
)

func main() {
	c, err := syntax.Parse("build(cache)!: replace archive index\n\nRefs #84")
	if err != nil {
		panic(err)
	}
	fmt.Println(c.Type(), c.Scope(), c.IsBreakingChange())
	entry := c.FooterAt(0)
	fmt.Println(entry.Token())
	fmt.Println(entry.Value())
}
Output:
build cache true
Refs
84

func (Commit) Body

func (c Commit) Body() string

func (Commit) BodyGap

func (c Commit) BodyGap() Gap

BodyGap describes the separator between the header and body. Inspection can expose a present body with zero blank lines and a corresponding diagnostic.

func (Commit) BodyLines

func (c Commit) BodyLines() iter.Seq[Line]

BodyLines iterates over lines in Body(), yielding zero lines when absent.

func (Commit) BodySpan

func (c Commit) BodySpan() Span

func (Commit) Description

func (c Commit) Description() string

func (Commit) DescriptionSpan

func (c Commit) DescriptionSpan() Span

func (Commit) Footer

func (c Commit) Footer() string

func (Commit) FooterAt

func (c Commit) FooterAt(index int) Footer

FooterAt returns a footer by value. It panics for an out-of-range index.

func (Commit) FooterCount

func (c Commit) FooterCount() int

func (Commit) FooterGap

func (c Commit) FooterGap() Gap

FooterGap describes the separator before the footer section, following the body if present and the header otherwise.

func (Commit) FooterLines

func (c Commit) FooterLines() iter.Seq[Line]

FooterLines iterates over lines in Footer(), yielding zero lines when absent.

func (Commit) FooterSpan

func (c Commit) FooterSpan() Span

func (Commit) Footers

func (c Commit) Footers() iter.Seq[Footer]

Footers iterates over all parsed footers in source order.

func (Commit) HasBody

func (c Commit) HasBody() bool

func (Commit) HasBreakingFooter

func (c Commit) HasBreakingFooter() bool

HasBreakingFooter reports an uppercase breaking footer marker. During inspection its value can be invalid; diagnostics describe that separately.

func (Commit) HasFooter

func (c Commit) HasFooter() bool

func (Commit) HasHeaderBang

func (c Commit) HasHeaderBang() bool

HasHeaderBang reports a bang immediately before the header colon.

func (Commit) HasScope

func (c Commit) HasScope() bool

func (Commit) Header

func (c Commit) Header() string

func (Commit) HeaderBangSpan

func (c Commit) HeaderBangSpan() Span

HeaderBangSpan locates the header bang, or returns the zero span if absent.

func (Commit) HeaderSeparator

func (c Commit) HeaderSeparator() string

func (Commit) HeaderSeparatorSpan

func (c Commit) HeaderSeparatorSpan() Span

func (Commit) HeaderSpan

func (c Commit) HeaderSpan() Span

func (Commit) Indent

func (c Commit) Indent() string

Indent returns leading horizontal whitespace before Type, if recovered by Inspect.

func (Commit) IndentSpan

func (c Commit) IndentSpan() Span

IndentSpan locates leading horizontal whitespace before Type, or returns zero if absent.

func (Commit) IsBreakingChange

func (c Commit) IsBreakingChange() bool

func (Commit) Lines

func (c Commit) Lines(span Span) LineIterator

Lines visits a source range with offsets relative to Message(), including when the range is empty. Invalid ranges panic like ordinary slice bounds.

func (Commit) Message

func (c Commit) Message() string

func (Commit) Position

func (c Commit) Position(offset int) Position

Position converts a zero-based byte offset in Message() into a 1-based line and byte column.

func (Commit) Scope

func (c Commit) Scope() string

func (Commit) ScopeSpan

func (c Commit) ScopeSpan() Span

func (Commit) Text

func (c Commit) Text(span Span) string

func (Commit) Trailing

func (c Commit) Trailing() string

Trailing returns terminal line endings after the last content section.

func (Commit) TrailingSpan

func (c Commit) TrailingSpan() Span

TrailingSpan locates terminal line endings after the last content section.

func (Commit) Type

func (c Commit) Type() string

func (Commit) TypeSpan

func (c Commit) TypeSpan() Span

type ErrorCode

type ErrorCode uint8

ErrorCode identifies a stable category of parsing failure.

const (
	InvalidEncoding ErrorCode = iota + 1
	InvalidCharacter
	InvalidType
	InvalidScope
	InvalidSeparator
	InvalidDescription
	InvalidSectionSeparator
	InvalidFooterValue
)

func (ErrorCode) String

func (c ErrorCode) String() string
type Footer struct {
	// contains filtered or unexported fields
}

Footer represents one parsed footer entry. Duplicate tokens are kept.

func (Footer) IsBreaking

func (f Footer) IsBreaking() bool

IsBreaking reports whether this footer uses an uppercase breaking token.

func (Footer) Separator

func (f Footer) Separator() Separator

func (Footer) SeparatorSpan

func (f Footer) SeparatorSpan() Span

SeparatorSpan returns the delimiter span between Token and Value, or zero if absent.

func (Footer) Span

func (f Footer) Span() Span

Span returns the range from the start of Token to the end of Value.

func (Footer) Token

func (f Footer) Token() string

func (Footer) TokenSpan

func (f Footer) TokenSpan() Span

func (Footer) Value

func (f Footer) Value() string

func (Footer) ValueSpan

func (f Footer) ValueSpan() Span

type Gap

type Gap struct {
	Span       Span
	BlankLines int
}

Gap describes the raw line-ending separator before a present body or footer. Span includes the preceding section's line ending. BlankLines excludes that first ending. An absent section returns the zero gap.

func (Gap) IsZero

func (g Gap) IsZero() bool

IsZero reports whether g represents an absent separator.

type Inspection

type Inspection struct {
	Commit      Commit
	Diagnostics []ParseError
	Structured  bool
}

Inspection contains source facts and diagnostics for linting. Structured is true when the header identifies the fields unambiguously, even if invalid. Otherwise only Message(), Header(), HeaderSpan(), and raw Lines are available. Diagnostics are in source order, except byte validation precedes grammar. The caller owns the diagnostic slice; changing it cannot affect Commit.

func Inspect

func Inspect(input string) Inspection

Inspect retains recoverable fields without repairing or normalising input. Parse remains the strict entry point. No diagnostics means Parse would accept the same input and produce the same fields. Invalid bytes or an ambiguous header stop structural recovery; callers can still inspect raw source lines.

Example
package main

import (
	"fmt"

	"github.com/conventionalcommit/syntax"
)

func main() {
	r := syntax.Inspect("feat:reload\nBody text.")
	fmt.Println(r.Structured, len(r.Diagnostics))
	fmt.Println(r.Commit.Type(), r.Commit.Description())
	fmt.Println(r.Commit.BodyGap().BlankLines)
}
Output:
true 2
feat reload
0

func (Inspection) Valid

func (i Inspection) Valid() bool

Valid reports whether the message parsed structurally with zero diagnostics.

type Line

type Line struct {
	Content Span
	Ending  Span
}

Line separates content from its line ending using byte positions.

type LineIterator

type LineIterator struct {
	// contains filtered or unexported fields
}

LineIterator visits lines without allocating a collection. Its zero value visits one empty line. Copies advance independently and retain the input.

func Lines

func Lines(input string) LineIterator

Lines iterates raw bytes without validating them. A final newline produces an empty last line, and empty input produces one empty line. Standalone CR is content; CR immediately followed by LF belongs to the line ending.

Example
package main

import (
	"fmt"

	"github.com/conventionalcommit/syntax"
)

func main() {
	it := syntax.Lines("a\r\nb\n")
	for line, ok := it.Next(); ok; line, ok = it.Next() {
		fmt.Println(line.Content.Len(), line.Ending.Len())
	}
}
Output:
1 2
1 1
0 0

func (*LineIterator) Next

func (it *LineIterator) Next() (Line, bool)

Next returns the next line and whether one was available. After exhaustion it returns a zero Line and false on every subsequent call.

type ParseError

type ParseError struct {
	Code   ErrorCode
	Offset int
}

ParseError locates a failure in the original input. Offset is a zero-based byte position and may equal the input length for missing content.

func (*ParseError) Error

func (e *ParseError) Error() string

type Position

type Position struct {
	Line   int
	Column int
}

Position identifies a 1-based line number and byte column within a message.

func Locate

func Locate(input string, offset int) Position

Locate converts a zero-based byte offset in input into a 1-based line and byte column. Out-of-range offsets are clamped to [0, len(input)].

type Separator

type Separator uint8

Separator identifies the punctuation separating a footer token and value.

const (
	Colon Separator = iota + 1 // Colon followed by one ASCII space.
	Hash                       // One ASCII space followed by hash.
)

func (Separator) String

func (s Separator) String() string

type Span

type Span struct {
	Start int
	End   int
}

Span is a half-open byte range into a commit's original message. An absent field has the zero span.

func (Span) Contains

func (s Span) Contains(offset int) bool

Contains reports whether byte offset lies within [Start, End).

func (Span) IsEmpty

func (s Span) IsEmpty() bool

IsEmpty reports whether s covers zero bytes.

func (Span) IsZero

func (s Span) IsZero() bool

IsZero reports whether s is the zero span, indicating an absent field.

func (Span) Len

func (s Span) Len() int

Len returns the number of bytes in the range.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL