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

Ensure that io writers are properly closed. #292

Merged
merged 1 commit into from
Apr 18, 2023
Merged
Show file tree
Hide file tree
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
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
}