Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
109 changes: 99 additions & 10 deletions .github/workflows/pre-commit.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,107 @@ on:
branches: [master, main, trunk]

jobs:
resolve-matrix:
name: Resolve Go Matrix
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.resolve.outputs.matrix }}
steps:
- name: Checkout repository
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1

- name: Resolve Go Versions
id: resolve
timeout-minutes: 2
run: |
python3 - << 'EOF'
import json
import os
import re
import sys
import urllib.request

def parse_version(v_str):
m = re.search(r'(\d+)\.(\d+)', v_str)
if not m:
return (0, 0)
return (int(m.group(1)), int(m.group(2)))

output_file = os.environ.get("GITHUB_OUTPUT")

def set_matrix_output(matrix_dict):
json_str = json.dumps(matrix_dict)
print(f"Setting matrix output: {json_str}", file=sys.stderr)
if output_file:
with open(output_file, "a", encoding="utf-8") as f:
f.write(f"matrix={json_str}\n")
else:
print(f"::set-output name=matrix::{json_str}")

default_matrix = {"go": ["go.mod"]}

# 1. Parse go.mod
mod_ver = (0, 0)
try:
with open("go.mod", "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if line.startswith("go "):
parts = line.split()
if len(parts) >= 2:
mod_ver = parse_version(parts[1])
break
except Exception as e:
print(f"Warning: failed to read go.mod: {e}", file=sys.stderr)

if mod_ver == (0, 0):
set_matrix_output(default_matrix)
sys.exit(0)

# 2. Fetch go.dev releases
try:
req = urllib.request.Request(
"https://go.dev/dl/?mode=json",
headers={"User-Agent": "dmlint-ci-matrix-resolver"}
)
with urllib.request.urlopen(req, timeout=10) as resp:
data = json.loads(resp.read().decode("utf-8"))
except Exception as e:
print(f"Warning: failed to fetch Go releases from go.dev: {e}", file=sys.stderr)
set_matrix_output(default_matrix)
sys.exit(0)

stables = [r for r in data if r.get("stable", False)]
if not stables:
set_matrix_output(default_matrix)
sys.exit(0)

stable_ver = parse_version(stables[0]["version"])
oldstable_ver = (0, 0)
for r in stables[1:]:
ver = parse_version(r["version"])
if ver < stable_ver:
oldstable_ver = ver
break

go_matrix = ["go.mod"]
if oldstable_ver > mod_ver:
go_matrix.append("oldstable")
if stable_ver > mod_ver and stable_ver != oldstable_ver:
go_matrix.append("stable")

set_matrix_output({"go": go_matrix})
EOF

pre-commit:
name: Build, Test & Pre-commit (${{ matrix.go }})
needs: resolve-matrix
runs-on: ubuntu-latest
env:
CI: "true"
strategy:
fail-fast: false
matrix:
go:
- go.mod
- oldstable
- stable
matrix: ${{ fromJSON(needs.resolve-matrix.outputs.matrix) }}

steps:
- name: Checkout repository
Expand Down Expand Up @@ -58,6 +147,10 @@ jobs:
GOTOOLCHAIN=auto go install golang.org/x/tools/cmd/stringer@latest
echo "$(go env GOPATH)/bin" >> "$GITHUB_PATH"

- name: Test Tools (make test-tools)
timeout-minutes: 3
run: make test-tools

- name: Generate (make generate)
timeout-minutes: 2
run: make generate
Expand All @@ -74,16 +167,12 @@ jobs:
timeout-minutes: 6
run: make test-ndebug

- name: Test Tools (make test-tools)
timeout-minutes: 3
run: make test-tools

# Run lint only for target version
- name: Install golangci-lint
if: matrix.go == 'go.mod'
timeout-minutes: 5
run: |
curl -sSfL https://golangci-lint.run/install.sh | sh -s -- -b "$(go env GOPATH)/bin" v2.11.2
curl -sSfL https://golangci-lint.run/install.sh | sh -s -- -b "$(go env GOPATH)/bin" v2.15.0

- name: Install pre-commit
if: matrix.go == 'go.mod'
Expand Down
1 change: 1 addition & 0 deletions .golangci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ linters:
- makezero
- mirror
- modernize
- intrange
- prealloc
- reassign
- unconvert
Expand Down
11 changes: 1 addition & 10 deletions cmd/dmlfmt/collector_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -419,16 +419,7 @@ func TestCollector_RelativeSourceDefaultExclusions(t *testing.T) {
"sub/nested.dml",
})

