Skip to content

Commit

Permalink
[builder] Close files immediately after writing is complete (#9466)
Browse files Browse the repository at this point in the history
Ensure that files written by `cmd/builder` are closed right after their
content is written. This came about while investigating #5403

**Link to tracking Issue:**
#5403 

**Testing:**
Local run on Windows

**Documentation:**
N/A
  • Loading branch information
pjanotti authored Feb 6, 2024
1 parent 9caec6c commit c1cb275
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 12 deletions.
1 change: 1 addition & 0 deletions cmd/builder/internal/builder/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,5 +162,6 @@ func processAndWrite(cfg Config, tmpl *template.Template, outFile string, tmplPa
return err
}

defer out.Close()
return tmpl.Execute(out, tmplParams)
}
15 changes: 3 additions & 12 deletions cmd/builder/internal/builder/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import (
"path/filepath"
"runtime"
"testing"
"time"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
Expand All @@ -36,25 +35,21 @@ func TestGenerateInvalidOutputPath(t *testing.T) {
}

func TestSkipGenerate(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("skipping the test on Windows, see https://github.com/open-telemetry/opentelemetry-collector/issues/5403")
}

cfg := NewDefaultConfig()
cfg.Distribution.OutputPath = t.TempDir()
cfg.SkipGenerate = true
err := Generate(cfg)
require.NoError(t, err)
outputFile, err := os.Open(cfg.Distribution.OutputPath)
defer func() {
require.NoError(t, outputFile.Close())
}()
require.NoError(t, err)
_, err = outputFile.Readdirnames(1)
require.ErrorIs(t, err, io.EOF, "skip generate should leave output directory empty")
}

func TestGenerateAndCompile(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("skipping the test on Windows, see https://github.com/open-telemetry/opentelemetry-collector/issues/5403")
}
// This test is dependent on the current file structure.
// The goal is find the root of the repo so we can replace the root module.
_, thisFile, _, _ := runtime.Caller(0)
Expand Down Expand Up @@ -129,8 +124,4 @@ func TestGenerateAndCompile(t *testing.T) {
require.NoError(t, GenerateAndCompile(cfg))
})
}

// Sleep for 1 second to make sure all processes using the files are completed
// (on Windows fail to delete temp dir otherwise).
time.Sleep(1 * time.Second)
}

0 comments on commit c1cb275

Please sign in to comment.