Centralize deterministic JSON file writing
This commit is contained in:
28
internal/jsonfile/jsonfile.go
Normal file
28
internal/jsonfile/jsonfile.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package jsonfile
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
// Write creates or truncates path and writes deterministic indented JSON.
|
||||
func Write(path string, value any) (err error) {
|
||||
file, err := os.Create(path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create %q: %w", path, err)
|
||||
}
|
||||
defer func() {
|
||||
closeErr := file.Close()
|
||||
if err == nil && closeErr != nil {
|
||||
err = fmt.Errorf("close %q: %w", path, closeErr)
|
||||
}
|
||||
}()
|
||||
|
||||
encoder := json.NewEncoder(file)
|
||||
encoder.SetIndent("", " ")
|
||||
if err := encoder.Encode(value); err != nil {
|
||||
return fmt.Errorf("encode %q: %w", path, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
69
internal/jsonfile/jsonfile_test.go
Normal file
69
internal/jsonfile/jsonfile_test.go
Normal file
@@ -0,0 +1,69 @@
|
||||
package jsonfile
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestWriteFormatsWithTwoSpaceIndentAndTrailingNewline(t *testing.T) {
|
||||
type payload struct {
|
||||
Name string `json:"name"`
|
||||
Items []int `json:"items"`
|
||||
}
|
||||
|
||||
path := filepath.Join(t.TempDir(), "out.json")
|
||||
value := payload{
|
||||
Name: "alpha",
|
||||
Items: []int{1, 2},
|
||||
}
|
||||
|
||||
if err := Write(path, value); err != nil {
|
||||
t.Fatalf("write failed: %v", err)
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatalf("read output: %v", err)
|
||||
}
|
||||
|
||||
got := string(data)
|
||||
want := "{\n \"name\": \"alpha\",\n \"items\": [\n 1,\n 2\n ]\n}\n"
|
||||
if got != want {
|
||||
t.Fatalf("formatted JSON mismatch\nwant:\n%s\ngot:\n%s", want, got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteProducesValidJSON(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "out.json")
|
||||
|
||||
value := map[string]any{
|
||||
"application": "seriatim",
|
||||
"segments": []map[string]any{
|
||||
{
|
||||
"id": 1,
|
||||
"speaker": "A",
|
||||
"text": "hello",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
if err := Write(path, value); err != nil {
|
||||
t.Fatalf("write failed: %v", err)
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatalf("read output: %v", err)
|
||||
}
|
||||
if !strings.HasSuffix(string(data), "\n") {
|
||||
t.Fatalf("output missing trailing newline: %q", string(data))
|
||||
}
|
||||
|
||||
var decoded map[string]any
|
||||
if err := json.Unmarshal(data, &decoded); err != nil {
|
||||
t.Fatalf("output is not valid JSON: %v", err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user