-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathpackage.go
311 lines (255 loc) · 7.9 KB
/
package.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
// Copyright (c) 2017 Andrey Gayvoronsky <[email protected]>
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package ooxml
import (
"archive/zip"
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"path"
"reflect"
"regexp"
)
//Package is interface to expose some of PackageInfo methods via embedded struct
type Package interface {
io.Closer
Save() error
SaveAs(target interface{}) error
}
//DocumentFactoryFn is factory to in a OOXML type specific type
type DocumentFactoryFn func(pkg *PackageInfo) (interface{}, error)
//DocumentValidatorFn is callback to validate OOXML document. Using right before saving
type DocumentValidatorFn func() error
//PackageInfo holds all required information for OOXML package
type PackageInfo struct {
Validator DocumentValidatorFn
reader interface{}
contentTypes *ContentTypes
relationships *Relationships
files map[string]interface{}
fileName string
}
var _ Package = (*PackageInfo)(nil)
//ErrorUnknownPackage returns a common error if DocumentFactoryFn returned invalid result
func ErrorUnknownPackage(p interface{}) error {
return fmt.Errorf("unknown type of document, expects: %s", reflect.Indirect(reflect.ValueOf(p)).Type().Name())
}
//NewPackage returns a new package with zip reader if there is any
func NewPackage(reader interface{}) *PackageInfo {
pkg := &PackageInfo{}
var zipReader *zip.Reader
switch rt := reader.(type) {
case *zip.Reader:
pkg.reader = rt
zipReader = rt
case *zip.ReadCloser:
pkg.reader = rt
zipReader = &rt.Reader
}
pkg.files = make(map[string]interface{})
if pkg.reader != nil {
//if there is a reader, than populate files with minimal information
for _, f := range zipReader.File {
pkg.files[f.Name] = f
switch {
case f.Name == "_rels/.rels":
pkg.relationships = NewRelationships(f, pkg)
case f.Name == "[Content_Types].xml":
pkg.contentTypes = newContentTypes(f, pkg)
}
}
} else {
//if it's a new package, then add minimal required information for any OOXML document
pkg.initPackage()
}
return pkg
}
//Open opens a file with fileName or io.Reader and returns an instance of document
func Open(f interface{}, docFactory DocumentFactoryFn) (interface{}, error) {
var pkg *PackageInfo
switch ft := f.(type) {
case string:
//f is name of file to open
zipFile, err := zip.OpenReader(ft)
if err != nil {
return nil, err
}
pkg = NewPackage(zipFile)
pkg.fileName = ft
case io.Reader:
//f is reader to read from
b, err := ioutil.ReadAll(ft)
if err != nil {
panic(err)
}
readerAt := bytes.NewReader(b)
zipReader, err := zip.NewReader(readerAt, int64(readerAt.Len()))
if err != nil {
return nil, err
}
pkg = NewPackage(zipReader)
default:
return nil, errors.New("unsupported type of f. It must be name of file or io.Reader")
}
return docFactory(pkg)
}
//IsNew returns true if package is a new one or false in other case
func (pkg *PackageInfo) IsNew() bool {
return pkg.reader == nil
}
//Close closes current OOXML package
func (pkg *PackageInfo) Close() error {
//close all opened reading streams
for _, content := range pkg.files {
if sr, ok := content.(*StreamFileReader); ok {
if err := sr.Close(); err != nil {
return err
}
}
}
//close zip reader
if closer, ok := pkg.reader.(*zip.ReadCloser); ok {
return closer.Close()
}
return nil
}
//Save saves current OOXML package
func (pkg *PackageInfo) Save() error {
if pkg.fileName == "" {
return fmt.Errorf("no filename defined for file. Try to use SaveAs")
}
//create file with a temp name
tmpFile, err := ioutil.TempFile(path.Dir(pkg.fileName), path.Base(pkg.fileName))
if err != nil {
return err
}
//save content
err = pkg.SavePackage(tmpFile)
if err != nil {
os.Remove(tmpFile.Name())
return err
}
tmpFile.Close()
//rename temp file into original name
return os.Rename(tmpFile.Name(), pkg.fileName)
}
//SaveAs saves current OOXML package with fileName or io.Writer
func (pkg *PackageInfo) SaveAs(target interface{}) error {
switch tt := target.(type) {
case io.Writer:
return pkg.SavePackage(tt)
case string:
f, err := os.OpenFile(tt, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666)
if err != nil {
return err
}
err = pkg.SavePackage(f)
f.Close()
return err
}
return fmt.Errorf("unsupported type of target. It must be name of file or io.Writer")
}
//FileName is a private method that returns filename of opened file
func (pkg *PackageInfo) FileName() string {
return pkg.fileName
}
//Add is a private method that adds a file to a package
func (pkg *PackageInfo) Add(fileName string, content interface{}) {
pkg.files[fileName] = content
}
//File is a private method that returns file with required name
func (pkg *PackageInfo) File(fileName string) interface{} {
for pkgFileName, content := range pkg.files {
if pkgFileName == fileName {
return content
}
}
return nil
}
//Remove is a private method that removes file from a package
func (pkg *PackageInfo) Remove(fileName string) {
if _, ok := pkg.files[fileName]; ok {
//remove content
delete(pkg.files, fileName)
//remove info about type of content
pkg.ContentTypes().RemoveContent(fileName)
}
}
//Files is a private method to get list of all files inside of package, using regexp pattern if required
func (pkg *PackageInfo) Files(pattern *regexp.Regexp) map[string]interface{} {
if pattern == nil {
return pkg.files
}
files := make(map[string]interface{})
for fileName, file := range pkg.files {
if pattern.MatchString(fileName) {
files[fileName] = file
}
}
return files
}
//SavePackage is private method with implementation of saving OOXML document to file
func (pkg *PackageInfo) SavePackage(f io.Writer) error {
//If there is a validator, then validate and exit if there is any error and package can't be saved
if pkg.Validator != nil {
if err := pkg.Validator(); err != nil {
return err
}
}
//files holds differ kind of information:
// 1) pointers to original files (*zip.File) that where not changed and must be coped as is
// 2) pointers to write only files (*StreamFileWriter) that require callback execution to save information
// 3) pointers to objects that must be marshaled to get content for a new file
var err error
zipper := zip.NewWriter(f)
//add files to zip
for fileName, content := range pkg.files {
switch ft := content.(type) {
case *zip.File:
//file was not updated, so lets copy it as is
err = CopyZipFile(ft, zipper)
case *StreamFileWriter:
//file was created as write stream, so copy it as is
err = ft.Save(zipper)
default:
//file was probably updated, so let's marshal it and save with a new content
err = MarshalZipFile(fileName, content, zipper)
}
if err != nil {
return err
}
}
//looks like zip file was successfully created without any errors
err = zipper.Close()
if err != nil {
return err
}
return nil
}
//Relationships is a getter that returns top-level relationships of package
func (pkg *PackageInfo) Relationships() *Relationships {
return pkg.relationships
}
//ContentTypes is a getter that returns content types of package
func (pkg *PackageInfo) ContentTypes() *ContentTypes {
return pkg.contentTypes
}
//initPackage populates package with minimal required information for any OOXML document
func (pkg *PackageInfo) initPackage() {
//content types must be initialized first of all - other types will use it
pkg.contentTypes = newContentTypes("[Content_Types].xml", pkg)
//register top-level relations
pkg.relationships = NewRelationships("_rels/.rels", pkg)
//add some default types
pkg.contentTypes.RegisterType("rels", ContentTypeRelationships)
pkg.contentTypes.RegisterType("vml", ContentTypeVmlDrawing)
pkg.contentTypes.RegisterType("png", "image/png")
pkg.contentTypes.RegisterType("jpeg", "image/jpeg")
pkg.contentTypes.RegisterType("jpg", "image/jpeg")
pkg.contentTypes.RegisterType("gif", "image/gif")
pkg.contentTypes.RegisterType("xml", "application/xml")
}