h2non / filetype

Fast, dependency-free Go package to infer binary file types based on the magic numbers header signature
https://pkg.go.dev/github.com/h2non/filetype?tab=doc
MIT License
2.13k stars 177 forks source link

Err is nil when filetype is unknown #43

Closed taylorkline closed 5 years ago

taylorkline commented 6 years ago

Expected behavior:

kind, err := filetype.MatchReader(badReader)

We would expect err != nil, but this is not so.

The documentation appears to contradict itself. In one example, we have:

  kind, unknown := filetype.Match(buf)
  if unknown != nil {
    fmt.Printf("Unknown: %s", unknown)
    return
  }

Yet, in another example, we have:

  // Try to match the file
  fooFile := []byte{0x01, 0x02}
  kind, _ := filetype.Match(fooFile)
  if kind == filetype.Unknown {
    fmt.Println("Unknown file type")
  } else {
    fmt.Printf("File type matched: %s\n", kind.Extension)
  }

I would expect the documentation to be consistent and the error to be populated if we have an unknown filetype.

kmanley commented 5 years ago

The error isn't populated if the filetype is unknown. In that case filetype.Unknown is returned and err==nil. An error is only returned if an error occurs. You're correct that this example is wrong though:

kind, unknown := filetype.Match(buf)
  if unknown != nil {
    fmt.Printf("Unknown: %s", unknown)
    return
  }

I submitted #59 to correct that

h2non commented 5 years ago

Should be fixed now. Thanks!