Skip to content

[BUG] Potential file handle leak in completion.go #523

@coding-shalabh

Description

@coding-shalabh

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:

  1. Making the file write operation fail after opening
  2. Monitoring open file handles
  3. 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions