Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

schema/gen/go: batch file writes via a bytes.Buffer #161

Merged
merged 1 commit into from
Apr 9, 2021
Merged
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
19 changes: 14 additions & 5 deletions schema/gen/go/generate.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
package gengo

import (
"bytes"
"fmt"
"io"
"os"
"io/ioutil"
"path/filepath"
"sort"

Expand Down Expand Up @@ -138,12 +139,20 @@ func Generate(pth string, pkgName string, ts schema.TypeSystem, adjCfg *AdjunctC
}

func withFile(filename string, fn func(io.Writer)) {
f, err := os.OpenFile(filename, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
if err != nil {
// Don't write directly to the file, as that many write syscalls can be
// expensive. Moreover, they can have a knock-on effect on daemons
// watching for file changes. gopls can easily eat CPU for many seconds
// just handling tens of thousands of file writes, for example.
//
// To alleviate both of those problems, write to a buffer first, and
// then write the resulting bytes to disk in a single go.
// A buffer is slightly better than bufio.Writer, as it gets us a bit
// more atomicity via the single write.
buf := new(bytes.Buffer)
fn(buf)
if err := ioutil.WriteFile(filename, buf.Bytes(), 0666); err != nil {
panic(err)
}
defer f.Close()
fn(f)
}

type sortableTypeNames []schema.TypeName
Expand Down