diff --git a/utils.go b/utils.go index 8b59751a..9d5731e7 100644 --- a/utils.go +++ b/utils.go @@ -3,6 +3,7 @@ package main import ( "fmt" "io" + "io/ioutil" "net/http" "os" ) @@ -60,6 +61,30 @@ func (downloader *Downloader) Download(url string, destination string) <-chan er return ch } +// DownloadTemp starts new download to temporary file and returns File +// +// Temporary file would be already removed, so no need to cleanup +func (downloader *Downloader) DownloadTemp(url string) (*os.File, error) { + ch := make(chan error, 1) + + tempfile, err := ioutil.TempFile(os.TempDir(), "aptly") + if err != nil { + return nil, err + } + + defer os.Remove(tempfile.Name()) + + downloader.queue <- &downloadTask{url: url, destination: tempfile.Name(), result: ch} + + err = <-ch + if err != nil { + tempfile.Close() + return nil, err + } + + return tempfile, nil +} + // handleTask processes single download task func (downloader *Downloader) handleTask(task *downloadTask) { resp, err := http.Get(task.url) diff --git a/utils_test.go b/utils_test.go index 3a85fafe..d61b00d7 100644 --- a/utils_test.go +++ b/utils_test.go @@ -74,3 +74,30 @@ func (s *DownloaderSuite) TestDownloadFileError(c *C) { res := <-d.Download("http://smira.ru/", "/no/such/file") c.Assert(res, ErrorMatches, ".*no such file or directory") } + +func (s *DownloaderSuite) TestDownloadTemp(c *C) { + d := NewDownloader(2) + defer d.Shutdown() + + f, err := d.DownloadTemp("http://smira.ru/") + c.Assert(err, IsNil) + defer f.Close() + + buf := make([]byte, 1) + + f.Read(buf) + c.Assert(buf, DeepEquals, []byte("<")) + + _, err = os.Stat(f.Name()) + c.Assert(os.IsNotExist(err), Equals, true) +} + +func (s *DownloaderSuite) TestDownloadTempError(c *C) { + d := NewDownloader(2) + defer d.Shutdown() + + f, err := d.DownloadTemp("http://smira.ru/doesntexist") + c.Assert(err, NotNil) + c.Assert(f, IsNil) + c.Assert(err, ErrorMatches, "HTTP code 404.*") +}