json.go 1.13 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 9 10 11
	"fmt"
	"io"
	"os"
)

func loadJSON[X any](inputPath string) (*X, error) {
12 13 14
	if inputPath == "" {
		return nil, errors.New("no path specified")
	}
protolambda's avatar
protolambda committed
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
	f, err := os.OpenFile(inputPath, os.O_RDONLY, 0)
	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
}

func writeJSON[X any](outputPath string, value X, outIfEmpty bool) error {
	var out io.Writer
	if outputPath != "" {
		f, err := os.OpenFile(outputPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0755)
		if err != nil {
			return fmt.Errorf("failed to open output file: %w", err)
		}
		defer f.Close()
		out = f
	} else if outIfEmpty {
		out = os.Stdout
	} else {
		return nil
	}
	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)
	}
	return nil
}