While integrating grab into my downloader application I wanted to add a custom hook to decide whether I really need to download the file based on some custom headers. The BeforeCopy hook appeared to be the place to do this as it would perform the request, let me read the headers, and return an error to cancel the request if I decide I don't want to read the body.
The issue with the BeforeCopy hook is that the openWriter has already run first, and if you are not doing a resume option on an existing file (which I am not) it will truncate the file when it opens it for writing. Then if the hook decides to cancel, it will have erased the existing file contents.
This patch removes the O_TRUNC option from the case in openWriter and moved it into copyFile after the BeforeCopy has evaluated. The result is that an existing file will not be truncated until it is actually going to write.
I debated solving this by adding another hook earlier into the lifecycle, but this seemed like a simpler change to make.
Minor extra changes to make testing easier were to add a Go.mod and .gitignore
While integrating grab into my downloader application I wanted to add a custom hook to decide whether I really need to download the file based on some custom headers. The
BeforeCopy
hook appeared to be the place to do this as it would perform the request, let me read the headers, and return an error to cancel the request if I decide I don't want to read the body. The issue with theBeforeCopy
hook is that theopenWriter
has already run first, and if you are not doing a resume option on an existing file (which I am not) it will truncate the file when it opens it for writing. Then if the hook decides to cancel, it will have erased the existing file contents.This patch removes the
O_TRUNC
option from the case inopenWriter
and moved it intocopyFile
after theBeforeCopy
has evaluated. The result is that an existing file will not be truncated until it is actually going to write.I debated solving this by adding another hook earlier into the lifecycle, but this seemed like a simpler change to make.
Minor extra changes to make testing easier were to add a
Go.mod
and.gitignore