Skip to content

Commit 1ae3898

Browse files
committed
main: check that code is formatted in unit test
Signed-off-by: Jason A. Donenfeld <[email protected]>
1 parent 39e0b6d commit 1ae3898

File tree

2 files changed

+65
-1
lines changed

2 files changed

+65
-1
lines changed

Makefile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ MAKEFLAGS += --no-print-directory
1010
generate-version-and-build:
1111
@export GIT_CEILING_DIRECTORIES="$(realpath $(CURDIR)/..)" && \
1212
tag="$$(git describe --dirty 2>/dev/null)" && \
13-
ver="$$(printf 'package main\nconst Version = "%s"\n' "$$tag")" && \
13+
ver="$$(printf 'package main\n\nconst Version = "%s"\n' "$$tag")" && \
1414
[ "$$(cat version.go 2>/dev/null)" != "$$ver" ] && \
1515
echo "$$ver" > version.go && \
1616
git update-index --assume-unchanged version.go || true

format_test.go

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/* SPDX-License-Identifier: MIT
2+
*
3+
* Copyright (C) 2021 WireGuard LLC. All Rights Reserved.
4+
*/
5+
package main
6+
7+
import (
8+
"bytes"
9+
"go/format"
10+
"io/fs"
11+
"os"
12+
"path/filepath"
13+
"runtime"
14+
"sync"
15+
"testing"
16+
)
17+
18+
func TestFormatting(t *testing.T) {
19+
_, caller, _, ok := runtime.Caller(0)
20+
if !ok {
21+
t.Fatalf("unable to determine source location")
22+
}
23+
dir := filepath.Dir(caller)
24+
if _, err := os.Stat(caller); err != nil {
25+
wd, err := os.Getwd()
26+
if err != nil {
27+
t.Fatalf("unable to get working directory: %v", wd)
28+
}
29+
caller = filepath.Join(wd, filepath.Base(caller))
30+
if _, err := os.Stat(caller); err != nil {
31+
t.Fatalf("unable to determine source location")
32+
}
33+
dir = filepath.Dir(caller)
34+
}
35+
var wg sync.WaitGroup
36+
filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error {
37+
if err != nil {
38+
t.Errorf("unable to walk %s: %v", path, err)
39+
return nil
40+
}
41+
if d.IsDir() || filepath.Ext(path) != ".go" {
42+
return nil
43+
}
44+
wg.Add(1)
45+
go func(path string) {
46+
defer wg.Done()
47+
src, err := os.ReadFile(path)
48+
if err != nil {
49+
t.Errorf("unable to read %s: %v", path, err)
50+
return
51+
}
52+
formatted, err := format.Source(src)
53+
if err != nil {
54+
t.Errorf("unable to format %s: %v", path, err)
55+
return
56+
}
57+
if !bytes.Equal(src, formatted) {
58+
t.Errorf("unformatted code: %s", path)
59+
}
60+
}(path)
61+
return nil
62+
})
63+
wg.Wait()
64+
}

0 commit comments

Comments
 (0)