oficina / sheets Public

Sheets import: a report, saved values for what cannot be calculated, typed text kept

xlsx.Import now returns a Report (codes, A1 coordinates and counts; no
content) alongside its error, and holds every cell to what the workbook
declared it to be.

A bounded second reader (scan_parts.go, scan_sheet.go) reads the first
worksheet's XML directly: resolved the way excelize resolves it, capped
in entries, bytes, depth and cells, matching the exact
worksheet/sheetData/row/c path so a decoy <c> or <v> elsewhere is not a
cell. It records whether a formula's <v> was present, which excelize
cannot say. Duplicate cells (by coordinate), duplicate <f>/<v>, unknown
f/@t, a formula or string cell without r or filed under another row,
and a chartsheet first all refuse. Excelize and the scan must agree on
which cells hold formulas, on each scanned cell's type and on each
formula's saved value, or the import stops at that cell.

Formulas (calc.Inspect):
- kept when the engine parses them and has every function; the result
  is compared with the saved value (numbers within 1e-9 relative, kinds
  strict) and differences reported; volatile formulas, formulas with no
  usable saved value, and every formula after a capped recalculation
  are reported unchecked;
- frozen to their saved value, reported by coordinate, when they are
  __xludf. (Google-only, including inside IFERROR), array or dataTable,
  sheet-qualified or external, unparseable, or call unknown functions;
- a frozen value must be a present <v>: finite n, b exactly 0/1, or str
  (empty allowed); e, absent, or any other type refuses the import.

Literal cells: text (shared, inline, str) goes through store.TextInput,
so "00123", "TRUE", "NaN", "=x" and "" stay text as ="..."; wrapped
input over 8 KiB refuses. Empty strings excelize's row reader drops
from the end of a row are visited from the scan. Booleans must be 0/1,
numbers finite; literal error and date cells refuse rather than turn
into text.

Reported, never imported: other worksheets (count), merges, comments,
validation, conditional formats, hyperlinks, defined names, hidden
rows/columns, frozen panes, filters, pictures, workbook charts and
images, and cells whose style used what is not carried (borders,
built-in number formats, wrap, fonts unlike the default, ...).

Fixtures are synthetic: raw XML written part by part (rawbook_test.go)
in the shapes Google and Excel write, and an excelize-built workbook
with one of each omitted feature. No real Google export is in the
corpus yet.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by codex agent, operated by paul@keymail.dev 0bdaa762483160ca4d7e2de02ce4253fa555d34f parent c005999
19 files changed, +1,773 −119
  • internal/sheets/handlers_import.go +1 −1
  • internal/sheets/xlsx/agree_test.go +34 −0
  • internal/sheets/xlsx/blob.go +4 −3
  • internal/sheets/xlsx/blob_test.go +1 −1
  • internal/sheets/xlsx/cell.go +247 −0
  • internal/sheets/xlsx/classify.go +70 −0
  • internal/sheets/xlsx/helpers_test.go +1 −1
  • internal/sheets/xlsx/import.go +85 −111
  • internal/sheets/xlsx/import_omissions_test.go +105 −0
  • internal/sheets/xlsx/import_refusals_test.go +114 −0
  • internal/sheets/xlsx/import_values_test.go +161 −0
  • internal/sheets/xlsx/omissions.go +96 −0
  • internal/sheets/xlsx/plaintext_test.go +1 −1
  • internal/sheets/xlsx/rawbook_test.go +140 −0
  • internal/sheets/xlsx/report.go +119 −0
  • internal/sheets/xlsx/roundtrip_test.go +1 −1
  • internal/sheets/xlsx/saved.go +128 −0
  • internal/sheets/xlsx/scan_parts.go +229 −0
  • internal/sheets/xlsx/scan_sheet.go +236 −0

CI passed — run details