origWd, err := os.Getwd()
if err != nil {
t.Fatalf("failed to get current working directory: %v", err)
}
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("failed to chdir to %s: %v", tmpDir, err)
}
t.Cleanup(func() {
_ = os.Chdir(origWd)
})
t.Chdir(tmpDir)

cfg := &CLIConfig{
Include: DefaultIncludePattern,
Expand Down
8 changes: 3 additions & 5 deletions cmd/dmlfmt/pipeline.go
Original file line number Diff line number Diff line change
Expand Up @@ -360,10 +360,8 @@ func runPipeline(

// Processing Pool (CPU bound, workers concurrency)
var processWg sync.WaitGroup
for i := 0; i < max(workers, 1); i++ {
processWg.Add(1)
go func() {
defer processWg.Done()
for range max(workers, 1) {
processWg.Go(func() {
for job := range processChan {
writeChan <- processFormattingJob(
job,
Expand All @@ -373,7 +371,7 @@ func runPipeline(
stats,
)
}
}()
})
}

go func() {
Expand Down
6 changes: 2 additions & 4 deletions cmd/dmlfmt/report_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,7 @@ func TestReport_ConcurrentIncrements(t *testing.T) {
incrementsPerGoroutine := 100

for range numGoroutines {
wg.Add(1)
go func() {
defer wg.Done()
wg.Go(func() {
for range incrementsPerGoroutine {
r.IncrementReformatted()
r.IncrementUnchanged()
Expand All @@ -94,7 +92,7 @@ func TestReport_ConcurrentIncrements(t *testing.T) {
_ = r.IsEmpty()
_ = r.Render(false)
}
}()
})
}

wg.Wait()
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module github.com/timoschenko/dmltools

go 1.23
go 1.27

require github.com/antlr4-go/antlr/v4 v4.13.1

Expand Down
2 changes: 1 addition & 1 deletion pkg/dmlex/expression.go
Original file line number Diff line number Diff line change
Expand Up @@ -442,7 +442,7 @@ func WrapExpression(ctx IExpressionContext) ISimplifiedExpr {
members[i] = oid.GetStart()
// Walk children to find the operator (DOT or ARROW) immediately preceding this objident.
// The children of the context are: [Expression] [op0] [Objident0] [op1] [Objident1] ...
for j := 0; j < c.GetChildCount(); j++ {
for j := range c.GetChildCount() {
if c.GetChild(j) == oid {
// The operator is the child immediately before this objident
if j > 0 {
Expand Down
3 changes: 1 addition & 2 deletions pkg/dmlex/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,7 @@ func (p *dmlParser) checkDmlVersion(localctx IDmlTagContext) {
// UnimplementedVersion returns the unsupported version string if any error is EUNIMPL.
func (l *ErrorListener) UnimplementedVersion() string {
for _, e := range l.Errors {
var verErr *UnimplementedVersionError
if errors.As(e.Err, &verErr) {
if verErr, ok := errors.AsType[*UnimplementedVersionError](e.Err); ok {
return verErr.Version
}
}
Expand Down
24 changes: 8 additions & 16 deletions pkg/fs/stream/hashed_buffer.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,14 +64,10 @@ func NewHashedBufferFromStream(
data := sb.String()

hb := HashedBuffer{
baseStreamHash: baseStreamHash{
hash: inHasher.Sum(),
},
antlrStreamWrapper: antlrStreamWrapper{
filename: filename,
index: 0,
size: len(data),
},
hash: inHasher.Sum(),
filename: filename,
index: 0,
size: len(data),
data: data,
capacity: sb.Cap(),
}
Expand All @@ -88,14 +84,10 @@ func NewHashedBufferFromString(filename string, data string) *HashedBuffer {
}

return &HashedBuffer{
baseStreamHash: baseStreamHash{
hash: inHasher.Sum(),
},
antlrStreamWrapper: antlrStreamWrapper{
filename: filename,
index: 0,
size: len(data),
},
hash: inHasher.Sum(),
filename: filename,
index: 0,
size: len(data),
data: data,
capacity: len(data),
}
Expand Down
16 changes: 8 additions & 8 deletions pkg/fs/stream/hashed_buffer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -181,19 +181,19 @@ func TestHashedBuffer_LA_LookaheadAndLookback(t *testing.T) {

// Initial position: index 0
if got := buf.LA(1); got != int('h') {
t.Errorf("LA(1) = %q, want 'h'", got)
t.Errorf("LA(1) = %v, want 'h'", got)
}
if got := buf.LA(2); got != int('e') {
t.Errorf("LA(2) = %q, want 'e'", got)
t.Errorf("LA(2) = %v, want 'e'", got)
}
if got := buf.LA(3); got != int('l') {
t.Errorf("LA(3) = %q, want 'l'", got)
t.Errorf("LA(3) = %v, want 'l'", got)
}
if got := buf.LA(4); got != int('l') {
t.Errorf("LA(4) = %q, want 'l'", got)
t.Errorf("LA(4) = %v, want 'l'", got)
}
if got := buf.LA(5); got != int('o') {
t.Errorf("LA(5) = %q, want 'o'", got)
t.Errorf("LA(5) = %v, want 'o'", got)
}
if got := buf.LA(6); got != antlr.TokenEOF {
t.Errorf("LA(6) = %d, want TokenEOF", got)
Expand All @@ -210,13 +210,13 @@ func TestHashedBuffer_LA_LookaheadAndLookback(t *testing.T) {
// Consume 'h'
buf.Consume()
if got := buf.LA(-1); got != int('h') {
t.Errorf("LA(-1) after consume = %q, want 'h'", got)
t.Errorf("LA(-1) after consume = %v, want 'h'", got)
}
if got := buf.LA(1); got != int('e') {
t.Errorf("LA(1) after consume = %q, want 'e'", got)
t.Errorf("LA(1) after consume = %v, want 'e'", got)
}
if got := buf.LA(2); got != int('l') {
t.Errorf("LA(2) after consume = %q, want 'l'", got)
t.Errorf("LA(2) after consume = %v, want 'l'", got)
}

// Deep negative lookback (LA(-2)) should panic
Expand Down
14 changes: 5 additions & 9 deletions pkg/fs/stream/hashed_runes_buffer.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,15 +52,11 @@ func NewHashedRunesBufferFromStream(
reader := bufio.NewReaderSize(teeStream, allocSize)

hfs := HashedRunesBuffer{
baseStreamHash: baseStreamHash{
hash: Hash{},
},
antlrStreamWrapper: antlrStreamWrapper{
filename: filename,
index: 0,
size: 0,
},
data: make([]rune, 0, allocSize),
hash: Hash{},
filename: filename,
index: 0,
size: 0,
data: make([]rune, 0, allocSize),
}

// Pre-build the buffer and read runes efficiently
Expand Down
26 changes: 10 additions & 16 deletions pkg/printer/layout/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -244,10 +244,8 @@ func (e *Engine) SetTracer(tracer TokenTracer) {
// Returns an error if the underlying writer fails during a flush.
func (e *Engine) Push(token antlr.Token, flag format.FormatFlag) error {
bt := BufferedToken{
FlaggedToken: FlaggedToken{
Token: token,
Flag: flag,
},
Token: token,
Flag: flag,
}
if token != nil {
bt.cache = NewTokenStringCache(token.GetText())
Expand Down Expand Up @@ -379,12 +377,10 @@ func (e *Engine) beginGroup(

if mode == WrapModeCollective {
e.buffer = append(e.buffer, BufferedToken{
synthetic: SlcWrappingGroupBegin,
ResolveWrappingCache: ResolveWrappingCache{
ResolvedSepBefore: format.SepNone,
AssingedGroup: nil,
CurrentGroup: nil,
},
synthetic: SlcWrappingGroupBegin,
ResolvedSepBefore: format.SepNone,
AssingedGroup: nil,
CurrentGroup: nil,
})
}
e.activeGroups = append(e.activeGroups, lg)
Expand Down Expand Up @@ -420,12 +416,10 @@ func (e *Engine) endGroup(expected *Group) {

if top.WrapMode == WrapModeCollective {
e.buffer = append(e.buffer, BufferedToken{
synthetic: SlcWrappingGroupEnd,
ResolveWrappingCache: ResolveWrappingCache{
ResolvedSepBefore: format.SepNone,
AssingedGroup: nil,
CurrentGroup: nil,
},
synthetic: SlcWrappingGroupEnd,
ResolvedSepBefore: format.SepNone,
AssingedGroup: nil,
CurrentGroup: nil,
})
}

Expand Down
2 changes: 1 addition & 1 deletion test/dmlex/dml_parser_switch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ func runSwitchParserTestCase(t *testing.T, tc *switchParserTestCase) {
wrap := func(val string) string {
var sb strings.Builder
sb.WriteString("dml 1.4;\n\nmethod foo() {\n")
for _, line := range strings.Split(val, "\n") {
for line := range strings.SplitSeq(val, "\n") {
if line != "" {
sb.WriteString(" ")
sb.WriteString(line)
Expand Down
Loading
Loading