json.go 1.5 KB
Newer Older
protolambda's avatar
protolambda committed
1 2 3 4
package cmd

import (
	"encoding/json"
5
	"errors"
protolambda's avatar
protolambda committed
6 7 8
	"fmt"
	"io"
	"os"
9 10

	"github.com/ethereum-optimism/optimism/op-service/ioutil"
protolambda's avatar
protolambda committed
11 12 13
)

func loadJSON[X any](inputPath string) (*X, error) {
14 15 16
	if inputPath == "" {
		return nil, errors.New("no path specified")
	}
17
	var f io.ReadCloser
18
	f, err := ioutil.OpenDecompressed(inputPath)
protolambda's avatar
protolambda committed
19 20 21 22 23 24 25 26 27 28 29
	if err != nil {
		return nil, fmt.Errorf("failed to open file %q: %w", inputPath, err)
	}
	defer f.Close()
	var state X
	if err := json.NewDecoder(f).Decode(&state); err != nil {
		return nil, fmt.Errorf("failed to decode file %q: %w", inputPath, err)
	}
	return &state, nil
}

30 31 32 33
func writeJSON[X any](outputPath string, value X) error {
	if outputPath == "" {
		return nil
	}
protolambda's avatar
protolambda committed
34
	var out io.Writer
35 36
	finish := func() error { return nil }
	if outputPath != "-" {
37
		f, err := ioutil.NewAtomicWriterCompressed(outputPath, 0755)
protolambda's avatar
protolambda committed
38 39 40
		if err != nil {
			return fmt.Errorf("failed to open output file: %w", err)
		}
41
		// Ensure we close the stream even if failures occur.
protolambda's avatar
protolambda committed
42 43
		defer f.Close()
		out = f
44 45 46
		// Closing the file causes it to be renamed to the final destination
		// so make sure we handle any errors it returns
		finish = f.Close
protolambda's avatar
protolambda committed
47
	} else {
48
		out = os.Stdout
protolambda's avatar
protolambda committed
49 50 51 52 53 54 55 56 57
	}
	enc := json.NewEncoder(out)
	if err := enc.Encode(value); err != nil {
		return fmt.Errorf("failed to encode to JSON: %w", err)
	}
	_, err := out.Write([]byte{'\n'})
	if err != nil {
		return fmt.Errorf("failed to append new-line: %w", err)
	}
58 59 60
	if err := finish(); err != nil {
		return fmt.Errorf("failed to finish write: %w", err)
	}
protolambda's avatar
protolambda committed
61 62
	return nil
}