Description
The file pkg/cmd/completion.go has two instances where file handles are closed without using defer, which can cause resource leaks if errors occur between opening and closing the file.
Impact
If an error occurs after opening a file but before the explicit Close() call, the file handle will never be closed. This can lead to:
- Resource exhaustion with many file handles open
- Files locked on Windows
- "Too many open files" errors
Locations
File: pkg/cmd/completion.go
Line 178:
f, err := os.Create(completionFile)
if err != nil {
return err
}
// ... code that could error ...
f.Close() // ← Not guaranteed to execute
Line 190:
f, err := os.Create(completionFile)
if err != nil {
return err
}
// ... code that could error ...
f.Close() // ← Not guaranteed to execute
Suggested Fix
Use defer to guarantee file closure:
f, err := os.Create(completionFile)
if err != nil {
return err
}
defer f.Close() // ← Guaranteed to execute
// ... rest of code ...
Steps to Reproduce
While this is hard to trigger in practice, you can simulate it by:
- Making the file write operation fail after opening
- Monitoring open file handles
- Observing that the file handle is never closed
Additional Context
This is a common Go anti-pattern. The Go community strongly recommends using defer for resource cleanup to prevent leaks.
Reference: Effective Go - Defer
Description
The file
pkg/cmd/completion.gohas two instances where file handles are closed without usingdefer, which can cause resource leaks if errors occur between opening and closing the file.Impact
If an error occurs after opening a file but before the explicit
Close()call, the file handle will never be closed. This can lead to:Locations
File:
pkg/cmd/completion.goLine 178:
Line 190:
Suggested Fix
Use
deferto guarantee file closure:Steps to Reproduce
While this is hard to trigger in practice, you can simulate it by:
Additional Context
This is a common Go anti-pattern. The Go community strongly recommends using
deferfor resource cleanup to prevent leaks.Reference: Effective Go - Defer