cavaliergopher / grab

A download manager package for Go
BSD 3-Clause "New" or "Revised" License
1.39k stars 150 forks source link

Delay file truncate until after BeforeCopy hook #80

Closed justinfx closed 4 years ago

justinfx commented 4 years ago

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

cavaliercoder commented 4 years ago

Nice work! Thanks

justinfx commented 4 years ago

Sweet. Thanks for the quick merge!