// Write the File to io.Writer as xlsx func (f *File) Write(writer io.Writer) (err error) { var parts map[string]string var zipWriter *zip.Writer parts, err = f.MarshallParts() if err != nil { return } zipWriter = zip.NewWriter(writer) for partName, part := range parts { var writer io.Writer writer, err = zipWriter.Create(partName) if err != nil { return } _, err = writer.Write([]byte(part)) if err != nil { return } } err = zipWriter.Close() return }
func AddMimetype(zippy *zip.Writer) { mimetype, err := zippy.Create("mimetype") if err != nil { log.Fatal(err) } WriteToFile(mimetype, "application/epub+zip") }
func addtozip(z *zip.Writer, name string, f *os.File) { if fi, _ := f.Stat(); fi.IsDir() { log.Println("Adding folder", name) names, _ := f.Readdirnames(-1) for _, subname := range names { file, err := os.Open(filepath.Join(f.Name(), subname)) if err != nil { log.Println(err) continue } addtozip(z, filepath.Join(name, subname), file) file.Close() } } else { log.Println("Adding file", name) fw, err := z.Create(name) if err != nil { panic(err) } _, err = io.Copy(fw, f) if err != nil { panic(err) } } }
// Save the File to an xlsx file at the provided path. func (f *File) Save(path string) (err error) { var parts map[string]string var target *os.File var zipWriter *zip.Writer parts, err = f.MarshallParts() if err != nil { return } target, err = os.Create(path) if err != nil { return } zipWriter = zip.NewWriter(target) for partName, part := range parts { var writer io.Writer writer, err = zipWriter.Create(partName) if err != nil { return } _, err = writer.Write([]byte(part)) if err != nil { return } } err = zipWriter.Close() if err != nil { return } return target.Close() }
// addIndexToZip generates an index.html file for the given Overlay and adds // it to the provided zip file. func addIndexToZip(c appengine.Context, z *zip.Writer, oKey *datastore.Key, o *Overlay) error { w, err := z.Create(fmt.Sprintf("%s/index.html", oKey.Encode())) if err != nil { return err } return zipTemplate.Execute(w, o) }
// Copy any files from the includes directory func copyIncludes(zw *zip.Writer, includes string) error { includes = path.Clean(includes) if !strings.HasSuffix(includes, "/") { includes += "/" } return filepath.Walk(includes, func(path string, info os.FileInfo, err error) error { if err != nil { return err } if info.IsDir() { return nil } path = filepath.ToSlash(path) if w, err := zw.Create(strings.TrimPrefix(path, includes)); err != nil { return err } else { b, err := ioutil.ReadFile(path) if err != nil { return err } else { _, err := w.Write(b) if err != nil { return err } } } return nil }) }
func AddContainer(zippy *zip.Writer) { container, err := zippy.Create(path.Join("META-INF", "container.xml")) if err != nil { log.Fatal(err) } WriteToFile(container, "<?xml version=\"1.0\"?><container version=\"1.0\" xmlns=\"urn:oasis:names:tc:opendocument:xmlns:container\"><rootfiles><rootfile full-path=\"OEBPS/content.opf\" media-type=\"application/oebps-package+xml\"/></rootfiles></container>") }
// Deal with files func zipFile(srcFile string, recPath string, tw *zip.Writer, fi os.FileInfo) { if fi.IsDir() { // fmt.Println("??") // Create tar header /* fh, err := zip.FileInfoHeader(fi) if err != nil { panic(err) } fh.Name = recPath // + "/" err = tw.WriteHeader(hdr) tw.Create(recPath) */ } else { // File reader fr, err := os.Open(srcFile) if err != nil { panic(err) } defer fr.Close() // Write hander w, err2 := tw.Create(recPath) if err2 != nil { panic(err) } // Write file data _, err = io.Copy(w, fr) if err != nil { panic(err) } } }
func array2XlsxWriteSharedStrings(zw *zip.Writer, data [][]string) (err error) { siList := []xlsxSharedStringSi{{""}} for _, row := range data { for _, v1 := range row { if v1 == "" { //ignore blank cell can save space continue } siList = append(siList, xlsxSharedStringSi{v1}) } } sst := xlsxSharedStringSst{ Xmlns: xmlNs, Count: len(siList), SiList: siList, } thisW, err := zw.Create(sharedStringsFileName) _, err = thisW.Write([]byte(xml.Header)) if err != nil { return } encoder := xml.NewEncoder(thisW) err = encoder.Encode(sst) if err != nil { return } return }
func AddTitle(book_title string, book_author string, zippy *zip.Writer) { title, err := zippy.Create(path.Join("OEBPS", "title.xhtml")) if err != nil { log.Fatal(err) } WriteToFile(title, fmt.Sprintf("<html>\n\t<head>\n\t\t<title>%s</title>\n\t</head>\n\t<body>\n\t\t<center><h1>%s</h1>\n\t\t<h2>by %s</h2></center>\n\t</body>\n</html>", book_title, book_title, book_author)) }
func addZipFileMust(w *zip.Writer, path string) { d, err := ioutil.ReadFile(path) fataliferr(err) f, err := w.Create(filepath.Base(path)) fataliferr(err) _, err = f.Write(d) fataliferr(err) // no need to close f. It's implicitly closed by the next Create() or Close() call }
func copyFile(outzip *zip.Writer, name string, in *zip.File) { w, err := outzip.Create(name) must(err) r, err := in.Open() must(err) defer r.Close() _, err = io.Copy(w, r) must(err) }
func walk(base, startPath string, zipWriter *zip.Writer) error { return filepath.Walk(startPath, func(path string, stat os.FileInfo, err error) error { if err != nil { return err } if stat.IsDir() { return nil } relativePath, err := filepath.Rel(startPath, path) if err != nil { return err } filePath := path if stat.Mode()&os.ModeSymlink != 0 { filePath, err = filepath.EvalSymlinks(path) if err != nil { return err } stat, err = os.Stat(filePath) if err != nil { return err } if stat.IsDir() { if err != nil { return err } return walk(Path.Join(base, ".", relativePath), filePath, zipWriter) } } name := Path.Join(base, filepath.ToSlash(relativePath)) dbg("+", filePath, "=>", name) file, err := os.Open(filePath) if err != nil { return err } defer file.Close() writer, err := zipWriter.Create(name) if err != nil { return err } _, err = io.Copy(writer, file) if err != nil { return err } return nil }) }
func (w *Writer) writeFile(z *zip.Writer, s string, b []byte) error { f, err := z.Create(s) if err != nil { return err } _, err = f.Write(b) return err }
func pack(z *zip.Writer, result *CheckResult) (err error) { var ( f io.Writer fnPattern = "%s.txt" ) if f, err = z.Create(fmt.Sprintf(fnPattern, result.Date)); err != nil { return } f.Write(result.Data) return }
func AddChapters(chapters []Chapter, zippy *zip.Writer) { chapter_fmt := "<html>\n\t<head>\n\t\t<title>%s</title>\n\t</head>\n\t<body>\n\t\t<center><h1>%s</h1></center>\n\t\t%s\n\t</body>\n</html>" for chapter := range chapters { chapter_filename := fmt.Sprintf("chapter%d.xhtml", chapter+1) chapter_file, err := zippy.Create(path.Join("OEBPS", chapter_filename)) if err != nil { log.Fatal(err) } WriteToFile(chapter_file, fmt.Sprintf(chapter_fmt, chapters[chapter].Title, chapters[chapter].Title, chapters[chapter].Text)) } }
func appendToArchive(archive *zip.Writer, download URLDownload) error { if download.err != nil { return download.err } fileName := fileNameFromURL(download.url) w, err := archive.Create(fileName) if err != nil { return err } _, err = io.Copy(w, download.body) defer download.body.Close() return nil }
func writeNodeJSShim(serviceName string, executableOutput string, lambdaAWSInfos []*LambdaAWSInfo, zipWriter *zip.Writer, logger *logrus.Logger) error { // Add the string literal adapter, which requires us to add exported // functions to the end of index.js. These NodeJS exports will be // linked to the AWS Lambda NodeJS function name, and are basically // automatically generated pass through proxies to the golang HTTP handler. nodeJSWriter, err := zipWriter.Create("index.js") if err != nil { return errors.New("Failed to create ZIP entry: index.js") } nodeJSSource := _escFSMustString(false, "/resources/index.js") nodeJSSource += "\n// DO NOT EDIT - CONTENT UNTIL EOF IS AUTOMATICALLY GENERATED\n" handlerNames := make(map[string]bool, 0) for _, eachLambda := range lambdaAWSInfos { if _, exists := handlerNames[eachLambda.jsHandlerName()]; !exists { nodeJSSource += createNewNodeJSProxyEntry(eachLambda, logger) handlerNames[eachLambda.jsHandlerName()] = true } // USER DEFINED RESOURCES for _, eachCustomResource := range eachLambda.customResources { if _, exists := handlerNames[eachCustomResource.jsHandlerName()]; !exists { nodeJSSource += createUserCustomResourceEntry(eachCustomResource, logger) handlerNames[eachCustomResource.jsHandlerName()] = true } } } // SPARTA CUSTOM RESOURCES for _, eachCustomResourceName := range golangCustomResourceTypes { nodeJSSource += createNewSpartaCustomResourceEntry(eachCustomResourceName, logger) } // Finally, replace // SPARTA_BINARY_NAME = 'Sparta.lambda.amd64'; // with the service binary name nodeJSSource += fmt.Sprintf("SPARTA_BINARY_NAME='%s';\n", executableOutput) // And the service name nodeJSSource += fmt.Sprintf("SPARTA_SERVICE_NAME='%s';\n", serviceName) logger.WithFields(logrus.Fields{ "index.js": nodeJSSource, }).Debug("Dynamically generated NodeJS adapter") stringReader := strings.NewReader(nodeJSSource) _, copyErr := io.Copy(nodeJSWriter, stringReader) return copyErr }
func AddTOC(title string, book_str string, chapters []Chapter, zippy *zip.Writer) { toc, err := zippy.Create(path.Join("OEBPS", "toc.ncx")) if err != nil { log.Fatal(err) } WriteToFile(toc, fmt.Sprintf("<?xml version=\"1.0\" encoding=\"UTF-8\"?><ncx xmlns=\"http://www.daisy.org/z3986/2005/ncx/\" version=\"2005-1\"><head><meta name=\"dtb:uid\" content=\"%s\"/><meta name=\"dtb:depth\" content=\"1\"/><meta name=\"dtb:totalPageCount\" content=\"0\"/><meta name=\"dtb:maxPageNumber\" content=\"0\"/></head><docTitle><text>%s</text></docTitle><navMap><navPoint id=\"title\" playOrder=\"1\"><navLabel><text>Title Page</text></navLabel><content src=\"title.xhtml\"/></navPoint>", book_str, title)) for chapter := range chapters { WriteToFile(toc, fmt.Sprintf("<navPoint id=\"chapter%d\" playOrder=\"%d\"><navLabel><text>%s</text></navLabel><content src=\"chapter%d.xhtml\"/></navPoint>", chapter, chapter+2, chapters[chapter].Title, chapter)) } WriteToFile(toc, "</navMap></ncx>") }
// CreateNW creates a node-webkit .nw file func (p Package) CreateNW(zw *zip.Writer, templates Templates, myapp io.Reader, includes string) error { // Add in a couple of package defaults p.Main = "index.html" p.EnvVar = nw.EnvVar if w, err := zw.Create("package.json"); err != nil { return err } else { if _, err := p.writeJsonTo(w); err != nil { return err } } filenameTemplates := map[string]string{ "index.html": templates.IndexHtml, "client.js": templates.ClientJs, "script.js": templates.ScriptJs} for filename, str := range filenameTemplates { if w, err := zw.Create(filename); err != nil { return err } else { if t, err := template.New(filename).Parse(str); err != nil { return err } else { if err := t.Execute(w, p); err != nil { return err } } } } if includes != "" { if err := copyIncludes(zw, includes); err != nil { return err } } binHeader := zip.FileHeader{Name: p.Bin} binHeader.SetMode(0755) // Make it executable if w, err := zw.CreateHeader(&binHeader); err != nil { return err } else { if _, err := io.Copy(w, myapp); err != nil { return err } } return nil }
func writeLines_To_ZipFile(lines []string, writer *zip.Writer, fileName string) { //Create a file in the zip file f, err := writer.Create(fileName) if err != nil { log.Fatal(err) } for _, line := range lines { _, err = f.Write([]byte(line + "\n")) if err != nil { log.Fatal(err) } } }
func AddHeader(title string, author string, url string, chapters []Chapter, zippy *zip.Writer) { content, err := zippy.Create(path.Join("OEBPS", "content.opf")) if err != nil { log.Fatal(err) } WriteToFile(content, "<?xml version=\"1.0\"?><package version=\"2.0\" xmlns=\"http://www.idpf.org/2007/opf\" unique-identifier=\"BookId\"><metadata xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:opf=\"http://www.idpf.org/2007/opf\"><dc:title>") WriteToFile(content, title) WriteToFile(content, "</dc:title><dc:creator opf:role=\"aut\">") WriteToFile(content, author) WriteToFile(content, "</dc:creator><dc:language>en-US</dc:language><dc:identifier id=\"BookId\">urn:uuid:") WriteToFile(content, url) WriteToFile(content, "</dc:identifier></metadata>") AddContentHeader(content, chapters) }
func archiveHook(context map[string]interface{}, serviceName string, zipWriter *zip.Writer, awsSession *session.Session, noop bool, logger *logrus.Logger) error { logger.Info("Adding userResource") resourceFileName := "userResource.json" binaryWriter, binaryWriterErr := zipWriter.Create(resourceFileName) if nil != binaryWriterErr { return binaryWriterErr } userdataReader := strings.NewReader(userdataResourceContents) _, copyErr := io.Copy(binaryWriter, userdataReader) return copyErr }
func (a *Archiver) addFile(filename string, zw *zip.Writer) error { file, err := os.Open(filename) if err != nil { return fmt.Errorf("failed opening %s: %s", filename, err) } defer file.Close() wr, err := zw.Create(filepath.Base(filename)) if err != nil { return fmt.Errorf("failed creating entry for %s in zip file: %s", filename, err) } if _, err := io.Copy(wr, file); err != nil { return fmt.Errorf("failed writing %s to zip: %s", filename, err) } return nil }
func array2XlsxWriteSheet1(zw *zip.Writer, data [][]string) (err error) { rowList := make([]xlsxRow, len(data)) totalIndex := 1 MaxCellIndex := 0 for rowIndex, row := range data { rowList[rowIndex].C = make([]xlsxC, len(row)) if len(row) > MaxCellIndex { MaxCellIndex = len(row) - 1 } for cellIndex, v1 := range row { index := totalIndex if v1 == "" { //ignore blank cell can save space index = 0 } else { totalIndex++ } rowList[rowIndex].C[cellIndex] = xlsxC{ R: CoordinateXy2Excel(cellIndex, rowIndex), T: "s", V: index, } } } sheetData := xlsxSheetData{ Row: rowList, } thisW, err := zw.Create(sheel1FileName) xmlBytes, err := xml.Marshal(sheetData) if err != nil { return } err = sheelTpl.Execute(thisW, struct { MaxPosition string SheetData string }{ MaxPosition: CoordinateXy2Excel(MaxCellIndex, len(data)-1), SheetData: string(xmlBytes), }) if err != nil { return } return }
// Write the File to io.Writer as xlsx func (f *File) Write(writer io.Writer, fn func(total int, current int) string) (err error) { var parts map[string]string var zipWriter *zip.Writer parts, err = f.MarshallParts() if err != nil { return } zipWriter = zip.NewWriter(writer) count := 0 for partName, part := range parts { var writer io.Writer writer, err = zipWriter.Create(partName) if err != nil { return } _, err = writer.Write([]byte(part)) if err != nil { return } for { ctrl := fn(len(parts), count) if ctrl == "pause" { time.Sleep(1 * time.Second) } else if ctrl == "export" || ctrl == "resume" { break } else if ctrl == "cancel" { zipWriter.Close() return } } count++ } fn(len(parts), len(parts)) err = zipWriter.Close() return }
func addFile(filename string, zw *zip.Writer) error { file, err := os.Open(filename) if err != nil { return fmt.Errorf("failed opening %s: %s", filename, err) } defer file.Close() wr, err := zw.Create(filename) if err != nil { return fmt.Errorf("failed creating entry for %s in zip file: %s", filename, err) } // Not checking how many bytes copied, // since we don't know the file size without doing more work if _, err := io.Copy(wr, file); err != nil { return fmt.Errorf("failed writing %s to zip: %s", filename, err) } return nil }
// read, resize, crop and zip a 'screenshot' named 'name' into 'zipArchive' func convert(zipFile *zip.Writer, infile io.Reader, filename string) error { img, err := png.Decode(infile) if err != nil { return err } resized := resize.Resize(0, TargetHeight, img, resize.Bicubic) croppedImg, _ := cutter.Crop(resized, cutter.Config{ Width: TargetWidth, Height: TargetHeight, Mode: cutter.Centered, }) zippedFile, err := zipFile.Create(filename) if err != nil { return err } return jpeg.Encode(zippedFile, croppedImg, JpegQuality) }
// Función encargada de recorrer un directorio y agregar los archivos al ZIP func walkDirectory(directory *os.File, zipWriter *zip.Writer) error { // Leemos contenido del directorio content, err := directory.Readdir(-1) if err != nil { return err } // Recorremos contenido del directorio for _, val := range content { if !val.IsDir() { // Es un archivo: anrimos el archivo y lo agregamos al Writer file, err := openPath(directory.Name() + "/" + val.Name()) if err != nil { return err } // Agregamos un archivo al ZIP fileWriter, err := zipWriter.Create(file.Name()) if err != nil { file.Close() return err } // Escrivimos sobre el nuevo archivo ZIP _, err = copyContent(file, fileWriter) } else { // Es un directorio: abrimos el directorio y recorremos su contenido dir, err := openPath(directory.Name() + "/" + val.Name()) if err != nil { return err } err = walkDirectory(dir, zipWriter) if err != nil { return err } } } // Cerramos directorio directory.Close() return nil }
// addTilesToZip fetches all the Tile records for a given Overlay, fetches // their associated image blobs, and adds them to the provided zip file. func addTilesToZip(c appengine.Context, z *zip.Writer, oKey *datastore.Key) error { base := oKey.Encode() q := datastore.NewQuery("Tile").Ancestor(oKey) for i := q.Run(c); ; { var t Tile if _, err := i.Next(&t); err == datastore.Done { break } else if err != nil { return err } name := fmt.Sprintf("%s/%d/%d/%d.png", base, t.Zoom, t.X, t.Y) w, err := z.Create(name) if err != nil { return err } if _, err = w.Write(t.Image); err != nil { return err } } return nil }