Skip to content

Commit

Permalink
Ensure that io writers are properly closed. (#292)
Browse files Browse the repository at this point in the history
Because the writers were being defered closed in New, this means that
some files could be closed before we had the opportunity to write to
them. This moves the close to their own func that can be ran in the
correct place.

Signed-off-by: Billy Lynch <billy@chainguard.dev>
  • Loading branch information
wlynch authored Apr 18, 2023
1 parent 04f9453 commit 23df870
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
1 change: 1 addition & 0 deletions internal/commands/root/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ func New(cfg *config.Config) *cobra.Command {
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
s := io.New(o.Config.LogPath)
defer s.Close()
return s.Wrap(func() error {
switch {
case o.FlagVersion:
Expand Down
15 changes: 13 additions & 2 deletions internal/io/streams.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ type Streams struct {

TTYIn io.Reader
TTYOut io.Writer

close []func() error
}

func New(logPath string) *Streams {
Expand All @@ -46,7 +48,7 @@ func New(logPath string) *Streams {
// As a janky way to preserve error message, tee stderr to
// a temp file.
if f, err := os.Create(logPath); err == nil {
defer f.Close()
s.close = append(s.close, f.Close)
s.Err = io.MultiWriter(s.Err, f)
}
}
Expand All @@ -55,7 +57,7 @@ func New(logPath string) *Streams {
// set the input/output if we can actually open it.
tty, err := tty.Open()
if err == nil {
defer tty.Close()
s.close = append(s.close, tty.Close)
s.TTYIn = tty.Input()
s.TTYOut = tty.Output()
} else {
Expand All @@ -80,3 +82,12 @@ func (s *Streams) Wrap(fn func() error) error {
}
return nil
}

func (s *Streams) Close() error {
for _, fn := range s.close {
if err := fn(); err != nil {
return err
}
}
return nil
}

0 comments on commit 23df870

Please sign in to comment.