go-tools icon indicating copy to clipboard operation
go-tools copied to clipboard

Feature Request: prevent forgetting `os.O_TRUNC` / `os.O_EXCL` / `os.O_APPEND`

Open seiyab opened this issue 10 months ago • 2 comments

I frequently forget to specify os.O_TRUNC when I use os.OpenFile(). Forgetting os.O_TRUNC sometime makes file broken. And I rarely detect this failure on test codes because it doesn't cause a problem if there isn't existing file. I was wondering if staticcheck prevents such failures.

Examples

// Bad
f, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY, 0600)

// Bad
f, err := os.OpenFile(filename, os.O_WRONLY, 0600)

// Good
f, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0600)

// Good
f, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_EXCL, 0600)

// Good
f, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)

Considerations

// I feel we should avoid this. But reporting this might be too aggressive.
flag := os.O_CREATE|os.O_WRONLY

// Probably it's OK.
flag := os.O_CREATE|os.O_WRONLY|os.O_TRUNC
// Perhaps we should avoid this. Probably out of scope in this issue.
f, err := os.OpenFile(filename, os.O_RDONLY, 0600)

// This looks fine.
f, err := os.Open(filename)

Edit I have updated the title, examples, considerations (2023-09-13 JST).

seiyab avatar Sep 13 '23 09:09 seiyab