Skip to content

Commit f1cc6fc

Browse files
authored
fix: close terminal reader on application exit (#54)
1 parent d61beb9 commit f1cc6fc

File tree

3 files changed

+26
-7
lines changed

3 files changed

+26
-7
lines changed

cmd/gemini/main.go

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package main
22

33
import (
44
"context"
5+
"errors"
56
"os"
67
"os/user"
78

@@ -23,8 +24,11 @@ func run() int {
2324
Version: version,
2425
}
2526

26-
var opts chat.Opts
27-
var configPath string
27+
var (
28+
opts chat.Opts
29+
configPath string
30+
)
31+
2832
rootCmd.Flags().StringVarP(&opts.GenerativeModel, "model", "m", gemini.DefaultModel,
2933
"generative model name")
3034
rootCmd.Flags().BoolVar(&opts.Multiline, "multiline", false,
@@ -38,7 +42,7 @@ func run() int {
3842
rootCmd.Flags().StringVarP(&configPath, "config", "c", defaultConfigPath,
3943
"path to configuration file in JSON format")
4044

41-
rootCmd.RunE = func(_ *cobra.Command, _ []string) error {
45+
rootCmd.RunE = func(_ *cobra.Command, _ []string) (err error) {
4246
configuration, err := config.NewConfiguration(configPath)
4347
if err != nil {
4448
return err
@@ -52,20 +56,22 @@ func run() int {
5256
if err != nil {
5357
return err
5458
}
59+
defer func() { err = errors.Join(err, chatSession.Close()) }()
5560

5661
chatHandler, err := chat.New(getCurrentUser(), chatSession, configuration, &opts)
5762
if err != nil {
5863
return err
5964
}
60-
chatHandler.Start()
65+
defer func() { err = errors.Join(err, chatHandler.Close()) }()
6166

62-
return chatSession.Close()
67+
chatHandler.Start()
68+
return nil
6369
}
6470

65-
err := rootCmd.Execute()
66-
if err != nil {
71+
if err := rootCmd.Execute(); err != nil {
6772
return 1
6873
}
74+
6975
return 0
7076
}
7177

internal/chat/chat.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,11 @@ func (c *Chat) Start() {
8080
}
8181
}
8282

83+
// Close closes the chat.
84+
func (c *Chat) Close() error {
85+
return c.io.Close()
86+
}
87+
8388
// getHandler returns the handler for the message.
8489
func (c *Chat) getHandler(prefix string) handler.MessageHandler {
8590
if prefix == cli.SystemCmdPrefix {

internal/terminal/io.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,14 @@ func NewIO(config *IOConfig) (*IO, error) {
5454
}, nil
5555
}
5656

57+
// Close releases underlying terminal resources.
58+
func (io *IO) Close() error {
59+
if io.Reader != nil {
60+
return io.Reader.Close()
61+
}
62+
return nil
63+
}
64+
5765
// Read reads input from the underlying source and returns it as a string.
5866
// If multiline is true, it reads all available lines; otherwise, it reads a single line.
5967
func (io *IO) Read() string {

0 commit comments

Comments
 (0)