Skip to content

Commit

Permalink
spreadsheet: clear temp files when closing sheets
Browse files Browse the repository at this point in the history
We don't bother keeping all files in memory as there
can be several, and we don't need them all.  This just
adds a Close() method that can be used to ensure the
temporary files are removed.
  • Loading branch information
tbaliance committed Oct 2, 2017
1 parent 56e9890 commit 76cd395
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
4 changes: 4 additions & 0 deletions spreadsheet/new.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
package spreadsheet

import (
"runtime"

"baliance.com/gooxml"
"baliance.com/gooxml/common"
"baliance.com/gooxml/schema/soo/sml"
Expand All @@ -18,6 +20,8 @@ func New() *Workbook {
wb := &Workbook{}
wb.x = sml.NewWorkbook()

runtime.SetFinalizer(wb, workbookFinalizer)

wb.AppProperties = common.NewAppProperties()
wb.CoreProperties = common.NewCoreProperties()
wb.StyleSheet = NewStyleSheet(wb)
Expand Down
25 changes: 22 additions & 3 deletions spreadsheet/workbook.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"image/jpeg"
"io"
"os"
"strings"
"time"

"baliance.com/gooxml"
Expand All @@ -29,6 +30,9 @@ import (
"baliance.com/gooxml/schema/soo/sml"
)

// ErrorNotFound is returned when something is not found
var ErrorNotFound = errors.New("not found")

// Workbook is the top level container item for a set of spreadsheets.
type Workbook struct {
common.DocBase
Expand Down Expand Up @@ -552,11 +556,26 @@ func (wb *Workbook) Protection() WorkbookProtection {
return WorkbookProtection{wb.x.WorkbookProtection}
}

func (wb *Workbook) GetSheet(name string) Sheet {
// GetSheet returns a sheet by name, or an error if a sheet by the given name
// was not found.
func (wb *Workbook) GetSheet(name string) (Sheet, error) {
for _, s := range wb.Sheets() {
if s.Name() == name {
return s
return s, nil
}
}
return Sheet{}
return Sheet{}, ErrorNotFound
}

func workbookFinalizer(wb *Workbook) {
wb.Close()
}

// Close closes the workbook, removing any temporary files that might have been
// created when opening a document.
func (wb *Workbook) Close() error {
if wb.TmpPath != "" && strings.HasPrefix(wb.TmpPath, os.TempDir()) {
return os.RemoveAll(wb.TmpPath)
}
return nil
}

0 comments on commit 76cd395

Please sign in to comment.