Home

cfg @281b64352ff6a2bcca6ce2c5e4b3adc8d08d32d3 - refs - log -
-
https://git.jolheiser.com/cfg.git
Convert between various configuration formats
cfg / cmd / cfg / main.go
- raw -
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 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
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
package main

import (
	"flag"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"strings"

	"go.jolheiser.com/cfg"
)

func maine() error {
	var unmarshal func([]byte, any) error
	var marshal func(any) ([]byte, error)

	fs := flag.NewFlagSet("cfg", flag.ExitOnError)
	fromFunc := func(s string) error {
		e, err := cfg.ParseEncoding(s)
		if err != nil {
			return err
		}
		unmarshal = e.Unmarshal
		return nil
	}
	fs.Func("from", "The format to convert from [json(c), jsonnet, yaml, toml, nix, dhall, kdl]", fromFunc)
	fs.Func("f", "--from", fromFunc)
	toFunc := func(s string) error {
		e, err := cfg.ParseEncoding(s)
		if err != nil {
			return err
		}
		marshal = e.Marshal
		return nil
	}
	fs.Func("to", "The format to convert to [json, yaml, toml, nix, kdl]", toFunc)
	fs.Func("t", "--to", toFunc)
	if err := fs.Parse(os.Args[1:]); err != nil {
		return err
	}

	cleanArg := func(arg string) string {
		return strings.TrimPrefix(filepath.Ext(arg), ".")
	}

	in := os.Stdin
	if fs.NArg() > 0 {
		fi, err := os.Open(fs.Arg(0))
		if err != nil {
			return err
		}
		defer fi.Close()
		in = fi

		if unmarshal == nil {
			if err := fromFunc(cleanArg(fs.Arg(0))); err != nil {
				return err
			}
		}

	} else if unmarshal == nil {
		unmarshal = cfg.JSON.Unmarshal
	}

	out := os.Stdout
	if fs.NArg() > 1 {
		fi, err := os.Create(fs.Arg(1))
		if err != nil {
			return err
		}
		defer fi.Close()
		out = fi

		if marshal == nil {
			if err := toFunc(cleanArg(fs.Arg(1))); err != nil {
				return err
			}
		}
	} else if marshal == nil {
		marshal = cfg.JSON.Marshal
	}

	var data any

	inData, err := io.ReadAll(in)
	if err != nil {
		return err
	}

	if err := unmarshal(inData, &data); err != nil {
		return err
	}

	outData, err := marshal(data)
	if err != nil {
		return err
	}

	if _, err := out.Write(outData); err != nil {
		return err
	}

	return nil
}

func main() {
	if err := maine(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}