diff --git a/internal/sheets/handlers_import.go b/internal/sheets/handlers_import.go
index 78661db..32df3b8 100644
--- a/internal/sheets/handlers_import.go
+++ b/internal/sheets/handlers_import.go
@@ -181,7 +181,7 @@ func (a *App) runImport(ctx context.Context, s SheetSummary, data []byte, progre
}
defer h.Release()
- if err := xlsx.Import(bytes.NewReader(data), h); err != nil {
+ if _, err := xlsx.Import(bytes.NewReader(data), h); err != nil {
a.discardSheet(s.ID)
return importFailure(err)
}
diff --git a/internal/sheets/xlsx/agree_test.go b/internal/sheets/xlsx/agree_test.go
new file mode 100644
index 0000000..bd80bbf
--- /dev/null
+++ b/internal/sheets/xlsx/agree_test.go
@@ -0,0 +1,34 @@
+package xlsx
+
+import (
+ "errors"
+ "testing"
+
+ "github.com/xuri/excelize/v2"
+)
+
+// agree is the check that keeps either reader from supplying a value
+// alone. Both read the same bytes, so a real workbook rarely makes
+// them differ; this drives the check directly with a scan that says
+// something excelize does not.
+func TestAgreeRefusesAScanExcelizeDoesNotConfirm(t *testing.T) {
+ f := excelize.NewFile()
+ defer f.Close()
+ sheet := f.GetSheetList()[0]
+ if err := f.SetCellFormula(sheet, "A1", "FOO(1)"); err != nil {
+ t.Fatal(err)
+ }
+ im := &importer{f: f, sheet: sheet}
+ for name, sc := range map[string]scannedCell{
+ "a saved value excelize did not read": {HasF: true, T: "str", HasV: true, V: "3"},
+ "a declared type excelize did not read": {HasF: true, T: "b"},
+ } {
+ if err := im.agree("A1", sc); !errors.Is(err, errScanInconsistent) {
+ t.Errorf("%s: agree = %v, want errScanInconsistent", name, err)
+ }
+ }
+ // excelize holds a formula it was given in memory as t="str".
+ if err := im.agree("A1", scannedCell{HasF: true, T: "str"}); err != nil {
+ t.Errorf("matching scan: agree = %v, want nil", err)
+ }
+}
diff --git a/internal/sheets/xlsx/blob.go b/internal/sheets/xlsx/blob.go
index 7911f77..a3473c8 100644
--- a/internal/sheets/xlsx/blob.go
+++ b/internal/sheets/xlsx/blob.go
@@ -48,11 +48,12 @@ func StoreSealed(ctx context.Context, underlying blobs.Store, key []byte, h *sto
}
// LoadSealed reads a blob written by StoreSealed (or any XLSX blob sealed
-// under key with blobs.Sealed) and imports it into h.
-func LoadSealed(ctx context.Context, underlying blobs.Store, key []byte, ref blobs.Ref, h *store.Handle) error {
+// under key with blobs.Sealed) and imports it into h, with Import's
+// report.
+func LoadSealed(ctx context.Context, underlying blobs.Store, key []byte, ref blobs.Ref, h *store.Handle) (Report, error) {
rc, err := blobs.Sealed(underlying, key).Get(ctx, ref.Hash)
if err != nil {
- return fmt.Errorf("xlsx: load sealed import: %w", err)
+ return Report{}, fmt.Errorf("xlsx: load sealed import: %w", err)
}
defer rc.Close()
return Import(rc, h)
diff --git a/internal/sheets/xlsx/blob_test.go b/internal/sheets/xlsx/blob_test.go
index 5e59a43..313e07a 100644
--- a/internal/sheets/xlsx/blob_test.go
+++ b/internal/sheets/xlsx/blob_test.go
@@ -83,7 +83,7 @@ func TestStoreSealedNeverWritesPlaintext(t *testing.T) {
// And the round trip itself must still work: LoadSealed recovers
// exactly what was stored.
h2 := newTab(t, db, testSealer(t))
- if err := xlsx.LoadSealed(context.Background(), underlying, key, ref, h2); err != nil {
+ if _, err := xlsx.LoadSealed(context.Background(), underlying, key, ref, h2); err != nil {
t.Fatalf("LoadSealed: %v", err)
}
rowID2, colID2, ok := cellAt(h2, 0, 0)
diff --git a/internal/sheets/xlsx/cell.go b/internal/sheets/xlsx/cell.go
new file mode 100644
index 0000000..e358732
--- /dev/null
+++ b/internal/sheets/xlsx/cell.go
@@ -0,0 +1,247 @@
+package xlsx
+
+import (
+ "errors"
+ "math"
+ "strconv"
+
+ "github.com/xuri/excelize/v2"
+
+ "amadan.net/oficina/sheets/internal/sheets/store"
+)
+
+// importer carries one import's state across its cells.
+type importer struct {
+ f *excelize.File
+ sheet string
+ h *store.Handle
+ scan *sheetScan
+ base *excelize.Style
+ rep *Report
+ kept []keptFormula
+ // capped is set when any write's recalculation was too wide to
+ // run (calc.MaxDirtyPerPass): its dependents stay dirty until the
+ // tab is next opened, so no value read during this import can be
+ // trusted as final.
+ capped bool
+}
+
+// keptFormula is a formula written as a formula, remembered so its
+// result can be compared with its saved value once every cell it could
+// depend on has been written.
+type keptFormula struct {
+ pos posKey
+ rowID, colID uint64
+ saved scannedCell
+ volatile bool
+}
+
+// Refusals a cell can cause. Each becomes a CellError, so the
+// coordinate is data and the cause stays out of the error's text.
+var (
+ errTextTooLong = errors.New("xlsx: text needs a wrapper past the input limit")
+ errCellIsError = errors.New("xlsx: cell holds an error value")
+ errCellNotNumber = errors.New("xlsx: number cell is not a finite number")
+ errCellType = errors.New("xlsx: cell type is not one import reads")
+)
+
+// cell imports one position. It creates the backing Row/Col only if
+// the cell has content or a format worth recording — an interior blank
+// cell with neither leaves no trace, matching the sparse model
+// (models.go's comment on Cell).
+func (im *importer) cell(p posKey, raw string) error {
+ ref, err := excelize.CoordinatesToCellName(p.Col+1, p.Row+1)
+ if err != nil {
+ return cellErr("cannot address cell", p.Row, p.Col, err)
+ }
+ formula, err := im.f.GetCellFormula(im.sheet, ref)
+ if err != nil {
+ return cellErr("cannot read the formula at", p.Row, p.Col, err)
+ }
+ sc, scanned := im.scan.Cells[p]
+ if (formula != "") != (scanned && sc.HasF) {
+ return cellErr("the workbook's parts disagree at", p.Row, p.Col, errScanInconsistent)
+ }
+ if scanned {
+ if err := im.agree(ref, sc); err != nil {
+ return cellErr("the workbook's parts disagree at", p.Row, p.Col, err)
+ }
+ }
+
+ var (
+ input string
+ cls formulaClass
+ )
+ if formula != "" {
+ cls = classify(formula, sc.FType)
+ input, err = im.formulaInput(p, formula, cls, sc)
+ } else {
+ input, err = im.literalInput(p, ref, raw, sc, scanned)
+ }
+ if err != nil {
+ return err
+ }
+
+ styleID, err := im.f.GetCellStyle(im.sheet, ref)
+ if err != nil {
+ return cellErr("cannot read the style at", p.Row, p.Col, err)
+ }
+ style, err := im.f.GetStyle(styleID)
+ if err != nil {
+ return cellErr("cannot read the style at", p.Row, p.Col, err)
+ }
+ format, hasFormat := formatFromStyle(style)
+ if input == "" && !hasFormat {
+ return nil // nothing here worth a Row/Col at all
+ }
+ if partialStyle(style, im.base) {
+ im.rep.cell(FormatPartial, p.Row, p.Col)
+ }
+
+ rowID, err := im.h.EnsureRow(p.Row)
+ if err != nil {
+ return cellErr("cannot make the row for cell", p.Row, p.Col, err)
+ }
+ colID, err := im.h.EnsureCol(p.Col)
+ if err != nil {
+ return cellErr("cannot make the column for cell", p.Row, p.Col, err)
+ }
+ if input != "" {
+ rep, err := im.h.SetReport(rowID, colID, input, importActor)
+ if err != nil {
+ return cellErr("cannot parse cell", p.Row, p.Col, err)
+ }
+ im.capped = im.capped || rep.Capped
+ }
+ if hasFormat {
+ if err := im.h.SetFormat(rowID, colID, format); err != nil {
+ return cellErr("cannot set the format at", p.Row, p.Col, err)
+ }
+ }
+ if formula != "" && cls.Supported {
+ im.kept = append(im.kept, keptFormula{pos: p, rowID: rowID, colID: colID,
+ saved: sc, volatile: cls.Volatile})
+ }
+ return nil
+}
+
+// formulaInput is a formula cell's raw input: the formula itself when
+// it is supported, otherwise its saved value, reported.
+func (im *importer) formulaInput(p posKey, formula string, cls formulaClass, sc scannedCell) (string, error) {
+ if cls.Supported {
+ return "=" + formula, nil
+ }
+ v, err := savedValue(sc)
+ if err != nil {
+ return "", cellErr("a formula has no usable saved value at", p.Row, p.Col, err)
+ }
+ input, wrapped := frozenInput(v)
+ if wrapped && len(input) > store.MaxInputBytes {
+ return "", cellErr("text is too long to keep as text at", p.Row, p.Col, errTextTooLong)
+ }
+ im.rep.cell(cls.Code, p.Row, p.Col)
+ if wrapped {
+ im.rep.cell(TextKept, p.Row, p.Col)
+ }
+ return input, nil
+}
+
+// literalInput is a non-formula cell's raw input, typed by what the
+// workbook declared the cell to be rather than by what its text looks
+// like.
+func (im *importer) literalInput(p posKey, ref, raw string, sc scannedCell, scanned bool) (string, error) {
+ cellType, err := im.f.GetCellType(im.sheet, ref)
+ if err != nil {
+ return "", cellErr("cannot read the cell type at", p.Row, p.Col, err)
+ }
+ switch cellType {
+ case excelize.CellTypeSharedString, excelize.CellTypeInlineString, excelize.CellTypeFormula:
+ // Text. An empty string is text too, where the workbook wrote
+ // one: an inline string, or a <v> the scan saw.
+ if raw == "" && !(scanned && (sc.HasV || sc.T == "inlineStr")) {
+ return "", nil
+ }
+ input, wrapped := store.TextInput(raw)
+ if wrapped {
+ if len(input) > store.MaxInputBytes {
+ return "", cellErr("text is too long to keep as text at", p.Row, p.Col, errTextTooLong)
+ }
+ im.rep.cell(TextKept, p.Row, p.Col)
+ }
+ return input, nil
+ case excelize.CellTypeBool:
+ switch raw {
+ case "1":
+ return "TRUE", nil
+ case "0":
+ return "FALSE", nil
+ }
+ return "", cellErr("cannot read the boolean at", p.Row, p.Col, errCellType)
+ case excelize.CellTypeUnset, excelize.CellTypeNumber:
+ if raw == "" {
+ return "", nil
+ }
+ n, err := strconv.ParseFloat(raw, 64)
+ if err != nil || math.IsNaN(n) || math.IsInf(n, 0) {
+ return "", cellErr("cannot read the number at", p.Row, p.Col, errCellNotNumber)
+ }
+ return raw, nil
+ case excelize.CellTypeError:
+ return "", cellErr("a cell holds an error value at", p.Row, p.Col, errCellIsError)
+ }
+ return "", cellErr("cannot read the cell type at", p.Row, p.Col, errCellType)
+}
+
+// compare checks every kept formula against the value its workbook
+// saved, after the last cell is written so each result is final.
+//
+// Final only if no write was capped. A capped write leaves dependents
+// dirty until the tab is next opened, and a stale value could match or
+// miss a saved one by accident, so then nothing is compared: every
+// kept formula is reported unchecked instead.
+func (im *importer) compare() {
+ for _, k := range im.kept {
+ saved, ok := comparableSaved(k.saved)
+ if !ok || k.volatile || im.capped {
+ im.rep.cell(FormulaUnchecked, k.pos.Row, k.pos.Col)
+ continue
+ }
+ if !sameValue(im.h.Value(k.rowID, k.colID), saved) {
+ im.rep.cell(FormulaDiffers, k.pos.Row, k.pos.Col)
+ }
+ }
+}
+
+// scanTypes maps a c element's t to excelize's reading of it, absent
+// and unknown both reading as Unset, as excelize's own table does.
+var scanTypes = map[string]excelize.CellType{
+ "b": excelize.CellTypeBool, "d": excelize.CellTypeDate, "n": excelize.CellTypeNumber,
+ "e": excelize.CellTypeError, "s": excelize.CellTypeSharedString,
+ "str": excelize.CellTypeFormula, "inlineStr": excelize.CellTypeInlineString,
+}
+
+// agree checks that excelize read a scanned cell as the scan did: the
+// same declared type and, for a formula whose <v> is the value itself
+// rather than an index or a date, the same saved value. Either reader
+// could be the one that is wrong; a disagreement stops the import
+// rather than let one of them quietly supply the value.
+func (im *importer) agree(ref string, sc scannedCell) error {
+ cellType, err := im.f.GetCellType(im.sheet, ref)
+ if err != nil {
+ return err
+ }
+ if cellType != scanTypes[sc.T] {
+ return errScanInconsistent
+ }
+ if !sc.HasF || sc.T == "s" || sc.T == "inlineStr" || sc.T == "d" {
+ return nil
+ }
+ raw, err := im.f.GetCellValue(im.sheet, ref, excelize.Options{RawCellValue: true})
+ if err != nil {
+ return err
+ }
+ if raw != sc.V {
+ return errScanInconsistent
+ }
+ return nil
+}
diff --git a/internal/sheets/xlsx/classify.go b/internal/sheets/xlsx/classify.go
new file mode 100644
index 0000000..b38ea96
--- /dev/null
+++ b/internal/sheets/xlsx/classify.go
@@ -0,0 +1,70 @@
+package xlsx
+
+import (
+ "strings"
+
+ "amadan.net/oficina/sheets/internal/sheets/calc"
+)
+
+// formulaClass is what import decides about one workbook formula.
+type formulaClass struct {
+ // Supported is true when the formula is kept as a formula: it
+ // parses, and every function it calls is one this engine has.
+ Supported bool
+ // Volatile is true when a kept formula reads the clock, so its
+ // saved value was computed at another moment and is not compared.
+ Volatile bool
+ // Code says why an unsupported formula is not kept.
+ Code Code
+}
+
+// classify decides whether formula (excelize's text, no leading "=")
+// stays a formula, given the type its <f> element declared.
+//
+// Order matters only for which reason a report names; any one of them
+// is enough to freeze the cell. The textual checks come before the
+// parser on purpose: a sheet-qualified or external reference must not
+// be kept even if a later parser learned to read one, because only
+// the first worksheet comes across and the reference would point at
+// nothing.
+func classify(formula, fType string) formulaClass {
+ if fType == "array" || fType == "dataTable" {
+ return formulaClass{Code: FormulaArray}
+ }
+ bare := outsideStrings(formula)
+ if strings.Contains(strings.ToUpper(bare), "__XLUDF.") {
+ return formulaClass{Code: FormulaGoogleOnly}
+ }
+ if strings.ContainsAny(bare, "![") {
+ return formulaClass{Code: FormulaOtherSheet}
+ }
+ node, err := calc.Parse(formula)
+ if err != nil {
+ return formulaClass{Code: FormulaUnsupported}
+ }
+ in := calc.Inspect(node)
+ if in.Unknown {
+ return formulaClass{Code: FormulaUnsupported}
+ }
+ return formulaClass{Supported: true, Volatile: in.Volatile}
+}
+
+// outsideStrings is formula with the contents of its double-quoted
+// string constants removed, so text inside a string ("Sheet2!A1" as a
+// label) cannot read as a reference. A doubled quote inside a string
+// toggles twice and so stays inside it.
+func outsideStrings(formula string) string {
+ var b strings.Builder
+ in := false
+ for i := 0; i < len(formula); i++ {
+ c := formula[i]
+ if c == '"' {
+ in = !in
+ continue
+ }
+ if !in {
+ b.WriteByte(c)
+ }
+ }
+ return b.String()
+}
diff --git a/internal/sheets/xlsx/helpers_test.go b/internal/sheets/xlsx/helpers_test.go
index c3cc600..6b69924 100644
--- a/internal/sheets/xlsx/helpers_test.go
+++ b/internal/sheets/xlsx/helpers_test.go
@@ -115,7 +115,7 @@ func importReader(t *testing.T, r io.Reader) *store.Handle {
t.Helper()
db := openTestDB(t)
h := newTab(t, db, testSealer(t))
- if err := xlsx.Import(r, h); err != nil {
+ if _, err := xlsx.Import(r, h); err != nil {
t.Fatalf("Import: %v", err)
}
return h
diff --git a/internal/sheets/xlsx/import.go b/internal/sheets/xlsx/import.go
index 2c90676..eba8a44 100644
--- a/internal/sheets/xlsx/import.go
+++ b/internal/sheets/xlsx/import.go
@@ -6,9 +6,11 @@
package xlsx
import (
+ "bytes"
"errors"
"fmt"
"io"
+ "sort"
"github.com/xuri/excelize/v2"
@@ -55,152 +57,124 @@ var openLimits = excelize.Options{
UnzipXMLSizeLimit: 64 << 20,
}
-// Import reads an XLSX workbook's first worksheet into h, cell by cell:
-// literal values become literal input, formulas are parsed and
-// evaluated by this app's own engine (never excelize's — see the package
-// doc), and each cell's fill, number format, bold, italic and alignment
-// are carried over via SetFormat.
+// maxWorkbookBytes bounds what Import reads from r. The upload handler
+// caps a file at 20 MB; this is the converter's own bound, since both
+// excelize and the worksheet scan need the whole file in memory.
+const maxWorkbookBytes = 32 << 20
+
+// Import reads an XLSX workbook's first worksheet into h and reports
+// what it changed or left behind.
+//
+// Literal values become literal input; text that would otherwise read
+// as something else is kept as text (store.TextInput). A formula is
+// kept when this app's own engine can calculate it (never excelize's —
+// see the package doc), and its result is compared with the value the
+// workbook saved. Any other formula is replaced by its saved value, and
+// a formula with no trustworthy saved value refuses the whole import:
+// a value is never manufactured. Fill, number format, bold, italic,
+// ink and alignment are carried over via SetFormat.
//
// Errors carry coordinates and codes, never cell content (spec §2.4):
// import runs as a background job whose error text reaches the owner and
// platform logs this app cannot grep, so "cannot parse cell B7" is what
// gets said — never what B7 actually contained.
-func Import(r io.Reader, h *store.Handle) error {
- f, err := excelize.OpenReader(r, openLimits)
+func Import(r io.Reader, h *store.Handle) (Report, error) {
+ data, err := io.ReadAll(io.LimitReader(r, maxWorkbookBytes+1))
+ if err != nil {
+ return Report{}, fmt.Errorf("xlsx: read workbook: %w", err)
+ }
+ if len(data) > maxWorkbookBytes {
+ return Report{}, errScanLimit
+ }
+ f, err := excelize.OpenReader(bytes.NewReader(data), openLimits)
if err != nil {
- return fmt.Errorf("xlsx: open workbook: %w", err)
+ return Report{}, fmt.Errorf("xlsx: open workbook: %w", err)
}
defer f.Close()
sheetList := f.GetSheetList()
if len(sheetList) == 0 {
- return errors.New("xlsx: workbook has no worksheets")
+ return Report{}, errors.New("xlsx: workbook has no worksheets")
}
sheetName := sheetList[0]
+ // The second reader: what the worksheet XML itself says about
+ // formulas and their saved values. It must name the same first
+ // sheet excelize does, or neither is trusted.
+ scan, err := scanWorkbook(data)
+ if err != nil {
+ return Report{}, fmt.Errorf("xlsx: scan worksheet: %w", err)
+ }
+ if scan.Name != sheetName {
+ return Report{}, errScanInconsistent
+ }
+
rows, err := f.GetRows(sheetName, excelize.Options{RawCellValue: true})
if err != nil {
- return fmt.Errorf("xlsx: read worksheet: %w", err)
+ return Report{}, fmt.Errorf("xlsx: read worksheet: %w", err)
}
// Fail before writing anything: a partial import left behind by
- // hitting the cap mid-way through would be a confusing half state,
- // and the bounding box is a cheap, conservative upper bound on the
- // cell count to check it against up front.
- total := 0
- for _, row := range rows {
- total += len(row)
- }
- if total > store.MaxCellsPerTab {
- return store.ErrTabTooLarge
+ // hitting the cap mid-way through would be a confusing half state.
+ positions := cellPositions(rows, scan)
+ if len(positions) > store.MaxCellsPerTab {
+ return Report{}, store.ErrTabTooLarge
}
- for rowPos, row := range rows {
- for colPos, raw := range row {
- if err := importCell(f, sheetName, h, rowPos, colPos, raw); err != nil {
- return err
- }
+ base, err := f.GetStyle(0)
+ if err != nil {
+ return Report{}, fmt.Errorf("xlsx: read the default style: %w", err)
+ }
+ im := &importer{f: f, sheet: sheetName, h: h, scan: scan, base: base,
+ rep: &Report{Worksheets: len(sheetList)}}
+ for _, p := range positions {
+ raw := ""
+ if p.Row < len(rows) && p.Col < len(rows[p.Row]) {
+ raw = rows[p.Row][p.Col]
+ }
+ if err := im.cell(p, raw); err != nil {
+ return Report{}, err
}
}
+ im.compare()
+ reportOmissions(f, sheetName, scan, im.rep)
// Layout last, and best effort. A workbook whose widths cannot be
// read is still a workbook whose cells can, and refusing the import
// over its margins would trade the document for its formatting.
widest := 0
- for _, row := range rows {
- if len(row) > widest {
- widest = len(row)
- }
+ for _, p := range positions {
+ widest = max(widest, p.Col+1)
}
importSizes(f, sheetName, h, len(rows), widest)
- return nil
+ return *im.rep, nil
}
-// importCell imports one XLSX cell at (rowPos, colPos) (0-based). It
-// creates the backing Row/Col only if the cell actually has content or a
-// format worth recording — an interior blank cell with neither leaves no
-// trace, matching the sparse model (models.go's comment on Cell).
-func importCell(f *excelize.File, sheetName string, h *store.Handle, rowPos, colPos int, raw string) error {
- cellRef, err := excelize.CoordinatesToCellName(colPos+1, rowPos+1)
- if err != nil {
- return cellErr("cannot address cell", rowPos, colPos, err)
- }
-
- input, err := cellInputText(f, sheetName, cellRef, rowPos, colPos, raw)
- if err != nil {
- return err
- }
-
- styleID, err := f.GetCellStyle(sheetName, cellRef)
- if err != nil {
- return cellErr("cannot read the style at", rowPos, colPos, err)
- }
- style, err := f.GetStyle(styleID)
- if err != nil {
- return cellErr("cannot read the style at", rowPos, colPos, err)
- }
- format, hasFormat := formatFromStyle(style)
-
- if input == "" && !hasFormat {
- return nil // nothing here worth a Row/Col at all
- }
-
- rowID, err := h.EnsureRow(rowPos)
- if err != nil {
- return cellErr("cannot make the row for cell", rowPos, colPos, err)
- }
- colID, err := h.EnsureCol(colPos)
- if err != nil {
- return cellErr("cannot make the column for cell", rowPos, colPos, err)
- }
-
- if input != "" {
- if err := h.Set(rowID, colID, input, importActor); err != nil {
- return cellErr("cannot parse cell", rowPos, colPos, err)
+// cellPositions is every position import visits, in row-major order:
+// each cell excelize's row reader returned, plus each formula or
+// string cell the scan found. The second half matters because the row
+// reader drops empty values from the end of a row, and a formula whose
+// saved value is "" or an empty-string text cell is not nothing.
+func cellPositions(rows [][]string, scan *sheetScan) []posKey {
+ seen := make(map[posKey]bool, len(scan.Cells))
+ var out []posKey
+ for r, row := range rows {
+ for c := range row {
+ p := posKey{Row: r, Col: c}
+ seen[p] = true
+ out = append(out, p)
}
}
- if hasFormat {
- if err := h.SetFormat(rowID, colID, format); err != nil {
- return cellErr("cannot set the format at", rowPos, colPos, err)
+ for p := range scan.Cells {
+ if !seen[p] {
+ out = append(out, p)
}
}
- return nil
-}
-
-// cellInputText decides what raw text (this app's own Set contract:
-// "" is blank, a leading "=" is a formula, anything else is a literal —
-// store/handle_codec.go) a cell becomes.
-//
-// A genuine XLSX formula is detected through excelize's own formula
-// reader, never by sniffing raw's leading character — but a plain TEXT
-// cell whose content happens to start with "=" is indistinguishable from
-// a formula once it becomes this app's raw text, because Set's contract
-// (predating this task — store/handle_codec.go, task 10) has exactly one
-// signal for "is this a formula": a leading "=" in the one text field a
-// cell has. That is a pre-existing modeling gap this task inherits, not
-// one introduced by XLSX import; it is called out in the task report
-// rather than worked around here.
-func cellInputText(f *excelize.File, sheetName, cellRef string, rowPos, colPos int, raw string) (string, error) {
- formula, err := f.GetCellFormula(sheetName, cellRef)
- if err != nil {
- return "", cellErr("cannot read the formula at", rowPos, colPos, err)
- }
- if formula != "" {
- return "=" + formula, nil
- }
- if raw == "" {
- return "", nil
- }
-
- cellType, err := f.GetCellType(sheetName, cellRef)
- if err != nil {
- return "", cellErr("cannot read the cell type at", rowPos, colPos, err)
- }
- if cellType == excelize.CellTypeBool {
- if raw == "1" {
- return "TRUE", nil
+ sort.Slice(out, func(i, j int) bool {
+ if out[i].Row != out[j].Row {
+ return out[i].Row < out[j].Row
}
- return "FALSE", nil
- }
- return raw, nil
+ return out[i].Col < out[j].Col
+ })
+ return out
}
diff --git a/internal/sheets/xlsx/import_omissions_test.go b/internal/sheets/xlsx/import_omissions_test.go
new file mode 100644
index 0000000..9b07670
--- /dev/null
+++ b/internal/sheets/xlsx/import_omissions_test.go
@@ -0,0 +1,105 @@
+package xlsx_test
+
+import (
+ "bytes"
+ "encoding/json"
+ "image"
+ "image/png"
+ "strings"
+ "testing"
+
+ "github.com/xuri/excelize/v2"
+
+ "amadan.net/oficina/sheets/internal/sheets/xlsx"
+)
+
+// featureBook is a workbook carrying one of each feature the import
+// leaves behind, built with excelize so each is written the way a real
+// spreadsheet writes it.
+func featureBook(t *testing.T) *bytes.Buffer {
+ t.Helper()
+ f := excelize.NewFile()
+ s := f.GetSheetList()[0]
+ must := func(err error) {
+ t.Helper()
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ for i, v := range []float64{1, 2, 3} {
+ cell, _ := excelize.CoordinatesToCellName(1, i+1)
+ must(f.SetCellFloat(s, cell, v, -1, 64))
+ }
+ must(f.SetCellStr(s, "B1", canary))
+ must(f.MergeCell(s, "B1", "C1"))
+ must(f.AddComment(s, excelize.Comment{Cell: "A1", Author: "a", Text: canary}))
+ dv := excelize.NewDataValidation(true)
+ dv.Sqref = "A1:A3"
+ must(dv.SetDropList([]string{"1", "2"}))
+ must(f.AddDataValidation(s, dv))
+ style, err := f.NewConditionalStyle(&excelize.Style{Font: &excelize.Font{Bold: true}})
+ must(err)
+ must(f.SetConditionalFormat(s, "A1:A3", []excelize.ConditionalFormatOptions{
+ {Type: "cell", Criteria: ">", Format: &style, Value: "1"}}))
+ must(f.SetCellHyperLink(s, "A2", "https://example.com/"+canary, "External"))
+ must(f.SetDefinedName(&excelize.DefinedName{Name: "TaxRate", RefersTo: s + "!$A$1"}))
+ must(f.SetRowVisible(s, 3, false))
+ must(f.SetColVisible(s, "D", false))
+ must(f.SetPanes(s, &excelize.Panes{Freeze: true, YSplit: 1, TopLeftCell: "A2", ActivePane: "bottomLeft"}))
+ must(f.AutoFilter(s, "A1:A3", nil))
+ var img bytes.Buffer
+ must(png.Encode(&img, image.NewRGBA(image.Rect(0, 0, 2, 2))))
+ must(f.AddPictureFromBytes(s, "E1", &excelize.Picture{Extension: ".png", File: img.Bytes()}))
+ must(f.AddChart(s, "G1", &excelize.Chart{Type: excelize.Col, Series: []excelize.ChartSeries{
+ {Name: s + "!$A$1", Values: s + "!$A$1:$A$3"}}}))
+ border, err := f.NewStyle(&excelize.Style{Border: []excelize.Border{{Type: "left", Color: "000000", Style: 1}}})
+ must(err)
+ must(f.SetCellStyle(s, "A3", "A3", border))
+ for _, name := range []string{"Second", "Third"} {
+ if _, err := f.NewSheet(name); err != nil {
+ t.Fatal(err)
+ }
+ }
+ var buf bytes.Buffer
+ must(f.Write(&buf))
+ return &buf
+}
+
+func TestImportReportsWhatItLeavesBehind(t *testing.T) {
+ h := newTab(t, openTestDB(t), testSealer(t))
+ rep, err := xlsx.Import(featureBook(t), h)
+ if err != nil {
+ t.Fatalf("Import: %v", err)
+ }
+ if rep.OmittedWorksheets() != 2 {
+ t.Errorf("omitted worksheets = %d, want 2", rep.OmittedWorksheets())
+ }
+ want := map[xlsx.Code]int{
+ xlsx.OmittedMerges: 1, xlsx.OmittedComments: 1, xlsx.OmittedValidation: 1,
+ xlsx.OmittedConditional: 1, xlsx.OmittedHyperlinks: 1, xlsx.OmittedDefinedNames: 1,
+ xlsx.OmittedHiddenRows: 1, xlsx.OmittedHiddenCols: 1, xlsx.OmittedFrozenPanes: 1,
+ xlsx.OmittedFilter: 1, xlsx.OmittedPictures: 1, xlsx.OmittedWorkbookChart: 1,
+ xlsx.OmittedWorkbookImage: 1, xlsx.FormatPartial: 1,
+ }
+ for code, n := range want {
+ if got := entry(rep, code); got.Count != n {
+ t.Logf("%s cells %v", code, got.Cells)
+ t.Errorf("%s = %d, want %d", code, got.Count, n)
+ }
+ }
+ if got := entry(rep, xlsx.OmittedUndetected).Count; got != 0 {
+ t.Errorf("undetected = %d, want every detector to have read its part", got)
+ }
+
+ // The report is codes, coordinates and counts. No text from the
+ // workbook reaches it — not a cell, a comment, a link or a name.
+ body, err := json.Marshal(rep)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, leak := range []string{canary, "TaxRate", "example.com", "Second", "Sheet1"} {
+ if strings.Contains(string(body), leak) {
+ t.Errorf("report carries %q: %s", leak, body)
+ }
+ }
+}
diff --git a/internal/sheets/xlsx/import_refusals_test.go b/internal/sheets/xlsx/import_refusals_test.go
new file mode 100644
index 0000000..6d6b29e
--- /dev/null
+++ b/internal/sheets/xlsx/import_refusals_test.go
@@ -0,0 +1,114 @@
+package xlsx_test
+
+import (
+ "errors"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/sheets/internal/sheets/xlsx"
+)
+
+// canary is content no refusal may repeat.
+const canary = "SECRET-LEDGER-7731"
+
+// Each workbook here must refuse the whole import. Where the cell is
+// known, the refusal names it as data (xlsx.CellError) and its text
+// carries the coordinate and nothing the cell held.
+func TestImportRefusesWhatItCannotTrust(t *testing.T) {
+ long := strings.Repeat("x", 9000)
+ cases := []struct {
+ name string
+ book rawBook
+ ref string // "" when the refusal precedes any one cell
+ }{
+ {"unsupported formula without a saved value",
+ rawBook{sheets: []string{row(1, formula("A1", "", `FOO("`+canary+`")`, nil))}}, "A1"},
+ {"unsupported formula that saved an error",
+ rawBook{sheets: []string{row(1, formula("A1", "e", `FOO("`+canary+`")`, ptr("#N/A")))}}, "A1"},
+ {"unsupported formula that saved a shared-string index",
+ rawBook{sheets: []string{row(1, formula("A1", "s", "FOO(1)", ptr("0")))}}, "A1"},
+ {"unsupported formula that saved a non-number",
+ rawBook{sheets: []string{row(1, formula("A1", "", "FOO(1)", ptr(canary)))}}, "A1"},
+ {"unsupported formula that saved an infinite number",
+ rawBook{sheets: []string{row(1, formula("A1", "", "FOO(1)", ptr("1e999")))}}, "A1"},
+ {"unsupported formula that saved a boolean other than 0 or 1",
+ rawBook{sheets: []string{row(1, formula("A1", "b", "FOO(1)", ptr("2")))}}, "A1"},
+ {"unsupported formula that saved a date",
+ rawBook{sheets: []string{row(1, formula("A1", "d", "FOO(1)", ptr("2026-11-01")))}}, "A1"},
+ {"a literal error value",
+ rawBook{sheets: []string{row(1, `<c r="A1" t="e"><v>#N/A</v></c>`)}}, "A1"},
+ {"a number cell that is not a number",
+ rawBook{sheets: []string{row(1, num("A1", canary))}}, "A1"},
+ {"ambiguous text past the input limit once wrapped",
+ rawBook{sheets: []string{row(1, inline("A1", "="+long))}}, "A1"},
+ {"a frozen saved string past the input limit once wrapped",
+ rawBook{sheets: []string{row(1, formula("A1", "str", "FOO(1)", ptr("="+long)))}}, "A1"},
+ {"a shared formula follower whose master is missing",
+ rawBook{sheets: []string{row(1, `<c r="A1"><f t="shared" si="5"/><v>1</v></c>`)}}, "A1"},
+ {"a cell written twice",
+ rawBook{sheets: []string{row(1, num("A1", "1"), formula("A1", "", "FOO(1)", ptr("2")))}}, ""},
+ {"a cell written twice in different case",
+ rawBook{sheets: []string{row(1, num("A1", "1"), num("a1", "2"))}}, ""},
+ {"a cell with two formulas",
+ rawBook{sheets: []string{row(1, `<c r="A1"><f>1+1</f><f>FOO(1)</f><v>2</v></c>`)}}, ""},
+ {"a cell with two saved values",
+ rawBook{sheets: []string{row(1, `<c r="A1"><f>FOO(1)</f><v>2</v><v>3</v></c>`)}}, ""},
+ {"a formula of a type the standard does not define",
+ rawBook{sheets: []string{row(1, `<c r="A1"><f t="bogus">1+1</f><v>2</v></c>`)}}, ""},
+ {"a formula cell with no reference",
+ rawBook{sheets: []string{`<row r="1"><c><f>FOO(1)</f><v>2</v></c></row>`}}, ""},
+ {"a formula cell filed under another row",
+ rawBook{sheets: []string{row(1, formula("A5", "", "FOO(1)", ptr("2")))}}, ""},
+ {"nesting past the depth bound",
+ rawBook{sheets: []string{row(1, num("A1", "1"))},
+ extra: `<extLst>` + strings.Repeat("<x>", 80) + strings.Repeat("</x>", 80) + `</extLst>`}, ""},
+ {"a chartsheet first",
+ rawBook{sheets: []string{row(1, num("A1", "1"))}, parts: map[string]string{
+ "xl/_rels/workbook.xml.rels": `<?xml version="1.0" encoding="UTF-8"?>
+<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
+<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/chartsheet" Target="worksheets/sheet1.xml"/>
+<Relationship Id="rIdS" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>
+</Relationships>`}}, ""},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ _, _, err := importRaw(t, c.book)
+ if err == nil {
+ t.Fatal("Import succeeded, want a refusal")
+ }
+ if strings.Contains(err.Error(), canary) || strings.Contains(err.Error(), "xxxx") {
+ t.Fatalf("refusal carries cell content: %q", err.Error())
+ }
+ var cell *xlsx.CellError
+ if c.ref != "" && (!errors.As(err, &cell) || cell.Ref != c.ref) {
+ t.Fatalf("refusal = %v, want a CellError at %s", err, c.ref)
+ }
+ })
+ }
+}
+
+// A <c> or <v> anywhere but its own place in sheetData is not a cell
+// and not a saved value, for this reader as for excelize; a decoy
+// there must neither add a cell nor replace the real saved value.
+func TestImportIgnoresDecoysOutsideTheCellPath(t *testing.T) {
+ book := rawBook{
+ sheets: []string{row(1,
+ `<c r="A1"><f>FOO(1)</f><extLst><ext><v>9</v><c r="B1"><f>FOO(2)</f></c></ext></extLst><v>7</v></c>`)},
+ extra: `<extLst><ext><sheetData><row r="2"><c r="A2"><f>FOO(3)</f></c></row></sheetData></ext></extLst>`,
+ }
+ h, rep, err := importRaw(t, book)
+ if err != nil {
+ t.Fatalf("Import: %v", err)
+ }
+ if raw, v := cellByRef(t, h, "A1"); raw != "7" || v.Num != 7 {
+ t.Errorf("A1 = %q %+v, want the saved 7", raw, v)
+ }
+ for _, ref := range []string{"B1", "A2"} {
+ if raw, _ := cellByRef(t, h, ref); raw != "" {
+ t.Errorf("%s = %q, want nothing: it was a decoy", ref, raw)
+ }
+ }
+ if got := entry(rep, xlsx.FormulaUnsupported); got.Count != 1 {
+ t.Errorf("unsupported = %+v, want A1 alone", got)
+ }
+}
diff --git a/internal/sheets/xlsx/import_values_test.go b/internal/sheets/xlsx/import_values_test.go
new file mode 100644
index 0000000..f612797
--- /dev/null
+++ b/internal/sheets/xlsx/import_values_test.go
@@ -0,0 +1,161 @@
+package xlsx_test
+
+import (
+ "strconv"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/sheets/internal/sheets/calc"
+ "amadan.net/oficina/sheets/internal/sheets/store"
+ "amadan.net/oficina/sheets/internal/sheets/xlsx"
+)
+
+// googleBook is a first worksheet in the shapes a Google Sheets export
+// writes, with a second worksheet that must not come across.
+func googleBook() rawBook {
+ return rawBook{sheets: []string{strings.Join([]string{
+ row(1,
+ num("A1", "5"),
+ formula("B1", "", "SUM(A1,1)", ptr("6")),
+ `<c r="C1"><f t="shared" ref="C1:C2" si="0">$A$1+1</f><v>6</v></c>`,
+ // Trailing, with an empty saved string: excelize's row
+ // reader drops it, and it must still come across.
+ formula("D1", "str", `IF(TRUE,"","x")`, ptr("")),
+ ),
+ row(2,
+ inline("A2", "00123"),
+ formula("B2", "", "A1*2", ptr("11")),
+ `<c r="C2"><f t="shared" ref="C1:C2" si="0"/><v>6</v></c>`,
+ inline("E2", ""),
+ ),
+ row(3, inline("A3", ""), formula("B3", "", "A1/3", ptr("1.66666666666667"))),
+ row(4, inline("A4", "TRUE"), formula("B4", "", "Sheet2!A1", ptr("42"))),
+ row(5, inline("A5", "=SUM(A1)"),
+ formula("B5", "str", `IFERROR(__xludf.DUMMYFUNCTION("SPLIT(""a,007"","","")"),"a")`, ptr("a"))),
+ row(6, inline("A6", "NaN"),
+ formula("B6", "str", `IFERROR(__xludf.DUMMYFUNCTION("""COMPUTED_VALUE"""),"007")`, ptr("007"))),
+ row(7, inline("A7", "hello"), `<c r="B7"><f t="array" ref="B7">SUM(A1*2)</f><v>10</v></c>`),
+ row(8, `<c r="A8" t="b"><v>1</v></c>`, formula("B8", "str", "FOO(1)", ptr("x"))),
+ row(9, formula("B9", "str", `IF(A1>0,"","x")`, ptr(""))),
+ row(10, formula("B10", "b", "TaxRate*2", ptr("1"))),
+ row(11, formula("B11", "", "NOW()", ptr("45000"))),
+ row(12, formula("B12", "", "A1+1", nil)),
+ row(13, formula("B13", "e", "1/0", ptr("#DIV/0!"))),
+ row(14, formula("B14", "", "A99", ptr("0"))),
+ }, ""), row(1, num("A1", "42"))}}
+}
+
+func TestImportKeepsTypedValuesAndFreezesWhatItCannotCalculate(t *testing.T) {
+ h, rep, err := importRaw(t, googleBook())
+ if err != nil {
+ t.Fatalf("Import: %v", err)
+ }
+ str := func(s string) calc.Value { return calc.Value{Kind: calc.KindStr, Str: s} }
+ n := func(v float64) calc.Value { return calc.Value{Kind: calc.KindNum, Num: v} }
+ cases := []struct {
+ ref string
+ raw string
+ value calc.Value
+ }{
+ {"A1", "5", n(5)},
+ {"A2", `="00123"`, str("00123")},
+ {"A3", `=""`, str("")},
+ {"A4", `="TRUE"`, str("TRUE")},
+ {"A5", `="=SUM(A1)"`, str("=SUM(A1)")},
+ {"A6", `="NaN"`, str("NaN")},
+ {"A7", "hello", str("hello")},
+ {"A8", "TRUE", calc.Value{Kind: calc.KindBool, Bool: true}},
+ {"B1", "=SUM(A1,1)", n(6)},
+ {"B2", "=A1*2", n(10)},
+ {"B4", "42", n(42)},
+ {"B5", "a", str("a")},
+ {"B6", `="007"`, str("007")},
+ {"B7", "10", n(10)},
+ {"B8", "x", str("x")},
+ {"B9", `=IF(A1>0,"","x")`, str("")},
+ {"B10", "TRUE", calc.Value{Kind: calc.KindBool, Bool: true}},
+ {"B12", "=A1+1", n(6)},
+ {"B13", "=1/0", calc.Value{Kind: calc.KindErr, Err: calc.ErrDiv0}},
+ {"C1", "=$A$1+1", n(6)},
+ {"C2", "=$A$1+1", n(6)},
+ {"D1", `=IF(TRUE,"","x")`, str("")},
+ {"E2", `=""`, str("")},
+ }
+ for _, c := range cases {
+ raw, value := cellByRef(t, h, c.ref)
+ if raw != c.raw || value != c.value {
+ t.Errorf("%s = %q %+v, want %q %+v", c.ref, raw, value, c.raw, c.value)
+ }
+ }
+
+ if rep.Worksheets != 2 || rep.OmittedWorksheets() != 1 {
+ t.Errorf("worksheets = %d (omitted %d), want 2 (1)", rep.Worksheets, rep.OmittedWorksheets())
+ }
+ wantCells := map[xlsx.Code][]string{
+ xlsx.TextKept: {"A2", "E2", "A3", "A4", "A5", "A6", "B6"},
+ xlsx.FormulaDiffers: {"B2", "B14"},
+ xlsx.FormulaOtherSheet: {"B4"},
+ xlsx.FormulaGoogleOnly: {"B5", "B6"},
+ xlsx.FormulaArray: {"B7"},
+ xlsx.FormulaUnsupported: {"B8", "B10"},
+ xlsx.FormulaUnchecked: {"B11", "B12"},
+ }
+ for code, want := range wantCells {
+ got := entry(rep, code)
+ if got.Count != len(want) || !sameStrings(got.Cells, want) {
+ t.Errorf("%s = %d %v, want %v", code, got.Count, got.Cells, want)
+ }
+ }
+}
+
+// cellByRef reads one cell's raw input and value by its A1 reference.
+func cellByRef(t *testing.T, h *store.Handle, ref string) (string, calc.Value) {
+ t.Helper()
+ for _, rp := range h.GridRows() {
+ for _, cp := range h.GridCols() {
+ if calc.A1(rp.Pos, cp.Pos) == ref {
+ raw, _ := h.RawInput(rp.ID, cp.ID)
+ return raw, h.Value(rp.ID, cp.ID)
+ }
+ }
+ }
+ return "", calc.Value{}
+}
+
+func sameStrings(a, b []string) bool {
+ if len(a) != len(b) {
+ return false
+ }
+ for i := range a {
+ if a[i] != b[i] {
+ return false
+ }
+ }
+ return true
+}
+
+// A write whose dependents pass calc.MaxDirtyPerPass is not
+// recalculated until the tab next opens, so no value read during the
+// import is final. Then nothing is compared: a stale value could match
+// a saved one by accident and hide a difference.
+func TestImportComparesNothingAfterACappedRecalculation(t *testing.T) {
+ if testing.Short() {
+ t.Skip("writes over calc.MaxDirtyPerPass cells")
+ }
+ n := calc.MaxDirtyPerPass + 1
+ rows := make([]string, 0, n+1)
+ for i := 1; i <= n; i++ {
+ rows = append(rows, row(i, formula("B"+strconv.Itoa(i), "", "$A$"+strconv.Itoa(n+1), ptr("1"))))
+ }
+ rows = append(rows, row(n+1, num("A"+strconv.Itoa(n+1), "1")))
+ _, rep, err := importRaw(t, rawBook{sheets: []string{strings.Join(rows, "")}})
+ if err != nil {
+ t.Fatalf("Import: %v", err)
+ }
+ if got := entry(rep, xlsx.FormulaUnchecked).Count; got != n {
+ t.Errorf("unchecked = %d, want all %d", got, n)
+ }
+ if got := entry(rep, xlsx.FormulaDiffers).Count; got != 0 {
+ t.Errorf("differs = %d, want none: nothing final was compared", got)
+ }
+}
diff --git a/internal/sheets/xlsx/omissions.go b/internal/sheets/xlsx/omissions.go
new file mode 100644
index 0000000..1e60ef6
--- /dev/null
+++ b/internal/sheets/xlsx/omissions.go
@@ -0,0 +1,96 @@
+package xlsx
+
+import (
+ "strings"
+
+ "github.com/xuri/excelize/v2"
+)
+
+// reportOmissions counts what the first worksheet and the workbook
+// hold that import does not carry. Counts, never content: a comment's
+// text, a validation's list and a defined name's formula stay where
+// they are.
+func reportOmissions(f *excelize.File, sheet string, scan *sheetScan, rep *Report) {
+ undetected := 0
+ count := func(code Code, n int, err error) {
+ if err != nil {
+ undetected++
+ return
+ }
+ rep.add(code, n)
+ }
+
+ merges, err := f.GetMergeCells(sheet, true)
+ count(OmittedMerges, len(merges), err)
+ comments, err := f.GetComments(sheet)
+ count(OmittedComments, len(comments), err)
+ validations, err := f.GetDataValidations(sheet)
+ count(OmittedValidation, len(validations), err)
+ conditional, err := f.GetConditionalFormats(sheet)
+ count(OmittedConditional, len(conditional), err)
+ pictures, err := f.GetPictureCells(sheet)
+ count(OmittedPictures, len(pictures), err)
+ rep.add(OmittedDefinedNames, definedNames(f.GetDefinedName()))
+
+ rep.add(OmittedHyperlinks, scan.Hyperlinks)
+ rep.add(OmittedHiddenRows, scan.HiddenRows)
+ rep.add(OmittedHiddenCols, scan.HiddenCols)
+ if scan.FrozenPane {
+ rep.add(OmittedFrozenPanes, 1)
+ }
+ if scan.AutoFilter {
+ rep.add(OmittedFilter, 1)
+ }
+ rep.add(OmittedWorkbookChart, scan.Charts)
+ rep.add(OmittedWorkbookImage, scan.Images)
+ rep.add(OmittedUndetected, undetected)
+}
+
+// partialStyle reports whether a cell's style uses something
+// formatFromStyle does not carry. base is the workbook's default
+// style: every cell has a font family and size, and only one that
+// differs from the default was a choice somebody made.
+func partialStyle(st, base *excelize.Style) bool {
+ if len(st.Border) > 0 {
+ return true
+ }
+ if st.NumFmt != 0 && (st.CustomNumFmt == nil || *st.CustomNumFmt == "") {
+ return true // a built-in number format: only custom ones come across
+ }
+ if st.Fill.Type == "gradient" || (st.Fill.Type == "pattern" && st.Fill.Pattern > 1) {
+ return true
+ }
+ if a := st.Alignment; a != nil {
+ if a.WrapText || a.Indent != 0 || a.TextRotation != 0 || a.ShrinkToFit ||
+ a.Vertical == "top" || a.Vertical == "center" {
+ return true
+ }
+ }
+ if ft := st.Font; ft != nil {
+ if ft.Underline != "" || ft.Strike || ft.VertAlign != "" {
+ return true
+ }
+ if b := base.Font; b != nil && (ft.Family != b.Family || ft.Size != b.Size ||
+ (ft.Color == "" && !sameTheme(ft.ColorTheme, b.ColorTheme))) {
+ return true // a theme ink differing from the default's: only literal ink comes across
+ }
+ }
+ return false
+}
+
+func sameTheme(a, b *int) bool {
+ return (a == nil && b == nil) || (a != nil && b != nil && *a == *b)
+}
+
+// definedNames counts the names a person defined. Excel's own _xlnm.
+// names (a filter's range, a print area) are how other features are
+// stored, and those are reported as themselves.
+func definedNames(names []excelize.DefinedName) int {
+ n := 0
+ for _, d := range names {
+ if !strings.HasPrefix(d.Name, "_xlnm.") {
+ n++
+ }
+ }
+ return n
+}
diff --git a/internal/sheets/xlsx/plaintext_test.go b/internal/sheets/xlsx/plaintext_test.go
index d670de2..2a0d71e 100644
--- a/internal/sheets/xlsx/plaintext_test.go
+++ b/internal/sheets/xlsx/plaintext_test.go
@@ -61,7 +61,7 @@ func TestImportDoesNotLeakPlaintext(t *testing.T) {
// also checks the WAL directly, but a checkpoint proves the main file
// itself is clean too).
target := newTab(t, d.G, sealer)
- if err := xlsx.Import(&buf, target); err != nil {
+ if _, err := xlsx.Import(&buf, target); err != nil {
t.Fatalf("Import: %v", err)
}
if err := d.G.Exec("PRAGMA wal_checkpoint(TRUNCATE)").Error; err != nil {
diff --git a/internal/sheets/xlsx/rawbook_test.go b/internal/sheets/xlsx/rawbook_test.go
new file mode 100644
index 0000000..c49cd13
--- /dev/null
+++ b/internal/sheets/xlsx/rawbook_test.go
@@ -0,0 +1,140 @@
+package xlsx_test
+
+import (
+ "archive/zip"
+ "bytes"
+ "fmt"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/sheets/internal/sheets/store"
+ "amadan.net/oficina/sheets/internal/sheets/xlsx"
+)
+
+// rawBook writes a workbook part by part, so a test controls the exact
+// XML a cell is written with: whether a formula has a <v>, what t it
+// declares, how Google wraps a function Excel lacks. excelize cannot
+// write most of these shapes, which is the point of reading them.
+//
+// sheets are each worksheet's <sheetData> rows; extra is any further
+// worksheet markup (after sheetData) for the first sheet.
+type rawBook struct {
+ sheets []string
+ extra string
+ parts map[string]string // replaces or adds a part by name
+}
+
+const rawStyles = `<?xml version="1.0" encoding="UTF-8"?>
+<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
+<fonts count="1"><font><sz val="10"/><name val="Arial"/></font></fonts>
+<fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills>
+<borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders>
+<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>
+<cellXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/></cellXfs>
+</styleSheet>`
+
+func (b rawBook) bytes(t *testing.T) []byte {
+ t.Helper()
+ parts := map[string]string{
+ "[Content_Types].xml": `<?xml version="1.0" encoding="UTF-8"?>
+<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
+<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
+<Default Extension="xml" ContentType="application/xml"/>
+<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>
+</Types>`,
+ "_rels/.rels": `<?xml version="1.0" encoding="UTF-8"?>
+<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
+<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>
+</Relationships>`,
+ "xl/styles.xml": rawStyles,
+ }
+ var sheets, rels strings.Builder
+ for i, data := range b.sheets {
+ n := i + 1
+ fmt.Fprintf(&sheets, `<sheet name="Sheet%d" sheetId="%d" r:id="rId%d"/>`, n, n, n)
+ fmt.Fprintf(&rels, `<Relationship Id="rId%d" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet%d.xml"/>`, n, n)
+ extra := ""
+ if i == 0 {
+ extra = b.extra
+ }
+ parts[fmt.Sprintf("xl/worksheets/sheet%d.xml", n)] = `<?xml version="1.0" encoding="UTF-8"?>
+<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheetData>` +
+ data + `</sheetData>` + extra + `</worksheet>`
+ }
+ fmt.Fprintf(&rels, `<Relationship Id="rIdS" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>`)
+ parts["xl/workbook.xml"] = `<?xml version="1.0" encoding="UTF-8"?>
+<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets>` +
+ sheets.String() + `</sheets></workbook>`
+ parts["xl/_rels/workbook.xml.rels"] = `<?xml version="1.0" encoding="UTF-8"?>
+<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` + rels.String() + `</Relationships>`
+ for name, body := range b.parts {
+ parts[name] = body
+ }
+
+ var buf bytes.Buffer
+ zw := zip.NewWriter(&buf)
+ for name, body := range parts {
+ w, err := zw.Create(name)
+ if err != nil {
+ t.Fatalf("zip create %s: %v", name, err)
+ }
+ if _, err := w.Write([]byte(body)); err != nil {
+ t.Fatalf("zip write %s: %v", name, err)
+ }
+ }
+ if err := zw.Close(); err != nil {
+ t.Fatalf("zip close: %v", err)
+ }
+ return buf.Bytes()
+}
+
+// importRaw imports b into a fresh tab and returns the handle, the
+// report and Import's error.
+func importRaw(t *testing.T, b rawBook) (*store.Handle, xlsx.Report, error) {
+ t.Helper()
+ h := newTab(t, openTestDB(t), testSealer(t))
+ rep, err := xlsx.Import(bytes.NewReader(b.bytes(t)), h)
+ return h, rep, err
+}
+
+// row wraps cells in a <row r="n">.
+func row(n int, cells ...string) string {
+ return fmt.Sprintf(`<row r="%d">%s</row>`, n, strings.Join(cells, ""))
+}
+
+// inline is an inline-string cell; num a number cell.
+func inline(ref, text string) string {
+ return fmt.Sprintf(`<c r="%s" t="inlineStr"><is><t xml:space="preserve">%s</t></is></c>`, ref, xmlEscape(text))
+}
+
+func num(ref, v string) string { return fmt.Sprintf(`<c r="%s"><v>%s</v></c>`, ref, v) }
+
+// formula is a formula cell; t is its declared type and v its saved
+// value, with v == nil meaning no <v> element at all.
+func formula(ref, t, f string, v *string) string {
+ attrs := fmt.Sprintf(`r="%s"`, ref)
+ if t != "" {
+ attrs += fmt.Sprintf(` t="%s"`, t)
+ }
+ body := "<f>" + xmlEscape(f) + "</f>"
+ if v != nil {
+ body += "<v>" + xmlEscape(*v) + "</v>"
+ }
+ return "<c " + attrs + ">" + body + "</c>"
+}
+
+func ptr(s string) *string { return &s }
+
+func xmlEscape(s string) string {
+ return strings.NewReplacer("&", "&amp;", "<", "&lt;", ">", "&gt;", `"`, "&quot;").Replace(s)
+}
+
+// entry finds code in rep, or a zero Entry.
+func entry(rep xlsx.Report, code xlsx.Code) xlsx.Entry {
+ for _, e := range rep.Entries {
+ if e.Code == code {
+ return e
+ }
+ }
+ return xlsx.Entry{}
+}
diff --git a/internal/sheets/xlsx/report.go b/internal/sheets/xlsx/report.go
new file mode 100644
index 0000000..b77cde9
--- /dev/null
+++ b/internal/sheets/xlsx/report.go
@@ -0,0 +1,119 @@
+package xlsx
+
+import "amadan.net/oficina/sheets/internal/sheets/calc"
+
+// Code names one kind of thing an import changed or left behind.
+//
+// A report is codes, coordinates and counts, never content: no cell
+// text, no formula, no sheet or file name. That is what lets it be
+// shown, stored sealed and carried around without becoming a second
+// copy of the workbook.
+type Code string
+
+// Per-cell codes: each carries the coordinates it applies to.
+const (
+ // A formula calling a function Google Sheets has and Excel does
+ // not; Google exports it wrapped in __xludf.DUMMYFUNCTION. Kept as
+ // its saved value.
+ FormulaGoogleOnly Code = "formula-google-only"
+ // An array formula (one formula filling a range). Kept as its
+ // saved value.
+ FormulaArray Code = "formula-array"
+ // A reference to another worksheet or another workbook. Kept as
+ // its saved value: only the first worksheet comes across.
+ FormulaOtherSheet Code = "formula-other-sheet"
+ // Any other formula this app cannot calculate. Kept as its saved
+ // value.
+ FormulaUnsupported Code = "formula-unsupported"
+ // A formula this app calculates, whose result here differs from
+ // the value the workbook saved. Kept as a formula.
+ FormulaDiffers Code = "formula-differs"
+ // A formula kept as a formula with no saved value to check it
+ // against.
+ FormulaUnchecked Code = "formula-unchecked"
+ // Text that would otherwise read as a number, a boolean, a formula
+ // or a blank, kept as text by a constant string formula ="...".
+ TextKept Code = "text-kept"
+ // A cell whose style used something this app does not carry:
+ // fonts, sizes, borders, wrapping, underline and the like.
+ FormatPartial Code = "format-partial"
+)
+
+// Count-only codes: what the worksheet or workbook had, none of it
+// imported.
+const (
+ OmittedMerges Code = "merges"
+ OmittedComments Code = "comments"
+ OmittedValidation Code = "validation"
+ OmittedConditional Code = "conditional-formats"
+ OmittedHyperlinks Code = "hyperlinks"
+ OmittedDefinedNames Code = "defined-names"
+ OmittedHiddenRows Code = "hidden-rows"
+ OmittedHiddenCols Code = "hidden-columns"
+ OmittedFrozenPanes Code = "frozen-panes"
+ OmittedFilter Code = "filter"
+ OmittedPictures Code = "pictures"
+ OmittedWorkbookChart Code = "workbook-charts"
+ OmittedWorkbookImage Code = "workbook-images"
+ // The detectors that could not read their part of the workbook,
+ // so a report says it did not look rather than imply there was
+ // nothing to find.
+ OmittedUndetected Code = "undetected"
+)
+
+// MaxListedCells is how many coordinates one entry names; Count keeps
+// the true total past it.
+const MaxListedCells = 200
+
+// Entry is one code and where it applies.
+type Entry struct {
+ Code Code `json:"code"`
+ Count int `json:"count"`
+ Cells []string `json:"cells,omitempty"`
+}
+
+// Report is what one import did beyond copying values across.
+//
+// It never claims completeness. An empty Entries says nothing was
+// detected, which is all it can say; the page that shows it states
+// the supported subset beside it.
+type Report struct {
+ // Worksheets is how many the workbook held. Only the first comes
+ // across, so Worksheets-1 were omitted.
+ Worksheets int `json:"worksheets"`
+ Entries []Entry `json:"entries,omitempty"`
+}
+
+// OmittedWorksheets is how many worksheets did not come across.
+func (r Report) OmittedWorksheets() int {
+ if r.Worksheets <= 1 {
+ return 0
+ }
+ return r.Worksheets - 1
+}
+
+func (r *Report) entry(code Code) *Entry {
+ for i := range r.Entries {
+ if r.Entries[i].Code == code {
+ return &r.Entries[i]
+ }
+ }
+ r.Entries = append(r.Entries, Entry{Code: code})
+ return &r.Entries[len(r.Entries)-1]
+}
+
+// cell records code at a 0-based position.
+func (r *Report) cell(code Code, rowPos, colPos int) {
+ e := r.entry(code)
+ e.Count++
+ if len(e.Cells) < MaxListedCells {
+ e.Cells = append(e.Cells, calc.A1(rowPos, colPos))
+ }
+}
+
+// add records n of a count-only code; zero records nothing.
+func (r *Report) add(code Code, n int) {
+ if n > 0 {
+ r.entry(code).Count += n
+ }
+}
diff --git a/internal/sheets/xlsx/roundtrip_test.go b/internal/sheets/xlsx/roundtrip_test.go
index c191bbb..7913c20 100644
--- a/internal/sheets/xlsx/roundtrip_test.go
+++ b/internal/sheets/xlsx/roundtrip_test.go
@@ -98,7 +98,7 @@ func TestImportErrorsContainNoCellContent(t *testing.T) {
sealer := testSealer(t)
h := newTab(t, db, sealer)
- err := xlsx.Import(buf, h)
+ _, err := xlsx.Import(buf, h)
if err == nil {
t.Fatal("want an error importing a deliberately unparseable formula, got nil")
}
diff --git a/internal/sheets/xlsx/saved.go b/internal/sheets/xlsx/saved.go
new file mode 100644
index 0000000..b0a099f
--- /dev/null
+++ b/internal/sheets/xlsx/saved.go
@@ -0,0 +1,128 @@
+package xlsx
+
+import (
+ "errors"
+ "math"
+ "strconv"
+
+ "amadan.net/oficina/sheets/internal/sheets/calc"
+ "amadan.net/oficina/sheets/internal/sheets/store"
+)
+
+// Why a formula's saved value cannot stand in for it. Each refuses the
+// import at the cell's coordinate: there is no trustworthy value to
+// keep, and import never manufactures one.
+var (
+ errNoSavedValue = errors.New("xlsx: formula has no saved value")
+ errSavedError = errors.New("xlsx: formula saved an error value")
+ errSavedUnreadable = errors.New("xlsx: formula saved a value of an unexpected type")
+)
+
+// savedValue reads the value a workbook saved with a formula, by the
+// rules a frozen cell is held to:
+//
+// - a <v> must be present: absent is not the empty string;
+// - t absent or "n": a finite number, parsed exactly;
+// - t "b": exactly "0" or "1";
+// - t "str": any text, the empty string included;
+// - t "e": refused, because no value in this app is an error that a
+// person did not compute, and error-to-text would change what the
+// cell means;
+// - anything else: refused.
+func savedValue(c scannedCell) (calc.Value, error) {
+ if !c.HasV {
+ return calc.Value{}, errNoSavedValue
+ }
+ switch c.T {
+ case "", "n":
+ n, err := strconv.ParseFloat(c.V, 64)
+ if err != nil || math.IsNaN(n) || math.IsInf(n, 0) {
+ return calc.Value{}, errSavedUnreadable
+ }
+ return calc.Value{Kind: calc.KindNum, Num: n}, nil
+ case "b":
+ switch c.V {
+ case "0":
+ return calc.Value{Kind: calc.KindBool}, nil
+ case "1":
+ return calc.Value{Kind: calc.KindBool, Bool: true}, nil
+ }
+ return calc.Value{}, errSavedUnreadable
+ case "str":
+ return calc.Value{Kind: calc.KindStr, Str: c.V}, nil
+ case "e":
+ return calc.Value{}, errSavedError
+ }
+ return calc.Value{}, errSavedUnreadable
+}
+
+// frozenInput is the raw input that holds v as a literal, and whether
+// holding it took the ="..." wrapper.
+func frozenInput(v calc.Value) (raw string, wrapped bool) {
+ switch v.Kind {
+ case calc.KindNum:
+ return strconv.FormatFloat(v.Num, 'g', -1, 64), false
+ case calc.KindBool:
+ if v.Bool {
+ return "TRUE", false
+ }
+ return "FALSE", false
+ default:
+ return store.TextInput(v.Str)
+ }
+}
+
+// savedErrors are the error values a workbook can save that this
+// engine also produces. Any other (#SPILL!, #CALC!, Google's #ERROR!)
+// compares unequal to everything, which is the truth.
+var savedErrors = map[string]calc.ErrKind{
+ "#DIV/0!": calc.ErrDiv0, "#VALUE!": calc.ErrValue, "#REF!": calc.ErrRef,
+ "#NAME?": calc.ErrName, "#NUM!": calc.ErrNum, "#N/A": calc.ErrNA,
+}
+
+// comparableSaved is a kept formula's saved value, to check this
+// engine's result against. Unlike savedValue it accepts an error,
+// because a kept formula is not being replaced by what it saved.
+func comparableSaved(c scannedCell) (calc.Value, bool) {
+ if c.HasV && c.T == "e" {
+ kind, ok := savedErrors[c.V]
+ if !ok {
+ return calc.Value{Kind: calc.KindErr, Err: calc.ErrNone}, true
+ }
+ return calc.Value{Kind: calc.KindErr, Err: kind}, true
+ }
+ v, err := savedValue(c)
+ return v, err == nil
+}
+
+// Numbers compare within a relative tolerance. Google writes 15
+// significant digits and Excel computes in its own order, so exact
+// comparison would flag nearly every division; anything past one part
+// in a billion is a different answer, not a rounding.
+const (
+ relTolerance = 1e-9
+ absTolerance = 1e-12
+)
+
+// sameValue reports whether this engine's result matches a saved one.
+func sameValue(ours, saved calc.Value) bool {
+ // Kinds compare strictly. A formula that computes to nothing here
+ // where the workbook saved 0 or "" is a real difference: blank,
+ // zero and the empty string answer ISBLANK, ISNUMBER and = apart.
+ if ours.Kind != saved.Kind {
+ return false
+ }
+ switch ours.Kind {
+ case calc.KindNum:
+ diff := math.Abs(ours.Num - saved.Num)
+ scale := math.Max(math.Abs(ours.Num), math.Abs(saved.Num))
+ return diff <= absTolerance || diff <= relTolerance*scale
+ case calc.KindStr:
+ return ours.Str == saved.Str
+ case calc.KindBool:
+ return ours.Bool == saved.Bool
+ case calc.KindErr:
+ return saved.Err != calc.ErrNone && ours.Err == saved.Err
+ }
+ return false
+}
diff --git a/internal/sheets/xlsx/scan_parts.go b/internal/sheets/xlsx/scan_parts.go
new file mode 100644
index 0000000..ef8abfd
--- /dev/null
+++ b/internal/sheets/xlsx/scan_parts.go
@@ -0,0 +1,229 @@
+package xlsx
+
+import (
+ "archive/zip"
+ "bytes"
+ "encoding/xml"
+ "errors"
+ "io"
+ "path"
+ "strings"
+)
+
+// The scan's own bounds. excelize's openLimits bound what excelize
+// decompresses; these bound what this package's second reader does,
+// since a bound on one reader says nothing about the other.
+const (
+ maxZipEntries = 10_000
+ maxPartBytes = 8 << 20 // _rels/.rels, the workbook and its rels
+ maxSheetBytes = 256 << 20
+ maxXMLDepth = 64
+ maxCachedBytes = 1 << 20 // one <v>; Excel caps a cell at 32,767 characters
+)
+
+const (
+ relOfficeDocument = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument"
+ relWorksheet = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet"
+ relNamespace = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
+)
+
+// errScanInconsistent is a workbook this package's reader and
+// excelize's disagree about. Either could be the one that is right;
+// neither is trusted to decide alone, so the import stops.
+var errScanInconsistent = errors.New("xlsx: workbook parts disagree")
+
+// errScanLimit is a part past one of the bounds above.
+var errScanLimit = errors.New("xlsx: workbook part exceeds a limit")
+
+// zipParts indexes a workbook's entries by name the way excelize does:
+// backslashes read as slashes, and a later duplicate replaces an
+// earlier one.
+type zipParts map[string]*zip.File
+
+func openParts(data []byte) (zipParts, error) {
+ zr, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
+ if err != nil {
+ return nil, err
+ }
+ if len(zr.File) > maxZipEntries {
+ return nil, errScanLimit
+ }
+ parts := make(zipParts, len(zr.File))
+ for _, f := range zr.File {
+ parts[strings.ReplaceAll(f.Name, `\`, "/")] = f
+ }
+ return parts, nil
+}
+
+// open returns a reader over one part that fails, rather than
+// truncating, once it has produced more than limit bytes.
+func (p zipParts) open(name string, limit int64) (io.ReadCloser, error) {
+ f, ok := p[name]
+ if !ok {
+ return nil, errScanInconsistent
+ }
+ rc, err := f.Open()
+ if err != nil {
+ return nil, err
+ }
+ return &capReader{rc: rc, left: limit}, nil
+}
+
+// count reports how many entries sit under prefix: charts and images,
+// which this import never reads, only counts.
+func (p zipParts) count(prefix string) int {
+ n := 0
+ for name := range p {
+ if strings.HasPrefix(name, prefix) && !strings.HasSuffix(name, "/") {
+ n++
+ }
+ }
+ return n
+}
+
+type capReader struct {
+ rc io.ReadCloser
+ left int64
+}
+
+func (c *capReader) Read(b []byte) (int, error) {
+ if c.left < 0 {
+ return 0, errScanLimit
+ }
+ if int64(len(b)) > c.left+1 {
+ b = b[:c.left+1]
+ }
+ n, err := c.rc.Read(b)
+ c.left -= int64(n)
+ if c.left < 0 {
+ return n, errScanLimit
+ }
+ return n, err
+}
+
+func (c *capReader) Close() error { return c.rc.Close() }
+
+// firstWorksheetPath resolves the first <sheet> of the workbook to its
+// part, by the same route excelize takes: _rels/.rels names the
+// workbook, the workbook's own rels name each sheet's target, and a
+// target resolves against the workbook's directory unless it is
+// absolute. It also returns that sheet's name, compared in memory with
+// excelize's first sheet and never written anywhere.
+func firstWorksheetPath(p zipParts) (sheetPath, name string, err error) {
+ rootRels, err := readRels(p, "_rels/.rels")
+ if err != nil {
+ return "", "", err
+ }
+ var wbPath string
+ for _, r := range rootRels {
+ if r.Type == relOfficeDocument {
+ wbPath = strings.TrimPrefix(r.Target, "/")
+ break
+ }
+ }
+ if wbPath == "" {
+ return "", "", errScanInconsistent
+ }
+ sheetID, name, err := firstSheetRelID(p, wbPath)
+ if err != nil {
+ return "", "", err
+ }
+ dir := path.Dir(wbPath)
+ relsPath := strings.TrimPrefix(path.Join(dir, "_rels", path.Base(wbPath)+".rels"), "./")
+ rels, err := readRels(p, relsPath)
+ if err != nil {
+ return "", "", err
+ }
+ for _, r := range rels {
+ if r.ID != sheetID {
+ continue
+ }
+ if r.Type != relWorksheet {
+ return "", "", errScanInconsistent // a chartsheet or dialog first
+ }
+ target := strings.ReplaceAll(r.Target, `\`, "/")
+ if strings.HasPrefix(target, "/") {
+ return strings.TrimPrefix(path.Clean(target), "/"), name, nil
+ }
+ return strings.TrimPrefix(path.Clean(dir+"/"+target), "/"), name, nil
+ }
+ return "", "", errScanInconsistent
+}
+
+type relationship struct {
+ ID string `xml:"Id,attr"`
+ Type string `xml:"Type,attr"`
+ Target string `xml:"Target,attr"`
+}
+
+func readRels(p zipParts, name string) ([]relationship, error) {
+ var doc struct {
+ Rels []relationship `xml:"Relationship"`
+ }
+ if err := decodePart(p, name, &doc); err != nil {
+ return nil, err
+ }
+ return doc.Rels, nil
+}
+
+func firstSheetRelID(p zipParts, wbPath string) (id, name string, err error) {
+ var doc struct {
+ Sheets []struct {
+ Name string `xml:"name,attr"`
+ Attrs []xml.Attr `xml:",any,attr"`
+ } `xml:"sheets>sheet"`
+ }
+ if err := decodePart(p, wbPath, &doc); err != nil {
+ return "", "", err
+ }
+ if len(doc.Sheets) == 0 {
+ return "", "", errScanInconsistent
+ }
+ for _, a := range doc.Sheets[0].Attrs {
+ if a.Name.Space == relNamespace && a.Name.Local == "id" {
+ return a.Value, doc.Sheets[0].Name, nil
+ }
+ }
+ return "", "", errScanInconsistent
+}
+
+// decodePart unmarshals one small part, bounded in bytes and depth.
+func decodePart(p zipParts, name string, into any) error {
+ rc, err := p.open(name, maxPartBytes)
+ if err != nil {
+ return err
+ }
+ defer rc.Close()
+ body, err := io.ReadAll(rc)
+ if err != nil {
+ return err
+ }
+ if err := checkDepth(body); err != nil {
+ return err
+ }
+ return xml.Unmarshal(body, into)
+}
+
+// checkDepth refuses XML nested deeper than maxXMLDepth before
+// encoding/xml, which has no depth limit of its own, unmarshals it.
+func checkDepth(body []byte) error {
+ d := xml.NewDecoder(bytes.NewReader(body))
+ depth := 0
+ for {
+ tok, err := d.RawToken()
+ if err == io.EOF {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ switch tok.(type) {
+ case xml.StartElement:
+ if depth++; depth > maxXMLDepth {
+ return errScanLimit
+ }
+ case xml.EndElement:
+ depth--
+ }
+ }
+}
diff --git a/internal/sheets/xlsx/scan_sheet.go b/internal/sheets/xlsx/scan_sheet.go
new file mode 100644
index 0000000..2231562
--- /dev/null
+++ b/internal/sheets/xlsx/scan_sheet.go
@@ -0,0 +1,236 @@
+package xlsx
+
+import (
+ "encoding/xml"
+ "errors"
+ "io"
+ "strconv"
+
+ "github.com/xuri/excelize/v2"
+
+ "amadan.net/oficina/sheets/internal/sheets/store"
+)
+
+// scannedCell is one <c> as the worksheet XML wrote it.
+//
+// It exists for what excelize cannot say. excelize's cell model keeps
+// <v> as a plain string with omitempty, so a formula whose saved value
+// is the empty string and a formula with no saved value at all read
+// the same; this reader records whether <v> was there.
+type scannedCell struct {
+ T string // the c element's t attribute: "", "n", "b", "e", "s", "str", "inlineStr", "d"
+ HasF bool
+ FType string // the f element's t attribute: "", "normal", "shared", "array", "dataTable"
+ HasV bool
+ V string
+}
+
+// sheetScan is what a bounded read of the first worksheet found.
+type sheetScan struct {
+ // Name is the first sheet's name, compared with excelize's.
+ Name string
+ // Cells holds every formula cell and every string-typed cell.
+ Cells map[posKey]scannedCell
+ // Layout and features the import does not carry, counted.
+ Hyperlinks, HiddenRows, HiddenCols int
+ FrozenPane, AutoFilter bool
+ // Charts and Images are workbook-wide part counts.
+ Charts, Images int
+}
+
+type posKey struct{ Row, Col int }
+
+// errCellWithoutRef is a formula or string cell whose position the XML
+// leaves implicit. excelize would place it by order; this reader does
+// not guess, so the two could disagree about where it is.
+var errCellWithoutRef = errors.New("xlsx: a cell has no reference")
+
+// scanWorkbook reads the first worksheet's XML directly, bounded.
+func scanWorkbook(data []byte) (*sheetScan, error) {
+ parts, err := openParts(data)
+ if err != nil {
+ return nil, err
+ }
+ sheetPath, name, err := firstWorksheetPath(parts)
+ if err != nil {
+ return nil, err
+ }
+ rc, err := parts.open(sheetPath, maxSheetBytes)
+ if err != nil {
+ return nil, err
+ }
+ defer rc.Close()
+
+ s := &sheetScan{
+ Name: name,
+ Cells: map[posKey]scannedCell{},
+ Charts: parts.count("xl/charts/chart"),
+ Images: parts.count("xl/media/"),
+ }
+ if err := s.walk(xml.NewDecoder(rc)); err != nil {
+ return nil, err
+ }
+ return s, nil
+}
+
+// Paths the walk acts on, as the stack of local names above an
+// element. Matching the whole path, not just the parent, is what keeps
+// a <c> or a <v> inside some extension element from being read as a
+// cell: excelize unmarshals by the same paths, so anything elsewhere is
+// invisible to it, and must be to this reader too.
+var (
+ pathRow = []string{"worksheet", "sheetData"}
+ pathCell = []string{"worksheet", "sheetData", "row"}
+ pathCellChild = []string{"worksheet", "sheetData", "row", "c"}
+ pathCol = []string{"worksheet", "cols"}
+ pathHyperlink = []string{"worksheet", "hyperlinks"}
+ pathPane = []string{"worksheet", "sheetViews", "sheetView"}
+ pathSheet = []string{"worksheet"}
+)
+
+// formulaTypes are the <f t> values ECMA-376 defines. Any other is a
+// formula whose meaning this reader does not know, and is refused.
+var formulaTypes = map[string]bool{"": true, "normal": true, "shared": true, "array": true, "dataTable": true}
+
+// errScanDuplicate is a cell written twice, or a cell with two <f> or
+// two <v>. Which one wins is a parser's accident; import refuses to
+// depend on it.
+var errScanDuplicate = errors.New("xlsx: worksheet repeats a cell or its parts")
+
+// maxScannedCells bounds the set of every <c> reference the walk has
+// seen, which duplicate detection needs.
+const maxScannedCells = 2 * store.MaxCellsPerTab
+
+// walk streams the worksheet, bounded in depth by the stack.
+func (s *sheetScan) walk(d *xml.Decoder) error {
+ var (
+ stack []string
+ cell scannedCell
+ ref string
+ rowNum string
+ fs, vs int
+ seen = map[posKey]bool{}
+ )
+ for {
+ tok, err := d.Token()
+ if err == io.EOF {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ switch t := tok.(type) {
+ case xml.StartElement:
+ if len(stack) >= maxXMLDepth {
+ return errScanLimit
+ }
+ name := t.Name.Local
+ switch {
+ case name == "row" && at(stack, pathRow):
+ rowNum = attr(t, "r")
+ if truthy(attr(t, "hidden")) {
+ s.HiddenRows++
+ }
+ case name == "c" && at(stack, pathCell):
+ cell, ref, fs, vs = scannedCell{T: attr(t, "t")}, attr(t, "r"), 0, 0
+ if ref != "" {
+ col, row, err := excelize.CellNameToCoordinates(ref)
+ if err != nil {
+ return errScanInconsistent
+ }
+ p := posKey{Row: row - 1, Col: col - 1}
+ if seen[p] {
+ return errScanDuplicate
+ }
+ if len(seen) >= maxScannedCells {
+ return store.ErrTabTooLarge
+ }
+ seen[p] = true
+ }
+ case name == "f" && at(stack, pathCellChild):
+ fs++
+ cell.HasF, cell.FType = true, attr(t, "t")
+ if !formulaTypes[cell.FType] {
+ return errScanInconsistent
+ }
+ case name == "v" && at(stack, pathCellChild):
+ vs++
+ cell.HasV = true
+ case name == "col" && at(stack, pathCol):
+ if truthy(attr(t, "hidden")) {
+ s.HiddenCols++
+ }
+ case name == "hyperlink" && at(stack, pathHyperlink):
+ s.Hyperlinks++
+ case name == "pane" && at(stack, pathPane):
+ st := attr(t, "state")
+ s.FrozenPane = s.FrozenPane || st == "frozen" || st == "frozenSplit"
+ case name == "autoFilter" && at(stack, pathSheet):
+ s.AutoFilter = true
+ }
+ if fs > 1 || vs > 1 {
+ return errScanDuplicate
+ }
+ stack = append(stack, name)
+ case xml.CharData:
+ if len(stack) == len(pathCellChild)+1 && stack[len(stack)-1] == "v" && at(stack[:len(stack)-1], pathCellChild) {
+ if len(cell.V)+len(t) > maxCachedBytes {
+ return errScanLimit
+ }
+ cell.V += string(t)
+ }
+ case xml.EndElement:
+ stack = stack[:len(stack)-1]
+ if t.Name.Local == "c" && at(stack, pathCell) {
+ if err := s.keep(ref, rowNum, cell); err != nil {
+ return err
+ }
+ }
+ }
+ }
+}
+
+// at reports whether stack is exactly path.
+func at(stack, path []string) bool {
+ if len(stack) != len(path) {
+ return false
+ }
+ for i := range path {
+ if stack[i] != path[i] {
+ return false
+ }
+ }
+ return true
+}
+
+// keep records a cell the import needs to know about: one with a
+// formula, or one typed as a string (whose value may be the empty
+// string, which excelize's row reader drops from the end of a row).
+func (s *sheetScan) keep(ref, rowNum string, c scannedCell) error {
+ if !c.HasF && c.T != "s" && c.T != "inlineStr" && c.T != "str" {
+ return nil
+ }
+ if ref == "" {
+ return errCellWithoutRef
+ }
+ col, row, err := excelize.CellNameToCoordinates(ref)
+ if err != nil {
+ return errScanInconsistent
+ }
+ if rowNum != "" && rowNum != strconv.Itoa(row) {
+ return errScanInconsistent // a cell filed under another row
+ }
+ s.Cells[posKey{Row: row - 1, Col: col - 1}] = c
+ return nil
+}
+
+func attr(t xml.StartElement, local string) string {
+ for _, a := range t.Attr {
+ if a.Name.Local == local { // by local name, as excelize's struct tags match
+ return a.Value
+ }
+ }
+ return ""
+}
+
+func truthy(v string) bool { return v == "1" || v == "true" }