Skip to content

Commit

Permalink
Handle absolute paths in relationships file, prevent panic on closing…
Browse files Browse the repository at this point in the history
… unopened files (#23)

* Handle absolute paths in relationships file

* Prevent closing an unopened file panicing
  • Loading branch information
dglsparsons authored Sep 13, 2020
1 parent f13424b commit 39d0773
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 4 deletions.
3 changes: 3 additions & 0 deletions file.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,9 @@ func readFile(file *zip.File) ([]byte, error) {

// Close closes the XlsxFile, rendering it unusable for I/O.
func (xl *XlsxFileCloser) Close() error {
if xl == nil {
return nil
}
return xl.zipReadCloser.Close()
}

Expand Down
15 changes: 11 additions & 4 deletions file_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,17 +33,24 @@ func TestGettingFileByNameFailure(t *testing.T) {
}

func TestOpeningMissingFile(t *testing.T) {
_, err := OpenFile("this_doesnt_exist.zip")
f, err := OpenFile("this_doesnt_exist.zip")
defer f.Close()

require.EqualError(t, err, "open this_doesnt_exist.zip: no such file or directory")
}

func TestHandlingSpuriousWorkbookLinks(t *testing.T) {
f, err := OpenFile("./test/test-xl-relationship-prefix.xlsx")
defer f.Close()
require.NoError(t, err)
}

func TestOpeningXlsxFile(t *testing.T) {
actual, err := OpenFile("./test/test-small.xlsx")
defer actual.Close()
f, err := OpenFile("./test/test-small.xlsx")
defer f.Close()

require.NoError(t, err)
require.Equal(t, []string{"datarefinery_groundtruth_400000"}, actual.Sheets)
require.Equal(t, []string{"datarefinery_groundtruth_400000"}, f.Sheets)
}

func TestClosingFile(t *testing.T) {
Expand Down
6 changes: 6 additions & 0 deletions sheets.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"archive/zip"
"encoding/xml"
"fmt"
"strings"
)

// workbook is a struct representing the data we care about from the workbook.xml file.
Expand All @@ -30,6 +31,11 @@ type relationship struct {
func getFileNameFromRelationships(rels []relationship, s sheet) (string, error) {
for _, rel := range rels {
if rel.ID == s.RelationshipID {
if strings.HasPrefix(rel.Target, "/") {
// path is absolute, take all but the leading slash
return rel.Target[1:], nil
}
// path is relative, so needs xl/ adding
return "xl/" + rel.Target, nil
}
}
Expand Down
Binary file added test/test-xl-relationship-prefix.xlsx
Binary file not shown.

0 comments on commit 39d0773

Please sign in to comment.