|
| 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