Skip to content

Commit

Permalink
windows/mkwinsyscall: write source to temp file if formatting fails
Browse files Browse the repository at this point in the history
This change writes the unformatted Go source code to a temp file if
"format.Source" fails. Print the temp file path to the console to make
it easy to find. The source code is what causes formatting errors, and
it can be difficult to diagnose them without this context.

Fixes golang/go#57925

Change-Id: Ifa4d8a6e8bc5006357b0bc88afce5ba1d6fe0a48
Reviewed-on: https://go-review.googlesource.com/c/sys/+/463216
Reviewed-by: Michael Knyszek <[email protected]>
Reviewed-by: Alex Brainman <[email protected]>
Auto-Submit: Bryan Mills <[email protected]>
Reviewed-by: Quim Muntal <[email protected]>
TryBot-Result: Gopher Robot <[email protected]>
Run-TryBot: Bryan Mills <[email protected]>
Reviewed-by: Bryan Mills <[email protected]>
  • Loading branch information
dagood authored and gopherbot committed Jan 30, 2023
1 parent 71da690 commit 4112509
Showing 1 changed file with 22 additions and 1 deletion.
23 changes: 22 additions & 1 deletion windows/mkwinsyscall/mkwinsyscall.go
Original file line number Diff line number Diff line change
Expand Up @@ -871,6 +871,22 @@ func (src *Source) Generate(w io.Writer) error {
return nil
}

func writeTempSourceFile(data []byte) (string, error) {
f, err := os.CreateTemp("", "mkwinsyscall-generated-*.go")
if err != nil {
return "", err
}
_, err = f.Write(data)
if closeErr := f.Close(); err == nil {
err = closeErr
}
if err != nil {
os.Remove(f.Name()) // best effort
return "", err
}
return f.Name(), nil
}

func usage() {
fmt.Fprintf(os.Stderr, "usage: mkwinsyscall [flags] [path ...]\n")
flag.PrintDefaults()
Expand All @@ -897,7 +913,12 @@ func main() {

data, err := format.Source(buf.Bytes())
if err != nil {
log.Fatal(err)
log.Printf("failed to format source: %v", err)
f, err := writeTempSourceFile(buf.Bytes())
if err != nil {
log.Fatalf("failed to write unformatted source to file: %v", err)
}
log.Fatalf("for diagnosis, wrote unformatted source to %v", f)
}
if *filename == "" {
_, err = os.Stdout.Write(data)
Expand Down

0 comments on commit 4112509

Please sign in to comment.