Skip to content

Commit

Permalink
internal/cuetxtar: ensure ordering of files in txtar is consistent
Browse files Browse the repository at this point in the history
Currently, if outputs change the ordering of such a file may
change within the file, resulting in large diffs.

This change ensures that the original ordering, is at least
maintained.

Signed-off-by: Marcel van Lohuizen <[email protected]>
Change-Id: I3ea91967c39e9656bb958bc23c06f60512276b6d
Reviewed-on: https://review.gerrithub.io/c/cue-lang/cue/+/1199751
Reviewed-by: Matthew Sackman <[email protected]>
TryBot-Result: CUEcueckoo <[email protected]>
  • Loading branch information
mpvl committed Aug 21, 2024
1 parent f889101 commit 358b945
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions internal/cuetxtar/txtar.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"os"
"path"
"path/filepath"
"slices"
"strings"
"testing"

Expand Down Expand Up @@ -416,6 +417,14 @@ func (x *TxTarTest) run(t *testing.T, f func(tc *Test)) {
if err != nil {
t.Fatalf("error parsing txtar file: %v", err)
}

// Record ordering of files in the archive to preserve that ordering
// later.
ordering := map[string]int{}
for i, f := range a.Files {
ordering[f.Name] = i
}

tc := &Test{
T: t,
Archive: a,
Expand Down Expand Up @@ -472,6 +481,7 @@ func (x *TxTarTest) run(t *testing.T, f func(tc *Test)) {
}
f(tc)

// Track the position of the fallback files.
index := make(map[string]int, len(a.Files))
for i, f := range a.Files {
index[f.Name] = i
Expand Down Expand Up @@ -605,6 +615,18 @@ func (x *TxTarTest) run(t *testing.T, f func(tc *Test)) {
a.Files = files

if update {
slices.SortStableFunc(a.Files, func(i, j txtar.File) int {
p, ok := ordering[i.Name]
if !ok {
p = len(a.Files)
}
q, ok := ordering[j.Name]
if !ok {
q = len(a.Files)
}
return q - p
})

err = os.WriteFile(fullpath, txtar.Format(a), 0644)
if err != nil {
t.Fatal(err)
Expand Down

0 comments on commit 358b945

Please sign in to comment.