From 6140e6ca1f285ae3210b2f5f876cfe52158d4bc9 Mon Sep 17 00:00:00 2001 From: Henrique Dias Date: Thu, 25 Feb 2016 19:22:40 +0000 Subject: [PATCH] fix OS X unzipping --- insthugo/insthugo.go | 71 ++++++++++++++++++++++++++++++-------------- 1 file changed, 48 insertions(+), 23 deletions(-) diff --git a/insthugo/insthugo.go b/insthugo/insthugo.go index 19f68bfe..36da229a 100644 --- a/insthugo/insthugo.go +++ b/insthugo/insthugo.go @@ -195,38 +195,63 @@ func checkSHA256() { fmt.Println("checked!") } -func unzip(archive, target string) error { - reader, err := zip.OpenReader(archive) +func unzip(src, dest string) error { + r, err := zip.OpenReader(src) if err != nil { return err } + defer func() { + if err := r.Close(); err != nil { + panic(err) + } + }() - if err := os.MkdirAll(target, 0755); err != nil { - return err + os.MkdirAll(dest, 0755) + + // Closure to address file descriptors issue with all the deferred .Close() methods + extractAndWriteFile := func(f *zip.File) error { + rc, err := f.Open() + if err != nil { + return err + } + defer func() { + if err := rc.Close(); err != nil { + panic(err) + } + }() + + path := filepath.Join(dest, f.Name) + + if f.FileInfo().IsDir() { + os.MkdirAll(path, f.Mode()) + } else { + if _, err := os.Stat(filepath.Dir(path)); os.IsNotExist(err) { + os.MkdirAll(filepath.Dir(path), 0755) + } + + f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode()) + if err != nil { + return err + } + defer func() { + if err := f.Close(); err != nil { + panic(err) + } + }() + _, err = io.Copy(f, rc) + + if err != nil { + return err + } + } + return nil } - for _, file := range reader.File { - path := filepath.Join(target, file.Name) - if file.FileInfo().IsDir() { - os.MkdirAll(path, file.Mode()) - continue - } - - fileReader, err := file.Open() + for _, f := range r.File { + err := extractAndWriteFile(f) if err != nil { return err } - defer fileReader.Close() - - targetFile, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, file.Mode()) - if err != nil { - return err - } - defer targetFile.Close() - - if _, err := io.Copy(targetFile, fileReader); err != nil { - return err - } } return nil